repo_name
string
path
string
copies
string
size
string
content
string
license
string
AMohseni76/Prime_Kernel
drivers/staging/rtl8192u/ieee80211/ieee80211_crypt_tkip.c
7883
20452
/* * Host AP crypt: host-based TKIP encryption implementation for Host AP driver * * Copyright (c) 2003-2004, Jouni Malinen <jkmaline@cc.hut.fi> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. See README and COPYING for * more details. */ //#include <linux/config.h> #include <linux/module.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/random.h> #include <linux/skbuff.h> #include <linux/netdevice.h> #include <linux/if_ether.h> #include <linux/if_arp.h> #include <asm/string.h> #include "ieee80211.h" #include <linux/crypto.h> #include <linux/scatterlist.h> #include <linux/crc32.h> MODULE_AUTHOR("Jouni Malinen"); MODULE_DESCRIPTION("Host AP crypt: TKIP"); MODULE_LICENSE("GPL"); struct ieee80211_tkip_data { #define TKIP_KEY_LEN 32 u8 key[TKIP_KEY_LEN]; int key_set; u32 tx_iv32; u16 tx_iv16; u16 tx_ttak[5]; int tx_phase1_done; u32 rx_iv32; u16 rx_iv16; u16 rx_ttak[5]; int rx_phase1_done; u32 rx_iv32_new; u16 rx_iv16_new; u32 dot11RSNAStatsTKIPReplays; u32 dot11RSNAStatsTKIPICVErrors; u32 dot11RSNAStatsTKIPLocalMICFailures; int key_idx; struct crypto_blkcipher *rx_tfm_arc4; struct crypto_hash *rx_tfm_michael; struct crypto_blkcipher *tx_tfm_arc4; struct crypto_hash *tx_tfm_michael; /* scratch buffers for virt_to_page() (crypto API) */ u8 rx_hdr[16], tx_hdr[16]; }; static void * ieee80211_tkip_init(int key_idx) { struct ieee80211_tkip_data *priv; priv = kzalloc(sizeof(*priv), GFP_ATOMIC); if (priv == NULL) goto fail; priv->key_idx = key_idx; priv->tx_tfm_arc4 = crypto_alloc_blkcipher("ecb(arc4)", 0, CRYPTO_ALG_ASYNC); if (IS_ERR(priv->tx_tfm_arc4)) { printk(KERN_DEBUG "ieee80211_crypt_tkip: could not allocate " "crypto API arc4\n"); priv->tx_tfm_arc4 = NULL; goto fail; } priv->tx_tfm_michael = crypto_alloc_hash("michael_mic", 0, CRYPTO_ALG_ASYNC); if (IS_ERR(priv->tx_tfm_michael)) { printk(KERN_DEBUG "ieee80211_crypt_tkip: could not allocate " "crypto API michael_mic\n"); priv->tx_tfm_michael = NULL; goto fail; } priv->rx_tfm_arc4 = crypto_alloc_blkcipher("ecb(arc4)", 0, CRYPTO_ALG_ASYNC); if (IS_ERR(priv->rx_tfm_arc4)) { printk(KERN_DEBUG "ieee80211_crypt_tkip: could not allocate " "crypto API arc4\n"); priv->rx_tfm_arc4 = NULL; goto fail; } priv->rx_tfm_michael = crypto_alloc_hash("michael_mic", 0, CRYPTO_ALG_ASYNC); if (IS_ERR(priv->rx_tfm_michael)) { printk(KERN_DEBUG "ieee80211_crypt_tkip: could not allocate " "crypto API michael_mic\n"); priv->rx_tfm_michael = NULL; goto fail; } return priv; fail: if (priv) { if (priv->tx_tfm_michael) crypto_free_hash(priv->tx_tfm_michael); if (priv->tx_tfm_arc4) crypto_free_blkcipher(priv->tx_tfm_arc4); if (priv->rx_tfm_michael) crypto_free_hash(priv->rx_tfm_michael); if (priv->rx_tfm_arc4) crypto_free_blkcipher(priv->rx_tfm_arc4); kfree(priv); } return NULL; } static void ieee80211_tkip_deinit(void *priv) { struct ieee80211_tkip_data *_priv = priv; if (_priv) { if (_priv->tx_tfm_michael) crypto_free_hash(_priv->tx_tfm_michael); if (_priv->tx_tfm_arc4) crypto_free_blkcipher(_priv->tx_tfm_arc4); if (_priv->rx_tfm_michael) crypto_free_hash(_priv->rx_tfm_michael); if (_priv->rx_tfm_arc4) crypto_free_blkcipher(_priv->rx_tfm_arc4); } kfree(priv); } static inline u16 RotR1(u16 val) { return (val >> 1) | (val << 15); } static inline u8 Lo8(u16 val) { return val & 0xff; } static inline u8 Hi8(u16 val) { return val >> 8; } static inline u16 Lo16(u32 val) { return val & 0xffff; } static inline u16 Hi16(u32 val) { return val >> 16; } static inline u16 Mk16(u8 hi, u8 lo) { return lo | (((u16) hi) << 8); } static inline u16 Mk16_le(u16 *v) { return le16_to_cpu(*v); } static const u16 Sbox[256] = { 0xC6A5, 0xF884, 0xEE99, 0xF68D, 0xFF0D, 0xD6BD, 0xDEB1, 0x9154, 0x6050, 0x0203, 0xCEA9, 0x567D, 0xE719, 0xB562, 0x4DE6, 0xEC9A, 0x8F45, 0x1F9D, 0x8940, 0xFA87, 0xEF15, 0xB2EB, 0x8EC9, 0xFB0B, 0x41EC, 0xB367, 0x5FFD, 0x45EA, 0x23BF, 0x53F7, 0xE496, 0x9B5B, 0x75C2, 0xE11C, 0x3DAE, 0x4C6A, 0x6C5A, 0x7E41, 0xF502, 0x834F, 0x685C, 0x51F4, 0xD134, 0xF908, 0xE293, 0xAB73, 0x6253, 0x2A3F, 0x080C, 0x9552, 0x4665, 0x9D5E, 0x3028, 0x37A1, 0x0A0F, 0x2FB5, 0x0E09, 0x2436, 0x1B9B, 0xDF3D, 0xCD26, 0x4E69, 0x7FCD, 0xEA9F, 0x121B, 0x1D9E, 0x5874, 0x342E, 0x362D, 0xDCB2, 0xB4EE, 0x5BFB, 0xA4F6, 0x764D, 0xB761, 0x7DCE, 0x527B, 0xDD3E, 0x5E71, 0x1397, 0xA6F5, 0xB968, 0x0000, 0xC12C, 0x4060, 0xE31F, 0x79C8, 0xB6ED, 0xD4BE, 0x8D46, 0x67D9, 0x724B, 0x94DE, 0x98D4, 0xB0E8, 0x854A, 0xBB6B, 0xC52A, 0x4FE5, 0xED16, 0x86C5, 0x9AD7, 0x6655, 0x1194, 0x8ACF, 0xE910, 0x0406, 0xFE81, 0xA0F0, 0x7844, 0x25BA, 0x4BE3, 0xA2F3, 0x5DFE, 0x80C0, 0x058A, 0x3FAD, 0x21BC, 0x7048, 0xF104, 0x63DF, 0x77C1, 0xAF75, 0x4263, 0x2030, 0xE51A, 0xFD0E, 0xBF6D, 0x814C, 0x1814, 0x2635, 0xC32F, 0xBEE1, 0x35A2, 0x88CC, 0x2E39, 0x9357, 0x55F2, 0xFC82, 0x7A47, 0xC8AC, 0xBAE7, 0x322B, 0xE695, 0xC0A0, 0x1998, 0x9ED1, 0xA37F, 0x4466, 0x547E, 0x3BAB, 0x0B83, 0x8CCA, 0xC729, 0x6BD3, 0x283C, 0xA779, 0xBCE2, 0x161D, 0xAD76, 0xDB3B, 0x6456, 0x744E, 0x141E, 0x92DB, 0x0C0A, 0x486C, 0xB8E4, 0x9F5D, 0xBD6E, 0x43EF, 0xC4A6, 0x39A8, 0x31A4, 0xD337, 0xF28B, 0xD532, 0x8B43, 0x6E59, 0xDAB7, 0x018C, 0xB164, 0x9CD2, 0x49E0, 0xD8B4, 0xACFA, 0xF307, 0xCF25, 0xCAAF, 0xF48E, 0x47E9, 0x1018, 0x6FD5, 0xF088, 0x4A6F, 0x5C72, 0x3824, 0x57F1, 0x73C7, 0x9751, 0xCB23, 0xA17C, 0xE89C, 0x3E21, 0x96DD, 0x61DC, 0x0D86, 0x0F85, 0xE090, 0x7C42, 0x71C4, 0xCCAA, 0x90D8, 0x0605, 0xF701, 0x1C12, 0xC2A3, 0x6A5F, 0xAEF9, 0x69D0, 0x1791, 0x9958, 0x3A27, 0x27B9, 0xD938, 0xEB13, 0x2BB3, 0x2233, 0xD2BB, 0xA970, 0x0789, 0x33A7, 0x2DB6, 0x3C22, 0x1592, 0xC920, 0x8749, 0xAAFF, 0x5078, 0xA57A, 0x038F, 0x59F8, 0x0980, 0x1A17, 0x65DA, 0xD731, 0x84C6, 0xD0B8, 0x82C3, 0x29B0, 0x5A77, 0x1E11, 0x7BCB, 0xA8FC, 0x6DD6, 0x2C3A, }; static inline u16 _S_(u16 v) { u16 t = Sbox[Hi8(v)]; return Sbox[Lo8(v)] ^ ((t << 8) | (t >> 8)); } #define PHASE1_LOOP_COUNT 8 static void tkip_mixing_phase1(u16 *TTAK, const u8 *TK, const u8 *TA, u32 IV32) { int i, j; /* Initialize the 80-bit TTAK from TSC (IV32) and TA[0..5] */ TTAK[0] = Lo16(IV32); TTAK[1] = Hi16(IV32); TTAK[2] = Mk16(TA[1], TA[0]); TTAK[3] = Mk16(TA[3], TA[2]); TTAK[4] = Mk16(TA[5], TA[4]); for (i = 0; i < PHASE1_LOOP_COUNT; i++) { j = 2 * (i & 1); TTAK[0] += _S_(TTAK[4] ^ Mk16(TK[1 + j], TK[0 + j])); TTAK[1] += _S_(TTAK[0] ^ Mk16(TK[5 + j], TK[4 + j])); TTAK[2] += _S_(TTAK[1] ^ Mk16(TK[9 + j], TK[8 + j])); TTAK[3] += _S_(TTAK[2] ^ Mk16(TK[13 + j], TK[12 + j])); TTAK[4] += _S_(TTAK[3] ^ Mk16(TK[1 + j], TK[0 + j])) + i; } } static void tkip_mixing_phase2(u8 *WEPSeed, const u8 *TK, const u16 *TTAK, u16 IV16) { /* Make temporary area overlap WEP seed so that the final copy can be * avoided on little endian hosts. */ u16 *PPK = (u16 *) &WEPSeed[4]; /* Step 1 - make copy of TTAK and bring in TSC */ PPK[0] = TTAK[0]; PPK[1] = TTAK[1]; PPK[2] = TTAK[2]; PPK[3] = TTAK[3]; PPK[4] = TTAK[4]; PPK[5] = TTAK[4] + IV16; /* Step 2 - 96-bit bijective mixing using S-box */ PPK[0] += _S_(PPK[5] ^ Mk16_le((u16 *) &TK[0])); PPK[1] += _S_(PPK[0] ^ Mk16_le((u16 *) &TK[2])); PPK[2] += _S_(PPK[1] ^ Mk16_le((u16 *) &TK[4])); PPK[3] += _S_(PPK[2] ^ Mk16_le((u16 *) &TK[6])); PPK[4] += _S_(PPK[3] ^ Mk16_le((u16 *) &TK[8])); PPK[5] += _S_(PPK[4] ^ Mk16_le((u16 *) &TK[10])); PPK[0] += RotR1(PPK[5] ^ Mk16_le((u16 *) &TK[12])); PPK[1] += RotR1(PPK[0] ^ Mk16_le((u16 *) &TK[14])); PPK[2] += RotR1(PPK[1]); PPK[3] += RotR1(PPK[2]); PPK[4] += RotR1(PPK[3]); PPK[5] += RotR1(PPK[4]); /* Step 3 - bring in last of TK bits, assign 24-bit WEP IV value * WEPSeed[0..2] is transmitted as WEP IV */ WEPSeed[0] = Hi8(IV16); WEPSeed[1] = (Hi8(IV16) | 0x20) & 0x7F; WEPSeed[2] = Lo8(IV16); WEPSeed[3] = Lo8((PPK[5] ^ Mk16_le((u16 *) &TK[0])) >> 1); #ifdef __BIG_ENDIAN { int i; for (i = 0; i < 6; i++) PPK[i] = (PPK[i] << 8) | (PPK[i] >> 8); } #endif } static int ieee80211_tkip_encrypt(struct sk_buff *skb, int hdr_len, void *priv) { struct ieee80211_tkip_data *tkey = priv; int len; u8 *pos; struct ieee80211_hdr_4addr *hdr; cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE); struct blkcipher_desc desc = {.tfm = tkey->tx_tfm_arc4}; int ret = 0; u8 rc4key[16], *icv; u32 crc; struct scatterlist sg; if (skb_headroom(skb) < 8 || skb_tailroom(skb) < 4 || skb->len < hdr_len) return -1; hdr = (struct ieee80211_hdr_4addr *) skb->data; if (!tcb_desc->bHwSec) { if (!tkey->tx_phase1_done) { tkip_mixing_phase1(tkey->tx_ttak, tkey->key, hdr->addr2, tkey->tx_iv32); tkey->tx_phase1_done = 1; } tkip_mixing_phase2(rc4key, tkey->key, tkey->tx_ttak, tkey->tx_iv16); } else tkey->tx_phase1_done = 1; len = skb->len - hdr_len; pos = skb_push(skb, 8); memmove(pos, pos + 8, hdr_len); pos += hdr_len; if (tcb_desc->bHwSec) { *pos++ = Hi8(tkey->tx_iv16); *pos++ = (Hi8(tkey->tx_iv16) | 0x20) & 0x7F; *pos++ = Lo8(tkey->tx_iv16); } else { *pos++ = rc4key[0]; *pos++ = rc4key[1]; *pos++ = rc4key[2]; } *pos++ = (tkey->key_idx << 6) | (1 << 5) /* Ext IV included */; *pos++ = tkey->tx_iv32 & 0xff; *pos++ = (tkey->tx_iv32 >> 8) & 0xff; *pos++ = (tkey->tx_iv32 >> 16) & 0xff; *pos++ = (tkey->tx_iv32 >> 24) & 0xff; if (!tcb_desc->bHwSec) { icv = skb_put(skb, 4); crc = ~crc32_le(~0, pos, len); icv[0] = crc; icv[1] = crc >> 8; icv[2] = crc >> 16; icv[3] = crc >> 24; crypto_blkcipher_setkey(tkey->tx_tfm_arc4, rc4key, 16); sg_init_one(&sg, pos, len+4); ret= crypto_blkcipher_encrypt(&desc, &sg, &sg, len + 4); } tkey->tx_iv16++; if (tkey->tx_iv16 == 0) { tkey->tx_phase1_done = 0; tkey->tx_iv32++; } if (!tcb_desc->bHwSec) return ret; else return 0; } static int ieee80211_tkip_decrypt(struct sk_buff *skb, int hdr_len, void *priv) { struct ieee80211_tkip_data *tkey = priv; u8 keyidx, *pos; u32 iv32; u16 iv16; struct ieee80211_hdr_4addr *hdr; cb_desc *tcb_desc = (cb_desc *)(skb->cb + MAX_DEV_ADDR_SIZE); struct blkcipher_desc desc = {.tfm = tkey->rx_tfm_arc4}; u8 rc4key[16]; u8 icv[4]; u32 crc; struct scatterlist sg; int plen; if (skb->len < hdr_len + 8 + 4) return -1; hdr = (struct ieee80211_hdr_4addr *) skb->data; pos = skb->data + hdr_len; keyidx = pos[3]; if (!(keyidx & (1 << 5))) { if (net_ratelimit()) { printk(KERN_DEBUG "TKIP: received packet without ExtIV" " flag from %pM\n", hdr->addr2); } return -2; } keyidx >>= 6; if (tkey->key_idx != keyidx) { printk(KERN_DEBUG "TKIP: RX tkey->key_idx=%d frame " "keyidx=%d priv=%p\n", tkey->key_idx, keyidx, priv); return -6; } if (!tkey->key_set) { if (net_ratelimit()) { printk(KERN_DEBUG "TKIP: received packet from %pM" " with keyid=%d that does not have a configured" " key\n", hdr->addr2, keyidx); } return -3; } iv16 = (pos[0] << 8) | pos[2]; iv32 = pos[4] | (pos[5] << 8) | (pos[6] << 16) | (pos[7] << 24); pos += 8; if (!tcb_desc->bHwSec) { if (iv32 < tkey->rx_iv32 || (iv32 == tkey->rx_iv32 && iv16 <= tkey->rx_iv16)) { if (net_ratelimit()) { printk(KERN_DEBUG "TKIP: replay detected: STA=%pM" " previous TSC %08x%04x received TSC " "%08x%04x\n", hdr->addr2, tkey->rx_iv32, tkey->rx_iv16, iv32, iv16); } tkey->dot11RSNAStatsTKIPReplays++; return -4; } if (iv32 != tkey->rx_iv32 || !tkey->rx_phase1_done) { tkip_mixing_phase1(tkey->rx_ttak, tkey->key, hdr->addr2, iv32); tkey->rx_phase1_done = 1; } tkip_mixing_phase2(rc4key, tkey->key, tkey->rx_ttak, iv16); plen = skb->len - hdr_len - 12; crypto_blkcipher_setkey(tkey->rx_tfm_arc4, rc4key, 16); sg_init_one(&sg, pos, plen+4); if (crypto_blkcipher_decrypt(&desc, &sg, &sg, plen + 4)) { if (net_ratelimit()) { printk(KERN_DEBUG ": TKIP: failed to decrypt " "received packet from %pM\n", hdr->addr2); } return -7; } crc = ~crc32_le(~0, pos, plen); icv[0] = crc; icv[1] = crc >> 8; icv[2] = crc >> 16; icv[3] = crc >> 24; if (memcmp(icv, pos + plen, 4) != 0) { if (iv32 != tkey->rx_iv32) { /* Previously cached Phase1 result was already lost, so * it needs to be recalculated for the next packet. */ tkey->rx_phase1_done = 0; } if (net_ratelimit()) { printk(KERN_DEBUG "TKIP: ICV error detected: STA=" "%pM\n", hdr->addr2); } tkey->dot11RSNAStatsTKIPICVErrors++; return -5; } } /* Update real counters only after Michael MIC verification has * completed */ tkey->rx_iv32_new = iv32; tkey->rx_iv16_new = iv16; /* Remove IV and ICV */ memmove(skb->data + 8, skb->data, hdr_len); skb_pull(skb, 8); skb_trim(skb, skb->len - 4); return keyidx; } static int michael_mic(struct crypto_hash *tfm_michael, u8 * key, u8 * hdr, u8 * data, size_t data_len, u8 * mic) { struct hash_desc desc; struct scatterlist sg[2]; if (tfm_michael == NULL) { printk(KERN_WARNING "michael_mic: tfm_michael == NULL\n"); return -1; } sg_init_table(sg, 2); sg_set_buf(&sg[0], hdr, 16); sg_set_buf(&sg[1], data, data_len); if (crypto_hash_setkey(tfm_michael, key, 8)) return -1; desc.tfm = tfm_michael; desc.flags = 0; return crypto_hash_digest(&desc, sg, data_len + 16, mic); } static void michael_mic_hdr(struct sk_buff *skb, u8 *hdr) { struct ieee80211_hdr_4addr *hdr11; hdr11 = (struct ieee80211_hdr_4addr *) skb->data; switch (le16_to_cpu(hdr11->frame_ctl) & (IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS)) { case IEEE80211_FCTL_TODS: memcpy(hdr, hdr11->addr3, ETH_ALEN); /* DA */ memcpy(hdr + ETH_ALEN, hdr11->addr2, ETH_ALEN); /* SA */ break; case IEEE80211_FCTL_FROMDS: memcpy(hdr, hdr11->addr1, ETH_ALEN); /* DA */ memcpy(hdr + ETH_ALEN, hdr11->addr3, ETH_ALEN); /* SA */ break; case IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS: memcpy(hdr, hdr11->addr3, ETH_ALEN); /* DA */ memcpy(hdr + ETH_ALEN, hdr11->addr4, ETH_ALEN); /* SA */ break; case 0: memcpy(hdr, hdr11->addr1, ETH_ALEN); /* DA */ memcpy(hdr + ETH_ALEN, hdr11->addr2, ETH_ALEN); /* SA */ break; } hdr[12] = 0; /* priority */ hdr[13] = hdr[14] = hdr[15] = 0; /* reserved */ } static int ieee80211_michael_mic_add(struct sk_buff *skb, int hdr_len, void *priv) { struct ieee80211_tkip_data *tkey = priv; u8 *pos; struct ieee80211_hdr_4addr *hdr; hdr = (struct ieee80211_hdr_4addr *) skb->data; if (skb_tailroom(skb) < 8 || skb->len < hdr_len) { printk(KERN_DEBUG "Invalid packet for Michael MIC add " "(tailroom=%d hdr_len=%d skb->len=%d)\n", skb_tailroom(skb), hdr_len, skb->len); return -1; } michael_mic_hdr(skb, tkey->tx_hdr); // { david, 2006.9.1 // fix the wpa process with wmm enabled. if(IEEE80211_QOS_HAS_SEQ(le16_to_cpu(hdr->frame_ctl))) { tkey->tx_hdr[12] = *(skb->data + hdr_len - 2) & 0x07; } // } pos = skb_put(skb, 8); if (michael_mic(tkey->tx_tfm_michael, &tkey->key[16], tkey->tx_hdr, skb->data + hdr_len, skb->len - 8 - hdr_len, pos)) return -1; return 0; } static void ieee80211_michael_mic_failure(struct net_device *dev, struct ieee80211_hdr_4addr *hdr, int keyidx) { union iwreq_data wrqu; struct iw_michaelmicfailure ev; /* TODO: needed parameters: count, keyid, key type, TSC */ memset(&ev, 0, sizeof(ev)); ev.flags = keyidx & IW_MICFAILURE_KEY_ID; if (hdr->addr1[0] & 0x01) ev.flags |= IW_MICFAILURE_GROUP; else ev.flags |= IW_MICFAILURE_PAIRWISE; ev.src_addr.sa_family = ARPHRD_ETHER; memcpy(ev.src_addr.sa_data, hdr->addr2, ETH_ALEN); memset(&wrqu, 0, sizeof(wrqu)); wrqu.data.length = sizeof(ev); wireless_send_event(dev, IWEVMICHAELMICFAILURE, &wrqu, (char *) &ev); } static int ieee80211_michael_mic_verify(struct sk_buff *skb, int keyidx, int hdr_len, void *priv) { struct ieee80211_tkip_data *tkey = priv; u8 mic[8]; struct ieee80211_hdr_4addr *hdr; hdr = (struct ieee80211_hdr_4addr *) skb->data; if (!tkey->key_set) return -1; michael_mic_hdr(skb, tkey->rx_hdr); // { david, 2006.9.1 // fix the wpa process with wmm enabled. if(IEEE80211_QOS_HAS_SEQ(le16_to_cpu(hdr->frame_ctl))) { tkey->rx_hdr[12] = *(skb->data + hdr_len - 2) & 0x07; } // } if (michael_mic(tkey->rx_tfm_michael, &tkey->key[24], tkey->rx_hdr, skb->data + hdr_len, skb->len - 8 - hdr_len, mic)) return -1; if (memcmp(mic, skb->data + skb->len - 8, 8) != 0) { struct ieee80211_hdr_4addr *hdr; hdr = (struct ieee80211_hdr_4addr *) skb->data; printk(KERN_DEBUG "%s: Michael MIC verification failed for " "MSDU from %pM keyidx=%d\n", skb->dev ? skb->dev->name : "N/A", hdr->addr2, keyidx); if (skb->dev) ieee80211_michael_mic_failure(skb->dev, hdr, keyidx); tkey->dot11RSNAStatsTKIPLocalMICFailures++; return -1; } /* Update TSC counters for RX now that the packet verification has * completed. */ tkey->rx_iv32 = tkey->rx_iv32_new; tkey->rx_iv16 = tkey->rx_iv16_new; skb_trim(skb, skb->len - 8); return 0; } static int ieee80211_tkip_set_key(void *key, int len, u8 *seq, void *priv) { struct ieee80211_tkip_data *tkey = priv; int keyidx; struct crypto_hash *tfm = tkey->tx_tfm_michael; struct crypto_blkcipher *tfm2 = tkey->tx_tfm_arc4; struct crypto_hash *tfm3 = tkey->rx_tfm_michael; struct crypto_blkcipher *tfm4 = tkey->rx_tfm_arc4; keyidx = tkey->key_idx; memset(tkey, 0, sizeof(*tkey)); tkey->key_idx = keyidx; tkey->tx_tfm_michael = tfm; tkey->tx_tfm_arc4 = tfm2; tkey->rx_tfm_michael = tfm3; tkey->rx_tfm_arc4 = tfm4; if (len == TKIP_KEY_LEN) { memcpy(tkey->key, key, TKIP_KEY_LEN); tkey->key_set = 1; tkey->tx_iv16 = 1; /* TSC is initialized to 1 */ if (seq) { tkey->rx_iv32 = (seq[5] << 24) | (seq[4] << 16) | (seq[3] << 8) | seq[2]; tkey->rx_iv16 = (seq[1] << 8) | seq[0]; } } else if (len == 0) tkey->key_set = 0; else return -1; return 0; } static int ieee80211_tkip_get_key(void *key, int len, u8 *seq, void *priv) { struct ieee80211_tkip_data *tkey = priv; if (len < TKIP_KEY_LEN) return -1; if (!tkey->key_set) return 0; memcpy(key, tkey->key, TKIP_KEY_LEN); if (seq) { /* Return the sequence number of the last transmitted frame. */ u16 iv16 = tkey->tx_iv16; u32 iv32 = tkey->tx_iv32; if (iv16 == 0) iv32--; iv16--; seq[0] = tkey->tx_iv16; seq[1] = tkey->tx_iv16 >> 8; seq[2] = tkey->tx_iv32; seq[3] = tkey->tx_iv32 >> 8; seq[4] = tkey->tx_iv32 >> 16; seq[5] = tkey->tx_iv32 >> 24; } return TKIP_KEY_LEN; } static char * ieee80211_tkip_print_stats(char *p, void *priv) { struct ieee80211_tkip_data *tkip = priv; p += sprintf(p, "key[%d] alg=TKIP key_set=%d " "tx_pn=%02x%02x%02x%02x%02x%02x " "rx_pn=%02x%02x%02x%02x%02x%02x " "replays=%d icv_errors=%d local_mic_failures=%d\n", tkip->key_idx, tkip->key_set, (tkip->tx_iv32 >> 24) & 0xff, (tkip->tx_iv32 >> 16) & 0xff, (tkip->tx_iv32 >> 8) & 0xff, tkip->tx_iv32 & 0xff, (tkip->tx_iv16 >> 8) & 0xff, tkip->tx_iv16 & 0xff, (tkip->rx_iv32 >> 24) & 0xff, (tkip->rx_iv32 >> 16) & 0xff, (tkip->rx_iv32 >> 8) & 0xff, tkip->rx_iv32 & 0xff, (tkip->rx_iv16 >> 8) & 0xff, tkip->rx_iv16 & 0xff, tkip->dot11RSNAStatsTKIPReplays, tkip->dot11RSNAStatsTKIPICVErrors, tkip->dot11RSNAStatsTKIPLocalMICFailures); return p; } static struct ieee80211_crypto_ops ieee80211_crypt_tkip = { .name = "TKIP", .init = ieee80211_tkip_init, .deinit = ieee80211_tkip_deinit, .encrypt_mpdu = ieee80211_tkip_encrypt, .decrypt_mpdu = ieee80211_tkip_decrypt, .encrypt_msdu = ieee80211_michael_mic_add, .decrypt_msdu = ieee80211_michael_mic_verify, .set_key = ieee80211_tkip_set_key, .get_key = ieee80211_tkip_get_key, .print_stats = ieee80211_tkip_print_stats, .extra_prefix_len = 4 + 4, /* IV + ExtIV */ .extra_postfix_len = 8 + 4, /* MIC + ICV */ .owner = THIS_MODULE, }; int __init ieee80211_crypto_tkip_init(void) { return ieee80211_register_crypto_ops(&ieee80211_crypt_tkip); } void __exit ieee80211_crypto_tkip_exit(void) { ieee80211_unregister_crypto_ops(&ieee80211_crypt_tkip); } void ieee80211_tkip_null(void) { // printk("============>%s()\n", __FUNCTION__); return; }
gpl-2.0
MoKee/android_kernel_lge_omap4-common
sound/oss/uart401.c
9419
10693
/* * sound/oss/uart401.c * * MPU-401 UART driver (formerly uart401_midi.c) * * * Copyright (C) by Hannu Savolainen 1993-1997 * * OSS/Free for Linux is distributed under the GNU GENERAL PUBLIC LICENSE (GPL) * Version 2 (June 1991). See the "COPYING" file distributed with this software * for more info. * * Changes: * Alan Cox Reformatted, removed sound_mem usage, use normal Linux * interrupt allocation. Protect against bogus unload * Fixed to allow IRQ > 15 * Christoph Hellwig Adapted to module_init/module_exit * Arnaldo C. de Melo got rid of check_region * * Status: * Untested */ #include <linux/init.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/spinlock.h> #include "sound_config.h" #include "mpu401.h" typedef struct uart401_devc { int base; int irq; int *osp; void (*midi_input_intr) (int dev, unsigned char data); int opened, disabled; volatile unsigned char input_byte; int my_dev; int share_irq; spinlock_t lock; } uart401_devc; #define DATAPORT (devc->base) #define COMDPORT (devc->base+1) #define STATPORT (devc->base+1) static int uart401_status(uart401_devc * devc) { return inb(STATPORT); } #define input_avail(devc) (!(uart401_status(devc)&INPUT_AVAIL)) #define output_ready(devc) (!(uart401_status(devc)&OUTPUT_READY)) static void uart401_cmd(uart401_devc * devc, unsigned char cmd) { outb((cmd), COMDPORT); } static int uart401_read(uart401_devc * devc) { return inb(DATAPORT); } static void uart401_write(uart401_devc * devc, unsigned char byte) { outb((byte), DATAPORT); } #define OUTPUT_READY 0x40 #define INPUT_AVAIL 0x80 #define MPU_ACK 0xFE #define MPU_RESET 0xFF #define UART_MODE_ON 0x3F static int reset_uart401(uart401_devc * devc); static void enter_uart_mode(uart401_devc * devc); static void uart401_input_loop(uart401_devc * devc) { int work_limit=30000; while (input_avail(devc) && --work_limit) { unsigned char c = uart401_read(devc); if (c == MPU_ACK) devc->input_byte = c; else if (devc->opened & OPEN_READ && devc->midi_input_intr) devc->midi_input_intr(devc->my_dev, c); } if(work_limit==0) printk(KERN_WARNING "Too much work in interrupt on uart401 (0x%X). UART jabbering ??\n", devc->base); } irqreturn_t uart401intr(int irq, void *dev_id) { uart401_devc *devc = dev_id; if (devc == NULL) { printk(KERN_ERR "uart401: bad devc\n"); return IRQ_NONE; } if (input_avail(devc)) uart401_input_loop(devc); return IRQ_HANDLED; } static int uart401_open(int dev, int mode, void (*input) (int dev, unsigned char data), void (*output) (int dev) ) { uart401_devc *devc = (uart401_devc *) midi_devs[dev]->devc; if (devc->opened) return -EBUSY; /* Flush the UART */ while (input_avail(devc)) uart401_read(devc); devc->midi_input_intr = input; devc->opened = mode; enter_uart_mode(devc); devc->disabled = 0; return 0; } static void uart401_close(int dev) { uart401_devc *devc = (uart401_devc *) midi_devs[dev]->devc; reset_uart401(devc); devc->opened = 0; } static int uart401_out(int dev, unsigned char midi_byte) { int timeout; unsigned long flags; uart401_devc *devc = (uart401_devc *) midi_devs[dev]->devc; if (devc->disabled) return 1; /* * Test for input since pending input seems to block the output. */ spin_lock_irqsave(&devc->lock,flags); if (input_avail(devc)) uart401_input_loop(devc); spin_unlock_irqrestore(&devc->lock,flags); /* * Sometimes it takes about 13000 loops before the output becomes ready * (After reset). Normally it takes just about 10 loops. */ for (timeout = 30000; timeout > 0 && !output_ready(devc); timeout--); if (!output_ready(devc)) { printk(KERN_WARNING "uart401: Timeout - Device not responding\n"); devc->disabled = 1; reset_uart401(devc); enter_uart_mode(devc); return 1; } uart401_write(devc, midi_byte); return 1; } static inline int uart401_start_read(int dev) { return 0; } static inline int uart401_end_read(int dev) { return 0; } static inline void uart401_kick(int dev) { } static inline int uart401_buffer_status(int dev) { return 0; } #define MIDI_SYNTH_NAME "MPU-401 UART" #define MIDI_SYNTH_CAPS SYNTH_CAP_INPUT #include "midi_synth.h" static const struct midi_operations uart401_operations = { .owner = THIS_MODULE, .info = {"MPU-401 (UART) MIDI", 0, 0, SNDCARD_MPU401}, .converter = &std_midi_synth, .in_info = {0}, .open = uart401_open, .close = uart401_close, .outputc = uart401_out, .start_read = uart401_start_read, .end_read = uart401_end_read, .kick = uart401_kick, .buffer_status = uart401_buffer_status, }; static void enter_uart_mode(uart401_devc * devc) { int ok, timeout; unsigned long flags; spin_lock_irqsave(&devc->lock,flags); for (timeout = 30000; timeout > 0 && !output_ready(devc); timeout--); devc->input_byte = 0; uart401_cmd(devc, UART_MODE_ON); ok = 0; for (timeout = 50000; timeout > 0 && !ok; timeout--) if (devc->input_byte == MPU_ACK) ok = 1; else if (input_avail(devc)) if (uart401_read(devc) == MPU_ACK) ok = 1; spin_unlock_irqrestore(&devc->lock,flags); } static int reset_uart401(uart401_devc * devc) { int ok, timeout, n; /* * Send the RESET command. Try again if no success at the first time. */ ok = 0; for (n = 0; n < 2 && !ok; n++) { for (timeout = 30000; timeout > 0 && !output_ready(devc); timeout--); devc->input_byte = 0; uart401_cmd(devc, MPU_RESET); /* * Wait at least 25 msec. This method is not accurate so let's make the * loop bit longer. Cannot sleep since this is called during boot. */ for (timeout = 50000; timeout > 0 && !ok; timeout--) { if (devc->input_byte == MPU_ACK) /* Interrupt */ ok = 1; else if (input_avail(devc)) { if (uart401_read(devc) == MPU_ACK) ok = 1; } } } if (ok) { DEB(printk("Reset UART401 OK\n")); } else DDB(printk("Reset UART401 failed - No hardware detected.\n")); if (ok) uart401_input_loop(devc); /* * Flush input before enabling interrupts */ return ok; } int probe_uart401(struct address_info *hw_config, struct module *owner) { uart401_devc *devc; char *name = "MPU-401 (UART) MIDI"; int ok = 0; unsigned long flags; DDB(printk("Entered probe_uart401()\n")); /* Default to "not found" */ hw_config->slots[4] = -1; if (!request_region(hw_config->io_base, 4, "MPU-401 UART")) { printk(KERN_INFO "uart401: could not request_region(%d, 4)\n", hw_config->io_base); return 0; } devc = kmalloc(sizeof(uart401_devc), GFP_KERNEL); if (!devc) { printk(KERN_WARNING "uart401: Can't allocate memory\n"); goto cleanup_region; } devc->base = hw_config->io_base; devc->irq = hw_config->irq; devc->osp = hw_config->osp; devc->midi_input_intr = NULL; devc->opened = 0; devc->input_byte = 0; devc->my_dev = 0; devc->share_irq = 0; spin_lock_init(&devc->lock); spin_lock_irqsave(&devc->lock,flags); ok = reset_uart401(devc); spin_unlock_irqrestore(&devc->lock,flags); if (!ok) goto cleanup_devc; if (hw_config->name) name = hw_config->name; if (devc->irq < 0) { devc->share_irq = 1; devc->irq *= -1; } else devc->share_irq = 0; if (!devc->share_irq) if (request_irq(devc->irq, uart401intr, 0, "MPU-401 UART", devc) < 0) { printk(KERN_WARNING "uart401: Failed to allocate IRQ%d\n", devc->irq); devc->share_irq = 1; } devc->my_dev = sound_alloc_mididev(); enter_uart_mode(devc); if (devc->my_dev == -1) { printk(KERN_INFO "uart401: Too many midi devices detected\n"); goto cleanup_irq; } conf_printf(name, hw_config); midi_devs[devc->my_dev] = kmalloc(sizeof(struct midi_operations), GFP_KERNEL); if (!midi_devs[devc->my_dev]) { printk(KERN_ERR "uart401: Failed to allocate memory\n"); goto cleanup_unload_mididev; } memcpy(midi_devs[devc->my_dev], &uart401_operations, sizeof(struct midi_operations)); if (owner) midi_devs[devc->my_dev]->owner = owner; midi_devs[devc->my_dev]->devc = devc; midi_devs[devc->my_dev]->converter = kmalloc(sizeof(struct synth_operations), GFP_KERNEL); if (!midi_devs[devc->my_dev]->converter) { printk(KERN_WARNING "uart401: Failed to allocate memory\n"); goto cleanup_midi_devs; } memcpy(midi_devs[devc->my_dev]->converter, &std_midi_synth, sizeof(struct synth_operations)); strcpy(midi_devs[devc->my_dev]->info.name, name); midi_devs[devc->my_dev]->converter->id = "UART401"; midi_devs[devc->my_dev]->converter->midi_dev = devc->my_dev; if (owner) midi_devs[devc->my_dev]->converter->owner = owner; hw_config->slots[4] = devc->my_dev; sequencer_init(); devc->opened = 0; return 1; cleanup_midi_devs: kfree(midi_devs[devc->my_dev]); cleanup_unload_mididev: sound_unload_mididev(devc->my_dev); cleanup_irq: if (!devc->share_irq) free_irq(devc->irq, devc); cleanup_devc: kfree(devc); cleanup_region: release_region(hw_config->io_base, 4); return 0; } void unload_uart401(struct address_info *hw_config) { uart401_devc *devc; int n=hw_config->slots[4]; /* Not set up */ if(n==-1 || midi_devs[n]==NULL) return; /* Not allocated (erm ??) */ devc = midi_devs[hw_config->slots[4]]->devc; if (devc == NULL) return; reset_uart401(devc); release_region(hw_config->io_base, 4); if (!devc->share_irq) free_irq(devc->irq, devc); if (devc) { kfree(midi_devs[devc->my_dev]->converter); kfree(midi_devs[devc->my_dev]); kfree(devc); devc = NULL; } /* This kills midi_devs[x] */ sound_unload_mididev(hw_config->slots[4]); } EXPORT_SYMBOL(probe_uart401); EXPORT_SYMBOL(unload_uart401); EXPORT_SYMBOL(uart401intr); static struct address_info cfg_mpu; static int io = -1; static int irq = -1; module_param(io, int, 0444); module_param(irq, int, 0444); static int __init init_uart401(void) { cfg_mpu.irq = irq; cfg_mpu.io_base = io; /* Can be loaded either for module use or to provide functions to others */ if (cfg_mpu.io_base != -1 && cfg_mpu.irq != -1) { printk(KERN_INFO "MPU-401 UART driver Copyright (C) Hannu Savolainen 1993-1997"); if (!probe_uart401(&cfg_mpu, THIS_MODULE)) return -ENODEV; } return 0; } static void __exit cleanup_uart401(void) { if (cfg_mpu.io_base != -1 && cfg_mpu.irq != -1) unload_uart401(&cfg_mpu); } module_init(init_uart401); module_exit(cleanup_uart401); #ifndef MODULE static int __init setup_uart401(char *str) { /* io, irq */ int ints[3]; str = get_options(str, ARRAY_SIZE(ints), ints); io = ints[1]; irq = ints[2]; return 1; } __setup("uart401=", setup_uart401); #endif MODULE_LICENSE("GPL");
gpl-2.0
shouhu1993/NX511J_kernel
drivers/isdn/hardware/avm/b1pcmcia.c
9675
5698
/* $Id: b1pcmcia.c,v 1.1.2.2 2004/01/16 21:09:27 keil Exp $ * * Module for AVM B1/M1/M2 PCMCIA-card. * * Copyright 1999 by Carsten Paeth <calle@calle.de> * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/skbuff.h> #include <linux/delay.h> #include <linux/mm.h> #include <linux/interrupt.h> #include <linux/ioport.h> #include <linux/init.h> #include <asm/io.h> #include <linux/capi.h> #include <linux/b1pcmcia.h> #include <linux/isdn/capicmd.h> #include <linux/isdn/capiutil.h> #include <linux/isdn/capilli.h> #include "avmcard.h" /* ------------------------------------------------------------- */ static char *revision = "$Revision: 1.1.2.2 $"; /* ------------------------------------------------------------- */ MODULE_DESCRIPTION("CAPI4Linux: Driver for AVM PCMCIA cards"); MODULE_AUTHOR("Carsten Paeth"); MODULE_LICENSE("GPL"); /* ------------------------------------------------------------- */ static void b1pcmcia_remove_ctr(struct capi_ctr *ctrl) { avmctrl_info *cinfo = (avmctrl_info *)(ctrl->driverdata); avmcard *card = cinfo->card; unsigned int port = card->port; b1_reset(port); b1_reset(port); detach_capi_ctr(ctrl); free_irq(card->irq, card); b1_free_card(card); } /* ------------------------------------------------------------- */ static LIST_HEAD(cards); static char *b1pcmcia_procinfo(struct capi_ctr *ctrl); static int b1pcmcia_add_card(unsigned int port, unsigned irq, enum avmcardtype cardtype) { avmctrl_info *cinfo; avmcard *card; char *cardname; int retval; card = b1_alloc_card(1); if (!card) { printk(KERN_WARNING "b1pcmcia: no memory.\n"); retval = -ENOMEM; goto err; } cinfo = card->ctrlinfo; switch (cardtype) { case avm_m1: sprintf(card->name, "m1-%x", port); break; case avm_m2: sprintf(card->name, "m2-%x", port); break; default: sprintf(card->name, "b1pcmcia-%x", port); break; } card->port = port; card->irq = irq; card->cardtype = cardtype; retval = request_irq(card->irq, b1_interrupt, IRQF_SHARED, card->name, card); if (retval) { printk(KERN_ERR "b1pcmcia: unable to get IRQ %d.\n", card->irq); retval = -EBUSY; goto err_free; } b1_reset(card->port); if ((retval = b1_detect(card->port, card->cardtype)) != 0) { printk(KERN_NOTICE "b1pcmcia: NO card at 0x%x (%d)\n", card->port, retval); retval = -ENODEV; goto err_free_irq; } b1_reset(card->port); b1_getrevision(card); cinfo->capi_ctrl.owner = THIS_MODULE; cinfo->capi_ctrl.driver_name = "b1pcmcia"; cinfo->capi_ctrl.driverdata = cinfo; cinfo->capi_ctrl.register_appl = b1_register_appl; cinfo->capi_ctrl.release_appl = b1_release_appl; cinfo->capi_ctrl.send_message = b1_send_message; cinfo->capi_ctrl.load_firmware = b1_load_firmware; cinfo->capi_ctrl.reset_ctr = b1_reset_ctr; cinfo->capi_ctrl.procinfo = b1pcmcia_procinfo; cinfo->capi_ctrl.proc_fops = &b1ctl_proc_fops; strcpy(cinfo->capi_ctrl.name, card->name); retval = attach_capi_ctr(&cinfo->capi_ctrl); if (retval) { printk(KERN_ERR "b1pcmcia: attach controller failed.\n"); goto err_free_irq; } switch (cardtype) { case avm_m1: cardname = "M1"; break; case avm_m2: cardname = "M2"; break; default: cardname = "B1 PCMCIA"; break; } printk(KERN_INFO "b1pcmcia: AVM %s at i/o %#x, irq %d, revision %d\n", cardname, card->port, card->irq, card->revision); list_add(&card->list, &cards); return cinfo->capi_ctrl.cnr; err_free_irq: free_irq(card->irq, card); err_free: b1_free_card(card); err: return retval; } /* ------------------------------------------------------------- */ static char *b1pcmcia_procinfo(struct capi_ctr *ctrl) { avmctrl_info *cinfo = (avmctrl_info *)(ctrl->driverdata); if (!cinfo) return ""; sprintf(cinfo->infobuf, "%s %s 0x%x %d r%d", cinfo->cardname[0] ? cinfo->cardname : "-", cinfo->version[VER_DRIVER] ? cinfo->version[VER_DRIVER] : "-", cinfo->card ? cinfo->card->port : 0x0, cinfo->card ? cinfo->card->irq : 0, cinfo->card ? cinfo->card->revision : 0 ); return cinfo->infobuf; } /* ------------------------------------------------------------- */ int b1pcmcia_addcard_b1(unsigned int port, unsigned irq) { return b1pcmcia_add_card(port, irq, avm_b1pcmcia); } int b1pcmcia_addcard_m1(unsigned int port, unsigned irq) { return b1pcmcia_add_card(port, irq, avm_m1); } int b1pcmcia_addcard_m2(unsigned int port, unsigned irq) { return b1pcmcia_add_card(port, irq, avm_m2); } int b1pcmcia_delcard(unsigned int port, unsigned irq) { struct list_head *l; avmcard *card; list_for_each(l, &cards) { card = list_entry(l, avmcard, list); if (card->port == port && card->irq == irq) { b1pcmcia_remove_ctr(&card->ctrlinfo[0].capi_ctrl); return 0; } } return -ESRCH; } EXPORT_SYMBOL(b1pcmcia_addcard_b1); EXPORT_SYMBOL(b1pcmcia_addcard_m1); EXPORT_SYMBOL(b1pcmcia_addcard_m2); EXPORT_SYMBOL(b1pcmcia_delcard); static struct capi_driver capi_driver_b1pcmcia = { .name = "b1pcmcia", .revision = "1.0", }; static int __init b1pcmcia_init(void) { char *p; char rev[32]; if ((p = strchr(revision, ':')) != NULL && p[1]) { strlcpy(rev, p + 2, 32); if ((p = strchr(rev, '$')) != NULL && p > rev) *(p - 1) = 0; } else strcpy(rev, "1.0"); strlcpy(capi_driver_b1pcmcia.revision, rev, 32); register_capi_driver(&capi_driver_b1pcmcia); printk(KERN_INFO "b1pci: revision %s\n", rev); return 0; } static void __exit b1pcmcia_exit(void) { unregister_capi_driver(&capi_driver_b1pcmcia); } module_init(b1pcmcia_init); module_exit(b1pcmcia_exit);
gpl-2.0
ardatdat/PureFroyo-Kernel
drivers/platform/x86/hp-wmi.c
716
15868
/* * HP WMI hotkeys * * Copyright (C) 2008 Red Hat <mjg@redhat.com> * * Portions based on wistron_btns.c: * Copyright (C) 2005 Miloslav Trmac <mitr@volny.cz> * Copyright (C) 2005 Bernhard Rosenkraenzer <bero@arklinux.org> * Copyright (C) 2005 Dmitry Torokhov <dtor@mail.ru> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/types.h> #include <linux/input.h> #include <acpi/acpi_drivers.h> #include <linux/platform_device.h> #include <linux/acpi.h> #include <linux/rfkill.h> #include <linux/string.h> MODULE_AUTHOR("Matthew Garrett <mjg59@srcf.ucam.org>"); MODULE_DESCRIPTION("HP laptop WMI hotkeys driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("wmi:95F24279-4D7B-4334-9387-ACCDC67EF61C"); MODULE_ALIAS("wmi:5FB7F034-2C63-45e9-BE91-3D44E2C707E4"); #define HPWMI_EVENT_GUID "95F24279-4D7B-4334-9387-ACCDC67EF61C" #define HPWMI_BIOS_GUID "5FB7F034-2C63-45e9-BE91-3D44E2C707E4" #define HPWMI_DISPLAY_QUERY 0x1 #define HPWMI_HDDTEMP_QUERY 0x2 #define HPWMI_ALS_QUERY 0x3 #define HPWMI_HARDWARE_QUERY 0x4 #define HPWMI_WIRELESS_QUERY 0x5 #define HPWMI_HOTKEY_QUERY 0xc enum hp_wmi_radio { HPWMI_WIFI = 0, HPWMI_BLUETOOTH = 1, HPWMI_WWAN = 2, }; enum hp_wmi_event_ids { HPWMI_DOCK_EVENT = 1, HPWMI_BEZEL_BUTTON = 4, HPWMI_WIRELESS = 5, }; static int __devinit hp_wmi_bios_setup(struct platform_device *device); static int __exit hp_wmi_bios_remove(struct platform_device *device); static int hp_wmi_resume_handler(struct device *device); struct bios_args { u32 signature; u32 command; u32 commandtype; u32 datasize; u32 data; }; struct bios_return { u32 sigpass; u32 return_code; u32 value; }; struct key_entry { char type; /* See KE_* below */ u16 code; u16 keycode; }; enum { KE_KEY, KE_END }; static struct key_entry hp_wmi_keymap[] = { {KE_KEY, 0x02, KEY_BRIGHTNESSUP}, {KE_KEY, 0x03, KEY_BRIGHTNESSDOWN}, {KE_KEY, 0x20e6, KEY_PROG1}, {KE_KEY, 0x2142, KEY_MEDIA}, {KE_KEY, 0x213b, KEY_INFO}, {KE_KEY, 0x2169, KEY_DIRECTION}, {KE_KEY, 0x231b, KEY_HELP}, {KE_END, 0} }; static struct input_dev *hp_wmi_input_dev; static struct platform_device *hp_wmi_platform_dev; static struct rfkill *wifi_rfkill; static struct rfkill *bluetooth_rfkill; static struct rfkill *wwan_rfkill; static const struct dev_pm_ops hp_wmi_pm_ops = { .resume = hp_wmi_resume_handler, .restore = hp_wmi_resume_handler, }; static struct platform_driver hp_wmi_driver = { .driver = { .name = "hp-wmi", .owner = THIS_MODULE, .pm = &hp_wmi_pm_ops, }, .probe = hp_wmi_bios_setup, .remove = hp_wmi_bios_remove, }; static int hp_wmi_perform_query(int query, int write, int value) { struct bios_return bios_return; acpi_status status; union acpi_object *obj; struct bios_args args = { .signature = 0x55434553, .command = write ? 0x2 : 0x1, .commandtype = query, .datasize = write ? 0x4 : 0, .data = value, }; struct acpi_buffer input = { sizeof(struct bios_args), &args }; struct acpi_buffer output = { ACPI_ALLOCATE_BUFFER, NULL }; status = wmi_evaluate_method(HPWMI_BIOS_GUID, 0, 0x3, &input, &output); obj = output.pointer; if (!obj) return -EINVAL; else if (obj->type != ACPI_TYPE_BUFFER) { kfree(obj); return -EINVAL; } bios_return = *((struct bios_return *)obj->buffer.pointer); kfree(obj); if (bios_return.return_code > 0) return bios_return.return_code * -1; else return bios_return.value; } static int hp_wmi_display_state(void) { return hp_wmi_perform_query(HPWMI_DISPLAY_QUERY, 0, 0); } static int hp_wmi_hddtemp_state(void) { return hp_wmi_perform_query(HPWMI_HDDTEMP_QUERY, 0, 0); } static int hp_wmi_als_state(void) { return hp_wmi_perform_query(HPWMI_ALS_QUERY, 0, 0); } static int hp_wmi_dock_state(void) { int ret = hp_wmi_perform_query(HPWMI_HARDWARE_QUERY, 0, 0); if (ret < 0) return ret; return ret & 0x1; } static int hp_wmi_tablet_state(void) { int ret = hp_wmi_perform_query(HPWMI_HARDWARE_QUERY, 0, 0); if (ret < 0) return ret; return (ret & 0x4) ? 1 : 0; } static int hp_wmi_set_block(void *data, bool blocked) { enum hp_wmi_radio r = (enum hp_wmi_radio) data; int query = BIT(r + 8) | ((!blocked) << r); return hp_wmi_perform_query(HPWMI_WIRELESS_QUERY, 1, query); } static const struct rfkill_ops hp_wmi_rfkill_ops = { .set_block = hp_wmi_set_block, }; static bool hp_wmi_get_sw_state(enum hp_wmi_radio r) { int wireless = hp_wmi_perform_query(HPWMI_WIRELESS_QUERY, 0, 0); int mask = 0x200 << (r * 8); if (wireless & mask) return false; else return true; } static bool hp_wmi_get_hw_state(enum hp_wmi_radio r) { int wireless = hp_wmi_perform_query(HPWMI_WIRELESS_QUERY, 0, 0); int mask = 0x800 << (r * 8); if (wireless & mask) return false; else return true; } static ssize_t show_display(struct device *dev, struct device_attribute *attr, char *buf) { int value = hp_wmi_display_state(); if (value < 0) return -EINVAL; return sprintf(buf, "%d\n", value); } static ssize_t show_hddtemp(struct device *dev, struct device_attribute *attr, char *buf) { int value = hp_wmi_hddtemp_state(); if (value < 0) return -EINVAL; return sprintf(buf, "%d\n", value); } static ssize_t show_als(struct device *dev, struct device_attribute *attr, char *buf) { int value = hp_wmi_als_state(); if (value < 0) return -EINVAL; return sprintf(buf, "%d\n", value); } static ssize_t show_dock(struct device *dev, struct device_attribute *attr, char *buf) { int value = hp_wmi_dock_state(); if (value < 0) return -EINVAL; return sprintf(buf, "%d\n", value); } static ssize_t show_tablet(struct device *dev, struct device_attribute *attr, char *buf) { int value = hp_wmi_tablet_state(); if (value < 0) return -EINVAL; return sprintf(buf, "%d\n", value); } static ssize_t set_als(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { u32 tmp = simple_strtoul(buf, NULL, 10); hp_wmi_perform_query(HPWMI_ALS_QUERY, 1, tmp); return count; } static DEVICE_ATTR(display, S_IRUGO, show_display, NULL); static DEVICE_ATTR(hddtemp, S_IRUGO, show_hddtemp, NULL); static DEVICE_ATTR(als, S_IRUGO | S_IWUSR, show_als, set_als); static DEVICE_ATTR(dock, S_IRUGO, show_dock, NULL); static DEVICE_ATTR(tablet, S_IRUGO, show_tablet, NULL); static struct key_entry *hp_wmi_get_entry_by_scancode(unsigned int code) { struct key_entry *key; for (key = hp_wmi_keymap; key->type != KE_END; key++) if (code == key->code) return key; return NULL; } static struct key_entry *hp_wmi_get_entry_by_keycode(unsigned int keycode) { struct key_entry *key; for (key = hp_wmi_keymap; key->type != KE_END; key++) if (key->type == KE_KEY && keycode == key->keycode) return key; return NULL; } static int hp_wmi_getkeycode(struct input_dev *dev, unsigned int scancode, unsigned int *keycode) { struct key_entry *key = hp_wmi_get_entry_by_scancode(scancode); if (key && key->type == KE_KEY) { *keycode = key->keycode; return 0; } return -EINVAL; } static int hp_wmi_setkeycode(struct input_dev *dev, unsigned int scancode, unsigned int keycode) { struct key_entry *key; unsigned int old_keycode; key = hp_wmi_get_entry_by_scancode(scancode); if (key && key->type == KE_KEY) { old_keycode = key->keycode; key->keycode = keycode; set_bit(keycode, dev->keybit); if (!hp_wmi_get_entry_by_keycode(old_keycode)) clear_bit(old_keycode, dev->keybit); return 0; } return -EINVAL; } static void hp_wmi_notify(u32 value, void *context) { struct acpi_buffer response = { ACPI_ALLOCATE_BUFFER, NULL }; static struct key_entry *key; union acpi_object *obj; int eventcode, key_code; acpi_status status; status = wmi_get_event_data(value, &response); if (status != AE_OK) { printk(KERN_INFO "hp-wmi: bad event status 0x%x\n", status); return; } obj = (union acpi_object *)response.pointer; if (!obj || obj->type != ACPI_TYPE_BUFFER || obj->buffer.length != 8) { printk(KERN_INFO "HP WMI: Unknown response received\n"); kfree(obj); return; } eventcode = *((u8 *) obj->buffer.pointer); kfree(obj); switch (eventcode) { case HPWMI_DOCK_EVENT: input_report_switch(hp_wmi_input_dev, SW_DOCK, hp_wmi_dock_state()); input_report_switch(hp_wmi_input_dev, SW_TABLET_MODE, hp_wmi_tablet_state()); input_sync(hp_wmi_input_dev); break; case HPWMI_BEZEL_BUTTON: key_code = hp_wmi_perform_query(HPWMI_HOTKEY_QUERY, 0, 0); key = hp_wmi_get_entry_by_scancode(key_code); if (key) { switch (key->type) { case KE_KEY: input_report_key(hp_wmi_input_dev, key->keycode, 1); input_sync(hp_wmi_input_dev); input_report_key(hp_wmi_input_dev, key->keycode, 0); input_sync(hp_wmi_input_dev); break; } } break; case HPWMI_WIRELESS: if (wifi_rfkill) rfkill_set_states(wifi_rfkill, hp_wmi_get_sw_state(HPWMI_WIFI), hp_wmi_get_hw_state(HPWMI_WIFI)); if (bluetooth_rfkill) rfkill_set_states(bluetooth_rfkill, hp_wmi_get_sw_state(HPWMI_BLUETOOTH), hp_wmi_get_hw_state(HPWMI_BLUETOOTH)); if (wwan_rfkill) rfkill_set_states(wwan_rfkill, hp_wmi_get_sw_state(HPWMI_WWAN), hp_wmi_get_hw_state(HPWMI_WWAN)); break; default: printk(KERN_INFO "HP WMI: Unknown key pressed - %x\n", eventcode); break; } } static int __init hp_wmi_input_setup(void) { struct key_entry *key; int err; hp_wmi_input_dev = input_allocate_device(); hp_wmi_input_dev->name = "HP WMI hotkeys"; hp_wmi_input_dev->phys = "wmi/input0"; hp_wmi_input_dev->id.bustype = BUS_HOST; hp_wmi_input_dev->getkeycode = hp_wmi_getkeycode; hp_wmi_input_dev->setkeycode = hp_wmi_setkeycode; for (key = hp_wmi_keymap; key->type != KE_END; key++) { switch (key->type) { case KE_KEY: set_bit(EV_KEY, hp_wmi_input_dev->evbit); set_bit(key->keycode, hp_wmi_input_dev->keybit); break; } } set_bit(EV_SW, hp_wmi_input_dev->evbit); set_bit(SW_DOCK, hp_wmi_input_dev->swbit); set_bit(SW_TABLET_MODE, hp_wmi_input_dev->swbit); /* Set initial hardware state */ input_report_switch(hp_wmi_input_dev, SW_DOCK, hp_wmi_dock_state()); input_report_switch(hp_wmi_input_dev, SW_TABLET_MODE, hp_wmi_tablet_state()); input_sync(hp_wmi_input_dev); err = input_register_device(hp_wmi_input_dev); if (err) { input_free_device(hp_wmi_input_dev); return err; } return 0; } static void cleanup_sysfs(struct platform_device *device) { device_remove_file(&device->dev, &dev_attr_display); device_remove_file(&device->dev, &dev_attr_hddtemp); device_remove_file(&device->dev, &dev_attr_als); device_remove_file(&device->dev, &dev_attr_dock); device_remove_file(&device->dev, &dev_attr_tablet); } static int __devinit hp_wmi_bios_setup(struct platform_device *device) { int err; int wireless = hp_wmi_perform_query(HPWMI_WIRELESS_QUERY, 0, 0); err = device_create_file(&device->dev, &dev_attr_display); if (err) goto add_sysfs_error; err = device_create_file(&device->dev, &dev_attr_hddtemp); if (err) goto add_sysfs_error; err = device_create_file(&device->dev, &dev_attr_als); if (err) goto add_sysfs_error; err = device_create_file(&device->dev, &dev_attr_dock); if (err) goto add_sysfs_error; err = device_create_file(&device->dev, &dev_attr_tablet); if (err) goto add_sysfs_error; if (wireless & 0x1) { wifi_rfkill = rfkill_alloc("hp-wifi", &device->dev, RFKILL_TYPE_WLAN, &hp_wmi_rfkill_ops, (void *) HPWMI_WIFI); rfkill_init_sw_state(wifi_rfkill, hp_wmi_get_sw_state(HPWMI_WIFI)); rfkill_set_hw_state(wifi_rfkill, hp_wmi_get_hw_state(HPWMI_WIFI)); err = rfkill_register(wifi_rfkill); if (err) goto register_wifi_error; } if (wireless & 0x2) { bluetooth_rfkill = rfkill_alloc("hp-bluetooth", &device->dev, RFKILL_TYPE_BLUETOOTH, &hp_wmi_rfkill_ops, (void *) HPWMI_BLUETOOTH); rfkill_init_sw_state(bluetooth_rfkill, hp_wmi_get_sw_state(HPWMI_BLUETOOTH)); rfkill_set_hw_state(bluetooth_rfkill, hp_wmi_get_hw_state(HPWMI_BLUETOOTH)); err = rfkill_register(bluetooth_rfkill); if (err) goto register_bluetooth_error; } if (wireless & 0x4) { wwan_rfkill = rfkill_alloc("hp-wwan", &device->dev, RFKILL_TYPE_WWAN, &hp_wmi_rfkill_ops, (void *) HPWMI_WWAN); rfkill_init_sw_state(wwan_rfkill, hp_wmi_get_sw_state(HPWMI_WWAN)); rfkill_set_hw_state(wwan_rfkill, hp_wmi_get_hw_state(HPWMI_WWAN)); err = rfkill_register(wwan_rfkill); if (err) goto register_wwan_err; } return 0; register_wwan_err: rfkill_destroy(wwan_rfkill); if (bluetooth_rfkill) rfkill_unregister(bluetooth_rfkill); register_bluetooth_error: rfkill_destroy(bluetooth_rfkill); if (wifi_rfkill) rfkill_unregister(wifi_rfkill); register_wifi_error: rfkill_destroy(wifi_rfkill); add_sysfs_error: cleanup_sysfs(device); return err; } static int __exit hp_wmi_bios_remove(struct platform_device *device) { cleanup_sysfs(device); if (wifi_rfkill) { rfkill_unregister(wifi_rfkill); rfkill_destroy(wifi_rfkill); } if (bluetooth_rfkill) { rfkill_unregister(bluetooth_rfkill); rfkill_destroy(bluetooth_rfkill); } if (wwan_rfkill) { rfkill_unregister(wwan_rfkill); rfkill_destroy(wwan_rfkill); } return 0; } static int hp_wmi_resume_handler(struct device *device) { /* * Hardware state may have changed while suspended, so trigger * input events for the current state. As this is a switch, * the input layer will only actually pass it on if the state * changed. */ if (hp_wmi_input_dev) { input_report_switch(hp_wmi_input_dev, SW_DOCK, hp_wmi_dock_state()); input_report_switch(hp_wmi_input_dev, SW_TABLET_MODE, hp_wmi_tablet_state()); input_sync(hp_wmi_input_dev); } if (wifi_rfkill) rfkill_set_states(wifi_rfkill, hp_wmi_get_sw_state(HPWMI_WIFI), hp_wmi_get_hw_state(HPWMI_WIFI)); if (bluetooth_rfkill) rfkill_set_states(bluetooth_rfkill, hp_wmi_get_sw_state(HPWMI_BLUETOOTH), hp_wmi_get_hw_state(HPWMI_BLUETOOTH)); if (wwan_rfkill) rfkill_set_states(wwan_rfkill, hp_wmi_get_sw_state(HPWMI_WWAN), hp_wmi_get_hw_state(HPWMI_WWAN)); return 0; } static int __init hp_wmi_init(void) { int err; if (wmi_has_guid(HPWMI_EVENT_GUID)) { err = wmi_install_notify_handler(HPWMI_EVENT_GUID, hp_wmi_notify, NULL); if (ACPI_SUCCESS(err)) hp_wmi_input_setup(); } if (wmi_has_guid(HPWMI_BIOS_GUID)) { err = platform_driver_register(&hp_wmi_driver); if (err) return 0; hp_wmi_platform_dev = platform_device_alloc("hp-wmi", -1); if (!hp_wmi_platform_dev) { platform_driver_unregister(&hp_wmi_driver); return 0; } platform_device_add(hp_wmi_platform_dev); } return 0; } static void __exit hp_wmi_exit(void) { if (wmi_has_guid(HPWMI_EVENT_GUID)) { wmi_remove_notify_handler(HPWMI_EVENT_GUID); input_unregister_device(hp_wmi_input_dev); } if (hp_wmi_platform_dev) { platform_device_del(hp_wmi_platform_dev); platform_driver_unregister(&hp_wmi_driver); } } module_init(hp_wmi_init); module_exit(hp_wmi_exit);
gpl-2.0
dbussink/linux
drivers/cpuidle/cpuidle-clps711x.c
972
1633
/* * CLPS711X CPU idle driver * * Copyright (C) 2014 Alexander Shiyan <shc_work@mail.ru> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. */ #include <linux/cpuidle.h> #include <linux/err.h> #include <linux/io.h> #include <linux/module.h> #include <linux/platform_device.h> #define CLPS711X_CPUIDLE_NAME "clps711x-cpuidle" static void __iomem *clps711x_halt; static int clps711x_cpuidle_halt(struct cpuidle_device *dev, struct cpuidle_driver *drv, int index) { writel(0xaa, clps711x_halt); return index; } static struct cpuidle_driver clps711x_idle_driver = { .name = CLPS711X_CPUIDLE_NAME, .owner = THIS_MODULE, .states[0] = { .name = "HALT", .desc = "CLPS711X HALT", .enter = clps711x_cpuidle_halt, .exit_latency = 1, }, .state_count = 1, }; static int __init clps711x_cpuidle_probe(struct platform_device *pdev) { struct resource *res; res = platform_get_resource(pdev, IORESOURCE_MEM, 0); clps711x_halt = devm_ioremap_resource(&pdev->dev, res); if (IS_ERR(clps711x_halt)) return PTR_ERR(clps711x_halt); return cpuidle_register(&clps711x_idle_driver, NULL); } static struct platform_driver clps711x_cpuidle_driver = { .driver = { .name = CLPS711X_CPUIDLE_NAME, }, }; module_platform_driver_probe(clps711x_cpuidle_driver, clps711x_cpuidle_probe); MODULE_AUTHOR("Alexander Shiyan <shc_work@mail.ru>"); MODULE_DESCRIPTION("CLPS711X CPU idle driver"); MODULE_LICENSE("GPL");
gpl-2.0
IllusionRom-deprecated/android_kernel_samsung_smdk4412
net/sctp/sysctl.c
1740
7326
/* SCTP kernel implementation * (C) Copyright IBM Corp. 2002, 2004 * Copyright (c) 2002 Intel Corp. * * This file is part of the SCTP kernel implementation * * Sysctl related interfaces for SCTP. * * This SCTP implementation 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 SCTP implementation 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 GNU CC; see the file COPYING. If not, write to * the Free Software Foundation, 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * * Please send any bug reports or fixes you make to the * email address(es): * lksctp developers <lksctp-developers@lists.sourceforge.net> * * Or submit a bug report through the following website: * http://www.sf.net/projects/lksctp * * Written or modified by: * Mingqin Liu <liuming@us.ibm.com> * Jon Grimm <jgrimm@us.ibm.com> * Ardelle Fan <ardelle.fan@intel.com> * Ryan Layer <rmlayer@us.ibm.com> * Sridhar Samudrala <sri@us.ibm.com> * * Any bugs reported given to us we will try to fix... any fixes shared will * be incorporated into the next SCTP release. */ #include <net/sctp/structs.h> #include <net/sctp/sctp.h> #include <linux/sysctl.h> static int zero = 0; static int one = 1; static int timer_max = 86400000; /* ms in one day */ static int int_max = INT_MAX; static int sack_timer_min = 1; static int sack_timer_max = 500; static int addr_scope_max = 3; /* check sctp_scope_policy_t in include/net/sctp/constants.h for max entries */ static int rwnd_scale_max = 16; static unsigned long max_autoclose_min = 0; static unsigned long max_autoclose_max = (MAX_SCHEDULE_TIMEOUT / HZ > UINT_MAX) ? UINT_MAX : MAX_SCHEDULE_TIMEOUT / HZ; extern long sysctl_sctp_mem[3]; extern int sysctl_sctp_rmem[3]; extern int sysctl_sctp_wmem[3]; static ctl_table sctp_table[] = { { .procname = "rto_initial", .data = &sctp_rto_initial, .maxlen = sizeof(unsigned int), .mode = 0644, .proc_handler = proc_dointvec_minmax, .extra1 = &one, .extra2 = &timer_max }, { .procname = "rto_min", .data = &sctp_rto_min, .maxlen = sizeof(unsigned int), .mode = 0644, .proc_handler = proc_dointvec_minmax, .extra1 = &one, .extra2 = &timer_max }, { .procname = "rto_max", .data = &sctp_rto_max, .maxlen = sizeof(unsigned int), .mode = 0644, .proc_handler = proc_dointvec_minmax, .extra1 = &one, .extra2 = &timer_max }, { .procname = "valid_cookie_life", .data = &sctp_valid_cookie_life, .maxlen = sizeof(unsigned int), .mode = 0644, .proc_handler = proc_dointvec_minmax, .extra1 = &one, .extra2 = &timer_max }, { .procname = "max_burst", .data = &sctp_max_burst, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_minmax, .extra1 = &zero, .extra2 = &int_max }, { .procname = "association_max_retrans", .data = &sctp_max_retrans_association, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_minmax, .extra1 = &one, .extra2 = &int_max }, { .procname = "sndbuf_policy", .data = &sctp_sndbuf_policy, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "rcvbuf_policy", .data = &sctp_rcvbuf_policy, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "path_max_retrans", .data = &sctp_max_retrans_path, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_minmax, .extra1 = &one, .extra2 = &int_max }, { .procname = "max_init_retransmits", .data = &sctp_max_retrans_init, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_minmax, .extra1 = &one, .extra2 = &int_max }, { .procname = "hb_interval", .data = &sctp_hb_interval, .maxlen = sizeof(unsigned int), .mode = 0644, .proc_handler = proc_dointvec_minmax, .extra1 = &one, .extra2 = &timer_max }, { .procname = "cookie_preserve_enable", .data = &sctp_cookie_preserve_enable, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "rto_alpha_exp_divisor", .data = &sctp_rto_alpha, .maxlen = sizeof(int), .mode = 0444, .proc_handler = proc_dointvec, }, { .procname = "rto_beta_exp_divisor", .data = &sctp_rto_beta, .maxlen = sizeof(int), .mode = 0444, .proc_handler = proc_dointvec, }, { .procname = "addip_enable", .data = &sctp_addip_enable, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "prsctp_enable", .data = &sctp_prsctp_enable, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "sack_timeout", .data = &sctp_sack_timeout, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_minmax, .extra1 = &sack_timer_min, .extra2 = &sack_timer_max, }, { .procname = "sctp_mem", .data = &sysctl_sctp_mem, .maxlen = sizeof(sysctl_sctp_mem), .mode = 0644, .proc_handler = proc_doulongvec_minmax }, { .procname = "sctp_rmem", .data = &sysctl_sctp_rmem, .maxlen = sizeof(sysctl_sctp_rmem), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "sctp_wmem", .data = &sysctl_sctp_wmem, .maxlen = sizeof(sysctl_sctp_wmem), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "auth_enable", .data = &sctp_auth_enable, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "addip_noauth_enable", .data = &sctp_addip_noauth, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "addr_scope_policy", .data = &sctp_scope_policy, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_minmax, .extra1 = &zero, .extra2 = &addr_scope_max, }, { .procname = "rwnd_update_shift", .data = &sctp_rwnd_upd_shift, .maxlen = sizeof(int), .mode = 0644, .proc_handler = &proc_dointvec_minmax, .extra1 = &one, .extra2 = &rwnd_scale_max, }, { .procname = "max_autoclose", .data = &sctp_max_autoclose, .maxlen = sizeof(unsigned long), .mode = 0644, .proc_handler = &proc_doulongvec_minmax, .extra1 = &max_autoclose_min, .extra2 = &max_autoclose_max, }, { /* sentinel */ } }; static struct ctl_path sctp_path[] = { { .procname = "net", }, { .procname = "sctp", }, { } }; static struct ctl_table_header * sctp_sysctl_header; /* Sysctl registration. */ void sctp_sysctl_register(void) { sctp_sysctl_header = register_sysctl_paths(sctp_path, sctp_table); } /* Sysctl deregistration. */ void sctp_sysctl_unregister(void) { unregister_sysctl_table(sctp_sysctl_header); }
gpl-2.0
zzpianoman/android_kernel_samsung_tuna
drivers/gpu/drm/vmwgfx/vmwgfx_resource.c
2252
28408
/************************************************************************** * * Copyright © 2009 VMware, Inc., Palo Alto, CA., USA * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE * USE OR OTHER DEALINGS IN THE SOFTWARE. * **************************************************************************/ #include "vmwgfx_drv.h" #include "vmwgfx_drm.h" #include "ttm/ttm_object.h" #include "ttm/ttm_placement.h" #include "drmP.h" #define VMW_RES_CONTEXT ttm_driver_type0 #define VMW_RES_SURFACE ttm_driver_type1 #define VMW_RES_STREAM ttm_driver_type2 struct vmw_user_context { struct ttm_base_object base; struct vmw_resource res; }; struct vmw_user_surface { struct ttm_base_object base; struct vmw_surface srf; }; struct vmw_user_dma_buffer { struct ttm_base_object base; struct vmw_dma_buffer dma; }; struct vmw_bo_user_rep { uint32_t handle; uint64_t map_handle; }; struct vmw_stream { struct vmw_resource res; uint32_t stream_id; }; struct vmw_user_stream { struct ttm_base_object base; struct vmw_stream stream; }; static inline struct vmw_dma_buffer * vmw_dma_buffer(struct ttm_buffer_object *bo) { return container_of(bo, struct vmw_dma_buffer, base); } static inline struct vmw_user_dma_buffer * vmw_user_dma_buffer(struct ttm_buffer_object *bo) { struct vmw_dma_buffer *vmw_bo = vmw_dma_buffer(bo); return container_of(vmw_bo, struct vmw_user_dma_buffer, dma); } struct vmw_resource *vmw_resource_reference(struct vmw_resource *res) { kref_get(&res->kref); return res; } static void vmw_resource_release(struct kref *kref) { struct vmw_resource *res = container_of(kref, struct vmw_resource, kref); struct vmw_private *dev_priv = res->dev_priv; idr_remove(res->idr, res->id); write_unlock(&dev_priv->resource_lock); if (likely(res->hw_destroy != NULL)) res->hw_destroy(res); if (res->res_free != NULL) res->res_free(res); else kfree(res); write_lock(&dev_priv->resource_lock); } void vmw_resource_unreference(struct vmw_resource **p_res) { struct vmw_resource *res = *p_res; struct vmw_private *dev_priv = res->dev_priv; *p_res = NULL; write_lock(&dev_priv->resource_lock); kref_put(&res->kref, vmw_resource_release); write_unlock(&dev_priv->resource_lock); } static int vmw_resource_init(struct vmw_private *dev_priv, struct vmw_resource *res, struct idr *idr, enum ttm_object_type obj_type, void (*res_free) (struct vmw_resource *res)) { int ret; kref_init(&res->kref); res->hw_destroy = NULL; res->res_free = res_free; res->res_type = obj_type; res->idr = idr; res->avail = false; res->dev_priv = dev_priv; do { if (unlikely(idr_pre_get(idr, GFP_KERNEL) == 0)) return -ENOMEM; write_lock(&dev_priv->resource_lock); ret = idr_get_new_above(idr, res, 1, &res->id); write_unlock(&dev_priv->resource_lock); } while (ret == -EAGAIN); return ret; } /** * vmw_resource_activate * * @res: Pointer to the newly created resource * @hw_destroy: Destroy function. NULL if none. * * Activate a resource after the hardware has been made aware of it. * Set tye destroy function to @destroy. Typically this frees the * resource and destroys the hardware resources associated with it. * Activate basically means that the function vmw_resource_lookup will * find it. */ static void vmw_resource_activate(struct vmw_resource *res, void (*hw_destroy) (struct vmw_resource *)) { struct vmw_private *dev_priv = res->dev_priv; write_lock(&dev_priv->resource_lock); res->avail = true; res->hw_destroy = hw_destroy; write_unlock(&dev_priv->resource_lock); } struct vmw_resource *vmw_resource_lookup(struct vmw_private *dev_priv, struct idr *idr, int id) { struct vmw_resource *res; read_lock(&dev_priv->resource_lock); res = idr_find(idr, id); if (res && res->avail) kref_get(&res->kref); else res = NULL; read_unlock(&dev_priv->resource_lock); if (unlikely(res == NULL)) return NULL; return res; } /** * Context management: */ static void vmw_hw_context_destroy(struct vmw_resource *res) { struct vmw_private *dev_priv = res->dev_priv; struct { SVGA3dCmdHeader header; SVGA3dCmdDestroyContext body; } *cmd = vmw_fifo_reserve(dev_priv, sizeof(*cmd)); if (unlikely(cmd == NULL)) { DRM_ERROR("Failed reserving FIFO space for surface " "destruction.\n"); return; } cmd->header.id = cpu_to_le32(SVGA_3D_CMD_CONTEXT_DESTROY); cmd->header.size = cpu_to_le32(sizeof(cmd->body)); cmd->body.cid = cpu_to_le32(res->id); vmw_fifo_commit(dev_priv, sizeof(*cmd)); vmw_3d_resource_dec(dev_priv); } static int vmw_context_init(struct vmw_private *dev_priv, struct vmw_resource *res, void (*res_free) (struct vmw_resource *res)) { int ret; struct { SVGA3dCmdHeader header; SVGA3dCmdDefineContext body; } *cmd; ret = vmw_resource_init(dev_priv, res, &dev_priv->context_idr, VMW_RES_CONTEXT, res_free); if (unlikely(ret != 0)) { if (res_free == NULL) kfree(res); else res_free(res); return ret; } cmd = vmw_fifo_reserve(dev_priv, sizeof(*cmd)); if (unlikely(cmd == NULL)) { DRM_ERROR("Fifo reserve failed.\n"); vmw_resource_unreference(&res); return -ENOMEM; } cmd->header.id = cpu_to_le32(SVGA_3D_CMD_CONTEXT_DEFINE); cmd->header.size = cpu_to_le32(sizeof(cmd->body)); cmd->body.cid = cpu_to_le32(res->id); vmw_fifo_commit(dev_priv, sizeof(*cmd)); (void) vmw_3d_resource_inc(dev_priv); vmw_resource_activate(res, vmw_hw_context_destroy); return 0; } struct vmw_resource *vmw_context_alloc(struct vmw_private *dev_priv) { struct vmw_resource *res = kmalloc(sizeof(*res), GFP_KERNEL); int ret; if (unlikely(res == NULL)) return NULL; ret = vmw_context_init(dev_priv, res, NULL); return (ret == 0) ? res : NULL; } /** * User-space context management: */ static void vmw_user_context_free(struct vmw_resource *res) { struct vmw_user_context *ctx = container_of(res, struct vmw_user_context, res); kfree(ctx); } /** * This function is called when user space has no more references on the * base object. It releases the base-object's reference on the resource object. */ static void vmw_user_context_base_release(struct ttm_base_object **p_base) { struct ttm_base_object *base = *p_base; struct vmw_user_context *ctx = container_of(base, struct vmw_user_context, base); struct vmw_resource *res = &ctx->res; *p_base = NULL; vmw_resource_unreference(&res); } int vmw_context_destroy_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct vmw_private *dev_priv = vmw_priv(dev); struct vmw_resource *res; struct vmw_user_context *ctx; struct drm_vmw_context_arg *arg = (struct drm_vmw_context_arg *)data; struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile; int ret = 0; res = vmw_resource_lookup(dev_priv, &dev_priv->context_idr, arg->cid); if (unlikely(res == NULL)) return -EINVAL; if (res->res_free != &vmw_user_context_free) { ret = -EINVAL; goto out; } ctx = container_of(res, struct vmw_user_context, res); if (ctx->base.tfile != tfile && !ctx->base.shareable) { ret = -EPERM; goto out; } ttm_ref_object_base_unref(tfile, ctx->base.hash.key, TTM_REF_USAGE); out: vmw_resource_unreference(&res); return ret; } int vmw_context_define_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct vmw_private *dev_priv = vmw_priv(dev); struct vmw_user_context *ctx = kmalloc(sizeof(*ctx), GFP_KERNEL); struct vmw_resource *res; struct vmw_resource *tmp; struct drm_vmw_context_arg *arg = (struct drm_vmw_context_arg *)data; struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile; int ret; if (unlikely(ctx == NULL)) return -ENOMEM; res = &ctx->res; ctx->base.shareable = false; ctx->base.tfile = NULL; ret = vmw_context_init(dev_priv, res, vmw_user_context_free); if (unlikely(ret != 0)) return ret; tmp = vmw_resource_reference(&ctx->res); ret = ttm_base_object_init(tfile, &ctx->base, false, VMW_RES_CONTEXT, &vmw_user_context_base_release, NULL); if (unlikely(ret != 0)) { vmw_resource_unreference(&tmp); goto out_err; } arg->cid = res->id; out_err: vmw_resource_unreference(&res); return ret; } int vmw_context_check(struct vmw_private *dev_priv, struct ttm_object_file *tfile, int id) { struct vmw_resource *res; int ret = 0; read_lock(&dev_priv->resource_lock); res = idr_find(&dev_priv->context_idr, id); if (res && res->avail) { struct vmw_user_context *ctx = container_of(res, struct vmw_user_context, res); if (ctx->base.tfile != tfile && !ctx->base.shareable) ret = -EPERM; } else ret = -EINVAL; read_unlock(&dev_priv->resource_lock); return ret; } /** * Surface management. */ static void vmw_hw_surface_destroy(struct vmw_resource *res) { struct vmw_private *dev_priv = res->dev_priv; struct { SVGA3dCmdHeader header; SVGA3dCmdDestroySurface body; } *cmd = vmw_fifo_reserve(dev_priv, sizeof(*cmd)); if (unlikely(cmd == NULL)) { DRM_ERROR("Failed reserving FIFO space for surface " "destruction.\n"); return; } cmd->header.id = cpu_to_le32(SVGA_3D_CMD_SURFACE_DESTROY); cmd->header.size = cpu_to_le32(sizeof(cmd->body)); cmd->body.sid = cpu_to_le32(res->id); vmw_fifo_commit(dev_priv, sizeof(*cmd)); vmw_3d_resource_dec(dev_priv); } void vmw_surface_res_free(struct vmw_resource *res) { struct vmw_surface *srf = container_of(res, struct vmw_surface, res); kfree(srf->sizes); kfree(srf->snooper.image); kfree(srf); } int vmw_surface_init(struct vmw_private *dev_priv, struct vmw_surface *srf, void (*res_free) (struct vmw_resource *res)) { int ret; struct { SVGA3dCmdHeader header; SVGA3dCmdDefineSurface body; } *cmd; SVGA3dSize *cmd_size; struct vmw_resource *res = &srf->res; struct drm_vmw_size *src_size; size_t submit_size; uint32_t cmd_len; int i; BUG_ON(res_free == NULL); ret = vmw_resource_init(dev_priv, res, &dev_priv->surface_idr, VMW_RES_SURFACE, res_free); if (unlikely(ret != 0)) { res_free(res); return ret; } submit_size = sizeof(*cmd) + srf->num_sizes * sizeof(SVGA3dSize); cmd_len = sizeof(cmd->body) + srf->num_sizes * sizeof(SVGA3dSize); cmd = vmw_fifo_reserve(dev_priv, submit_size); if (unlikely(cmd == NULL)) { DRM_ERROR("Fifo reserve failed for create surface.\n"); vmw_resource_unreference(&res); return -ENOMEM; } cmd->header.id = cpu_to_le32(SVGA_3D_CMD_SURFACE_DEFINE); cmd->header.size = cpu_to_le32(cmd_len); cmd->body.sid = cpu_to_le32(res->id); cmd->body.surfaceFlags = cpu_to_le32(srf->flags); cmd->body.format = cpu_to_le32(srf->format); for (i = 0; i < DRM_VMW_MAX_SURFACE_FACES; ++i) { cmd->body.face[i].numMipLevels = cpu_to_le32(srf->mip_levels[i]); } cmd += 1; cmd_size = (SVGA3dSize *) cmd; src_size = srf->sizes; for (i = 0; i < srf->num_sizes; ++i, cmd_size++, src_size++) { cmd_size->width = cpu_to_le32(src_size->width); cmd_size->height = cpu_to_le32(src_size->height); cmd_size->depth = cpu_to_le32(src_size->depth); } vmw_fifo_commit(dev_priv, submit_size); (void) vmw_3d_resource_inc(dev_priv); vmw_resource_activate(res, vmw_hw_surface_destroy); return 0; } static void vmw_user_surface_free(struct vmw_resource *res) { struct vmw_surface *srf = container_of(res, struct vmw_surface, res); struct vmw_user_surface *user_srf = container_of(srf, struct vmw_user_surface, srf); kfree(srf->sizes); kfree(srf->snooper.image); kfree(user_srf); } int vmw_user_surface_lookup_handle(struct vmw_private *dev_priv, struct ttm_object_file *tfile, uint32_t handle, struct vmw_surface **out) { struct vmw_resource *res; struct vmw_surface *srf; struct vmw_user_surface *user_srf; struct ttm_base_object *base; int ret = -EINVAL; base = ttm_base_object_lookup(tfile, handle); if (unlikely(base == NULL)) return -EINVAL; if (unlikely(base->object_type != VMW_RES_SURFACE)) goto out_bad_resource; user_srf = container_of(base, struct vmw_user_surface, base); srf = &user_srf->srf; res = &srf->res; read_lock(&dev_priv->resource_lock); if (!res->avail || res->res_free != &vmw_user_surface_free) { read_unlock(&dev_priv->resource_lock); goto out_bad_resource; } kref_get(&res->kref); read_unlock(&dev_priv->resource_lock); *out = srf; ret = 0; out_bad_resource: ttm_base_object_unref(&base); return ret; } static void vmw_user_surface_base_release(struct ttm_base_object **p_base) { struct ttm_base_object *base = *p_base; struct vmw_user_surface *user_srf = container_of(base, struct vmw_user_surface, base); struct vmw_resource *res = &user_srf->srf.res; *p_base = NULL; vmw_resource_unreference(&res); } int vmw_surface_destroy_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct drm_vmw_surface_arg *arg = (struct drm_vmw_surface_arg *)data; struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile; return ttm_ref_object_base_unref(tfile, arg->sid, TTM_REF_USAGE); } int vmw_surface_define_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct vmw_private *dev_priv = vmw_priv(dev); struct vmw_user_surface *user_srf = kmalloc(sizeof(*user_srf), GFP_KERNEL); struct vmw_surface *srf; struct vmw_resource *res; struct vmw_resource *tmp; union drm_vmw_surface_create_arg *arg = (union drm_vmw_surface_create_arg *)data; struct drm_vmw_surface_create_req *req = &arg->req; struct drm_vmw_surface_arg *rep = &arg->rep; struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile; struct drm_vmw_size __user *user_sizes; int ret; int i; if (unlikely(user_srf == NULL)) return -ENOMEM; srf = &user_srf->srf; res = &srf->res; srf->flags = req->flags; srf->format = req->format; srf->scanout = req->scanout; memcpy(srf->mip_levels, req->mip_levels, sizeof(srf->mip_levels)); srf->num_sizes = 0; for (i = 0; i < DRM_VMW_MAX_SURFACE_FACES; ++i) srf->num_sizes += srf->mip_levels[i]; if (srf->num_sizes > DRM_VMW_MAX_SURFACE_FACES * DRM_VMW_MAX_MIP_LEVELS) { ret = -EINVAL; goto out_err0; } srf->sizes = kmalloc(srf->num_sizes * sizeof(*srf->sizes), GFP_KERNEL); if (unlikely(srf->sizes == NULL)) { ret = -ENOMEM; goto out_err0; } user_sizes = (struct drm_vmw_size __user *)(unsigned long) req->size_addr; ret = copy_from_user(srf->sizes, user_sizes, srf->num_sizes * sizeof(*srf->sizes)); if (unlikely(ret != 0)) { ret = -EFAULT; goto out_err1; } if (srf->scanout && srf->num_sizes == 1 && srf->sizes[0].width == 64 && srf->sizes[0].height == 64 && srf->format == SVGA3D_A8R8G8B8) { srf->snooper.image = kmalloc(64 * 64 * 4, GFP_KERNEL); /* clear the image */ if (srf->snooper.image) { memset(srf->snooper.image, 0x00, 64 * 64 * 4); } else { DRM_ERROR("Failed to allocate cursor_image\n"); ret = -ENOMEM; goto out_err1; } } else { srf->snooper.image = NULL; } srf->snooper.crtc = NULL; user_srf->base.shareable = false; user_srf->base.tfile = NULL; /** * From this point, the generic resource management functions * destroy the object on failure. */ ret = vmw_surface_init(dev_priv, srf, vmw_user_surface_free); if (unlikely(ret != 0)) return ret; tmp = vmw_resource_reference(&srf->res); ret = ttm_base_object_init(tfile, &user_srf->base, req->shareable, VMW_RES_SURFACE, &vmw_user_surface_base_release, NULL); if (unlikely(ret != 0)) { vmw_resource_unreference(&tmp); vmw_resource_unreference(&res); return ret; } rep->sid = user_srf->base.hash.key; if (rep->sid == SVGA3D_INVALID_ID) DRM_ERROR("Created bad Surface ID.\n"); vmw_resource_unreference(&res); return 0; out_err1: kfree(srf->sizes); out_err0: kfree(user_srf); return ret; } int vmw_surface_reference_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { union drm_vmw_surface_reference_arg *arg = (union drm_vmw_surface_reference_arg *)data; struct drm_vmw_surface_arg *req = &arg->req; struct drm_vmw_surface_create_req *rep = &arg->rep; struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile; struct vmw_surface *srf; struct vmw_user_surface *user_srf; struct drm_vmw_size __user *user_sizes; struct ttm_base_object *base; int ret = -EINVAL; base = ttm_base_object_lookup(tfile, req->sid); if (unlikely(base == NULL)) { DRM_ERROR("Could not find surface to reference.\n"); return -EINVAL; } if (unlikely(base->object_type != VMW_RES_SURFACE)) goto out_bad_resource; user_srf = container_of(base, struct vmw_user_surface, base); srf = &user_srf->srf; ret = ttm_ref_object_add(tfile, &user_srf->base, TTM_REF_USAGE, NULL); if (unlikely(ret != 0)) { DRM_ERROR("Could not add a reference to a surface.\n"); goto out_no_reference; } rep->flags = srf->flags; rep->format = srf->format; memcpy(rep->mip_levels, srf->mip_levels, sizeof(srf->mip_levels)); user_sizes = (struct drm_vmw_size __user *)(unsigned long) rep->size_addr; if (user_sizes) ret = copy_to_user(user_sizes, srf->sizes, srf->num_sizes * sizeof(*srf->sizes)); if (unlikely(ret != 0)) { DRM_ERROR("copy_to_user failed %p %u\n", user_sizes, srf->num_sizes); ret = -EFAULT; } out_bad_resource: out_no_reference: ttm_base_object_unref(&base); return ret; } int vmw_surface_check(struct vmw_private *dev_priv, struct ttm_object_file *tfile, uint32_t handle, int *id) { struct ttm_base_object *base; struct vmw_user_surface *user_srf; int ret = -EPERM; base = ttm_base_object_lookup(tfile, handle); if (unlikely(base == NULL)) return -EINVAL; if (unlikely(base->object_type != VMW_RES_SURFACE)) goto out_bad_surface; user_srf = container_of(base, struct vmw_user_surface, base); *id = user_srf->srf.res.id; ret = 0; out_bad_surface: /** * FIXME: May deadlock here when called from the * command parsing code. */ ttm_base_object_unref(&base); return ret; } /** * Buffer management. */ static size_t vmw_dmabuf_acc_size(struct ttm_bo_global *glob, unsigned long num_pages) { static size_t bo_user_size = ~0; size_t page_array_size = (num_pages * sizeof(void *) + PAGE_SIZE - 1) & PAGE_MASK; if (unlikely(bo_user_size == ~0)) { bo_user_size = glob->ttm_bo_extra_size + ttm_round_pot(sizeof(struct vmw_dma_buffer)); } return bo_user_size + page_array_size; } void vmw_dmabuf_bo_free(struct ttm_buffer_object *bo) { struct vmw_dma_buffer *vmw_bo = vmw_dma_buffer(bo); struct ttm_bo_global *glob = bo->glob; ttm_mem_global_free(glob->mem_glob, bo->acc_size); kfree(vmw_bo); } int vmw_dmabuf_init(struct vmw_private *dev_priv, struct vmw_dma_buffer *vmw_bo, size_t size, struct ttm_placement *placement, bool interruptible, void (*bo_free) (struct ttm_buffer_object *bo)) { struct ttm_bo_device *bdev = &dev_priv->bdev; struct ttm_mem_global *mem_glob = bdev->glob->mem_glob; size_t acc_size; int ret; BUG_ON(!bo_free); acc_size = vmw_dmabuf_acc_size(bdev->glob, (size + PAGE_SIZE - 1) >> PAGE_SHIFT); ret = ttm_mem_global_alloc(mem_glob, acc_size, false, false); if (unlikely(ret != 0)) { /* we must free the bo here as * ttm_buffer_object_init does so as well */ bo_free(&vmw_bo->base); return ret; } memset(vmw_bo, 0, sizeof(*vmw_bo)); INIT_LIST_HEAD(&vmw_bo->validate_list); ret = ttm_bo_init(bdev, &vmw_bo->base, size, ttm_bo_type_device, placement, 0, 0, interruptible, NULL, acc_size, bo_free); return ret; } static void vmw_user_dmabuf_destroy(struct ttm_buffer_object *bo) { struct vmw_user_dma_buffer *vmw_user_bo = vmw_user_dma_buffer(bo); struct ttm_bo_global *glob = bo->glob; ttm_mem_global_free(glob->mem_glob, bo->acc_size); kfree(vmw_user_bo); } static void vmw_user_dmabuf_release(struct ttm_base_object **p_base) { struct vmw_user_dma_buffer *vmw_user_bo; struct ttm_base_object *base = *p_base; struct ttm_buffer_object *bo; *p_base = NULL; if (unlikely(base == NULL)) return; vmw_user_bo = container_of(base, struct vmw_user_dma_buffer, base); bo = &vmw_user_bo->dma.base; ttm_bo_unref(&bo); } int vmw_dmabuf_alloc_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct vmw_private *dev_priv = vmw_priv(dev); union drm_vmw_alloc_dmabuf_arg *arg = (union drm_vmw_alloc_dmabuf_arg *)data; struct drm_vmw_alloc_dmabuf_req *req = &arg->req; struct drm_vmw_dmabuf_rep *rep = &arg->rep; struct vmw_user_dma_buffer *vmw_user_bo; struct ttm_buffer_object *tmp; struct vmw_master *vmaster = vmw_master(file_priv->master); int ret; vmw_user_bo = kzalloc(sizeof(*vmw_user_bo), GFP_KERNEL); if (unlikely(vmw_user_bo == NULL)) return -ENOMEM; ret = ttm_read_lock(&vmaster->lock, true); if (unlikely(ret != 0)) { kfree(vmw_user_bo); return ret; } ret = vmw_dmabuf_init(dev_priv, &vmw_user_bo->dma, req->size, &vmw_vram_sys_placement, true, &vmw_user_dmabuf_destroy); if (unlikely(ret != 0)) goto out_no_dmabuf; tmp = ttm_bo_reference(&vmw_user_bo->dma.base); ret = ttm_base_object_init(vmw_fpriv(file_priv)->tfile, &vmw_user_bo->base, false, ttm_buffer_type, &vmw_user_dmabuf_release, NULL); if (unlikely(ret != 0)) goto out_no_base_object; else { rep->handle = vmw_user_bo->base.hash.key; rep->map_handle = vmw_user_bo->dma.base.addr_space_offset; rep->cur_gmr_id = vmw_user_bo->base.hash.key; rep->cur_gmr_offset = 0; } out_no_base_object: ttm_bo_unref(&tmp); out_no_dmabuf: ttm_read_unlock(&vmaster->lock); return ret; } int vmw_dmabuf_unref_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct drm_vmw_unref_dmabuf_arg *arg = (struct drm_vmw_unref_dmabuf_arg *)data; return ttm_ref_object_base_unref(vmw_fpriv(file_priv)->tfile, arg->handle, TTM_REF_USAGE); } uint32_t vmw_dmabuf_validate_node(struct ttm_buffer_object *bo, uint32_t cur_validate_node) { struct vmw_dma_buffer *vmw_bo = vmw_dma_buffer(bo); if (likely(vmw_bo->on_validate_list)) return vmw_bo->cur_validate_node; vmw_bo->cur_validate_node = cur_validate_node; vmw_bo->on_validate_list = true; return cur_validate_node; } void vmw_dmabuf_validate_clear(struct ttm_buffer_object *bo) { struct vmw_dma_buffer *vmw_bo = vmw_dma_buffer(bo); vmw_bo->on_validate_list = false; } int vmw_user_dmabuf_lookup(struct ttm_object_file *tfile, uint32_t handle, struct vmw_dma_buffer **out) { struct vmw_user_dma_buffer *vmw_user_bo; struct ttm_base_object *base; base = ttm_base_object_lookup(tfile, handle); if (unlikely(base == NULL)) { printk(KERN_ERR "Invalid buffer object handle 0x%08lx.\n", (unsigned long)handle); return -ESRCH; } if (unlikely(base->object_type != ttm_buffer_type)) { ttm_base_object_unref(&base); printk(KERN_ERR "Invalid buffer object handle 0x%08lx.\n", (unsigned long)handle); return -EINVAL; } vmw_user_bo = container_of(base, struct vmw_user_dma_buffer, base); (void)ttm_bo_reference(&vmw_user_bo->dma.base); ttm_base_object_unref(&base); *out = &vmw_user_bo->dma; return 0; } /* * Stream management */ static void vmw_stream_destroy(struct vmw_resource *res) { struct vmw_private *dev_priv = res->dev_priv; struct vmw_stream *stream; int ret; DRM_INFO("%s: unref\n", __func__); stream = container_of(res, struct vmw_stream, res); ret = vmw_overlay_unref(dev_priv, stream->stream_id); WARN_ON(ret != 0); } static int vmw_stream_init(struct vmw_private *dev_priv, struct vmw_stream *stream, void (*res_free) (struct vmw_resource *res)) { struct vmw_resource *res = &stream->res; int ret; ret = vmw_resource_init(dev_priv, res, &dev_priv->stream_idr, VMW_RES_STREAM, res_free); if (unlikely(ret != 0)) { if (res_free == NULL) kfree(stream); else res_free(&stream->res); return ret; } ret = vmw_overlay_claim(dev_priv, &stream->stream_id); if (ret) { vmw_resource_unreference(&res); return ret; } DRM_INFO("%s: claimed\n", __func__); vmw_resource_activate(&stream->res, vmw_stream_destroy); return 0; } /** * User-space context management: */ static void vmw_user_stream_free(struct vmw_resource *res) { struct vmw_user_stream *stream = container_of(res, struct vmw_user_stream, stream.res); kfree(stream); } /** * This function is called when user space has no more references on the * base object. It releases the base-object's reference on the resource object. */ static void vmw_user_stream_base_release(struct ttm_base_object **p_base) { struct ttm_base_object *base = *p_base; struct vmw_user_stream *stream = container_of(base, struct vmw_user_stream, base); struct vmw_resource *res = &stream->stream.res; *p_base = NULL; vmw_resource_unreference(&res); } int vmw_stream_unref_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct vmw_private *dev_priv = vmw_priv(dev); struct vmw_resource *res; struct vmw_user_stream *stream; struct drm_vmw_stream_arg *arg = (struct drm_vmw_stream_arg *)data; struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile; int ret = 0; res = vmw_resource_lookup(dev_priv, &dev_priv->stream_idr, arg->stream_id); if (unlikely(res == NULL)) return -EINVAL; if (res->res_free != &vmw_user_stream_free) { ret = -EINVAL; goto out; } stream = container_of(res, struct vmw_user_stream, stream.res); if (stream->base.tfile != tfile) { ret = -EINVAL; goto out; } ttm_ref_object_base_unref(tfile, stream->base.hash.key, TTM_REF_USAGE); out: vmw_resource_unreference(&res); return ret; } int vmw_stream_claim_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct vmw_private *dev_priv = vmw_priv(dev); struct vmw_user_stream *stream = kmalloc(sizeof(*stream), GFP_KERNEL); struct vmw_resource *res; struct vmw_resource *tmp; struct drm_vmw_stream_arg *arg = (struct drm_vmw_stream_arg *)data; struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile; int ret; if (unlikely(stream == NULL)) return -ENOMEM; res = &stream->stream.res; stream->base.shareable = false; stream->base.tfile = NULL; ret = vmw_stream_init(dev_priv, &stream->stream, vmw_user_stream_free); if (unlikely(ret != 0)) return ret; tmp = vmw_resource_reference(res); ret = ttm_base_object_init(tfile, &stream->base, false, VMW_RES_STREAM, &vmw_user_stream_base_release, NULL); if (unlikely(ret != 0)) { vmw_resource_unreference(&tmp); goto out_err; } arg->stream_id = res->id; out_err: vmw_resource_unreference(&res); return ret; } int vmw_user_stream_lookup(struct vmw_private *dev_priv, struct ttm_object_file *tfile, uint32_t *inout_id, struct vmw_resource **out) { struct vmw_user_stream *stream; struct vmw_resource *res; int ret; res = vmw_resource_lookup(dev_priv, &dev_priv->stream_idr, *inout_id); if (unlikely(res == NULL)) return -EINVAL; if (res->res_free != &vmw_user_stream_free) { ret = -EINVAL; goto err_ref; } stream = container_of(res, struct vmw_user_stream, stream.res); if (stream->base.tfile != tfile) { ret = -EPERM; goto err_ref; } *inout_id = stream->stream.stream_id; *out = res; return 0; err_ref: vmw_resource_unreference(&res); return ret; }
gpl-2.0
webbhorn/netgroups
drivers/net/usb/cdc_eem.c
2508
9669
/* * USB CDC EEM network interface driver * Copyright (C) 2009 Oberthur Technologies * by Omar Laazimani, Olivier Condemine * * 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/module.h> #include <linux/init.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/ctype.h> #include <linux/ethtool.h> #include <linux/workqueue.h> #include <linux/mii.h> #include <linux/usb.h> #include <linux/crc32.h> #include <linux/usb/cdc.h> #include <linux/usb/usbnet.h> #include <linux/gfp.h> #include <linux/if_vlan.h> /* * This driver is an implementation of the CDC "Ethernet Emulation * Model" (EEM) specification, which encapsulates Ethernet frames * for transport over USB using a simpler USB device model than the * previous CDC "Ethernet Control Model" (ECM, or "CDC Ethernet"). * * For details, see www.usb.org/developers/devclass_docs/CDC_EEM10.pdf * * This version has been tested with GIGAntIC WuaoW SIM Smart Card on 2.6.24, * 2.6.27 and 2.6.30rc2 kernel. * It has also been validated on Openmoko Om 2008.12 (based on 2.6.24 kernel). * build on 23-April-2009 */ #define EEM_HEAD 2 /* 2 byte header */ /*-------------------------------------------------------------------------*/ static void eem_linkcmd_complete(struct urb *urb) { dev_kfree_skb(urb->context); usb_free_urb(urb); } static void eem_linkcmd(struct usbnet *dev, struct sk_buff *skb) { struct urb *urb; int status; urb = usb_alloc_urb(0, GFP_ATOMIC); if (!urb) goto fail; usb_fill_bulk_urb(urb, dev->udev, dev->out, skb->data, skb->len, eem_linkcmd_complete, skb); status = usb_submit_urb(urb, GFP_ATOMIC); if (status) { usb_free_urb(urb); fail: dev_kfree_skb(skb); netdev_warn(dev->net, "link cmd failure\n"); return; } } static int eem_bind(struct usbnet *dev, struct usb_interface *intf) { int status = 0; status = usbnet_get_endpoints(dev, intf); if (status < 0) { usb_set_intfdata(intf, NULL); usb_driver_release_interface(driver_of(intf), intf); return status; } /* no jumbogram (16K) support for now */ dev->net->hard_header_len += EEM_HEAD + ETH_FCS_LEN + VLAN_HLEN; dev->hard_mtu = dev->net->mtu + dev->net->hard_header_len; return 0; } /* * EEM permits packing multiple Ethernet frames into USB transfers * (a "bundle"), but for TX we don't try to do that. */ static struct sk_buff *eem_tx_fixup(struct usbnet *dev, struct sk_buff *skb, gfp_t flags) { struct sk_buff *skb2 = NULL; u16 len = skb->len; u32 crc = 0; int padlen = 0; /* When ((len + EEM_HEAD + ETH_FCS_LEN) % dev->maxpacket) is * zero, stick two bytes of zero length EEM packet on the end. * Else the framework would add invalid single byte padding, * since it can't know whether ZLPs will be handled right by * all the relevant hardware and software. */ if (!((len + EEM_HEAD + ETH_FCS_LEN) % dev->maxpacket)) padlen += 2; if (!skb_cloned(skb)) { int headroom = skb_headroom(skb); int tailroom = skb_tailroom(skb); if ((tailroom >= ETH_FCS_LEN + padlen) && (headroom >= EEM_HEAD)) goto done; if ((headroom + tailroom) > (EEM_HEAD + ETH_FCS_LEN + padlen)) { skb->data = memmove(skb->head + EEM_HEAD, skb->data, skb->len); skb_set_tail_pointer(skb, len); goto done; } } skb2 = skb_copy_expand(skb, EEM_HEAD, ETH_FCS_LEN + padlen, flags); if (!skb2) return NULL; dev_kfree_skb_any(skb); skb = skb2; done: /* we don't use the "no Ethernet CRC" option */ crc = crc32_le(~0, skb->data, skb->len); crc = ~crc; put_unaligned_le32(crc, skb_put(skb, 4)); /* EEM packet header format: * b0..13: length of ethernet frame * b14: bmCRC (1 == valid Ethernet CRC) * b15: bmType (0 == data) */ len = skb->len; put_unaligned_le16(BIT(14) | len, skb_push(skb, 2)); /* Bundle a zero length EEM packet if needed */ if (padlen) put_unaligned_le16(0, skb_put(skb, 2)); return skb; } static int eem_rx_fixup(struct usbnet *dev, struct sk_buff *skb) { /* * Our task here is to strip off framing, leaving skb with one * data frame for the usbnet framework code to process. But we * may have received multiple EEM payloads, or command payloads. * So we must process _everything_ as if it's a header, except * maybe the last data payload * * REVISIT the framework needs updating so that when we consume * all payloads (the last or only message was a command, or a * zero length EEM packet) that is not accounted as an rx_error. */ do { struct sk_buff *skb2 = NULL; u16 header; u16 len = 0; /* incomplete EEM header? */ if (skb->len < EEM_HEAD) return 0; /* * EEM packet header format: * b0..14: EEM type dependent (Data or Command) * b15: bmType */ header = get_unaligned_le16(skb->data); skb_pull(skb, EEM_HEAD); /* * The bmType bit helps to denote when EEM * packet is data or command : * bmType = 0 : EEM data payload * bmType = 1 : EEM (link) command */ if (header & BIT(15)) { u16 bmEEMCmd; /* * EEM (link) command packet: * b0..10: bmEEMCmdParam * b11..13: bmEEMCmd * b14: bmReserved (must be 0) * b15: 1 (EEM command) */ if (header & BIT(14)) { netdev_dbg(dev->net, "reserved command %04x\n", header); continue; } bmEEMCmd = (header >> 11) & 0x7; switch (bmEEMCmd) { /* Responding to echo requests is mandatory. */ case 0: /* Echo command */ len = header & 0x7FF; /* bogus command? */ if (skb->len < len) return 0; skb2 = skb_clone(skb, GFP_ATOMIC); if (unlikely(!skb2)) goto next; skb_trim(skb2, len); put_unaligned_le16(BIT(15) | (1 << 11) | len, skb_push(skb2, 2)); eem_linkcmd(dev, skb2); break; /* * Host may choose to ignore hints. * - suspend: peripheral ready to suspend * - response: suggest N millisec polling * - response complete: suggest N sec polling * * Suspend is reported and maybe heeded. */ case 2: /* Suspend hint */ usbnet_device_suggests_idle(dev); continue; case 3: /* Response hint */ case 4: /* Response complete hint */ continue; /* * Hosts should never receive host-to-peripheral * or reserved command codes; or responses to an * echo command we didn't send. */ case 1: /* Echo response */ case 5: /* Tickle */ default: /* reserved */ netdev_warn(dev->net, "unexpected link command %d\n", bmEEMCmd); continue; } } else { u32 crc, crc2; int is_last; /* zero length EEM packet? */ if (header == 0) continue; /* * EEM data packet header : * b0..13: length of ethernet frame * b14: bmCRC * b15: 0 (EEM data) */ len = header & 0x3FFF; /* bogus EEM payload? */ if (skb->len < len) return 0; /* bogus ethernet frame? */ if (len < (ETH_HLEN + ETH_FCS_LEN)) goto next; /* * Treat the last payload differently: framework * code expects our "fixup" to have stripped off * headers, so "skb" is a data packet (or error). * Else if it's not the last payload, keep "skb" * for further processing. */ is_last = (len == skb->len); if (is_last) skb2 = skb; else { skb2 = skb_clone(skb, GFP_ATOMIC); if (unlikely(!skb2)) return 0; } /* * The bmCRC helps to denote when the CRC field in * the Ethernet frame contains a calculated CRC: * bmCRC = 1 : CRC is calculated * bmCRC = 0 : CRC = 0xDEADBEEF */ if (header & BIT(14)) { crc = get_unaligned_le32(skb2->data + len - ETH_FCS_LEN); crc2 = ~crc32_le(~0, skb2->data, skb2->len - ETH_FCS_LEN); } else { crc = get_unaligned_be32(skb2->data + len - ETH_FCS_LEN); crc2 = 0xdeadbeef; } skb_trim(skb2, len - ETH_FCS_LEN); if (is_last) return crc == crc2; if (unlikely(crc != crc2)) { dev->net->stats.rx_errors++; dev_kfree_skb_any(skb2); } else usbnet_skb_return(dev, skb2); } next: skb_pull(skb, len); } while (skb->len); return 1; } static const struct driver_info eem_info = { .description = "CDC EEM Device", .flags = FLAG_ETHER | FLAG_POINTTOPOINT, .bind = eem_bind, .rx_fixup = eem_rx_fixup, .tx_fixup = eem_tx_fixup, }; /*-------------------------------------------------------------------------*/ static const struct usb_device_id products[] = { { USB_INTERFACE_INFO(USB_CLASS_COMM, USB_CDC_SUBCLASS_EEM, USB_CDC_PROTO_EEM), .driver_info = (unsigned long) &eem_info, }, { /* EMPTY == end of list */ }, }; MODULE_DEVICE_TABLE(usb, products); static struct usb_driver eem_driver = { .name = "cdc_eem", .id_table = products, .probe = usbnet_probe, .disconnect = usbnet_disconnect, .suspend = usbnet_suspend, .resume = usbnet_resume, .disable_hub_initiated_lpm = 1, }; module_usb_driver(eem_driver); MODULE_AUTHOR("Omar Laazimani <omar.oberthur@gmail.com>"); MODULE_DESCRIPTION("USB CDC EEM"); MODULE_LICENSE("GPL");
gpl-2.0
milaq/android_kernel_hp_tenderloin
fs/nfs/idmap.c
2508
19319
/* * fs/nfs/idmap.c * * UID and GID to name mapping for clients. * * Copyright (c) 2002 The Regents of the University of Michigan. * All rights reserved. * * Marius Aamodt Eriksen <marius@umich.edu> * * 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 name of the University nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED ``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 REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <linux/types.h> #include <linux/string.h> #include <linux/kernel.h> static int nfs_map_string_to_numeric(const char *name, size_t namelen, __u32 *res) { unsigned long val; char buf[16]; if (memchr(name, '@', namelen) != NULL || namelen >= sizeof(buf)) return 0; memcpy(buf, name, namelen); buf[namelen] = '\0'; if (strict_strtoul(buf, 0, &val) != 0) return 0; *res = val; return 1; } static int nfs_map_numeric_to_string(__u32 id, char *buf, size_t buflen) { return snprintf(buf, buflen, "%u", id); } #ifdef CONFIG_NFS_USE_NEW_IDMAPPER #include <linux/slab.h> #include <linux/cred.h> #include <linux/sunrpc/sched.h> #include <linux/nfs4.h> #include <linux/nfs_fs_sb.h> #include <linux/nfs_idmap.h> #include <linux/keyctl.h> #include <linux/key-type.h> #include <linux/rcupdate.h> #include <linux/err.h> #include <keys/user-type.h> #define NFS_UINT_MAXLEN 11 const struct cred *id_resolver_cache; struct key_type key_type_id_resolver = { .name = "id_resolver", .instantiate = user_instantiate, .match = user_match, .revoke = user_revoke, .destroy = user_destroy, .describe = user_describe, .read = user_read, }; int nfs_idmap_init(void) { struct cred *cred; struct key *keyring; int ret = 0; printk(KERN_NOTICE "Registering the %s key type\n", key_type_id_resolver.name); cred = prepare_kernel_cred(NULL); if (!cred) return -ENOMEM; keyring = key_alloc(&key_type_keyring, ".id_resolver", 0, 0, cred, (KEY_POS_ALL & ~KEY_POS_SETATTR) | KEY_USR_VIEW | KEY_USR_READ, KEY_ALLOC_NOT_IN_QUOTA); if (IS_ERR(keyring)) { ret = PTR_ERR(keyring); goto failed_put_cred; } ret = key_instantiate_and_link(keyring, NULL, 0, NULL, NULL); if (ret < 0) goto failed_put_key; ret = register_key_type(&key_type_id_resolver); if (ret < 0) goto failed_put_key; cred->thread_keyring = keyring; cred->jit_keyring = KEY_REQKEY_DEFL_THREAD_KEYRING; id_resolver_cache = cred; return 0; failed_put_key: key_put(keyring); failed_put_cred: put_cred(cred); return ret; } void nfs_idmap_quit(void) { key_revoke(id_resolver_cache->thread_keyring); unregister_key_type(&key_type_id_resolver); put_cred(id_resolver_cache); } /* * Assemble the description to pass to request_key() * This function will allocate a new string and update dest to point * at it. The caller is responsible for freeing dest. * * On error 0 is returned. Otherwise, the length of dest is returned. */ static ssize_t nfs_idmap_get_desc(const char *name, size_t namelen, const char *type, size_t typelen, char **desc) { char *cp; size_t desclen = typelen + namelen + 2; *desc = kmalloc(desclen, GFP_KERNEL); if (!*desc) return -ENOMEM; cp = *desc; memcpy(cp, type, typelen); cp += typelen; *cp++ = ':'; memcpy(cp, name, namelen); cp += namelen; *cp = '\0'; return desclen; } static ssize_t nfs_idmap_request_key(const char *name, size_t namelen, const char *type, void *data, size_t data_size) { const struct cred *saved_cred; struct key *rkey; char *desc; struct user_key_payload *payload; ssize_t ret; ret = nfs_idmap_get_desc(name, namelen, type, strlen(type), &desc); if (ret <= 0) goto out; saved_cred = override_creds(id_resolver_cache); rkey = request_key(&key_type_id_resolver, desc, ""); revert_creds(saved_cred); kfree(desc); if (IS_ERR(rkey)) { ret = PTR_ERR(rkey); goto out; } rcu_read_lock(); rkey->perm |= KEY_USR_VIEW; ret = key_validate(rkey); if (ret < 0) goto out_up; payload = rcu_dereference(rkey->payload.data); if (IS_ERR_OR_NULL(payload)) { ret = PTR_ERR(payload); goto out_up; } ret = payload->datalen; if (ret > 0 && ret <= data_size) memcpy(data, payload->data, ret); else ret = -EINVAL; out_up: rcu_read_unlock(); key_put(rkey); out: return ret; } /* ID -> Name */ static ssize_t nfs_idmap_lookup_name(__u32 id, const char *type, char *buf, size_t buflen) { char id_str[NFS_UINT_MAXLEN]; int id_len; ssize_t ret; id_len = snprintf(id_str, sizeof(id_str), "%u", id); ret = nfs_idmap_request_key(id_str, id_len, type, buf, buflen); if (ret < 0) return -EINVAL; return ret; } /* Name -> ID */ static int nfs_idmap_lookup_id(const char *name, size_t namelen, const char *type, __u32 *id) { char id_str[NFS_UINT_MAXLEN]; long id_long; ssize_t data_size; int ret = 0; data_size = nfs_idmap_request_key(name, namelen, type, id_str, NFS_UINT_MAXLEN); if (data_size <= 0) { ret = -EINVAL; } else { ret = strict_strtol(id_str, 10, &id_long); *id = (__u32)id_long; } return ret; } int nfs_map_name_to_uid(const struct nfs_server *server, const char *name, size_t namelen, __u32 *uid) { if (nfs_map_string_to_numeric(name, namelen, uid)) return 0; return nfs_idmap_lookup_id(name, namelen, "uid", uid); } int nfs_map_group_to_gid(const struct nfs_server *server, const char *name, size_t namelen, __u32 *gid) { if (nfs_map_string_to_numeric(name, namelen, gid)) return 0; return nfs_idmap_lookup_id(name, namelen, "gid", gid); } int nfs_map_uid_to_name(const struct nfs_server *server, __u32 uid, char *buf, size_t buflen) { int ret = -EINVAL; if (!(server->caps & NFS_CAP_UIDGID_NOMAP)) ret = nfs_idmap_lookup_name(uid, "user", buf, buflen); if (ret < 0) ret = nfs_map_numeric_to_string(uid, buf, buflen); return ret; } int nfs_map_gid_to_group(const struct nfs_server *server, __u32 gid, char *buf, size_t buflen) { int ret = -EINVAL; if (!(server->caps & NFS_CAP_UIDGID_NOMAP)) ret = nfs_idmap_lookup_name(gid, "group", buf, buflen); if (ret < 0) ret = nfs_map_numeric_to_string(gid, buf, buflen); return ret; } #else /* CONFIG_NFS_USE_NEW_IDMAPPER not defined */ #include <linux/module.h> #include <linux/mutex.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/socket.h> #include <linux/in.h> #include <linux/sched.h> #include <linux/sunrpc/clnt.h> #include <linux/workqueue.h> #include <linux/sunrpc/rpc_pipe_fs.h> #include <linux/nfs_fs.h> #include <linux/nfs_idmap.h> #include "nfs4_fs.h" #define IDMAP_HASH_SZ 128 /* Default cache timeout is 10 minutes */ unsigned int nfs_idmap_cache_timeout = 600 * HZ; static int param_set_idmap_timeout(const char *val, struct kernel_param *kp) { char *endp; int num = simple_strtol(val, &endp, 0); int jif = num * HZ; if (endp == val || *endp || num < 0 || jif < num) return -EINVAL; *((int *)kp->arg) = jif; return 0; } module_param_call(idmap_cache_timeout, param_set_idmap_timeout, param_get_int, &nfs_idmap_cache_timeout, 0644); struct idmap_hashent { unsigned long ih_expires; __u32 ih_id; size_t ih_namelen; char ih_name[IDMAP_NAMESZ]; }; struct idmap_hashtable { __u8 h_type; struct idmap_hashent h_entries[IDMAP_HASH_SZ]; }; struct idmap { struct dentry *idmap_dentry; wait_queue_head_t idmap_wq; struct idmap_msg idmap_im; struct mutex idmap_lock; /* Serializes upcalls */ struct mutex idmap_im_lock; /* Protects the hashtable */ struct idmap_hashtable idmap_user_hash; struct idmap_hashtable idmap_group_hash; }; static ssize_t idmap_pipe_upcall(struct file *, struct rpc_pipe_msg *, char __user *, size_t); static ssize_t idmap_pipe_downcall(struct file *, const char __user *, size_t); static void idmap_pipe_destroy_msg(struct rpc_pipe_msg *); static unsigned int fnvhash32(const void *, size_t); static const struct rpc_pipe_ops idmap_upcall_ops = { .upcall = idmap_pipe_upcall, .downcall = idmap_pipe_downcall, .destroy_msg = idmap_pipe_destroy_msg, }; int nfs_idmap_new(struct nfs_client *clp) { struct idmap *idmap; int error; BUG_ON(clp->cl_idmap != NULL); idmap = kzalloc(sizeof(*idmap), GFP_KERNEL); if (idmap == NULL) return -ENOMEM; idmap->idmap_dentry = rpc_mkpipe(clp->cl_rpcclient->cl_path.dentry, "idmap", idmap, &idmap_upcall_ops, 0); if (IS_ERR(idmap->idmap_dentry)) { error = PTR_ERR(idmap->idmap_dentry); kfree(idmap); return error; } mutex_init(&idmap->idmap_lock); mutex_init(&idmap->idmap_im_lock); init_waitqueue_head(&idmap->idmap_wq); idmap->idmap_user_hash.h_type = IDMAP_TYPE_USER; idmap->idmap_group_hash.h_type = IDMAP_TYPE_GROUP; clp->cl_idmap = idmap; return 0; } void nfs_idmap_delete(struct nfs_client *clp) { struct idmap *idmap = clp->cl_idmap; if (!idmap) return; rpc_unlink(idmap->idmap_dentry); clp->cl_idmap = NULL; kfree(idmap); } /* * Helper routines for manipulating the hashtable */ static inline struct idmap_hashent * idmap_name_hash(struct idmap_hashtable* h, const char *name, size_t len) { return &h->h_entries[fnvhash32(name, len) % IDMAP_HASH_SZ]; } static struct idmap_hashent * idmap_lookup_name(struct idmap_hashtable *h, const char *name, size_t len) { struct idmap_hashent *he = idmap_name_hash(h, name, len); if (he->ih_namelen != len || memcmp(he->ih_name, name, len) != 0) return NULL; if (time_after(jiffies, he->ih_expires)) return NULL; return he; } static inline struct idmap_hashent * idmap_id_hash(struct idmap_hashtable* h, __u32 id) { return &h->h_entries[fnvhash32(&id, sizeof(id)) % IDMAP_HASH_SZ]; } static struct idmap_hashent * idmap_lookup_id(struct idmap_hashtable *h, __u32 id) { struct idmap_hashent *he = idmap_id_hash(h, id); if (he->ih_id != id || he->ih_namelen == 0) return NULL; if (time_after(jiffies, he->ih_expires)) return NULL; return he; } /* * Routines for allocating new entries in the hashtable. * For now, we just have 1 entry per bucket, so it's all * pretty trivial. */ static inline struct idmap_hashent * idmap_alloc_name(struct idmap_hashtable *h, char *name, size_t len) { return idmap_name_hash(h, name, len); } static inline struct idmap_hashent * idmap_alloc_id(struct idmap_hashtable *h, __u32 id) { return idmap_id_hash(h, id); } static void idmap_update_entry(struct idmap_hashent *he, const char *name, size_t namelen, __u32 id) { he->ih_id = id; memcpy(he->ih_name, name, namelen); he->ih_name[namelen] = '\0'; he->ih_namelen = namelen; he->ih_expires = jiffies + nfs_idmap_cache_timeout; } /* * Name -> ID */ static int nfs_idmap_id(struct idmap *idmap, struct idmap_hashtable *h, const char *name, size_t namelen, __u32 *id) { struct rpc_pipe_msg msg; struct idmap_msg *im; struct idmap_hashent *he; DECLARE_WAITQUEUE(wq, current); int ret = -EIO; im = &idmap->idmap_im; /* * String sanity checks * Note that the userland daemon expects NUL terminated strings */ for (;;) { if (namelen == 0) return -EINVAL; if (name[namelen-1] != '\0') break; namelen--; } if (namelen >= IDMAP_NAMESZ) return -EINVAL; mutex_lock(&idmap->idmap_lock); mutex_lock(&idmap->idmap_im_lock); he = idmap_lookup_name(h, name, namelen); if (he != NULL) { *id = he->ih_id; ret = 0; goto out; } memset(im, 0, sizeof(*im)); memcpy(im->im_name, name, namelen); im->im_type = h->h_type; im->im_conv = IDMAP_CONV_NAMETOID; memset(&msg, 0, sizeof(msg)); msg.data = im; msg.len = sizeof(*im); add_wait_queue(&idmap->idmap_wq, &wq); if (rpc_queue_upcall(idmap->idmap_dentry->d_inode, &msg) < 0) { remove_wait_queue(&idmap->idmap_wq, &wq); goto out; } set_current_state(TASK_UNINTERRUPTIBLE); mutex_unlock(&idmap->idmap_im_lock); schedule(); __set_current_state(TASK_RUNNING); remove_wait_queue(&idmap->idmap_wq, &wq); mutex_lock(&idmap->idmap_im_lock); if (im->im_status & IDMAP_STATUS_SUCCESS) { *id = im->im_id; ret = 0; } out: memset(im, 0, sizeof(*im)); mutex_unlock(&idmap->idmap_im_lock); mutex_unlock(&idmap->idmap_lock); return ret; } /* * ID -> Name */ static int nfs_idmap_name(struct idmap *idmap, struct idmap_hashtable *h, __u32 id, char *name) { struct rpc_pipe_msg msg; struct idmap_msg *im; struct idmap_hashent *he; DECLARE_WAITQUEUE(wq, current); int ret = -EIO; unsigned int len; im = &idmap->idmap_im; mutex_lock(&idmap->idmap_lock); mutex_lock(&idmap->idmap_im_lock); he = idmap_lookup_id(h, id); if (he) { memcpy(name, he->ih_name, he->ih_namelen); ret = he->ih_namelen; goto out; } memset(im, 0, sizeof(*im)); im->im_type = h->h_type; im->im_conv = IDMAP_CONV_IDTONAME; im->im_id = id; memset(&msg, 0, sizeof(msg)); msg.data = im; msg.len = sizeof(*im); add_wait_queue(&idmap->idmap_wq, &wq); if (rpc_queue_upcall(idmap->idmap_dentry->d_inode, &msg) < 0) { remove_wait_queue(&idmap->idmap_wq, &wq); goto out; } set_current_state(TASK_UNINTERRUPTIBLE); mutex_unlock(&idmap->idmap_im_lock); schedule(); __set_current_state(TASK_RUNNING); remove_wait_queue(&idmap->idmap_wq, &wq); mutex_lock(&idmap->idmap_im_lock); if (im->im_status & IDMAP_STATUS_SUCCESS) { if ((len = strnlen(im->im_name, IDMAP_NAMESZ)) == 0) goto out; memcpy(name, im->im_name, len); ret = len; } out: memset(im, 0, sizeof(*im)); mutex_unlock(&idmap->idmap_im_lock); mutex_unlock(&idmap->idmap_lock); return ret; } /* RPC pipefs upcall/downcall routines */ static ssize_t idmap_pipe_upcall(struct file *filp, struct rpc_pipe_msg *msg, char __user *dst, size_t buflen) { char *data = (char *)msg->data + msg->copied; size_t mlen = min(msg->len, buflen); unsigned long left; left = copy_to_user(dst, data, mlen); if (left == mlen) { msg->errno = -EFAULT; return -EFAULT; } mlen -= left; msg->copied += mlen; msg->errno = 0; return mlen; } static ssize_t idmap_pipe_downcall(struct file *filp, const char __user *src, size_t mlen) { struct rpc_inode *rpci = RPC_I(filp->f_path.dentry->d_inode); struct idmap *idmap = (struct idmap *)rpci->private; struct idmap_msg im_in, *im = &idmap->idmap_im; struct idmap_hashtable *h; struct idmap_hashent *he = NULL; size_t namelen_in; int ret; if (mlen != sizeof(im_in)) return -ENOSPC; if (copy_from_user(&im_in, src, mlen) != 0) return -EFAULT; mutex_lock(&idmap->idmap_im_lock); ret = mlen; im->im_status = im_in.im_status; /* If we got an error, terminate now, and wake up pending upcalls */ if (!(im_in.im_status & IDMAP_STATUS_SUCCESS)) { wake_up(&idmap->idmap_wq); goto out; } /* Sanity checking of strings */ ret = -EINVAL; namelen_in = strnlen(im_in.im_name, IDMAP_NAMESZ); if (namelen_in == 0 || namelen_in == IDMAP_NAMESZ) goto out; switch (im_in.im_type) { case IDMAP_TYPE_USER: h = &idmap->idmap_user_hash; break; case IDMAP_TYPE_GROUP: h = &idmap->idmap_group_hash; break; default: goto out; } switch (im_in.im_conv) { case IDMAP_CONV_IDTONAME: /* Did we match the current upcall? */ if (im->im_conv == IDMAP_CONV_IDTONAME && im->im_type == im_in.im_type && im->im_id == im_in.im_id) { /* Yes: copy string, including the terminating '\0' */ memcpy(im->im_name, im_in.im_name, namelen_in); im->im_name[namelen_in] = '\0'; wake_up(&idmap->idmap_wq); } he = idmap_alloc_id(h, im_in.im_id); break; case IDMAP_CONV_NAMETOID: /* Did we match the current upcall? */ if (im->im_conv == IDMAP_CONV_NAMETOID && im->im_type == im_in.im_type && strnlen(im->im_name, IDMAP_NAMESZ) == namelen_in && memcmp(im->im_name, im_in.im_name, namelen_in) == 0) { im->im_id = im_in.im_id; wake_up(&idmap->idmap_wq); } he = idmap_alloc_name(h, im_in.im_name, namelen_in); break; default: goto out; } /* If the entry is valid, also copy it to the cache */ if (he != NULL) idmap_update_entry(he, im_in.im_name, namelen_in, im_in.im_id); ret = mlen; out: mutex_unlock(&idmap->idmap_im_lock); return ret; } static void idmap_pipe_destroy_msg(struct rpc_pipe_msg *msg) { struct idmap_msg *im = msg->data; struct idmap *idmap = container_of(im, struct idmap, idmap_im); if (msg->errno >= 0) return; mutex_lock(&idmap->idmap_im_lock); im->im_status = IDMAP_STATUS_LOOKUPFAIL; wake_up(&idmap->idmap_wq); mutex_unlock(&idmap->idmap_im_lock); } /* * Fowler/Noll/Vo hash * http://www.isthe.com/chongo/tech/comp/fnv/ */ #define FNV_P_32 ((unsigned int)0x01000193) /* 16777619 */ #define FNV_1_32 ((unsigned int)0x811c9dc5) /* 2166136261 */ static unsigned int fnvhash32(const void *buf, size_t buflen) { const unsigned char *p, *end = (const unsigned char *)buf + buflen; unsigned int hash = FNV_1_32; for (p = buf; p < end; p++) { hash *= FNV_P_32; hash ^= (unsigned int)*p; } return hash; } int nfs_map_name_to_uid(const struct nfs_server *server, const char *name, size_t namelen, __u32 *uid) { struct idmap *idmap = server->nfs_client->cl_idmap; if (nfs_map_string_to_numeric(name, namelen, uid)) return 0; return nfs_idmap_id(idmap, &idmap->idmap_user_hash, name, namelen, uid); } int nfs_map_group_to_gid(const struct nfs_server *server, const char *name, size_t namelen, __u32 *uid) { struct idmap *idmap = server->nfs_client->cl_idmap; if (nfs_map_string_to_numeric(name, namelen, uid)) return 0; return nfs_idmap_id(idmap, &idmap->idmap_group_hash, name, namelen, uid); } int nfs_map_uid_to_name(const struct nfs_server *server, __u32 uid, char *buf, size_t buflen) { struct idmap *idmap = server->nfs_client->cl_idmap; int ret = -EINVAL; if (!(server->caps & NFS_CAP_UIDGID_NOMAP)) ret = nfs_idmap_name(idmap, &idmap->idmap_user_hash, uid, buf); if (ret < 0) ret = nfs_map_numeric_to_string(uid, buf, buflen); return ret; } int nfs_map_gid_to_group(const struct nfs_server *server, __u32 uid, char *buf, size_t buflen) { struct idmap *idmap = server->nfs_client->cl_idmap; int ret = -EINVAL; if (!(server->caps & NFS_CAP_UIDGID_NOMAP)) ret = nfs_idmap_name(idmap, &idmap->idmap_group_hash, uid, buf); if (ret < 0) ret = nfs_map_numeric_to_string(uid, buf, buflen); return ret; } #endif /* CONFIG_NFS_USE_NEW_IDMAPPER */
gpl-2.0
mastero9017/hammerhead
drivers/net/usb/qmi_wwan.c
2764
19245
/* * Copyright (c) 2012 Bjørn Mork <bjorn@mork.no> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. */ #include <linux/module.h> #include <linux/netdevice.h> #include <linux/ethtool.h> #include <linux/mii.h> #include <linux/usb.h> #include <linux/usb/cdc.h> #include <linux/usb/usbnet.h> #include <linux/usb/cdc-wdm.h> /* The name of the CDC Device Management driver */ #define DM_DRIVER "cdc_wdm" /* * This driver supports wwan (3G/LTE/?) devices using a vendor * specific management protocol called Qualcomm MSM Interface (QMI) - * in addition to the more common AT commands over serial interface * management * * QMI is wrapped in CDC, using CDC encapsulated commands on the * control ("master") interface of a two-interface CDC Union * resembling standard CDC ECM. The devices do not use the control * interface for any other CDC messages. Most likely because the * management protocol is used in place of the standard CDC * notifications NOTIFY_NETWORK_CONNECTION and NOTIFY_SPEED_CHANGE * * Handling a protocol like QMI is out of the scope for any driver. * It can be exported as a character device using the cdc-wdm driver, * which will enable userspace applications ("modem managers") to * handle it. This may be required to use the network interface * provided by the driver. * * These devices may alternatively/additionally be configured using AT * commands on any of the serial interfaces driven by the option driver * * This driver binds only to the data ("slave") interface to enable * the cdc-wdm driver to bind to the control interface. It still * parses the CDC functional descriptors on the control interface to * a) verify that this is indeed a handled interface (CDC Union * header lists it as slave) * b) get MAC address and other ethernet config from the CDC Ethernet * header * c) enable user bind requests against the control interface, which * is the common way to bind to CDC Ethernet Control Model type * interfaces * d) provide a hint to the user about which interface is the * corresponding management interface */ static int qmi_wwan_bind(struct usbnet *dev, struct usb_interface *intf) { int status = -1; struct usb_interface *control = NULL; u8 *buf = intf->cur_altsetting->extra; int len = intf->cur_altsetting->extralen; struct usb_interface_descriptor *desc = &intf->cur_altsetting->desc; struct usb_cdc_union_desc *cdc_union = NULL; struct usb_cdc_ether_desc *cdc_ether = NULL; u32 required = 1 << USB_CDC_HEADER_TYPE | 1 << USB_CDC_UNION_TYPE; u32 found = 0; atomic_t *pmcount = (void *)&dev->data[1]; atomic_set(pmcount, 0); /* * assume a data interface has no additional descriptors and * that the control and data interface are numbered * consecutively - this holds for the Huawei device at least */ if (len == 0 && desc->bInterfaceNumber > 0) { control = usb_ifnum_to_if(dev->udev, desc->bInterfaceNumber - 1); if (!control) goto err; buf = control->cur_altsetting->extra; len = control->cur_altsetting->extralen; dev_dbg(&intf->dev, "guessing \"control\" => %s, \"data\" => this\n", dev_name(&control->dev)); } while (len > 3) { struct usb_descriptor_header *h = (void *)buf; /* ignore any misplaced descriptors */ if (h->bDescriptorType != USB_DT_CS_INTERFACE) goto next_desc; /* buf[2] is CDC descriptor subtype */ switch (buf[2]) { case USB_CDC_HEADER_TYPE: if (found & 1 << USB_CDC_HEADER_TYPE) { dev_dbg(&intf->dev, "extra CDC header\n"); goto err; } if (h->bLength != sizeof(struct usb_cdc_header_desc)) { dev_dbg(&intf->dev, "CDC header len %u\n", h->bLength); goto err; } break; case USB_CDC_UNION_TYPE: if (found & 1 << USB_CDC_UNION_TYPE) { dev_dbg(&intf->dev, "extra CDC union\n"); goto err; } if (h->bLength != sizeof(struct usb_cdc_union_desc)) { dev_dbg(&intf->dev, "CDC union len %u\n", h->bLength); goto err; } cdc_union = (struct usb_cdc_union_desc *)buf; break; case USB_CDC_ETHERNET_TYPE: if (found & 1 << USB_CDC_ETHERNET_TYPE) { dev_dbg(&intf->dev, "extra CDC ether\n"); goto err; } if (h->bLength != sizeof(struct usb_cdc_ether_desc)) { dev_dbg(&intf->dev, "CDC ether len %u\n", h->bLength); goto err; } cdc_ether = (struct usb_cdc_ether_desc *)buf; break; } /* * Remember which CDC functional descriptors we've seen. Works * for all types we care about, of which USB_CDC_ETHERNET_TYPE * (0x0f) is the highest numbered */ if (buf[2] < 32) found |= 1 << buf[2]; next_desc: len -= h->bLength; buf += h->bLength; } /* did we find all the required ones? */ if ((found & required) != required) { dev_err(&intf->dev, "CDC functional descriptors missing\n"); goto err; } /* give the user a helpful hint if trying to bind to the wrong interface */ if (cdc_union && desc->bInterfaceNumber == cdc_union->bMasterInterface0) { dev_err(&intf->dev, "leaving \"control\" interface for " DM_DRIVER " - try binding to %s instead!\n", dev_name(&usb_ifnum_to_if(dev->udev, cdc_union->bSlaveInterface0)->dev)); goto err; } /* errors aren't fatal - we can live with the dynamic address */ if (cdc_ether) { dev->hard_mtu = le16_to_cpu(cdc_ether->wMaxSegmentSize); usbnet_get_ethernet_addr(dev, cdc_ether->iMACAddress); } /* success! point the user to the management interface */ if (control) dev_info(&intf->dev, "Use \"" DM_DRIVER "\" for QMI interface %s\n", dev_name(&control->dev)); /* XXX: add a sysfs symlink somewhere to help management applications find it? */ /* collect bulk endpoints now that we know intf == "data" interface */ status = usbnet_get_endpoints(dev, intf); err: return status; } /* using a counter to merge subdriver requests with our own into a combined state */ static int qmi_wwan_manage_power(struct usbnet *dev, int on) { atomic_t *pmcount = (void *)&dev->data[1]; int rv = 0; dev_dbg(&dev->intf->dev, "%s() pmcount=%d, on=%d\n", __func__, atomic_read(pmcount), on); if ((on && atomic_add_return(1, pmcount) == 1) || (!on && atomic_dec_and_test(pmcount))) { /* need autopm_get/put here to ensure the usbcore sees the new value */ rv = usb_autopm_get_interface(dev->intf); if (rv < 0) goto err; dev->intf->needs_remote_wakeup = on; usb_autopm_put_interface(dev->intf); } err: return rv; } static int qmi_wwan_cdc_wdm_manage_power(struct usb_interface *intf, int on) { struct usbnet *dev = usb_get_intfdata(intf); return qmi_wwan_manage_power(dev, on); } /* Some devices combine the "control" and "data" functions into a * single interface with all three endpoints: interrupt + bulk in and * out * * Setting up cdc-wdm as a subdriver owning the interrupt endpoint * will let it provide userspace access to the encapsulated QMI * protocol without interfering with the usbnet operations. */ static int qmi_wwan_bind_shared(struct usbnet *dev, struct usb_interface *intf) { int rv; struct usb_driver *subdriver = NULL; atomic_t *pmcount = (void *)&dev->data[1]; /* ZTE makes devices where the interface descriptors and endpoint * configurations of two or more interfaces are identical, even * though the functions are completely different. If set, then * driver_info->data is a bitmap of acceptable interface numbers * allowing us to bind to one such interface without binding to * all of them */ if (dev->driver_info->data && !test_bit(intf->cur_altsetting->desc.bInterfaceNumber, &dev->driver_info->data)) { dev_info(&intf->dev, "not on our whitelist - ignored"); rv = -ENODEV; goto err; } atomic_set(pmcount, 0); /* collect all three endpoints */ rv = usbnet_get_endpoints(dev, intf); if (rv < 0) goto err; /* require interrupt endpoint for subdriver */ if (!dev->status) { rv = -EINVAL; goto err; } subdriver = usb_cdc_wdm_register(intf, &dev->status->desc, 512, &qmi_wwan_cdc_wdm_manage_power); if (IS_ERR(subdriver)) { rv = PTR_ERR(subdriver); goto err; } /* can't let usbnet use the interrupt endpoint */ dev->status = NULL; /* save subdriver struct for suspend/resume wrappers */ dev->data[0] = (unsigned long)subdriver; err: return rv; } /* Gobi devices uses identical class/protocol codes for all interfaces regardless * of function. Some of these are CDC ACM like and have the exact same endpoints * we are looking for. This leaves two possible strategies for identifying the * correct interface: * a) hardcoding interface number, or * b) use the fact that the wwan interface is the only one lacking additional * (CDC functional) descriptors * * Let's see if we can get away with the generic b) solution. */ static int qmi_wwan_bind_gobi(struct usbnet *dev, struct usb_interface *intf) { int rv = -EINVAL; /* ignore any interface with additional descriptors */ if (intf->cur_altsetting->extralen) goto err; rv = qmi_wwan_bind_shared(dev, intf); err: return rv; } static void qmi_wwan_unbind_shared(struct usbnet *dev, struct usb_interface *intf) { struct usb_driver *subdriver = (void *)dev->data[0]; if (subdriver && subdriver->disconnect) subdriver->disconnect(intf); dev->data[0] = (unsigned long)NULL; } /* suspend/resume wrappers calling both usbnet and the cdc-wdm * subdriver if present. * * NOTE: cdc-wdm also supports pre/post_reset, but we cannot provide * wrappers for those without adding usbnet reset support first. */ static int qmi_wwan_suspend(struct usb_interface *intf, pm_message_t message) { struct usbnet *dev = usb_get_intfdata(intf); struct usb_driver *subdriver = (void *)dev->data[0]; int ret; ret = usbnet_suspend(intf, message); if (ret < 0) goto err; if (subdriver && subdriver->suspend) ret = subdriver->suspend(intf, message); if (ret < 0) usbnet_resume(intf); err: return ret; } static int qmi_wwan_resume(struct usb_interface *intf) { struct usbnet *dev = usb_get_intfdata(intf); struct usb_driver *subdriver = (void *)dev->data[0]; int ret = 0; if (subdriver && subdriver->resume) ret = subdriver->resume(intf); if (ret < 0) goto err; ret = usbnet_resume(intf); if (ret < 0 && subdriver && subdriver->resume && subdriver->suspend) subdriver->suspend(intf, PMSG_SUSPEND); err: return ret; } static const struct driver_info qmi_wwan_info = { .description = "QMI speaking wwan device", .flags = FLAG_WWAN, .bind = qmi_wwan_bind, .manage_power = qmi_wwan_manage_power, }; static const struct driver_info qmi_wwan_shared = { .description = "QMI speaking wwan device with combined interface", .flags = FLAG_WWAN, .bind = qmi_wwan_bind_shared, .unbind = qmi_wwan_unbind_shared, .manage_power = qmi_wwan_manage_power, }; static const struct driver_info qmi_wwan_gobi = { .description = "Qualcomm Gobi wwan/QMI device", .flags = FLAG_WWAN, .bind = qmi_wwan_bind_gobi, .unbind = qmi_wwan_unbind_shared, .manage_power = qmi_wwan_manage_power, }; /* ZTE suck at making USB descriptors */ static const struct driver_info qmi_wwan_force_int4 = { .description = "Qualcomm Gobi wwan/QMI device", .flags = FLAG_WWAN, .bind = qmi_wwan_bind_gobi, .unbind = qmi_wwan_unbind_shared, .manage_power = qmi_wwan_manage_power, .data = BIT(4), /* interface whitelist bitmap */ }; /* Sierra Wireless provide equally useless interface descriptors * Devices in QMI mode can be switched between two different * configurations: * a) USB interface #8 is QMI/wwan * b) USB interfaces #8, #19 and #20 are QMI/wwan * * Both configurations provide a number of other interfaces (serial++), * some of which have the same endpoint configuration as we expect, so * a whitelist or blacklist is necessary. * * FIXME: The below whitelist should include BIT(20). It does not * because I cannot get it to work... */ static const struct driver_info qmi_wwan_sierra = { .description = "Sierra Wireless wwan/QMI device", .flags = FLAG_WWAN, .bind = qmi_wwan_bind_gobi, .unbind = qmi_wwan_unbind_shared, .manage_power = qmi_wwan_manage_power, .data = BIT(8) | BIT(19), /* interface whitelist bitmap */ }; #define HUAWEI_VENDOR_ID 0x12D1 #define QMI_GOBI_DEVICE(vend, prod) \ USB_DEVICE(vend, prod), \ .driver_info = (unsigned long)&qmi_wwan_gobi static const struct usb_device_id products[] = { { /* Huawei E392, E398 and possibly others sharing both device id and more... */ .match_flags = USB_DEVICE_ID_MATCH_VENDOR | USB_DEVICE_ID_MATCH_INT_INFO, .idVendor = HUAWEI_VENDOR_ID, .bInterfaceClass = USB_CLASS_VENDOR_SPEC, .bInterfaceSubClass = 1, .bInterfaceProtocol = 8, /* NOTE: This is the *slave* interface of the CDC Union! */ .driver_info = (unsigned long)&qmi_wwan_info, }, { /* Huawei E392, E398 and possibly others in "Windows mode" * using a combined control and data interface without any CDC * functional descriptors */ .match_flags = USB_DEVICE_ID_MATCH_VENDOR | USB_DEVICE_ID_MATCH_INT_INFO, .idVendor = HUAWEI_VENDOR_ID, .bInterfaceClass = USB_CLASS_VENDOR_SPEC, .bInterfaceSubClass = 1, .bInterfaceProtocol = 17, .driver_info = (unsigned long)&qmi_wwan_shared, }, { /* Pantech UML290 */ .match_flags = USB_DEVICE_ID_MATCH_DEVICE | USB_DEVICE_ID_MATCH_INT_INFO, .idVendor = 0x106c, .idProduct = 0x3718, .bInterfaceClass = 0xff, .bInterfaceSubClass = 0xf0, .bInterfaceProtocol = 0xff, .driver_info = (unsigned long)&qmi_wwan_shared, }, { /* ZTE MF820D */ .match_flags = USB_DEVICE_ID_MATCH_DEVICE | USB_DEVICE_ID_MATCH_INT_INFO, .idVendor = 0x19d2, .idProduct = 0x0167, .bInterfaceClass = 0xff, .bInterfaceSubClass = 0xff, .bInterfaceProtocol = 0xff, .driver_info = (unsigned long)&qmi_wwan_force_int4, }, { /* ZTE (Vodafone) K3565-Z */ .match_flags = USB_DEVICE_ID_MATCH_DEVICE | USB_DEVICE_ID_MATCH_INT_INFO, .idVendor = 0x19d2, .idProduct = 0x0063, .bInterfaceClass = 0xff, .bInterfaceSubClass = 0xff, .bInterfaceProtocol = 0xff, .driver_info = (unsigned long)&qmi_wwan_force_int4, }, { /* ZTE (Vodafone) K3570-Z */ .match_flags = USB_DEVICE_ID_MATCH_DEVICE | USB_DEVICE_ID_MATCH_INT_INFO, .idVendor = 0x19d2, .idProduct = 0x1008, .bInterfaceClass = 0xff, .bInterfaceSubClass = 0xff, .bInterfaceProtocol = 0xff, .driver_info = (unsigned long)&qmi_wwan_force_int4, }, { /* ZTE (Vodafone) K3571-Z */ .match_flags = USB_DEVICE_ID_MATCH_DEVICE | USB_DEVICE_ID_MATCH_INT_INFO, .idVendor = 0x19d2, .idProduct = 0x1010, .bInterfaceClass = 0xff, .bInterfaceSubClass = 0xff, .bInterfaceProtocol = 0xff, .driver_info = (unsigned long)&qmi_wwan_force_int4, }, { /* ZTE (Vodafone) K4505-Z */ .match_flags = USB_DEVICE_ID_MATCH_DEVICE | USB_DEVICE_ID_MATCH_INT_INFO, .idVendor = 0x19d2, .idProduct = 0x0104, .bInterfaceClass = 0xff, .bInterfaceSubClass = 0xff, .bInterfaceProtocol = 0xff, .driver_info = (unsigned long)&qmi_wwan_force_int4, }, { /* Sierra Wireless MC77xx in QMI mode */ .match_flags = USB_DEVICE_ID_MATCH_DEVICE | USB_DEVICE_ID_MATCH_INT_INFO, .idVendor = 0x1199, .idProduct = 0x68a2, .bInterfaceClass = 0xff, .bInterfaceSubClass = 0xff, .bInterfaceProtocol = 0xff, .driver_info = (unsigned long)&qmi_wwan_sierra, }, {QMI_GOBI_DEVICE(0x05c6, 0x9212)}, /* Acer Gobi Modem Device */ {QMI_GOBI_DEVICE(0x03f0, 0x1f1d)}, /* HP un2400 Gobi Modem Device */ {QMI_GOBI_DEVICE(0x03f0, 0x371d)}, /* HP un2430 Mobile Broadband Module */ {QMI_GOBI_DEVICE(0x04da, 0x250d)}, /* Panasonic Gobi Modem device */ {QMI_GOBI_DEVICE(0x413c, 0x8172)}, /* Dell Gobi Modem device */ {QMI_GOBI_DEVICE(0x1410, 0xa001)}, /* Novatel Gobi Modem device */ {QMI_GOBI_DEVICE(0x0b05, 0x1776)}, /* Asus Gobi Modem device */ {QMI_GOBI_DEVICE(0x19d2, 0xfff3)}, /* ONDA Gobi Modem device */ {QMI_GOBI_DEVICE(0x05c6, 0x9001)}, /* Generic Gobi Modem device */ {QMI_GOBI_DEVICE(0x05c6, 0x9002)}, /* Generic Gobi Modem device */ {QMI_GOBI_DEVICE(0x05c6, 0x9202)}, /* Generic Gobi Modem device */ {QMI_GOBI_DEVICE(0x05c6, 0x9203)}, /* Generic Gobi Modem device */ {QMI_GOBI_DEVICE(0x05c6, 0x9222)}, /* Generic Gobi Modem device */ {QMI_GOBI_DEVICE(0x05c6, 0x9009)}, /* Generic Gobi Modem device */ {QMI_GOBI_DEVICE(0x413c, 0x8186)}, /* Dell Gobi 2000 Modem device (N0218, VU936) */ {QMI_GOBI_DEVICE(0x05c6, 0x920b)}, /* Generic Gobi 2000 Modem device */ {QMI_GOBI_DEVICE(0x05c6, 0x9225)}, /* Sony Gobi 2000 Modem device (N0279, VU730) */ {QMI_GOBI_DEVICE(0x05c6, 0x9245)}, /* Samsung Gobi 2000 Modem device (VL176) */ {QMI_GOBI_DEVICE(0x03f0, 0x251d)}, /* HP Gobi 2000 Modem device (VP412) */ {QMI_GOBI_DEVICE(0x05c6, 0x9215)}, /* Acer Gobi 2000 Modem device (VP413) */ {QMI_GOBI_DEVICE(0x05c6, 0x9265)}, /* Asus Gobi 2000 Modem device (VR305) */ {QMI_GOBI_DEVICE(0x05c6, 0x9235)}, /* Top Global Gobi 2000 Modem device (VR306) */ {QMI_GOBI_DEVICE(0x05c6, 0x9275)}, /* iRex Technologies Gobi 2000 Modem device (VR307) */ {QMI_GOBI_DEVICE(0x1199, 0x9001)}, /* Sierra Wireless Gobi 2000 Modem device (VT773) */ {QMI_GOBI_DEVICE(0x1199, 0x9002)}, /* Sierra Wireless Gobi 2000 Modem device (VT773) */ {QMI_GOBI_DEVICE(0x1199, 0x9003)}, /* Sierra Wireless Gobi 2000 Modem device (VT773) */ {QMI_GOBI_DEVICE(0x1199, 0x9004)}, /* Sierra Wireless Gobi 2000 Modem device (VT773) */ {QMI_GOBI_DEVICE(0x1199, 0x9005)}, /* Sierra Wireless Gobi 2000 Modem device (VT773) */ {QMI_GOBI_DEVICE(0x1199, 0x9006)}, /* Sierra Wireless Gobi 2000 Modem device (VT773) */ {QMI_GOBI_DEVICE(0x1199, 0x9007)}, /* Sierra Wireless Gobi 2000 Modem device (VT773) */ {QMI_GOBI_DEVICE(0x1199, 0x9008)}, /* Sierra Wireless Gobi 2000 Modem device (VT773) */ {QMI_GOBI_DEVICE(0x1199, 0x9009)}, /* Sierra Wireless Gobi 2000 Modem device (VT773) */ {QMI_GOBI_DEVICE(0x1199, 0x900a)}, /* Sierra Wireless Gobi 2000 Modem device (VT773) */ {QMI_GOBI_DEVICE(0x1199, 0x9011)}, /* Sierra Wireless Gobi 2000 Modem device (MC8305) */ {QMI_GOBI_DEVICE(0x16d8, 0x8002)}, /* CMDTech Gobi 2000 Modem device (VU922) */ {QMI_GOBI_DEVICE(0x05c6, 0x9205)}, /* Gobi 2000 Modem device */ {QMI_GOBI_DEVICE(0x1199, 0x9013)}, /* Sierra Wireless Gobi 3000 Modem device (MC8355) */ { } /* END */ }; MODULE_DEVICE_TABLE(usb, products); static struct usb_driver qmi_wwan_driver = { .name = "qmi_wwan", .id_table = products, .probe = usbnet_probe, .disconnect = usbnet_disconnect, .suspend = qmi_wwan_suspend, .resume = qmi_wwan_resume, .reset_resume = qmi_wwan_resume, .supports_autosuspend = 1, }; static int __init qmi_wwan_init(void) { return usb_register(&qmi_wwan_driver); } module_init(qmi_wwan_init); static void __exit qmi_wwan_exit(void) { usb_deregister(&qmi_wwan_driver); } module_exit(qmi_wwan_exit); MODULE_AUTHOR("Bjørn Mork <bjorn@mork.no>"); MODULE_DESCRIPTION("Qualcomm MSM Interface (QMI) WWAN driver"); MODULE_LICENSE("GPL");
gpl-2.0
sonicxml/furry-octo-lana
sound/soc/codecs/tlv320dac33.c
2764
45004
/* * ALSA SoC Texas Instruments TLV320DAC33 codec driver * * Author: Peter Ujfalusi <peter.ujfalusi@ti.com> * * Copyright: (C) 2009 Nokia Corporation * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * 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/module.h> #include <linux/moduleparam.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/pm.h> #include <linux/i2c.h> #include <linux/platform_device.h> #include <linux/interrupt.h> #include <linux/gpio.h> #include <linux/regulator/consumer.h> #include <linux/slab.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/soc.h> #include <sound/initval.h> #include <sound/tlv.h> #include <sound/tlv320dac33-plat.h> #include "tlv320dac33.h" /* * The internal FIFO is 24576 bytes long * It can be configured to hold 16bit or 24bit samples * In 16bit configuration the FIFO can hold 6144 stereo samples * In 24bit configuration the FIFO can hold 4096 stereo samples */ #define DAC33_FIFO_SIZE_16BIT 6144 #define DAC33_FIFO_SIZE_24BIT 4096 #define DAC33_MODE7_MARGIN 10 /* Safety margin for FIFO in Mode7 */ #define BURST_BASEFREQ_HZ 49152000 #define SAMPLES_TO_US(rate, samples) \ (1000000000 / ((rate * 1000) / samples)) #define US_TO_SAMPLES(rate, us) \ (rate / (1000000 / (us < 1000000 ? us : 1000000))) #define UTHR_FROM_PERIOD_SIZE(samples, playrate, burstrate) \ ((samples * 5000) / ((burstrate * 5000) / (burstrate - playrate))) static void dac33_calculate_times(struct snd_pcm_substream *substream); static int dac33_prepare_chip(struct snd_pcm_substream *substream); enum dac33_state { DAC33_IDLE = 0, DAC33_PREFILL, DAC33_PLAYBACK, DAC33_FLUSH, }; enum dac33_fifo_modes { DAC33_FIFO_BYPASS = 0, DAC33_FIFO_MODE1, DAC33_FIFO_MODE7, DAC33_FIFO_LAST_MODE, }; #define DAC33_NUM_SUPPLIES 3 static const char *dac33_supply_names[DAC33_NUM_SUPPLIES] = { "AVDD", "DVDD", "IOVDD", }; struct tlv320dac33_priv { struct mutex mutex; struct workqueue_struct *dac33_wq; struct work_struct work; struct snd_soc_codec *codec; struct regulator_bulk_data supplies[DAC33_NUM_SUPPLIES]; struct snd_pcm_substream *substream; int power_gpio; int chip_power; int irq; unsigned int refclk; unsigned int alarm_threshold; /* set to be half of LATENCY_TIME_MS */ enum dac33_fifo_modes fifo_mode;/* FIFO mode selection */ unsigned int fifo_size; /* Size of the FIFO in samples */ unsigned int nsample; /* burst read amount from host */ int mode1_latency; /* latency caused by the i2c writes in * us */ u8 burst_bclkdiv; /* BCLK divider value in burst mode */ unsigned int burst_rate; /* Interface speed in Burst modes */ int keep_bclk; /* Keep the BCLK continuously running * in FIFO modes */ spinlock_t lock; unsigned long long t_stamp1; /* Time stamp for FIFO modes to */ unsigned long long t_stamp2; /* calculate the FIFO caused delay */ unsigned int mode1_us_burst; /* Time to burst read n number of * samples */ unsigned int mode7_us_to_lthr; /* Time to reach lthr from uthr */ unsigned int uthr; enum dac33_state state; enum snd_soc_control_type control_type; void *control_data; }; static const u8 dac33_reg[DAC33_CACHEREGNUM] = { 0x00, 0x00, 0x00, 0x00, /* 0x00 - 0x03 */ 0x00, 0x00, 0x00, 0x00, /* 0x04 - 0x07 */ 0x00, 0x00, 0x00, 0x00, /* 0x08 - 0x0b */ 0x00, 0x00, 0x00, 0x00, /* 0x0c - 0x0f */ 0x00, 0x00, 0x00, 0x00, /* 0x10 - 0x13 */ 0x00, 0x00, 0x00, 0x00, /* 0x14 - 0x17 */ 0x00, 0x00, 0x00, 0x00, /* 0x18 - 0x1b */ 0x00, 0x00, 0x00, 0x00, /* 0x1c - 0x1f */ 0x00, 0x00, 0x00, 0x00, /* 0x20 - 0x23 */ 0x00, 0x00, 0x00, 0x00, /* 0x24 - 0x27 */ 0x00, 0x00, 0x00, 0x00, /* 0x28 - 0x2b */ 0x00, 0x00, 0x00, 0x80, /* 0x2c - 0x2f */ 0x80, 0x00, 0x00, 0x00, /* 0x30 - 0x33 */ 0x00, 0x00, 0x00, 0x00, /* 0x34 - 0x37 */ 0x00, 0x00, /* 0x38 - 0x39 */ /* Registers 0x3a - 0x3f are reserved */ 0x00, 0x00, /* 0x3a - 0x3b */ 0x00, 0x00, 0x00, 0x00, /* 0x3c - 0x3f */ 0x00, 0x00, 0x00, 0x00, /* 0x40 - 0x43 */ 0x00, 0x80, /* 0x44 - 0x45 */ /* Registers 0x46 - 0x47 are reserved */ 0x80, 0x80, /* 0x46 - 0x47 */ 0x80, 0x00, 0x00, /* 0x48 - 0x4a */ /* Registers 0x4b - 0x7c are reserved */ 0x00, /* 0x4b */ 0x00, 0x00, 0x00, 0x00, /* 0x4c - 0x4f */ 0x00, 0x00, 0x00, 0x00, /* 0x50 - 0x53 */ 0x00, 0x00, 0x00, 0x00, /* 0x54 - 0x57 */ 0x00, 0x00, 0x00, 0x00, /* 0x58 - 0x5b */ 0x00, 0x00, 0x00, 0x00, /* 0x5c - 0x5f */ 0x00, 0x00, 0x00, 0x00, /* 0x60 - 0x63 */ 0x00, 0x00, 0x00, 0x00, /* 0x64 - 0x67 */ 0x00, 0x00, 0x00, 0x00, /* 0x68 - 0x6b */ 0x00, 0x00, 0x00, 0x00, /* 0x6c - 0x6f */ 0x00, 0x00, 0x00, 0x00, /* 0x70 - 0x73 */ 0x00, 0x00, 0x00, 0x00, /* 0x74 - 0x77 */ 0x00, 0x00, 0x00, 0x00, /* 0x78 - 0x7b */ 0x00, /* 0x7c */ 0xda, 0x33, 0x03, /* 0x7d - 0x7f */ }; /* Register read and write */ static inline unsigned int dac33_read_reg_cache(struct snd_soc_codec *codec, unsigned reg) { u8 *cache = codec->reg_cache; if (reg >= DAC33_CACHEREGNUM) return 0; return cache[reg]; } static inline void dac33_write_reg_cache(struct snd_soc_codec *codec, u8 reg, u8 value) { u8 *cache = codec->reg_cache; if (reg >= DAC33_CACHEREGNUM) return; cache[reg] = value; } static int dac33_read(struct snd_soc_codec *codec, unsigned int reg, u8 *value) { struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); int val, ret = 0; *value = reg & 0xff; /* If powered off, return the cached value */ if (dac33->chip_power) { val = i2c_smbus_read_byte_data(codec->control_data, value[0]); if (val < 0) { dev_err(codec->dev, "Read failed (%d)\n", val); value[0] = dac33_read_reg_cache(codec, reg); ret = val; } else { value[0] = val; dac33_write_reg_cache(codec, reg, val); } } else { value[0] = dac33_read_reg_cache(codec, reg); } return ret; } static int dac33_write(struct snd_soc_codec *codec, unsigned int reg, unsigned int value) { struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); u8 data[2]; int ret = 0; /* * data is * D15..D8 dac33 register offset * D7...D0 register data */ data[0] = reg & 0xff; data[1] = value & 0xff; dac33_write_reg_cache(codec, data[0], data[1]); if (dac33->chip_power) { ret = codec->hw_write(codec->control_data, data, 2); if (ret != 2) dev_err(codec->dev, "Write failed (%d)\n", ret); else ret = 0; } return ret; } static int dac33_write_locked(struct snd_soc_codec *codec, unsigned int reg, unsigned int value) { struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); int ret; mutex_lock(&dac33->mutex); ret = dac33_write(codec, reg, value); mutex_unlock(&dac33->mutex); return ret; } #define DAC33_I2C_ADDR_AUTOINC 0x80 static int dac33_write16(struct snd_soc_codec *codec, unsigned int reg, unsigned int value) { struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); u8 data[3]; int ret = 0; /* * data is * D23..D16 dac33 register offset * D15..D8 register data MSB * D7...D0 register data LSB */ data[0] = reg & 0xff; data[1] = (value >> 8) & 0xff; data[2] = value & 0xff; dac33_write_reg_cache(codec, data[0], data[1]); dac33_write_reg_cache(codec, data[0] + 1, data[2]); if (dac33->chip_power) { /* We need to set autoincrement mode for 16 bit writes */ data[0] |= DAC33_I2C_ADDR_AUTOINC; ret = codec->hw_write(codec->control_data, data, 3); if (ret != 3) dev_err(codec->dev, "Write failed (%d)\n", ret); else ret = 0; } return ret; } static void dac33_init_chip(struct snd_soc_codec *codec) { struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); if (unlikely(!dac33->chip_power)) return; /* A : DAC sample rate Fsref/1.5 */ dac33_write(codec, DAC33_DAC_CTRL_A, DAC33_DACRATE(0)); /* B : DAC src=normal, not muted */ dac33_write(codec, DAC33_DAC_CTRL_B, DAC33_DACSRCR_RIGHT | DAC33_DACSRCL_LEFT); /* C : (defaults) */ dac33_write(codec, DAC33_DAC_CTRL_C, 0x00); /* 73 : volume soft stepping control, clock source = internal osc (?) */ dac33_write(codec, DAC33_ANA_VOL_SOFT_STEP_CTRL, DAC33_VOLCLKEN); /* Restore only selected registers (gains mostly) */ dac33_write(codec, DAC33_LDAC_DIG_VOL_CTRL, dac33_read_reg_cache(codec, DAC33_LDAC_DIG_VOL_CTRL)); dac33_write(codec, DAC33_RDAC_DIG_VOL_CTRL, dac33_read_reg_cache(codec, DAC33_RDAC_DIG_VOL_CTRL)); dac33_write(codec, DAC33_LINEL_TO_LLO_VOL, dac33_read_reg_cache(codec, DAC33_LINEL_TO_LLO_VOL)); dac33_write(codec, DAC33_LINER_TO_RLO_VOL, dac33_read_reg_cache(codec, DAC33_LINER_TO_RLO_VOL)); dac33_write(codec, DAC33_OUT_AMP_CTRL, dac33_read_reg_cache(codec, DAC33_OUT_AMP_CTRL)); dac33_write(codec, DAC33_LDAC_PWR_CTRL, dac33_read_reg_cache(codec, DAC33_LDAC_PWR_CTRL)); dac33_write(codec, DAC33_RDAC_PWR_CTRL, dac33_read_reg_cache(codec, DAC33_RDAC_PWR_CTRL)); } static inline int dac33_read_id(struct snd_soc_codec *codec) { int i, ret = 0; u8 reg; for (i = 0; i < 3; i++) { ret = dac33_read(codec, DAC33_DEVICE_ID_MSB + i, &reg); if (ret < 0) break; } return ret; } static inline void dac33_soft_power(struct snd_soc_codec *codec, int power) { u8 reg; reg = dac33_read_reg_cache(codec, DAC33_PWR_CTRL); if (power) reg |= DAC33_PDNALLB; else reg &= ~(DAC33_PDNALLB | DAC33_OSCPDNB | DAC33_DACRPDNB | DAC33_DACLPDNB); dac33_write(codec, DAC33_PWR_CTRL, reg); } static inline void dac33_disable_digital(struct snd_soc_codec *codec) { u8 reg; /* Stop the DAI clock */ reg = dac33_read_reg_cache(codec, DAC33_SER_AUDIOIF_CTRL_B); reg &= ~DAC33_BCLKON; dac33_write(codec, DAC33_SER_AUDIOIF_CTRL_B, reg); /* Power down the Oscillator, and DACs */ reg = dac33_read_reg_cache(codec, DAC33_PWR_CTRL); reg &= ~(DAC33_OSCPDNB | DAC33_DACRPDNB | DAC33_DACLPDNB); dac33_write(codec, DAC33_PWR_CTRL, reg); } static int dac33_hard_power(struct snd_soc_codec *codec, int power) { struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); int ret = 0; mutex_lock(&dac33->mutex); /* Safety check */ if (unlikely(power == dac33->chip_power)) { dev_dbg(codec->dev, "Trying to set the same power state: %s\n", power ? "ON" : "OFF"); goto exit; } if (power) { ret = regulator_bulk_enable(ARRAY_SIZE(dac33->supplies), dac33->supplies); if (ret != 0) { dev_err(codec->dev, "Failed to enable supplies: %d\n", ret); goto exit; } if (dac33->power_gpio >= 0) gpio_set_value(dac33->power_gpio, 1); dac33->chip_power = 1; } else { dac33_soft_power(codec, 0); if (dac33->power_gpio >= 0) gpio_set_value(dac33->power_gpio, 0); ret = regulator_bulk_disable(ARRAY_SIZE(dac33->supplies), dac33->supplies); if (ret != 0) { dev_err(codec->dev, "Failed to disable supplies: %d\n", ret); goto exit; } dac33->chip_power = 0; } exit: mutex_unlock(&dac33->mutex); return ret; } static int dac33_playback_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(w->codec); switch (event) { case SND_SOC_DAPM_PRE_PMU: if (likely(dac33->substream)) { dac33_calculate_times(dac33->substream); dac33_prepare_chip(dac33->substream); } break; case SND_SOC_DAPM_POST_PMD: dac33_disable_digital(w->codec); break; } return 0; } static int dac33_get_fifo_mode(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); ucontrol->value.integer.value[0] = dac33->fifo_mode; return 0; } static int dac33_set_fifo_mode(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); int ret = 0; if (dac33->fifo_mode == ucontrol->value.integer.value[0]) return 0; /* Do not allow changes while stream is running*/ if (codec->active) return -EPERM; if (ucontrol->value.integer.value[0] < 0 || ucontrol->value.integer.value[0] >= DAC33_FIFO_LAST_MODE) ret = -EINVAL; else dac33->fifo_mode = ucontrol->value.integer.value[0]; return ret; } /* Codec operation modes */ static const char *dac33_fifo_mode_texts[] = { "Bypass", "Mode 1", "Mode 7" }; static const struct soc_enum dac33_fifo_mode_enum = SOC_ENUM_SINGLE_EXT(ARRAY_SIZE(dac33_fifo_mode_texts), dac33_fifo_mode_texts); /* L/R Line Output Gain */ static const char *lr_lineout_gain_texts[] = { "Line -12dB DAC 0dB", "Line -6dB DAC 6dB", "Line 0dB DAC 12dB", "Line 6dB DAC 18dB", }; static const struct soc_enum l_lineout_gain_enum = SOC_ENUM_SINGLE(DAC33_LDAC_PWR_CTRL, 0, ARRAY_SIZE(lr_lineout_gain_texts), lr_lineout_gain_texts); static const struct soc_enum r_lineout_gain_enum = SOC_ENUM_SINGLE(DAC33_RDAC_PWR_CTRL, 0, ARRAY_SIZE(lr_lineout_gain_texts), lr_lineout_gain_texts); /* * DACL/R digital volume control: * from 0 dB to -63.5 in 0.5 dB steps * Need to be inverted later on: * 0x00 == 0 dB * 0x7f == -63.5 dB */ static DECLARE_TLV_DB_SCALE(dac_digivol_tlv, -6350, 50, 0); static const struct snd_kcontrol_new dac33_snd_controls[] = { SOC_DOUBLE_R_TLV("DAC Digital Playback Volume", DAC33_LDAC_DIG_VOL_CTRL, DAC33_RDAC_DIG_VOL_CTRL, 0, 0x7f, 1, dac_digivol_tlv), SOC_DOUBLE_R("DAC Digital Playback Switch", DAC33_LDAC_DIG_VOL_CTRL, DAC33_RDAC_DIG_VOL_CTRL, 7, 1, 1), SOC_DOUBLE_R("Line to Line Out Volume", DAC33_LINEL_TO_LLO_VOL, DAC33_LINER_TO_RLO_VOL, 0, 127, 1), SOC_ENUM("Left Line Output Gain", l_lineout_gain_enum), SOC_ENUM("Right Line Output Gain", r_lineout_gain_enum), }; static const struct snd_kcontrol_new dac33_mode_snd_controls[] = { SOC_ENUM_EXT("FIFO Mode", dac33_fifo_mode_enum, dac33_get_fifo_mode, dac33_set_fifo_mode), }; /* Analog bypass */ static const struct snd_kcontrol_new dac33_dapm_abypassl_control = SOC_DAPM_SINGLE("Switch", DAC33_LINEL_TO_LLO_VOL, 7, 1, 1); static const struct snd_kcontrol_new dac33_dapm_abypassr_control = SOC_DAPM_SINGLE("Switch", DAC33_LINER_TO_RLO_VOL, 7, 1, 1); /* LOP L/R invert selection */ static const char *dac33_lr_lom_texts[] = {"DAC", "LOP"}; static const struct soc_enum dac33_left_lom_enum = SOC_ENUM_SINGLE(DAC33_OUT_AMP_CTRL, 3, ARRAY_SIZE(dac33_lr_lom_texts), dac33_lr_lom_texts); static const struct snd_kcontrol_new dac33_dapm_left_lom_control = SOC_DAPM_ENUM("Route", dac33_left_lom_enum); static const struct soc_enum dac33_right_lom_enum = SOC_ENUM_SINGLE(DAC33_OUT_AMP_CTRL, 2, ARRAY_SIZE(dac33_lr_lom_texts), dac33_lr_lom_texts); static const struct snd_kcontrol_new dac33_dapm_right_lom_control = SOC_DAPM_ENUM("Route", dac33_right_lom_enum); static const struct snd_soc_dapm_widget dac33_dapm_widgets[] = { SND_SOC_DAPM_OUTPUT("LEFT_LO"), SND_SOC_DAPM_OUTPUT("RIGHT_LO"), SND_SOC_DAPM_INPUT("LINEL"), SND_SOC_DAPM_INPUT("LINER"), SND_SOC_DAPM_DAC("DACL", "Left Playback", SND_SOC_NOPM, 0, 0), SND_SOC_DAPM_DAC("DACR", "Right Playback", SND_SOC_NOPM, 0, 0), /* Analog bypass */ SND_SOC_DAPM_SWITCH("Analog Left Bypass", SND_SOC_NOPM, 0, 0, &dac33_dapm_abypassl_control), SND_SOC_DAPM_SWITCH("Analog Right Bypass", SND_SOC_NOPM, 0, 0, &dac33_dapm_abypassr_control), SND_SOC_DAPM_MUX("Left LOM Inverted From", SND_SOC_NOPM, 0, 0, &dac33_dapm_left_lom_control), SND_SOC_DAPM_MUX("Right LOM Inverted From", SND_SOC_NOPM, 0, 0, &dac33_dapm_right_lom_control), /* * For DAPM path, when only the anlog bypass path is enabled, and the * LOP inverted from the corresponding DAC side. * This is needed, so we can attach the DAC power supply in this case. */ SND_SOC_DAPM_PGA("Left Bypass PGA", SND_SOC_NOPM, 0, 0, NULL, 0), SND_SOC_DAPM_PGA("Right Bypass PGA", SND_SOC_NOPM, 0, 0, NULL, 0), SND_SOC_DAPM_REG(snd_soc_dapm_mixer, "Output Left Amplifier", DAC33_OUT_AMP_PWR_CTRL, 6, 3, 3, 0), SND_SOC_DAPM_REG(snd_soc_dapm_mixer, "Output Right Amplifier", DAC33_OUT_AMP_PWR_CTRL, 4, 3, 3, 0), SND_SOC_DAPM_SUPPLY("Left DAC Power", DAC33_LDAC_PWR_CTRL, 2, 0, NULL, 0), SND_SOC_DAPM_SUPPLY("Right DAC Power", DAC33_RDAC_PWR_CTRL, 2, 0, NULL, 0), SND_SOC_DAPM_SUPPLY("Codec Power", DAC33_PWR_CTRL, 4, 0, NULL, 0), SND_SOC_DAPM_PRE("Pre Playback", dac33_playback_event), SND_SOC_DAPM_POST("Post Playback", dac33_playback_event), }; static const struct snd_soc_dapm_route audio_map[] = { /* Analog bypass */ {"Analog Left Bypass", "Switch", "LINEL"}, {"Analog Right Bypass", "Switch", "LINER"}, {"Output Left Amplifier", NULL, "DACL"}, {"Output Right Amplifier", NULL, "DACR"}, {"Left Bypass PGA", NULL, "Analog Left Bypass"}, {"Right Bypass PGA", NULL, "Analog Right Bypass"}, {"Left LOM Inverted From", "DAC", "Left Bypass PGA"}, {"Right LOM Inverted From", "DAC", "Right Bypass PGA"}, {"Left LOM Inverted From", "LOP", "Analog Left Bypass"}, {"Right LOM Inverted From", "LOP", "Analog Right Bypass"}, {"Output Left Amplifier", NULL, "Left LOM Inverted From"}, {"Output Right Amplifier", NULL, "Right LOM Inverted From"}, {"DACL", NULL, "Left DAC Power"}, {"DACR", NULL, "Right DAC Power"}, {"Left Bypass PGA", NULL, "Left DAC Power"}, {"Right Bypass PGA", NULL, "Right DAC Power"}, /* output */ {"LEFT_LO", NULL, "Output Left Amplifier"}, {"RIGHT_LO", NULL, "Output Right Amplifier"}, {"LEFT_LO", NULL, "Codec Power"}, {"RIGHT_LO", NULL, "Codec Power"}, }; static int dac33_add_widgets(struct snd_soc_codec *codec) { struct snd_soc_dapm_context *dapm = &codec->dapm; snd_soc_dapm_new_controls(dapm, dac33_dapm_widgets, ARRAY_SIZE(dac33_dapm_widgets)); /* set up audio path interconnects */ snd_soc_dapm_add_routes(dapm, audio_map, ARRAY_SIZE(audio_map)); return 0; } static int dac33_set_bias_level(struct snd_soc_codec *codec, enum snd_soc_bias_level level) { int ret; switch (level) { case SND_SOC_BIAS_ON: break; case SND_SOC_BIAS_PREPARE: break; case SND_SOC_BIAS_STANDBY: if (codec->dapm.bias_level == SND_SOC_BIAS_OFF) { /* Coming from OFF, switch on the codec */ ret = dac33_hard_power(codec, 1); if (ret != 0) return ret; dac33_init_chip(codec); } break; case SND_SOC_BIAS_OFF: /* Do not power off, when the codec is already off */ if (codec->dapm.bias_level == SND_SOC_BIAS_OFF) return 0; ret = dac33_hard_power(codec, 0); if (ret != 0) return ret; break; } codec->dapm.bias_level = level; return 0; } static inline void dac33_prefill_handler(struct tlv320dac33_priv *dac33) { struct snd_soc_codec *codec = dac33->codec; unsigned int delay; unsigned long flags; switch (dac33->fifo_mode) { case DAC33_FIFO_MODE1: dac33_write16(codec, DAC33_NSAMPLE_MSB, DAC33_THRREG(dac33->nsample)); /* Take the timestamps */ spin_lock_irqsave(&dac33->lock, flags); dac33->t_stamp2 = ktime_to_us(ktime_get()); dac33->t_stamp1 = dac33->t_stamp2; spin_unlock_irqrestore(&dac33->lock, flags); dac33_write16(codec, DAC33_PREFILL_MSB, DAC33_THRREG(dac33->alarm_threshold)); /* Enable Alarm Threshold IRQ with a delay */ delay = SAMPLES_TO_US(dac33->burst_rate, dac33->alarm_threshold) + 1000; usleep_range(delay, delay + 500); dac33_write(codec, DAC33_FIFO_IRQ_MASK, DAC33_MAT); break; case DAC33_FIFO_MODE7: /* Take the timestamp */ spin_lock_irqsave(&dac33->lock, flags); dac33->t_stamp1 = ktime_to_us(ktime_get()); /* Move back the timestamp with drain time */ dac33->t_stamp1 -= dac33->mode7_us_to_lthr; spin_unlock_irqrestore(&dac33->lock, flags); dac33_write16(codec, DAC33_PREFILL_MSB, DAC33_THRREG(DAC33_MODE7_MARGIN)); /* Enable Upper Threshold IRQ */ dac33_write(codec, DAC33_FIFO_IRQ_MASK, DAC33_MUT); break; default: dev_warn(codec->dev, "Unhandled FIFO mode: %d\n", dac33->fifo_mode); break; } } static inline void dac33_playback_handler(struct tlv320dac33_priv *dac33) { struct snd_soc_codec *codec = dac33->codec; unsigned long flags; switch (dac33->fifo_mode) { case DAC33_FIFO_MODE1: /* Take the timestamp */ spin_lock_irqsave(&dac33->lock, flags); dac33->t_stamp2 = ktime_to_us(ktime_get()); spin_unlock_irqrestore(&dac33->lock, flags); dac33_write16(codec, DAC33_NSAMPLE_MSB, DAC33_THRREG(dac33->nsample)); break; case DAC33_FIFO_MODE7: /* At the moment we are not using interrupts in mode7 */ break; default: dev_warn(codec->dev, "Unhandled FIFO mode: %d\n", dac33->fifo_mode); break; } } static void dac33_work(struct work_struct *work) { struct snd_soc_codec *codec; struct tlv320dac33_priv *dac33; u8 reg; dac33 = container_of(work, struct tlv320dac33_priv, work); codec = dac33->codec; mutex_lock(&dac33->mutex); switch (dac33->state) { case DAC33_PREFILL: dac33->state = DAC33_PLAYBACK; dac33_prefill_handler(dac33); break; case DAC33_PLAYBACK: dac33_playback_handler(dac33); break; case DAC33_IDLE: break; case DAC33_FLUSH: dac33->state = DAC33_IDLE; /* Mask all interrupts from dac33 */ dac33_write(codec, DAC33_FIFO_IRQ_MASK, 0); /* flush fifo */ reg = dac33_read_reg_cache(codec, DAC33_FIFO_CTRL_A); reg |= DAC33_FIFOFLUSH; dac33_write(codec, DAC33_FIFO_CTRL_A, reg); break; } mutex_unlock(&dac33->mutex); } static irqreturn_t dac33_interrupt_handler(int irq, void *dev) { struct snd_soc_codec *codec = dev; struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); unsigned long flags; spin_lock_irqsave(&dac33->lock, flags); dac33->t_stamp1 = ktime_to_us(ktime_get()); spin_unlock_irqrestore(&dac33->lock, flags); /* Do not schedule the workqueue in Mode7 */ if (dac33->fifo_mode != DAC33_FIFO_MODE7) queue_work(dac33->dac33_wq, &dac33->work); return IRQ_HANDLED; } static void dac33_oscwait(struct snd_soc_codec *codec) { int timeout = 60; u8 reg; do { usleep_range(1000, 2000); dac33_read(codec, DAC33_INT_OSC_STATUS, &reg); } while (((reg & 0x03) != DAC33_OSCSTATUS_NORMAL) && timeout--); if ((reg & 0x03) != DAC33_OSCSTATUS_NORMAL) dev_err(codec->dev, "internal oscillator calibration failed\n"); } static int dac33_startup(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_codec *codec = rtd->codec; struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); /* Stream started, save the substream pointer */ dac33->substream = substream; snd_pcm_hw_constraint_msbits(substream->runtime, 0, 32, 24); return 0; } static void dac33_shutdown(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_codec *codec = rtd->codec; struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); dac33->substream = NULL; } #define CALC_BURST_RATE(bclkdiv, bclk_per_sample) \ (BURST_BASEFREQ_HZ / bclkdiv / bclk_per_sample) static int dac33_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_codec *codec = rtd->codec; struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); /* Check parameters for validity */ switch (params_rate(params)) { case 44100: case 48000: break; default: dev_err(codec->dev, "unsupported rate %d\n", params_rate(params)); return -EINVAL; } switch (params_format(params)) { case SNDRV_PCM_FORMAT_S16_LE: dac33->fifo_size = DAC33_FIFO_SIZE_16BIT; dac33->burst_rate = CALC_BURST_RATE(dac33->burst_bclkdiv, 32); break; case SNDRV_PCM_FORMAT_S32_LE: dac33->fifo_size = DAC33_FIFO_SIZE_24BIT; dac33->burst_rate = CALC_BURST_RATE(dac33->burst_bclkdiv, 64); break; default: dev_err(codec->dev, "unsupported format %d\n", params_format(params)); return -EINVAL; } return 0; } #define CALC_OSCSET(rate, refclk) ( \ ((((rate * 10000) / refclk) * 4096) + 7000) / 10000) #define CALC_RATIOSET(rate, refclk) ( \ ((((refclk * 100000) / rate) * 16384) + 50000) / 100000) /* * tlv320dac33 is strict on the sequence of the register writes, if the register * writes happens in different order, than dac33 might end up in unknown state. * Use the known, working sequence of register writes to initialize the dac33. */ static int dac33_prepare_chip(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_codec *codec = rtd->codec; struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); unsigned int oscset, ratioset, pwr_ctrl, reg_tmp; u8 aictrl_a, aictrl_b, fifoctrl_a; switch (substream->runtime->rate) { case 44100: case 48000: oscset = CALC_OSCSET(substream->runtime->rate, dac33->refclk); ratioset = CALC_RATIOSET(substream->runtime->rate, dac33->refclk); break; default: dev_err(codec->dev, "unsupported rate %d\n", substream->runtime->rate); return -EINVAL; } aictrl_a = dac33_read_reg_cache(codec, DAC33_SER_AUDIOIF_CTRL_A); aictrl_a &= ~(DAC33_NCYCL_MASK | DAC33_WLEN_MASK); /* Read FIFO control A, and clear FIFO flush bit */ fifoctrl_a = dac33_read_reg_cache(codec, DAC33_FIFO_CTRL_A); fifoctrl_a &= ~DAC33_FIFOFLUSH; fifoctrl_a &= ~DAC33_WIDTH; switch (substream->runtime->format) { case SNDRV_PCM_FORMAT_S16_LE: aictrl_a |= (DAC33_NCYCL_16 | DAC33_WLEN_16); fifoctrl_a |= DAC33_WIDTH; break; case SNDRV_PCM_FORMAT_S32_LE: aictrl_a |= (DAC33_NCYCL_32 | DAC33_WLEN_24); break; default: dev_err(codec->dev, "unsupported format %d\n", substream->runtime->format); return -EINVAL; } mutex_lock(&dac33->mutex); if (!dac33->chip_power) { /* * Chip is not powered yet. * Do the init in the dac33_set_bias_level later. */ mutex_unlock(&dac33->mutex); return 0; } dac33_soft_power(codec, 0); dac33_soft_power(codec, 1); reg_tmp = dac33_read_reg_cache(codec, DAC33_INT_OSC_CTRL); dac33_write(codec, DAC33_INT_OSC_CTRL, reg_tmp); /* Write registers 0x08 and 0x09 (MSB, LSB) */ dac33_write16(codec, DAC33_INT_OSC_FREQ_RAT_A, oscset); /* OSC calibration time */ dac33_write(codec, DAC33_CALIB_TIME, 96); /* adjustment treshold & step */ dac33_write(codec, DAC33_INT_OSC_CTRL_B, DAC33_ADJTHRSHLD(2) | DAC33_ADJSTEP(1)); /* div=4 / gain=1 / div */ dac33_write(codec, DAC33_INT_OSC_CTRL_C, DAC33_REFDIV(4)); pwr_ctrl = dac33_read_reg_cache(codec, DAC33_PWR_CTRL); pwr_ctrl |= DAC33_OSCPDNB | DAC33_DACRPDNB | DAC33_DACLPDNB; dac33_write(codec, DAC33_PWR_CTRL, pwr_ctrl); dac33_oscwait(codec); if (dac33->fifo_mode) { /* Generic for all FIFO modes */ /* 50-51 : ASRC Control registers */ dac33_write(codec, DAC33_ASRC_CTRL_A, DAC33_SRCLKDIV(1)); dac33_write(codec, DAC33_ASRC_CTRL_B, 1); /* ??? */ /* Write registers 0x34 and 0x35 (MSB, LSB) */ dac33_write16(codec, DAC33_SRC_REF_CLK_RATIO_A, ratioset); /* Set interrupts to high active */ dac33_write(codec, DAC33_INTP_CTRL_A, DAC33_INTPM_AHIGH); } else { /* FIFO bypass mode */ /* 50-51 : ASRC Control registers */ dac33_write(codec, DAC33_ASRC_CTRL_A, DAC33_SRCBYP); dac33_write(codec, DAC33_ASRC_CTRL_B, 0); /* ??? */ } /* Interrupt behaviour configuration */ switch (dac33->fifo_mode) { case DAC33_FIFO_MODE1: dac33_write(codec, DAC33_FIFO_IRQ_MODE_B, DAC33_ATM(DAC33_FIFO_IRQ_MODE_LEVEL)); break; case DAC33_FIFO_MODE7: dac33_write(codec, DAC33_FIFO_IRQ_MODE_A, DAC33_UTM(DAC33_FIFO_IRQ_MODE_LEVEL)); break; default: /* in FIFO bypass mode, the interrupts are not used */ break; } aictrl_b = dac33_read_reg_cache(codec, DAC33_SER_AUDIOIF_CTRL_B); switch (dac33->fifo_mode) { case DAC33_FIFO_MODE1: /* * For mode1: * Disable the FIFO bypass (Enable the use of FIFO) * Select nSample mode * BCLK is only running when data is needed by DAC33 */ fifoctrl_a &= ~DAC33_FBYPAS; fifoctrl_a &= ~DAC33_FAUTO; if (dac33->keep_bclk) aictrl_b |= DAC33_BCLKON; else aictrl_b &= ~DAC33_BCLKON; break; case DAC33_FIFO_MODE7: /* * For mode1: * Disable the FIFO bypass (Enable the use of FIFO) * Select Threshold mode * BCLK is only running when data is needed by DAC33 */ fifoctrl_a &= ~DAC33_FBYPAS; fifoctrl_a |= DAC33_FAUTO; if (dac33->keep_bclk) aictrl_b |= DAC33_BCLKON; else aictrl_b &= ~DAC33_BCLKON; break; default: /* * For FIFO bypass mode: * Enable the FIFO bypass (Disable the FIFO use) * Set the BCLK as continuous */ fifoctrl_a |= DAC33_FBYPAS; aictrl_b |= DAC33_BCLKON; break; } dac33_write(codec, DAC33_FIFO_CTRL_A, fifoctrl_a); dac33_write(codec, DAC33_SER_AUDIOIF_CTRL_A, aictrl_a); dac33_write(codec, DAC33_SER_AUDIOIF_CTRL_B, aictrl_b); /* * BCLK divide ratio * 0: 1.5 * 1: 1 * 2: 2 * ... * 254: 254 * 255: 255 */ if (dac33->fifo_mode) dac33_write(codec, DAC33_SER_AUDIOIF_CTRL_C, dac33->burst_bclkdiv); else if (substream->runtime->format == SNDRV_PCM_FORMAT_S16_LE) dac33_write(codec, DAC33_SER_AUDIOIF_CTRL_C, 32); else dac33_write(codec, DAC33_SER_AUDIOIF_CTRL_C, 16); switch (dac33->fifo_mode) { case DAC33_FIFO_MODE1: dac33_write16(codec, DAC33_ATHR_MSB, DAC33_THRREG(dac33->alarm_threshold)); break; case DAC33_FIFO_MODE7: /* * Configure the threshold levels, and leave 10 sample space * at the bottom, and also at the top of the FIFO */ dac33_write16(codec, DAC33_UTHR_MSB, DAC33_THRREG(dac33->uthr)); dac33_write16(codec, DAC33_LTHR_MSB, DAC33_THRREG(DAC33_MODE7_MARGIN)); break; default: break; } mutex_unlock(&dac33->mutex); return 0; } static void dac33_calculate_times(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_codec *codec = rtd->codec; struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); unsigned int period_size = substream->runtime->period_size; unsigned int rate = substream->runtime->rate; unsigned int nsample_limit; /* In bypass mode we don't need to calculate */ if (!dac33->fifo_mode) return; switch (dac33->fifo_mode) { case DAC33_FIFO_MODE1: /* Number of samples under i2c latency */ dac33->alarm_threshold = US_TO_SAMPLES(rate, dac33->mode1_latency); nsample_limit = dac33->fifo_size - dac33->alarm_threshold; if (period_size <= dac33->alarm_threshold) /* * Configure nSamaple to number of periods, * which covers the latency requironment. */ dac33->nsample = period_size * ((dac33->alarm_threshold / period_size) + (dac33->alarm_threshold % period_size ? 1 : 0)); else if (period_size > nsample_limit) dac33->nsample = nsample_limit; else dac33->nsample = period_size; dac33->mode1_us_burst = SAMPLES_TO_US(dac33->burst_rate, dac33->nsample); dac33->t_stamp1 = 0; dac33->t_stamp2 = 0; break; case DAC33_FIFO_MODE7: dac33->uthr = UTHR_FROM_PERIOD_SIZE(period_size, rate, dac33->burst_rate) + 9; if (dac33->uthr > (dac33->fifo_size - DAC33_MODE7_MARGIN)) dac33->uthr = dac33->fifo_size - DAC33_MODE7_MARGIN; if (dac33->uthr < (DAC33_MODE7_MARGIN + 10)) dac33->uthr = (DAC33_MODE7_MARGIN + 10); dac33->mode7_us_to_lthr = SAMPLES_TO_US(substream->runtime->rate, dac33->uthr - DAC33_MODE7_MARGIN + 1); dac33->t_stamp1 = 0; break; default: break; } } static int dac33_pcm_trigger(struct snd_pcm_substream *substream, int cmd, struct snd_soc_dai *dai) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_codec *codec = rtd->codec; struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); int ret = 0; switch (cmd) { case SNDRV_PCM_TRIGGER_START: case SNDRV_PCM_TRIGGER_RESUME: case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: if (dac33->fifo_mode) { dac33->state = DAC33_PREFILL; queue_work(dac33->dac33_wq, &dac33->work); } break; case SNDRV_PCM_TRIGGER_STOP: case SNDRV_PCM_TRIGGER_SUSPEND: case SNDRV_PCM_TRIGGER_PAUSE_PUSH: if (dac33->fifo_mode) { dac33->state = DAC33_FLUSH; queue_work(dac33->dac33_wq, &dac33->work); } break; default: ret = -EINVAL; } return ret; } static snd_pcm_sframes_t dac33_dai_delay( struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_codec *codec = rtd->codec; struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); unsigned long long t0, t1, t_now; unsigned int time_delta, uthr; int samples_out, samples_in, samples; snd_pcm_sframes_t delay = 0; unsigned long flags; switch (dac33->fifo_mode) { case DAC33_FIFO_BYPASS: break; case DAC33_FIFO_MODE1: spin_lock_irqsave(&dac33->lock, flags); t0 = dac33->t_stamp1; t1 = dac33->t_stamp2; spin_unlock_irqrestore(&dac33->lock, flags); t_now = ktime_to_us(ktime_get()); /* We have not started to fill the FIFO yet, delay is 0 */ if (!t1) goto out; if (t0 > t1) { /* * Phase 1: * After Alarm threshold, and before nSample write */ time_delta = t_now - t0; samples_out = time_delta ? US_TO_SAMPLES( substream->runtime->rate, time_delta) : 0; if (likely(dac33->alarm_threshold > samples_out)) delay = dac33->alarm_threshold - samples_out; else delay = 0; } else if ((t_now - t1) <= dac33->mode1_us_burst) { /* * Phase 2: * After nSample write (during burst operation) */ time_delta = t_now - t0; samples_out = time_delta ? US_TO_SAMPLES( substream->runtime->rate, time_delta) : 0; time_delta = t_now - t1; samples_in = time_delta ? US_TO_SAMPLES( dac33->burst_rate, time_delta) : 0; samples = dac33->alarm_threshold; samples += (samples_in - samples_out); if (likely(samples > 0)) delay = samples; else delay = 0; } else { /* * Phase 3: * After burst operation, before next alarm threshold */ time_delta = t_now - t0; samples_out = time_delta ? US_TO_SAMPLES( substream->runtime->rate, time_delta) : 0; samples_in = dac33->nsample; samples = dac33->alarm_threshold; samples += (samples_in - samples_out); if (likely(samples > 0)) delay = samples > dac33->fifo_size ? dac33->fifo_size : samples; else delay = 0; } break; case DAC33_FIFO_MODE7: spin_lock_irqsave(&dac33->lock, flags); t0 = dac33->t_stamp1; uthr = dac33->uthr; spin_unlock_irqrestore(&dac33->lock, flags); t_now = ktime_to_us(ktime_get()); /* We have not started to fill the FIFO yet, delay is 0 */ if (!t0) goto out; if (t_now <= t0) { /* * Either the timestamps are messed or equal. Report * maximum delay */ delay = uthr; goto out; } time_delta = t_now - t0; if (time_delta <= dac33->mode7_us_to_lthr) { /* * Phase 1: * After burst (draining phase) */ samples_out = US_TO_SAMPLES( substream->runtime->rate, time_delta); if (likely(uthr > samples_out)) delay = uthr - samples_out; else delay = 0; } else { /* * Phase 2: * During burst operation */ time_delta = time_delta - dac33->mode7_us_to_lthr; samples_out = US_TO_SAMPLES( substream->runtime->rate, time_delta); samples_in = US_TO_SAMPLES( dac33->burst_rate, time_delta); delay = DAC33_MODE7_MARGIN + samples_in - samples_out; if (unlikely(delay > uthr)) delay = uthr; } break; default: dev_warn(codec->dev, "Unhandled FIFO mode: %d\n", dac33->fifo_mode); break; } out: return delay; } static int dac33_set_dai_sysclk(struct snd_soc_dai *codec_dai, int clk_id, unsigned int freq, int dir) { struct snd_soc_codec *codec = codec_dai->codec; struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); u8 ioc_reg, asrcb_reg; ioc_reg = dac33_read_reg_cache(codec, DAC33_INT_OSC_CTRL); asrcb_reg = dac33_read_reg_cache(codec, DAC33_ASRC_CTRL_B); switch (clk_id) { case TLV320DAC33_MCLK: ioc_reg |= DAC33_REFSEL; asrcb_reg |= DAC33_SRCREFSEL; break; case TLV320DAC33_SLEEPCLK: ioc_reg &= ~DAC33_REFSEL; asrcb_reg &= ~DAC33_SRCREFSEL; break; default: dev_err(codec->dev, "Invalid clock ID (%d)\n", clk_id); break; } dac33->refclk = freq; dac33_write_reg_cache(codec, DAC33_INT_OSC_CTRL, ioc_reg); dac33_write_reg_cache(codec, DAC33_ASRC_CTRL_B, asrcb_reg); return 0; } static int dac33_set_dai_fmt(struct snd_soc_dai *codec_dai, unsigned int fmt) { struct snd_soc_codec *codec = codec_dai->codec; struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); u8 aictrl_a, aictrl_b; aictrl_a = dac33_read_reg_cache(codec, DAC33_SER_AUDIOIF_CTRL_A); aictrl_b = dac33_read_reg_cache(codec, DAC33_SER_AUDIOIF_CTRL_B); /* set master/slave audio interface */ switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) { case SND_SOC_DAIFMT_CBM_CFM: /* Codec Master */ aictrl_a |= (DAC33_MSBCLK | DAC33_MSWCLK); break; case SND_SOC_DAIFMT_CBS_CFS: /* Codec Slave */ if (dac33->fifo_mode) { dev_err(codec->dev, "FIFO mode requires master mode\n"); return -EINVAL; } else aictrl_a &= ~(DAC33_MSBCLK | DAC33_MSWCLK); break; default: return -EINVAL; } aictrl_a &= ~DAC33_AFMT_MASK; switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { case SND_SOC_DAIFMT_I2S: aictrl_a |= DAC33_AFMT_I2S; break; case SND_SOC_DAIFMT_DSP_A: aictrl_a |= DAC33_AFMT_DSP; aictrl_b &= ~DAC33_DATA_DELAY_MASK; aictrl_b |= DAC33_DATA_DELAY(0); break; case SND_SOC_DAIFMT_RIGHT_J: aictrl_a |= DAC33_AFMT_RIGHT_J; break; case SND_SOC_DAIFMT_LEFT_J: aictrl_a |= DAC33_AFMT_LEFT_J; break; default: dev_err(codec->dev, "Unsupported format (%u)\n", fmt & SND_SOC_DAIFMT_FORMAT_MASK); return -EINVAL; } dac33_write_reg_cache(codec, DAC33_SER_AUDIOIF_CTRL_A, aictrl_a); dac33_write_reg_cache(codec, DAC33_SER_AUDIOIF_CTRL_B, aictrl_b); return 0; } static int dac33_soc_probe(struct snd_soc_codec *codec) { struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); int ret = 0; codec->control_data = dac33->control_data; codec->hw_write = (hw_write_t) i2c_master_send; codec->dapm.idle_bias_off = 1; dac33->codec = codec; /* Read the tlv320dac33 ID registers */ ret = dac33_hard_power(codec, 1); if (ret != 0) { dev_err(codec->dev, "Failed to power up codec: %d\n", ret); goto err_power; } ret = dac33_read_id(codec); dac33_hard_power(codec, 0); if (ret < 0) { dev_err(codec->dev, "Failed to read chip ID: %d\n", ret); ret = -ENODEV; goto err_power; } /* Check if the IRQ number is valid and request it */ if (dac33->irq >= 0) { ret = request_irq(dac33->irq, dac33_interrupt_handler, IRQF_TRIGGER_RISING | IRQF_DISABLED, codec->name, codec); if (ret < 0) { dev_err(codec->dev, "Could not request IRQ%d (%d)\n", dac33->irq, ret); dac33->irq = -1; } if (dac33->irq != -1) { /* Setup work queue */ dac33->dac33_wq = create_singlethread_workqueue("tlv320dac33"); if (dac33->dac33_wq == NULL) { free_irq(dac33->irq, codec); return -ENOMEM; } INIT_WORK(&dac33->work, dac33_work); } } snd_soc_add_controls(codec, dac33_snd_controls, ARRAY_SIZE(dac33_snd_controls)); /* Only add the FIFO controls, if we have valid IRQ number */ if (dac33->irq >= 0) snd_soc_add_controls(codec, dac33_mode_snd_controls, ARRAY_SIZE(dac33_mode_snd_controls)); dac33_add_widgets(codec); err_power: return ret; } static int dac33_soc_remove(struct snd_soc_codec *codec) { struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); dac33_set_bias_level(codec, SND_SOC_BIAS_OFF); if (dac33->irq >= 0) { free_irq(dac33->irq, dac33->codec); destroy_workqueue(dac33->dac33_wq); } return 0; } static int dac33_soc_suspend(struct snd_soc_codec *codec, pm_message_t state) { dac33_set_bias_level(codec, SND_SOC_BIAS_OFF); return 0; } static int dac33_soc_resume(struct snd_soc_codec *codec) { dac33_set_bias_level(codec, SND_SOC_BIAS_STANDBY); return 0; } static struct snd_soc_codec_driver soc_codec_dev_tlv320dac33 = { .read = dac33_read_reg_cache, .write = dac33_write_locked, .set_bias_level = dac33_set_bias_level, .reg_cache_size = ARRAY_SIZE(dac33_reg), .reg_word_size = sizeof(u8), .reg_cache_default = dac33_reg, .probe = dac33_soc_probe, .remove = dac33_soc_remove, .suspend = dac33_soc_suspend, .resume = dac33_soc_resume, }; #define DAC33_RATES (SNDRV_PCM_RATE_44100 | \ SNDRV_PCM_RATE_48000) #define DAC33_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S32_LE) static struct snd_soc_dai_ops dac33_dai_ops = { .startup = dac33_startup, .shutdown = dac33_shutdown, .hw_params = dac33_hw_params, .trigger = dac33_pcm_trigger, .delay = dac33_dai_delay, .set_sysclk = dac33_set_dai_sysclk, .set_fmt = dac33_set_dai_fmt, }; static struct snd_soc_dai_driver dac33_dai = { .name = "tlv320dac33-hifi", .playback = { .stream_name = "Playback", .channels_min = 2, .channels_max = 2, .rates = DAC33_RATES, .formats = DAC33_FORMATS,}, .ops = &dac33_dai_ops, }; static int __devinit dac33_i2c_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct tlv320dac33_platform_data *pdata; struct tlv320dac33_priv *dac33; int ret, i; if (client->dev.platform_data == NULL) { dev_err(&client->dev, "Platform data not set\n"); return -ENODEV; } pdata = client->dev.platform_data; dac33 = kzalloc(sizeof(struct tlv320dac33_priv), GFP_KERNEL); if (dac33 == NULL) return -ENOMEM; dac33->control_data = client; mutex_init(&dac33->mutex); spin_lock_init(&dac33->lock); i2c_set_clientdata(client, dac33); dac33->power_gpio = pdata->power_gpio; dac33->burst_bclkdiv = pdata->burst_bclkdiv; dac33->keep_bclk = pdata->keep_bclk; dac33->mode1_latency = pdata->mode1_latency; if (!dac33->mode1_latency) dac33->mode1_latency = 10000; /* 10ms */ dac33->irq = client->irq; /* Disable FIFO use by default */ dac33->fifo_mode = DAC33_FIFO_BYPASS; /* Check if the reset GPIO number is valid and request it */ if (dac33->power_gpio >= 0) { ret = gpio_request(dac33->power_gpio, "tlv320dac33 reset"); if (ret < 0) { dev_err(&client->dev, "Failed to request reset GPIO (%d)\n", dac33->power_gpio); goto err_gpio; } gpio_direction_output(dac33->power_gpio, 0); } for (i = 0; i < ARRAY_SIZE(dac33->supplies); i++) dac33->supplies[i].supply = dac33_supply_names[i]; ret = regulator_bulk_get(&client->dev, ARRAY_SIZE(dac33->supplies), dac33->supplies); if (ret != 0) { dev_err(&client->dev, "Failed to request supplies: %d\n", ret); goto err_get; } ret = snd_soc_register_codec(&client->dev, &soc_codec_dev_tlv320dac33, &dac33_dai, 1); if (ret < 0) goto err_register; return ret; err_register: regulator_bulk_free(ARRAY_SIZE(dac33->supplies), dac33->supplies); err_get: if (dac33->power_gpio >= 0) gpio_free(dac33->power_gpio); err_gpio: kfree(dac33); return ret; } static int __devexit dac33_i2c_remove(struct i2c_client *client) { struct tlv320dac33_priv *dac33 = i2c_get_clientdata(client); if (unlikely(dac33->chip_power)) dac33_hard_power(dac33->codec, 0); if (dac33->power_gpio >= 0) gpio_free(dac33->power_gpio); regulator_bulk_free(ARRAY_SIZE(dac33->supplies), dac33->supplies); snd_soc_unregister_codec(&client->dev); kfree(dac33); return 0; } static const struct i2c_device_id tlv320dac33_i2c_id[] = { { .name = "tlv320dac33", .driver_data = 0, }, { }, }; MODULE_DEVICE_TABLE(i2c, tlv320dac33_i2c_id); static struct i2c_driver tlv320dac33_i2c_driver = { .driver = { .name = "tlv320dac33-codec", .owner = THIS_MODULE, }, .probe = dac33_i2c_probe, .remove = __devexit_p(dac33_i2c_remove), .id_table = tlv320dac33_i2c_id, }; static int __init dac33_module_init(void) { int r; r = i2c_add_driver(&tlv320dac33_i2c_driver); if (r < 0) { printk(KERN_ERR "DAC33: driver registration failed\n"); return r; } return 0; } module_init(dac33_module_init); static void __exit dac33_module_exit(void) { i2c_del_driver(&tlv320dac33_i2c_driver); } module_exit(dac33_module_exit); MODULE_DESCRIPTION("ASoC TLV320DAC33 codec driver"); MODULE_AUTHOR("Peter Ujfalusi <peter.ujfalusi@ti.com>"); MODULE_LICENSE("GPL");
gpl-2.0
javelinanddart/android_kernel_htc_pyramid
drivers/video/exynos/exynos_mipi_dsi_common.c
4812
23037
/* linux/drivers/video/exynos/exynos_mipi_dsi_common.c * * Samsung SoC MIPI-DSI common driver. * * Copyright (c) 2012 Samsung Electronics Co., Ltd * * InKi Dae, <inki.dae@samsung.com> * Donghwa Lee, <dh09.lee@samsung.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/mutex.h> #include <linux/wait.h> #include <linux/fs.h> #include <linux/mm.h> #include <linux/fb.h> #include <linux/ctype.h> #include <linux/platform_device.h> #include <linux/io.h> #include <linux/memory.h> #include <linux/delay.h> #include <linux/kthread.h> #include <video/mipi_display.h> #include <video/exynos_mipi_dsim.h> #include <mach/map.h> #include "exynos_mipi_dsi_regs.h" #include "exynos_mipi_dsi_lowlevel.h" #include "exynos_mipi_dsi_common.h" #define MIPI_FIFO_TIMEOUT msecs_to_jiffies(250) #define MIPI_RX_FIFO_READ_DONE 0x30800002 #define MIPI_MAX_RX_FIFO 20 #define MHZ (1000 * 1000) #define FIN_HZ (24 * MHZ) #define DFIN_PLL_MIN_HZ (6 * MHZ) #define DFIN_PLL_MAX_HZ (12 * MHZ) #define DFVCO_MIN_HZ (500 * MHZ) #define DFVCO_MAX_HZ (1000 * MHZ) #define TRY_GET_FIFO_TIMEOUT (5000 * 2) #define TRY_FIFO_CLEAR (10) /* MIPI-DSIM status types. */ enum { DSIM_STATE_INIT, /* should be initialized. */ DSIM_STATE_STOP, /* CPU and LCDC are LP mode. */ DSIM_STATE_HSCLKEN, /* HS clock was enabled. */ DSIM_STATE_ULPS }; /* define DSI lane types. */ enum { DSIM_LANE_CLOCK = (1 << 0), DSIM_LANE_DATA0 = (1 << 1), DSIM_LANE_DATA1 = (1 << 2), DSIM_LANE_DATA2 = (1 << 3), DSIM_LANE_DATA3 = (1 << 4) }; static unsigned int dpll_table[15] = { 100, 120, 170, 220, 270, 320, 390, 450, 510, 560, 640, 690, 770, 870, 950 }; irqreturn_t exynos_mipi_dsi_interrupt_handler(int irq, void *dev_id) { unsigned int intsrc = 0; unsigned int intmsk = 0; struct mipi_dsim_device *dsim = NULL; dsim = dev_id; if (!dsim) { dev_dbg(dsim->dev, KERN_ERR "%s:error: wrong parameter\n", __func__); return IRQ_HANDLED; } intsrc = exynos_mipi_dsi_read_interrupt(dsim); intmsk = exynos_mipi_dsi_read_interrupt_mask(dsim); intmsk = ~(intmsk) & intsrc; switch (intmsk) { case INTMSK_RX_DONE: complete(&dsim_rd_comp); dev_dbg(dsim->dev, "MIPI INTMSK_RX_DONE\n"); break; case INTMSK_FIFO_EMPTY: complete(&dsim_wr_comp); dev_dbg(dsim->dev, "MIPI INTMSK_FIFO_EMPTY\n"); break; default: break; } exynos_mipi_dsi_clear_interrupt(dsim, intmsk); return IRQ_HANDLED; } /* * write long packet to mipi dsi slave * @dsim: mipi dsim device structure. * @data0: packet data to send. * @data1: size of packet data */ static void exynos_mipi_dsi_long_data_wr(struct mipi_dsim_device *dsim, const unsigned char *data0, unsigned int data_size) { unsigned int data_cnt = 0, payload = 0; /* in case that data count is more then 4 */ for (data_cnt = 0; data_cnt < data_size; data_cnt += 4) { /* * after sending 4bytes per one time, * send remainder data less then 4. */ if ((data_size - data_cnt) < 4) { if ((data_size - data_cnt) == 3) { payload = data0[data_cnt] | data0[data_cnt + 1] << 8 | data0[data_cnt + 2] << 16; dev_dbg(dsim->dev, "count = 3 payload = %x, %x %x %x\n", payload, data0[data_cnt], data0[data_cnt + 1], data0[data_cnt + 2]); } else if ((data_size - data_cnt) == 2) { payload = data0[data_cnt] | data0[data_cnt + 1] << 8; dev_dbg(dsim->dev, "count = 2 payload = %x, %x %x\n", payload, data0[data_cnt], data0[data_cnt + 1]); } else if ((data_size - data_cnt) == 1) { payload = data0[data_cnt]; } exynos_mipi_dsi_wr_tx_data(dsim, payload); /* send 4bytes per one time. */ } else { payload = data0[data_cnt] | data0[data_cnt + 1] << 8 | data0[data_cnt + 2] << 16 | data0[data_cnt + 3] << 24; dev_dbg(dsim->dev, "count = 4 payload = %x, %x %x %x %x\n", payload, *(u8 *)(data0 + data_cnt), data0[data_cnt + 1], data0[data_cnt + 2], data0[data_cnt + 3]); exynos_mipi_dsi_wr_tx_data(dsim, payload); } } } int exynos_mipi_dsi_wr_data(struct mipi_dsim_device *dsim, unsigned int data_id, const unsigned char *data0, unsigned int data_size) { unsigned int check_rx_ack = 0; if (dsim->state == DSIM_STATE_ULPS) { dev_err(dsim->dev, "state is ULPS.\n"); return -EINVAL; } /* FIXME!!! why does it need this delay? */ msleep(20); mutex_lock(&dsim->lock); switch (data_id) { /* short packet types of packet types for command. */ case MIPI_DSI_GENERIC_SHORT_WRITE_0_PARAM: case MIPI_DSI_GENERIC_SHORT_WRITE_1_PARAM: case MIPI_DSI_GENERIC_SHORT_WRITE_2_PARAM: case MIPI_DSI_DCS_SHORT_WRITE: case MIPI_DSI_DCS_SHORT_WRITE_PARAM: case MIPI_DSI_SET_MAXIMUM_RETURN_PACKET_SIZE: exynos_mipi_dsi_wr_tx_header(dsim, data_id, data0[0], data0[1]); if (check_rx_ack) { /* process response func should be implemented */ mutex_unlock(&dsim->lock); return 0; } else { mutex_unlock(&dsim->lock); return -EINVAL; } /* general command */ case MIPI_DSI_COLOR_MODE_OFF: case MIPI_DSI_COLOR_MODE_ON: case MIPI_DSI_SHUTDOWN_PERIPHERAL: case MIPI_DSI_TURN_ON_PERIPHERAL: exynos_mipi_dsi_wr_tx_header(dsim, data_id, data0[0], data0[1]); if (check_rx_ack) { /* process response func should be implemented. */ mutex_unlock(&dsim->lock); return 0; } else { mutex_unlock(&dsim->lock); return -EINVAL; } /* packet types for video data */ case MIPI_DSI_V_SYNC_START: case MIPI_DSI_V_SYNC_END: case MIPI_DSI_H_SYNC_START: case MIPI_DSI_H_SYNC_END: case MIPI_DSI_END_OF_TRANSMISSION: mutex_unlock(&dsim->lock); return 0; /* long packet type and null packet */ case MIPI_DSI_NULL_PACKET: case MIPI_DSI_BLANKING_PACKET: mutex_unlock(&dsim->lock); return 0; case MIPI_DSI_GENERIC_LONG_WRITE: case MIPI_DSI_DCS_LONG_WRITE: { unsigned int size, payload = 0; INIT_COMPLETION(dsim_wr_comp); size = data_size * 4; /* if data count is less then 4, then send 3bytes data. */ if (data_size < 4) { payload = data0[0] | data0[1] << 8 | data0[2] << 16; exynos_mipi_dsi_wr_tx_data(dsim, payload); dev_dbg(dsim->dev, "count = %d payload = %x,%x %x %x\n", data_size, payload, data0[0], data0[1], data0[2]); /* in case that data count is more then 4 */ } else exynos_mipi_dsi_long_data_wr(dsim, data0, data_size); /* put data into header fifo */ exynos_mipi_dsi_wr_tx_header(dsim, data_id, data_size & 0xff, (data_size & 0xff00) >> 8); if (!wait_for_completion_interruptible_timeout(&dsim_wr_comp, MIPI_FIFO_TIMEOUT)) { dev_warn(dsim->dev, "command write timeout.\n"); mutex_unlock(&dsim->lock); return -EAGAIN; } if (check_rx_ack) { /* process response func should be implemented. */ mutex_unlock(&dsim->lock); return 0; } else { mutex_unlock(&dsim->lock); return -EINVAL; } } /* packet typo for video data */ case MIPI_DSI_PACKED_PIXEL_STREAM_16: case MIPI_DSI_PACKED_PIXEL_STREAM_18: case MIPI_DSI_PIXEL_STREAM_3BYTE_18: case MIPI_DSI_PACKED_PIXEL_STREAM_24: if (check_rx_ack) { /* process response func should be implemented. */ mutex_unlock(&dsim->lock); return 0; } else { mutex_unlock(&dsim->lock); return -EINVAL; } default: dev_warn(dsim->dev, "data id %x is not supported current DSI spec.\n", data_id); mutex_unlock(&dsim->lock); return -EINVAL; } mutex_unlock(&dsim->lock); return 0; } static unsigned int exynos_mipi_dsi_long_data_rd(struct mipi_dsim_device *dsim, unsigned int req_size, unsigned int rx_data, u8 *rx_buf) { unsigned int rcv_pkt, i, j; u16 rxsize; /* for long packet */ rxsize = (u16)((rx_data & 0x00ffff00) >> 8); dev_dbg(dsim->dev, "mipi dsi rx size : %d\n", rxsize); if (rxsize != req_size) { dev_dbg(dsim->dev, "received size mismatch received: %d, requested: %d\n", rxsize, req_size); goto err; } for (i = 0; i < (rxsize >> 2); i++) { rcv_pkt = exynos_mipi_dsi_rd_rx_fifo(dsim); dev_dbg(dsim->dev, "received pkt : %08x\n", rcv_pkt); for (j = 0; j < 4; j++) { rx_buf[(i * 4) + j] = (u8)(rcv_pkt >> (j * 8)) & 0xff; dev_dbg(dsim->dev, "received value : %02x\n", (rcv_pkt >> (j * 8)) & 0xff); } } if (rxsize % 4) { rcv_pkt = exynos_mipi_dsi_rd_rx_fifo(dsim); dev_dbg(dsim->dev, "received pkt : %08x\n", rcv_pkt); for (j = 0; j < (rxsize % 4); j++) { rx_buf[(i * 4) + j] = (u8)(rcv_pkt >> (j * 8)) & 0xff; dev_dbg(dsim->dev, "received value : %02x\n", (rcv_pkt >> (j * 8)) & 0xff); } } return rxsize; err: return -EINVAL; } static unsigned int exynos_mipi_dsi_response_size(unsigned int req_size) { switch (req_size) { case 1: return MIPI_DSI_RX_GENERIC_SHORT_READ_RESPONSE_1BYTE; case 2: return MIPI_DSI_RX_GENERIC_SHORT_READ_RESPONSE_2BYTE; default: return MIPI_DSI_RX_GENERIC_LONG_READ_RESPONSE; } } int exynos_mipi_dsi_rd_data(struct mipi_dsim_device *dsim, unsigned int data_id, unsigned int data0, unsigned int req_size, u8 *rx_buf) { unsigned int rx_data, rcv_pkt, i; u8 response = 0; u16 rxsize; if (dsim->state == DSIM_STATE_ULPS) { dev_err(dsim->dev, "state is ULPS.\n"); return -EINVAL; } /* FIXME!!! */ msleep(20); mutex_lock(&dsim->lock); INIT_COMPLETION(dsim_rd_comp); exynos_mipi_dsi_rd_tx_header(dsim, MIPI_DSI_SET_MAXIMUM_RETURN_PACKET_SIZE, req_size); response = exynos_mipi_dsi_response_size(req_size); switch (data_id) { case MIPI_DSI_GENERIC_READ_REQUEST_0_PARAM: case MIPI_DSI_GENERIC_READ_REQUEST_1_PARAM: case MIPI_DSI_GENERIC_READ_REQUEST_2_PARAM: case MIPI_DSI_DCS_READ: exynos_mipi_dsi_rd_tx_header(dsim, data_id, data0); /* process response func should be implemented. */ break; default: dev_warn(dsim->dev, "data id %x is not supported current DSI spec.\n", data_id); return -EINVAL; } if (!wait_for_completion_interruptible_timeout(&dsim_rd_comp, MIPI_FIFO_TIMEOUT)) { pr_err("RX done interrupt timeout\n"); mutex_unlock(&dsim->lock); return 0; } msleep(20); rx_data = exynos_mipi_dsi_rd_rx_fifo(dsim); if ((u8)(rx_data & 0xff) != response) { printk(KERN_ERR "mipi dsi wrong response rx_data : %x, response:%x\n", rx_data, response); goto clear_rx_fifo; } if (req_size <= 2) { /* for short packet */ for (i = 0; i < req_size; i++) rx_buf[i] = (rx_data >> (8 + (i * 8))) & 0xff; rxsize = req_size; } else { /* for long packet */ rxsize = exynos_mipi_dsi_long_data_rd(dsim, req_size, rx_data, rx_buf); if (rxsize != req_size) goto clear_rx_fifo; } rcv_pkt = exynos_mipi_dsi_rd_rx_fifo(dsim); msleep(20); if (rcv_pkt != MIPI_RX_FIFO_READ_DONE) { dev_info(dsim->dev, "Can't found RX FIFO READ DONE FLAG : %x\n", rcv_pkt); goto clear_rx_fifo; } mutex_unlock(&dsim->lock); return rxsize; clear_rx_fifo: i = 0; while (1) { rcv_pkt = exynos_mipi_dsi_rd_rx_fifo(dsim); if ((rcv_pkt == MIPI_RX_FIFO_READ_DONE) || (i > MIPI_MAX_RX_FIFO)) break; dev_dbg(dsim->dev, "mipi dsi clear rx fifo : %08x\n", rcv_pkt); i++; } dev_info(dsim->dev, "mipi dsi rx done count : %d, rcv_pkt : %08x\n", i, rcv_pkt); mutex_unlock(&dsim->lock); return 0; } static int exynos_mipi_dsi_pll_on(struct mipi_dsim_device *dsim, unsigned int enable) { int sw_timeout; if (enable) { sw_timeout = 1000; exynos_mipi_dsi_enable_pll(dsim, 1); while (1) { sw_timeout--; if (exynos_mipi_dsi_is_pll_stable(dsim)) return 0; if (sw_timeout == 0) return -EINVAL; } } else exynos_mipi_dsi_enable_pll(dsim, 0); return 0; } static unsigned long exynos_mipi_dsi_change_pll(struct mipi_dsim_device *dsim, unsigned int pre_divider, unsigned int main_divider, unsigned int scaler) { unsigned long dfin_pll, dfvco, dpll_out; unsigned int i, freq_band = 0xf; dfin_pll = (FIN_HZ / pre_divider); /****************************************************** * Serial Clock(=ByteClk X 8) FreqBand[3:0] * ****************************************************** * ~ 99.99 MHz 0000 * 100 ~ 119.99 MHz 0001 * 120 ~ 159.99 MHz 0010 * 160 ~ 199.99 MHz 0011 * 200 ~ 239.99 MHz 0100 * 140 ~ 319.99 MHz 0101 * 320 ~ 389.99 MHz 0110 * 390 ~ 449.99 MHz 0111 * 450 ~ 509.99 MHz 1000 * 510 ~ 559.99 MHz 1001 * 560 ~ 639.99 MHz 1010 * 640 ~ 689.99 MHz 1011 * 690 ~ 769.99 MHz 1100 * 770 ~ 869.99 MHz 1101 * 870 ~ 949.99 MHz 1110 * 950 ~ 1000 MHz 1111 ******************************************************/ if (dfin_pll < DFIN_PLL_MIN_HZ || dfin_pll > DFIN_PLL_MAX_HZ) { dev_warn(dsim->dev, "fin_pll range should be 6MHz ~ 12MHz\n"); exynos_mipi_dsi_enable_afc(dsim, 0, 0); } else { if (dfin_pll < 7 * MHZ) exynos_mipi_dsi_enable_afc(dsim, 1, 0x1); else if (dfin_pll < 8 * MHZ) exynos_mipi_dsi_enable_afc(dsim, 1, 0x0); else if (dfin_pll < 9 * MHZ) exynos_mipi_dsi_enable_afc(dsim, 1, 0x3); else if (dfin_pll < 10 * MHZ) exynos_mipi_dsi_enable_afc(dsim, 1, 0x2); else if (dfin_pll < 11 * MHZ) exynos_mipi_dsi_enable_afc(dsim, 1, 0x5); else exynos_mipi_dsi_enable_afc(dsim, 1, 0x4); } dfvco = dfin_pll * main_divider; dev_dbg(dsim->dev, "dfvco = %lu, dfin_pll = %lu, main_divider = %d\n", dfvco, dfin_pll, main_divider); if (dfvco < DFVCO_MIN_HZ || dfvco > DFVCO_MAX_HZ) dev_warn(dsim->dev, "fvco range should be 500MHz ~ 1000MHz\n"); dpll_out = dfvco / (1 << scaler); dev_dbg(dsim->dev, "dpll_out = %lu, dfvco = %lu, scaler = %d\n", dpll_out, dfvco, scaler); for (i = 0; i < ARRAY_SIZE(dpll_table); i++) { if (dpll_out < dpll_table[i] * MHZ) { freq_band = i; break; } } dev_dbg(dsim->dev, "freq_band = %d\n", freq_band); exynos_mipi_dsi_pll_freq(dsim, pre_divider, main_divider, scaler); exynos_mipi_dsi_hs_zero_ctrl(dsim, 0); exynos_mipi_dsi_prep_ctrl(dsim, 0); /* Freq Band */ exynos_mipi_dsi_pll_freq_band(dsim, freq_band); /* Stable time */ exynos_mipi_dsi_pll_stable_time(dsim, dsim->dsim_config->pll_stable_time); /* Enable PLL */ dev_dbg(dsim->dev, "FOUT of mipi dphy pll is %luMHz\n", (dpll_out / MHZ)); return dpll_out; } static int exynos_mipi_dsi_set_clock(struct mipi_dsim_device *dsim, unsigned int byte_clk_sel, unsigned int enable) { unsigned int esc_div; unsigned long esc_clk_error_rate; unsigned long hs_clk = 0, byte_clk = 0, escape_clk = 0; if (enable) { dsim->e_clk_src = byte_clk_sel; /* Escape mode clock and byte clock source */ exynos_mipi_dsi_set_byte_clock_src(dsim, byte_clk_sel); /* DPHY, DSIM Link : D-PHY clock out */ if (byte_clk_sel == DSIM_PLL_OUT_DIV8) { hs_clk = exynos_mipi_dsi_change_pll(dsim, dsim->dsim_config->p, dsim->dsim_config->m, dsim->dsim_config->s); if (hs_clk == 0) { dev_err(dsim->dev, "failed to get hs clock.\n"); return -EINVAL; } byte_clk = hs_clk / 8; exynos_mipi_dsi_enable_pll_bypass(dsim, 0); exynos_mipi_dsi_pll_on(dsim, 1); /* DPHY : D-PHY clock out, DSIM link : external clock out */ } else if (byte_clk_sel == DSIM_EXT_CLK_DIV8) { dev_warn(dsim->dev, "this project is not support\n"); dev_warn(dsim->dev, "external clock source for MIPI DSIM.\n"); } else if (byte_clk_sel == DSIM_EXT_CLK_BYPASS) { dev_warn(dsim->dev, "this project is not support\n"); dev_warn(dsim->dev, "external clock source for MIPI DSIM\n"); } /* escape clock divider */ esc_div = byte_clk / (dsim->dsim_config->esc_clk); dev_dbg(dsim->dev, "esc_div = %d, byte_clk = %lu, esc_clk = %lu\n", esc_div, byte_clk, dsim->dsim_config->esc_clk); if ((byte_clk / esc_div) >= (20 * MHZ) || (byte_clk / esc_div) > dsim->dsim_config->esc_clk) esc_div += 1; escape_clk = byte_clk / esc_div; dev_dbg(dsim->dev, "escape_clk = %lu, byte_clk = %lu, esc_div = %d\n", escape_clk, byte_clk, esc_div); /* enable escape clock. */ exynos_mipi_dsi_enable_byte_clock(dsim, 1); /* enable byte clk and escape clock */ exynos_mipi_dsi_set_esc_clk_prs(dsim, 1, esc_div); /* escape clock on lane */ exynos_mipi_dsi_enable_esc_clk_on_lane(dsim, (DSIM_LANE_CLOCK | dsim->data_lane), 1); dev_dbg(dsim->dev, "byte clock is %luMHz\n", (byte_clk / MHZ)); dev_dbg(dsim->dev, "escape clock that user's need is %lu\n", (dsim->dsim_config->esc_clk / MHZ)); dev_dbg(dsim->dev, "escape clock divider is %x\n", esc_div); dev_dbg(dsim->dev, "escape clock is %luMHz\n", ((byte_clk / esc_div) / MHZ)); if ((byte_clk / esc_div) > escape_clk) { esc_clk_error_rate = escape_clk / (byte_clk / esc_div); dev_warn(dsim->dev, "error rate is %lu over.\n", (esc_clk_error_rate / 100)); } else if ((byte_clk / esc_div) < (escape_clk)) { esc_clk_error_rate = (byte_clk / esc_div) / escape_clk; dev_warn(dsim->dev, "error rate is %lu under.\n", (esc_clk_error_rate / 100)); } } else { exynos_mipi_dsi_enable_esc_clk_on_lane(dsim, (DSIM_LANE_CLOCK | dsim->data_lane), 0); exynos_mipi_dsi_set_esc_clk_prs(dsim, 0, 0); /* disable escape clock. */ exynos_mipi_dsi_enable_byte_clock(dsim, 0); if (byte_clk_sel == DSIM_PLL_OUT_DIV8) exynos_mipi_dsi_pll_on(dsim, 0); } return 0; } int exynos_mipi_dsi_init_dsim(struct mipi_dsim_device *dsim) { dsim->state = DSIM_STATE_INIT; switch (dsim->dsim_config->e_no_data_lane) { case DSIM_DATA_LANE_1: dsim->data_lane = DSIM_LANE_DATA0; break; case DSIM_DATA_LANE_2: dsim->data_lane = DSIM_LANE_DATA0 | DSIM_LANE_DATA1; break; case DSIM_DATA_LANE_3: dsim->data_lane = DSIM_LANE_DATA0 | DSIM_LANE_DATA1 | DSIM_LANE_DATA2; break; case DSIM_DATA_LANE_4: dsim->data_lane = DSIM_LANE_DATA0 | DSIM_LANE_DATA1 | DSIM_LANE_DATA2 | DSIM_LANE_DATA3; break; default: dev_info(dsim->dev, "data lane is invalid.\n"); return -EINVAL; }; exynos_mipi_dsi_sw_reset(dsim); exynos_mipi_dsi_func_reset(dsim); exynos_mipi_dsi_dp_dn_swap(dsim, 0); return 0; } void exynos_mipi_dsi_init_interrupt(struct mipi_dsim_device *dsim) { unsigned int src = 0; src = (INTSRC_SFR_FIFO_EMPTY | INTSRC_RX_DATA_DONE); exynos_mipi_dsi_set_interrupt(dsim, src, 1); src = 0; src = ~(INTMSK_RX_DONE | INTMSK_FIFO_EMPTY); exynos_mipi_dsi_set_interrupt_mask(dsim, src, 1); } int exynos_mipi_dsi_enable_frame_done_int(struct mipi_dsim_device *dsim, unsigned int enable) { /* enable only frame done interrupt */ exynos_mipi_dsi_set_interrupt_mask(dsim, INTMSK_FRAME_DONE, enable); return 0; } void exynos_mipi_dsi_stand_by(struct mipi_dsim_device *dsim, unsigned int enable) { /* consider Main display and Sub display. */ exynos_mipi_dsi_set_main_stand_by(dsim, enable); } int exynos_mipi_dsi_set_display_mode(struct mipi_dsim_device *dsim, struct mipi_dsim_config *dsim_config) { struct mipi_dsim_platform_data *dsim_pd; struct fb_videomode *timing; dsim_pd = (struct mipi_dsim_platform_data *)dsim->pd; timing = (struct fb_videomode *)dsim_pd->lcd_panel_info; /* in case of VIDEO MODE (RGB INTERFACE), it sets polarities. */ if (dsim_config->e_interface == (u32) DSIM_VIDEO) { if (dsim_config->auto_vertical_cnt == 0) { exynos_mipi_dsi_set_main_disp_vporch(dsim, dsim_config->cmd_allow, timing->upper_margin, timing->lower_margin); exynos_mipi_dsi_set_main_disp_hporch(dsim, timing->left_margin, timing->right_margin); exynos_mipi_dsi_set_main_disp_sync_area(dsim, timing->vsync_len, timing->hsync_len); } } exynos_mipi_dsi_set_main_disp_resol(dsim, timing->xres, timing->yres); exynos_mipi_dsi_display_config(dsim, dsim_config); dev_info(dsim->dev, "lcd panel ==> width = %d, height = %d\n", timing->xres, timing->yres); return 0; } int exynos_mipi_dsi_init_link(struct mipi_dsim_device *dsim) { unsigned int time_out = 100; switch (dsim->state) { case DSIM_STATE_INIT: exynos_mipi_dsi_init_fifo_pointer(dsim, 0x1f); /* dsi configuration */ exynos_mipi_dsi_init_config(dsim); exynos_mipi_dsi_enable_lane(dsim, DSIM_LANE_CLOCK, 1); exynos_mipi_dsi_enable_lane(dsim, dsim->data_lane, 1); /* set clock configuration */ exynos_mipi_dsi_set_clock(dsim, dsim->dsim_config->e_byte_clk, 1); /* check clock and data lane state are stop state */ while (!(exynos_mipi_dsi_is_lane_state(dsim))) { time_out--; if (time_out == 0) { dev_err(dsim->dev, "DSI Master is not stop state.\n"); dev_err(dsim->dev, "Check initialization process\n"); return -EINVAL; } } if (time_out != 0) { dev_info(dsim->dev, "DSI Master driver has been completed.\n"); dev_info(dsim->dev, "DSI Master state is stop state\n"); } dsim->state = DSIM_STATE_STOP; /* BTA sequence counters */ exynos_mipi_dsi_set_stop_state_counter(dsim, dsim->dsim_config->stop_holding_cnt); exynos_mipi_dsi_set_bta_timeout(dsim, dsim->dsim_config->bta_timeout); exynos_mipi_dsi_set_lpdr_timeout(dsim, dsim->dsim_config->rx_timeout); return 0; default: dev_info(dsim->dev, "DSI Master is already init.\n"); return 0; } return 0; } int exynos_mipi_dsi_set_hs_enable(struct mipi_dsim_device *dsim) { if (dsim->state != DSIM_STATE_STOP) { dev_warn(dsim->dev, "DSIM is not in stop state.\n"); return 0; } if (dsim->e_clk_src == DSIM_EXT_CLK_BYPASS) { dev_warn(dsim->dev, "clock source is external bypass.\n"); return 0; } dsim->state = DSIM_STATE_HSCLKEN; /* set LCDC and CPU transfer mode to HS. */ exynos_mipi_dsi_set_lcdc_transfer_mode(dsim, 0); exynos_mipi_dsi_set_cpu_transfer_mode(dsim, 0); exynos_mipi_dsi_enable_hs_clock(dsim, 1); return 0; } int exynos_mipi_dsi_set_data_transfer_mode(struct mipi_dsim_device *dsim, unsigned int mode) { if (mode) { if (dsim->state != DSIM_STATE_HSCLKEN) { dev_err(dsim->dev, "HS Clock lane is not enabled.\n"); return -EINVAL; } exynos_mipi_dsi_set_lcdc_transfer_mode(dsim, 0); } else { if (dsim->state == DSIM_STATE_INIT || dsim->state == DSIM_STATE_ULPS) { dev_err(dsim->dev, "DSI Master is not STOP or HSDT state.\n"); return -EINVAL; } exynos_mipi_dsi_set_cpu_transfer_mode(dsim, 0); } return 0; } int exynos_mipi_dsi_get_frame_done_status(struct mipi_dsim_device *dsim) { return _exynos_mipi_dsi_get_frame_done_status(dsim); } int exynos_mipi_dsi_clear_frame_done(struct mipi_dsim_device *dsim) { _exynos_mipi_dsi_clear_frame_done(dsim); return 0; } int exynos_mipi_dsi_fifo_clear(struct mipi_dsim_device *dsim, unsigned int val) { int try = TRY_FIFO_CLEAR; exynos_mipi_dsi_sw_reset_release(dsim); exynos_mipi_dsi_func_reset(dsim); do { if (exynos_mipi_dsi_get_sw_reset_release(dsim)) { exynos_mipi_dsi_init_interrupt(dsim); dev_dbg(dsim->dev, "reset release done.\n"); return 0; } } while (--try); dev_err(dsim->dev, "failed to clear dsim fifo.\n"); return -EAGAIN; } MODULE_AUTHOR("InKi Dae <inki.dae@samsung.com>"); MODULE_DESCRIPTION("Samusung SoC MIPI-DSI common driver"); MODULE_LICENSE("GPL");
gpl-2.0
Tkkg1994/Hulk-Kernel-V2
drivers/hwmon/sch56xx-common.c
4812
21702
/*************************************************************************** * Copyright (C) 2010-2012 Hans de Goede <hdegoede@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. * * * * 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. * ***************************************************************************/ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/module.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/err.h> #include <linux/io.h> #include <linux/acpi.h> #include <linux/delay.h> #include <linux/fs.h> #include <linux/watchdog.h> #include <linux/miscdevice.h> #include <linux/uaccess.h> #include <linux/kref.h> #include <linux/slab.h> #include "sch56xx-common.h" /* Insmod parameters */ static int nowayout = WATCHDOG_NOWAYOUT; module_param(nowayout, int, 0); MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started (default=" __MODULE_STRING(WATCHDOG_NOWAYOUT) ")"); #define SIO_SCH56XX_LD_EM 0x0C /* Embedded uController Logical Dev */ #define SIO_UNLOCK_KEY 0x55 /* Key to enable Super-I/O */ #define SIO_LOCK_KEY 0xAA /* Key to disable Super-I/O */ #define SIO_REG_LDSEL 0x07 /* Logical device select */ #define SIO_REG_DEVID 0x20 /* Device ID */ #define SIO_REG_ENABLE 0x30 /* Logical device enable */ #define SIO_REG_ADDR 0x66 /* Logical device address (2 bytes) */ #define SIO_SCH5627_ID 0xC6 /* Chipset ID */ #define SIO_SCH5636_ID 0xC7 /* Chipset ID */ #define REGION_LENGTH 10 #define SCH56XX_CMD_READ 0x02 #define SCH56XX_CMD_WRITE 0x03 /* Watchdog registers */ #define SCH56XX_REG_WDOG_PRESET 0x58B #define SCH56XX_REG_WDOG_CONTROL 0x58C #define SCH56XX_WDOG_TIME_BASE_SEC 0x01 #define SCH56XX_REG_WDOG_OUTPUT_ENABLE 0x58E #define SCH56XX_WDOG_OUTPUT_ENABLE 0x02 struct sch56xx_watchdog_data { u16 addr; u32 revision; struct mutex *io_lock; struct mutex watchdog_lock; struct list_head list; /* member of the watchdog_data_list */ struct kref kref; struct miscdevice watchdog_miscdev; unsigned long watchdog_is_open; char watchdog_name[10]; /* must be unique to avoid sysfs conflict */ char watchdog_expect_close; u8 watchdog_preset; u8 watchdog_control; u8 watchdog_output_enable; }; static struct platform_device *sch56xx_pdev; /* * Somewhat ugly :( global data pointer list with all sch56xx devices, so that * we can find our device data as when using misc_register there is no other * method to get to ones device data from the open fop. */ static LIST_HEAD(watchdog_data_list); /* Note this lock not only protect list access, but also data.kref access */ static DEFINE_MUTEX(watchdog_data_mutex); /* Super I/O functions */ static inline int superio_inb(int base, int reg) { outb(reg, base); return inb(base + 1); } static inline int superio_enter(int base) { /* Don't step on other drivers' I/O space by accident */ if (!request_muxed_region(base, 2, "sch56xx")) { pr_err("I/O address 0x%04x already in use\n", base); return -EBUSY; } outb(SIO_UNLOCK_KEY, base); return 0; } static inline void superio_select(int base, int ld) { outb(SIO_REG_LDSEL, base); outb(ld, base + 1); } static inline void superio_exit(int base) { outb(SIO_LOCK_KEY, base); release_region(base, 2); } static int sch56xx_send_cmd(u16 addr, u8 cmd, u16 reg, u8 v) { u8 val; int i; /* * According to SMSC for the commands we use the maximum time for * the EM to respond is 15 ms, but testing shows in practice it * responds within 15-32 reads, so we first busy poll, and if * that fails sleep a bit and try again until we are way past * the 15 ms maximum response time. */ const int max_busy_polls = 64; const int max_lazy_polls = 32; /* (Optional) Write-Clear the EC to Host Mailbox Register */ val = inb(addr + 1); outb(val, addr + 1); /* Set Mailbox Address Pointer to first location in Region 1 */ outb(0x00, addr + 2); outb(0x80, addr + 3); /* Write Request Packet Header */ outb(cmd, addr + 4); /* VREG Access Type read:0x02 write:0x03 */ outb(0x01, addr + 5); /* # of Entries: 1 Byte (8-bit) */ outb(0x04, addr + 2); /* Mailbox AP to first data entry loc. */ /* Write Value field */ if (cmd == SCH56XX_CMD_WRITE) outb(v, addr + 4); /* Write Address field */ outb(reg & 0xff, addr + 6); outb(reg >> 8, addr + 7); /* Execute the Random Access Command */ outb(0x01, addr); /* Write 01h to the Host-to-EC register */ /* EM Interface Polling "Algorithm" */ for (i = 0; i < max_busy_polls + max_lazy_polls; i++) { if (i >= max_busy_polls) msleep(1); /* Read Interrupt source Register */ val = inb(addr + 8); /* Write Clear the interrupt source bits */ if (val) outb(val, addr + 8); /* Command Completed ? */ if (val & 0x01) break; } if (i == max_busy_polls + max_lazy_polls) { pr_err("Max retries exceeded reading virtual " "register 0x%04hx (%d)\n", reg, 1); return -EIO; } /* * According to SMSC we may need to retry this, but sofar I've always * seen this succeed in 1 try. */ for (i = 0; i < max_busy_polls; i++) { /* Read EC-to-Host Register */ val = inb(addr + 1); /* Command Completed ? */ if (val == 0x01) break; if (i == 0) pr_warn("EC reports: 0x%02x reading virtual register " "0x%04hx\n", (unsigned int)val, reg); } if (i == max_busy_polls) { pr_err("Max retries exceeded reading virtual " "register 0x%04hx (%d)\n", reg, 2); return -EIO; } /* * According to the SMSC app note we should now do: * * Set Mailbox Address Pointer to first location in Region 1 * * outb(0x00, addr + 2); * outb(0x80, addr + 3); * * But if we do that things don't work, so let's not. */ /* Read Value field */ if (cmd == SCH56XX_CMD_READ) return inb(addr + 4); return 0; } int sch56xx_read_virtual_reg(u16 addr, u16 reg) { return sch56xx_send_cmd(addr, SCH56XX_CMD_READ, reg, 0); } EXPORT_SYMBOL(sch56xx_read_virtual_reg); int sch56xx_write_virtual_reg(u16 addr, u16 reg, u8 val) { return sch56xx_send_cmd(addr, SCH56XX_CMD_WRITE, reg, val); } EXPORT_SYMBOL(sch56xx_write_virtual_reg); int sch56xx_read_virtual_reg16(u16 addr, u16 reg) { int lsb, msb; /* Read LSB first, this will cause the matching MSB to be latched */ lsb = sch56xx_read_virtual_reg(addr, reg); if (lsb < 0) return lsb; msb = sch56xx_read_virtual_reg(addr, reg + 1); if (msb < 0) return msb; return lsb | (msb << 8); } EXPORT_SYMBOL(sch56xx_read_virtual_reg16); int sch56xx_read_virtual_reg12(u16 addr, u16 msb_reg, u16 lsn_reg, int high_nibble) { int msb, lsn; /* Read MSB first, this will cause the matching LSN to be latched */ msb = sch56xx_read_virtual_reg(addr, msb_reg); if (msb < 0) return msb; lsn = sch56xx_read_virtual_reg(addr, lsn_reg); if (lsn < 0) return lsn; if (high_nibble) return (msb << 4) | (lsn >> 4); else return (msb << 4) | (lsn & 0x0f); } EXPORT_SYMBOL(sch56xx_read_virtual_reg12); /* * Watchdog routines */ /* * Release our data struct when the platform device has been released *and* * all references to our watchdog device are released. */ static void sch56xx_watchdog_release_resources(struct kref *r) { struct sch56xx_watchdog_data *data = container_of(r, struct sch56xx_watchdog_data, kref); kfree(data); } static int watchdog_set_timeout(struct sch56xx_watchdog_data *data, int timeout) { int ret, resolution; u8 control; /* 1 second or 60 second resolution? */ if (timeout <= 255) resolution = 1; else resolution = 60; if (timeout < resolution || timeout > (resolution * 255)) return -EINVAL; mutex_lock(&data->watchdog_lock); if (!data->addr) { ret = -ENODEV; goto leave; } if (resolution == 1) control = data->watchdog_control | SCH56XX_WDOG_TIME_BASE_SEC; else control = data->watchdog_control & ~SCH56XX_WDOG_TIME_BASE_SEC; if (data->watchdog_control != control) { mutex_lock(data->io_lock); ret = sch56xx_write_virtual_reg(data->addr, SCH56XX_REG_WDOG_CONTROL, control); mutex_unlock(data->io_lock); if (ret) goto leave; data->watchdog_control = control; } /* * Remember new timeout value, but do not write as that (re)starts * the watchdog countdown. */ data->watchdog_preset = DIV_ROUND_UP(timeout, resolution); ret = data->watchdog_preset * resolution; leave: mutex_unlock(&data->watchdog_lock); return ret; } static int watchdog_get_timeout(struct sch56xx_watchdog_data *data) { int timeout; mutex_lock(&data->watchdog_lock); if (data->watchdog_control & SCH56XX_WDOG_TIME_BASE_SEC) timeout = data->watchdog_preset; else timeout = data->watchdog_preset * 60; mutex_unlock(&data->watchdog_lock); return timeout; } static int watchdog_start(struct sch56xx_watchdog_data *data) { int ret; u8 val; mutex_lock(&data->watchdog_lock); if (!data->addr) { ret = -ENODEV; goto leave_unlock_watchdog; } /* * The sch56xx's watchdog cannot really be started / stopped * it is always running, but we can avoid the timer expiring * from causing a system reset by clearing the output enable bit. * * The sch56xx's watchdog will set the watchdog event bit, bit 0 * of the second interrupt source register (at base-address + 9), * when the timer expires. * * This will only cause a system reset if the 0-1 flank happens when * output enable is true. Setting output enable after the flank will * not cause a reset, nor will the timer expiring a second time. * This means we must clear the watchdog event bit in case it is set. * * The timer may still be running (after a recent watchdog_stop) and * mere milliseconds away from expiring, so the timer must be reset * first! */ mutex_lock(data->io_lock); /* 1. Reset the watchdog countdown counter */ ret = sch56xx_write_virtual_reg(data->addr, SCH56XX_REG_WDOG_PRESET, data->watchdog_preset); if (ret) goto leave; /* 2. Enable output (if not already enabled) */ if (!(data->watchdog_output_enable & SCH56XX_WDOG_OUTPUT_ENABLE)) { val = data->watchdog_output_enable | SCH56XX_WDOG_OUTPUT_ENABLE; ret = sch56xx_write_virtual_reg(data->addr, SCH56XX_REG_WDOG_OUTPUT_ENABLE, val); if (ret) goto leave; data->watchdog_output_enable = val; } /* 3. Clear the watchdog event bit if set */ val = inb(data->addr + 9); if (val & 0x01) outb(0x01, data->addr + 9); leave: mutex_unlock(data->io_lock); leave_unlock_watchdog: mutex_unlock(&data->watchdog_lock); return ret; } static int watchdog_trigger(struct sch56xx_watchdog_data *data) { int ret; mutex_lock(&data->watchdog_lock); if (!data->addr) { ret = -ENODEV; goto leave; } /* Reset the watchdog countdown counter */ mutex_lock(data->io_lock); ret = sch56xx_write_virtual_reg(data->addr, SCH56XX_REG_WDOG_PRESET, data->watchdog_preset); mutex_unlock(data->io_lock); leave: mutex_unlock(&data->watchdog_lock); return ret; } static int watchdog_stop_unlocked(struct sch56xx_watchdog_data *data) { int ret = 0; u8 val; if (!data->addr) return -ENODEV; if (data->watchdog_output_enable & SCH56XX_WDOG_OUTPUT_ENABLE) { val = data->watchdog_output_enable & ~SCH56XX_WDOG_OUTPUT_ENABLE; mutex_lock(data->io_lock); ret = sch56xx_write_virtual_reg(data->addr, SCH56XX_REG_WDOG_OUTPUT_ENABLE, val); mutex_unlock(data->io_lock); if (ret) return ret; data->watchdog_output_enable = val; } return ret; } static int watchdog_stop(struct sch56xx_watchdog_data *data) { int ret; mutex_lock(&data->watchdog_lock); ret = watchdog_stop_unlocked(data); mutex_unlock(&data->watchdog_lock); return ret; } static int watchdog_release(struct inode *inode, struct file *filp) { struct sch56xx_watchdog_data *data = filp->private_data; if (data->watchdog_expect_close) { watchdog_stop(data); data->watchdog_expect_close = 0; } else { watchdog_trigger(data); pr_crit("unexpected close, not stopping watchdog!\n"); } clear_bit(0, &data->watchdog_is_open); mutex_lock(&watchdog_data_mutex); kref_put(&data->kref, sch56xx_watchdog_release_resources); mutex_unlock(&watchdog_data_mutex); return 0; } static int watchdog_open(struct inode *inode, struct file *filp) { struct sch56xx_watchdog_data *pos, *data = NULL; int ret, watchdog_is_open; /* * We get called from drivers/char/misc.c with misc_mtx hold, and we * call misc_register() from sch56xx_watchdog_probe() with * watchdog_data_mutex hold, as misc_register() takes the misc_mtx * lock, this is a possible deadlock, so we use mutex_trylock here. */ if (!mutex_trylock(&watchdog_data_mutex)) return -ERESTARTSYS; list_for_each_entry(pos, &watchdog_data_list, list) { if (pos->watchdog_miscdev.minor == iminor(inode)) { data = pos; break; } } /* Note we can never not have found data, so we don't check for this */ watchdog_is_open = test_and_set_bit(0, &data->watchdog_is_open); if (!watchdog_is_open) kref_get(&data->kref); mutex_unlock(&watchdog_data_mutex); if (watchdog_is_open) return -EBUSY; filp->private_data = data; /* Start the watchdog */ ret = watchdog_start(data); if (ret) { watchdog_release(inode, filp); return ret; } return nonseekable_open(inode, filp); } static ssize_t watchdog_write(struct file *filp, const char __user *buf, size_t count, loff_t *offset) { int ret; struct sch56xx_watchdog_data *data = filp->private_data; if (count) { if (!nowayout) { size_t i; /* Clear it in case it was set with a previous write */ data->watchdog_expect_close = 0; for (i = 0; i != count; i++) { char c; if (get_user(c, buf + i)) return -EFAULT; if (c == 'V') data->watchdog_expect_close = 1; } } ret = watchdog_trigger(data); if (ret) return ret; } return count; } static long watchdog_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { struct watchdog_info ident = { .options = WDIOF_KEEPALIVEPING | WDIOF_SETTIMEOUT, .identity = "sch56xx watchdog" }; int i, ret = 0; struct sch56xx_watchdog_data *data = filp->private_data; switch (cmd) { case WDIOC_GETSUPPORT: ident.firmware_version = data->revision; if (!nowayout) ident.options |= WDIOF_MAGICCLOSE; if (copy_to_user((void __user *)arg, &ident, sizeof(ident))) ret = -EFAULT; break; case WDIOC_GETSTATUS: case WDIOC_GETBOOTSTATUS: ret = put_user(0, (int __user *)arg); break; case WDIOC_KEEPALIVE: ret = watchdog_trigger(data); break; case WDIOC_GETTIMEOUT: i = watchdog_get_timeout(data); ret = put_user(i, (int __user *)arg); break; case WDIOC_SETTIMEOUT: if (get_user(i, (int __user *)arg)) { ret = -EFAULT; break; } ret = watchdog_set_timeout(data, i); if (ret >= 0) ret = put_user(ret, (int __user *)arg); break; case WDIOC_SETOPTIONS: if (get_user(i, (int __user *)arg)) { ret = -EFAULT; break; } if (i & WDIOS_DISABLECARD) ret = watchdog_stop(data); else if (i & WDIOS_ENABLECARD) ret = watchdog_trigger(data); else ret = -EINVAL; break; default: ret = -ENOTTY; } return ret; } static const struct file_operations watchdog_fops = { .owner = THIS_MODULE, .llseek = no_llseek, .open = watchdog_open, .release = watchdog_release, .write = watchdog_write, .unlocked_ioctl = watchdog_ioctl, }; struct sch56xx_watchdog_data *sch56xx_watchdog_register( u16 addr, u32 revision, struct mutex *io_lock, int check_enabled) { struct sch56xx_watchdog_data *data; int i, err, control, output_enable; const int watchdog_minors[] = { WATCHDOG_MINOR, 212, 213, 214, 215 }; /* Cache the watchdog registers */ mutex_lock(io_lock); control = sch56xx_read_virtual_reg(addr, SCH56XX_REG_WDOG_CONTROL); output_enable = sch56xx_read_virtual_reg(addr, SCH56XX_REG_WDOG_OUTPUT_ENABLE); mutex_unlock(io_lock); if (control < 0) return NULL; if (output_enable < 0) return NULL; if (check_enabled && !(output_enable & SCH56XX_WDOG_OUTPUT_ENABLE)) { pr_warn("Watchdog not enabled by BIOS, not registering\n"); return NULL; } data = kzalloc(sizeof(struct sch56xx_watchdog_data), GFP_KERNEL); if (!data) return NULL; data->addr = addr; data->revision = revision; data->io_lock = io_lock; data->watchdog_control = control; data->watchdog_output_enable = output_enable; mutex_init(&data->watchdog_lock); INIT_LIST_HEAD(&data->list); kref_init(&data->kref); err = watchdog_set_timeout(data, 60); if (err < 0) goto error; /* * We take the data_mutex lock early so that watchdog_open() cannot * run when misc_register() has completed, but we've not yet added * our data to the watchdog_data_list. */ mutex_lock(&watchdog_data_mutex); for (i = 0; i < ARRAY_SIZE(watchdog_minors); i++) { /* Register our watchdog part */ snprintf(data->watchdog_name, sizeof(data->watchdog_name), "watchdog%c", (i == 0) ? '\0' : ('0' + i)); data->watchdog_miscdev.name = data->watchdog_name; data->watchdog_miscdev.fops = &watchdog_fops; data->watchdog_miscdev.minor = watchdog_minors[i]; err = misc_register(&data->watchdog_miscdev); if (err == -EBUSY) continue; if (err) break; list_add(&data->list, &watchdog_data_list); pr_info("Registered /dev/%s chardev major 10, minor: %d\n", data->watchdog_name, watchdog_minors[i]); break; } mutex_unlock(&watchdog_data_mutex); if (err) { pr_err("Registering watchdog chardev: %d\n", err); goto error; } if (i == ARRAY_SIZE(watchdog_minors)) { pr_warn("Couldn't register watchdog (no free minor)\n"); goto error; } return data; error: kfree(data); return NULL; } EXPORT_SYMBOL(sch56xx_watchdog_register); void sch56xx_watchdog_unregister(struct sch56xx_watchdog_data *data) { mutex_lock(&watchdog_data_mutex); misc_deregister(&data->watchdog_miscdev); list_del(&data->list); mutex_unlock(&watchdog_data_mutex); mutex_lock(&data->watchdog_lock); if (data->watchdog_is_open) { pr_warn("platform device unregistered with watchdog " "open! Stopping watchdog.\n"); watchdog_stop_unlocked(data); } /* Tell the wdog start/stop/trigger functions our dev is gone */ data->addr = 0; data->io_lock = NULL; mutex_unlock(&data->watchdog_lock); mutex_lock(&watchdog_data_mutex); kref_put(&data->kref, sch56xx_watchdog_release_resources); mutex_unlock(&watchdog_data_mutex); } EXPORT_SYMBOL(sch56xx_watchdog_unregister); /* * platform dev find, add and remove functions */ static int __init sch56xx_find(int sioaddr, unsigned short *address, const char **name) { u8 devid; int err; err = superio_enter(sioaddr); if (err) return err; devid = superio_inb(sioaddr, SIO_REG_DEVID); switch (devid) { case SIO_SCH5627_ID: *name = "sch5627"; break; case SIO_SCH5636_ID: *name = "sch5636"; break; default: pr_debug("Unsupported device id: 0x%02x\n", (unsigned int)devid); err = -ENODEV; goto exit; } superio_select(sioaddr, SIO_SCH56XX_LD_EM); if (!(superio_inb(sioaddr, SIO_REG_ENABLE) & 0x01)) { pr_warn("Device not activated\n"); err = -ENODEV; goto exit; } /* * Warning the order of the low / high byte is the other way around * as on most other superio devices!! */ *address = superio_inb(sioaddr, SIO_REG_ADDR) | superio_inb(sioaddr, SIO_REG_ADDR + 1) << 8; if (*address == 0) { pr_warn("Base address not set\n"); err = -ENODEV; goto exit; } exit: superio_exit(sioaddr); return err; } static int __init sch56xx_device_add(unsigned short address, const char *name) { struct resource res = { .start = address, .end = address + REGION_LENGTH - 1, .flags = IORESOURCE_IO, }; int err; sch56xx_pdev = platform_device_alloc(name, address); if (!sch56xx_pdev) return -ENOMEM; res.name = sch56xx_pdev->name; err = acpi_check_resource_conflict(&res); if (err) goto exit_device_put; err = platform_device_add_resources(sch56xx_pdev, &res, 1); if (err) { pr_err("Device resource addition failed\n"); goto exit_device_put; } err = platform_device_add(sch56xx_pdev); if (err) { pr_err("Device addition failed\n"); goto exit_device_put; } return 0; exit_device_put: platform_device_put(sch56xx_pdev); return err; } static int __init sch56xx_init(void) { int err; unsigned short address; const char *name; err = sch56xx_find(0x4e, &address, &name); if (err) err = sch56xx_find(0x2e, &address, &name); if (err) return err; return sch56xx_device_add(address, name); } static void __exit sch56xx_exit(void) { platform_device_unregister(sch56xx_pdev); } MODULE_DESCRIPTION("SMSC SCH56xx Hardware Monitoring Common Code"); MODULE_AUTHOR("Hans de Goede <hdegoede@redhat.com>"); MODULE_LICENSE("GPL"); module_init(sch56xx_init); module_exit(sch56xx_exit);
gpl-2.0
Volidol1/android_kernel_lge_d605
sound/soc/codecs/tlv320dac33.c
4812
44705
/* * ALSA SoC Texas Instruments TLV320DAC33 codec driver * * Author: Peter Ujfalusi <peter.ujfalusi@ti.com> * * Copyright: (C) 2009 Nokia Corporation * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * 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/module.h> #include <linux/moduleparam.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/pm.h> #include <linux/i2c.h> #include <linux/interrupt.h> #include <linux/gpio.h> #include <linux/regulator/consumer.h> #include <linux/slab.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/soc.h> #include <sound/initval.h> #include <sound/tlv.h> #include <sound/tlv320dac33-plat.h> #include "tlv320dac33.h" /* * The internal FIFO is 24576 bytes long * It can be configured to hold 16bit or 24bit samples * In 16bit configuration the FIFO can hold 6144 stereo samples * In 24bit configuration the FIFO can hold 4096 stereo samples */ #define DAC33_FIFO_SIZE_16BIT 6144 #define DAC33_FIFO_SIZE_24BIT 4096 #define DAC33_MODE7_MARGIN 10 /* Safety margin for FIFO in Mode7 */ #define BURST_BASEFREQ_HZ 49152000 #define SAMPLES_TO_US(rate, samples) \ (1000000000 / (((rate) * 1000) / (samples))) #define US_TO_SAMPLES(rate, us) \ ((rate) / (1000000 / ((us) < 1000000 ? (us) : 1000000))) #define UTHR_FROM_PERIOD_SIZE(samples, playrate, burstrate) \ (((samples)*5000) / (((burstrate)*5000) / ((burstrate) - (playrate)))) static void dac33_calculate_times(struct snd_pcm_substream *substream); static int dac33_prepare_chip(struct snd_pcm_substream *substream); enum dac33_state { DAC33_IDLE = 0, DAC33_PREFILL, DAC33_PLAYBACK, DAC33_FLUSH, }; enum dac33_fifo_modes { DAC33_FIFO_BYPASS = 0, DAC33_FIFO_MODE1, DAC33_FIFO_MODE7, DAC33_FIFO_LAST_MODE, }; #define DAC33_NUM_SUPPLIES 3 static const char *dac33_supply_names[DAC33_NUM_SUPPLIES] = { "AVDD", "DVDD", "IOVDD", }; struct tlv320dac33_priv { struct mutex mutex; struct workqueue_struct *dac33_wq; struct work_struct work; struct snd_soc_codec *codec; struct regulator_bulk_data supplies[DAC33_NUM_SUPPLIES]; struct snd_pcm_substream *substream; int power_gpio; int chip_power; int irq; unsigned int refclk; unsigned int alarm_threshold; /* set to be half of LATENCY_TIME_MS */ enum dac33_fifo_modes fifo_mode;/* FIFO mode selection */ unsigned int fifo_size; /* Size of the FIFO in samples */ unsigned int nsample; /* burst read amount from host */ int mode1_latency; /* latency caused by the i2c writes in * us */ u8 burst_bclkdiv; /* BCLK divider value in burst mode */ unsigned int burst_rate; /* Interface speed in Burst modes */ int keep_bclk; /* Keep the BCLK continuously running * in FIFO modes */ spinlock_t lock; unsigned long long t_stamp1; /* Time stamp for FIFO modes to */ unsigned long long t_stamp2; /* calculate the FIFO caused delay */ unsigned int mode1_us_burst; /* Time to burst read n number of * samples */ unsigned int mode7_us_to_lthr; /* Time to reach lthr from uthr */ unsigned int uthr; enum dac33_state state; enum snd_soc_control_type control_type; void *control_data; }; static const u8 dac33_reg[DAC33_CACHEREGNUM] = { 0x00, 0x00, 0x00, 0x00, /* 0x00 - 0x03 */ 0x00, 0x00, 0x00, 0x00, /* 0x04 - 0x07 */ 0x00, 0x00, 0x00, 0x00, /* 0x08 - 0x0b */ 0x00, 0x00, 0x00, 0x00, /* 0x0c - 0x0f */ 0x00, 0x00, 0x00, 0x00, /* 0x10 - 0x13 */ 0x00, 0x00, 0x00, 0x00, /* 0x14 - 0x17 */ 0x00, 0x00, 0x00, 0x00, /* 0x18 - 0x1b */ 0x00, 0x00, 0x00, 0x00, /* 0x1c - 0x1f */ 0x00, 0x00, 0x00, 0x00, /* 0x20 - 0x23 */ 0x00, 0x00, 0x00, 0x00, /* 0x24 - 0x27 */ 0x00, 0x00, 0x00, 0x00, /* 0x28 - 0x2b */ 0x00, 0x00, 0x00, 0x80, /* 0x2c - 0x2f */ 0x80, 0x00, 0x00, 0x00, /* 0x30 - 0x33 */ 0x00, 0x00, 0x00, 0x00, /* 0x34 - 0x37 */ 0x00, 0x00, /* 0x38 - 0x39 */ /* Registers 0x3a - 0x3f are reserved */ 0x00, 0x00, /* 0x3a - 0x3b */ 0x00, 0x00, 0x00, 0x00, /* 0x3c - 0x3f */ 0x00, 0x00, 0x00, 0x00, /* 0x40 - 0x43 */ 0x00, 0x80, /* 0x44 - 0x45 */ /* Registers 0x46 - 0x47 are reserved */ 0x80, 0x80, /* 0x46 - 0x47 */ 0x80, 0x00, 0x00, /* 0x48 - 0x4a */ /* Registers 0x4b - 0x7c are reserved */ 0x00, /* 0x4b */ 0x00, 0x00, 0x00, 0x00, /* 0x4c - 0x4f */ 0x00, 0x00, 0x00, 0x00, /* 0x50 - 0x53 */ 0x00, 0x00, 0x00, 0x00, /* 0x54 - 0x57 */ 0x00, 0x00, 0x00, 0x00, /* 0x58 - 0x5b */ 0x00, 0x00, 0x00, 0x00, /* 0x5c - 0x5f */ 0x00, 0x00, 0x00, 0x00, /* 0x60 - 0x63 */ 0x00, 0x00, 0x00, 0x00, /* 0x64 - 0x67 */ 0x00, 0x00, 0x00, 0x00, /* 0x68 - 0x6b */ 0x00, 0x00, 0x00, 0x00, /* 0x6c - 0x6f */ 0x00, 0x00, 0x00, 0x00, /* 0x70 - 0x73 */ 0x00, 0x00, 0x00, 0x00, /* 0x74 - 0x77 */ 0x00, 0x00, 0x00, 0x00, /* 0x78 - 0x7b */ 0x00, /* 0x7c */ 0xda, 0x33, 0x03, /* 0x7d - 0x7f */ }; /* Register read and write */ static inline unsigned int dac33_read_reg_cache(struct snd_soc_codec *codec, unsigned reg) { u8 *cache = codec->reg_cache; if (reg >= DAC33_CACHEREGNUM) return 0; return cache[reg]; } static inline void dac33_write_reg_cache(struct snd_soc_codec *codec, u8 reg, u8 value) { u8 *cache = codec->reg_cache; if (reg >= DAC33_CACHEREGNUM) return; cache[reg] = value; } static int dac33_read(struct snd_soc_codec *codec, unsigned int reg, u8 *value) { struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); int val, ret = 0; *value = reg & 0xff; /* If powered off, return the cached value */ if (dac33->chip_power) { val = i2c_smbus_read_byte_data(codec->control_data, value[0]); if (val < 0) { dev_err(codec->dev, "Read failed (%d)\n", val); value[0] = dac33_read_reg_cache(codec, reg); ret = val; } else { value[0] = val; dac33_write_reg_cache(codec, reg, val); } } else { value[0] = dac33_read_reg_cache(codec, reg); } return ret; } static int dac33_write(struct snd_soc_codec *codec, unsigned int reg, unsigned int value) { struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); u8 data[2]; int ret = 0; /* * data is * D15..D8 dac33 register offset * D7...D0 register data */ data[0] = reg & 0xff; data[1] = value & 0xff; dac33_write_reg_cache(codec, data[0], data[1]); if (dac33->chip_power) { ret = codec->hw_write(codec->control_data, data, 2); if (ret != 2) dev_err(codec->dev, "Write failed (%d)\n", ret); else ret = 0; } return ret; } static int dac33_write_locked(struct snd_soc_codec *codec, unsigned int reg, unsigned int value) { struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); int ret; mutex_lock(&dac33->mutex); ret = dac33_write(codec, reg, value); mutex_unlock(&dac33->mutex); return ret; } #define DAC33_I2C_ADDR_AUTOINC 0x80 static int dac33_write16(struct snd_soc_codec *codec, unsigned int reg, unsigned int value) { struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); u8 data[3]; int ret = 0; /* * data is * D23..D16 dac33 register offset * D15..D8 register data MSB * D7...D0 register data LSB */ data[0] = reg & 0xff; data[1] = (value >> 8) & 0xff; data[2] = value & 0xff; dac33_write_reg_cache(codec, data[0], data[1]); dac33_write_reg_cache(codec, data[0] + 1, data[2]); if (dac33->chip_power) { /* We need to set autoincrement mode for 16 bit writes */ data[0] |= DAC33_I2C_ADDR_AUTOINC; ret = codec->hw_write(codec->control_data, data, 3); if (ret != 3) dev_err(codec->dev, "Write failed (%d)\n", ret); else ret = 0; } return ret; } static void dac33_init_chip(struct snd_soc_codec *codec) { struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); if (unlikely(!dac33->chip_power)) return; /* A : DAC sample rate Fsref/1.5 */ dac33_write(codec, DAC33_DAC_CTRL_A, DAC33_DACRATE(0)); /* B : DAC src=normal, not muted */ dac33_write(codec, DAC33_DAC_CTRL_B, DAC33_DACSRCR_RIGHT | DAC33_DACSRCL_LEFT); /* C : (defaults) */ dac33_write(codec, DAC33_DAC_CTRL_C, 0x00); /* 73 : volume soft stepping control, clock source = internal osc (?) */ dac33_write(codec, DAC33_ANA_VOL_SOFT_STEP_CTRL, DAC33_VOLCLKEN); /* Restore only selected registers (gains mostly) */ dac33_write(codec, DAC33_LDAC_DIG_VOL_CTRL, dac33_read_reg_cache(codec, DAC33_LDAC_DIG_VOL_CTRL)); dac33_write(codec, DAC33_RDAC_DIG_VOL_CTRL, dac33_read_reg_cache(codec, DAC33_RDAC_DIG_VOL_CTRL)); dac33_write(codec, DAC33_LINEL_TO_LLO_VOL, dac33_read_reg_cache(codec, DAC33_LINEL_TO_LLO_VOL)); dac33_write(codec, DAC33_LINER_TO_RLO_VOL, dac33_read_reg_cache(codec, DAC33_LINER_TO_RLO_VOL)); dac33_write(codec, DAC33_OUT_AMP_CTRL, dac33_read_reg_cache(codec, DAC33_OUT_AMP_CTRL)); dac33_write(codec, DAC33_LDAC_PWR_CTRL, dac33_read_reg_cache(codec, DAC33_LDAC_PWR_CTRL)); dac33_write(codec, DAC33_RDAC_PWR_CTRL, dac33_read_reg_cache(codec, DAC33_RDAC_PWR_CTRL)); } static inline int dac33_read_id(struct snd_soc_codec *codec) { int i, ret = 0; u8 reg; for (i = 0; i < 3; i++) { ret = dac33_read(codec, DAC33_DEVICE_ID_MSB + i, &reg); if (ret < 0) break; } return ret; } static inline void dac33_soft_power(struct snd_soc_codec *codec, int power) { u8 reg; reg = dac33_read_reg_cache(codec, DAC33_PWR_CTRL); if (power) reg |= DAC33_PDNALLB; else reg &= ~(DAC33_PDNALLB | DAC33_OSCPDNB | DAC33_DACRPDNB | DAC33_DACLPDNB); dac33_write(codec, DAC33_PWR_CTRL, reg); } static inline void dac33_disable_digital(struct snd_soc_codec *codec) { u8 reg; /* Stop the DAI clock */ reg = dac33_read_reg_cache(codec, DAC33_SER_AUDIOIF_CTRL_B); reg &= ~DAC33_BCLKON; dac33_write(codec, DAC33_SER_AUDIOIF_CTRL_B, reg); /* Power down the Oscillator, and DACs */ reg = dac33_read_reg_cache(codec, DAC33_PWR_CTRL); reg &= ~(DAC33_OSCPDNB | DAC33_DACRPDNB | DAC33_DACLPDNB); dac33_write(codec, DAC33_PWR_CTRL, reg); } static int dac33_hard_power(struct snd_soc_codec *codec, int power) { struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); int ret = 0; mutex_lock(&dac33->mutex); /* Safety check */ if (unlikely(power == dac33->chip_power)) { dev_dbg(codec->dev, "Trying to set the same power state: %s\n", power ? "ON" : "OFF"); goto exit; } if (power) { ret = regulator_bulk_enable(ARRAY_SIZE(dac33->supplies), dac33->supplies); if (ret != 0) { dev_err(codec->dev, "Failed to enable supplies: %d\n", ret); goto exit; } if (dac33->power_gpio >= 0) gpio_set_value(dac33->power_gpio, 1); dac33->chip_power = 1; } else { dac33_soft_power(codec, 0); if (dac33->power_gpio >= 0) gpio_set_value(dac33->power_gpio, 0); ret = regulator_bulk_disable(ARRAY_SIZE(dac33->supplies), dac33->supplies); if (ret != 0) { dev_err(codec->dev, "Failed to disable supplies: %d\n", ret); goto exit; } dac33->chip_power = 0; } exit: mutex_unlock(&dac33->mutex); return ret; } static int dac33_playback_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(w->codec); switch (event) { case SND_SOC_DAPM_PRE_PMU: if (likely(dac33->substream)) { dac33_calculate_times(dac33->substream); dac33_prepare_chip(dac33->substream); } break; case SND_SOC_DAPM_POST_PMD: dac33_disable_digital(w->codec); break; } return 0; } static int dac33_get_fifo_mode(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); ucontrol->value.integer.value[0] = dac33->fifo_mode; return 0; } static int dac33_set_fifo_mode(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); int ret = 0; if (dac33->fifo_mode == ucontrol->value.integer.value[0]) return 0; /* Do not allow changes while stream is running*/ if (codec->active) return -EPERM; if (ucontrol->value.integer.value[0] < 0 || ucontrol->value.integer.value[0] >= DAC33_FIFO_LAST_MODE) ret = -EINVAL; else dac33->fifo_mode = ucontrol->value.integer.value[0]; return ret; } /* Codec operation modes */ static const char *dac33_fifo_mode_texts[] = { "Bypass", "Mode 1", "Mode 7" }; static const struct soc_enum dac33_fifo_mode_enum = SOC_ENUM_SINGLE_EXT(ARRAY_SIZE(dac33_fifo_mode_texts), dac33_fifo_mode_texts); /* L/R Line Output Gain */ static const char *lr_lineout_gain_texts[] = { "Line -12dB DAC 0dB", "Line -6dB DAC 6dB", "Line 0dB DAC 12dB", "Line 6dB DAC 18dB", }; static const struct soc_enum l_lineout_gain_enum = SOC_ENUM_SINGLE(DAC33_LDAC_PWR_CTRL, 0, ARRAY_SIZE(lr_lineout_gain_texts), lr_lineout_gain_texts); static const struct soc_enum r_lineout_gain_enum = SOC_ENUM_SINGLE(DAC33_RDAC_PWR_CTRL, 0, ARRAY_SIZE(lr_lineout_gain_texts), lr_lineout_gain_texts); /* * DACL/R digital volume control: * from 0 dB to -63.5 in 0.5 dB steps * Need to be inverted later on: * 0x00 == 0 dB * 0x7f == -63.5 dB */ static DECLARE_TLV_DB_SCALE(dac_digivol_tlv, -6350, 50, 0); static const struct snd_kcontrol_new dac33_snd_controls[] = { SOC_DOUBLE_R_TLV("DAC Digital Playback Volume", DAC33_LDAC_DIG_VOL_CTRL, DAC33_RDAC_DIG_VOL_CTRL, 0, 0x7f, 1, dac_digivol_tlv), SOC_DOUBLE_R("DAC Digital Playback Switch", DAC33_LDAC_DIG_VOL_CTRL, DAC33_RDAC_DIG_VOL_CTRL, 7, 1, 1), SOC_DOUBLE_R("Line to Line Out Volume", DAC33_LINEL_TO_LLO_VOL, DAC33_LINER_TO_RLO_VOL, 0, 127, 1), SOC_ENUM("Left Line Output Gain", l_lineout_gain_enum), SOC_ENUM("Right Line Output Gain", r_lineout_gain_enum), }; static const struct snd_kcontrol_new dac33_mode_snd_controls[] = { SOC_ENUM_EXT("FIFO Mode", dac33_fifo_mode_enum, dac33_get_fifo_mode, dac33_set_fifo_mode), }; /* Analog bypass */ static const struct snd_kcontrol_new dac33_dapm_abypassl_control = SOC_DAPM_SINGLE("Switch", DAC33_LINEL_TO_LLO_VOL, 7, 1, 1); static const struct snd_kcontrol_new dac33_dapm_abypassr_control = SOC_DAPM_SINGLE("Switch", DAC33_LINER_TO_RLO_VOL, 7, 1, 1); /* LOP L/R invert selection */ static const char *dac33_lr_lom_texts[] = {"DAC", "LOP"}; static const struct soc_enum dac33_left_lom_enum = SOC_ENUM_SINGLE(DAC33_OUT_AMP_CTRL, 3, ARRAY_SIZE(dac33_lr_lom_texts), dac33_lr_lom_texts); static const struct snd_kcontrol_new dac33_dapm_left_lom_control = SOC_DAPM_ENUM("Route", dac33_left_lom_enum); static const struct soc_enum dac33_right_lom_enum = SOC_ENUM_SINGLE(DAC33_OUT_AMP_CTRL, 2, ARRAY_SIZE(dac33_lr_lom_texts), dac33_lr_lom_texts); static const struct snd_kcontrol_new dac33_dapm_right_lom_control = SOC_DAPM_ENUM("Route", dac33_right_lom_enum); static const struct snd_soc_dapm_widget dac33_dapm_widgets[] = { SND_SOC_DAPM_OUTPUT("LEFT_LO"), SND_SOC_DAPM_OUTPUT("RIGHT_LO"), SND_SOC_DAPM_INPUT("LINEL"), SND_SOC_DAPM_INPUT("LINER"), SND_SOC_DAPM_DAC("DACL", "Left Playback", SND_SOC_NOPM, 0, 0), SND_SOC_DAPM_DAC("DACR", "Right Playback", SND_SOC_NOPM, 0, 0), /* Analog bypass */ SND_SOC_DAPM_SWITCH("Analog Left Bypass", SND_SOC_NOPM, 0, 0, &dac33_dapm_abypassl_control), SND_SOC_DAPM_SWITCH("Analog Right Bypass", SND_SOC_NOPM, 0, 0, &dac33_dapm_abypassr_control), SND_SOC_DAPM_MUX("Left LOM Inverted From", SND_SOC_NOPM, 0, 0, &dac33_dapm_left_lom_control), SND_SOC_DAPM_MUX("Right LOM Inverted From", SND_SOC_NOPM, 0, 0, &dac33_dapm_right_lom_control), /* * For DAPM path, when only the anlog bypass path is enabled, and the * LOP inverted from the corresponding DAC side. * This is needed, so we can attach the DAC power supply in this case. */ SND_SOC_DAPM_PGA("Left Bypass PGA", SND_SOC_NOPM, 0, 0, NULL, 0), SND_SOC_DAPM_PGA("Right Bypass PGA", SND_SOC_NOPM, 0, 0, NULL, 0), SND_SOC_DAPM_REG(snd_soc_dapm_mixer, "Output Left Amplifier", DAC33_OUT_AMP_PWR_CTRL, 6, 3, 3, 0), SND_SOC_DAPM_REG(snd_soc_dapm_mixer, "Output Right Amplifier", DAC33_OUT_AMP_PWR_CTRL, 4, 3, 3, 0), SND_SOC_DAPM_SUPPLY("Left DAC Power", DAC33_LDAC_PWR_CTRL, 2, 0, NULL, 0), SND_SOC_DAPM_SUPPLY("Right DAC Power", DAC33_RDAC_PWR_CTRL, 2, 0, NULL, 0), SND_SOC_DAPM_SUPPLY("Codec Power", DAC33_PWR_CTRL, 4, 0, NULL, 0), SND_SOC_DAPM_PRE("Pre Playback", dac33_playback_event), SND_SOC_DAPM_POST("Post Playback", dac33_playback_event), }; static const struct snd_soc_dapm_route audio_map[] = { /* Analog bypass */ {"Analog Left Bypass", "Switch", "LINEL"}, {"Analog Right Bypass", "Switch", "LINER"}, {"Output Left Amplifier", NULL, "DACL"}, {"Output Right Amplifier", NULL, "DACR"}, {"Left Bypass PGA", NULL, "Analog Left Bypass"}, {"Right Bypass PGA", NULL, "Analog Right Bypass"}, {"Left LOM Inverted From", "DAC", "Left Bypass PGA"}, {"Right LOM Inverted From", "DAC", "Right Bypass PGA"}, {"Left LOM Inverted From", "LOP", "Analog Left Bypass"}, {"Right LOM Inverted From", "LOP", "Analog Right Bypass"}, {"Output Left Amplifier", NULL, "Left LOM Inverted From"}, {"Output Right Amplifier", NULL, "Right LOM Inverted From"}, {"DACL", NULL, "Left DAC Power"}, {"DACR", NULL, "Right DAC Power"}, {"Left Bypass PGA", NULL, "Left DAC Power"}, {"Right Bypass PGA", NULL, "Right DAC Power"}, /* output */ {"LEFT_LO", NULL, "Output Left Amplifier"}, {"RIGHT_LO", NULL, "Output Right Amplifier"}, {"LEFT_LO", NULL, "Codec Power"}, {"RIGHT_LO", NULL, "Codec Power"}, }; static int dac33_set_bias_level(struct snd_soc_codec *codec, enum snd_soc_bias_level level) { int ret; switch (level) { case SND_SOC_BIAS_ON: break; case SND_SOC_BIAS_PREPARE: break; case SND_SOC_BIAS_STANDBY: if (codec->dapm.bias_level == SND_SOC_BIAS_OFF) { /* Coming from OFF, switch on the codec */ ret = dac33_hard_power(codec, 1); if (ret != 0) return ret; dac33_init_chip(codec); } break; case SND_SOC_BIAS_OFF: /* Do not power off, when the codec is already off */ if (codec->dapm.bias_level == SND_SOC_BIAS_OFF) return 0; ret = dac33_hard_power(codec, 0); if (ret != 0) return ret; break; } codec->dapm.bias_level = level; return 0; } static inline void dac33_prefill_handler(struct tlv320dac33_priv *dac33) { struct snd_soc_codec *codec = dac33->codec; unsigned int delay; unsigned long flags; switch (dac33->fifo_mode) { case DAC33_FIFO_MODE1: dac33_write16(codec, DAC33_NSAMPLE_MSB, DAC33_THRREG(dac33->nsample)); /* Take the timestamps */ spin_lock_irqsave(&dac33->lock, flags); dac33->t_stamp2 = ktime_to_us(ktime_get()); dac33->t_stamp1 = dac33->t_stamp2; spin_unlock_irqrestore(&dac33->lock, flags); dac33_write16(codec, DAC33_PREFILL_MSB, DAC33_THRREG(dac33->alarm_threshold)); /* Enable Alarm Threshold IRQ with a delay */ delay = SAMPLES_TO_US(dac33->burst_rate, dac33->alarm_threshold) + 1000; usleep_range(delay, delay + 500); dac33_write(codec, DAC33_FIFO_IRQ_MASK, DAC33_MAT); break; case DAC33_FIFO_MODE7: /* Take the timestamp */ spin_lock_irqsave(&dac33->lock, flags); dac33->t_stamp1 = ktime_to_us(ktime_get()); /* Move back the timestamp with drain time */ dac33->t_stamp1 -= dac33->mode7_us_to_lthr; spin_unlock_irqrestore(&dac33->lock, flags); dac33_write16(codec, DAC33_PREFILL_MSB, DAC33_THRREG(DAC33_MODE7_MARGIN)); /* Enable Upper Threshold IRQ */ dac33_write(codec, DAC33_FIFO_IRQ_MASK, DAC33_MUT); break; default: dev_warn(codec->dev, "Unhandled FIFO mode: %d\n", dac33->fifo_mode); break; } } static inline void dac33_playback_handler(struct tlv320dac33_priv *dac33) { struct snd_soc_codec *codec = dac33->codec; unsigned long flags; switch (dac33->fifo_mode) { case DAC33_FIFO_MODE1: /* Take the timestamp */ spin_lock_irqsave(&dac33->lock, flags); dac33->t_stamp2 = ktime_to_us(ktime_get()); spin_unlock_irqrestore(&dac33->lock, flags); dac33_write16(codec, DAC33_NSAMPLE_MSB, DAC33_THRREG(dac33->nsample)); break; case DAC33_FIFO_MODE7: /* At the moment we are not using interrupts in mode7 */ break; default: dev_warn(codec->dev, "Unhandled FIFO mode: %d\n", dac33->fifo_mode); break; } } static void dac33_work(struct work_struct *work) { struct snd_soc_codec *codec; struct tlv320dac33_priv *dac33; u8 reg; dac33 = container_of(work, struct tlv320dac33_priv, work); codec = dac33->codec; mutex_lock(&dac33->mutex); switch (dac33->state) { case DAC33_PREFILL: dac33->state = DAC33_PLAYBACK; dac33_prefill_handler(dac33); break; case DAC33_PLAYBACK: dac33_playback_handler(dac33); break; case DAC33_IDLE: break; case DAC33_FLUSH: dac33->state = DAC33_IDLE; /* Mask all interrupts from dac33 */ dac33_write(codec, DAC33_FIFO_IRQ_MASK, 0); /* flush fifo */ reg = dac33_read_reg_cache(codec, DAC33_FIFO_CTRL_A); reg |= DAC33_FIFOFLUSH; dac33_write(codec, DAC33_FIFO_CTRL_A, reg); break; } mutex_unlock(&dac33->mutex); } static irqreturn_t dac33_interrupt_handler(int irq, void *dev) { struct snd_soc_codec *codec = dev; struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); unsigned long flags; spin_lock_irqsave(&dac33->lock, flags); dac33->t_stamp1 = ktime_to_us(ktime_get()); spin_unlock_irqrestore(&dac33->lock, flags); /* Do not schedule the workqueue in Mode7 */ if (dac33->fifo_mode != DAC33_FIFO_MODE7) queue_work(dac33->dac33_wq, &dac33->work); return IRQ_HANDLED; } static void dac33_oscwait(struct snd_soc_codec *codec) { int timeout = 60; u8 reg; do { usleep_range(1000, 2000); dac33_read(codec, DAC33_INT_OSC_STATUS, &reg); } while (((reg & 0x03) != DAC33_OSCSTATUS_NORMAL) && timeout--); if ((reg & 0x03) != DAC33_OSCSTATUS_NORMAL) dev_err(codec->dev, "internal oscillator calibration failed\n"); } static int dac33_startup(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_codec *codec = rtd->codec; struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); /* Stream started, save the substream pointer */ dac33->substream = substream; return 0; } static void dac33_shutdown(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_codec *codec = rtd->codec; struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); dac33->substream = NULL; } #define CALC_BURST_RATE(bclkdiv, bclk_per_sample) \ (BURST_BASEFREQ_HZ / bclkdiv / bclk_per_sample) static int dac33_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_codec *codec = rtd->codec; struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); /* Check parameters for validity */ switch (params_rate(params)) { case 44100: case 48000: break; default: dev_err(codec->dev, "unsupported rate %d\n", params_rate(params)); return -EINVAL; } switch (params_format(params)) { case SNDRV_PCM_FORMAT_S16_LE: dac33->fifo_size = DAC33_FIFO_SIZE_16BIT; dac33->burst_rate = CALC_BURST_RATE(dac33->burst_bclkdiv, 32); break; case SNDRV_PCM_FORMAT_S32_LE: dac33->fifo_size = DAC33_FIFO_SIZE_24BIT; dac33->burst_rate = CALC_BURST_RATE(dac33->burst_bclkdiv, 64); break; default: dev_err(codec->dev, "unsupported format %d\n", params_format(params)); return -EINVAL; } return 0; } #define CALC_OSCSET(rate, refclk) ( \ ((((rate * 10000) / refclk) * 4096) + 7000) / 10000) #define CALC_RATIOSET(rate, refclk) ( \ ((((refclk * 100000) / rate) * 16384) + 50000) / 100000) /* * tlv320dac33 is strict on the sequence of the register writes, if the register * writes happens in different order, than dac33 might end up in unknown state. * Use the known, working sequence of register writes to initialize the dac33. */ static int dac33_prepare_chip(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_codec *codec = rtd->codec; struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); unsigned int oscset, ratioset, pwr_ctrl, reg_tmp; u8 aictrl_a, aictrl_b, fifoctrl_a; switch (substream->runtime->rate) { case 44100: case 48000: oscset = CALC_OSCSET(substream->runtime->rate, dac33->refclk); ratioset = CALC_RATIOSET(substream->runtime->rate, dac33->refclk); break; default: dev_err(codec->dev, "unsupported rate %d\n", substream->runtime->rate); return -EINVAL; } aictrl_a = dac33_read_reg_cache(codec, DAC33_SER_AUDIOIF_CTRL_A); aictrl_a &= ~(DAC33_NCYCL_MASK | DAC33_WLEN_MASK); /* Read FIFO control A, and clear FIFO flush bit */ fifoctrl_a = dac33_read_reg_cache(codec, DAC33_FIFO_CTRL_A); fifoctrl_a &= ~DAC33_FIFOFLUSH; fifoctrl_a &= ~DAC33_WIDTH; switch (substream->runtime->format) { case SNDRV_PCM_FORMAT_S16_LE: aictrl_a |= (DAC33_NCYCL_16 | DAC33_WLEN_16); fifoctrl_a |= DAC33_WIDTH; break; case SNDRV_PCM_FORMAT_S32_LE: aictrl_a |= (DAC33_NCYCL_32 | DAC33_WLEN_24); break; default: dev_err(codec->dev, "unsupported format %d\n", substream->runtime->format); return -EINVAL; } mutex_lock(&dac33->mutex); if (!dac33->chip_power) { /* * Chip is not powered yet. * Do the init in the dac33_set_bias_level later. */ mutex_unlock(&dac33->mutex); return 0; } dac33_soft_power(codec, 0); dac33_soft_power(codec, 1); reg_tmp = dac33_read_reg_cache(codec, DAC33_INT_OSC_CTRL); dac33_write(codec, DAC33_INT_OSC_CTRL, reg_tmp); /* Write registers 0x08 and 0x09 (MSB, LSB) */ dac33_write16(codec, DAC33_INT_OSC_FREQ_RAT_A, oscset); /* OSC calibration time */ dac33_write(codec, DAC33_CALIB_TIME, 96); /* adjustment treshold & step */ dac33_write(codec, DAC33_INT_OSC_CTRL_B, DAC33_ADJTHRSHLD(2) | DAC33_ADJSTEP(1)); /* div=4 / gain=1 / div */ dac33_write(codec, DAC33_INT_OSC_CTRL_C, DAC33_REFDIV(4)); pwr_ctrl = dac33_read_reg_cache(codec, DAC33_PWR_CTRL); pwr_ctrl |= DAC33_OSCPDNB | DAC33_DACRPDNB | DAC33_DACLPDNB; dac33_write(codec, DAC33_PWR_CTRL, pwr_ctrl); dac33_oscwait(codec); if (dac33->fifo_mode) { /* Generic for all FIFO modes */ /* 50-51 : ASRC Control registers */ dac33_write(codec, DAC33_ASRC_CTRL_A, DAC33_SRCLKDIV(1)); dac33_write(codec, DAC33_ASRC_CTRL_B, 1); /* ??? */ /* Write registers 0x34 and 0x35 (MSB, LSB) */ dac33_write16(codec, DAC33_SRC_REF_CLK_RATIO_A, ratioset); /* Set interrupts to high active */ dac33_write(codec, DAC33_INTP_CTRL_A, DAC33_INTPM_AHIGH); } else { /* FIFO bypass mode */ /* 50-51 : ASRC Control registers */ dac33_write(codec, DAC33_ASRC_CTRL_A, DAC33_SRCBYP); dac33_write(codec, DAC33_ASRC_CTRL_B, 0); /* ??? */ } /* Interrupt behaviour configuration */ switch (dac33->fifo_mode) { case DAC33_FIFO_MODE1: dac33_write(codec, DAC33_FIFO_IRQ_MODE_B, DAC33_ATM(DAC33_FIFO_IRQ_MODE_LEVEL)); break; case DAC33_FIFO_MODE7: dac33_write(codec, DAC33_FIFO_IRQ_MODE_A, DAC33_UTM(DAC33_FIFO_IRQ_MODE_LEVEL)); break; default: /* in FIFO bypass mode, the interrupts are not used */ break; } aictrl_b = dac33_read_reg_cache(codec, DAC33_SER_AUDIOIF_CTRL_B); switch (dac33->fifo_mode) { case DAC33_FIFO_MODE1: /* * For mode1: * Disable the FIFO bypass (Enable the use of FIFO) * Select nSample mode * BCLK is only running when data is needed by DAC33 */ fifoctrl_a &= ~DAC33_FBYPAS; fifoctrl_a &= ~DAC33_FAUTO; if (dac33->keep_bclk) aictrl_b |= DAC33_BCLKON; else aictrl_b &= ~DAC33_BCLKON; break; case DAC33_FIFO_MODE7: /* * For mode1: * Disable the FIFO bypass (Enable the use of FIFO) * Select Threshold mode * BCLK is only running when data is needed by DAC33 */ fifoctrl_a &= ~DAC33_FBYPAS; fifoctrl_a |= DAC33_FAUTO; if (dac33->keep_bclk) aictrl_b |= DAC33_BCLKON; else aictrl_b &= ~DAC33_BCLKON; break; default: /* * For FIFO bypass mode: * Enable the FIFO bypass (Disable the FIFO use) * Set the BCLK as continuous */ fifoctrl_a |= DAC33_FBYPAS; aictrl_b |= DAC33_BCLKON; break; } dac33_write(codec, DAC33_FIFO_CTRL_A, fifoctrl_a); dac33_write(codec, DAC33_SER_AUDIOIF_CTRL_A, aictrl_a); dac33_write(codec, DAC33_SER_AUDIOIF_CTRL_B, aictrl_b); /* * BCLK divide ratio * 0: 1.5 * 1: 1 * 2: 2 * ... * 254: 254 * 255: 255 */ if (dac33->fifo_mode) dac33_write(codec, DAC33_SER_AUDIOIF_CTRL_C, dac33->burst_bclkdiv); else if (substream->runtime->format == SNDRV_PCM_FORMAT_S16_LE) dac33_write(codec, DAC33_SER_AUDIOIF_CTRL_C, 32); else dac33_write(codec, DAC33_SER_AUDIOIF_CTRL_C, 16); switch (dac33->fifo_mode) { case DAC33_FIFO_MODE1: dac33_write16(codec, DAC33_ATHR_MSB, DAC33_THRREG(dac33->alarm_threshold)); break; case DAC33_FIFO_MODE7: /* * Configure the threshold levels, and leave 10 sample space * at the bottom, and also at the top of the FIFO */ dac33_write16(codec, DAC33_UTHR_MSB, DAC33_THRREG(dac33->uthr)); dac33_write16(codec, DAC33_LTHR_MSB, DAC33_THRREG(DAC33_MODE7_MARGIN)); break; default: break; } mutex_unlock(&dac33->mutex); return 0; } static void dac33_calculate_times(struct snd_pcm_substream *substream) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_codec *codec = rtd->codec; struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); unsigned int period_size = substream->runtime->period_size; unsigned int rate = substream->runtime->rate; unsigned int nsample_limit; /* In bypass mode we don't need to calculate */ if (!dac33->fifo_mode) return; switch (dac33->fifo_mode) { case DAC33_FIFO_MODE1: /* Number of samples under i2c latency */ dac33->alarm_threshold = US_TO_SAMPLES(rate, dac33->mode1_latency); nsample_limit = dac33->fifo_size - dac33->alarm_threshold; if (period_size <= dac33->alarm_threshold) /* * Configure nSamaple to number of periods, * which covers the latency requironment. */ dac33->nsample = period_size * ((dac33->alarm_threshold / period_size) + (dac33->alarm_threshold % period_size ? 1 : 0)); else if (period_size > nsample_limit) dac33->nsample = nsample_limit; else dac33->nsample = period_size; dac33->mode1_us_burst = SAMPLES_TO_US(dac33->burst_rate, dac33->nsample); dac33->t_stamp1 = 0; dac33->t_stamp2 = 0; break; case DAC33_FIFO_MODE7: dac33->uthr = UTHR_FROM_PERIOD_SIZE(period_size, rate, dac33->burst_rate) + 9; if (dac33->uthr > (dac33->fifo_size - DAC33_MODE7_MARGIN)) dac33->uthr = dac33->fifo_size - DAC33_MODE7_MARGIN; if (dac33->uthr < (DAC33_MODE7_MARGIN + 10)) dac33->uthr = (DAC33_MODE7_MARGIN + 10); dac33->mode7_us_to_lthr = SAMPLES_TO_US(substream->runtime->rate, dac33->uthr - DAC33_MODE7_MARGIN + 1); dac33->t_stamp1 = 0; break; default: break; } } static int dac33_pcm_trigger(struct snd_pcm_substream *substream, int cmd, struct snd_soc_dai *dai) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_codec *codec = rtd->codec; struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); int ret = 0; switch (cmd) { case SNDRV_PCM_TRIGGER_START: case SNDRV_PCM_TRIGGER_RESUME: case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: if (dac33->fifo_mode) { dac33->state = DAC33_PREFILL; queue_work(dac33->dac33_wq, &dac33->work); } break; case SNDRV_PCM_TRIGGER_STOP: case SNDRV_PCM_TRIGGER_SUSPEND: case SNDRV_PCM_TRIGGER_PAUSE_PUSH: if (dac33->fifo_mode) { dac33->state = DAC33_FLUSH; queue_work(dac33->dac33_wq, &dac33->work); } break; default: ret = -EINVAL; } return ret; } static snd_pcm_sframes_t dac33_dai_delay( struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_codec *codec = rtd->codec; struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); unsigned long long t0, t1, t_now; unsigned int time_delta, uthr; int samples_out, samples_in, samples; snd_pcm_sframes_t delay = 0; unsigned long flags; switch (dac33->fifo_mode) { case DAC33_FIFO_BYPASS: break; case DAC33_FIFO_MODE1: spin_lock_irqsave(&dac33->lock, flags); t0 = dac33->t_stamp1; t1 = dac33->t_stamp2; spin_unlock_irqrestore(&dac33->lock, flags); t_now = ktime_to_us(ktime_get()); /* We have not started to fill the FIFO yet, delay is 0 */ if (!t1) goto out; if (t0 > t1) { /* * Phase 1: * After Alarm threshold, and before nSample write */ time_delta = t_now - t0; samples_out = time_delta ? US_TO_SAMPLES( substream->runtime->rate, time_delta) : 0; if (likely(dac33->alarm_threshold > samples_out)) delay = dac33->alarm_threshold - samples_out; else delay = 0; } else if ((t_now - t1) <= dac33->mode1_us_burst) { /* * Phase 2: * After nSample write (during burst operation) */ time_delta = t_now - t0; samples_out = time_delta ? US_TO_SAMPLES( substream->runtime->rate, time_delta) : 0; time_delta = t_now - t1; samples_in = time_delta ? US_TO_SAMPLES( dac33->burst_rate, time_delta) : 0; samples = dac33->alarm_threshold; samples += (samples_in - samples_out); if (likely(samples > 0)) delay = samples; else delay = 0; } else { /* * Phase 3: * After burst operation, before next alarm threshold */ time_delta = t_now - t0; samples_out = time_delta ? US_TO_SAMPLES( substream->runtime->rate, time_delta) : 0; samples_in = dac33->nsample; samples = dac33->alarm_threshold; samples += (samples_in - samples_out); if (likely(samples > 0)) delay = samples > dac33->fifo_size ? dac33->fifo_size : samples; else delay = 0; } break; case DAC33_FIFO_MODE7: spin_lock_irqsave(&dac33->lock, flags); t0 = dac33->t_stamp1; uthr = dac33->uthr; spin_unlock_irqrestore(&dac33->lock, flags); t_now = ktime_to_us(ktime_get()); /* We have not started to fill the FIFO yet, delay is 0 */ if (!t0) goto out; if (t_now <= t0) { /* * Either the timestamps are messed or equal. Report * maximum delay */ delay = uthr; goto out; } time_delta = t_now - t0; if (time_delta <= dac33->mode7_us_to_lthr) { /* * Phase 1: * After burst (draining phase) */ samples_out = US_TO_SAMPLES( substream->runtime->rate, time_delta); if (likely(uthr > samples_out)) delay = uthr - samples_out; else delay = 0; } else { /* * Phase 2: * During burst operation */ time_delta = time_delta - dac33->mode7_us_to_lthr; samples_out = US_TO_SAMPLES( substream->runtime->rate, time_delta); samples_in = US_TO_SAMPLES( dac33->burst_rate, time_delta); delay = DAC33_MODE7_MARGIN + samples_in - samples_out; if (unlikely(delay > uthr)) delay = uthr; } break; default: dev_warn(codec->dev, "Unhandled FIFO mode: %d\n", dac33->fifo_mode); break; } out: return delay; } static int dac33_set_dai_sysclk(struct snd_soc_dai *codec_dai, int clk_id, unsigned int freq, int dir) { struct snd_soc_codec *codec = codec_dai->codec; struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); u8 ioc_reg, asrcb_reg; ioc_reg = dac33_read_reg_cache(codec, DAC33_INT_OSC_CTRL); asrcb_reg = dac33_read_reg_cache(codec, DAC33_ASRC_CTRL_B); switch (clk_id) { case TLV320DAC33_MCLK: ioc_reg |= DAC33_REFSEL; asrcb_reg |= DAC33_SRCREFSEL; break; case TLV320DAC33_SLEEPCLK: ioc_reg &= ~DAC33_REFSEL; asrcb_reg &= ~DAC33_SRCREFSEL; break; default: dev_err(codec->dev, "Invalid clock ID (%d)\n", clk_id); break; } dac33->refclk = freq; dac33_write_reg_cache(codec, DAC33_INT_OSC_CTRL, ioc_reg); dac33_write_reg_cache(codec, DAC33_ASRC_CTRL_B, asrcb_reg); return 0; } static int dac33_set_dai_fmt(struct snd_soc_dai *codec_dai, unsigned int fmt) { struct snd_soc_codec *codec = codec_dai->codec; struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); u8 aictrl_a, aictrl_b; aictrl_a = dac33_read_reg_cache(codec, DAC33_SER_AUDIOIF_CTRL_A); aictrl_b = dac33_read_reg_cache(codec, DAC33_SER_AUDIOIF_CTRL_B); /* set master/slave audio interface */ switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) { case SND_SOC_DAIFMT_CBM_CFM: /* Codec Master */ aictrl_a |= (DAC33_MSBCLK | DAC33_MSWCLK); break; case SND_SOC_DAIFMT_CBS_CFS: /* Codec Slave */ if (dac33->fifo_mode) { dev_err(codec->dev, "FIFO mode requires master mode\n"); return -EINVAL; } else aictrl_a &= ~(DAC33_MSBCLK | DAC33_MSWCLK); break; default: return -EINVAL; } aictrl_a &= ~DAC33_AFMT_MASK; switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { case SND_SOC_DAIFMT_I2S: aictrl_a |= DAC33_AFMT_I2S; break; case SND_SOC_DAIFMT_DSP_A: aictrl_a |= DAC33_AFMT_DSP; aictrl_b &= ~DAC33_DATA_DELAY_MASK; aictrl_b |= DAC33_DATA_DELAY(0); break; case SND_SOC_DAIFMT_RIGHT_J: aictrl_a |= DAC33_AFMT_RIGHT_J; break; case SND_SOC_DAIFMT_LEFT_J: aictrl_a |= DAC33_AFMT_LEFT_J; break; default: dev_err(codec->dev, "Unsupported format (%u)\n", fmt & SND_SOC_DAIFMT_FORMAT_MASK); return -EINVAL; } dac33_write_reg_cache(codec, DAC33_SER_AUDIOIF_CTRL_A, aictrl_a); dac33_write_reg_cache(codec, DAC33_SER_AUDIOIF_CTRL_B, aictrl_b); return 0; } static int dac33_soc_probe(struct snd_soc_codec *codec) { struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); int ret = 0; codec->control_data = dac33->control_data; codec->hw_write = (hw_write_t) i2c_master_send; dac33->codec = codec; /* Read the tlv320dac33 ID registers */ ret = dac33_hard_power(codec, 1); if (ret != 0) { dev_err(codec->dev, "Failed to power up codec: %d\n", ret); goto err_power; } ret = dac33_read_id(codec); dac33_hard_power(codec, 0); if (ret < 0) { dev_err(codec->dev, "Failed to read chip ID: %d\n", ret); ret = -ENODEV; goto err_power; } /* Check if the IRQ number is valid and request it */ if (dac33->irq >= 0) { ret = request_irq(dac33->irq, dac33_interrupt_handler, IRQF_TRIGGER_RISING, codec->name, codec); if (ret < 0) { dev_err(codec->dev, "Could not request IRQ%d (%d)\n", dac33->irq, ret); dac33->irq = -1; } if (dac33->irq != -1) { /* Setup work queue */ dac33->dac33_wq = create_singlethread_workqueue("tlv320dac33"); if (dac33->dac33_wq == NULL) { free_irq(dac33->irq, codec); return -ENOMEM; } INIT_WORK(&dac33->work, dac33_work); } } /* Only add the FIFO controls, if we have valid IRQ number */ if (dac33->irq >= 0) snd_soc_add_codec_controls(codec, dac33_mode_snd_controls, ARRAY_SIZE(dac33_mode_snd_controls)); err_power: return ret; } static int dac33_soc_remove(struct snd_soc_codec *codec) { struct tlv320dac33_priv *dac33 = snd_soc_codec_get_drvdata(codec); dac33_set_bias_level(codec, SND_SOC_BIAS_OFF); if (dac33->irq >= 0) { free_irq(dac33->irq, dac33->codec); destroy_workqueue(dac33->dac33_wq); } return 0; } static int dac33_soc_suspend(struct snd_soc_codec *codec) { dac33_set_bias_level(codec, SND_SOC_BIAS_OFF); return 0; } static int dac33_soc_resume(struct snd_soc_codec *codec) { dac33_set_bias_level(codec, SND_SOC_BIAS_STANDBY); return 0; } static struct snd_soc_codec_driver soc_codec_dev_tlv320dac33 = { .read = dac33_read_reg_cache, .write = dac33_write_locked, .set_bias_level = dac33_set_bias_level, .idle_bias_off = true, .reg_cache_size = ARRAY_SIZE(dac33_reg), .reg_word_size = sizeof(u8), .reg_cache_default = dac33_reg, .probe = dac33_soc_probe, .remove = dac33_soc_remove, .suspend = dac33_soc_suspend, .resume = dac33_soc_resume, .controls = dac33_snd_controls, .num_controls = ARRAY_SIZE(dac33_snd_controls), .dapm_widgets = dac33_dapm_widgets, .num_dapm_widgets = ARRAY_SIZE(dac33_dapm_widgets), .dapm_routes = audio_map, .num_dapm_routes = ARRAY_SIZE(audio_map), }; #define DAC33_RATES (SNDRV_PCM_RATE_44100 | \ SNDRV_PCM_RATE_48000) #define DAC33_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S32_LE) static const struct snd_soc_dai_ops dac33_dai_ops = { .startup = dac33_startup, .shutdown = dac33_shutdown, .hw_params = dac33_hw_params, .trigger = dac33_pcm_trigger, .delay = dac33_dai_delay, .set_sysclk = dac33_set_dai_sysclk, .set_fmt = dac33_set_dai_fmt, }; static struct snd_soc_dai_driver dac33_dai = { .name = "tlv320dac33-hifi", .playback = { .stream_name = "Playback", .channels_min = 2, .channels_max = 2, .rates = DAC33_RATES, .formats = DAC33_FORMATS, .sig_bits = 24, }, .ops = &dac33_dai_ops, }; static int __devinit dac33_i2c_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct tlv320dac33_platform_data *pdata; struct tlv320dac33_priv *dac33; int ret, i; if (client->dev.platform_data == NULL) { dev_err(&client->dev, "Platform data not set\n"); return -ENODEV; } pdata = client->dev.platform_data; dac33 = devm_kzalloc(&client->dev, sizeof(struct tlv320dac33_priv), GFP_KERNEL); if (dac33 == NULL) return -ENOMEM; dac33->control_data = client; mutex_init(&dac33->mutex); spin_lock_init(&dac33->lock); i2c_set_clientdata(client, dac33); dac33->power_gpio = pdata->power_gpio; dac33->burst_bclkdiv = pdata->burst_bclkdiv; dac33->keep_bclk = pdata->keep_bclk; dac33->mode1_latency = pdata->mode1_latency; if (!dac33->mode1_latency) dac33->mode1_latency = 10000; /* 10ms */ dac33->irq = client->irq; /* Disable FIFO use by default */ dac33->fifo_mode = DAC33_FIFO_BYPASS; /* Check if the reset GPIO number is valid and request it */ if (dac33->power_gpio >= 0) { ret = gpio_request(dac33->power_gpio, "tlv320dac33 reset"); if (ret < 0) { dev_err(&client->dev, "Failed to request reset GPIO (%d)\n", dac33->power_gpio); goto err_gpio; } gpio_direction_output(dac33->power_gpio, 0); } for (i = 0; i < ARRAY_SIZE(dac33->supplies); i++) dac33->supplies[i].supply = dac33_supply_names[i]; ret = regulator_bulk_get(&client->dev, ARRAY_SIZE(dac33->supplies), dac33->supplies); if (ret != 0) { dev_err(&client->dev, "Failed to request supplies: %d\n", ret); goto err_get; } ret = snd_soc_register_codec(&client->dev, &soc_codec_dev_tlv320dac33, &dac33_dai, 1); if (ret < 0) goto err_register; return ret; err_register: regulator_bulk_free(ARRAY_SIZE(dac33->supplies), dac33->supplies); err_get: if (dac33->power_gpio >= 0) gpio_free(dac33->power_gpio); err_gpio: return ret; } static int __devexit dac33_i2c_remove(struct i2c_client *client) { struct tlv320dac33_priv *dac33 = i2c_get_clientdata(client); if (unlikely(dac33->chip_power)) dac33_hard_power(dac33->codec, 0); if (dac33->power_gpio >= 0) gpio_free(dac33->power_gpio); regulator_bulk_free(ARRAY_SIZE(dac33->supplies), dac33->supplies); snd_soc_unregister_codec(&client->dev); return 0; } static const struct i2c_device_id tlv320dac33_i2c_id[] = { { .name = "tlv320dac33", .driver_data = 0, }, { }, }; MODULE_DEVICE_TABLE(i2c, tlv320dac33_i2c_id); static struct i2c_driver tlv320dac33_i2c_driver = { .driver = { .name = "tlv320dac33-codec", .owner = THIS_MODULE, }, .probe = dac33_i2c_probe, .remove = __devexit_p(dac33_i2c_remove), .id_table = tlv320dac33_i2c_id, }; static int __init dac33_module_init(void) { int r; r = i2c_add_driver(&tlv320dac33_i2c_driver); if (r < 0) { printk(KERN_ERR "DAC33: driver registration failed\n"); return r; } return 0; } module_init(dac33_module_init); static void __exit dac33_module_exit(void) { i2c_del_driver(&tlv320dac33_i2c_driver); } module_exit(dac33_module_exit); MODULE_DESCRIPTION("ASoC TLV320DAC33 codec driver"); MODULE_AUTHOR("Peter Ujfalusi <peter.ujfalusi@ti.com>"); MODULE_LICENSE("GPL");
gpl-2.0
ShinySide/HispAsian_Lolli
drivers/media/video/mt9v032.c
4812
21724
/* * Driver for MT9V032 CMOS Image Sensor from Micron * * Copyright (C) 2010, Laurent Pinchart <laurent.pinchart@ideasonboard.com> * * Based on the MT9M001 driver, * * Copyright (C) 2008, Guennadi Liakhovetski <kernel@pengutronix.de> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/delay.h> #include <linux/i2c.h> #include <linux/log2.h> #include <linux/mutex.h> #include <linux/slab.h> #include <linux/videodev2.h> #include <linux/v4l2-mediabus.h> #include <linux/module.h> #include <media/mt9v032.h> #include <media/v4l2-ctrls.h> #include <media/v4l2-device.h> #include <media/v4l2-subdev.h> #define MT9V032_PIXEL_ARRAY_HEIGHT 492 #define MT9V032_PIXEL_ARRAY_WIDTH 782 #define MT9V032_CHIP_VERSION 0x00 #define MT9V032_CHIP_ID_REV1 0x1311 #define MT9V032_CHIP_ID_REV3 0x1313 #define MT9V032_COLUMN_START 0x01 #define MT9V032_COLUMN_START_MIN 1 #define MT9V032_COLUMN_START_DEF 1 #define MT9V032_COLUMN_START_MAX 752 #define MT9V032_ROW_START 0x02 #define MT9V032_ROW_START_MIN 4 #define MT9V032_ROW_START_DEF 5 #define MT9V032_ROW_START_MAX 482 #define MT9V032_WINDOW_HEIGHT 0x03 #define MT9V032_WINDOW_HEIGHT_MIN 1 #define MT9V032_WINDOW_HEIGHT_DEF 480 #define MT9V032_WINDOW_HEIGHT_MAX 480 #define MT9V032_WINDOW_WIDTH 0x04 #define MT9V032_WINDOW_WIDTH_MIN 1 #define MT9V032_WINDOW_WIDTH_DEF 752 #define MT9V032_WINDOW_WIDTH_MAX 752 #define MT9V032_HORIZONTAL_BLANKING 0x05 #define MT9V032_HORIZONTAL_BLANKING_MIN 43 #define MT9V032_HORIZONTAL_BLANKING_MAX 1023 #define MT9V032_VERTICAL_BLANKING 0x06 #define MT9V032_VERTICAL_BLANKING_MIN 4 #define MT9V032_VERTICAL_BLANKING_MAX 3000 #define MT9V032_CHIP_CONTROL 0x07 #define MT9V032_CHIP_CONTROL_MASTER_MODE (1 << 3) #define MT9V032_CHIP_CONTROL_DOUT_ENABLE (1 << 7) #define MT9V032_CHIP_CONTROL_SEQUENTIAL (1 << 8) #define MT9V032_SHUTTER_WIDTH1 0x08 #define MT9V032_SHUTTER_WIDTH2 0x09 #define MT9V032_SHUTTER_WIDTH_CONTROL 0x0a #define MT9V032_TOTAL_SHUTTER_WIDTH 0x0b #define MT9V032_TOTAL_SHUTTER_WIDTH_MIN 1 #define MT9V032_TOTAL_SHUTTER_WIDTH_DEF 480 #define MT9V032_TOTAL_SHUTTER_WIDTH_MAX 32767 #define MT9V032_RESET 0x0c #define MT9V032_READ_MODE 0x0d #define MT9V032_READ_MODE_ROW_BIN_MASK (3 << 0) #define MT9V032_READ_MODE_ROW_BIN_SHIFT 0 #define MT9V032_READ_MODE_COLUMN_BIN_MASK (3 << 2) #define MT9V032_READ_MODE_COLUMN_BIN_SHIFT 2 #define MT9V032_READ_MODE_ROW_FLIP (1 << 4) #define MT9V032_READ_MODE_COLUMN_FLIP (1 << 5) #define MT9V032_READ_MODE_DARK_COLUMNS (1 << 6) #define MT9V032_READ_MODE_DARK_ROWS (1 << 7) #define MT9V032_PIXEL_OPERATION_MODE 0x0f #define MT9V032_PIXEL_OPERATION_MODE_COLOR (1 << 2) #define MT9V032_PIXEL_OPERATION_MODE_HDR (1 << 6) #define MT9V032_ANALOG_GAIN 0x35 #define MT9V032_ANALOG_GAIN_MIN 16 #define MT9V032_ANALOG_GAIN_DEF 16 #define MT9V032_ANALOG_GAIN_MAX 64 #define MT9V032_MAX_ANALOG_GAIN 0x36 #define MT9V032_MAX_ANALOG_GAIN_MAX 127 #define MT9V032_FRAME_DARK_AVERAGE 0x42 #define MT9V032_DARK_AVG_THRESH 0x46 #define MT9V032_DARK_AVG_LOW_THRESH_MASK (255 << 0) #define MT9V032_DARK_AVG_LOW_THRESH_SHIFT 0 #define MT9V032_DARK_AVG_HIGH_THRESH_MASK (255 << 8) #define MT9V032_DARK_AVG_HIGH_THRESH_SHIFT 8 #define MT9V032_ROW_NOISE_CORR_CONTROL 0x70 #define MT9V032_ROW_NOISE_CORR_ENABLE (1 << 5) #define MT9V032_ROW_NOISE_CORR_USE_BLK_AVG (1 << 7) #define MT9V032_PIXEL_CLOCK 0x74 #define MT9V032_PIXEL_CLOCK_INV_LINE (1 << 0) #define MT9V032_PIXEL_CLOCK_INV_FRAME (1 << 1) #define MT9V032_PIXEL_CLOCK_XOR_LINE (1 << 2) #define MT9V032_PIXEL_CLOCK_CONT_LINE (1 << 3) #define MT9V032_PIXEL_CLOCK_INV_PXL_CLK (1 << 4) #define MT9V032_TEST_PATTERN 0x7f #define MT9V032_TEST_PATTERN_DATA_MASK (1023 << 0) #define MT9V032_TEST_PATTERN_DATA_SHIFT 0 #define MT9V032_TEST_PATTERN_USE_DATA (1 << 10) #define MT9V032_TEST_PATTERN_GRAY_MASK (3 << 11) #define MT9V032_TEST_PATTERN_GRAY_NONE (0 << 11) #define MT9V032_TEST_PATTERN_GRAY_VERTICAL (1 << 11) #define MT9V032_TEST_PATTERN_GRAY_HORIZONTAL (2 << 11) #define MT9V032_TEST_PATTERN_GRAY_DIAGONAL (3 << 11) #define MT9V032_TEST_PATTERN_ENABLE (1 << 13) #define MT9V032_TEST_PATTERN_FLIP (1 << 14) #define MT9V032_AEC_AGC_ENABLE 0xaf #define MT9V032_AEC_ENABLE (1 << 0) #define MT9V032_AGC_ENABLE (1 << 1) #define MT9V032_THERMAL_INFO 0xc1 struct mt9v032 { struct v4l2_subdev subdev; struct media_pad pad; struct v4l2_mbus_framefmt format; struct v4l2_rect crop; struct v4l2_ctrl_handler ctrls; struct mutex power_lock; int power_count; struct mt9v032_platform_data *pdata; u16 chip_control; u16 aec_agc; }; static struct mt9v032 *to_mt9v032(struct v4l2_subdev *sd) { return container_of(sd, struct mt9v032, subdev); } static int mt9v032_read(struct i2c_client *client, const u8 reg) { s32 data = i2c_smbus_read_word_swapped(client, reg); dev_dbg(&client->dev, "%s: read 0x%04x from 0x%02x\n", __func__, data, reg); return data; } static int mt9v032_write(struct i2c_client *client, const u8 reg, const u16 data) { dev_dbg(&client->dev, "%s: writing 0x%04x to 0x%02x\n", __func__, data, reg); return i2c_smbus_write_word_swapped(client, reg, data); } static int mt9v032_set_chip_control(struct mt9v032 *mt9v032, u16 clear, u16 set) { struct i2c_client *client = v4l2_get_subdevdata(&mt9v032->subdev); u16 value = (mt9v032->chip_control & ~clear) | set; int ret; ret = mt9v032_write(client, MT9V032_CHIP_CONTROL, value); if (ret < 0) return ret; mt9v032->chip_control = value; return 0; } static int mt9v032_update_aec_agc(struct mt9v032 *mt9v032, u16 which, int enable) { struct i2c_client *client = v4l2_get_subdevdata(&mt9v032->subdev); u16 value = mt9v032->aec_agc; int ret; if (enable) value |= which; else value &= ~which; ret = mt9v032_write(client, MT9V032_AEC_AGC_ENABLE, value); if (ret < 0) return ret; mt9v032->aec_agc = value; return 0; } static int mt9v032_power_on(struct mt9v032 *mt9v032) { struct i2c_client *client = v4l2_get_subdevdata(&mt9v032->subdev); int ret; if (mt9v032->pdata->set_clock) { mt9v032->pdata->set_clock(&mt9v032->subdev, 25000000); udelay(1); } /* Reset the chip and stop data read out */ ret = mt9v032_write(client, MT9V032_RESET, 1); if (ret < 0) return ret; ret = mt9v032_write(client, MT9V032_RESET, 0); if (ret < 0) return ret; return mt9v032_write(client, MT9V032_CHIP_CONTROL, 0); } static void mt9v032_power_off(struct mt9v032 *mt9v032) { if (mt9v032->pdata->set_clock) mt9v032->pdata->set_clock(&mt9v032->subdev, 0); } static int __mt9v032_set_power(struct mt9v032 *mt9v032, bool on) { struct i2c_client *client = v4l2_get_subdevdata(&mt9v032->subdev); int ret; if (!on) { mt9v032_power_off(mt9v032); return 0; } ret = mt9v032_power_on(mt9v032); if (ret < 0) return ret; /* Configure the pixel clock polarity */ if (mt9v032->pdata && mt9v032->pdata->clk_pol) { ret = mt9v032_write(client, MT9V032_PIXEL_CLOCK, MT9V032_PIXEL_CLOCK_INV_PXL_CLK); if (ret < 0) return ret; } /* Disable the noise correction algorithm and restore the controls. */ ret = mt9v032_write(client, MT9V032_ROW_NOISE_CORR_CONTROL, 0); if (ret < 0) return ret; return v4l2_ctrl_handler_setup(&mt9v032->ctrls); } /* ----------------------------------------------------------------------------- * V4L2 subdev video operations */ static struct v4l2_mbus_framefmt * __mt9v032_get_pad_format(struct mt9v032 *mt9v032, struct v4l2_subdev_fh *fh, unsigned int pad, enum v4l2_subdev_format_whence which) { switch (which) { case V4L2_SUBDEV_FORMAT_TRY: return v4l2_subdev_get_try_format(fh, pad); case V4L2_SUBDEV_FORMAT_ACTIVE: return &mt9v032->format; default: return NULL; } } static struct v4l2_rect * __mt9v032_get_pad_crop(struct mt9v032 *mt9v032, struct v4l2_subdev_fh *fh, unsigned int pad, enum v4l2_subdev_format_whence which) { switch (which) { case V4L2_SUBDEV_FORMAT_TRY: return v4l2_subdev_get_try_crop(fh, pad); case V4L2_SUBDEV_FORMAT_ACTIVE: return &mt9v032->crop; default: return NULL; } } static int mt9v032_s_stream(struct v4l2_subdev *subdev, int enable) { const u16 mode = MT9V032_CHIP_CONTROL_MASTER_MODE | MT9V032_CHIP_CONTROL_DOUT_ENABLE | MT9V032_CHIP_CONTROL_SEQUENTIAL; struct i2c_client *client = v4l2_get_subdevdata(subdev); struct mt9v032 *mt9v032 = to_mt9v032(subdev); struct v4l2_mbus_framefmt *format = &mt9v032->format; struct v4l2_rect *crop = &mt9v032->crop; unsigned int hratio; unsigned int vratio; int ret; if (!enable) return mt9v032_set_chip_control(mt9v032, mode, 0); /* Configure the window size and row/column bin */ hratio = DIV_ROUND_CLOSEST(crop->width, format->width); vratio = DIV_ROUND_CLOSEST(crop->height, format->height); ret = mt9v032_write(client, MT9V032_READ_MODE, (hratio - 1) << MT9V032_READ_MODE_ROW_BIN_SHIFT | (vratio - 1) << MT9V032_READ_MODE_COLUMN_BIN_SHIFT); if (ret < 0) return ret; ret = mt9v032_write(client, MT9V032_COLUMN_START, crop->left); if (ret < 0) return ret; ret = mt9v032_write(client, MT9V032_ROW_START, crop->top); if (ret < 0) return ret; ret = mt9v032_write(client, MT9V032_WINDOW_WIDTH, crop->width); if (ret < 0) return ret; ret = mt9v032_write(client, MT9V032_WINDOW_HEIGHT, crop->height); if (ret < 0) return ret; ret = mt9v032_write(client, MT9V032_HORIZONTAL_BLANKING, max(43, 660 - crop->width)); if (ret < 0) return ret; /* Switch to master "normal" mode */ return mt9v032_set_chip_control(mt9v032, 0, mode); } static int mt9v032_enum_mbus_code(struct v4l2_subdev *subdev, struct v4l2_subdev_fh *fh, struct v4l2_subdev_mbus_code_enum *code) { if (code->index > 0) return -EINVAL; code->code = V4L2_MBUS_FMT_SGRBG10_1X10; return 0; } static int mt9v032_enum_frame_size(struct v4l2_subdev *subdev, struct v4l2_subdev_fh *fh, struct v4l2_subdev_frame_size_enum *fse) { if (fse->index >= 8 || fse->code != V4L2_MBUS_FMT_SGRBG10_1X10) return -EINVAL; fse->min_width = MT9V032_WINDOW_WIDTH_DEF / fse->index; fse->max_width = fse->min_width; fse->min_height = MT9V032_WINDOW_HEIGHT_DEF / fse->index; fse->max_height = fse->min_height; return 0; } static int mt9v032_get_format(struct v4l2_subdev *subdev, struct v4l2_subdev_fh *fh, struct v4l2_subdev_format *format) { struct mt9v032 *mt9v032 = to_mt9v032(subdev); format->format = *__mt9v032_get_pad_format(mt9v032, fh, format->pad, format->which); return 0; } static int mt9v032_set_format(struct v4l2_subdev *subdev, struct v4l2_subdev_fh *fh, struct v4l2_subdev_format *format) { struct mt9v032 *mt9v032 = to_mt9v032(subdev); struct v4l2_mbus_framefmt *__format; struct v4l2_rect *__crop; unsigned int width; unsigned int height; unsigned int hratio; unsigned int vratio; __crop = __mt9v032_get_pad_crop(mt9v032, fh, format->pad, format->which); /* Clamp the width and height to avoid dividing by zero. */ width = clamp_t(unsigned int, ALIGN(format->format.width, 2), max(__crop->width / 8, MT9V032_WINDOW_WIDTH_MIN), __crop->width); height = clamp_t(unsigned int, ALIGN(format->format.height, 2), max(__crop->height / 8, MT9V032_WINDOW_HEIGHT_MIN), __crop->height); hratio = DIV_ROUND_CLOSEST(__crop->width, width); vratio = DIV_ROUND_CLOSEST(__crop->height, height); __format = __mt9v032_get_pad_format(mt9v032, fh, format->pad, format->which); __format->width = __crop->width / hratio; __format->height = __crop->height / vratio; format->format = *__format; return 0; } static int mt9v032_get_crop(struct v4l2_subdev *subdev, struct v4l2_subdev_fh *fh, struct v4l2_subdev_crop *crop) { struct mt9v032 *mt9v032 = to_mt9v032(subdev); crop->rect = *__mt9v032_get_pad_crop(mt9v032, fh, crop->pad, crop->which); return 0; } static int mt9v032_set_crop(struct v4l2_subdev *subdev, struct v4l2_subdev_fh *fh, struct v4l2_subdev_crop *crop) { struct mt9v032 *mt9v032 = to_mt9v032(subdev); struct v4l2_mbus_framefmt *__format; struct v4l2_rect *__crop; struct v4l2_rect rect; /* Clamp the crop rectangle boundaries and align them to a non multiple * of 2 pixels to ensure a GRBG Bayer pattern. */ rect.left = clamp(ALIGN(crop->rect.left + 1, 2) - 1, MT9V032_COLUMN_START_MIN, MT9V032_COLUMN_START_MAX); rect.top = clamp(ALIGN(crop->rect.top + 1, 2) - 1, MT9V032_ROW_START_MIN, MT9V032_ROW_START_MAX); rect.width = clamp(ALIGN(crop->rect.width, 2), MT9V032_WINDOW_WIDTH_MIN, MT9V032_WINDOW_WIDTH_MAX); rect.height = clamp(ALIGN(crop->rect.height, 2), MT9V032_WINDOW_HEIGHT_MIN, MT9V032_WINDOW_HEIGHT_MAX); rect.width = min(rect.width, MT9V032_PIXEL_ARRAY_WIDTH - rect.left); rect.height = min(rect.height, MT9V032_PIXEL_ARRAY_HEIGHT - rect.top); __crop = __mt9v032_get_pad_crop(mt9v032, fh, crop->pad, crop->which); if (rect.width != __crop->width || rect.height != __crop->height) { /* Reset the output image size if the crop rectangle size has * been modified. */ __format = __mt9v032_get_pad_format(mt9v032, fh, crop->pad, crop->which); __format->width = rect.width; __format->height = rect.height; } *__crop = rect; crop->rect = rect; return 0; } /* ----------------------------------------------------------------------------- * V4L2 subdev control operations */ #define V4L2_CID_TEST_PATTERN (V4L2_CID_USER_BASE | 0x1001) static int mt9v032_s_ctrl(struct v4l2_ctrl *ctrl) { struct mt9v032 *mt9v032 = container_of(ctrl->handler, struct mt9v032, ctrls); struct i2c_client *client = v4l2_get_subdevdata(&mt9v032->subdev); u16 data; switch (ctrl->id) { case V4L2_CID_AUTOGAIN: return mt9v032_update_aec_agc(mt9v032, MT9V032_AGC_ENABLE, ctrl->val); case V4L2_CID_GAIN: return mt9v032_write(client, MT9V032_ANALOG_GAIN, ctrl->val); case V4L2_CID_EXPOSURE_AUTO: return mt9v032_update_aec_agc(mt9v032, MT9V032_AEC_ENABLE, ctrl->val); case V4L2_CID_EXPOSURE: return mt9v032_write(client, MT9V032_TOTAL_SHUTTER_WIDTH, ctrl->val); case V4L2_CID_TEST_PATTERN: switch (ctrl->val) { case 0: data = 0; break; case 1: data = MT9V032_TEST_PATTERN_GRAY_VERTICAL | MT9V032_TEST_PATTERN_ENABLE; break; case 2: data = MT9V032_TEST_PATTERN_GRAY_HORIZONTAL | MT9V032_TEST_PATTERN_ENABLE; break; case 3: data = MT9V032_TEST_PATTERN_GRAY_DIAGONAL | MT9V032_TEST_PATTERN_ENABLE; break; default: data = (ctrl->val << MT9V032_TEST_PATTERN_DATA_SHIFT) | MT9V032_TEST_PATTERN_USE_DATA | MT9V032_TEST_PATTERN_ENABLE | MT9V032_TEST_PATTERN_FLIP; break; } return mt9v032_write(client, MT9V032_TEST_PATTERN, data); } return 0; } static struct v4l2_ctrl_ops mt9v032_ctrl_ops = { .s_ctrl = mt9v032_s_ctrl, }; static const struct v4l2_ctrl_config mt9v032_ctrls[] = { { .ops = &mt9v032_ctrl_ops, .id = V4L2_CID_TEST_PATTERN, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Test pattern", .min = 0, .max = 1023, .step = 1, .def = 0, .flags = 0, } }; /* ----------------------------------------------------------------------------- * V4L2 subdev core operations */ static int mt9v032_set_power(struct v4l2_subdev *subdev, int on) { struct mt9v032 *mt9v032 = to_mt9v032(subdev); int ret = 0; mutex_lock(&mt9v032->power_lock); /* If the power count is modified from 0 to != 0 or from != 0 to 0, * update the power state. */ if (mt9v032->power_count == !on) { ret = __mt9v032_set_power(mt9v032, !!on); if (ret < 0) goto done; } /* Update the power count. */ mt9v032->power_count += on ? 1 : -1; WARN_ON(mt9v032->power_count < 0); done: mutex_unlock(&mt9v032->power_lock); return ret; } /* ----------------------------------------------------------------------------- * V4L2 subdev internal operations */ static int mt9v032_registered(struct v4l2_subdev *subdev) { struct i2c_client *client = v4l2_get_subdevdata(subdev); struct mt9v032 *mt9v032 = to_mt9v032(subdev); s32 data; int ret; dev_info(&client->dev, "Probing MT9V032 at address 0x%02x\n", client->addr); ret = mt9v032_power_on(mt9v032); if (ret < 0) { dev_err(&client->dev, "MT9V032 power up failed\n"); return ret; } /* Read and check the sensor version */ data = mt9v032_read(client, MT9V032_CHIP_VERSION); if (data != MT9V032_CHIP_ID_REV1 && data != MT9V032_CHIP_ID_REV3) { dev_err(&client->dev, "MT9V032 not detected, wrong version " "0x%04x\n", data); return -ENODEV; } mt9v032_power_off(mt9v032); dev_info(&client->dev, "MT9V032 detected at address 0x%02x\n", client->addr); return ret; } static int mt9v032_open(struct v4l2_subdev *subdev, struct v4l2_subdev_fh *fh) { struct v4l2_mbus_framefmt *format; struct v4l2_rect *crop; crop = v4l2_subdev_get_try_crop(fh, 0); crop->left = MT9V032_COLUMN_START_DEF; crop->top = MT9V032_ROW_START_DEF; crop->width = MT9V032_WINDOW_WIDTH_DEF; crop->height = MT9V032_WINDOW_HEIGHT_DEF; format = v4l2_subdev_get_try_format(fh, 0); format->code = V4L2_MBUS_FMT_SGRBG10_1X10; format->width = MT9V032_WINDOW_WIDTH_DEF; format->height = MT9V032_WINDOW_HEIGHT_DEF; format->field = V4L2_FIELD_NONE; format->colorspace = V4L2_COLORSPACE_SRGB; return mt9v032_set_power(subdev, 1); } static int mt9v032_close(struct v4l2_subdev *subdev, struct v4l2_subdev_fh *fh) { return mt9v032_set_power(subdev, 0); } static struct v4l2_subdev_core_ops mt9v032_subdev_core_ops = { .s_power = mt9v032_set_power, }; static struct v4l2_subdev_video_ops mt9v032_subdev_video_ops = { .s_stream = mt9v032_s_stream, }; static struct v4l2_subdev_pad_ops mt9v032_subdev_pad_ops = { .enum_mbus_code = mt9v032_enum_mbus_code, .enum_frame_size = mt9v032_enum_frame_size, .get_fmt = mt9v032_get_format, .set_fmt = mt9v032_set_format, .get_crop = mt9v032_get_crop, .set_crop = mt9v032_set_crop, }; static struct v4l2_subdev_ops mt9v032_subdev_ops = { .core = &mt9v032_subdev_core_ops, .video = &mt9v032_subdev_video_ops, .pad = &mt9v032_subdev_pad_ops, }; static const struct v4l2_subdev_internal_ops mt9v032_subdev_internal_ops = { .registered = mt9v032_registered, .open = mt9v032_open, .close = mt9v032_close, }; /* ----------------------------------------------------------------------------- * Driver initialization and probing */ static int mt9v032_probe(struct i2c_client *client, const struct i2c_device_id *did) { struct mt9v032 *mt9v032; unsigned int i; int ret; if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_WORD_DATA)) { dev_warn(&client->adapter->dev, "I2C-Adapter doesn't support I2C_FUNC_SMBUS_WORD\n"); return -EIO; } mt9v032 = kzalloc(sizeof(*mt9v032), GFP_KERNEL); if (!mt9v032) return -ENOMEM; mutex_init(&mt9v032->power_lock); mt9v032->pdata = client->dev.platform_data; v4l2_ctrl_handler_init(&mt9v032->ctrls, ARRAY_SIZE(mt9v032_ctrls) + 4); v4l2_ctrl_new_std(&mt9v032->ctrls, &mt9v032_ctrl_ops, V4L2_CID_AUTOGAIN, 0, 1, 1, 1); v4l2_ctrl_new_std(&mt9v032->ctrls, &mt9v032_ctrl_ops, V4L2_CID_GAIN, MT9V032_ANALOG_GAIN_MIN, MT9V032_ANALOG_GAIN_MAX, 1, MT9V032_ANALOG_GAIN_DEF); v4l2_ctrl_new_std_menu(&mt9v032->ctrls, &mt9v032_ctrl_ops, V4L2_CID_EXPOSURE_AUTO, V4L2_EXPOSURE_MANUAL, 0, V4L2_EXPOSURE_AUTO); v4l2_ctrl_new_std(&mt9v032->ctrls, &mt9v032_ctrl_ops, V4L2_CID_EXPOSURE, MT9V032_TOTAL_SHUTTER_WIDTH_MIN, MT9V032_TOTAL_SHUTTER_WIDTH_MAX, 1, MT9V032_TOTAL_SHUTTER_WIDTH_DEF); for (i = 0; i < ARRAY_SIZE(mt9v032_ctrls); ++i) v4l2_ctrl_new_custom(&mt9v032->ctrls, &mt9v032_ctrls[i], NULL); mt9v032->subdev.ctrl_handler = &mt9v032->ctrls; if (mt9v032->ctrls.error) printk(KERN_INFO "%s: control initialization error %d\n", __func__, mt9v032->ctrls.error); mt9v032->crop.left = MT9V032_COLUMN_START_DEF; mt9v032->crop.top = MT9V032_ROW_START_DEF; mt9v032->crop.width = MT9V032_WINDOW_WIDTH_DEF; mt9v032->crop.height = MT9V032_WINDOW_HEIGHT_DEF; mt9v032->format.code = V4L2_MBUS_FMT_SGRBG10_1X10; mt9v032->format.width = MT9V032_WINDOW_WIDTH_DEF; mt9v032->format.height = MT9V032_WINDOW_HEIGHT_DEF; mt9v032->format.field = V4L2_FIELD_NONE; mt9v032->format.colorspace = V4L2_COLORSPACE_SRGB; mt9v032->aec_agc = MT9V032_AEC_ENABLE | MT9V032_AGC_ENABLE; v4l2_i2c_subdev_init(&mt9v032->subdev, client, &mt9v032_subdev_ops); mt9v032->subdev.internal_ops = &mt9v032_subdev_internal_ops; mt9v032->subdev.flags |= V4L2_SUBDEV_FL_HAS_DEVNODE; mt9v032->pad.flags = MEDIA_PAD_FL_SOURCE; ret = media_entity_init(&mt9v032->subdev.entity, 1, &mt9v032->pad, 0); if (ret < 0) kfree(mt9v032); return ret; } static int mt9v032_remove(struct i2c_client *client) { struct v4l2_subdev *subdev = i2c_get_clientdata(client); struct mt9v032 *mt9v032 = to_mt9v032(subdev); v4l2_device_unregister_subdev(subdev); media_entity_cleanup(&subdev->entity); kfree(mt9v032); return 0; } static const struct i2c_device_id mt9v032_id[] = { { "mt9v032", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, mt9v032_id); static struct i2c_driver mt9v032_driver = { .driver = { .name = "mt9v032", }, .probe = mt9v032_probe, .remove = mt9v032_remove, .id_table = mt9v032_id, }; module_i2c_driver(mt9v032_driver); MODULE_DESCRIPTION("Aptina MT9V032 Camera driver"); MODULE_AUTHOR("Laurent Pinchart <laurent.pinchart@ideasonboard.com>"); MODULE_LICENSE("GPL");
gpl-2.0
jamiethemorris/sense-dna-kernel
drivers/media/video/gspca/zc3xx.c
4812
262475
/* * Z-Star/Vimicro zc301/zc302p/vc30x driver * * Copyright (C) 2009-2012 Jean-Francois Moine <http://moinejf.free.fr> * Copyright (C) 2004 2005 2006 Michel Xhaard mxhaard@magic.fr * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/input.h> #include "gspca.h" #include "jpeg.h" MODULE_AUTHOR("Jean-Francois Moine <http://moinejf.free.fr>, " "Serge A. Suchkov <Serge.A.S@tochka.ru>"); MODULE_DESCRIPTION("GSPCA ZC03xx/VC3xx USB Camera Driver"); MODULE_LICENSE("GPL"); static int force_sensor = -1; #define REG08_DEF 3 /* default JPEG compression (70%) */ #include "zc3xx-reg.h" /* controls */ enum e_ctrl { BRIGHTNESS, CONTRAST, EXPOSURE, GAMMA, AUTOGAIN, LIGHTFREQ, SHARPNESS, QUALITY, NCTRLS /* number of controls */ }; #define AUTOGAIN_DEF 1 /* specific webcam descriptor */ struct sd { struct gspca_dev gspca_dev; /* !! must be the first item */ struct gspca_ctrl ctrls[NCTRLS]; struct work_struct work; struct workqueue_struct *work_thread; u8 reg08; /* webcam compression quality */ u8 bridge; u8 sensor; /* Type of image sensor chip */ u16 chip_revision; u8 jpeg_hdr[JPEG_HDR_SZ]; }; enum bridges { BRIDGE_ZC301, BRIDGE_ZC303, }; enum sensors { SENSOR_ADCM2700, SENSOR_CS2102, SENSOR_CS2102K, SENSOR_GC0303, SENSOR_GC0305, SENSOR_HDCS2020, SENSOR_HV7131B, SENSOR_HV7131R, SENSOR_ICM105A, SENSOR_MC501CB, SENSOR_MT9V111_1, /* (mi360soc) zc301 */ SENSOR_MT9V111_3, /* (mi360soc) zc303 */ SENSOR_OV7620, /* OV7648 - same values */ SENSOR_OV7630C, SENSOR_PAS106, SENSOR_PAS202B, SENSOR_PB0330, SENSOR_PO2030, SENSOR_TAS5130C, SENSOR_MAX }; /* V4L2 controls supported by the driver */ static void setcontrast(struct gspca_dev *gspca_dev); static void setexposure(struct gspca_dev *gspca_dev); static int sd_setautogain(struct gspca_dev *gspca_dev, __s32 val); static void setlightfreq(struct gspca_dev *gspca_dev); static void setsharpness(struct gspca_dev *gspca_dev); static int sd_setquality(struct gspca_dev *gspca_dev, __s32 val); static const struct ctrl sd_ctrls[NCTRLS] = { [BRIGHTNESS] = { { .id = V4L2_CID_BRIGHTNESS, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Brightness", .minimum = 0, .maximum = 255, .step = 1, .default_value = 128, }, .set_control = setcontrast }, [CONTRAST] = { { .id = V4L2_CID_CONTRAST, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Contrast", .minimum = 0, .maximum = 255, .step = 1, .default_value = 128, }, .set_control = setcontrast }, [EXPOSURE] = { { .id = V4L2_CID_EXPOSURE, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Exposure", .minimum = 0x30d, .maximum = 0x493e, .step = 1, .default_value = 0x927 }, .set_control = setexposure }, [GAMMA] = { { .id = V4L2_CID_GAMMA, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Gamma", .minimum = 1, .maximum = 6, .step = 1, .default_value = 4, }, .set_control = setcontrast }, [AUTOGAIN] = { { .id = V4L2_CID_AUTOGAIN, .type = V4L2_CTRL_TYPE_BOOLEAN, .name = "Auto Gain", .minimum = 0, .maximum = 1, .step = 1, .default_value = AUTOGAIN_DEF, .flags = V4L2_CTRL_FLAG_UPDATE }, .set = sd_setautogain }, [LIGHTFREQ] = { { .id = V4L2_CID_POWER_LINE_FREQUENCY, .type = V4L2_CTRL_TYPE_MENU, .name = "Light frequency filter", .minimum = 0, .maximum = 2, /* 0: 0, 1: 50Hz, 2:60Hz */ .step = 1, .default_value = 0, }, .set_control = setlightfreq }, [SHARPNESS] = { { .id = V4L2_CID_SHARPNESS, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Sharpness", .minimum = 0, .maximum = 3, .step = 1, .default_value = 2, }, .set_control = setsharpness }, [QUALITY] = { { .id = V4L2_CID_JPEG_COMPRESSION_QUALITY, .type = V4L2_CTRL_TYPE_INTEGER, .name = "Compression Quality", .minimum = 40, .maximum = 70, .step = 1, .default_value = 70 /* updated in sd_init() */ }, .set = sd_setquality }, }; static const struct v4l2_pix_format vga_mode[] = { {320, 240, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE, .bytesperline = 320, .sizeimage = 320 * 240 * 3 / 8 + 590, .colorspace = V4L2_COLORSPACE_JPEG, .priv = 1}, {640, 480, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE, .bytesperline = 640, .sizeimage = 640 * 480 * 3 / 8 + 590, .colorspace = V4L2_COLORSPACE_JPEG, .priv = 0}, }; static const struct v4l2_pix_format broken_vga_mode[] = { {320, 232, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE, .bytesperline = 320, .sizeimage = 320 * 232 * 4 / 8 + 590, .colorspace = V4L2_COLORSPACE_JPEG, .priv = 1}, {640, 472, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE, .bytesperline = 640, .sizeimage = 640 * 472 * 3 / 8 + 590, .colorspace = V4L2_COLORSPACE_JPEG, .priv = 0}, }; static const struct v4l2_pix_format sif_mode[] = { {176, 144, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE, .bytesperline = 176, .sizeimage = 176 * 144 * 3 / 8 + 590, .colorspace = V4L2_COLORSPACE_JPEG, .priv = 1}, {352, 288, V4L2_PIX_FMT_JPEG, V4L2_FIELD_NONE, .bytesperline = 352, .sizeimage = 352 * 288 * 3 / 8 + 590, .colorspace = V4L2_COLORSPACE_JPEG, .priv = 0}, }; /* bridge reg08 -> JPEG quality conversion table */ static u8 jpeg_qual[] = {40, 50, 60, 70, /*80*/}; /* usb exchanges */ struct usb_action { u8 req; u8 val; u16 idx; }; static const struct usb_action adcm2700_Initial[] = { {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc */ {0xa0, 0x04, ZC3XX_R002_CLOCKSELECT}, /* 00,02,04,cc */ {0xa0, 0x00, ZC3XX_R008_CLOCKSETTING}, /* 00,08,03,cc */ {0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */ {0xa0, 0xd3, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,d3,cc */ {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc */ {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc */ {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc */ {0xa0, 0xd8, ZC3XX_R006_FRAMEHEIGHTLOW}, /* 00,06,d8,cc */ {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc */ {0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,03,cc */ {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc */ {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc */ {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,00,cc */ {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,00,cc */ {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,00,cc */ {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,00,cc */ {0xa0, 0xde, ZC3XX_R09C_WINHEIGHTLOW}, /* 00,9c,de,cc */ {0xa0, 0x86, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,86,cc */ {0xbb, 0x00, 0x0400}, /* 04,00,00,bb */ {0xdd, 0x00, 0x0010}, /* 00,00,10,dd */ {0xbb, 0x0f, 0x140f}, /* 14,0f,0f,bb */ {0xa0, 0xb7, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,37,cc */ {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc */ {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, /* 01,89,06,cc */ {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc */ {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc */ {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc */ {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc */ {0xa0, 0x58, ZC3XX_R116_RGAIN}, /* 01,16,58,cc */ {0xa0, 0x5a, ZC3XX_R118_BGAIN}, /* 01,18,5a,cc */ {0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,02,cc */ {0xa0, 0xd3, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,d3,cc */ {0xbb, 0x00, 0x0408}, /* 04,00,08,bb */ {0xdd, 0x00, 0x0200}, /* 00,02,00,dd */ {0xbb, 0x00, 0x0400}, /* 04,00,00,bb */ {0xdd, 0x00, 0x0010}, /* 00,00,10,dd */ {0xbb, 0x0f, 0x140f}, /* 14,0f,0f,bb */ {0xbb, 0xe0, 0x0c2e}, /* 0c,e0,2e,bb */ {0xbb, 0x01, 0x2000}, /* 20,01,00,bb */ {0xbb, 0x96, 0x2400}, /* 24,96,00,bb */ {0xbb, 0x06, 0x1006}, /* 10,06,06,bb */ {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */ {0xdd, 0x00, 0x0010}, /* 00,00,10,dd */ {0xaa, 0xfe, 0x0002}, /* 00,fe,02,aa */ {0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */ {0xdd, 0x00, 0x0010}, /* 00,00,10,dd */ {0xbb, 0x5f, 0x2090}, /* 20,5f,90,bb */ {0xbb, 0x01, 0x8000}, /* 80,01,00,bb */ {0xbb, 0x09, 0x8400}, /* 84,09,00,bb */ {0xbb, 0x86, 0x0002}, /* 00,86,02,bb */ {0xbb, 0xe6, 0x0401}, /* 04,e6,01,bb */ {0xbb, 0x86, 0x0802}, /* 08,86,02,bb */ {0xbb, 0xe6, 0x0c01}, /* 0c,e6,01,bb */ {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */ {0xdd, 0x00, 0x0010}, /* 00,00,10,dd */ {0xaa, 0xfe, 0x0000}, /* 00,fe,00,aa */ {0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */ {0xdd, 0x00, 0x0010}, /* 00,00,10,dd */ {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */ {0xaa, 0xfe, 0x0020}, /* 00,fe,20,aa */ /*mswin+*/ {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, {0xaa, 0xfe, 0x0002}, {0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, {0xaa, 0xb4, 0xcd37}, {0xaa, 0xa4, 0x0004}, {0xaa, 0xa8, 0x0007}, {0xaa, 0xac, 0x0004}, /*mswin-*/ {0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */ {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */ {0xdd, 0x00, 0x0010}, /* 00,00,10,dd */ {0xaa, 0xfe, 0x0000}, /* 00,fe,00,aa */ {0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */ {0xdd, 0x00, 0x0010}, /* 00,00,10,dd */ {0xbb, 0x04, 0x0400}, /* 04,04,00,bb */ {0xdd, 0x00, 0x0100}, /* 00,01,00,dd */ {0xbb, 0x01, 0x0400}, /* 04,01,00,bb */ {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */ {0xaa, 0xfe, 0x0002}, /* 00,fe,02,aa */ {0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */ {0xbb, 0x41, 0x2803}, /* 28,41,03,bb */ {0xbb, 0x40, 0x2c03}, /* 2c,40,03,bb */ {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */ {0xaa, 0xfe, 0x0010}, /* 00,fe,10,aa */ {} }; static const struct usb_action adcm2700_InitialScale[] = { {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc */ {0xa0, 0x10, ZC3XX_R002_CLOCKSELECT}, /* 00,02,10,cc */ {0xa0, 0x00, ZC3XX_R008_CLOCKSETTING}, /* 00,08,03,cc */ {0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */ {0xa0, 0xd3, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,d3,cc */ {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc */ {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc */ {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc */ {0xa0, 0xd0, ZC3XX_R006_FRAMEHEIGHTLOW}, /* 00,06,d0,cc */ {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc */ {0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,03,cc */ {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc */ {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc */ {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,00,cc */ {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,00,cc */ {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,00,cc */ {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,00,cc */ {0xa0, 0xd8, ZC3XX_R09C_WINHEIGHTLOW}, /* 00,9c,d8,cc */ {0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,88,cc */ {0xbb, 0x00, 0x0400}, /* 04,00,00,bb */ {0xdd, 0x00, 0x0010}, /* 00,00,10,dd */ {0xbb, 0x0f, 0x140f}, /* 14,0f,0f,bb */ {0xa0, 0xb7, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,37,cc */ {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc */ {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, /* 01,89,06,cc */ {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc */ {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc */ {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc */ {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc */ {0xa0, 0x58, ZC3XX_R116_RGAIN}, /* 01,16,58,cc */ {0xa0, 0x5a, ZC3XX_R118_BGAIN}, /* 01,18,5a,cc */ {0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,02,cc */ {0xa0, 0xd3, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,d3,cc */ {0xbb, 0x00, 0x0408}, /* 04,00,08,bb */ {0xdd, 0x00, 0x0200}, /* 00,02,00,dd */ {0xbb, 0x00, 0x0400}, /* 04,00,00,bb */ {0xdd, 0x00, 0x0050}, /* 00,00,50,dd */ {0xbb, 0x0f, 0x140f}, /* 14,0f,0f,bb */ {0xbb, 0xe0, 0x0c2e}, /* 0c,e0,2e,bb */ {0xbb, 0x01, 0x2000}, /* 20,01,00,bb */ {0xbb, 0x96, 0x2400}, /* 24,96,00,bb */ {0xbb, 0x06, 0x1006}, /* 10,06,06,bb */ {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */ {0xdd, 0x00, 0x0010}, /* 00,00,10,dd */ {0xaa, 0xfe, 0x0002}, /* 00,fe,02,aa */ {0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */ {0xdd, 0x00, 0x0010}, /* 00,00,10,dd */ {0xbb, 0x5f, 0x2090}, /* 20,5f,90,bb */ {0xbb, 0x01, 0x8000}, /* 80,01,00,bb */ {0xbb, 0x09, 0x8400}, /* 84,09,00,bb */ {0xbb, 0x86, 0x0002}, /* 00,88,02,bb */ {0xbb, 0xe6, 0x0401}, /* 04,e6,01,bb */ {0xbb, 0x86, 0x0802}, /* 08,88,02,bb */ {0xbb, 0xe6, 0x0c01}, /* 0c,e6,01,bb */ {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */ {0xdd, 0x00, 0x0010}, /* 00,00,10,dd */ {0xaa, 0xfe, 0x0000}, /* 00,fe,00,aa */ {0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */ {0xdd, 0x00, 0x0010}, /* 00,00,10,dd */ {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */ {0xaa, 0xfe, 0x0020}, /* 00,fe,20,aa */ /*******/ {0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */ {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */ {0xdd, 0x00, 0x0010}, /* 00,00,10,dd */ {0xaa, 0xfe, 0x0000}, /* 00,fe,00,aa */ {0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */ {0xdd, 0x00, 0x0010}, /* 00,00,10,dd */ {0xbb, 0x04, 0x0400}, /* 04,04,00,bb */ {0xdd, 0x00, 0x0100}, /* 00,01,00,dd */ {0xbb, 0x01, 0x0400}, /* 04,01,00,bb */ {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */ {0xaa, 0xfe, 0x0002}, /* 00,fe,02,aa */ {0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */ {0xbb, 0x41, 0x2803}, /* 28,41,03,bb */ {0xbb, 0x40, 0x2c03}, /* 2c,40,03,bb */ {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */ {0xaa, 0xfe, 0x0010}, /* 00,fe,10,aa */ {} }; static const struct usb_action adcm2700_50HZ[] = { {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */ {0xaa, 0xfe, 0x0002}, /* 00,fe,02,aa */ {0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */ {0xbb, 0x05, 0x8400}, /* 84,05,00,bb */ {0xbb, 0xd0, 0xb007}, /* b0,d0,07,bb */ {0xbb, 0xa0, 0xb80f}, /* b8,a0,0f,bb */ {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */ {0xaa, 0xfe, 0x0010}, /* 00,fe,10,aa */ {0xaa, 0x26, 0x00d0}, /* 00,26,d0,aa */ {0xaa, 0x28, 0x0002}, /* 00,28,02,aa */ {} }; static const struct usb_action adcm2700_60HZ[] = { {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */ {0xaa, 0xfe, 0x0002}, /* 00,fe,02,aa */ {0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */ {0xbb, 0x07, 0x8400}, /* 84,07,00,bb */ {0xbb, 0x82, 0xb006}, /* b0,82,06,bb */ {0xbb, 0x04, 0xb80d}, /* b8,04,0d,bb */ {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */ {0xaa, 0xfe, 0x0010}, /* 00,fe,10,aa */ {0xaa, 0x26, 0x0057}, /* 00,26,57,aa */ {0xaa, 0x28, 0x0002}, /* 00,28,02,aa */ {} }; static const struct usb_action adcm2700_NoFliker[] = { {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */ {0xaa, 0xfe, 0x0002}, /* 00,fe,02,aa */ {0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0a,cc */ {0xbb, 0x07, 0x8400}, /* 84,07,00,bb */ {0xbb, 0x05, 0xb000}, /* b0,05,00,bb */ {0xbb, 0xa0, 0xb801}, /* b8,a0,01,bb */ {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */ {0xaa, 0xfe, 0x0010}, /* 00,fe,10,aa */ {} }; static const struct usb_action cs2102_InitialScale[] = { /* 320x240 */ {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, {0xa0, 0x10, ZC3XX_R002_CLOCKSELECT}, {0xa0, 0x00, ZC3XX_R010_CMOSSENSORSELECT}, {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, {0xa0, 0x20, ZC3XX_R080_HBLANKHIGH}, {0xa0, 0x21, ZC3XX_R081_HBLANKLOW}, {0xa0, 0x30, ZC3XX_R083_RGAINADDR}, {0xa0, 0x31, ZC3XX_R084_GGAINADDR}, {0xa0, 0x32, ZC3XX_R085_BGAINADDR}, {0xa0, 0x23, ZC3XX_R086_EXPTIMEHIGH}, {0xa0, 0x24, ZC3XX_R087_EXPTIMEMID}, {0xa0, 0x25, ZC3XX_R088_EXPTIMELOW}, {0xa0, 0xb3, ZC3XX_R08B_I2CDEVICEADDR}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* 00 */ {0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, {0xaa, 0x02, 0x0008}, {0xaa, 0x03, 0x0000}, {0xaa, 0x11, 0x0000}, {0xaa, 0x12, 0x0089}, {0xaa, 0x13, 0x0000}, {0xaa, 0x14, 0x00e9}, {0xaa, 0x20, 0x0000}, {0xaa, 0x22, 0x0000}, {0xaa, 0x0b, 0x0004}, {0xaa, 0x30, 0x0030}, {0xaa, 0x31, 0x0030}, {0xaa, 0x32, 0x0030}, {0xa0, 0x37, ZC3XX_R101_SENSORCORRECTION}, {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, {0xa0, 0x10, 0x01ae}, {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, {0xa0, 0x68, ZC3XX_R18D_YTARGET}, {0xa0, 0x00, 0x01ad}, {} }; static const struct usb_action cs2102_Initial[] = { /* 640x480 */ {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, {0xa0, 0x00, ZC3XX_R002_CLOCKSELECT}, {0xa0, 0x00, ZC3XX_R010_CMOSSENSORSELECT}, {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, {0xa0, 0x20, ZC3XX_R080_HBLANKHIGH}, {0xa0, 0x21, ZC3XX_R081_HBLANKLOW}, {0xa0, 0x30, ZC3XX_R083_RGAINADDR}, {0xa0, 0x31, ZC3XX_R084_GGAINADDR}, {0xa0, 0x32, ZC3XX_R085_BGAINADDR}, {0xa0, 0x23, ZC3XX_R086_EXPTIMEHIGH}, {0xa0, 0x24, ZC3XX_R087_EXPTIMEMID}, {0xa0, 0x25, ZC3XX_R088_EXPTIMELOW}, {0xa0, 0xb3, ZC3XX_R08B_I2CDEVICEADDR}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* 00 */ {0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, {0xaa, 0x02, 0x0008}, {0xaa, 0x03, 0x0000}, {0xaa, 0x11, 0x0001}, {0xaa, 0x12, 0x0087}, {0xaa, 0x13, 0x0001}, {0xaa, 0x14, 0x00e7}, {0xaa, 0x20, 0x0000}, {0xaa, 0x22, 0x0000}, {0xaa, 0x0b, 0x0004}, {0xaa, 0x30, 0x0030}, {0xaa, 0x31, 0x0030}, {0xaa, 0x32, 0x0030}, {0xa0, 0x77, ZC3XX_R101_SENSORCORRECTION}, {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, {0xa0, 0x15, 0x01ae}, {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, {0xa0, 0x68, ZC3XX_R18D_YTARGET}, {0xa0, 0x00, 0x01ad}, {} }; static const struct usb_action cs2102_50HZScale[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xaa, 0x23, 0x0001}, {0xaa, 0x24, 0x005f}, {0xaa, 0x25, 0x0090}, {0xaa, 0x21, 0x00dd}, {0xa0, 0x02, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0xbf, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x20, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x3a, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x98, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0xdd, ZC3XX_R01D_HSYNC_0}, {0xa0, 0xe4, ZC3XX_R01E_HSYNC_1}, {0xa0, 0xf0, ZC3XX_R01F_HSYNC_2}, {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, {} }; static const struct usb_action cs2102_50HZ[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xaa, 0x23, 0x0000}, {0xaa, 0x24, 0x00af}, {0xaa, 0x25, 0x00c8}, {0xaa, 0x21, 0x0068}, {0xa0, 0x01, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x5f, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x90, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x1d, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x4c, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x68, ZC3XX_R01D_HSYNC_0}, {0xa0, 0xe3, ZC3XX_R01E_HSYNC_1}, {0xa0, 0xf0, ZC3XX_R01F_HSYNC_2}, {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, {} }; static const struct usb_action cs2102_60HZScale[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xaa, 0x23, 0x0001}, {0xaa, 0x24, 0x0055}, {0xaa, 0x25, 0x00cc}, {0xaa, 0x21, 0x003f}, {0xa0, 0x02, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0xab, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x98, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x30, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0xd4, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x39, ZC3XX_R01D_HSYNC_0}, {0xa0, 0x70, ZC3XX_R01E_HSYNC_1}, {0xa0, 0xb0, ZC3XX_R01F_HSYNC_2}, {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, {} }; static const struct usb_action cs2102_60HZ[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xaa, 0x23, 0x0000}, {0xaa, 0x24, 0x00aa}, {0xaa, 0x25, 0x00e6}, {0xaa, 0x21, 0x003f}, {0xa0, 0x01, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x55, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0xcc, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x18, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x6a, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x3f, ZC3XX_R01D_HSYNC_0}, {0xa0, 0xa5, ZC3XX_R01E_HSYNC_1}, {0xa0, 0xf0, ZC3XX_R01F_HSYNC_2}, {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, {} }; static const struct usb_action cs2102_NoFlikerScale[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xaa, 0x23, 0x0001}, {0xaa, 0x24, 0x005f}, {0xaa, 0x25, 0x0000}, {0xaa, 0x21, 0x0001}, {0xa0, 0x02, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0xbf, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x00, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x80, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x01, ZC3XX_R01D_HSYNC_0}, {0xa0, 0x40, ZC3XX_R01E_HSYNC_1}, {0xa0, 0xa0, ZC3XX_R01F_HSYNC_2}, {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, {} }; static const struct usb_action cs2102_NoFliker[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xaa, 0x23, 0x0000}, {0xaa, 0x24, 0x00af}, {0xaa, 0x25, 0x0080}, {0xaa, 0x21, 0x0001}, {0xa0, 0x01, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x5f, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x80, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x80, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x01, ZC3XX_R01D_HSYNC_0}, {0xa0, 0x40, ZC3XX_R01E_HSYNC_1}, {0xa0, 0xa0, ZC3XX_R01F_HSYNC_2}, {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, {} }; /* CS2102_KOCOM */ static const struct usb_action cs2102K_InitialScale[] = { {0xa0, 0x11, ZC3XX_R002_CLOCKSELECT}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, {0xa0, 0x08, ZC3XX_R010_CMOSSENSORSELECT}, {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, {0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, {0xa0, 0xe8, ZC3XX_R09C_WINHEIGHTLOW}, {0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW}, {0xa0, 0x55, ZC3XX_R08B_I2CDEVICEADDR}, {0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x00, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x0a, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x02, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x0b, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x02, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x0c, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x7c, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x0d, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0xa3, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x03, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0xfb, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x05, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x00, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x06, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x03, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x09, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x08, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x0e, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x04, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x0f, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x18, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x10, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x18, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x11, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x18, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x12, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x18, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x15, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x00, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x16, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x0c, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x17, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x0c, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x04, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0xb7, ZC3XX_R101_SENSORCORRECTION}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x78, ZC3XX_R18D_YTARGET}, {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, {0xa0, 0x20, ZC3XX_R087_EXPTIMEMID}, {0xa0, 0x21, ZC3XX_R088_EXPTIMELOW}, {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, {0xa0, 0x00, 0x01ad}, {0xa0, 0x01, 0x01b1}, {0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x60, ZC3XX_R116_RGAIN}, {0xa0, 0x40, ZC3XX_R117_GGAIN}, {0xa0, 0x4c, ZC3XX_R118_BGAIN}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* clock ? */ {0xa0, 0x08, ZC3XX_R1C6_SHARPNESS00}, /* sharpness+ */ {0xa0, 0x0f, ZC3XX_R1CB_SHARPNESS05}, /* sharpness- */ {0xa0, 0x13, ZC3XX_R120_GAMMA00}, /* gamma 4 */ {0xa0, 0x38, ZC3XX_R121_GAMMA01}, {0xa0, 0x59, ZC3XX_R122_GAMMA02}, {0xa0, 0x79, ZC3XX_R123_GAMMA03}, {0xa0, 0x92, ZC3XX_R124_GAMMA04}, {0xa0, 0xa7, ZC3XX_R125_GAMMA05}, {0xa0, 0xb9, ZC3XX_R126_GAMMA06}, {0xa0, 0xc8, ZC3XX_R127_GAMMA07}, {0xa0, 0xd4, ZC3XX_R128_GAMMA08}, {0xa0, 0xdf, ZC3XX_R129_GAMMA09}, {0xa0, 0xe7, ZC3XX_R12A_GAMMA0A}, {0xa0, 0xee, ZC3XX_R12B_GAMMA0B}, {0xa0, 0xf4, ZC3XX_R12C_GAMMA0C}, {0xa0, 0xf9, ZC3XX_R12D_GAMMA0D}, {0xa0, 0xfc, ZC3XX_R12E_GAMMA0E}, {0xa0, 0xff, ZC3XX_R12F_GAMMA0F}, {0xa0, 0x26, ZC3XX_R130_GAMMA10}, {0xa0, 0x22, ZC3XX_R131_GAMMA11}, {0xa0, 0x20, ZC3XX_R132_GAMMA12}, {0xa0, 0x1c, ZC3XX_R133_GAMMA13}, {0xa0, 0x16, ZC3XX_R134_GAMMA14}, {0xa0, 0x13, ZC3XX_R135_GAMMA15}, {0xa0, 0x10, ZC3XX_R136_GAMMA16}, {0xa0, 0x0d, ZC3XX_R137_GAMMA17}, {0xa0, 0x0b, ZC3XX_R138_GAMMA18}, {0xa0, 0x09, ZC3XX_R139_GAMMA19}, {0xa0, 0x07, ZC3XX_R13A_GAMMA1A}, {0xa0, 0x06, ZC3XX_R13B_GAMMA1B}, {0xa0, 0x05, ZC3XX_R13C_GAMMA1C}, {0xa0, 0x04, ZC3XX_R13D_GAMMA1D}, {0xa0, 0x03, ZC3XX_R13E_GAMMA1E}, {0xa0, 0x02, ZC3XX_R13F_GAMMA1F}, {0xa0, 0x58, ZC3XX_R10A_RGB00}, /* matrix */ {0xa0, 0xf4, ZC3XX_R10B_RGB01}, {0xa0, 0xf4, ZC3XX_R10C_RGB02}, {0xa0, 0xf4, ZC3XX_R10D_RGB10}, {0xa0, 0x58, ZC3XX_R10E_RGB11}, {0xa0, 0xf4, ZC3XX_R10F_RGB12}, {0xa0, 0xf4, ZC3XX_R110_RGB20}, {0xa0, 0xf4, ZC3XX_R111_RGB21}, {0xa0, 0x58, ZC3XX_R112_RGB22}, {0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x00, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x13, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x22, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x14, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x01, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x20, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x01, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x21, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x22, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x04, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x01, ZC3XX_R0A3_EXPOSURETIMEHIGH}, {0xa0, 0x22, ZC3XX_R0A4_EXPOSURETIMELOW}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0xee, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x3a, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x0c, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x28, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x04, ZC3XX_R01D_HSYNC_0}, {0xa0, 0x0f, ZC3XX_R01E_HSYNC_1}, {0xa0, 0x19, ZC3XX_R01F_HSYNC_2}, {0xa0, 0x1f, ZC3XX_R020_HSYNC_3}, {0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN}, {0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN}, {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x60, ZC3XX_R116_RGAIN}, {0xa0, 0x40, ZC3XX_R117_GGAIN}, {0xa0, 0x4c, ZC3XX_R118_BGAIN}, {0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x20, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x01, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x21, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x5c, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x00, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x13, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x5c, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x14, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x01, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x04, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x20, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x01, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x21, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x96, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x00, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x13, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x96, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x14, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x01, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x04, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN}, {} }; static const struct usb_action cs2102K_Initial[] = { {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, {0xa0, 0x00, ZC3XX_R002_CLOCKSELECT}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, {0xa0, 0x08, ZC3XX_R010_CMOSSENSORSELECT}, {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, {0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, {0xa0, 0xe8, ZC3XX_R09C_WINHEIGHTLOW}, {0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW}, /*fixme: next sequence = i2c exchanges*/ {0xa0, 0x55, ZC3XX_R08B_I2CDEVICEADDR}, {0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x00, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x0a, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x02, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x0b, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x02, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x0c, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x7b, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x0d, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0xa3, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x03, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0xfb, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x05, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x00, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x06, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x03, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x09, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x08, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x0e, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x04, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x0f, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x18, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x10, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x18, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x11, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x18, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x12, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x18, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x15, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x00, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x16, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x0c, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x17, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x0c, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x04, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0xf7, ZC3XX_R101_SENSORCORRECTION}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x78, ZC3XX_R18D_YTARGET}, {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, {0xa0, 0x20, ZC3XX_R087_EXPTIMEMID}, {0xa0, 0x21, ZC3XX_R088_EXPTIMELOW}, {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, {0xa0, 0x00, 0x01ad}, {0xa0, 0x01, 0x01b1}, {0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x60, ZC3XX_R116_RGAIN}, {0xa0, 0x40, ZC3XX_R117_GGAIN}, {0xa0, 0x4c, ZC3XX_R118_BGAIN}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* clock ? */ {0xa0, 0x08, ZC3XX_R1C6_SHARPNESS00}, /* sharpness+ */ {0xa0, 0x0f, ZC3XX_R1CB_SHARPNESS05}, /* sharpness- */ {0xa0, 0x13, ZC3XX_R120_GAMMA00}, /* gamma 4 */ {0xa0, 0x38, ZC3XX_R121_GAMMA01}, {0xa0, 0x59, ZC3XX_R122_GAMMA02}, {0xa0, 0x79, ZC3XX_R123_GAMMA03}, {0xa0, 0x92, ZC3XX_R124_GAMMA04}, {0xa0, 0xa7, ZC3XX_R125_GAMMA05}, {0xa0, 0xb9, ZC3XX_R126_GAMMA06}, {0xa0, 0xc8, ZC3XX_R127_GAMMA07}, {0xa0, 0xd4, ZC3XX_R128_GAMMA08}, {0xa0, 0xdf, ZC3XX_R129_GAMMA09}, {0xa0, 0xe7, ZC3XX_R12A_GAMMA0A}, {0xa0, 0xee, ZC3XX_R12B_GAMMA0B}, {0xa0, 0xf4, ZC3XX_R12C_GAMMA0C}, {0xa0, 0xf9, ZC3XX_R12D_GAMMA0D}, {0xa0, 0xfc, ZC3XX_R12E_GAMMA0E}, {0xa0, 0xff, ZC3XX_R12F_GAMMA0F}, {0xa0, 0x26, ZC3XX_R130_GAMMA10}, {0xa0, 0x22, ZC3XX_R131_GAMMA11}, {0xa0, 0x20, ZC3XX_R132_GAMMA12}, {0xa0, 0x1c, ZC3XX_R133_GAMMA13}, {0xa0, 0x16, ZC3XX_R134_GAMMA14}, {0xa0, 0x13, ZC3XX_R135_GAMMA15}, {0xa0, 0x10, ZC3XX_R136_GAMMA16}, {0xa0, 0x0d, ZC3XX_R137_GAMMA17}, {0xa0, 0x0b, ZC3XX_R138_GAMMA18}, {0xa0, 0x09, ZC3XX_R139_GAMMA19}, {0xa0, 0x07, ZC3XX_R13A_GAMMA1A}, {0xa0, 0x06, ZC3XX_R13B_GAMMA1B}, {0xa0, 0x05, ZC3XX_R13C_GAMMA1C}, {0xa0, 0x04, ZC3XX_R13D_GAMMA1D}, {0xa0, 0x03, ZC3XX_R13E_GAMMA1E}, {0xa0, 0x02, ZC3XX_R13F_GAMMA1F}, {0xa0, 0x58, ZC3XX_R10A_RGB00}, /* matrix */ {0xa0, 0xf4, ZC3XX_R10B_RGB01}, {0xa0, 0xf4, ZC3XX_R10C_RGB02}, {0xa0, 0xf4, ZC3XX_R10D_RGB10}, {0xa0, 0x58, ZC3XX_R10E_RGB11}, {0xa0, 0xf4, ZC3XX_R10F_RGB12}, {0xa0, 0xf4, ZC3XX_R110_RGB20}, {0xa0, 0xf4, ZC3XX_R111_RGB21}, {0xa0, 0x58, ZC3XX_R112_RGB22}, {0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x00, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x13, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x22, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x14, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x01, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x20, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x01, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x21, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x22, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x04, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x01, ZC3XX_R0A3_EXPOSURETIMEHIGH}, {0xa0, 0x22, ZC3XX_R0A4_EXPOSURETIMELOW}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0xee, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x3a, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x0c, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x28, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x04, ZC3XX_R01D_HSYNC_0}, {0xa0, 0x0f, ZC3XX_R01E_HSYNC_1}, {0xa0, 0x19, ZC3XX_R01F_HSYNC_2}, {0xa0, 0x1f, ZC3XX_R020_HSYNC_3}, {0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN}, {0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN}, {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x60, ZC3XX_R116_RGAIN}, {0xa0, 0x40, ZC3XX_R117_GGAIN}, {0xa0, 0x4c, ZC3XX_R118_BGAIN}, {0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x20, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x01, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x21, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x5c, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x00, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x13, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x5c, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x14, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x01, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x04, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x20, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x01, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x21, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x96, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x00, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x13, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x96, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x14, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x01, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x04, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN}, /*fixme:what does the next sequence?*/ {0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x20, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x01, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x21, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0xd0, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x00, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x13, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0xd0, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x14, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x01, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x04, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x02, ZC3XX_R008_CLOCKSETTING}, {0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x20, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x02, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x21, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x0a, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x00, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x13, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x0a, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x14, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x02, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x04, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x20, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x02, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x21, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x44, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x00, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x13, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x44, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x14, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x02, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x04, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x20, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x02, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x21, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x7e, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x00, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x13, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x7e, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x14, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x02, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x18, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x04, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x00, ZC3XX_R094_I2CWRITEACK}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN}, {} }; static const struct usb_action gc0305_Initial[] = { /* 640x480 */ {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc */ {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* 00,08,03,cc */ {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */ {0xa0, 0x04, ZC3XX_R002_CLOCKSELECT}, /* 00,02,04,cc */ {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc */ {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc */ {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc */ {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, /* 00,06,e0,cc */ {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc */ {0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,03,cc */ {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc */ {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,00,cc */ {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,00,cc */ {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,00,cc */ {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,00,cc */ {0xa0, 0xe6, ZC3XX_R09C_WINHEIGHTLOW}, /* 00,9c,e6,cc */ {0xa0, 0x86, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,86,cc */ {0xa0, 0x98, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,98,cc */ {0xaa, 0x13, 0x0002}, /* 00,13,02,aa */ {0xaa, 0x15, 0x0003}, /* 00,15,03,aa */ {0xaa, 0x01, 0x0000}, /* 00,01,00,aa */ {0xaa, 0x02, 0x0000}, /* 00,02,00,aa */ {0xaa, 0x1a, 0x0000}, /* 00,1a,00,aa */ {0xaa, 0x1c, 0x0017}, /* 00,1c,17,aa */ {0xaa, 0x1d, 0x0080}, /* 00,1d,80,aa */ {0xaa, 0x1f, 0x0008}, /* 00,1f,08,aa */ {0xaa, 0x21, 0x0012}, /* 00,21,12,aa */ {0xa0, 0x82, ZC3XX_R086_EXPTIMEHIGH}, /* 00,86,82,cc */ {0xa0, 0x83, ZC3XX_R087_EXPTIMEMID}, /* 00,87,83,cc */ {0xa0, 0x84, ZC3XX_R088_EXPTIMELOW}, /* 00,88,84,cc */ {0xaa, 0x05, 0x0000}, /* 00,05,00,aa */ {0xaa, 0x0a, 0x0000}, /* 00,0a,00,aa */ {0xaa, 0x0b, 0x00b0}, /* 00,0b,b0,aa */ {0xaa, 0x0c, 0x0000}, /* 00,0c,00,aa */ {0xaa, 0x0d, 0x00b0}, /* 00,0d,b0,aa */ {0xaa, 0x0e, 0x0000}, /* 00,0e,00,aa */ {0xaa, 0x0f, 0x00b0}, /* 00,0f,b0,aa */ {0xaa, 0x10, 0x0000}, /* 00,10,00,aa */ {0xaa, 0x11, 0x00b0}, /* 00,11,b0,aa */ {0xaa, 0x16, 0x0001}, /* 00,16,01,aa */ {0xaa, 0x17, 0x00e6}, /* 00,17,e6,aa */ {0xaa, 0x18, 0x0002}, /* 00,18,02,aa */ {0xaa, 0x19, 0x0086}, /* 00,19,86,aa */ {0xaa, 0x20, 0x0000}, /* 00,20,00,aa */ {0xaa, 0x1b, 0x0020}, /* 00,1b,20,aa */ {0xa0, 0xb7, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,b7,cc */ {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc */ {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc */ {0xa0, 0x76, ZC3XX_R189_AWBSTATUS}, /* 01,89,76,cc */ {0xa0, 0x09, 0x01ad}, /* 01,ad,09,cc */ {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc */ {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc */ {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc */ {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc */ {0xa0, 0x60, ZC3XX_R1A8_DIGITALGAIN}, /* 01,a8,60,cc */ {0xa0, 0x85, ZC3XX_R18D_YTARGET}, /* 01,8d,85,cc */ {0xa0, 0x00, 0x011e}, /* 01,1e,00,cc */ {0xa0, 0x52, ZC3XX_R116_RGAIN}, /* 01,16,52,cc */ {0xa0, 0x40, ZC3XX_R117_GGAIN}, /* 01,17,40,cc */ {0xa0, 0x52, ZC3XX_R118_BGAIN}, /* 01,18,52,cc */ {0xa0, 0x03, ZC3XX_R113_RGB03}, /* 01,13,03,cc */ {} }; static const struct usb_action gc0305_InitialScale[] = { /* 320x240 */ {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc */ {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* 00,08,03,cc */ {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */ {0xa0, 0x10, ZC3XX_R002_CLOCKSELECT}, /* 00,02,10,cc */ {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc */ {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc */ {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc */ {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, /* 00,06,e0,cc */ {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc */ {0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,03,cc */ {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc */ {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,00,cc */ {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,00,cc */ {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,00,cc */ {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,00,cc */ {0xa0, 0xe8, ZC3XX_R09C_WINHEIGHTLOW}, /* 00,9c,e8,cc */ {0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,88,cc */ {0xa0, 0x98, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,98,cc */ {0xaa, 0x13, 0x0000}, /* 00,13,00,aa */ {0xaa, 0x15, 0x0001}, /* 00,15,01,aa */ {0xaa, 0x01, 0x0000}, /* 00,01,00,aa */ {0xaa, 0x02, 0x0000}, /* 00,02,00,aa */ {0xaa, 0x1a, 0x0000}, /* 00,1a,00,aa */ {0xaa, 0x1c, 0x0017}, /* 00,1c,17,aa */ {0xaa, 0x1d, 0x0080}, /* 00,1d,80,aa */ {0xaa, 0x1f, 0x0008}, /* 00,1f,08,aa */ {0xaa, 0x21, 0x0012}, /* 00,21,12,aa */ {0xa0, 0x82, ZC3XX_R086_EXPTIMEHIGH}, /* 00,86,82,cc */ {0xa0, 0x83, ZC3XX_R087_EXPTIMEMID}, /* 00,87,83,cc */ {0xa0, 0x84, ZC3XX_R088_EXPTIMELOW}, /* 00,88,84,cc */ {0xaa, 0x05, 0x0000}, /* 00,05,00,aa */ {0xaa, 0x0a, 0x0000}, /* 00,0a,00,aa */ {0xaa, 0x0b, 0x00b0}, /* 00,0b,b0,aa */ {0xaa, 0x0c, 0x0000}, /* 00,0c,00,aa */ {0xaa, 0x0d, 0x00b0}, /* 00,0d,b0,aa */ {0xaa, 0x0e, 0x0000}, /* 00,0e,00,aa */ {0xaa, 0x0f, 0x00b0}, /* 00,0f,b0,aa */ {0xaa, 0x10, 0x0000}, /* 00,10,00,aa */ {0xaa, 0x11, 0x00b0}, /* 00,11,b0,aa */ {0xaa, 0x16, 0x0001}, /* 00,16,01,aa */ {0xaa, 0x17, 0x00e8}, /* 00,17,e8,aa */ {0xaa, 0x18, 0x0002}, /* 00,18,02,aa */ {0xaa, 0x19, 0x0088}, /* 00,19,88,aa */ {0xaa, 0x20, 0x0000}, /* 00,20,00,aa */ {0xaa, 0x1b, 0x0020}, /* 00,1b,20,aa */ {0xa0, 0xb7, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,b7,cc */ {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc */ {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc */ {0xa0, 0x76, ZC3XX_R189_AWBSTATUS}, /* 01,89,76,cc */ {0xa0, 0x09, 0x01ad}, /* 01,ad,09,cc */ {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc */ {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc */ {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc */ {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc */ {0xa0, 0x60, ZC3XX_R1A8_DIGITALGAIN}, /* 01,a8,60,cc */ {0xa0, 0x00, 0x011e}, /* 01,1e,00,cc */ {0xa0, 0x52, ZC3XX_R116_RGAIN}, /* 01,16,52,cc */ {0xa0, 0x40, ZC3XX_R117_GGAIN}, /* 01,17,40,cc */ {0xa0, 0x52, ZC3XX_R118_BGAIN}, /* 01,18,52,cc */ {0xa0, 0x03, ZC3XX_R113_RGB03}, /* 01,13,03,cc */ {} }; static const struct usb_action gc0305_50HZ[] = { {0xaa, 0x82, 0x0000}, /* 00,82,00,aa */ {0xaa, 0x83, 0x0002}, /* 00,83,02,aa */ {0xaa, 0x84, 0x0038}, /* 00,84,38,aa */ /* win: 00,84,ec */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x0b, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,0b,cc */ {0xa0, 0x18, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,18,cc */ /* win: 01,92,10 */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0x8e, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,8e,cc */ /* win: 01,97,ec */ {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, /* 01,8c,0e,cc */ {0xa0, 0x15, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,15,cc */ {0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,10,cc */ {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,24,cc */ {0xa0, 0x62, ZC3XX_R01D_HSYNC_0}, /* 00,1d,62,cc */ {0xa0, 0x90, ZC3XX_R01E_HSYNC_1}, /* 00,1e,90,cc */ {0xa0, 0xc8, ZC3XX_R01F_HSYNC_2}, /* 00,1f,c8,cc */ {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */ {0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN}, /* 01,1d,60,cc */ {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,42,cc */ /* {0xa0, 0x85, ZC3XX_R18D_YTARGET}, * 01,8d,85,cc * * if 640x480 */ {} }; static const struct usb_action gc0305_60HZ[] = { {0xaa, 0x82, 0x0000}, /* 00,82,00,aa */ {0xaa, 0x83, 0x0000}, /* 00,83,00,aa */ {0xaa, 0x84, 0x00ec}, /* 00,84,ec,aa */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x0b, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,0b,cc */ {0xa0, 0x10, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,10,cc */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0xec, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,ec,cc */ {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, /* 01,8c,0e,cc */ {0xa0, 0x15, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,15,cc */ {0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,10,cc */ {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,24,cc */ {0xa0, 0x62, ZC3XX_R01D_HSYNC_0}, /* 00,1d,62,cc */ {0xa0, 0x90, ZC3XX_R01E_HSYNC_1}, /* 00,1e,90,cc */ {0xa0, 0xc8, ZC3XX_R01F_HSYNC_2}, /* 00,1f,c8,cc */ {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */ {0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN}, /* 01,1d,60,cc */ {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,42,cc */ {0xa0, 0x80, ZC3XX_R18D_YTARGET}, /* 01,8d,80,cc */ {} }; static const struct usb_action gc0305_NoFliker[] = { {0xa0, 0x0c, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0c,cc */ {0xaa, 0x82, 0x0000}, /* 00,82,00,aa */ {0xaa, 0x83, 0x0000}, /* 00,83,00,aa */ {0xaa, 0x84, 0x0020}, /* 00,84,20,aa */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x00, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,00,cc */ {0xa0, 0x48, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,48,cc */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0x10, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,10,cc */ {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, /* 01,8c,0e,cc */ {0xa0, 0x15, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,15,cc */ {0xa0, 0x62, ZC3XX_R01D_HSYNC_0}, /* 00,1d,62,cc */ {0xa0, 0x90, ZC3XX_R01E_HSYNC_1}, /* 00,1e,90,cc */ {0xa0, 0xc8, ZC3XX_R01F_HSYNC_2}, /* 00,1f,c8,cc */ {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */ {0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN}, /* 01,1d,60,cc */ {0xa0, 0x03, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,03,cc */ {0xa0, 0x80, ZC3XX_R18D_YTARGET}, /* 01,8d,80,cc */ {} }; static const struct usb_action hdcs2020_InitialScale[] = { {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, {0xa0, 0x11, ZC3XX_R002_CLOCKSELECT}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* qtable 0x05 */ {0xa0, 0x08, ZC3XX_R010_CMOSSENSORSELECT}, {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, {0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, {0xa0, 0xe8, ZC3XX_R09C_WINHEIGHTLOW}, {0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW}, {0xaa, 0x1c, 0x0000}, {0xaa, 0x0a, 0x0001}, {0xaa, 0x0b, 0x0006}, {0xaa, 0x0c, 0x007b}, {0xaa, 0x0d, 0x00a7}, {0xaa, 0x03, 0x00fb}, {0xaa, 0x05, 0x0000}, {0xaa, 0x06, 0x0003}, {0xaa, 0x09, 0x0008}, {0xaa, 0x0f, 0x0018}, /* set sensor gain */ {0xaa, 0x10, 0x0018}, {0xaa, 0x11, 0x0018}, {0xaa, 0x12, 0x0018}, {0xaa, 0x15, 0x004e}, {0xaa, 0x1c, 0x0004}, {0xa0, 0xb7, ZC3XX_R101_SENSORCORRECTION}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x70, ZC3XX_R18D_YTARGET}, {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, {0xa1, 0x01, 0x0002}, {0xa1, 0x01, 0x0008}, {0xa1, 0x01, 0x0180}, {0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x40, ZC3XX_R116_RGAIN}, {0xa0, 0x40, ZC3XX_R117_GGAIN}, {0xa0, 0x40, ZC3XX_R118_BGAIN}, {0xa1, 0x01, 0x0008}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* clock ? */ {0xa0, 0x08, ZC3XX_R1C6_SHARPNESS00}, /* sharpness+ */ {0xa1, 0x01, 0x01c8}, {0xa1, 0x01, 0x01c9}, {0xa1, 0x01, 0x01ca}, {0xa0, 0x0f, ZC3XX_R1CB_SHARPNESS05}, /* sharpness- */ {0xa0, 0x13, ZC3XX_R120_GAMMA00}, /* gamma 4 */ {0xa0, 0x38, ZC3XX_R121_GAMMA01}, {0xa0, 0x59, ZC3XX_R122_GAMMA02}, {0xa0, 0x79, ZC3XX_R123_GAMMA03}, {0xa0, 0x92, ZC3XX_R124_GAMMA04}, {0xa0, 0xa7, ZC3XX_R125_GAMMA05}, {0xa0, 0xb9, ZC3XX_R126_GAMMA06}, {0xa0, 0xc8, ZC3XX_R127_GAMMA07}, {0xa0, 0xd4, ZC3XX_R128_GAMMA08}, {0xa0, 0xdf, ZC3XX_R129_GAMMA09}, {0xa0, 0xe7, ZC3XX_R12A_GAMMA0A}, {0xa0, 0xee, ZC3XX_R12B_GAMMA0B}, {0xa0, 0xf4, ZC3XX_R12C_GAMMA0C}, {0xa0, 0xf9, ZC3XX_R12D_GAMMA0D}, {0xa0, 0xfc, ZC3XX_R12E_GAMMA0E}, {0xa0, 0xff, ZC3XX_R12F_GAMMA0F}, {0xa0, 0x26, ZC3XX_R130_GAMMA10}, {0xa0, 0x22, ZC3XX_R131_GAMMA11}, {0xa0, 0x20, ZC3XX_R132_GAMMA12}, {0xa0, 0x1c, ZC3XX_R133_GAMMA13}, {0xa0, 0x16, ZC3XX_R134_GAMMA14}, {0xa0, 0x13, ZC3XX_R135_GAMMA15}, {0xa0, 0x10, ZC3XX_R136_GAMMA16}, {0xa0, 0x0d, ZC3XX_R137_GAMMA17}, {0xa0, 0x0b, ZC3XX_R138_GAMMA18}, {0xa0, 0x09, ZC3XX_R139_GAMMA19}, {0xa0, 0x07, ZC3XX_R13A_GAMMA1A}, {0xa0, 0x06, ZC3XX_R13B_GAMMA1B}, {0xa0, 0x05, ZC3XX_R13C_GAMMA1C}, {0xa0, 0x04, ZC3XX_R13D_GAMMA1D}, {0xa0, 0x03, ZC3XX_R13E_GAMMA1E}, {0xa0, 0x02, ZC3XX_R13F_GAMMA1F}, {0xa0, 0x66, ZC3XX_R10A_RGB00}, /* matrix */ {0xa0, 0xed, ZC3XX_R10B_RGB01}, {0xa0, 0xed, ZC3XX_R10C_RGB02}, {0xa0, 0xed, ZC3XX_R10D_RGB10}, {0xa0, 0x66, ZC3XX_R10E_RGB11}, {0xa0, 0xed, ZC3XX_R10F_RGB12}, {0xa0, 0xed, ZC3XX_R110_RGB20}, {0xa0, 0xed, ZC3XX_R111_RGB21}, {0xa0, 0x66, ZC3XX_R112_RGB22}, {0xa1, 0x01, 0x0180}, {0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xaa, 0x13, 0x0031}, {0xaa, 0x14, 0x0001}, {0xaa, 0x0e, 0x0004}, {0xaa, 0x19, 0x00cd}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x02, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x62, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x3d, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x0c, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 0x14 */ {0xa0, 0x28, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x04, ZC3XX_R01D_HSYNC_0}, {0xa0, 0x18, ZC3XX_R01E_HSYNC_1}, {0xa0, 0x2c, ZC3XX_R01F_HSYNC_2}, {0xa0, 0x41, ZC3XX_R020_HSYNC_3}, {0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN}, {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa1, 0x01, 0x0180}, {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x40, ZC3XX_R116_RGAIN}, {0xa0, 0x40, ZC3XX_R117_GGAIN}, {0xa0, 0x40, ZC3XX_R118_BGAIN}, {} }; static const struct usb_action hdcs2020_Initial[] = { {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, {0xa0, 0x00, ZC3XX_R002_CLOCKSELECT}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, {0xa0, 0x08, ZC3XX_R010_CMOSSENSORSELECT}, {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, {0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, {0xa0, 0xe8, ZC3XX_R09C_WINHEIGHTLOW}, {0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW}, {0xaa, 0x1c, 0x0000}, {0xaa, 0x0a, 0x0001}, {0xaa, 0x0b, 0x0006}, {0xaa, 0x0c, 0x007a}, {0xaa, 0x0d, 0x00a7}, {0xaa, 0x03, 0x00fb}, {0xaa, 0x05, 0x0000}, {0xaa, 0x06, 0x0003}, {0xaa, 0x09, 0x0008}, {0xaa, 0x0f, 0x0018}, /* original setting */ {0xaa, 0x10, 0x0018}, {0xaa, 0x11, 0x0018}, {0xaa, 0x12, 0x0018}, {0xaa, 0x15, 0x004e}, {0xaa, 0x1c, 0x0004}, {0xa0, 0xf7, ZC3XX_R101_SENSORCORRECTION}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x70, ZC3XX_R18D_YTARGET}, {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, {0xa1, 0x01, 0x0002}, {0xa1, 0x01, 0x0008}, {0xa1, 0x01, 0x0180}, {0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x40, ZC3XX_R116_RGAIN}, {0xa0, 0x40, ZC3XX_R117_GGAIN}, {0xa0, 0x40, ZC3XX_R118_BGAIN}, {0xa1, 0x01, 0x0008}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* clock ? */ {0xa0, 0x08, ZC3XX_R1C6_SHARPNESS00}, /* sharpness+ */ {0xa1, 0x01, 0x01c8}, {0xa1, 0x01, 0x01c9}, {0xa1, 0x01, 0x01ca}, {0xa0, 0x0f, ZC3XX_R1CB_SHARPNESS05}, /* sharpness- */ {0xa0, 0x13, ZC3XX_R120_GAMMA00}, /* gamma 4 */ {0xa0, 0x38, ZC3XX_R121_GAMMA01}, {0xa0, 0x59, ZC3XX_R122_GAMMA02}, {0xa0, 0x79, ZC3XX_R123_GAMMA03}, {0xa0, 0x92, ZC3XX_R124_GAMMA04}, {0xa0, 0xa7, ZC3XX_R125_GAMMA05}, {0xa0, 0xb9, ZC3XX_R126_GAMMA06}, {0xa0, 0xc8, ZC3XX_R127_GAMMA07}, {0xa0, 0xd4, ZC3XX_R128_GAMMA08}, {0xa0, 0xdf, ZC3XX_R129_GAMMA09}, {0xa0, 0xe7, ZC3XX_R12A_GAMMA0A}, {0xa0, 0xee, ZC3XX_R12B_GAMMA0B}, {0xa0, 0xf4, ZC3XX_R12C_GAMMA0C}, {0xa0, 0xf9, ZC3XX_R12D_GAMMA0D}, {0xa0, 0xfc, ZC3XX_R12E_GAMMA0E}, {0xa0, 0xff, ZC3XX_R12F_GAMMA0F}, {0xa0, 0x26, ZC3XX_R130_GAMMA10}, {0xa0, 0x22, ZC3XX_R131_GAMMA11}, {0xa0, 0x20, ZC3XX_R132_GAMMA12}, {0xa0, 0x1c, ZC3XX_R133_GAMMA13}, {0xa0, 0x16, ZC3XX_R134_GAMMA14}, {0xa0, 0x13, ZC3XX_R135_GAMMA15}, {0xa0, 0x10, ZC3XX_R136_GAMMA16}, {0xa0, 0x0d, ZC3XX_R137_GAMMA17}, {0xa0, 0x0b, ZC3XX_R138_GAMMA18}, {0xa0, 0x09, ZC3XX_R139_GAMMA19}, {0xa0, 0x07, ZC3XX_R13A_GAMMA1A}, {0xa0, 0x06, ZC3XX_R13B_GAMMA1B}, {0xa0, 0x05, ZC3XX_R13C_GAMMA1C}, {0xa0, 0x04, ZC3XX_R13D_GAMMA1D}, {0xa0, 0x03, ZC3XX_R13E_GAMMA1E}, {0xa0, 0x02, ZC3XX_R13F_GAMMA1F}, {0xa0, 0x66, ZC3XX_R10A_RGB00}, /* matrix */ {0xa0, 0xed, ZC3XX_R10B_RGB01}, {0xa0, 0xed, ZC3XX_R10C_RGB02}, {0xa0, 0xed, ZC3XX_R10D_RGB10}, {0xa0, 0x66, ZC3XX_R10E_RGB11}, {0xa0, 0xed, ZC3XX_R10F_RGB12}, {0xa0, 0xed, ZC3XX_R110_RGB20}, {0xa0, 0xed, ZC3XX_R111_RGB21}, {0xa0, 0x66, ZC3XX_R112_RGB22}, {0xa1, 0x01, 0x0180}, {0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /**** set exposure ***/ {0xaa, 0x13, 0x0031}, {0xaa, 0x14, 0x0001}, {0xaa, 0x0e, 0x0004}, {0xaa, 0x19, 0x00cd}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x02, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x62, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x3d, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x0c, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x28, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x04, ZC3XX_R01D_HSYNC_0}, {0xa0, 0x18, ZC3XX_R01E_HSYNC_1}, {0xa0, 0x2c, ZC3XX_R01F_HSYNC_2}, {0xa0, 0x41, ZC3XX_R020_HSYNC_3}, {0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN}, {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa1, 0x01, 0x0180}, {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x40, ZC3XX_R116_RGAIN}, {0xa0, 0x40, ZC3XX_R117_GGAIN}, {0xa0, 0x40, ZC3XX_R118_BGAIN}, {} }; static const struct usb_action hdcs2020_50HZ[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xaa, 0x13, 0x0018}, /* 00,13,18,aa */ {0xaa, 0x14, 0x0001}, /* 00,14,01,aa */ {0xaa, 0x0e, 0x0005}, /* 00,0e,05,aa */ {0xaa, 0x19, 0x001f}, /* 00,19,1f,aa */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x02, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,02,cc */ {0xa0, 0x76, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,76,cc */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0x46, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,46,cc */ {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */ {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */ {0xa0, 0x0c, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,0c,cc */ {0xa0, 0x28, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,28,cc */ {0xa0, 0x05, ZC3XX_R01D_HSYNC_0}, /* 00,1d,05,cc */ {0xa0, 0x1a, ZC3XX_R01E_HSYNC_1}, /* 00,1e,1a,cc */ {0xa0, 0x2f, ZC3XX_R01F_HSYNC_2}, /* 00,1f,2f,cc */ {} }; static const struct usb_action hdcs2020_60HZ[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xaa, 0x13, 0x0031}, /* 00,13,31,aa */ {0xaa, 0x14, 0x0001}, /* 00,14,01,aa */ {0xaa, 0x0e, 0x0004}, /* 00,0e,04,aa */ {0xaa, 0x19, 0x00cd}, /* 00,19,cd,aa */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x02, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,02,cc */ {0xa0, 0x62, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,62,cc */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0x3d, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,3d,cc */ {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */ {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */ {0xa0, 0x0c, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,0c,cc */ {0xa0, 0x28, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,28,cc */ {0xa0, 0x04, ZC3XX_R01D_HSYNC_0}, /* 00,1d,04,cc */ {0xa0, 0x18, ZC3XX_R01E_HSYNC_1}, /* 00,1e,18,cc */ {0xa0, 0x2c, ZC3XX_R01F_HSYNC_2}, /* 00,1f,2c,cc */ {} }; static const struct usb_action hdcs2020_NoFliker[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xaa, 0x13, 0x0010}, /* 00,13,10,aa */ {0xaa, 0x14, 0x0001}, /* 00,14,01,aa */ {0xaa, 0x0e, 0x0004}, /* 00,0e,04,aa */ {0xaa, 0x19, 0x0000}, /* 00,19,00,aa */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x02, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,02,cc */ {0xa0, 0x70, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,70,cc */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0x10, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,10,cc */ {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */ {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */ {0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,00,cc */ {0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,00,cc */ {0xa0, 0x04, ZC3XX_R01D_HSYNC_0}, /* 00,1d,04,cc */ {0xa0, 0x17, ZC3XX_R01E_HSYNC_1}, /* 00,1e,17,cc */ {0xa0, 0x2a, ZC3XX_R01F_HSYNC_2}, /* 00,1f,2a,cc */ {} }; static const struct usb_action hv7131b_InitialScale[] = { /* 320x240 */ {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, {0xa0, 0x10, ZC3XX_R002_CLOCKSELECT}, {0xa0, 0x00, ZC3XX_R010_CMOSSENSORSELECT}, {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, {0xa0, 0x77, ZC3XX_R101_SENSORCORRECTION}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* 00 */ {0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, {0xaa, 0x30, 0x002d}, {0xaa, 0x01, 0x0005}, {0xaa, 0x11, 0x0000}, {0xaa, 0x13, 0x0001}, /* {0xaa, 0x13, 0x0000}, */ {0xaa, 0x14, 0x0001}, {0xaa, 0x15, 0x00e8}, {0xaa, 0x16, 0x0002}, {0xaa, 0x17, 0x0086}, /* 00,17,88,aa */ {0xaa, 0x31, 0x0038}, {0xaa, 0x32, 0x0038}, {0xaa, 0x33, 0x0038}, {0xaa, 0x5b, 0x0001}, {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, {0xa0, 0x68, ZC3XX_R18D_YTARGET}, {0xa0, 0x60, ZC3XX_R1A8_DIGITALGAIN}, {0xa0, 0x00, 0x01ad}, {0xa0, 0xc0, 0x019b}, {0xa0, 0xa0, 0x019c}, {0xa0, 0x02, ZC3XX_R188_MINGAIN}, {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, {0xaa, 0x02, 0x0090}, /* 00,02,80,aa */ {} }; static const struct usb_action hv7131b_Initial[] = { /* 640x480*/ {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, {0xa0, 0x00, ZC3XX_R002_CLOCKSELECT}, {0xa0, 0x00, ZC3XX_R010_CMOSSENSORSELECT}, {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, {0xa0, 0x37, ZC3XX_R101_SENSORCORRECTION}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* 00 */ {0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, {0xaa, 0x30, 0x002d}, {0xaa, 0x01, 0x0005}, {0xaa, 0x11, 0x0001}, {0xaa, 0x13, 0x0000}, /* {0xaa, 0x13, 0x0001}; */ {0xaa, 0x14, 0x0001}, {0xaa, 0x15, 0x00e6}, {0xaa, 0x16, 0x0002}, {0xaa, 0x17, 0x0086}, {0xaa, 0x31, 0x0038}, {0xaa, 0x32, 0x0038}, {0xaa, 0x33, 0x0038}, {0xaa, 0x5b, 0x0001}, {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, {0xa0, 0x70, ZC3XX_R18D_YTARGET}, {0xa0, 0x60, ZC3XX_R1A8_DIGITALGAIN}, {0xa0, 0x00, 0x01ad}, {0xa0, 0xc0, 0x019b}, {0xa0, 0xa0, 0x019c}, {0xa0, 0x02, ZC3XX_R188_MINGAIN}, {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, {0xaa, 0x02, 0x0090}, /* {0xaa, 0x02, 0x0080}, */ {} }; static const struct usb_action hv7131b_50HZ[] = { /* 640x480*/ {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xaa, 0x25, 0x0007}, /* 00,25,07,aa */ {0xaa, 0x26, 0x0053}, /* 00,26,53,aa */ {0xaa, 0x27, 0x0000}, /* 00,27,00,aa */ {0xaa, 0x20, 0x0000}, /* 00,20,00,aa */ {0xaa, 0x21, 0x0050}, /* 00,21,50,aa */ {0xaa, 0x22, 0x001b}, /* 00,22,1b,aa */ {0xaa, 0x23, 0x00fc}, /* 00,23,fc,aa */ {0xa0, 0x2f, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,2f,cc */ {0xa0, 0x9b, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,9b,cc */ {0xa0, 0x80, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,80,cc */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0xea, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,ea,cc */ {0xa0, 0x60, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,60,cc */ {0xa0, 0x0c, ZC3XX_R18C_AEFREEZE}, /* 01,8c,0c,cc */ {0xa0, 0x18, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,18,cc */ {0xa0, 0x18, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,18,cc */ {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,24,cc */ {0xa0, 0x00, ZC3XX_R01D_HSYNC_0}, /* 00,1d,00,cc */ {0xa0, 0x50, ZC3XX_R01E_HSYNC_1}, /* 00,1e,50,cc */ {0xa0, 0x1b, ZC3XX_R01F_HSYNC_2}, /* 00,1f,1b,cc */ {0xa0, 0xfc, ZC3XX_R020_HSYNC_3}, /* 00,20,fc,cc */ {} }; static const struct usb_action hv7131b_50HZScale[] = { /* 320x240 */ {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xaa, 0x25, 0x0007}, /* 00,25,07,aa */ {0xaa, 0x26, 0x0053}, /* 00,26,53,aa */ {0xaa, 0x27, 0x0000}, /* 00,27,00,aa */ {0xaa, 0x20, 0x0000}, /* 00,20,00,aa */ {0xaa, 0x21, 0x0050}, /* 00,21,50,aa */ {0xaa, 0x22, 0x0012}, /* 00,22,12,aa */ {0xaa, 0x23, 0x0080}, /* 00,23,80,aa */ {0xa0, 0x2f, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,2f,cc */ {0xa0, 0x9b, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,9b,cc */ {0xa0, 0x80, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,80,cc */ {0xa0, 0x01, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,01,cc */ {0xa0, 0xd4, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,d4,cc */ {0xa0, 0xc0, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,c0,cc */ {0xa0, 0x07, ZC3XX_R18C_AEFREEZE}, /* 01,8c,07,cc */ {0xa0, 0x0f, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,0f,cc */ {0xa0, 0x18, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,18,cc */ {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,24,cc */ {0xa0, 0x00, ZC3XX_R01D_HSYNC_0}, /* 00,1d,00,cc */ {0xa0, 0x50, ZC3XX_R01E_HSYNC_1}, /* 00,1e,50,cc */ {0xa0, 0x12, ZC3XX_R01F_HSYNC_2}, /* 00,1f,12,cc */ {0xa0, 0x80, ZC3XX_R020_HSYNC_3}, /* 00,20,80,cc */ {} }; static const struct usb_action hv7131b_60HZ[] = { /* 640x480*/ {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xaa, 0x25, 0x0007}, /* 00,25,07,aa */ {0xaa, 0x26, 0x00a1}, /* 00,26,a1,aa */ {0xaa, 0x27, 0x0020}, /* 00,27,20,aa */ {0xaa, 0x20, 0x0000}, /* 00,20,00,aa */ {0xaa, 0x21, 0x0040}, /* 00,21,40,aa */ {0xaa, 0x22, 0x0013}, /* 00,22,13,aa */ {0xaa, 0x23, 0x004c}, /* 00,23,4c,aa */ {0xa0, 0x2f, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,2f,cc */ {0xa0, 0x4d, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,4d,cc */ {0xa0, 0x60, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,60,cc */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0xc3, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,c3,cc */ {0xa0, 0x50, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,50,cc */ {0xa0, 0x0c, ZC3XX_R18C_AEFREEZE}, /* 01,8c,0c,cc */ {0xa0, 0x18, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,18,cc */ {0xa0, 0x18, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,18,cc */ {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,24,cc */ {0xa0, 0x00, ZC3XX_R01D_HSYNC_0}, /* 00,1d,00,cc */ {0xa0, 0x40, ZC3XX_R01E_HSYNC_1}, /* 00,1e,40,cc */ {0xa0, 0x13, ZC3XX_R01F_HSYNC_2}, /* 00,1f,13,cc */ {0xa0, 0x4c, ZC3XX_R020_HSYNC_3}, /* 00,20,4c,cc */ {} }; static const struct usb_action hv7131b_60HZScale[] = { /* 320x240 */ {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xaa, 0x25, 0x0007}, /* 00,25,07,aa */ {0xaa, 0x26, 0x00a1}, /* 00,26,a1,aa */ {0xaa, 0x27, 0x0020}, /* 00,27,20,aa */ {0xaa, 0x20, 0x0000}, /* 00,20,00,aa */ {0xaa, 0x21, 0x00a0}, /* 00,21,a0,aa */ {0xaa, 0x22, 0x0016}, /* 00,22,16,aa */ {0xaa, 0x23, 0x0040}, /* 00,23,40,aa */ {0xa0, 0x2f, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,2f,cc */ {0xa0, 0x4d, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,4d,cc */ {0xa0, 0x60, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,60,cc */ {0xa0, 0x01, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,01,cc */ {0xa0, 0x86, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,86,cc */ {0xa0, 0xa0, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,a0,cc */ {0xa0, 0x07, ZC3XX_R18C_AEFREEZE}, /* 01,8c,07,cc */ {0xa0, 0x0f, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,0f,cc */ {0xa0, 0x18, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,18,cc */ {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,24,cc */ {0xa0, 0x00, ZC3XX_R01D_HSYNC_0}, /* 00,1d,00,cc */ {0xa0, 0xa0, ZC3XX_R01E_HSYNC_1}, /* 00,1e,a0,cc */ {0xa0, 0x16, ZC3XX_R01F_HSYNC_2}, /* 00,1f,16,cc */ {0xa0, 0x40, ZC3XX_R020_HSYNC_3}, /* 00,20,40,cc */ {} }; static const struct usb_action hv7131b_NoFliker[] = { /* 640x480*/ {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xaa, 0x25, 0x0003}, /* 00,25,03,aa */ {0xaa, 0x26, 0x0000}, /* 00,26,00,aa */ {0xaa, 0x27, 0x0000}, /* 00,27,00,aa */ {0xaa, 0x20, 0x0000}, /* 00,20,00,aa */ {0xaa, 0x21, 0x0010}, /* 00,21,10,aa */ {0xaa, 0x22, 0x0000}, /* 00,22,00,aa */ {0xaa, 0x23, 0x0003}, /* 00,23,03,aa */ {0xa0, 0x2f, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,2f,cc */ {0xa0, 0xf8, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,f8,cc */ {0xa0, 0x00, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,00,cc */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x02, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,02,cc */ {0xa0, 0x00, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,00,cc */ {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */ {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */ {0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,00,cc */ {0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,00,cc */ {0xa0, 0x00, ZC3XX_R01D_HSYNC_0}, /* 00,1d,00,cc */ {0xa0, 0x10, ZC3XX_R01E_HSYNC_1}, /* 00,1e,10,cc */ {0xa0, 0x00, ZC3XX_R01F_HSYNC_2}, /* 00,1f,00,cc */ {0xa0, 0x03, ZC3XX_R020_HSYNC_3}, /* 00,20,03,cc */ {} }; static const struct usb_action hv7131b_NoFlikerScale[] = { /* 320x240 */ {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xaa, 0x25, 0x0003}, /* 00,25,03,aa */ {0xaa, 0x26, 0x0000}, /* 00,26,00,aa */ {0xaa, 0x27, 0x0000}, /* 00,27,00,aa */ {0xaa, 0x20, 0x0000}, /* 00,20,00,aa */ {0xaa, 0x21, 0x00a0}, /* 00,21,a0,aa */ {0xaa, 0x22, 0x0016}, /* 00,22,16,aa */ {0xaa, 0x23, 0x0040}, /* 00,23,40,aa */ {0xa0, 0x2f, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,2f,cc */ {0xa0, 0xf8, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,f8,cc */ {0xa0, 0x00, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,00,cc */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x02, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,02,cc */ {0xa0, 0x00, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,00,cc */ {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */ {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */ {0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,00,cc */ {0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,00,cc */ {0xa0, 0x00, ZC3XX_R01D_HSYNC_0}, /* 00,1d,00,cc */ {0xa0, 0xa0, ZC3XX_R01E_HSYNC_1}, /* 00,1e,a0,cc */ {0xa0, 0x16, ZC3XX_R01F_HSYNC_2}, /* 00,1f,16,cc */ {0xa0, 0x40, ZC3XX_R020_HSYNC_3}, /* 00,20,40,cc */ {} }; /* from lPEPI264v.inf (hv7131b!) */ static const struct usb_action hv7131r_InitialScale[] = { {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, {0xa0, 0x10, ZC3XX_R002_CLOCKSELECT}, {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, {0xa0, 0x77, ZC3XX_R101_SENSORCORRECTION}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, {0xa0, 0x07, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, {0xa0, 0x01, ZC3XX_R09B_WINHEIGHTHIGH}, {0xa0, 0xe8, ZC3XX_R09C_WINHEIGHTLOW}, {0xa0, 0x02, ZC3XX_R09D_WINWIDTHHIGH}, {0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW}, {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, {0xa0, 0x07, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xdd, 0x00, 0x0200}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xaa, 0x01, 0x000c}, {0xaa, 0x11, 0x0000}, {0xaa, 0x13, 0x0000}, {0xaa, 0x14, 0x0001}, {0xaa, 0x15, 0x00e8}, {0xaa, 0x16, 0x0002}, {0xaa, 0x17, 0x0088}, {0xaa, 0x30, 0x000b}, {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, {0xa0, 0x78, ZC3XX_R18D_YTARGET}, {0xa0, 0x50, ZC3XX_R1A8_DIGITALGAIN}, {0xa0, 0x00, 0x01ad}, {0xa0, 0xc0, 0x019b}, {0xa0, 0xa0, 0x019c}, {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, {} }; static const struct usb_action hv7131r_Initial[] = { {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, {0xa0, 0x00, ZC3XX_R002_CLOCKSELECT}, {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, {0xa0, 0x77, ZC3XX_R101_SENSORCORRECTION}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, {0xa0, 0x07, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, {0xa0, 0x01, ZC3XX_R09B_WINHEIGHTHIGH}, {0xa0, 0xe6, ZC3XX_R09C_WINHEIGHTLOW}, {0xa0, 0x02, ZC3XX_R09D_WINWIDTHHIGH}, {0xa0, 0x86, ZC3XX_R09E_WINWIDTHLOW}, {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, {0xa0, 0x07, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xdd, 0x00, 0x0200}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xaa, 0x01, 0x000c}, {0xaa, 0x11, 0x0000}, {0xaa, 0x13, 0x0000}, {0xaa, 0x14, 0x0001}, {0xaa, 0x15, 0x00e6}, {0xaa, 0x16, 0x0002}, {0xaa, 0x17, 0x0086}, {0xaa, 0x30, 0x000b}, {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, {0xa0, 0x78, ZC3XX_R18D_YTARGET}, {0xa0, 0x50, ZC3XX_R1A8_DIGITALGAIN}, {0xa0, 0x00, 0x01ad}, {0xa0, 0xc0, 0x019b}, {0xa0, 0xa0, 0x019c}, {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, {} }; static const struct usb_action hv7131r_50HZ[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xa0, 0x06, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x68, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0xa0, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0xea, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x60, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x18, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x66, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x00, ZC3XX_R01D_HSYNC_0}, {0xa0, 0xd0, ZC3XX_R01E_HSYNC_1}, {0xa0, 0x00, ZC3XX_R01F_HSYNC_2}, {0xa0, 0x08, ZC3XX_R020_HSYNC_3}, {} }; static const struct usb_action hv7131r_50HZScale[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xa0, 0x0c, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0xd1, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x40, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x01, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0xd4, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0xc0, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x18, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x66, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x00, ZC3XX_R01D_HSYNC_0}, {0xa0, 0xd0, ZC3XX_R01E_HSYNC_1}, {0xa0, 0x00, ZC3XX_R01F_HSYNC_2}, {0xa0, 0x08, ZC3XX_R020_HSYNC_3}, {} }; static const struct usb_action hv7131r_60HZ[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xa0, 0x06, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x1a, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x80, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0xc3, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x50, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x18, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x66, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x00, ZC3XX_R01D_HSYNC_0}, {0xa0, 0xd0, ZC3XX_R01E_HSYNC_1}, {0xa0, 0x00, ZC3XX_R01F_HSYNC_2}, {0xa0, 0x08, ZC3XX_R020_HSYNC_3}, {} }; static const struct usb_action hv7131r_60HZScale[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xa0, 0x0c, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x35, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x00, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x01, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x86, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0xa0, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x18, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x66, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x00, ZC3XX_R01D_HSYNC_0}, {0xa0, 0xd0, ZC3XX_R01E_HSYNC_1}, {0xa0, 0x00, ZC3XX_R01F_HSYNC_2}, {0xa0, 0x08, ZC3XX_R020_HSYNC_3}, {} }; static const struct usb_action hv7131r_NoFliker[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xa0, 0x2f, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0xf8, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x00, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x02, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x58, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x0c, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x18, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x00, ZC3XX_R01D_HSYNC_0}, {0xa0, 0xd0, ZC3XX_R01E_HSYNC_1}, {0xa0, 0x00, ZC3XX_R01F_HSYNC_2}, {0xa0, 0x08, ZC3XX_R020_HSYNC_3}, {} }; static const struct usb_action hv7131r_NoFlikerScale[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xa0, 0x2f, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0xf8, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x00, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x04, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0xb0, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x0c, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x18, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x00, ZC3XX_R01D_HSYNC_0}, {0xa0, 0xd0, ZC3XX_R01E_HSYNC_1}, {0xa0, 0x00, ZC3XX_R01F_HSYNC_2}, {0xa0, 0x08, ZC3XX_R020_HSYNC_3}, {} }; static const struct usb_action icm105a_InitialScale[] = { {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, {0xa0, 0x10, ZC3XX_R002_CLOCKSELECT}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, {0xa0, 0x0c, ZC3XX_R010_CMOSSENSORSELECT}, {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, {0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0xa1, ZC3XX_R08B_I2CDEVICEADDR}, {0xa0, 0x00, ZC3XX_R097_WINYSTARTHIGH}, {0xa0, 0x01, ZC3XX_R098_WINYSTARTLOW}, {0xa0, 0x00, ZC3XX_R099_WINXSTARTHIGH}, {0xa0, 0x01, ZC3XX_R09A_WINXSTARTLOW}, {0xa0, 0x01, ZC3XX_R11A_FIRSTYLOW}, {0xa0, 0x01, ZC3XX_R11C_FIRSTXLOW}, {0xa0, 0x01, ZC3XX_R09B_WINHEIGHTHIGH}, {0xa0, 0xe8, ZC3XX_R09C_WINHEIGHTLOW}, {0xa0, 0x02, ZC3XX_R09D_WINWIDTHHIGH}, {0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW}, {0xa0, 0x37, ZC3XX_R101_SENSORCORRECTION}, {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, {0xaa, 0x01, 0x0010}, {0xaa, 0x03, 0x0000}, {0xaa, 0x04, 0x0001}, {0xaa, 0x05, 0x0020}, {0xaa, 0x06, 0x0001}, {0xaa, 0x08, 0x0000}, {0xaa, 0x03, 0x0001}, {0xaa, 0x04, 0x0011}, {0xaa, 0x05, 0x00a0}, {0xaa, 0x06, 0x0001}, {0xaa, 0x08, 0x0000}, {0xaa, 0x03, 0x0002}, {0xaa, 0x04, 0x0013}, {0xaa, 0x05, 0x0020}, {0xaa, 0x06, 0x0001}, {0xaa, 0x08, 0x0000}, {0xaa, 0x03, 0x0003}, {0xaa, 0x04, 0x0015}, {0xaa, 0x05, 0x0020}, {0xaa, 0x06, 0x0005}, {0xaa, 0x08, 0x0000}, {0xaa, 0x03, 0x0004}, {0xaa, 0x04, 0x0017}, {0xaa, 0x05, 0x0020}, {0xaa, 0x06, 0x000d}, {0xaa, 0x08, 0x0000}, {0xaa, 0x03, 0x0005}, {0xaa, 0x04, 0x0019}, {0xaa, 0x05, 0x0020}, {0xaa, 0x06, 0x0005}, {0xaa, 0x08, 0x0000}, {0xaa, 0x03, 0x0006}, {0xaa, 0x04, 0x0017}, {0xaa, 0x05, 0x0026}, {0xaa, 0x06, 0x0005}, {0xaa, 0x08, 0x0000}, {0xaa, 0x03, 0x0007}, {0xaa, 0x04, 0x0019}, {0xaa, 0x05, 0x0022}, {0xaa, 0x06, 0x0005}, {0xaa, 0x08, 0x0000}, {0xaa, 0x03, 0x0008}, {0xaa, 0x04, 0x0021}, {0xaa, 0x05, 0x00aa}, {0xaa, 0x06, 0x0005}, {0xaa, 0x08, 0x0000}, {0xaa, 0x03, 0x0009}, {0xaa, 0x04, 0x0023}, {0xaa, 0x05, 0x00aa}, {0xaa, 0x06, 0x000d}, {0xaa, 0x08, 0x0000}, {0xaa, 0x03, 0x000a}, {0xaa, 0x04, 0x0025}, {0xaa, 0x05, 0x00aa}, {0xaa, 0x06, 0x0005}, {0xaa, 0x08, 0x0000}, {0xaa, 0x03, 0x000b}, {0xaa, 0x04, 0x00ec}, {0xaa, 0x05, 0x002e}, {0xaa, 0x06, 0x0005}, {0xaa, 0x08, 0x0000}, {0xaa, 0x03, 0x000c}, {0xaa, 0x04, 0x00fa}, {0xaa, 0x05, 0x002a}, {0xaa, 0x06, 0x0005}, {0xaa, 0x08, 0x0000}, {0xaa, 0x07, 0x000d}, {0xaa, 0x01, 0x0005}, {0xaa, 0x94, 0x0002}, {0xaa, 0x90, 0x0000}, {0xaa, 0x91, 0x001f}, {0xaa, 0x10, 0x0064}, {0xaa, 0x9b, 0x00f0}, {0xaa, 0x9c, 0x0002}, {0xaa, 0x14, 0x001a}, {0xaa, 0x20, 0x0080}, {0xaa, 0x22, 0x0080}, {0xaa, 0x24, 0x0080}, {0xaa, 0x26, 0x0080}, {0xaa, 0x00, 0x0084}, {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, {0xaa, 0xa8, 0x00c0}, {0xa1, 0x01, 0x0002}, {0xa1, 0x01, 0x0008}, {0xa1, 0x01, 0x0180}, {0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x40, ZC3XX_R116_RGAIN}, {0xa0, 0x40, ZC3XX_R117_GGAIN}, {0xa0, 0x40, ZC3XX_R118_BGAIN}, {0xa1, 0x01, 0x0008}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* clock ? */ {0xa0, 0x08, ZC3XX_R1C6_SHARPNESS00}, /* sharpness+ */ {0xa1, 0x01, 0x01c8}, {0xa1, 0x01, 0x01c9}, {0xa1, 0x01, 0x01ca}, {0xa0, 0x0f, ZC3XX_R1CB_SHARPNESS05}, /* sharpness- */ {0xa0, 0x52, ZC3XX_R10A_RGB00}, /* matrix */ {0xa0, 0xf7, ZC3XX_R10B_RGB01}, {0xa0, 0xf7, ZC3XX_R10C_RGB02}, {0xa0, 0xf7, ZC3XX_R10D_RGB10}, {0xa0, 0x52, ZC3XX_R10E_RGB11}, {0xa0, 0xf7, ZC3XX_R10F_RGB12}, {0xa0, 0xf7, ZC3XX_R110_RGB20}, {0xa0, 0xf7, ZC3XX_R111_RGB21}, {0xa0, 0x52, ZC3XX_R112_RGB22}, {0xa1, 0x01, 0x0180}, {0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xaa, 0x0d, 0x0003}, {0xaa, 0x0c, 0x008c}, {0xaa, 0x0e, 0x0095}, {0xaa, 0x0f, 0x0002}, {0xaa, 0x1c, 0x0094}, {0xaa, 0x1d, 0x0002}, {0xaa, 0x20, 0x0080}, {0xaa, 0x22, 0x0080}, {0xaa, 0x24, 0x0080}, {0xaa, 0x26, 0x0080}, {0xaa, 0x00, 0x0084}, {0xa0, 0x02, ZC3XX_R0A3_EXPOSURETIMEHIGH}, {0xa0, 0x94, ZC3XX_R0A4_EXPOSURETIMELOW}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x20, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x84, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x12, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0xe3, ZC3XX_R01D_HSYNC_0}, {0xa0, 0xec, ZC3XX_R01E_HSYNC_1}, {0xa0, 0xf5, ZC3XX_R01F_HSYNC_2}, {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, {0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0xc0, ZC3XX_R1A8_DIGITALGAIN}, {0xa0, 0xc0, ZC3XX_R11D_GLOBALGAIN}, {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa1, 0x01, 0x0180}, {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x40, ZC3XX_R116_RGAIN}, {0xa0, 0x40, ZC3XX_R117_GGAIN}, {0xa0, 0x40, ZC3XX_R118_BGAIN}, {} }; static const struct usb_action icm105a_Initial[] = { {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, {0xa0, 0x00, ZC3XX_R002_CLOCKSELECT}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, {0xa0, 0x0c, ZC3XX_R010_CMOSSENSORSELECT}, {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, {0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0xa1, ZC3XX_R08B_I2CDEVICEADDR}, {0xa0, 0x00, ZC3XX_R097_WINYSTARTHIGH}, {0xa0, 0x02, ZC3XX_R098_WINYSTARTLOW}, {0xa0, 0x00, ZC3XX_R099_WINXSTARTHIGH}, {0xa0, 0x02, ZC3XX_R09A_WINXSTARTLOW}, {0xa0, 0x02, ZC3XX_R11A_FIRSTYLOW}, {0xa0, 0x02, ZC3XX_R11C_FIRSTXLOW}, {0xa0, 0x01, ZC3XX_R09B_WINHEIGHTHIGH}, {0xa0, 0xe6, ZC3XX_R09C_WINHEIGHTLOW}, {0xa0, 0x02, ZC3XX_R09D_WINWIDTHHIGH}, {0xa0, 0x86, ZC3XX_R09E_WINWIDTHLOW}, {0xa0, 0x77, ZC3XX_R101_SENSORCORRECTION}, {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, {0xaa, 0x01, 0x0010}, {0xaa, 0x03, 0x0000}, {0xaa, 0x04, 0x0001}, {0xaa, 0x05, 0x0020}, {0xaa, 0x06, 0x0001}, {0xaa, 0x08, 0x0000}, {0xaa, 0x03, 0x0001}, {0xaa, 0x04, 0x0011}, {0xaa, 0x05, 0x00a0}, {0xaa, 0x06, 0x0001}, {0xaa, 0x08, 0x0000}, {0xaa, 0x03, 0x0002}, {0xaa, 0x04, 0x0013}, {0xaa, 0x05, 0x0020}, {0xaa, 0x06, 0x0001}, {0xaa, 0x08, 0x0000}, {0xaa, 0x03, 0x0003}, {0xaa, 0x04, 0x0015}, {0xaa, 0x05, 0x0020}, {0xaa, 0x06, 0x0005}, {0xaa, 0x08, 0x0000}, {0xaa, 0x03, 0x0004}, {0xaa, 0x04, 0x0017}, {0xaa, 0x05, 0x0020}, {0xaa, 0x06, 0x000d}, {0xaa, 0x08, 0x0000}, {0xaa, 0x03, 0x0005}, {0xa0, 0x04, ZC3XX_R092_I2CADDRESSSELECT}, {0xa0, 0x19, ZC3XX_R093_I2CSETVALUE}, {0xa0, 0x01, ZC3XX_R090_I2CCOMMAND}, {0xa1, 0x01, 0x0091}, {0xaa, 0x05, 0x0020}, {0xaa, 0x06, 0x0005}, {0xaa, 0x08, 0x0000}, {0xaa, 0x03, 0x0006}, {0xaa, 0x04, 0x0017}, {0xaa, 0x05, 0x0026}, {0xaa, 0x06, 0x0005}, {0xaa, 0x08, 0x0000}, {0xaa, 0x03, 0x0007}, {0xaa, 0x04, 0x0019}, {0xaa, 0x05, 0x0022}, {0xaa, 0x06, 0x0005}, {0xaa, 0x08, 0x0000}, {0xaa, 0x03, 0x0008}, {0xaa, 0x04, 0x0021}, {0xaa, 0x05, 0x00aa}, {0xaa, 0x06, 0x0005}, {0xaa, 0x08, 0x0000}, {0xaa, 0x03, 0x0009}, {0xaa, 0x04, 0x0023}, {0xaa, 0x05, 0x00aa}, {0xaa, 0x06, 0x000d}, {0xaa, 0x08, 0x0000}, {0xaa, 0x03, 0x000a}, {0xaa, 0x04, 0x0025}, {0xaa, 0x05, 0x00aa}, {0xaa, 0x06, 0x0005}, {0xaa, 0x08, 0x0000}, {0xaa, 0x03, 0x000b}, {0xaa, 0x04, 0x00ec}, {0xaa, 0x05, 0x002e}, {0xaa, 0x06, 0x0005}, {0xaa, 0x08, 0x0000}, {0xaa, 0x03, 0x000c}, {0xaa, 0x04, 0x00fa}, {0xaa, 0x05, 0x002a}, {0xaa, 0x06, 0x0005}, {0xaa, 0x08, 0x0000}, {0xaa, 0x07, 0x000d}, {0xaa, 0x01, 0x0005}, {0xaa, 0x94, 0x0002}, {0xaa, 0x90, 0x0000}, {0xaa, 0x91, 0x0010}, {0xaa, 0x10, 0x0064}, {0xaa, 0x9b, 0x00f0}, {0xaa, 0x9c, 0x0002}, {0xaa, 0x14, 0x001a}, {0xaa, 0x20, 0x0080}, {0xaa, 0x22, 0x0080}, {0xaa, 0x24, 0x0080}, {0xaa, 0x26, 0x0080}, {0xaa, 0x00, 0x0084}, {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, {0xaa, 0xa8, 0x0080}, {0xa0, 0x78, ZC3XX_R18D_YTARGET}, {0xa1, 0x01, 0x0002}, {0xa1, 0x01, 0x0008}, {0xa1, 0x01, 0x0180}, {0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x40, ZC3XX_R116_RGAIN}, {0xa0, 0x40, ZC3XX_R117_GGAIN}, {0xa0, 0x40, ZC3XX_R118_BGAIN}, {0xa1, 0x01, 0x0008}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* clock ? */ {0xa0, 0x08, ZC3XX_R1C6_SHARPNESS00}, /* sharpness+ */ {0xa1, 0x01, 0x01c8}, {0xa1, 0x01, 0x01c9}, {0xa1, 0x01, 0x01ca}, {0xa0, 0x0f, ZC3XX_R1CB_SHARPNESS05}, /* sharpness- */ {0xa0, 0x52, ZC3XX_R10A_RGB00}, /* matrix */ {0xa0, 0xf7, ZC3XX_R10B_RGB01}, {0xa0, 0xf7, ZC3XX_R10C_RGB02}, {0xa0, 0xf7, ZC3XX_R10D_RGB10}, {0xa0, 0x52, ZC3XX_R10E_RGB11}, {0xa0, 0xf7, ZC3XX_R10F_RGB12}, {0xa0, 0xf7, ZC3XX_R110_RGB20}, {0xa0, 0xf7, ZC3XX_R111_RGB21}, {0xa0, 0x52, ZC3XX_R112_RGB22}, {0xa1, 0x01, 0x0180}, {0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xaa, 0x0d, 0x0003}, {0xaa, 0x0c, 0x0020}, {0xaa, 0x0e, 0x000e}, {0xaa, 0x0f, 0x0002}, {0xaa, 0x1c, 0x000d}, {0xaa, 0x1d, 0x0002}, {0xaa, 0x20, 0x0080}, {0xaa, 0x22, 0x0080}, {0xaa, 0x24, 0x0080}, {0xaa, 0x26, 0x0080}, {0xaa, 0x00, 0x0084}, {0xa0, 0x02, ZC3XX_R0A3_EXPOSURETIMEHIGH}, {0xa0, 0x0d, ZC3XX_R0A4_EXPOSURETIMELOW}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x1a, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x4b, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x12, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0xc8, ZC3XX_R01D_HSYNC_0}, {0xa0, 0xd8, ZC3XX_R01E_HSYNC_1}, {0xa0, 0xea, ZC3XX_R01F_HSYNC_2}, {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, {0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa1, 0x01, 0x0180}, {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x40, ZC3XX_R116_RGAIN}, {0xa0, 0x40, ZC3XX_R117_GGAIN}, {0xa0, 0x40, ZC3XX_R118_BGAIN}, {} }; static const struct usb_action icm105a_50HZScale[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xaa, 0x0d, 0x0003}, /* 00,0d,03,aa */ {0xaa, 0x0c, 0x0020}, /* 00,0c,20,aa */ {0xaa, 0x0e, 0x000e}, /* 00,0e,0e,aa */ {0xaa, 0x0f, 0x0002}, /* 00,0f,02,aa */ {0xaa, 0x1c, 0x000d}, /* 00,1c,0d,aa */ {0xaa, 0x1d, 0x0002}, /* 00,1d,02,aa */ {0xaa, 0x20, 0x0080}, /* 00,20,80,aa */ {0xaa, 0x22, 0x0080}, /* 00,22,80,aa */ {0xaa, 0x24, 0x0080}, /* 00,24,80,aa */ {0xaa, 0x26, 0x0080}, /* 00,26,80,aa */ {0xaa, 0x00, 0x0084}, /* 00,00,84,aa */ {0xa0, 0x02, ZC3XX_R0A3_EXPOSURETIMEHIGH}, /* 00,a3,02,cc */ {0xa0, 0x0d, ZC3XX_R0A4_EXPOSURETIMELOW}, /* 00,a4,0d,cc */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,04,cc */ {0xa0, 0x1a, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,1a,cc */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0x4b, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,4b,cc */ {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */ {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */ {0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,10,cc */ {0xa0, 0x12, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,12,cc */ {0xa0, 0xc8, ZC3XX_R01D_HSYNC_0}, /* 00,1d,c8,cc */ {0xa0, 0xd8, ZC3XX_R01E_HSYNC_1}, /* 00,1e,d8,cc */ {0xa0, 0xea, ZC3XX_R01F_HSYNC_2}, /* 00,1f,ea,cc */ {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */ {} }; static const struct usb_action icm105a_50HZ[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xaa, 0x0d, 0x0003}, /* 00,0d,03,aa */ {0xaa, 0x0c, 0x008c}, /* 00,0c,8c,aa */ {0xaa, 0x0e, 0x0095}, /* 00,0e,95,aa */ {0xaa, 0x0f, 0x0002}, /* 00,0f,02,aa */ {0xaa, 0x1c, 0x0094}, /* 00,1c,94,aa */ {0xaa, 0x1d, 0x0002}, /* 00,1d,02,aa */ {0xaa, 0x20, 0x0080}, /* 00,20,80,aa */ {0xaa, 0x22, 0x0080}, /* 00,22,80,aa */ {0xaa, 0x24, 0x0080}, /* 00,24,80,aa */ {0xaa, 0x26, 0x0080}, /* 00,26,80,aa */ {0xaa, 0x00, 0x0084}, /* 00,00,84,aa */ {0xa0, 0x02, ZC3XX_R0A3_EXPOSURETIMEHIGH}, /* 00,a3,02,cc */ {0xa0, 0x94, ZC3XX_R0A4_EXPOSURETIMELOW}, /* 00,a4,94,cc */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,04,cc */ {0xa0, 0x20, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,20,cc */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0x84, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,84,cc */ {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */ {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */ {0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,10,cc */ {0xa0, 0x12, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,12,cc */ {0xa0, 0xe3, ZC3XX_R01D_HSYNC_0}, /* 00,1d,e3,cc */ {0xa0, 0xec, ZC3XX_R01E_HSYNC_1}, /* 00,1e,ec,cc */ {0xa0, 0xf5, ZC3XX_R01F_HSYNC_2}, /* 00,1f,f5,cc */ {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */ {0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN}, /* 01,a7,00,cc */ {0xa0, 0xc0, ZC3XX_R1A8_DIGITALGAIN}, /* 01,a8,c0,cc */ {} }; static const struct usb_action icm105a_60HZScale[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xaa, 0x0d, 0x0003}, /* 00,0d,03,aa */ {0xaa, 0x0c, 0x0004}, /* 00,0c,04,aa */ {0xaa, 0x0e, 0x000d}, /* 00,0e,0d,aa */ {0xaa, 0x0f, 0x0002}, /* 00,0f,02,aa */ {0xaa, 0x1c, 0x0008}, /* 00,1c,08,aa */ {0xaa, 0x1d, 0x0002}, /* 00,1d,02,aa */ {0xaa, 0x20, 0x0080}, /* 00,20,80,aa */ {0xaa, 0x22, 0x0080}, /* 00,22,80,aa */ {0xaa, 0x24, 0x0080}, /* 00,24,80,aa */ {0xaa, 0x26, 0x0080}, /* 00,26,80,aa */ {0xaa, 0x00, 0x0084}, /* 00,00,84,aa */ {0xa0, 0x02, ZC3XX_R0A3_EXPOSURETIMEHIGH}, /* 00,a3,02,cc */ {0xa0, 0x08, ZC3XX_R0A4_EXPOSURETIMELOW}, /* 00,a4,08,cc */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,04,cc */ {0xa0, 0x10, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,10,cc */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0x41, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,41,cc */ {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */ {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */ {0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,10,cc */ {0xa0, 0x12, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,12,cc */ {0xa0, 0xc1, ZC3XX_R01D_HSYNC_0}, /* 00,1d,c1,cc */ {0xa0, 0xd4, ZC3XX_R01E_HSYNC_1}, /* 00,1e,d4,cc */ {0xa0, 0xe8, ZC3XX_R01F_HSYNC_2}, /* 00,1f,e8,cc */ {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */ {} }; static const struct usb_action icm105a_60HZ[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xaa, 0x0d, 0x0003}, /* 00,0d,03,aa */ {0xaa, 0x0c, 0x0008}, /* 00,0c,08,aa */ {0xaa, 0x0e, 0x0086}, /* 00,0e,86,aa */ {0xaa, 0x0f, 0x0002}, /* 00,0f,02,aa */ {0xaa, 0x1c, 0x0085}, /* 00,1c,85,aa */ {0xaa, 0x1d, 0x0002}, /* 00,1d,02,aa */ {0xaa, 0x20, 0x0080}, /* 00,20,80,aa */ {0xaa, 0x22, 0x0080}, /* 00,22,80,aa */ {0xaa, 0x24, 0x0080}, /* 00,24,80,aa */ {0xaa, 0x26, 0x0080}, /* 00,26,80,aa */ {0xaa, 0x00, 0x0084}, /* 00,00,84,aa */ {0xa0, 0x02, ZC3XX_R0A3_EXPOSURETIMEHIGH}, /* 00,a3,02,cc */ {0xa0, 0x85, ZC3XX_R0A4_EXPOSURETIMELOW}, /* 00,a4,85,cc */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,04,cc */ {0xa0, 0x08, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,08,cc */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0x81, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,81,cc */ {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */ {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */ {0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,10,cc */ {0xa0, 0x12, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,12,cc */ {0xa0, 0xc2, ZC3XX_R01D_HSYNC_0}, /* 00,1d,c2,cc */ {0xa0, 0xd6, ZC3XX_R01E_HSYNC_1}, /* 00,1e,d6,cc */ {0xa0, 0xea, ZC3XX_R01F_HSYNC_2}, /* 00,1f,ea,cc */ {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */ {0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN}, /* 01,a7,00,cc */ {0xa0, 0xc0, ZC3XX_R1A8_DIGITALGAIN}, /* 01,a8,c0,cc */ {} }; static const struct usb_action icm105a_NoFlikerScale[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xaa, 0x0d, 0x0003}, /* 00,0d,03,aa */ {0xaa, 0x0c, 0x0004}, /* 00,0c,04,aa */ {0xaa, 0x0e, 0x000d}, /* 00,0e,0d,aa */ {0xaa, 0x0f, 0x0002}, /* 00,0f,02,aa */ {0xaa, 0x1c, 0x0000}, /* 00,1c,00,aa */ {0xaa, 0x1d, 0x0002}, /* 00,1d,02,aa */ {0xaa, 0x20, 0x0080}, /* 00,20,80,aa */ {0xaa, 0x22, 0x0080}, /* 00,22,80,aa */ {0xaa, 0x24, 0x0080}, /* 00,24,80,aa */ {0xaa, 0x26, 0x0080}, /* 00,26,80,aa */ {0xaa, 0x00, 0x0084}, /* 00,00,84,aa */ {0xa0, 0x02, ZC3XX_R0A3_EXPOSURETIMEHIGH}, /* 00,a3,02,cc */ {0xa0, 0x00, ZC3XX_R0A4_EXPOSURETIMELOW}, /* 00,a4,00,cc */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,04,cc */ {0xa0, 0x20, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,20,cc */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0x10, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,10,cc */ {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */ {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */ {0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,00,cc */ {0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,00,cc */ {0xa0, 0xc1, ZC3XX_R01D_HSYNC_0}, /* 00,1d,c1,cc */ {0xa0, 0xd4, ZC3XX_R01E_HSYNC_1}, /* 00,1e,d4,cc */ {0xa0, 0xe8, ZC3XX_R01F_HSYNC_2}, /* 00,1f,e8,cc */ {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */ {} }; static const struct usb_action icm105a_NoFliker[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xaa, 0x0d, 0x0003}, /* 00,0d,03,aa */ {0xaa, 0x0c, 0x0004}, /* 00,0c,04,aa */ {0xaa, 0x0e, 0x0081}, /* 00,0e,81,aa */ {0xaa, 0x0f, 0x0002}, /* 00,0f,02,aa */ {0xaa, 0x1c, 0x0080}, /* 00,1c,80,aa */ {0xaa, 0x1d, 0x0002}, /* 00,1d,02,aa */ {0xaa, 0x20, 0x0080}, /* 00,20,80,aa */ {0xaa, 0x22, 0x0080}, /* 00,22,80,aa */ {0xaa, 0x24, 0x0080}, /* 00,24,80,aa */ {0xaa, 0x26, 0x0080}, /* 00,26,80,aa */ {0xaa, 0x00, 0x0084}, /* 00,00,84,aa */ {0xa0, 0x02, ZC3XX_R0A3_EXPOSURETIMEHIGH}, /* 00,a3,02,cc */ {0xa0, 0x80, ZC3XX_R0A4_EXPOSURETIMELOW}, /* 00,a4,80,cc */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,04,cc */ {0xa0, 0x20, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,20,cc */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0x10, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,10,cc */ {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */ {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */ {0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,00,cc */ {0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,00,cc */ {0xa0, 0xc1, ZC3XX_R01D_HSYNC_0}, /* 00,1d,c1,cc */ {0xa0, 0xd4, ZC3XX_R01E_HSYNC_1}, /* 00,1e,d4,cc */ {0xa0, 0xe8, ZC3XX_R01F_HSYNC_2}, /* 00,1f,e8,cc */ {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */ {0xa0, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN}, /* 01,a7,00,cc */ {0xa0, 0xc0, ZC3XX_R1A8_DIGITALGAIN}, /* 01,a8,c0,cc */ {} }; static const struct usb_action mc501cb_Initial[] = { {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc */ {0xa0, 0x00, ZC3XX_R002_CLOCKSELECT}, /* 00,02,00,cc */ {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */ {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc */ {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* 00,08,03,cc */ {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc */ {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc */ {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc */ {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc */ {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc */ {0xa0, 0xd8, ZC3XX_R006_FRAMEHEIGHTLOW}, /* 00,06,d8,cc */ {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,00,cc */ {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,00,cc */ {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,00,cc */ {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,00,cc */ {0xa0, 0x01, ZC3XX_R09B_WINHEIGHTHIGH}, /* 00,9b,01,cc */ {0xa0, 0xde, ZC3XX_R09C_WINHEIGHTLOW}, /* 00,9c,de,cc */ {0xa0, 0x02, ZC3XX_R09D_WINWIDTHHIGH}, /* 00,9d,02,cc */ {0xa0, 0x86, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,86,cc */ {0xa0, 0x33, ZC3XX_R086_EXPTIMEHIGH}, /* 00,86,33,cc */ {0xa0, 0x34, ZC3XX_R087_EXPTIMEMID}, /* 00,87,34,cc */ {0xa0, 0x35, ZC3XX_R088_EXPTIMELOW}, /* 00,88,35,cc */ {0xa0, 0xb0, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,b0,cc */ {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc */ {0xaa, 0x01, 0x0001}, /* 00,01,01,aa */ {0xaa, 0x01, 0x0003}, /* 00,01,03,aa */ {0xaa, 0x01, 0x0001}, /* 00,01,01,aa */ {0xaa, 0x03, 0x0000}, /* 00,03,00,aa */ {0xaa, 0x10, 0x0000}, /* 00,10,00,aa */ {0xaa, 0x11, 0x0080}, /* 00,11,80,aa */ {0xaa, 0x12, 0x0000}, /* 00,12,00,aa */ {0xaa, 0x13, 0x0000}, /* 00,13,00,aa */ {0xaa, 0x14, 0x0000}, /* 00,14,00,aa */ {0xaa, 0x15, 0x0000}, /* 00,15,00,aa */ {0xaa, 0x16, 0x0000}, /* 00,16,00,aa */ {0xaa, 0x17, 0x0001}, /* 00,17,01,aa */ {0xaa, 0x18, 0x00de}, /* 00,18,de,aa */ {0xaa, 0x19, 0x0002}, /* 00,19,02,aa */ {0xaa, 0x1a, 0x0086}, /* 00,1a,86,aa */ {0xaa, 0x20, 0x00a8}, /* 00,20,a8,aa */ {0xaa, 0x22, 0x0000}, /* 00,22,00,aa */ {0xaa, 0x23, 0x0000}, /* 00,23,00,aa */ {0xaa, 0x24, 0x0000}, /* 00,24,00,aa */ {0xaa, 0x40, 0x0033}, /* 00,40,33,aa */ {0xaa, 0x41, 0x0077}, /* 00,41,77,aa */ {0xaa, 0x42, 0x0053}, /* 00,42,53,aa */ {0xaa, 0x43, 0x00b0}, /* 00,43,b0,aa */ {0xaa, 0x4b, 0x0001}, /* 00,4b,01,aa */ {0xaa, 0x72, 0x0020}, /* 00,72,20,aa */ {0xaa, 0x73, 0x0000}, /* 00,73,00,aa */ {0xaa, 0x80, 0x0000}, /* 00,80,00,aa */ {0xaa, 0x85, 0x0050}, /* 00,85,50,aa */ {0xaa, 0x91, 0x0070}, /* 00,91,70,aa */ {0xaa, 0x92, 0x0072}, /* 00,92,72,aa */ {0xaa, 0x03, 0x0001}, /* 00,03,01,aa */ {0xaa, 0x10, 0x00a0}, /* 00,10,a0,aa */ {0xaa, 0x11, 0x0001}, /* 00,11,01,aa */ {0xaa, 0x30, 0x0000}, /* 00,30,00,aa */ {0xaa, 0x60, 0x0000}, /* 00,60,00,aa */ {0xaa, 0xa0, 0x001a}, /* 00,a0,1a,aa */ {0xaa, 0xa1, 0x0000}, /* 00,a1,00,aa */ {0xaa, 0xa2, 0x003f}, /* 00,a2,3f,aa */ {0xaa, 0xa3, 0x0028}, /* 00,a3,28,aa */ {0xaa, 0xa4, 0x0010}, /* 00,a4,10,aa */ {0xaa, 0xa5, 0x0020}, /* 00,a5,20,aa */ {0xaa, 0xb1, 0x0044}, /* 00,b1,44,aa */ {0xaa, 0xd0, 0x0001}, /* 00,d0,01,aa */ {0xaa, 0xd1, 0x0085}, /* 00,d1,85,aa */ {0xaa, 0xd2, 0x0080}, /* 00,d2,80,aa */ {0xaa, 0xd3, 0x0080}, /* 00,d3,80,aa */ {0xaa, 0xd4, 0x0080}, /* 00,d4,80,aa */ {0xaa, 0xd5, 0x0080}, /* 00,d5,80,aa */ {0xaa, 0xc0, 0x00c3}, /* 00,c0,c3,aa */ {0xaa, 0xc2, 0x0044}, /* 00,c2,44,aa */ {0xaa, 0xc4, 0x0040}, /* 00,c4,40,aa */ {0xaa, 0xc5, 0x0020}, /* 00,c5,20,aa */ {0xaa, 0xc6, 0x0008}, /* 00,c6,08,aa */ {0xaa, 0x03, 0x0004}, /* 00,03,04,aa */ {0xaa, 0x10, 0x0000}, /* 00,10,00,aa */ {0xaa, 0x40, 0x0030}, /* 00,40,30,aa */ {0xaa, 0x41, 0x0020}, /* 00,41,20,aa */ {0xaa, 0x42, 0x002d}, /* 00,42,2d,aa */ {0xaa, 0x03, 0x0003}, /* 00,03,03,aa */ {0xaa, 0x1c, 0x0050}, /* 00,1C,50,aa */ {0xaa, 0x11, 0x0081}, /* 00,11,81,aa */ {0xaa, 0x3b, 0x001d}, /* 00,3b,1D,aa */ {0xaa, 0x3c, 0x004c}, /* 00,3c,4C,aa */ {0xaa, 0x3d, 0x0018}, /* 00,3d,18,aa */ {0xaa, 0x3e, 0x006a}, /* 00,3e,6A,aa */ {0xaa, 0x01, 0x0000}, /* 00,01,00,aa */ {0xaa, 0x52, 0x00ff}, /* 00,52,FF,aa */ {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc */ {0xa0, 0x37, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,37,cc */ {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, /* 01,89,06,cc */ {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc */ {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc */ {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc */ {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc */ {0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,02,cc */ {0xaa, 0x03, 0x0002}, /* 00,03,02,aa */ {0xaa, 0x51, 0x0027}, /* 00,51,27,aa */ {0xaa, 0x52, 0x0020}, /* 00,52,20,aa */ {0xaa, 0x03, 0x0003}, /* 00,03,03,aa */ {0xaa, 0x50, 0x0010}, /* 00,50,10,aa */ {0xaa, 0x51, 0x0010}, /* 00,51,10,aa */ {0xaa, 0x54, 0x0010}, /* 00,54,10,aa */ {0xaa, 0x55, 0x0010}, /* 00,55,10,aa */ {0xa0, 0xf0, 0x0199}, /* 01,99,F0,cc */ {0xa0, 0x80, 0x019a}, /* 01,9A,80,cc */ {0xaa, 0x03, 0x0003}, /* 00,03,03,aa */ {0xaa, 0x10, 0x00fc}, /* 00,10,fc,aa */ {0xaa, 0x36, 0x001d}, /* 00,36,1D,aa */ {0xaa, 0x37, 0x004c}, /* 00,37,4C,aa */ {0xaa, 0x3b, 0x001d}, /* 00,3B,1D,aa */ {} }; static const struct usb_action mc501cb_InitialScale[] = { /* 320x240 */ {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc */ {0xa0, 0x10, ZC3XX_R002_CLOCKSELECT}, /* 00,02,10,cc */ {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */ {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc */ {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* 00,08,03,cc */ {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc */ {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc */ {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc */ {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc */ {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc */ {0xa0, 0xd0, ZC3XX_R006_FRAMEHEIGHTLOW}, /* 00,06,d0,cc */ {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,00,cc */ {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,00,cc */ {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,00,cc */ {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,00,cc */ {0xa0, 0x01, ZC3XX_R09B_WINHEIGHTHIGH}, /* 00,9b,01,cc */ {0xa0, 0xd8, ZC3XX_R09C_WINHEIGHTLOW}, /* 00,9c,d8,cc */ {0xa0, 0x02, ZC3XX_R09D_WINWIDTHHIGH}, /* 00,9d,02,cc */ {0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,88,cc */ {0xa0, 0x33, ZC3XX_R086_EXPTIMEHIGH}, /* 00,86,33,cc */ {0xa0, 0x34, ZC3XX_R087_EXPTIMEMID}, /* 00,87,34,cc */ {0xa0, 0x35, ZC3XX_R088_EXPTIMELOW}, /* 00,88,35,cc */ {0xa0, 0xb0, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,b0,cc */ {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc */ {0xaa, 0x01, 0x0001}, /* 00,01,01,aa */ {0xaa, 0x01, 0x0003}, /* 00,01,03,aa */ {0xaa, 0x01, 0x0001}, /* 00,01,01,aa */ {0xaa, 0x03, 0x0000}, /* 00,03,00,aa */ {0xaa, 0x10, 0x0000}, /* 00,10,00,aa */ {0xaa, 0x11, 0x0080}, /* 00,11,80,aa */ {0xaa, 0x12, 0x0000}, /* 00,12,00,aa */ {0xaa, 0x13, 0x0000}, /* 00,13,00,aa */ {0xaa, 0x14, 0x0000}, /* 00,14,00,aa */ {0xaa, 0x15, 0x0000}, /* 00,15,00,aa */ {0xaa, 0x16, 0x0000}, /* 00,16,00,aa */ {0xaa, 0x17, 0x0001}, /* 00,17,01,aa */ {0xaa, 0x18, 0x00d8}, /* 00,18,d8,aa */ {0xaa, 0x19, 0x0002}, /* 00,19,02,aa */ {0xaa, 0x1a, 0x0088}, /* 00,1a,88,aa */ {0xaa, 0x20, 0x00a8}, /* 00,20,a8,aa */ {0xaa, 0x22, 0x0000}, /* 00,22,00,aa */ {0xaa, 0x23, 0x0000}, /* 00,23,00,aa */ {0xaa, 0x24, 0x0000}, /* 00,24,00,aa */ {0xaa, 0x40, 0x0033}, /* 00,40,33,aa */ {0xaa, 0x41, 0x0077}, /* 00,41,77,aa */ {0xaa, 0x42, 0x0053}, /* 00,42,53,aa */ {0xaa, 0x43, 0x00b0}, /* 00,43,b0,aa */ {0xaa, 0x4b, 0x0001}, /* 00,4b,01,aa */ {0xaa, 0x72, 0x0020}, /* 00,72,20,aa */ {0xaa, 0x73, 0x0000}, /* 00,73,00,aa */ {0xaa, 0x80, 0x0000}, /* 00,80,00,aa */ {0xaa, 0x85, 0x0050}, /* 00,85,50,aa */ {0xaa, 0x91, 0x0070}, /* 00,91,70,aa */ {0xaa, 0x92, 0x0072}, /* 00,92,72,aa */ {0xaa, 0x03, 0x0001}, /* 00,03,01,aa */ {0xaa, 0x10, 0x00a0}, /* 00,10,a0,aa */ {0xaa, 0x11, 0x0001}, /* 00,11,01,aa */ {0xaa, 0x30, 0x0000}, /* 00,30,00,aa */ {0xaa, 0x60, 0x0000}, /* 00,60,00,aa */ {0xaa, 0xa0, 0x001a}, /* 00,a0,1a,aa */ {0xaa, 0xa1, 0x0000}, /* 00,a1,00,aa */ {0xaa, 0xa2, 0x003f}, /* 00,a2,3f,aa */ {0xaa, 0xa3, 0x0028}, /* 00,a3,28,aa */ {0xaa, 0xa4, 0x0010}, /* 00,a4,10,aa */ {0xaa, 0xa5, 0x0020}, /* 00,a5,20,aa */ {0xaa, 0xb1, 0x0044}, /* 00,b1,44,aa */ {0xaa, 0xd0, 0x0001}, /* 00,d0,01,aa */ {0xaa, 0xd1, 0x0085}, /* 00,d1,85,aa */ {0xaa, 0xd2, 0x0080}, /* 00,d2,80,aa */ {0xaa, 0xd3, 0x0080}, /* 00,d3,80,aa */ {0xaa, 0xd4, 0x0080}, /* 00,d4,80,aa */ {0xaa, 0xd5, 0x0080}, /* 00,d5,80,aa */ {0xaa, 0xc0, 0x00c3}, /* 00,c0,c3,aa */ {0xaa, 0xc2, 0x0044}, /* 00,c2,44,aa */ {0xaa, 0xc4, 0x0040}, /* 00,c4,40,aa */ {0xaa, 0xc5, 0x0020}, /* 00,c5,20,aa */ {0xaa, 0xc6, 0x0008}, /* 00,c6,08,aa */ {0xaa, 0x03, 0x0004}, /* 00,03,04,aa */ {0xaa, 0x10, 0x0000}, /* 00,10,00,aa */ {0xaa, 0x40, 0x0030}, /* 00,40,30,aa */ {0xaa, 0x41, 0x0020}, /* 00,41,20,aa */ {0xaa, 0x42, 0x002d}, /* 00,42,2d,aa */ {0xaa, 0x03, 0x0003}, /* 00,03,03,aa */ {0xaa, 0x1c, 0x0050}, /* 00,1c,50,aa */ {0xaa, 0x11, 0x0081}, /* 00,11,81,aa */ {0xaa, 0x3b, 0x003a}, /* 00,3b,3A,aa */ {0xaa, 0x3c, 0x0098}, /* 00,3c,98,aa */ {0xaa, 0x3d, 0x0030}, /* 00,3d,30,aa */ {0xaa, 0x3e, 0x00d4}, /* 00,3E,D4,aa */ {0xaa, 0x01, 0x0000}, /* 00,01,00,aa */ {0xaa, 0x52, 0x00ff}, /* 00,52,FF,aa */ {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc */ {0xa0, 0x37, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,37,cc */ {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, /* 01,89,06,cc */ {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc */ {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc */ {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc */ {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc */ {0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,02,cc */ {0xaa, 0x03, 0x0002}, /* 00,03,02,aa */ {0xaa, 0x51, 0x004e}, /* 00,51,4E,aa */ {0xaa, 0x52, 0x0041}, /* 00,52,41,aa */ {0xaa, 0x03, 0x0003}, /* 00,03,03,aa */ {0xaa, 0x50, 0x0010}, /* 00,50,10,aa */ {0xaa, 0x51, 0x0010}, /* 00,51,10,aa */ {0xaa, 0x54, 0x0010}, /* 00,54,10,aa */ {0xaa, 0x55, 0x0010}, /* 00,55,10,aa */ {0xa0, 0xf0, 0x0199}, /* 01,99,F0,cc */ {0xa0, 0x80, 0x019a}, /* 01,9A,80,cc */ {} }; static const struct usb_action mc501cb_50HZ[] = { {0xaa, 0x03, 0x0003}, /* 00,03,03,aa */ {0xaa, 0x10, 0x00fc}, /* 00,10,fc,aa */ {0xaa, 0x36, 0x001d}, /* 00,36,1D,aa */ {0xaa, 0x37, 0x004c}, /* 00,37,4C,aa */ {0xaa, 0x3b, 0x001d}, /* 00,3B,1D,aa */ {0xaa, 0x3c, 0x004c}, /* 00,3C,4C,aa */ {0xaa, 0x3d, 0x001d}, /* 00,3D,1D,aa */ {0xaa, 0x3e, 0x004c}, /* 00,3E,4C,aa */ {} }; static const struct usb_action mc501cb_50HZScale[] = { {0xaa, 0x03, 0x0003}, /* 00,03,03,aa */ {0xaa, 0x10, 0x00fc}, /* 00,10,fc,aa */ {0xaa, 0x36, 0x003a}, /* 00,36,3A,aa */ {0xaa, 0x37, 0x0098}, /* 00,37,98,aa */ {0xaa, 0x3b, 0x003a}, /* 00,3B,3A,aa */ {0xaa, 0x3c, 0x0098}, /* 00,3C,98,aa */ {0xaa, 0x3d, 0x003a}, /* 00,3D,3A,aa */ {0xaa, 0x3e, 0x0098}, /* 00,3E,98,aa */ {} }; static const struct usb_action mc501cb_60HZ[] = { {0xaa, 0x03, 0x0003}, /* 00,03,03,aa */ {0xaa, 0x10, 0x00fc}, /* 00,10,fc,aa */ {0xaa, 0x36, 0x0018}, /* 00,36,18,aa */ {0xaa, 0x37, 0x006a}, /* 00,37,6A,aa */ {0xaa, 0x3d, 0x0018}, /* 00,3D,18,aa */ {0xaa, 0x3e, 0x006a}, /* 00,3E,6A,aa */ {0xaa, 0x3b, 0x0018}, /* 00,3B,18,aa */ {0xaa, 0x3c, 0x006a}, /* 00,3C,6A,aa */ {} }; static const struct usb_action mc501cb_60HZScale[] = { {0xaa, 0x03, 0x0003}, /* 00,03,03,aa */ {0xaa, 0x10, 0x00fc}, /* 00,10,fc,aa */ {0xaa, 0x36, 0x0030}, /* 00,36,30,aa */ {0xaa, 0x37, 0x00d4}, /* 00,37,D4,aa */ {0xaa, 0x3d, 0x0030}, /* 00,3D,30,aa */ {0xaa, 0x3e, 0x00d4}, /* 00,3E,D4,aa */ {0xaa, 0x3b, 0x0030}, /* 00,3B,30,aa */ {0xaa, 0x3c, 0x00d4}, /* 00,3C,D4,aa */ {} }; static const struct usb_action mc501cb_NoFliker[] = { {0xaa, 0x03, 0x0003}, /* 00,03,03,aa */ {0xaa, 0x10, 0x00fc}, /* 00,10,fc,aa */ {0xaa, 0x36, 0x0018}, /* 00,36,18,aa */ {0xaa, 0x37, 0x006a}, /* 00,37,6A,aa */ {0xaa, 0x3d, 0x0018}, /* 00,3D,18,aa */ {0xaa, 0x3e, 0x006a}, /* 00,3E,6A,aa */ {0xaa, 0x3b, 0x0018}, /* 00,3B,18,aa */ {0xaa, 0x3c, 0x006a}, /* 00,3C,6A,aa */ {} }; static const struct usb_action mc501cb_NoFlikerScale[] = { {0xaa, 0x03, 0x0003}, /* 00,03,03,aa */ {0xaa, 0x10, 0x00fc}, /* 00,10,fc,aa */ {0xaa, 0x36, 0x0030}, /* 00,36,30,aa */ {0xaa, 0x37, 0x00d4}, /* 00,37,D4,aa */ {0xaa, 0x3d, 0x0030}, /* 00,3D,30,aa */ {0xaa, 0x3e, 0x00d4}, /* 00,3E,D4,aa */ {0xaa, 0x3b, 0x0030}, /* 00,3B,30,aa */ {0xaa, 0x3c, 0x00d4}, /* 00,3C,D4,aa */ {} }; /* from zs211.inf */ static const struct usb_action ov7620_Initial[] = { /* 640x480 */ {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc */ {0xa0, 0x40, ZC3XX_R002_CLOCKSELECT}, /* 00,02,40,cc */ {0xa0, 0x00, ZC3XX_R008_CLOCKSETTING}, /* 00,08,00,cc */ {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc */ {0xa0, 0x06, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,06,cc */ {0xa0, 0x02, ZC3XX_R083_RGAINADDR}, /* 00,83,02,cc */ {0xa0, 0x01, ZC3XX_R085_BGAINADDR}, /* 00,85,01,cc */ {0xa0, 0x80, ZC3XX_R086_EXPTIMEHIGH}, /* 00,86,80,cc */ {0xa0, 0x81, ZC3XX_R087_EXPTIMEMID}, /* 00,87,81,cc */ {0xa0, 0x10, ZC3XX_R088_EXPTIMELOW}, /* 00,88,10,cc */ {0xa0, 0xa1, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,a1,cc */ {0xa0, 0x08, ZC3XX_R08D_COMPABILITYMODE}, /* 00,8d,08,cc */ {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc */ {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc */ {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc */ {0xa0, 0xd8, ZC3XX_R006_FRAMEHEIGHTLOW}, /* 00,06,d8,cc */ {0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,03,cc */ {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc */ {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,00,cc */ {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,00,cc */ {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,00,cc */ {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,00,cc */ {0xa0, 0xde, ZC3XX_R09C_WINHEIGHTLOW}, /* 00,9c,de,cc */ {0xa0, 0x86, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,86,cc */ {0xaa, 0x12, 0x0088}, /* 00,12,88,aa */ {0xaa, 0x12, 0x0048}, /* 00,12,48,aa */ {0xaa, 0x75, 0x008a}, /* 00,75,8a,aa */ {0xaa, 0x13, 0x00a3}, /* 00,13,a3,aa */ {0xaa, 0x04, 0x0000}, /* 00,04,00,aa */ {0xaa, 0x05, 0x0000}, /* 00,05,00,aa */ {0xaa, 0x14, 0x0000}, /* 00,14,00,aa */ {0xaa, 0x15, 0x0004}, /* 00,15,04,aa */ {0xaa, 0x17, 0x0018}, /* 00,17,18,aa */ {0xaa, 0x18, 0x00ba}, /* 00,18,ba,aa */ {0xaa, 0x19, 0x0002}, /* 00,19,02,aa */ {0xaa, 0x1a, 0x00f1}, /* 00,1a,f1,aa */ {0xaa, 0x20, 0x0040}, /* 00,20,40,aa */ {0xaa, 0x24, 0x0088}, /* 00,24,88,aa */ {0xaa, 0x25, 0x0078}, /* 00,25,78,aa */ {0xaa, 0x27, 0x00f6}, /* 00,27,f6,aa */ {0xaa, 0x28, 0x00a0}, /* 00,28,a0,aa */ {0xaa, 0x21, 0x0000}, /* 00,21,00,aa */ {0xaa, 0x2a, 0x0083}, /* 00,2a,83,aa */ {0xaa, 0x2b, 0x0096}, /* 00,2b,96,aa */ {0xaa, 0x2d, 0x0005}, /* 00,2d,05,aa */ {0xaa, 0x74, 0x0020}, /* 00,74,20,aa */ {0xaa, 0x61, 0x0068}, /* 00,61,68,aa */ {0xaa, 0x64, 0x0088}, /* 00,64,88,aa */ {0xaa, 0x00, 0x0000}, /* 00,00,00,aa */ {0xaa, 0x06, 0x0080}, /* 00,06,80,aa */ {0xaa, 0x01, 0x0090}, /* 00,01,90,aa */ {0xaa, 0x02, 0x0030}, /* 00,02,30,aa */ {0xa0, 0x77, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,77,cc */ {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc */ {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc */ {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, /* 01,89,06,cc */ {0xa0, 0x00, 0x01ad}, /* 01,ad,00,cc */ {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc */ {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc */ {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc */ {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc */ {0xa0, 0x68, ZC3XX_R116_RGAIN}, /* 01,16,68,cc */ {0xa0, 0x52, ZC3XX_R118_BGAIN}, /* 01,18,52,cc */ {0xa0, 0x40, ZC3XX_R11D_GLOBALGAIN}, /* 01,1d,40,cc */ {0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,02,cc */ {0xa0, 0x50, ZC3XX_R1A8_DIGITALGAIN}, /* 01,a8,50,cc */ {} }; static const struct usb_action ov7620_InitialScale[] = { /* 320x240 */ {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc */ {0xa0, 0x50, ZC3XX_R002_CLOCKSELECT}, /* 00,02,50,cc */ {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* 00,08,00,cc */ /* mx change? */ {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc */ {0xa0, 0x06, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,06,cc */ {0xa0, 0x02, ZC3XX_R083_RGAINADDR}, /* 00,83,02,cc */ {0xa0, 0x01, ZC3XX_R085_BGAINADDR}, /* 00,85,01,cc */ {0xa0, 0x80, ZC3XX_R086_EXPTIMEHIGH}, /* 00,86,80,cc */ {0xa0, 0x81, ZC3XX_R087_EXPTIMEMID}, /* 00,87,81,cc */ {0xa0, 0x10, ZC3XX_R088_EXPTIMELOW}, /* 00,88,10,cc */ {0xa0, 0xa1, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,a1,cc */ {0xa0, 0x08, ZC3XX_R08D_COMPABILITYMODE}, /* 00,8d,08,cc */ {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc */ {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc */ {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc */ {0xa0, 0xd0, ZC3XX_R006_FRAMEHEIGHTLOW}, /* 00,06,d0,cc */ {0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,03,cc */ {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc */ {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,00,cc */ {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,00,cc */ {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,00,cc */ {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,00,cc */ {0xa0, 0xd6, ZC3XX_R09C_WINHEIGHTLOW}, /* 00,9c,d6,cc */ /* OV7648 00,9c,d8,cc */ {0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,88,cc */ {0xaa, 0x12, 0x0088}, /* 00,12,88,aa */ {0xaa, 0x12, 0x0048}, /* 00,12,48,aa */ {0xaa, 0x75, 0x008a}, /* 00,75,8a,aa */ {0xaa, 0x13, 0x00a3}, /* 00,13,a3,aa */ {0xaa, 0x04, 0x0000}, /* 00,04,00,aa */ {0xaa, 0x05, 0x0000}, /* 00,05,00,aa */ {0xaa, 0x14, 0x0000}, /* 00,14,00,aa */ {0xaa, 0x15, 0x0004}, /* 00,15,04,aa */ {0xaa, 0x24, 0x0088}, /* 00,24,88,aa */ {0xaa, 0x25, 0x0078}, /* 00,25,78,aa */ {0xaa, 0x17, 0x0018}, /* 00,17,18,aa */ {0xaa, 0x18, 0x00ba}, /* 00,18,ba,aa */ {0xaa, 0x19, 0x0002}, /* 00,19,02,aa */ {0xaa, 0x1a, 0x00f2}, /* 00,1a,f2,aa */ {0xaa, 0x20, 0x0040}, /* 00,20,40,aa */ {0xaa, 0x27, 0x00f6}, /* 00,27,f6,aa */ {0xaa, 0x28, 0x00a0}, /* 00,28,a0,aa */ {0xaa, 0x21, 0x0000}, /* 00,21,00,aa */ {0xaa, 0x2a, 0x0083}, /* 00,2a,83,aa */ {0xaa, 0x2b, 0x0096}, /* 00,2b,96,aa */ {0xaa, 0x2d, 0x0005}, /* 00,2d,05,aa */ {0xaa, 0x74, 0x0020}, /* 00,74,20,aa */ {0xaa, 0x61, 0x0068}, /* 00,61,68,aa */ {0xaa, 0x64, 0x0088}, /* 00,64,88,aa */ {0xaa, 0x00, 0x0000}, /* 00,00,00,aa */ {0xaa, 0x06, 0x0080}, /* 00,06,80,aa */ {0xaa, 0x01, 0x0090}, /* 00,01,90,aa */ {0xaa, 0x02, 0x0030}, /* 00,02,30,aa */ {0xa0, 0x77, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,77,cc */ {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc */ {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc */ {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, /* 01,89,06,cc */ {0xa0, 0x00, 0x01ad}, /* 01,ad,00,cc */ {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc */ {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc */ {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc */ {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc */ {0xa0, 0x68, ZC3XX_R116_RGAIN}, /* 01,16,68,cc */ {0xa0, 0x52, ZC3XX_R118_BGAIN}, /* 01,18,52,cc */ {0xa0, 0x50, ZC3XX_R11D_GLOBALGAIN}, /* 01,1d,50,cc */ {0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,02,cc */ {0xa0, 0x50, ZC3XX_R1A8_DIGITALGAIN}, /* 01,a8,50,cc */ {} }; static const struct usb_action ov7620_50HZ[] = { {0xaa, 0x13, 0x00a3}, /* 00,13,a3,aa */ {0xdd, 0x00, 0x0100}, /* 00,01,00,dd */ {0xaa, 0x2b, 0x0096}, /* 00,2b,96,aa */ {0xaa, 0x75, 0x008a}, /* 00,75,8a,aa */ {0xaa, 0x2d, 0x0005}, /* 00,2d,05,aa */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,04,cc */ {0xa0, 0x18, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,18,cc */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0x83, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,83,cc */ {0xaa, 0x10, 0x0082}, /* 00,10,82,aa */ {0xaa, 0x76, 0x0003}, /* 00,76,03,aa */ /* {0xa0, 0x40, ZC3XX_R002_CLOCKSELECT}, * 00,02,40,cc * if mode0 (640x480) */ {} }; static const struct usb_action ov7620_60HZ[] = { {0xaa, 0x13, 0x00a3}, /* 00,13,a3,aa */ /* (bug in zs211.inf) */ {0xdd, 0x00, 0x0100}, /* 00,01,00,dd */ {0xaa, 0x2b, 0x0000}, /* 00,2b,00,aa */ {0xaa, 0x75, 0x008a}, /* 00,75,8a,aa */ {0xaa, 0x2d, 0x0005}, /* 00,2d,05,aa */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,04,cc */ {0xa0, 0x18, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,18,cc */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0x83, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,83,cc */ {0xaa, 0x10, 0x0020}, /* 00,10,20,aa */ {0xaa, 0x76, 0x0003}, /* 00,76,03,aa */ /* {0xa0, 0x40, ZC3XX_R002_CLOCKSELECT}, * 00,02,40,cc * if mode0 (640x480) */ /* ?? in gspca v1, it was {0xa0, 0x00, 0x0039}, * 00,00,00,dd * {0xa1, 0x01, 0x0037}, */ {} }; static const struct usb_action ov7620_NoFliker[] = { {0xaa, 0x13, 0x00a3}, /* 00,13,a3,aa */ /* (bug in zs211.inf) */ {0xdd, 0x00, 0x0100}, /* 00,01,00,dd */ {0xaa, 0x2b, 0x0000}, /* 00,2b,00,aa */ {0xaa, 0x75, 0x008e}, /* 00,75,8e,aa */ {0xaa, 0x2d, 0x0001}, /* 00,2d,01,aa */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,04,cc */ {0xa0, 0x18, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,18,cc */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0x01, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,01,cc */ /* {0xa0, 0x44, ZC3XX_R002_CLOCKSELECT}, * 00,02,44,cc * if mode1 (320x240) */ /* ?? was {0xa0, 0x00, 0x0039}, * 00,00,00,dd * {0xa1, 0x01, 0x0037}, */ {} }; static const struct usb_action ov7630c_InitialScale[] = { {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, {0xa0, 0x10, ZC3XX_R002_CLOCKSELECT}, {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, {0xa0, 0x10, ZC3XX_R002_CLOCKSELECT}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, {0xa0, 0x06, ZC3XX_R010_CMOSSENSORSELECT}, {0xa0, 0xa1, ZC3XX_R08B_I2CDEVICEADDR}, {0xa0, 0x08, ZC3XX_R08D_COMPABILITYMODE}, {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xaa, 0x12, 0x0080}, {0xa0, 0x02, ZC3XX_R083_RGAINADDR}, {0xa0, 0x01, ZC3XX_R085_BGAINADDR}, {0xa0, 0x90, ZC3XX_R086_EXPTIMEHIGH}, {0xa0, 0x91, ZC3XX_R087_EXPTIMEMID}, {0xa0, 0x10, ZC3XX_R088_EXPTIMELOW}, {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, {0xa0, 0xd8, ZC3XX_R09C_WINHEIGHTLOW}, {0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW}, {0xaa, 0x12, 0x0069}, {0xaa, 0x04, 0x0020}, {0xaa, 0x06, 0x0050}, {0xaa, 0x13, 0x0083}, {0xaa, 0x14, 0x0000}, {0xaa, 0x15, 0x0024}, {0xaa, 0x17, 0x0018}, {0xaa, 0x18, 0x00ba}, {0xaa, 0x19, 0x0002}, {0xaa, 0x1a, 0x00f6}, {0xaa, 0x1b, 0x0002}, {0xaa, 0x20, 0x00c2}, {0xaa, 0x24, 0x0060}, {0xaa, 0x25, 0x0040}, {0xaa, 0x26, 0x0030}, {0xaa, 0x27, 0x00ea}, {0xaa, 0x28, 0x00a0}, {0xaa, 0x21, 0x0000}, {0xaa, 0x2a, 0x0081}, {0xaa, 0x2b, 0x0096}, {0xaa, 0x2d, 0x0094}, {0xaa, 0x2f, 0x003d}, {0xaa, 0x30, 0x0024}, {0xaa, 0x60, 0x0000}, {0xaa, 0x61, 0x0040}, {0xaa, 0x68, 0x007c}, {0xaa, 0x6f, 0x0015}, {0xaa, 0x75, 0x0088}, {0xaa, 0x77, 0x00b5}, {0xaa, 0x01, 0x0060}, {0xaa, 0x02, 0x0060}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x77, ZC3XX_R101_SENSORCORRECTION}, {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, {0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x00, 0x01ad}, {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, {0xa0, 0x60, ZC3XX_R116_RGAIN}, {0xa0, 0x46, ZC3XX_R118_BGAIN}, {0xa0, 0x04, ZC3XX_R113_RGB03}, /* 0x10, */ {0xa1, 0x01, 0x0002}, {0xa0, 0x50, ZC3XX_R10A_RGB00}, /* matrix */ {0xa0, 0xf8, ZC3XX_R10B_RGB01}, {0xa0, 0xf8, ZC3XX_R10C_RGB02}, {0xa0, 0xf8, ZC3XX_R10D_RGB10}, {0xa0, 0x50, ZC3XX_R10E_RGB11}, {0xa0, 0xf8, ZC3XX_R10F_RGB12}, {0xa0, 0xf8, ZC3XX_R110_RGB20}, {0xa0, 0xf8, ZC3XX_R111_RGB21}, {0xa0, 0x50, ZC3XX_R112_RGB22}, {0xa1, 0x01, 0x0008}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* clock ? */ {0xa0, 0x08, ZC3XX_R1C6_SHARPNESS00}, /* sharpness+ */ {0xa1, 0x01, 0x01c8}, {0xa1, 0x01, 0x01c9}, {0xa1, 0x01, 0x01ca}, {0xa0, 0x0f, ZC3XX_R1CB_SHARPNESS05}, /* sharpness- */ {0xa0, 0x01, ZC3XX_R120_GAMMA00}, /* gamma 2 ?*/ {0xa0, 0x0c, ZC3XX_R121_GAMMA01}, {0xa0, 0x1f, ZC3XX_R122_GAMMA02}, {0xa0, 0x3a, ZC3XX_R123_GAMMA03}, {0xa0, 0x53, ZC3XX_R124_GAMMA04}, {0xa0, 0x6d, ZC3XX_R125_GAMMA05}, {0xa0, 0x85, ZC3XX_R126_GAMMA06}, {0xa0, 0x9c, ZC3XX_R127_GAMMA07}, {0xa0, 0xb0, ZC3XX_R128_GAMMA08}, {0xa0, 0xc2, ZC3XX_R129_GAMMA09}, {0xa0, 0xd1, ZC3XX_R12A_GAMMA0A}, {0xa0, 0xde, ZC3XX_R12B_GAMMA0B}, {0xa0, 0xe9, ZC3XX_R12C_GAMMA0C}, {0xa0, 0xf2, ZC3XX_R12D_GAMMA0D}, {0xa0, 0xf9, ZC3XX_R12E_GAMMA0E}, {0xa0, 0xff, ZC3XX_R12F_GAMMA0F}, {0xa0, 0x05, ZC3XX_R130_GAMMA10}, {0xa0, 0x0f, ZC3XX_R131_GAMMA11}, {0xa0, 0x16, ZC3XX_R132_GAMMA12}, {0xa0, 0x1a, ZC3XX_R133_GAMMA13}, {0xa0, 0x19, ZC3XX_R134_GAMMA14}, {0xa0, 0x19, ZC3XX_R135_GAMMA15}, {0xa0, 0x17, ZC3XX_R136_GAMMA16}, {0xa0, 0x15, ZC3XX_R137_GAMMA17}, {0xa0, 0x12, ZC3XX_R138_GAMMA18}, {0xa0, 0x10, ZC3XX_R139_GAMMA19}, {0xa0, 0x0e, ZC3XX_R13A_GAMMA1A}, {0xa0, 0x0b, ZC3XX_R13B_GAMMA1B}, {0xa0, 0x09, ZC3XX_R13C_GAMMA1C}, {0xa0, 0x08, ZC3XX_R13D_GAMMA1D}, {0xa0, 0x06, ZC3XX_R13E_GAMMA1E}, {0xa0, 0x03, ZC3XX_R13F_GAMMA1F}, {0xa0, 0x50, ZC3XX_R10A_RGB00}, /* matrix */ {0xa0, 0xf8, ZC3XX_R10B_RGB01}, {0xa0, 0xf8, ZC3XX_R10C_RGB02}, {0xa0, 0xf8, ZC3XX_R10D_RGB10}, {0xa0, 0x50, ZC3XX_R10E_RGB11}, {0xa0, 0xf8, ZC3XX_R10F_RGB12}, {0xa0, 0xf8, ZC3XX_R110_RGB20}, {0xa0, 0xf8, ZC3XX_R111_RGB21}, {0xa0, 0x50, ZC3XX_R112_RGB22}, {0xa1, 0x01, 0x0180}, {0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE}, {0xaa, 0x10, 0x001b}, {0xaa, 0x76, 0x0002}, {0xaa, 0x2a, 0x0081}, {0xaa, 0x2b, 0x0000}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x01, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0xb8, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x37, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x26, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x50, ZC3XX_R11D_GLOBALGAIN}, {0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x40, ZC3XX_R180_AUTOCORRECTENABLE}, {0xaa, 0x13, 0x0083}, /* 40 */ {0xa1, 0x01, 0x0180}, {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, {} }; static const struct usb_action ov7630c_Initial[] = { {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, {0xa0, 0x00, ZC3XX_R002_CLOCKSELECT}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, {0xa0, 0x06, ZC3XX_R010_CMOSSENSORSELECT}, {0xa0, 0xa1, ZC3XX_R08B_I2CDEVICEADDR}, {0xa0, 0x08, ZC3XX_R08D_COMPABILITYMODE}, {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xaa, 0x12, 0x0080}, {0xa0, 0x02, ZC3XX_R083_RGAINADDR}, {0xa0, 0x01, ZC3XX_R085_BGAINADDR}, {0xa0, 0x90, ZC3XX_R086_EXPTIMEHIGH}, {0xa0, 0x91, ZC3XX_R087_EXPTIMEMID}, {0xa0, 0x10, ZC3XX_R088_EXPTIMELOW}, {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, {0xa0, 0xe6, ZC3XX_R09C_WINHEIGHTLOW}, {0xa0, 0x86, ZC3XX_R09E_WINWIDTHLOW}, {0xaa, 0x12, 0x0069}, /* i2c */ {0xaa, 0x04, 0x0020}, {0xaa, 0x06, 0x0050}, {0xaa, 0x13, 0x00c3}, {0xaa, 0x14, 0x0000}, {0xaa, 0x15, 0x0024}, {0xaa, 0x19, 0x0003}, {0xaa, 0x1a, 0x00f6}, {0xaa, 0x1b, 0x0002}, {0xaa, 0x20, 0x00c2}, {0xaa, 0x24, 0x0060}, {0xaa, 0x25, 0x0040}, {0xaa, 0x26, 0x0030}, {0xaa, 0x27, 0x00ea}, {0xaa, 0x28, 0x00a0}, {0xaa, 0x21, 0x0000}, {0xaa, 0x2a, 0x0081}, {0xaa, 0x2b, 0x0096}, {0xaa, 0x2d, 0x0084}, {0xaa, 0x2f, 0x003d}, {0xaa, 0x30, 0x0024}, {0xaa, 0x60, 0x0000}, {0xaa, 0x61, 0x0040}, {0xaa, 0x68, 0x007c}, {0xaa, 0x6f, 0x0015}, {0xaa, 0x75, 0x0088}, {0xaa, 0x77, 0x00b5}, {0xaa, 0x01, 0x0060}, {0xaa, 0x02, 0x0060}, {0xaa, 0x17, 0x0018}, {0xaa, 0x18, 0x00ba}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x77, ZC3XX_R101_SENSORCORRECTION}, {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, {0xa0, 0x04, ZC3XX_R1A7_CALCGLOBALMEAN}, {0xa0, 0x00, 0x01ad}, {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, {0xa0, 0x60, ZC3XX_R116_RGAIN}, {0xa0, 0x46, ZC3XX_R118_BGAIN}, {0xa0, 0x04, ZC3XX_R113_RGB03}, {0xa1, 0x01, 0x0002}, {0xa0, 0x4e, ZC3XX_R10A_RGB00}, /* matrix */ {0xa0, 0xfe, ZC3XX_R10B_RGB01}, {0xa0, 0xf4, ZC3XX_R10C_RGB02}, {0xa0, 0xf7, ZC3XX_R10D_RGB10}, {0xa0, 0x4d, ZC3XX_R10E_RGB11}, {0xa0, 0xfc, ZC3XX_R10F_RGB12}, {0xa0, 0x00, ZC3XX_R110_RGB20}, {0xa0, 0xf6, ZC3XX_R111_RGB21}, {0xa0, 0x4a, ZC3XX_R112_RGB22}, {0xa1, 0x01, 0x0008}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* clock ? */ {0xa0, 0x08, ZC3XX_R1C6_SHARPNESS00}, /* sharpness+ */ {0xa1, 0x01, 0x01c8}, {0xa1, 0x01, 0x01c9}, {0xa1, 0x01, 0x01ca}, {0xa0, 0x0f, ZC3XX_R1CB_SHARPNESS05}, /* sharpness- */ {0xa0, 0x16, ZC3XX_R120_GAMMA00}, /* gamma ~4 */ {0xa0, 0x3a, ZC3XX_R121_GAMMA01}, {0xa0, 0x5b, ZC3XX_R122_GAMMA02}, {0xa0, 0x7c, ZC3XX_R123_GAMMA03}, {0xa0, 0x94, ZC3XX_R124_GAMMA04}, {0xa0, 0xa9, ZC3XX_R125_GAMMA05}, {0xa0, 0xbb, ZC3XX_R126_GAMMA06}, {0xa0, 0xca, ZC3XX_R127_GAMMA07}, {0xa0, 0xd7, ZC3XX_R128_GAMMA08}, {0xa0, 0xe1, ZC3XX_R129_GAMMA09}, {0xa0, 0xea, ZC3XX_R12A_GAMMA0A}, {0xa0, 0xf1, ZC3XX_R12B_GAMMA0B}, {0xa0, 0xf7, ZC3XX_R12C_GAMMA0C}, {0xa0, 0xfc, ZC3XX_R12D_GAMMA0D}, {0xa0, 0xff, ZC3XX_R12E_GAMMA0E}, {0xa0, 0xff, ZC3XX_R12F_GAMMA0F}, {0xa0, 0x20, ZC3XX_R130_GAMMA10}, {0xa0, 0x22, ZC3XX_R131_GAMMA11}, {0xa0, 0x20, ZC3XX_R132_GAMMA12}, {0xa0, 0x1c, ZC3XX_R133_GAMMA13}, {0xa0, 0x16, ZC3XX_R134_GAMMA14}, {0xa0, 0x13, ZC3XX_R135_GAMMA15}, {0xa0, 0x10, ZC3XX_R136_GAMMA16}, {0xa0, 0x0d, ZC3XX_R137_GAMMA17}, {0xa0, 0x0b, ZC3XX_R138_GAMMA18}, {0xa0, 0x09, ZC3XX_R139_GAMMA19}, {0xa0, 0x07, ZC3XX_R13A_GAMMA1A}, {0xa0, 0x06, ZC3XX_R13B_GAMMA1B}, {0xa0, 0x05, ZC3XX_R13C_GAMMA1C}, {0xa0, 0x04, ZC3XX_R13D_GAMMA1D}, {0xa0, 0x00, ZC3XX_R13E_GAMMA1E}, {0xa0, 0x01, ZC3XX_R13F_GAMMA1F}, {0xa0, 0x4e, ZC3XX_R10A_RGB00}, /* matrix */ {0xa0, 0xfe, ZC3XX_R10B_RGB01}, {0xa0, 0xf4, ZC3XX_R10C_RGB02}, {0xa0, 0xf7, ZC3XX_R10D_RGB10}, {0xa0, 0x4d, ZC3XX_R10E_RGB11}, {0xa0, 0xfc, ZC3XX_R10F_RGB12}, {0xa0, 0x00, ZC3XX_R110_RGB20}, {0xa0, 0xf6, ZC3XX_R111_RGB21}, {0xa0, 0x4a, ZC3XX_R112_RGB22}, {0xa1, 0x01, 0x0180}, {0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE}, {0xaa, 0x10, 0x000d}, {0xaa, 0x76, 0x0002}, {0xaa, 0x2a, 0x0081}, {0xaa, 0x2b, 0x0000}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x00, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0xd8, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x1b, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x26, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x50, ZC3XX_R11D_GLOBALGAIN}, {0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x40, ZC3XX_R180_AUTOCORRECTENABLE}, {0xaa, 0x13, 0x00c3}, {0xa1, 0x01, 0x0180}, {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, {} }; static const struct usb_action pas106b_Initial_com[] = { /* Sream and Sensor specific */ {0xa1, 0x01, 0x0010}, /* CMOSSensorSelect */ /* System */ {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* SystemControl */ {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* SystemControl */ /* Picture size */ {0xa0, 0x00, ZC3XX_R002_CLOCKSELECT}, /* ClockSelect */ {0xa0, 0x03, 0x003a}, {0xa0, 0x0c, 0x003b}, {0xa0, 0x04, 0x0038}, {} }; static const struct usb_action pas106b_InitialScale[] = { /* 176x144 */ /* JPEG control */ {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* Sream and Sensor specific */ {0xa0, 0x0f, ZC3XX_R010_CMOSSENSORSELECT}, /* Picture size */ {0xa0, 0x00, ZC3XX_R003_FRAMEWIDTHHIGH}, {0xa0, 0xb0, ZC3XX_R004_FRAMEWIDTHLOW}, {0xa0, 0x00, ZC3XX_R005_FRAMEHEIGHTHIGH}, {0xa0, 0x90, ZC3XX_R006_FRAMEHEIGHTLOW}, /* System */ {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* Sream and Sensor specific */ {0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* Sensor Interface */ {0xa0, 0x08, ZC3XX_R08D_COMPABILITYMODE}, /* Window inside sensor array */ {0xa0, 0x03, ZC3XX_R09A_WINXSTARTLOW}, {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, {0xa0, 0x03, ZC3XX_R11C_FIRSTXLOW}, {0xa0, 0x28, ZC3XX_R09C_WINHEIGHTLOW}, {0xa0, 0x68, ZC3XX_R09E_WINWIDTHLOW}, /* Init the sensor */ {0xaa, 0x02, 0x0004}, {0xaa, 0x08, 0x0000}, {0xaa, 0x09, 0x0005}, {0xaa, 0x0a, 0x0002}, {0xaa, 0x0b, 0x0002}, {0xaa, 0x0c, 0x0005}, {0xaa, 0x0d, 0x0000}, {0xaa, 0x0e, 0x0002}, {0xaa, 0x14, 0x0081}, /* Other registers */ {0xa0, 0x37, ZC3XX_R101_SENSORCORRECTION}, /* Frame retreiving */ {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* Gains */ {0xa0, 0xa0, ZC3XX_R1A8_DIGITALGAIN}, /* Unknown */ {0xa0, 0x00, 0x01ad}, /* Sharpness */ {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* Other registers */ {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* Auto exposure and white balance */ {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, /*Dead pixels */ {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* EEPROM */ {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* JPEG control */ {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, {0xa0, 0x08, ZC3XX_R1C6_SHARPNESS00}, {0xa0, 0x0f, ZC3XX_R1CB_SHARPNESS05}, /* Other registers */ {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* Auto exposure and white balance */ {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, /*Dead pixels */ {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* EEPROM */ {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* JPEG control */ {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, {0xa0, 0x08, ZC3XX_R1C6_SHARPNESS00}, {0xa0, 0x0f, ZC3XX_R1CB_SHARPNESS05}, {0xa0, 0x58, ZC3XX_R10A_RGB00}, /* matrix */ {0xa0, 0xf4, ZC3XX_R10B_RGB01}, {0xa0, 0xf4, ZC3XX_R10C_RGB02}, {0xa0, 0xf4, ZC3XX_R10D_RGB10}, {0xa0, 0x58, ZC3XX_R10E_RGB11}, {0xa0, 0xf4, ZC3XX_R10F_RGB12}, {0xa0, 0xf4, ZC3XX_R110_RGB20}, {0xa0, 0xf4, ZC3XX_R111_RGB21}, {0xa0, 0x58, ZC3XX_R112_RGB22}, /* Auto correction */ {0xa0, 0x03, ZC3XX_R181_WINXSTART}, {0xa0, 0x08, ZC3XX_R182_WINXWIDTH}, {0xa0, 0x16, ZC3XX_R183_WINXCENTER}, {0xa0, 0x03, ZC3XX_R184_WINYSTART}, {0xa0, 0x05, ZC3XX_R185_WINYWIDTH}, {0xa0, 0x14, ZC3XX_R186_WINYCENTER}, {0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE}, /* Auto exposure and white balance */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x03, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0xb1, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x87, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x0c, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x18, ZC3XX_R18F_AEUNFREEZE}, /* sensor on */ {0xaa, 0x07, 0x00b1}, {0xaa, 0x05, 0x0003}, {0xaa, 0x04, 0x0001}, {0xaa, 0x03, 0x003b}, /* Gains */ {0xa0, 0x20, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x26, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0xa0, ZC3XX_R11D_GLOBALGAIN}, {0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN}, /* Auto correction */ {0xa0, 0x40, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa1, 0x01, 0x0180}, /* AutoCorrectEnable */ {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, /* Gains */ {0xa0, 0x40, ZC3XX_R116_RGAIN}, {0xa0, 0x40, ZC3XX_R117_GGAIN}, {0xa0, 0x40, ZC3XX_R118_BGAIN}, {} }; static const struct usb_action pas106b_Initial[] = { /* 352x288 */ /* JPEG control */ {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* Sream and Sensor specific */ {0xa0, 0x0f, ZC3XX_R010_CMOSSENSORSELECT}, /* Picture size */ {0xa0, 0x01, ZC3XX_R003_FRAMEWIDTHHIGH}, {0xa0, 0x60, ZC3XX_R004_FRAMEWIDTHLOW}, {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, {0xa0, 0x20, ZC3XX_R006_FRAMEHEIGHTLOW}, /* System */ {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* Sream and Sensor specific */ {0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* Sensor Interface */ {0xa0, 0x08, ZC3XX_R08D_COMPABILITYMODE}, /* Window inside sensor array */ {0xa0, 0x03, ZC3XX_R09A_WINXSTARTLOW}, {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, {0xa0, 0x03, ZC3XX_R11C_FIRSTXLOW}, {0xa0, 0x28, ZC3XX_R09C_WINHEIGHTLOW}, {0xa0, 0x68, ZC3XX_R09E_WINWIDTHLOW}, /* Init the sensor */ {0xaa, 0x02, 0x0004}, {0xaa, 0x08, 0x0000}, {0xaa, 0x09, 0x0005}, {0xaa, 0x0a, 0x0002}, {0xaa, 0x0b, 0x0002}, {0xaa, 0x0c, 0x0005}, {0xaa, 0x0d, 0x0000}, {0xaa, 0x0e, 0x0002}, {0xaa, 0x14, 0x0081}, /* Other registers */ {0xa0, 0x37, ZC3XX_R101_SENSORCORRECTION}, /* Frame retreiving */ {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* Gains */ {0xa0, 0xa0, ZC3XX_R1A8_DIGITALGAIN}, /* Unknown */ {0xa0, 0x00, 0x01ad}, /* Sharpness */ {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* Other registers */ {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* Auto exposure and white balance */ {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, {0xa0, 0x80, ZC3XX_R18D_YTARGET}, /*Dead pixels */ {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* EEPROM */ {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* JPEG control */ {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, {0xa0, 0x08, ZC3XX_R1C6_SHARPNESS00}, {0xa0, 0x0f, ZC3XX_R1CB_SHARPNESS05}, /* Other registers */ {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* Auto exposure and white balance */ {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, /*Dead pixels */ {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* EEPROM */ {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* JPEG control */ {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, {0xa0, 0x08, ZC3XX_R1C6_SHARPNESS00}, {0xa0, 0x0f, ZC3XX_R1CB_SHARPNESS05}, {0xa0, 0x58, ZC3XX_R10A_RGB00}, /* matrix */ {0xa0, 0xf4, ZC3XX_R10B_RGB01}, {0xa0, 0xf4, ZC3XX_R10C_RGB02}, {0xa0, 0xf4, ZC3XX_R10D_RGB10}, {0xa0, 0x58, ZC3XX_R10E_RGB11}, {0xa0, 0xf4, ZC3XX_R10F_RGB12}, {0xa0, 0xf4, ZC3XX_R110_RGB20}, {0xa0, 0xf4, ZC3XX_R111_RGB21}, {0xa0, 0x58, ZC3XX_R112_RGB22}, /* Auto correction */ {0xa0, 0x03, ZC3XX_R181_WINXSTART}, {0xa0, 0x08, ZC3XX_R182_WINXWIDTH}, {0xa0, 0x16, ZC3XX_R183_WINXCENTER}, {0xa0, 0x03, ZC3XX_R184_WINYSTART}, {0xa0, 0x05, ZC3XX_R185_WINYWIDTH}, {0xa0, 0x14, ZC3XX_R186_WINYCENTER}, {0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE}, /* Auto exposure and white balance */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x03, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0xb1, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x87, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* sensor on */ {0xaa, 0x07, 0x00b1}, {0xaa, 0x05, 0x0003}, {0xaa, 0x04, 0x0001}, {0xaa, 0x03, 0x003b}, /* Gains */ {0xa0, 0x20, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x26, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN}, /* Auto correction */ {0xa0, 0x40, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa1, 0x01, 0x0180}, /* AutoCorrectEnable */ {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, /* Gains */ {0xa0, 0x40, ZC3XX_R116_RGAIN}, {0xa0, 0x40, ZC3XX_R117_GGAIN}, {0xa0, 0x40, ZC3XX_R118_BGAIN}, {0xa0, 0x00, 0x0007}, /* AutoCorrectEnable */ {0xa0, 0xff, ZC3XX_R018_FRAMELOST}, /* Frame adjust */ {} }; static const struct usb_action pas106b_50HZ[] = { {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x06, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,06,cc */ {0xa0, 0x54, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,54,cc */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0x87, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,87,cc */ {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */ {0xa0, 0x30, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,30,cc */ {0xaa, 0x03, 0x0021}, /* 00,03,21,aa */ {0xaa, 0x04, 0x000c}, /* 00,04,0c,aa */ {0xaa, 0x05, 0x0002}, /* 00,05,02,aa */ {0xaa, 0x07, 0x001c}, /* 00,07,1c,aa */ {0xa0, 0x04, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,04,cc */ {} }; static const struct usb_action pas106b_60HZ[] = { {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x06, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,06,cc */ {0xa0, 0x2e, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,2e,cc */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0x71, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,71,cc */ {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */ {0xa0, 0x30, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,30,cc */ {0xaa, 0x03, 0x001c}, /* 00,03,1c,aa */ {0xaa, 0x04, 0x0004}, /* 00,04,04,aa */ {0xaa, 0x05, 0x0001}, /* 00,05,01,aa */ {0xaa, 0x07, 0x00c4}, /* 00,07,c4,aa */ {0xa0, 0x04, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,04,cc */ {} }; static const struct usb_action pas106b_NoFliker[] = { {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x06, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,06,cc */ {0xa0, 0x50, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,50,cc */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0x10, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,10,cc */ {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */ {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */ {0xaa, 0x03, 0x0013}, /* 00,03,13,aa */ {0xaa, 0x04, 0x0000}, /* 00,04,00,aa */ {0xaa, 0x05, 0x0001}, /* 00,05,01,aa */ {0xaa, 0x07, 0x0030}, /* 00,07,30,aa */ {0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,00,cc */ {} }; /* from lvWIMv.inf 046d:08a2/:08aa 2007/06/03 */ static const struct usb_action pas202b_Initial[] = { /* 640x480 */ {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc */ {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, {0xa0, 0x0e, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0e,cc */ {0xa0, 0x00, ZC3XX_R002_CLOCKSELECT}, /* 00,02,00,cc */ {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc */ {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc */ {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc */ {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, /* 00,06,e0,cc */ {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc */ {0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,03,cc */ {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc */ {0xa0, 0x08, ZC3XX_R08D_COMPABILITYMODE}, /* 00,8d,08,cc */ {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,00,cc */ {0xa0, 0x03, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,03,cc */ {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,00,cc */ {0xa0, 0x03, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,03,cc */ {0xa0, 0x01, ZC3XX_R09B_WINHEIGHTHIGH}, /* 00,9b,01,cc */ {0xa0, 0xe6, ZC3XX_R09C_WINHEIGHTLOW}, /* 00,9c,e6,cc */ {0xa0, 0x02, ZC3XX_R09D_WINWIDTHHIGH}, /* 00,9d,02,cc */ {0xa0, 0x86, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,86,cc */ {0xaa, 0x02, 0x0002}, /* 00,02,04,aa --> 02 */ {0xaa, 0x07, 0x0006}, /* 00,07,06,aa */ {0xaa, 0x08, 0x0002}, /* 00,08,02,aa */ {0xaa, 0x09, 0x0006}, /* 00,09,06,aa */ {0xaa, 0x0a, 0x0001}, /* 00,0a,01,aa */ {0xaa, 0x0b, 0x0001}, /* 00,0b,01,aa */ {0xaa, 0x0c, 0x0006}, {0xaa, 0x0d, 0x0000}, /* 00,0d,00,aa */ {0xaa, 0x10, 0x0000}, /* 00,10,00,aa */ {0xaa, 0x12, 0x0005}, /* 00,12,05,aa */ {0xaa, 0x13, 0x0063}, /* 00,13,63,aa */ {0xaa, 0x15, 0x0070}, /* 00,15,70,aa */ {0xa0, 0xb7, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,b7,cc */ {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc */ {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, /* 01,89,06,cc */ {0xa0, 0x00, 0x01ad}, /* 01,ad,00,cc */ {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc */ {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc */ {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc */ {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc */ {0xa0, 0x70, ZC3XX_R18D_YTARGET}, /* 01,8d,70,cc */ {} }; static const struct usb_action pas202b_InitialScale[] = { /* 320x240 */ {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc */ {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, {0xa0, 0x0e, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,0e,cc */ {0xa0, 0x10, ZC3XX_R002_CLOCKSELECT}, /* 00,02,10,cc */ {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc */ {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc */ {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc */ {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc */ {0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,03,cc */ {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc */ {0xa0, 0x08, ZC3XX_R08D_COMPABILITYMODE}, /* 00,8d,08,cc */ {0xa0, 0x08, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,08,cc */ {0xa0, 0x02, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,02,cc */ {0xa0, 0x08, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,08,cc */ {0xa0, 0x02, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,02,cc */ {0xa0, 0x01, ZC3XX_R09B_WINHEIGHTHIGH}, /* 00,9b,01,cc */ {0xa0, 0xe8, ZC3XX_R09C_WINHEIGHTLOW}, {0xa0, 0x02, ZC3XX_R09D_WINWIDTHHIGH}, /* 00,9d,02,cc */ {0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,88,cc */ {0xaa, 0x02, 0x0002}, /* 00,02,02,aa */ {0xaa, 0x07, 0x0006}, /* 00,07,06,aa */ {0xaa, 0x08, 0x0002}, /* 00,08,02,aa */ {0xaa, 0x09, 0x0006}, /* 00,09,06,aa */ {0xaa, 0x0a, 0x0001}, /* 00,0a,01,aa */ {0xaa, 0x0b, 0x0001}, /* 00,0b,01,aa */ {0xaa, 0x0c, 0x0006}, {0xaa, 0x0d, 0x0000}, /* 00,0d,00,aa */ {0xaa, 0x10, 0x0000}, /* 00,10,00,aa */ {0xaa, 0x12, 0x0005}, /* 00,12,05,aa */ {0xaa, 0x13, 0x0063}, /* 00,13,63,aa */ {0xaa, 0x15, 0x0070}, /* 00,15,70,aa */ {0xa0, 0x37, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,37,cc */ {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc */ {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, /* 01,89,06,cc */ {0xa0, 0x00, 0x01ad}, /* 01,ad,00,cc */ {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc */ {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc */ {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc */ {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc */ {0xa0, 0x70, ZC3XX_R18D_YTARGET}, /* 01,8d,70,cc */ {0xa0, 0xff, ZC3XX_R097_WINYSTARTHIGH}, {0xa0, 0xfe, ZC3XX_R098_WINYSTARTLOW}, {} }; static const struct usb_action pas202b_50HZ[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xa0, 0x20, ZC3XX_R087_EXPTIMEMID}, /* 00,87,20,cc */ {0xa0, 0x21, ZC3XX_R088_EXPTIMELOW}, /* 00,88,21,cc */ {0xaa, 0x20, 0x0002}, /* 00,20,02,aa */ {0xaa, 0x21, 0x001b}, {0xaa, 0x03, 0x0044}, /* 00,03,44,aa */ {0xaa, 0x04, 0x0008}, {0xaa, 0x05, 0x001b}, {0xaa, 0x0e, 0x0001}, /* 00,0e,01,aa */ {0xaa, 0x0f, 0x0000}, /* 00,0f,00,aa */ {0xa0, 0x1c, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,24,cc */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x02, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x1b, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0x4d, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,4d,cc */ {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x1b, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x44, ZC3XX_R01D_HSYNC_0}, /* 00,1d,44,cc */ {0xa0, 0x6f, ZC3XX_R01E_HSYNC_1}, /* 00,1e,6f,cc */ {0xa0, 0xad, ZC3XX_R01F_HSYNC_2}, /* 00,1f,ad,cc */ {0xa0, 0xeb, ZC3XX_R020_HSYNC_3}, /* 00,20,eb,cc */ {0xa0, 0x0f, ZC3XX_R087_EXPTIMEMID}, /* 00,87,0f,cc */ {0xa0, 0x0e, ZC3XX_R088_EXPTIMELOW}, /* 00,88,0e,cc */ {} }; static const struct usb_action pas202b_50HZScale[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xa0, 0x20, ZC3XX_R087_EXPTIMEMID}, /* 00,87,20,cc */ {0xa0, 0x21, ZC3XX_R088_EXPTIMELOW}, /* 00,88,21,cc */ {0xaa, 0x20, 0x0004}, {0xaa, 0x21, 0x003d}, {0xaa, 0x03, 0x0041}, /* 00,03,41,aa */ {0xaa, 0x04, 0x0010}, {0xaa, 0x05, 0x003d}, {0xaa, 0x0e, 0x0001}, /* 00,0e,01,aa */ {0xaa, 0x0f, 0x0000}, /* 00,0f,00,aa */ {0xa0, 0x1c, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,24,cc */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x3d, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0x9b, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,9b,cc */ {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x1b, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x41, ZC3XX_R01D_HSYNC_0}, /* 00,1d,41,cc */ {0xa0, 0x6f, ZC3XX_R01E_HSYNC_1}, /* 00,1e,6f,cc */ {0xa0, 0xad, ZC3XX_R01F_HSYNC_2}, /* 00,1f,ad,cc */ {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */ {0xa0, 0x0f, ZC3XX_R087_EXPTIMEMID}, /* 00,87,0f,cc */ {0xa0, 0x0e, ZC3XX_R088_EXPTIMELOW}, /* 00,88,0e,cc */ {} }; static const struct usb_action pas202b_60HZ[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xa0, 0x20, ZC3XX_R087_EXPTIMEMID}, /* 00,87,20,cc */ {0xa0, 0x21, ZC3XX_R088_EXPTIMELOW}, /* 00,88,21,cc */ {0xaa, 0x20, 0x0002}, /* 00,20,02,aa */ {0xaa, 0x21, 0x0000}, /* 00,21,00,aa */ {0xaa, 0x03, 0x0045}, /* 00,03,45,aa */ {0xaa, 0x04, 0x0008}, /* 00,04,08,aa */ {0xaa, 0x05, 0x0000}, /* 00,05,00,aa */ {0xaa, 0x0e, 0x0001}, /* 00,0e,01,aa */ {0xaa, 0x0f, 0x0000}, /* 00,0f,00,aa */ {0xa0, 0x1c, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,24,cc */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x02, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x00, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0x40, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,40,cc */ {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x1b, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x45, ZC3XX_R01D_HSYNC_0}, /* 00,1d,45,cc */ {0xa0, 0x8e, ZC3XX_R01E_HSYNC_1}, /* 00,1e,8e,cc */ {0xa0, 0xc1, ZC3XX_R01F_HSYNC_2}, /* 00,1f,c1,cc */ {0xa0, 0xf5, ZC3XX_R020_HSYNC_3}, /* 00,20,f5,cc */ {0xa0, 0x0f, ZC3XX_R087_EXPTIMEMID}, /* 00,87,0f,cc */ {0xa0, 0x0e, ZC3XX_R088_EXPTIMELOW}, /* 00,88,0e,cc */ {} }; static const struct usb_action pas202b_60HZScale[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xa0, 0x20, ZC3XX_R087_EXPTIMEMID}, /* 00,87,20,cc */ {0xa0, 0x21, ZC3XX_R088_EXPTIMELOW}, /* 00,88,21,cc */ {0xaa, 0x20, 0x0004}, {0xaa, 0x21, 0x0008}, {0xaa, 0x03, 0x0042}, /* 00,03,42,aa */ {0xaa, 0x04, 0x0010}, {0xaa, 0x05, 0x0008}, {0xaa, 0x0e, 0x0001}, /* 00,0e,01,aa */ {0xaa, 0x0f, 0x0000}, /* 00,0f,00,aa */ {0xa0, 0x1c, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,24,cc */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x08, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0x81, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,81,cc */ {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x1b, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x42, ZC3XX_R01D_HSYNC_0}, /* 00,1d,42,cc */ {0xa0, 0x6f, ZC3XX_R01E_HSYNC_1}, /* 00,1e,6f,cc */ {0xa0, 0xaf, ZC3XX_R01F_HSYNC_2}, /* 00,1f,af,cc */ {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */ {0xa0, 0x0f, ZC3XX_R087_EXPTIMEMID}, /* 00,87,0f,cc */ {0xa0, 0x0e, ZC3XX_R088_EXPTIMELOW}, /* 00,88,0e,cc */ {} }; static const struct usb_action pas202b_NoFliker[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xa0, 0x20, ZC3XX_R087_EXPTIMEMID}, /* 00,87,20,cc */ {0xa0, 0x21, ZC3XX_R088_EXPTIMELOW}, /* 00,88,21,cc */ {0xaa, 0x20, 0x0002}, /* 00,20,02,aa */ {0xaa, 0x21, 0x0006}, {0xaa, 0x03, 0x0040}, /* 00,03,40,aa */ {0xaa, 0x04, 0x0008}, /* 00,04,08,aa */ {0xaa, 0x05, 0x0006}, {0xaa, 0x0e, 0x0001}, /* 00,0e,01,aa */ {0xaa, 0x0f, 0x0000}, /* 00,0f,00,aa */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x02, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x06, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0x01, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */ {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */ {0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,00,cc */ {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x40, ZC3XX_R01D_HSYNC_0}, /* 00,1d,40,cc */ {0xa0, 0x60, ZC3XX_R01E_HSYNC_1}, /* 00,1e,60,cc */ {0xa0, 0x90, ZC3XX_R01F_HSYNC_2}, /* 00,1f,90,cc */ {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */ {0xa0, 0x0f, ZC3XX_R087_EXPTIMEMID}, /* 00,87,0f,cc */ {0xa0, 0x0e, ZC3XX_R088_EXPTIMELOW}, /* 00,88,0e,cc */ {} }; static const struct usb_action pas202b_NoFlikerScale[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xa0, 0x20, ZC3XX_R087_EXPTIMEMID}, /* 00,87,20,cc */ {0xa0, 0x21, ZC3XX_R088_EXPTIMELOW}, /* 00,88,21,cc */ {0xaa, 0x20, 0x0004}, {0xaa, 0x21, 0x000c}, {0xaa, 0x03, 0x0040}, /* 00,03,40,aa */ {0xaa, 0x04, 0x0010}, {0xaa, 0x05, 0x000c}, {0xaa, 0x0e, 0x0001}, /* 00,0e,01,aa */ {0xaa, 0x0f, 0x0000}, /* 00,0f,00,aa */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x0c, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0x02, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,02,cc */ {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, /* 01,8c,10,cc */ {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,20,cc */ {0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,00,cc */ {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x40, ZC3XX_R01D_HSYNC_0}, /* 00,1d,40,cc */ {0xa0, 0x60, ZC3XX_R01E_HSYNC_1}, /* 00,1e,60,cc */ {0xa0, 0x90, ZC3XX_R01F_HSYNC_2}, /* 00,1f,90,cc */ {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */ {0xa0, 0x0f, ZC3XX_R087_EXPTIMEMID}, /* 00,87,0f,cc */ {0xa0, 0x0e, ZC3XX_R088_EXPTIMELOW}, /* 00,88,0e,cc */ {} }; /* mt9v111 (mi0360soc) and pb0330 from vm30x.inf 0ac8:301b 07/02/13 */ static const struct usb_action mt9v111_1_Initial[] = { /* 640x480 */ {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, {0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, {0xa0, 0x00, ZC3XX_R002_CLOCKSELECT}, {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, {0xa0, 0xdc, ZC3XX_R08B_I2CDEVICEADDR}, {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, {0xa0, 0x07, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, {0xa0, 0xdc, ZC3XX_R08B_I2CDEVICEADDR}, {0xdd, 0x00, 0x0200}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xaa, 0x01, 0x0001}, {0xaa, 0x06, 0x0000}, {0xaa, 0x08, 0x0483}, {0xaa, 0x01, 0x0004}, {0xaa, 0x08, 0x0006}, {0xaa, 0x02, 0x0011}, {0xaa, 0x03, 0x01e5}, /*jfm: was 01e7*/ {0xaa, 0x04, 0x0285}, /*jfm: was 0287*/ {0xaa, 0x07, 0x3002}, {0xaa, 0x20, 0x5100}, {0xaa, 0x35, 0x507f}, {0xaa, 0x30, 0x0005}, {0xaa, 0x31, 0x0000}, {0xaa, 0x58, 0x0078}, {0xaa, 0x62, 0x0411}, {0xaa, 0x2b, 0x007f}, {0xaa, 0x2c, 0x007f}, /*jfm: was 0030*/ {0xaa, 0x2d, 0x007f}, /*jfm: was 0030*/ {0xaa, 0x2e, 0x007f}, /*jfm: was 0030*/ {0xa0, 0x10, ZC3XX_R087_EXPTIMEMID}, {0xa0, 0xb7, ZC3XX_R101_SENSORCORRECTION}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, {0xa0, 0x09, 0x01ad}, /*jfm: was 00*/ {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, {0xa0, 0x60, ZC3XX_R1A8_DIGITALGAIN}, {0xa0, 0x6c, ZC3XX_R18D_YTARGET}, {0xa0, 0x61, ZC3XX_R116_RGAIN}, {0xa0, 0x65, ZC3XX_R118_BGAIN}, {} }; static const struct usb_action mt9v111_1_InitialScale[] = { /* 320x240 */ {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, {0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, {0xa0, 0x10, ZC3XX_R002_CLOCKSELECT}, {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, {0xa0, 0xdc, ZC3XX_R08B_I2CDEVICEADDR}, {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, {0xa0, 0x07, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, {0xa0, 0xdc, ZC3XX_R08B_I2CDEVICEADDR}, {0xdd, 0x00, 0x0200}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xaa, 0x01, 0x0001}, {0xaa, 0x06, 0x0000}, {0xaa, 0x08, 0x0483}, {0xaa, 0x01, 0x0004}, {0xaa, 0x08, 0x0006}, {0xaa, 0x02, 0x0011}, {0xaa, 0x03, 0x01e7}, {0xaa, 0x04, 0x0287}, {0xaa, 0x07, 0x3002}, {0xaa, 0x20, 0x5100}, {0xaa, 0x35, 0x007f}, /*jfm: was 0050*/ {0xaa, 0x30, 0x0005}, {0xaa, 0x31, 0x0000}, {0xaa, 0x58, 0x0078}, {0xaa, 0x62, 0x0411}, {0xaa, 0x2b, 0x007f}, /*jfm: was 28*/ {0xaa, 0x2c, 0x007f}, /*jfm: was 30*/ {0xaa, 0x2d, 0x007f}, /*jfm: was 30*/ {0xaa, 0x2e, 0x007f}, /*jfm: was 28*/ {0xa0, 0x10, ZC3XX_R087_EXPTIMEMID}, {0xa0, 0xb7, ZC3XX_R101_SENSORCORRECTION}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, {0xa0, 0x09, 0x01ad}, /*jfm: was 00*/ {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, {0xa0, 0x60, ZC3XX_R1A8_DIGITALGAIN}, {0xa0, 0x6c, ZC3XX_R18D_YTARGET}, {0xa0, 0x61, ZC3XX_R116_RGAIN}, {0xa0, 0x65, ZC3XX_R118_BGAIN}, {} }; static const struct usb_action mt9v111_1_AE50HZ[] = { {0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xbb, 0x00, 0x0562}, {0xbb, 0x01, 0x09aa}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x03, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x9b, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x47, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x1c, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x14, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x66, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x62, ZC3XX_R01D_HSYNC_0}, {0xa0, 0x90, ZC3XX_R01E_HSYNC_1}, {0xa0, 0xc8, ZC3XX_R01F_HSYNC_2}, {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, {0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN}, {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, {} }; static const struct usb_action mt9v111_1_AE50HZScale[] = { {0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xbb, 0x00, 0x0509}, {0xbb, 0x01, 0x0934}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0xd2, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x9a, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x1c, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x14, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x66, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0xd7, ZC3XX_R01D_HSYNC_0}, {0xa0, 0xf4, ZC3XX_R01E_HSYNC_1}, {0xa0, 0xf9, ZC3XX_R01F_HSYNC_2}, {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, {} }; static const struct usb_action mt9v111_1_AE60HZ[] = { {0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xaa, 0x05, 0x003d}, {0xaa, 0x09, 0x016e}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0xdd, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x3d, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x1c, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x14, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x62, ZC3XX_R01D_HSYNC_0}, {0xa0, 0x90, ZC3XX_R01E_HSYNC_1}, {0xa0, 0xc8, ZC3XX_R01F_HSYNC_2}, {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, {0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN}, {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, {} }; static const struct usb_action mt9v111_1_AE60HZScale[] = { {0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xbb, 0x00, 0x0509}, {0xbb, 0x01, 0x0983}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x8f, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x81, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x1c, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x14, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0xd7, ZC3XX_R01D_HSYNC_0}, {0xa0, 0xf4, ZC3XX_R01E_HSYNC_1}, {0xa0, 0xf9, ZC3XX_R01F_HSYNC_2}, {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, {} }; static const struct usb_action mt9v111_1_AENoFliker[] = { {0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xbb, 0x00, 0x0509}, {0xbb, 0x01, 0x0960}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0xf0, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x04, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x1c, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x09, ZC3XX_R01D_HSYNC_0}, {0xa0, 0x40, ZC3XX_R01E_HSYNC_1}, {0xa0, 0x90, ZC3XX_R01F_HSYNC_2}, {0xa0, 0xe0, ZC3XX_R020_HSYNC_3}, {0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN}, {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, {} }; static const struct usb_action mt9v111_1_AENoFlikerScale[] = { {0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xbb, 0x00, 0x0534}, {0xbb, 0x02, 0x0960}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0xf0, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x04, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x1c, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x34, ZC3XX_R01D_HSYNC_0}, {0xa0, 0x60, ZC3XX_R01E_HSYNC_1}, {0xa0, 0x90, ZC3XX_R01F_HSYNC_2}, {0xa0, 0xe0, ZC3XX_R020_HSYNC_3}, {0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN}, {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, {} }; /* from usbvm303.inf 0ac8:303b 07/03/25 (3 - tas5130c) */ static const struct usb_action mt9v111_3_Initial[] = { {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, {0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, {0xa0, 0x00, ZC3XX_R002_CLOCKSELECT}, {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, {0xa0, 0xdc, ZC3XX_R08B_I2CDEVICEADDR}, {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, {0xa0, 0x07, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, {0xa0, 0xdc, ZC3XX_R08B_I2CDEVICEADDR}, {0xdd, 0x00, 0x0200}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xaa, 0x01, 0x0001}, /* select IFP/SOC registers */ {0xaa, 0x06, 0x0000}, /* operating mode control */ {0xaa, 0x08, 0x0483}, /* output format control */ /* H red first, V red or blue first, * raw Bayer, auto flicker */ {0xaa, 0x01, 0x0004}, /* select sensor core registers */ {0xaa, 0x08, 0x0006}, /* row start */ {0xaa, 0x02, 0x0011}, /* column start */ {0xaa, 0x03, 0x01e5}, /* window height - 1 */ {0xaa, 0x04, 0x0285}, /* window width - 1 */ {0xaa, 0x07, 0x3002}, /* output control */ {0xaa, 0x20, 0x1100}, /* read mode: bits 8 & 12 (?) */ {0xaa, 0x35, 0x007f}, /* global gain */ {0xaa, 0x30, 0x0005}, {0xaa, 0x31, 0x0000}, {0xaa, 0x58, 0x0078}, {0xaa, 0x62, 0x0411}, {0xaa, 0x2b, 0x007f}, /* green1 gain */ {0xaa, 0x2c, 0x007f}, /* blue gain */ {0xaa, 0x2d, 0x007f}, /* red gain */ {0xaa, 0x2e, 0x007f}, /* green2 gain */ {0xa0, 0x10, ZC3XX_R087_EXPTIMEMID}, {0xa0, 0x37, ZC3XX_R101_SENSORCORRECTION}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, {0xa0, 0x00, 0x01ad}, {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, {0xa0, 0x60, ZC3XX_R1A8_DIGITALGAIN}, {0xa0, 0x80, ZC3XX_R18D_YTARGET}, {0xa0, 0x61, ZC3XX_R116_RGAIN}, {0xa0, 0x65, ZC3XX_R118_BGAIN}, {} }; static const struct usb_action mt9v111_3_InitialScale[] = { {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, {0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, {0xa0, 0x10, ZC3XX_R002_CLOCKSELECT}, {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, {0xa0, 0xdc, ZC3XX_R08B_I2CDEVICEADDR}, {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, {0xa0, 0x07, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, {0xa0, 0xdc, ZC3XX_R08B_I2CDEVICEADDR}, {0xdd, 0x00, 0x0200}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xaa, 0x01, 0x0001}, {0xaa, 0x06, 0x0000}, {0xaa, 0x08, 0x0483}, {0xaa, 0x01, 0x0004}, {0xaa, 0x08, 0x0006}, {0xaa, 0x02, 0x0011}, {0xaa, 0x03, 0x01e7}, {0xaa, 0x04, 0x0287}, {0xaa, 0x07, 0x3002}, {0xaa, 0x20, 0x1100}, {0xaa, 0x35, 0x007f}, {0xaa, 0x30, 0x0005}, {0xaa, 0x31, 0x0000}, {0xaa, 0x58, 0x0078}, {0xaa, 0x62, 0x0411}, {0xaa, 0x2b, 0x007f}, {0xaa, 0x2c, 0x007f}, {0xaa, 0x2d, 0x007f}, {0xaa, 0x2e, 0x007f}, {0xa0, 0x10, ZC3XX_R087_EXPTIMEMID}, {0xa0, 0x37, ZC3XX_R101_SENSORCORRECTION}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, {0xa0, 0x00, 0x01ad}, {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, {0xa0, 0x60, ZC3XX_R1A8_DIGITALGAIN}, {0xa0, 0x80, ZC3XX_R18D_YTARGET}, {0xa0, 0x61, ZC3XX_R116_RGAIN}, {0xa0, 0x65, ZC3XX_R118_BGAIN}, {} }; static const struct usb_action mt9v111_3_AE50HZ[] = { {0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xaa, 0x05, 0x0009}, /* horizontal blanking */ {0xaa, 0x09, 0x01ce}, /* shutter width */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0xd2, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x9a, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x1c, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x14, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0xd7, ZC3XX_R01D_HSYNC_0}, {0xa0, 0xf4, ZC3XX_R01E_HSYNC_1}, {0xa0, 0xf9, ZC3XX_R01F_HSYNC_2}, {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, {} }; static const struct usb_action mt9v111_3_AE50HZScale[] = { {0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xaa, 0x05, 0x0009}, {0xaa, 0x09, 0x01ce}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0xd2, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x9a, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x1c, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x14, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0xd7, ZC3XX_R01D_HSYNC_0}, {0xa0, 0xf4, ZC3XX_R01E_HSYNC_1}, {0xa0, 0xf9, ZC3XX_R01F_HSYNC_2}, {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, {} }; static const struct usb_action mt9v111_3_AE60HZ[] = { {0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xaa, 0x05, 0x0009}, {0xaa, 0x09, 0x0083}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x8f, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x81, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x1c, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x14, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0xd7, ZC3XX_R01D_HSYNC_0}, {0xa0, 0xf4, ZC3XX_R01E_HSYNC_1}, {0xa0, 0xf9, ZC3XX_R01F_HSYNC_2}, {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, {} }; static const struct usb_action mt9v111_3_AE60HZScale[] = { {0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xaa, 0x05, 0x0009}, {0xaa, 0x09, 0x0083}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x8f, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x81, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x1c, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x14, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0xd7, ZC3XX_R01D_HSYNC_0}, {0xa0, 0xf4, ZC3XX_R01E_HSYNC_1}, {0xa0, 0xf9, ZC3XX_R01F_HSYNC_2}, {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, {} }; static const struct usb_action mt9v111_3_AENoFliker[] = { {0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xaa, 0x05, 0x0034}, {0xaa, 0x09, 0x0260}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0xf0, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x04, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x1c, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x34, ZC3XX_R01D_HSYNC_0}, {0xa0, 0x60, ZC3XX_R01E_HSYNC_1}, {0xa0, 0x90, ZC3XX_R01F_HSYNC_2}, {0xa0, 0xe0, ZC3XX_R020_HSYNC_3}, {0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN}, {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, {} }; static const struct usb_action mt9v111_3_AENoFlikerScale[] = { {0xa0, 0x00, ZC3XX_R180_AUTOCORRECTENABLE}, {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xaa, 0x05, 0x0034}, {0xaa, 0x09, 0x0260}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0xf0, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x04, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x1c, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x34, ZC3XX_R01D_HSYNC_0}, {0xa0, 0x60, ZC3XX_R01E_HSYNC_1}, {0xa0, 0x90, ZC3XX_R01F_HSYNC_2}, {0xa0, 0xe0, ZC3XX_R020_HSYNC_3}, {0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN}, {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, {} }; static const struct usb_action pb0330_Initial[] = { /* 640x480 */ {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* 00 */ {0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, {0xa0, 0x00, ZC3XX_R002_CLOCKSELECT}, {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x07, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, {0xdd, 0x00, 0x0200}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xaa, 0x01, 0x0006}, {0xaa, 0x02, 0x0011}, {0xaa, 0x03, 0x01e5}, /*jfm: was 1e7*/ {0xaa, 0x04, 0x0285}, /*jfm: was 0287*/ {0xaa, 0x06, 0x0003}, {0xaa, 0x07, 0x3002}, {0xaa, 0x20, 0x1100}, {0xaa, 0x2f, 0xf7b0}, {0xaa, 0x30, 0x0005}, {0xaa, 0x31, 0x0000}, {0xaa, 0x34, 0x0100}, {0xaa, 0x35, 0x0060}, {0xaa, 0x3d, 0x068f}, {0xaa, 0x40, 0x01e0}, {0xaa, 0x58, 0x0078}, {0xaa, 0x62, 0x0411}, {0xa0, 0x10, ZC3XX_R087_EXPTIMEMID}, {0xa0, 0x37, ZC3XX_R101_SENSORCORRECTION}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, {0xa0, 0x09, 0x01ad}, /*jfm: was 00 */ {0xa0, 0x15, 0x01ae}, {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, {0xa0, 0x60, ZC3XX_R1A8_DIGITALGAIN}, {0xa0, 0x78, ZC3XX_R18D_YTARGET}, /*jfm: was 6c*/ {} }; static const struct usb_action pb0330_InitialScale[] = { /* 320x240 */ {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* 00 */ {0xa0, 0x0a, ZC3XX_R010_CMOSSENSORSELECT}, {0xa0, 0x10, ZC3XX_R002_CLOCKSELECT}, {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x07, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, {0xdd, 0x00, 0x0200}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xaa, 0x01, 0x0006}, {0xaa, 0x02, 0x0011}, {0xaa, 0x03, 0x01e7}, {0xaa, 0x04, 0x0287}, {0xaa, 0x06, 0x0003}, {0xaa, 0x07, 0x3002}, {0xaa, 0x20, 0x1100}, {0xaa, 0x2f, 0xf7b0}, {0xaa, 0x30, 0x0005}, {0xaa, 0x31, 0x0000}, {0xaa, 0x34, 0x0100}, {0xaa, 0x35, 0x0060}, {0xaa, 0x3d, 0x068f}, {0xaa, 0x40, 0x01e0}, {0xaa, 0x58, 0x0078}, {0xaa, 0x62, 0x0411}, {0xa0, 0x10, ZC3XX_R087_EXPTIMEMID}, {0xa0, 0x37, ZC3XX_R101_SENSORCORRECTION}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, {0xa0, 0x09, 0x01ad}, {0xa0, 0x15, 0x01ae}, {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, {0xa0, 0x60, ZC3XX_R1A8_DIGITALGAIN}, {0xa0, 0x78, ZC3XX_R18D_YTARGET}, /*jfm: was 6c*/ {} }; static const struct usb_action pb0330_50HZ[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xbb, 0x00, 0x055c}, {0xbb, 0x01, 0x09aa}, {0xbb, 0x00, 0x1001}, {0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0xc4, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x47, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x1a, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x14, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x66, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x5c, ZC3XX_R01D_HSYNC_0}, {0xa0, 0x90, ZC3XX_R01E_HSYNC_1}, {0xa0, 0xc8, ZC3XX_R01F_HSYNC_2}, {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, {} }; static const struct usb_action pb0330_50HZScale[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xbb, 0x00, 0x0566}, {0xbb, 0x02, 0x09b2}, {0xbb, 0x00, 0x1002}, {0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x8c, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x8a, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x1a, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x14, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x66, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0xd7, ZC3XX_R01D_HSYNC_0}, {0xa0, 0xf0, ZC3XX_R01E_HSYNC_1}, {0xa0, 0xf8, ZC3XX_R01F_HSYNC_2}, {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, {} }; static const struct usb_action pb0330_60HZ[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xbb, 0x00, 0x0535}, {0xbb, 0x01, 0x0974}, {0xbb, 0x00, 0x1001}, {0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0xfe, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x3e, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x1a, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x14, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x66, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x35, ZC3XX_R01D_HSYNC_0}, {0xa0, 0x50, ZC3XX_R01E_HSYNC_1}, {0xa0, 0x90, ZC3XX_R01F_HSYNC_2}, {0xa0, 0xd0, ZC3XX_R020_HSYNC_3}, {} }; static const struct usb_action pb0330_60HZScale[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xbb, 0x00, 0x0535}, {0xbb, 0x02, 0x096c}, {0xbb, 0x00, 0x1002}, {0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0xc0, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x7c, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x1a, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x14, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x66, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x35, ZC3XX_R01D_HSYNC_0}, {0xa0, 0x50, ZC3XX_R01E_HSYNC_1}, {0xa0, 0x90, ZC3XX_R01F_HSYNC_2}, {0xa0, 0xd0, ZC3XX_R020_HSYNC_3}, {} }; static const struct usb_action pb0330_NoFliker[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xbb, 0x00, 0x0509}, {0xbb, 0x02, 0x0940}, {0xbb, 0x00, 0x1002}, {0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0xf0, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x01, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x09, ZC3XX_R01D_HSYNC_0}, {0xa0, 0x40, ZC3XX_R01E_HSYNC_1}, {0xa0, 0x90, ZC3XX_R01F_HSYNC_2}, {0xa0, 0xe0, ZC3XX_R020_HSYNC_3}, {} }; static const struct usb_action pb0330_NoFlikerScale[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, {0xbb, 0x00, 0x0535}, {0xbb, 0x01, 0x0980}, {0xbb, 0x00, 0x1001}, {0xa0, 0x60, ZC3XX_R11D_GLOBALGAIN}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, {0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0xf0, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x01, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x10, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x20, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x35, ZC3XX_R01D_HSYNC_0}, {0xa0, 0x60, ZC3XX_R01E_HSYNC_1}, {0xa0, 0x90, ZC3XX_R01F_HSYNC_2}, {0xa0, 0xe0, ZC3XX_R020_HSYNC_3}, {} }; /* from oem9.inf */ static const struct usb_action po2030_Initial[] = { /* 640x480 */ {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc */ {0xa0, 0x04, ZC3XX_R002_CLOCKSELECT}, /* 00,02,04,cc */ {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */ {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc */ {0xa0, 0x04, ZC3XX_R080_HBLANKHIGH}, /* 00,80,04,cc */ {0xa0, 0x05, ZC3XX_R081_HBLANKLOW}, /* 00,81,05,cc */ {0xa0, 0x16, ZC3XX_R083_RGAINADDR}, /* 00,83,16,cc */ {0xa0, 0x18, ZC3XX_R085_BGAINADDR}, /* 00,85,18,cc */ {0xa0, 0x1a, ZC3XX_R086_EXPTIMEHIGH}, /* 00,86,1a,cc */ {0xa0, 0x1b, ZC3XX_R087_EXPTIMEMID}, /* 00,87,1b,cc */ {0xa0, 0x1c, ZC3XX_R088_EXPTIMELOW}, /* 00,88,1c,cc */ {0xa0, 0xee, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,ee,cc */ {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* 00,08,03,cc */ {0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,03,cc */ {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc */ {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc */ {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc */ {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc */ {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, /* 00,06,e0,cc */ {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,42,cc */ {0xaa, 0x8d, 0x0008}, /* 00,8d,08,aa */ {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,00,cc */ {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,00,cc */ {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,00,cc */ {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,00,cc */ {0xa0, 0xe6, ZC3XX_R09C_WINHEIGHTLOW}, /* 00,9c,e6,cc */ {0xa0, 0x86, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,86,cc */ {0xaa, 0x09, 0x00ce}, /* 00,09,ce,aa */ {0xaa, 0x0b, 0x0005}, /* 00,0b,05,aa */ {0xaa, 0x0d, 0x0054}, /* 00,0d,54,aa */ {0xaa, 0x0f, 0x00eb}, /* 00,0f,eb,aa */ {0xaa, 0x87, 0x0000}, /* 00,87,00,aa */ {0xaa, 0x88, 0x0004}, /* 00,88,04,aa */ {0xaa, 0x89, 0x0000}, /* 00,89,00,aa */ {0xaa, 0x8a, 0x0005}, /* 00,8a,05,aa */ {0xaa, 0x13, 0x0003}, /* 00,13,03,aa */ {0xaa, 0x16, 0x0040}, /* 00,16,40,aa */ {0xaa, 0x18, 0x0040}, /* 00,18,40,aa */ {0xaa, 0x1d, 0x0002}, /* 00,1d,02,aa */ {0xaa, 0x29, 0x00e8}, /* 00,29,e8,aa */ {0xaa, 0x45, 0x0045}, /* 00,45,45,aa */ {0xaa, 0x50, 0x00ed}, /* 00,50,ed,aa */ {0xaa, 0x51, 0x0025}, /* 00,51,25,aa */ {0xaa, 0x52, 0x0042}, /* 00,52,42,aa */ {0xaa, 0x53, 0x002f}, /* 00,53,2f,aa */ {0xaa, 0x79, 0x0025}, /* 00,79,25,aa */ {0xaa, 0x7b, 0x0000}, /* 00,7b,00,aa */ {0xaa, 0x7e, 0x0025}, /* 00,7e,25,aa */ {0xaa, 0x7f, 0x0025}, /* 00,7f,25,aa */ {0xaa, 0x21, 0x0000}, /* 00,21,00,aa */ {0xaa, 0x33, 0x0036}, /* 00,33,36,aa */ {0xaa, 0x36, 0x0060}, /* 00,36,60,aa */ {0xaa, 0x37, 0x0008}, /* 00,37,08,aa */ {0xaa, 0x3b, 0x0031}, /* 00,3b,31,aa */ {0xaa, 0x44, 0x000f}, /* 00,44,0f,aa */ {0xaa, 0x58, 0x0002}, /* 00,58,02,aa */ {0xaa, 0x66, 0x00c0}, /* 00,66,c0,aa */ {0xaa, 0x67, 0x0044}, /* 00,67,44,aa */ {0xaa, 0x6b, 0x00a0}, /* 00,6b,a0,aa */ {0xaa, 0x6c, 0x0054}, /* 00,6c,54,aa */ {0xaa, 0xd6, 0x0007}, /* 00,d6,07,aa */ {0xa0, 0xf7, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,f7,cc */ {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc */ {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc */ {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, /* 01,89,06,cc */ {0xa0, 0x00, 0x01ad}, /* 01,ad,00,cc */ {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc */ {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc */ {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc */ {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc */ {0xa0, 0x7a, ZC3XX_R116_RGAIN}, /* 01,16,7a,cc */ {0xa0, 0x4a, ZC3XX_R118_BGAIN}, /* 01,18,4a,cc */ {} }; /* from oem9.inf */ static const struct usb_action po2030_InitialScale[] = { /* 320x240 */ {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc */ {0xa0, 0x10, ZC3XX_R002_CLOCKSELECT}, /* 00,02,10,cc */ {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc */ {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc */ {0xa0, 0x04, ZC3XX_R080_HBLANKHIGH}, /* 00,80,04,cc */ {0xa0, 0x05, ZC3XX_R081_HBLANKLOW}, /* 00,81,05,cc */ {0xa0, 0x16, ZC3XX_R083_RGAINADDR}, /* 00,83,16,cc */ {0xa0, 0x18, ZC3XX_R085_BGAINADDR}, /* 00,85,18,cc */ {0xa0, 0x1a, ZC3XX_R086_EXPTIMEHIGH}, /* 00,86,1a,cc */ {0xa0, 0x1b, ZC3XX_R087_EXPTIMEMID}, /* 00,87,1b,cc */ {0xa0, 0x1c, ZC3XX_R088_EXPTIMELOW}, /* 00,88,1c,cc */ {0xa0, 0xee, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,ee,cc */ {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, /* 00,08,03,cc */ {0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,03,cc */ {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc */ {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc */ {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc */ {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc */ {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, /* 00,06,e0,cc */ {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,42,cc */ {0xaa, 0x8d, 0x0008}, /* 00,8d,08,aa */ {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,00,cc */ {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,00,cc */ {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,00,cc */ {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,00,cc */ {0xa0, 0xe8, ZC3XX_R09C_WINHEIGHTLOW}, /* 00,9c,e8,cc */ {0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,88,cc */ {0xaa, 0x09, 0x00cc}, /* 00,09,cc,aa */ {0xaa, 0x0b, 0x0005}, /* 00,0b,05,aa */ {0xaa, 0x0d, 0x0058}, /* 00,0d,58,aa */ {0xaa, 0x0f, 0x00ed}, /* 00,0f,ed,aa */ {0xaa, 0x87, 0x0000}, /* 00,87,00,aa */ {0xaa, 0x88, 0x0004}, /* 00,88,04,aa */ {0xaa, 0x89, 0x0000}, /* 00,89,00,aa */ {0xaa, 0x8a, 0x0005}, /* 00,8a,05,aa */ {0xaa, 0x13, 0x0003}, /* 00,13,03,aa */ {0xaa, 0x16, 0x0040}, /* 00,16,40,aa */ {0xaa, 0x18, 0x0040}, /* 00,18,40,aa */ {0xaa, 0x1d, 0x0002}, /* 00,1d,02,aa */ {0xaa, 0x29, 0x00e8}, /* 00,29,e8,aa */ {0xaa, 0x45, 0x0045}, /* 00,45,45,aa */ {0xaa, 0x50, 0x00ed}, /* 00,50,ed,aa */ {0xaa, 0x51, 0x0025}, /* 00,51,25,aa */ {0xaa, 0x52, 0x0042}, /* 00,52,42,aa */ {0xaa, 0x53, 0x002f}, /* 00,53,2f,aa */ {0xaa, 0x79, 0x0025}, /* 00,79,25,aa */ {0xaa, 0x7b, 0x0000}, /* 00,7b,00,aa */ {0xaa, 0x7e, 0x0025}, /* 00,7e,25,aa */ {0xaa, 0x7f, 0x0025}, /* 00,7f,25,aa */ {0xaa, 0x21, 0x0000}, /* 00,21,00,aa */ {0xaa, 0x33, 0x0036}, /* 00,33,36,aa */ {0xaa, 0x36, 0x0060}, /* 00,36,60,aa */ {0xaa, 0x37, 0x0008}, /* 00,37,08,aa */ {0xaa, 0x3b, 0x0031}, /* 00,3b,31,aa */ {0xaa, 0x44, 0x000f}, /* 00,44,0f,aa */ {0xaa, 0x58, 0x0002}, /* 00,58,02,aa */ {0xaa, 0x66, 0x00c0}, /* 00,66,c0,aa */ {0xaa, 0x67, 0x0044}, /* 00,67,44,aa */ {0xaa, 0x6b, 0x00a0}, /* 00,6b,a0,aa */ {0xaa, 0x6c, 0x0054}, /* 00,6c,54,aa */ {0xaa, 0xd6, 0x0007}, /* 00,d6,07,aa */ {0xa0, 0xf7, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,f7,cc */ {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc */ {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc */ {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, /* 01,89,06,cc */ {0xa0, 0x00, 0x01ad}, /* 01,ad,00,cc */ {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc */ {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc */ {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc */ {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc */ {0xa0, 0x7a, ZC3XX_R116_RGAIN}, /* 01,16,7a,cc */ {0xa0, 0x4a, ZC3XX_R118_BGAIN}, /* 01,18,4a,cc */ {} }; static const struct usb_action po2030_50HZ[] = { {0xaa, 0x8d, 0x0008}, /* 00,8d,08,aa */ {0xaa, 0x1a, 0x0001}, /* 00,1a,01,aa */ {0xaa, 0x1b, 0x000a}, /* 00,1b,0a,aa */ {0xaa, 0x1c, 0x00b0}, /* 00,1c,b0,aa */ {0xa0, 0x05, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,05,cc */ {0xa0, 0x35, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,35,cc */ {0xa0, 0x70, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,70,cc */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x85, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,85,cc */ {0xa0, 0x58, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,58,cc */ {0xa0, 0x0c, ZC3XX_R18C_AEFREEZE}, /* 01,8c,0c,cc */ {0xa0, 0x18, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,18,cc */ {0xa0, 0x60, ZC3XX_R1A8_DIGITALGAIN}, /* 01,a8,60,cc */ {0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,10,cc */ {0xa0, 0x22, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,22,cc */ {0xa0, 0x88, ZC3XX_R18D_YTARGET}, /* 01,8d,88,cc */ {0xa0, 0x58, ZC3XX_R11D_GLOBALGAIN}, /* 01,1d,58,cc */ {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,42,cc */ {} }; static const struct usb_action po2030_60HZ[] = { {0xaa, 0x8d, 0x0008}, /* 00,8d,08,aa */ {0xaa, 0x1a, 0x0000}, /* 00,1a,00,aa */ {0xaa, 0x1b, 0x00de}, /* 00,1b,de,aa */ {0xaa, 0x1c, 0x0040}, /* 00,1c,40,aa */ {0xa0, 0x08, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,08,cc */ {0xa0, 0xae, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,ae,cc */ {0xa0, 0x80, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,80,cc */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x6f, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,6f,cc */ {0xa0, 0x20, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,20,cc */ {0xa0, 0x0c, ZC3XX_R18C_AEFREEZE}, /* 01,8c,0c,cc */ {0xa0, 0x18, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,18,cc */ {0xa0, 0x60, ZC3XX_R1A8_DIGITALGAIN}, /* 01,a8,60,cc */ {0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,10,cc */ {0xa0, 0x22, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,22,cc */ {0xa0, 0x88, ZC3XX_R18D_YTARGET}, /* 01,8d,88,cc */ /* win: 01,8d,80 */ {0xa0, 0x58, ZC3XX_R11D_GLOBALGAIN}, /* 01,1d,58,cc */ {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,42,cc */ {} }; static const struct usb_action po2030_NoFliker[] = { {0xa0, 0x02, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,02,cc */ {0xaa, 0x8d, 0x000d}, /* 00,8d,0d,aa */ {0xaa, 0x1a, 0x0000}, /* 00,1a,00,aa */ {0xaa, 0x1b, 0x0002}, /* 00,1b,02,aa */ {0xaa, 0x1c, 0x0078}, /* 00,1c,78,aa */ {0xaa, 0x46, 0x0000}, /* 00,46,00,aa */ {0xaa, 0x15, 0x0000}, /* 00,15,00,aa */ {} }; static const struct usb_action tas5130c_InitialScale[] = { /* 320x240 */ {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, {0xa0, 0x50, ZC3XX_R002_CLOCKSELECT}, {0xa0, 0x03, ZC3XX_R008_CLOCKSETTING}, {0xa0, 0x02, ZC3XX_R010_CMOSSENSORSELECT}, {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, {0xa0, 0x00, ZC3XX_R001_SYSTEMOPERATING}, {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, {0xa0, 0x04, ZC3XX_R098_WINYSTARTLOW}, {0xa0, 0x0f, ZC3XX_R09A_WINXSTARTLOW}, {0xa0, 0x04, ZC3XX_R11A_FIRSTYLOW}, {0xa0, 0x0f, ZC3XX_R11C_FIRSTXLOW}, {0xa0, 0xe8, ZC3XX_R09C_WINHEIGHTLOW}, {0xa0, 0x02, ZC3XX_R09D_WINWIDTHHIGH}, {0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW}, {0xa0, 0x06, ZC3XX_R08D_COMPABILITYMODE}, {0xa0, 0xf7, ZC3XX_R101_SENSORCORRECTION}, {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, {0xa0, 0x70, ZC3XX_R18D_YTARGET}, {0xa0, 0x50, ZC3XX_R1A8_DIGITALGAIN}, {0xa0, 0x00, 0x01ad}, {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, {0xa0, 0x07, ZC3XX_R0A5_EXPOSUREGAIN}, {0xa0, 0x02, ZC3XX_R0A6_EXPOSUREBLACKLVL}, {} }; static const struct usb_action tas5130c_Initial[] = { /* 640x480 */ {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, {0xa0, 0x40, ZC3XX_R002_CLOCKSELECT}, {0xa0, 0x00, ZC3XX_R008_CLOCKSETTING}, {0xa0, 0x02, ZC3XX_R010_CMOSSENSORSELECT}, {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, {0xa0, 0x00, ZC3XX_R001_SYSTEMOPERATING}, {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, {0xa0, 0x05, ZC3XX_R098_WINYSTARTLOW}, {0xa0, 0x0f, ZC3XX_R09A_WINXSTARTLOW}, {0xa0, 0x05, ZC3XX_R11A_FIRSTYLOW}, {0xa0, 0x0f, ZC3XX_R11C_FIRSTXLOW}, {0xa0, 0xe6, ZC3XX_R09C_WINHEIGHTLOW}, {0xa0, 0x02, ZC3XX_R09D_WINWIDTHHIGH}, {0xa0, 0x86, ZC3XX_R09E_WINWIDTHLOW}, {0xa0, 0x06, ZC3XX_R08D_COMPABILITYMODE}, {0xa0, 0x37, ZC3XX_R101_SENSORCORRECTION}, {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, {0xa0, 0x06, ZC3XX_R189_AWBSTATUS}, {0xa0, 0x70, ZC3XX_R18D_YTARGET}, {0xa0, 0x50, ZC3XX_R1A8_DIGITALGAIN}, {0xa0, 0x00, 0x01ad}, {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, {0xa0, 0x07, ZC3XX_R0A5_EXPOSUREGAIN}, {0xa0, 0x02, ZC3XX_R0A6_EXPOSUREBLACKLVL}, {} }; static const struct usb_action tas5130c_50HZ[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xaa, 0xa3, 0x0001}, /* 00,a3,01,aa */ {0xaa, 0xa4, 0x0063}, /* 00,a4,63,aa */ {0xa0, 0x01, ZC3XX_R0A3_EXPOSURETIMEHIGH}, /* 00,a3,01,cc */ {0xa0, 0x63, ZC3XX_R0A4_EXPOSURETIMELOW}, /* 00,a4,63,cc */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x04, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0xfe, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0x47, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,47,cc */ {0xa0, 0x0c, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x18, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x08, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0xd3, ZC3XX_R01D_HSYNC_0}, /* 00,1d,d3,cc */ {0xa0, 0xda, ZC3XX_R01E_HSYNC_1}, /* 00,1e,da,cc */ {0xa0, 0xea, ZC3XX_R01F_HSYNC_2}, /* 00,1f,ea,cc */ {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */ {0xa0, 0x03, ZC3XX_R09F_MAXXHIGH}, /* 00,9f,03,cc */ {0xa0, 0x4c, ZC3XX_R0A0_MAXXLOW}, {0xa0, 0x50, ZC3XX_R11D_GLOBALGAIN}, {} }; static const struct usb_action tas5130c_50HZScale[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xaa, 0xa3, 0x0001}, /* 00,a3,01,aa */ {0xaa, 0xa4, 0x0077}, /* 00,a4,77,aa */ {0xa0, 0x01, ZC3XX_R0A3_EXPOSURETIMEHIGH}, /* 00,a3,01,cc */ {0xa0, 0x77, ZC3XX_R0A4_EXPOSURETIMELOW}, /* 00,a4,77,cc */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x07, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0xd0, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0x7d, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,7d,cc */ {0xa0, 0x0c, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x18, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x08, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0xf0, ZC3XX_R01D_HSYNC_0}, /* 00,1d,f0,cc */ {0xa0, 0xf4, ZC3XX_R01E_HSYNC_1}, /* 00,1e,f4,cc */ {0xa0, 0xf8, ZC3XX_R01F_HSYNC_2}, /* 00,1f,f8,cc */ {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */ {0xa0, 0x03, ZC3XX_R09F_MAXXHIGH}, /* 00,9f,03,cc */ {0xa0, 0xc0, ZC3XX_R0A0_MAXXLOW}, {0xa0, 0x50, ZC3XX_R11D_GLOBALGAIN}, {} }; static const struct usb_action tas5130c_60HZ[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xaa, 0xa3, 0x0001}, /* 00,a3,01,aa */ {0xaa, 0xa4, 0x0036}, /* 00,a4,36,aa */ {0xa0, 0x01, ZC3XX_R0A3_EXPOSURETIMEHIGH}, /* 00,a3,01,cc */ {0xa0, 0x36, ZC3XX_R0A4_EXPOSURETIMELOW}, /* 00,a4,36,cc */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x05, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x54, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0x3e, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,3e,cc */ {0xa0, 0x0c, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x18, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x08, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0xca, ZC3XX_R01D_HSYNC_0}, /* 00,1d,ca,cc */ {0xa0, 0xd0, ZC3XX_R01E_HSYNC_1}, /* 00,1e,d0,cc */ {0xa0, 0xe0, ZC3XX_R01F_HSYNC_2}, /* 00,1f,e0,cc */ {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */ {0xa0, 0x03, ZC3XX_R09F_MAXXHIGH}, /* 00,9f,03,cc */ {0xa0, 0x28, ZC3XX_R0A0_MAXXLOW}, {0xa0, 0x50, ZC3XX_R11D_GLOBALGAIN}, {} }; static const struct usb_action tas5130c_60HZScale[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xaa, 0xa3, 0x0001}, /* 00,a3,01,aa */ {0xaa, 0xa4, 0x0077}, /* 00,a4,77,aa */ {0xa0, 0x01, ZC3XX_R0A3_EXPOSURETIMEHIGH}, /* 00,a3,01,cc */ {0xa0, 0x77, ZC3XX_R0A4_EXPOSURETIMELOW}, /* 00,a4,77,cc */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x09, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x47, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc */ {0xa0, 0x7d, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,7d,cc */ {0xa0, 0x0c, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x18, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x08, ZC3XX_R1A9_DIGITALLIMITDIFF}, {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0xc8, ZC3XX_R01D_HSYNC_0}, /* 00,1d,c8,cc */ {0xa0, 0xd0, ZC3XX_R01E_HSYNC_1}, /* 00,1e,d0,cc */ {0xa0, 0xe0, ZC3XX_R01F_HSYNC_2}, /* 00,1f,e0,cc */ {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */ {0xa0, 0x03, ZC3XX_R09F_MAXXHIGH}, /* 00,9f,03,cc */ {0xa0, 0x20, ZC3XX_R0A0_MAXXLOW}, {0xa0, 0x50, ZC3XX_R11D_GLOBALGAIN}, {} }; static const struct usb_action tas5130c_NoFliker[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xaa, 0xa3, 0x0001}, /* 00,a3,01,aa */ {0xaa, 0xa4, 0x0040}, /* 00,a4,40,aa */ {0xa0, 0x01, ZC3XX_R0A3_EXPOSURETIMEHIGH}, /* 00,a3,01,cc */ {0xa0, 0x40, ZC3XX_R0A4_EXPOSURETIMELOW}, /* 00,a4,40,cc */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x05, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0xa0, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x04, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x0c, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x18, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,00,cc */ {0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,00,cc */ {0xa0, 0xbc, ZC3XX_R01D_HSYNC_0}, /* 00,1d,bc,cc */ {0xa0, 0xd0, ZC3XX_R01E_HSYNC_1}, /* 00,1e,d0,cc */ {0xa0, 0xe0, ZC3XX_R01F_HSYNC_2}, /* 00,1f,e0,cc */ {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */ {0xa0, 0x02, ZC3XX_R09F_MAXXHIGH}, /* 00,9f,02,cc */ {0xa0, 0xf0, ZC3XX_R0A0_MAXXLOW}, {0xa0, 0x50, ZC3XX_R11D_GLOBALGAIN}, {} }; static const struct usb_action tas5130c_NoFlikerScale[] = { {0xa0, 0x00, ZC3XX_R019_AUTOADJUSTFPS}, /* 00,19,00,cc */ {0xaa, 0xa3, 0x0001}, /* 00,a3,01,aa */ {0xaa, 0xa4, 0x0090}, /* 00,a4,90,aa */ {0xa0, 0x01, ZC3XX_R0A3_EXPOSURETIMEHIGH}, /* 00,a3,01,cc */ {0xa0, 0x90, ZC3XX_R0A4_EXPOSURETIMELOW}, /* 00,a4,90,cc */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc */ {0xa0, 0x0a, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x00, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, {0xa0, 0x04, ZC3XX_R197_ANTIFLICKERLOW}, {0xa0, 0x0c, ZC3XX_R18C_AEFREEZE}, {0xa0, 0x18, ZC3XX_R18F_AEUNFREEZE}, {0xa0, 0x00, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,00,cc */ {0xa0, 0x00, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,00,cc */ {0xa0, 0xbc, ZC3XX_R01D_HSYNC_0}, /* 00,1d,bc,cc */ {0xa0, 0xd0, ZC3XX_R01E_HSYNC_1}, /* 00,1e,d0,cc */ {0xa0, 0xe0, ZC3XX_R01F_HSYNC_2}, /* 00,1f,e0,cc */ {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc */ {0xa0, 0x02, ZC3XX_R09F_MAXXHIGH}, /* 00,9f,02,cc */ {0xa0, 0xf0, ZC3XX_R0A0_MAXXLOW}, {0xa0, 0x50, ZC3XX_R11D_GLOBALGAIN}, {} }; /* from usbvm305.inf 0ac8:305b 07/06/15 (3 - tas5130c) */ static const struct usb_action gc0303_Initial[] = { {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc, */ {0xa0, 0x02, ZC3XX_R008_CLOCKSETTING}, /* 00,08,02,cc, */ {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc, */ {0xa0, 0x00, ZC3XX_R002_CLOCKSELECT}, {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc, */ {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc, */ {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc, */ {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, /* 00,06,e0,cc, */ {0xa0, 0x98, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,98,cc, */ {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc, */ {0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,03,cc, */ {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc, */ {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,00,cc, */ {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,00,cc, */ {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,00,cc, */ {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,00,cc, */ {0xa0, 0xe8, ZC3XX_R09C_WINHEIGHTLOW}, /* 00,9c,e6,cc, * 6<->8 */ {0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,86,cc, * 6<->8 */ {0xa0, 0x10, ZC3XX_R087_EXPTIMEMID}, /* 00,87,10,cc, */ {0xa0, 0x98, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,98,cc, */ {0xaa, 0x01, 0x0000}, {0xaa, 0x1a, 0x0000}, /* 00,1a,00,aa, */ {0xaa, 0x1c, 0x0017}, /* 00,1c,17,aa, */ {0xaa, 0x1b, 0x0000}, {0xa0, 0x82, ZC3XX_R086_EXPTIMEHIGH}, /* 00,86,82,cc, */ {0xa0, 0x83, ZC3XX_R087_EXPTIMEMID}, /* 00,87,83,cc, */ {0xa0, 0x84, ZC3XX_R088_EXPTIMELOW}, /* 00,88,84,cc, */ {0xaa, 0x05, 0x0010}, /* 00,05,10,aa, */ {0xaa, 0x0a, 0x0002}, {0xaa, 0x0b, 0x0000}, {0xaa, 0x0c, 0x0002}, {0xaa, 0x0d, 0x0000}, {0xaa, 0x0e, 0x0002}, {0xaa, 0x0f, 0x0000}, {0xaa, 0x10, 0x0002}, {0xaa, 0x11, 0x0000}, {0xaa, 0x16, 0x0001}, /* 00,16,01,aa, */ {0xaa, 0x17, 0x00e8}, /* 00,17,e6,aa, (e6 -> e8) */ {0xaa, 0x18, 0x0002}, /* 00,18,02,aa, */ {0xaa, 0x19, 0x0088}, /* 00,19,86,aa, */ {0xaa, 0x20, 0x0020}, /* 00,20,20,aa, */ {0xa0, 0xb7, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,b7,cc, */ {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc, */ {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc, */ {0xa0, 0x76, ZC3XX_R189_AWBSTATUS}, /* 01,89,76,cc, */ {0xa0, 0x09, 0x01ad}, /* 01,ad,09,cc, */ {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc, */ {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc, */ {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc, */ {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc, */ {0xa0, 0x58, ZC3XX_R1A8_DIGITALGAIN}, {0xa0, 0x61, ZC3XX_R116_RGAIN}, /* 01,16,61,cc, */ {0xa0, 0x65, ZC3XX_R118_BGAIN}, /* 01,18,65,cc */ {0xaa, 0x1b, 0x0000}, {} }; static const struct usb_action gc0303_InitialScale[] = { {0xa0, 0x01, ZC3XX_R000_SYSTEMCONTROL}, /* 00,00,01,cc, */ {0xa0, 0x02, ZC3XX_R008_CLOCKSETTING}, /* 00,08,02,cc, */ {0xa0, 0x01, ZC3XX_R010_CMOSSENSORSELECT}, /* 00,10,01,cc, */ {0xa0, 0x10, ZC3XX_R002_CLOCKSELECT}, {0xa0, 0x02, ZC3XX_R003_FRAMEWIDTHHIGH}, /* 00,03,02,cc, */ {0xa0, 0x80, ZC3XX_R004_FRAMEWIDTHLOW}, /* 00,04,80,cc, */ {0xa0, 0x01, ZC3XX_R005_FRAMEHEIGHTHIGH}, /* 00,05,01,cc, */ {0xa0, 0xe0, ZC3XX_R006_FRAMEHEIGHTLOW}, /* 00,06,e0,cc, */ {0xa0, 0x98, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,98,cc, */ {0xa0, 0x01, ZC3XX_R001_SYSTEMOPERATING}, /* 00,01,01,cc, */ {0xa0, 0x03, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,03,cc, */ {0xa0, 0x01, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,01,cc, */ {0xa0, 0x00, ZC3XX_R098_WINYSTARTLOW}, /* 00,98,00,cc, */ {0xa0, 0x00, ZC3XX_R09A_WINXSTARTLOW}, /* 00,9a,00,cc, */ {0xa0, 0x00, ZC3XX_R11A_FIRSTYLOW}, /* 01,1a,00,cc, */ {0xa0, 0x00, ZC3XX_R11C_FIRSTXLOW}, /* 01,1c,00,cc, */ {0xa0, 0xe8, ZC3XX_R09C_WINHEIGHTLOW}, /* 00,9c,e8,cc, * 8<->6 */ {0xa0, 0x88, ZC3XX_R09E_WINWIDTHLOW}, /* 00,9e,88,cc, * 8<->6 */ {0xa0, 0x10, ZC3XX_R087_EXPTIMEMID}, /* 00,87,10,cc, */ {0xa0, 0x98, ZC3XX_R08B_I2CDEVICEADDR}, /* 00,8b,98,cc, */ {0xaa, 0x01, 0x0000}, {0xaa, 0x1a, 0x0000}, /* 00,1a,00,aa, */ {0xaa, 0x1c, 0x0017}, /* 00,1c,17,aa, */ {0xaa, 0x1b, 0x0000}, {0xa0, 0x82, ZC3XX_R086_EXPTIMEHIGH}, /* 00,86,82,cc, */ {0xa0, 0x83, ZC3XX_R087_EXPTIMEMID}, /* 00,87,83,cc, */ {0xa0, 0x84, ZC3XX_R088_EXPTIMELOW}, /* 00,88,84,cc, */ {0xaa, 0x05, 0x0010}, /* 00,05,10,aa, */ {0xaa, 0x0a, 0x0001}, {0xaa, 0x0b, 0x0000}, {0xaa, 0x0c, 0x0001}, {0xaa, 0x0d, 0x0000}, {0xaa, 0x0e, 0x0001}, {0xaa, 0x0f, 0x0000}, {0xaa, 0x10, 0x0001}, {0xaa, 0x11, 0x0000}, {0xaa, 0x16, 0x0001}, /* 00,16,01,aa, */ {0xaa, 0x17, 0x00e8}, /* 00,17,e6,aa (e6 -> e8) */ {0xaa, 0x18, 0x0002}, /* 00,18,02,aa, */ {0xaa, 0x19, 0x0088}, /* 00,19,88,aa, */ {0xa0, 0xb7, ZC3XX_R101_SENSORCORRECTION}, /* 01,01,b7,cc, */ {0xa0, 0x05, ZC3XX_R012_VIDEOCONTROLFUNC}, /* 00,12,05,cc, */ {0xa0, 0x0d, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0d,cc, */ {0xa0, 0x76, ZC3XX_R189_AWBSTATUS}, /* 01,89,76,cc, */ {0xa0, 0x09, 0x01ad}, /* 01,ad,09,cc, */ {0xa0, 0x03, ZC3XX_R1C5_SHARPNESSMODE}, /* 01,c5,03,cc, */ {0xa0, 0x13, ZC3XX_R1CB_SHARPNESS05}, /* 01,cb,13,cc, */ {0xa0, 0x08, ZC3XX_R250_DEADPIXELSMODE}, /* 02,50,08,cc, */ {0xa0, 0x08, ZC3XX_R301_EEPROMACCESS}, /* 03,01,08,cc, */ {0xa0, 0x58, ZC3XX_R1A8_DIGITALGAIN}, {0xa0, 0x61, ZC3XX_R116_RGAIN}, /* 01,16,61,cc, */ {0xa0, 0x65, ZC3XX_R118_BGAIN}, /* 01,18,65,cc */ {0xaa, 0x1b, 0x0000}, {} }; static const struct usb_action gc0303_50HZ[] = { {0xaa, 0x82, 0x0000}, /* 00,82,00,aa */ {0xaa, 0x83, 0x0001}, /* 00,83,01,aa */ {0xaa, 0x84, 0x0063}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc, */ {0xa0, 0x06, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,0d,cc, */ {0xa0, 0xa8, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,50,cc, */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc, */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc, */ {0xa0, 0x47, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,47,cc, */ {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, /* 01,8c,0e,cc, */ {0xa0, 0x15, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,15,cc, */ {0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,10,cc, */ {0xa0, 0x48, ZC3XX_R1AA_DIGITALGAINSTEP}, {0xa0, 0x62, ZC3XX_R01D_HSYNC_0}, /* 00,1d,62,cc, */ {0xa0, 0x90, ZC3XX_R01E_HSYNC_1}, /* 00,1e,90,cc, */ {0xa0, 0xc8, ZC3XX_R01F_HSYNC_2}, /* 00,1f,c8,cc, */ {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc, */ {0xa0, 0x58, ZC3XX_R11D_GLOBALGAIN}, /* 01,1d,58,cc, */ {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,42,cc, */ {0xa0, 0x7f, ZC3XX_R18D_YTARGET}, {} }; static const struct usb_action gc0303_50HZScale[] = { {0xaa, 0x82, 0x0000}, /* 00,82,00,aa */ {0xaa, 0x83, 0x0003}, /* 00,83,03,aa */ {0xaa, 0x84, 0x0054}, /* 00,84,54,aa */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc, */ {0xa0, 0x0d, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,0d,cc, */ {0xa0, 0x50, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,50,cc, */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc, */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc, */ {0xa0, 0x8e, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,8e,cc, */ {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, /* 01,8c,0e,cc, */ {0xa0, 0x15, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,15,cc, */ {0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,10,cc, */ {0xa0, 0x48, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,24,cc, */ {0xa0, 0x62, ZC3XX_R01D_HSYNC_0}, /* 00,1d,62,cc, */ {0xa0, 0x90, ZC3XX_R01E_HSYNC_1}, /* 00,1e,90,cc, */ {0xa0, 0xc8, ZC3XX_R01F_HSYNC_2}, /* 00,1f,c8,cc, */ {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc, */ {0xa0, 0x58, ZC3XX_R11D_GLOBALGAIN}, /* 01,1d,58,cc, */ {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,42,cc, */ {0xa0, 0x7f, ZC3XX_R18D_YTARGET}, {} }; static const struct usb_action gc0303_60HZ[] = { {0xaa, 0x82, 0x0000}, /* 00,82,00,aa */ {0xaa, 0x83, 0x0000}, {0xaa, 0x84, 0x003b}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc, */ {0xa0, 0x05, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,91,05,cc, */ {0xa0, 0x88, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,92,88,cc, */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc, */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc, */ {0xa0, 0x3b, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,3b,cc, */ {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, /* 01,8c,0e,cc, */ {0xa0, 0x15, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,15,cc, */ {0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,a9,10,cc, */ {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,aa,24,cc, */ {0xa0, 0x62, ZC3XX_R01D_HSYNC_0}, /* 00,1d,62,cc, */ {0xa0, 0x90, ZC3XX_R01E_HSYNC_1}, /* 00,1e,90,cc, */ {0xa0, 0xc8, ZC3XX_R01F_HSYNC_2}, /* 00,1f,c8,cc, */ {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc, */ {0xa0, 0x58, ZC3XX_R11D_GLOBALGAIN}, /* 01,1d,58,cc, */ {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,42,cc, */ {0xa0, 0x80, ZC3XX_R18D_YTARGET}, {} }; static const struct usb_action gc0303_60HZScale[] = { {0xaa, 0x82, 0x0000}, /* 00,82,00,aa */ {0xaa, 0x83, 0x0000}, {0xaa, 0x84, 0x0076}, {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc, */ {0xa0, 0x0b, ZC3XX_R191_EXPOSURELIMITMID}, /* 01,1,0b,cc, */ {0xa0, 0x10, ZC3XX_R192_EXPOSURELIMITLOW}, /* 01,2,10,cc, */ {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,5,00,cc, */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,6,00,cc, */ {0xa0, 0x76, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,7,76,cc, */ {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, /* 01,c,0e,cc, */ {0xa0, 0x15, ZC3XX_R18F_AEUNFREEZE}, /* 01,f,15,cc, */ {0xa0, 0x10, ZC3XX_R1A9_DIGITALLIMITDIFF}, /* 01,9,10,cc, */ {0xa0, 0x24, ZC3XX_R1AA_DIGITALGAINSTEP}, /* 01,a,24,cc, */ {0xa0, 0x62, ZC3XX_R01D_HSYNC_0}, /* 00,d,62,cc, */ {0xa0, 0x90, ZC3XX_R01E_HSYNC_1}, /* 00,e,90,cc, */ {0xa0, 0xc8, ZC3XX_R01F_HSYNC_2}, /* 00,f,c8,cc, */ {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,0,ff,cc, */ {0xa0, 0x58, ZC3XX_R11D_GLOBALGAIN}, /* 01,d,58,cc, */ {0xa0, 0x42, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,42,cc, */ {0xa0, 0x80, ZC3XX_R18D_YTARGET}, {} }; static const struct usb_action gc0303_NoFliker[] = { {0xa0, 0x0c, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0c,cc, */ {0xaa, 0x82, 0x0000}, /* 00,82,00,aa */ {0xaa, 0x83, 0x0000}, /* 00,83,00,aa */ {0xaa, 0x84, 0x0020}, /* 00,84,20,aa */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,0,00,cc, */ {0xa0, 0x00, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x48, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc, */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc, */ {0xa0, 0x10, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,10,cc, */ {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, /* 01,8c,0e,cc, */ {0xa0, 0x15, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,15,cc, */ {0xa0, 0x62, ZC3XX_R01D_HSYNC_0}, /* 00,1d,62,cc, */ {0xa0, 0x90, ZC3XX_R01E_HSYNC_1}, /* 00,1e,90,cc, */ {0xa0, 0xc8, ZC3XX_R01F_HSYNC_2}, /* 00,1f,c8,cc, */ {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc, */ {0xa0, 0x58, ZC3XX_R11D_GLOBALGAIN}, /* 01,1d,58,cc, */ {0xa0, 0x03, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,03,cc */ {} }; static const struct usb_action gc0303_NoFlikerScale[] = { {0xa0, 0x0c, ZC3XX_R100_OPERATIONMODE}, /* 01,00,0c,cc, */ {0xaa, 0x82, 0x0000}, /* 00,82,00,aa */ {0xaa, 0x83, 0x0000}, /* 00,83,00,aa */ {0xaa, 0x84, 0x0020}, /* 00,84,20,aa */ {0xa0, 0x00, ZC3XX_R190_EXPOSURELIMITHIGH}, /* 01,90,00,cc, */ {0xa0, 0x00, ZC3XX_R191_EXPOSURELIMITMID}, {0xa0, 0x48, ZC3XX_R192_EXPOSURELIMITLOW}, {0xa0, 0x00, ZC3XX_R195_ANTIFLICKERHIGH}, /* 01,95,00,cc, */ {0xa0, 0x00, ZC3XX_R196_ANTIFLICKERMID}, /* 01,96,00,cc, */ {0xa0, 0x10, ZC3XX_R197_ANTIFLICKERLOW}, /* 01,97,10,cc, */ {0xa0, 0x0e, ZC3XX_R18C_AEFREEZE}, /* 01,8c,0e,cc, */ {0xa0, 0x15, ZC3XX_R18F_AEUNFREEZE}, /* 01,8f,15,cc, */ {0xa0, 0x62, ZC3XX_R01D_HSYNC_0}, /* 00,1d,62,cc, */ {0xa0, 0x90, ZC3XX_R01E_HSYNC_1}, /* 00,1e,90,cc, */ {0xa0, 0xc8, ZC3XX_R01F_HSYNC_2}, /* 00,1f,c8,cc, */ {0xa0, 0xff, ZC3XX_R020_HSYNC_3}, /* 00,20,ff,cc, */ {0xa0, 0x58, ZC3XX_R11D_GLOBALGAIN}, /* 01,1d,58,cc, */ {0xa0, 0x03, ZC3XX_R180_AUTOCORRECTENABLE}, /* 01,80,03,cc */ {} }; static u8 reg_r(struct gspca_dev *gspca_dev, u16 index) { int ret; if (gspca_dev->usb_err < 0) return 0; ret = usb_control_msg(gspca_dev->dev, usb_rcvctrlpipe(gspca_dev->dev, 0), 0xa1, USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE, 0x01, /* value */ index, gspca_dev->usb_buf, 1, 500); if (ret < 0) { pr_err("reg_r err %d\n", ret); gspca_dev->usb_err = ret; return 0; } return gspca_dev->usb_buf[0]; } static void reg_w(struct gspca_dev *gspca_dev, u8 value, u16 index) { int ret; if (gspca_dev->usb_err < 0) return; ret = usb_control_msg(gspca_dev->dev, usb_sndctrlpipe(gspca_dev->dev, 0), 0xa0, USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE, value, index, NULL, 0, 500); if (ret < 0) { pr_err("reg_w_i err %d\n", ret); gspca_dev->usb_err = ret; } } static u16 i2c_read(struct gspca_dev *gspca_dev, u8 reg) { u8 retbyte; u16 retval; if (gspca_dev->usb_err < 0) return 0; reg_w(gspca_dev, reg, 0x0092); reg_w(gspca_dev, 0x02, 0x0090); /* <- read command */ msleep(20); retbyte = reg_r(gspca_dev, 0x0091); /* read status */ if (retbyte != 0x00) pr_err("i2c_r status error %02x\n", retbyte); retval = reg_r(gspca_dev, 0x0095); /* read Lowbyte */ retval |= reg_r(gspca_dev, 0x0096) << 8; /* read Hightbyte */ return retval; } static u8 i2c_write(struct gspca_dev *gspca_dev, u8 reg, u8 valL, u8 valH) { u8 retbyte; if (gspca_dev->usb_err < 0) return 0; reg_w(gspca_dev, reg, 0x92); reg_w(gspca_dev, valL, 0x93); reg_w(gspca_dev, valH, 0x94); reg_w(gspca_dev, 0x01, 0x90); /* <- write command */ msleep(1); retbyte = reg_r(gspca_dev, 0x0091); /* read status */ if (retbyte != 0x00) pr_err("i2c_w status error %02x\n", retbyte); return retbyte; } static void usb_exchange(struct gspca_dev *gspca_dev, const struct usb_action *action) { while (action->req) { switch (action->req) { case 0xa0: /* write register */ reg_w(gspca_dev, action->val, action->idx); break; case 0xa1: /* read status */ reg_r(gspca_dev, action->idx); break; case 0xaa: i2c_write(gspca_dev, action->val, /* reg */ action->idx & 0xff, /* valL */ action->idx >> 8); /* valH */ break; case 0xbb: i2c_write(gspca_dev, action->idx >> 8, /* reg */ action->idx & 0xff, /* valL */ action->val); /* valH */ break; default: /* case 0xdd: * delay */ msleep(action->idx); break; } action++; msleep(1); } } static void setmatrix(struct gspca_dev *gspca_dev) { struct sd *sd = (struct sd *) gspca_dev; int i; const u8 *matrix; static const u8 adcm2700_matrix[9] = /* {0x66, 0xed, 0xed, 0xed, 0x66, 0xed, 0xed, 0xed, 0x66}; */ /*ms-win*/ {0x74, 0xed, 0xed, 0xed, 0x74, 0xed, 0xed, 0xed, 0x74}; static const u8 gc0305_matrix[9] = {0x50, 0xf8, 0xf8, 0xf8, 0x50, 0xf8, 0xf8, 0xf8, 0x50}; static const u8 ov7620_matrix[9] = {0x58, 0xf4, 0xf4, 0xf4, 0x58, 0xf4, 0xf4, 0xf4, 0x58}; static const u8 pas202b_matrix[9] = {0x4c, 0xf5, 0xff, 0xf9, 0x51, 0xf5, 0xfb, 0xed, 0x5f}; static const u8 po2030_matrix[9] = {0x60, 0xf0, 0xf0, 0xf0, 0x60, 0xf0, 0xf0, 0xf0, 0x60}; static const u8 tas5130c_matrix[9] = {0x68, 0xec, 0xec, 0xec, 0x68, 0xec, 0xec, 0xec, 0x68}; static const u8 gc0303_matrix[9] = {0x6c, 0xea, 0xea, 0xea, 0x6c, 0xea, 0xea, 0xea, 0x6c}; static const u8 *matrix_tb[SENSOR_MAX] = { [SENSOR_ADCM2700] = adcm2700_matrix, [SENSOR_CS2102] = ov7620_matrix, [SENSOR_CS2102K] = NULL, [SENSOR_GC0303] = gc0303_matrix, [SENSOR_GC0305] = gc0305_matrix, [SENSOR_HDCS2020] = NULL, [SENSOR_HV7131B] = NULL, [SENSOR_HV7131R] = po2030_matrix, [SENSOR_ICM105A] = po2030_matrix, [SENSOR_MC501CB] = NULL, [SENSOR_MT9V111_1] = gc0305_matrix, [SENSOR_MT9V111_3] = gc0305_matrix, [SENSOR_OV7620] = ov7620_matrix, [SENSOR_OV7630C] = NULL, [SENSOR_PAS106] = NULL, [SENSOR_PAS202B] = pas202b_matrix, [SENSOR_PB0330] = gc0305_matrix, [SENSOR_PO2030] = po2030_matrix, [SENSOR_TAS5130C] = tas5130c_matrix, }; matrix = matrix_tb[sd->sensor]; if (matrix == NULL) return; /* matrix already loaded */ for (i = 0; i < ARRAY_SIZE(ov7620_matrix); i++) reg_w(gspca_dev, matrix[i], 0x010a + i); } static void setsharpness(struct gspca_dev *gspca_dev) { struct sd *sd = (struct sd *) gspca_dev; int sharpness; static const u8 sharpness_tb[][2] = { {0x02, 0x03}, {0x04, 0x07}, {0x08, 0x0f}, {0x10, 0x1e} }; sharpness = sd->ctrls[SHARPNESS].val; reg_w(gspca_dev, sharpness_tb[sharpness][0], 0x01c6); reg_r(gspca_dev, 0x01c8); reg_r(gspca_dev, 0x01c9); reg_r(gspca_dev, 0x01ca); reg_w(gspca_dev, sharpness_tb[sharpness][1], 0x01cb); } static void setcontrast(struct gspca_dev *gspca_dev) { struct sd *sd = (struct sd *) gspca_dev; const u8 *Tgamma; int g, i, brightness, contrast, adj, gp1, gp2; u8 gr[16]; static const u8 delta_b[16] = /* delta for brightness */ {0x50, 0x38, 0x2d, 0x28, 0x24, 0x21, 0x1e, 0x1d, 0x1d, 0x1b, 0x1b, 0x1b, 0x19, 0x18, 0x18, 0x18}; static const u8 delta_c[16] = /* delta for contrast */ {0x2c, 0x1a, 0x12, 0x0c, 0x0a, 0x06, 0x06, 0x06, 0x04, 0x06, 0x04, 0x04, 0x03, 0x03, 0x02, 0x02}; static const u8 gamma_tb[6][16] = { {0x00, 0x00, 0x03, 0x0d, 0x1b, 0x2e, 0x45, 0x5f, 0x79, 0x93, 0xab, 0xc1, 0xd4, 0xe5, 0xf3, 0xff}, {0x01, 0x0c, 0x1f, 0x3a, 0x53, 0x6d, 0x85, 0x9c, 0xb0, 0xc2, 0xd1, 0xde, 0xe9, 0xf2, 0xf9, 0xff}, {0x04, 0x16, 0x30, 0x4e, 0x68, 0x81, 0x98, 0xac, 0xbe, 0xcd, 0xda, 0xe4, 0xed, 0xf5, 0xfb, 0xff}, {0x13, 0x38, 0x59, 0x79, 0x92, 0xa7, 0xb9, 0xc8, 0xd4, 0xdf, 0xe7, 0xee, 0xf4, 0xf9, 0xfc, 0xff}, {0x20, 0x4b, 0x6e, 0x8d, 0xa3, 0xb5, 0xc5, 0xd2, 0xdc, 0xe5, 0xec, 0xf2, 0xf6, 0xfa, 0xfd, 0xff}, {0x24, 0x44, 0x64, 0x84, 0x9d, 0xb2, 0xc4, 0xd3, 0xe0, 0xeb, 0xf4, 0xff, 0xff, 0xff, 0xff, 0xff}, }; Tgamma = gamma_tb[sd->ctrls[GAMMA].val - 1]; contrast = ((int) sd->ctrls[CONTRAST].val - 128); /* -128 / 127 */ brightness = ((int) sd->ctrls[BRIGHTNESS].val - 128); /* -128 / 92 */ adj = 0; gp1 = gp2 = 0; for (i = 0; i < 16; i++) { g = Tgamma[i] + delta_b[i] * brightness / 256 - delta_c[i] * contrast / 256 - adj / 2; if (g > 0xff) g = 0xff; else if (g < 0) g = 0; reg_w(gspca_dev, g, 0x0120 + i); /* gamma */ if (contrast > 0) adj--; else if (contrast < 0) adj++; if (i > 1) gr[i - 1] = (g - gp2) / 2; else if (i != 0) gr[0] = gp1 == 0 ? 0 : (g - gp1); gp2 = gp1; gp1 = g; } gr[15] = (0xff - gp2) / 2; for (i = 0; i < 16; i++) reg_w(gspca_dev, gr[i], 0x0130 + i); /* gradient */ } static void getexposure(struct gspca_dev *gspca_dev) { struct sd *sd = (struct sd *) gspca_dev; if (sd->sensor != SENSOR_HV7131R) return; sd->ctrls[EXPOSURE].val = (i2c_read(gspca_dev, 0x25) << 9) | (i2c_read(gspca_dev, 0x26) << 1) | (i2c_read(gspca_dev, 0x27) >> 7); } static void setexposure(struct gspca_dev *gspca_dev) { struct sd *sd = (struct sd *) gspca_dev; int val; if (sd->sensor != SENSOR_HV7131R) return; val = sd->ctrls[EXPOSURE].val; i2c_write(gspca_dev, 0x25, val >> 9, 0x00); i2c_write(gspca_dev, 0x26, val >> 1, 0x00); i2c_write(gspca_dev, 0x27, val << 7, 0x00); } static void setquality(struct gspca_dev *gspca_dev) { struct sd *sd = (struct sd *) gspca_dev; s8 reg07; reg07 = 0; switch (sd->sensor) { case SENSOR_OV7620: reg07 = 0x30; break; case SENSOR_HV7131R: case SENSOR_PAS202B: return; /* done by work queue */ } reg_w(gspca_dev, sd->reg08, ZC3XX_R008_CLOCKSETTING); if (reg07 != 0) reg_w(gspca_dev, reg07, 0x0007); } /* Matches the sensor's internal frame rate to the lighting frequency. * Valid frequencies are: * 50Hz, for European and Asian lighting (default) * 60Hz, for American lighting * 0 = No Fliker (for outdoore usage) */ static void setlightfreq(struct gspca_dev *gspca_dev) { struct sd *sd = (struct sd *) gspca_dev; int i, mode; const struct usb_action *zc3_freq; static const struct usb_action *freq_tb[SENSOR_MAX][6] = { [SENSOR_ADCM2700] = {adcm2700_NoFliker, adcm2700_NoFliker, adcm2700_50HZ, adcm2700_50HZ, adcm2700_60HZ, adcm2700_60HZ}, [SENSOR_CS2102] = {cs2102_NoFliker, cs2102_NoFlikerScale, cs2102_50HZ, cs2102_50HZScale, cs2102_60HZ, cs2102_60HZScale}, [SENSOR_CS2102K] = {cs2102_NoFliker, cs2102_NoFlikerScale, NULL, NULL, /* currently disabled */ NULL, NULL}, [SENSOR_GC0303] = {gc0303_NoFliker, gc0303_NoFlikerScale, gc0303_50HZ, gc0303_50HZScale, gc0303_60HZ, gc0303_60HZScale}, [SENSOR_GC0305] = {gc0305_NoFliker, gc0305_NoFliker, gc0305_50HZ, gc0305_50HZ, gc0305_60HZ, gc0305_60HZ}, [SENSOR_HDCS2020] = {hdcs2020_NoFliker, hdcs2020_NoFliker, hdcs2020_50HZ, hdcs2020_50HZ, hdcs2020_60HZ, hdcs2020_60HZ}, [SENSOR_HV7131B] = {hv7131b_NoFliker, hv7131b_NoFlikerScale, hv7131b_50HZ, hv7131b_50HZScale, hv7131b_60HZ, hv7131b_60HZScale}, [SENSOR_HV7131R] = {hv7131r_NoFliker, hv7131r_NoFlikerScale, hv7131r_50HZ, hv7131r_50HZScale, hv7131r_60HZ, hv7131r_60HZScale}, [SENSOR_ICM105A] = {icm105a_NoFliker, icm105a_NoFlikerScale, icm105a_50HZ, icm105a_50HZScale, icm105a_60HZ, icm105a_60HZScale}, [SENSOR_MC501CB] = {mc501cb_NoFliker, mc501cb_NoFlikerScale, mc501cb_50HZ, mc501cb_50HZScale, mc501cb_60HZ, mc501cb_60HZScale}, [SENSOR_MT9V111_1] = {mt9v111_1_AENoFliker, mt9v111_1_AENoFlikerScale, mt9v111_1_AE50HZ, mt9v111_1_AE50HZScale, mt9v111_1_AE60HZ, mt9v111_1_AE60HZScale}, [SENSOR_MT9V111_3] = {mt9v111_3_AENoFliker, mt9v111_3_AENoFlikerScale, mt9v111_3_AE50HZ, mt9v111_3_AE50HZScale, mt9v111_3_AE60HZ, mt9v111_3_AE60HZScale}, [SENSOR_OV7620] = {ov7620_NoFliker, ov7620_NoFliker, ov7620_50HZ, ov7620_50HZ, ov7620_60HZ, ov7620_60HZ}, [SENSOR_OV7630C] = {NULL, NULL, NULL, NULL, NULL, NULL}, [SENSOR_PAS106] = {pas106b_NoFliker, pas106b_NoFliker, pas106b_50HZ, pas106b_50HZ, pas106b_60HZ, pas106b_60HZ}, [SENSOR_PAS202B] = {pas202b_NoFliker, pas202b_NoFlikerScale, pas202b_50HZ, pas202b_50HZScale, pas202b_60HZ, pas202b_60HZScale}, [SENSOR_PB0330] = {pb0330_NoFliker, pb0330_NoFlikerScale, pb0330_50HZ, pb0330_50HZScale, pb0330_60HZ, pb0330_60HZScale}, [SENSOR_PO2030] = {po2030_NoFliker, po2030_NoFliker, po2030_50HZ, po2030_50HZ, po2030_60HZ, po2030_60HZ}, [SENSOR_TAS5130C] = {tas5130c_NoFliker, tas5130c_NoFlikerScale, tas5130c_50HZ, tas5130c_50HZScale, tas5130c_60HZ, tas5130c_60HZScale}, }; i = sd->ctrls[LIGHTFREQ].val * 2; mode = gspca_dev->cam.cam_mode[gspca_dev->curr_mode].priv; if (mode) i++; /* 320x240 */ zc3_freq = freq_tb[sd->sensor][i]; if (zc3_freq == NULL) return; usb_exchange(gspca_dev, zc3_freq); switch (sd->sensor) { case SENSOR_GC0305: if (mode /* if 320x240 */ && sd->ctrls[LIGHTFREQ].val == 1) /* and 50Hz */ reg_w(gspca_dev, 0x85, 0x018d); /* win: 0x80, 0x018d */ break; case SENSOR_OV7620: if (!mode) { /* if 640x480 */ if (sd->ctrls[LIGHTFREQ].val != 0) /* and filter */ reg_w(gspca_dev, 0x40, 0x0002); else reg_w(gspca_dev, 0x44, 0x0002); } break; case SENSOR_PAS202B: reg_w(gspca_dev, 0x00, 0x01a7); break; } } static void setautogain(struct gspca_dev *gspca_dev) { struct sd *sd = (struct sd *) gspca_dev; u8 autoval; if (sd->ctrls[AUTOGAIN].val) autoval = 0x42; else autoval = 0x02; reg_w(gspca_dev, autoval, 0x0180); } /* update the transfer parameters */ /* This function is executed from a work queue. */ /* The exact use of the bridge registers 07 and 08 is not known. * The following algorithm has been adapted from ms-win traces */ static void transfer_update(struct work_struct *work) { struct sd *sd = container_of(work, struct sd, work); struct gspca_dev *gspca_dev = &sd->gspca_dev; int change, good; u8 reg07, reg11; /* synchronize with the main driver and initialize the registers */ mutex_lock(&gspca_dev->usb_lock); reg07 = 0; /* max */ reg_w(gspca_dev, reg07, 0x0007); reg_w(gspca_dev, sd->reg08, ZC3XX_R008_CLOCKSETTING); mutex_unlock(&gspca_dev->usb_lock); good = 0; for (;;) { msleep(100); /* get the transfer status */ /* the bit 0 of the bridge register 11 indicates overflow */ mutex_lock(&gspca_dev->usb_lock); if (!gspca_dev->present || !gspca_dev->streaming) goto err; reg11 = reg_r(gspca_dev, 0x0011); if (gspca_dev->usb_err < 0 || !gspca_dev->present || !gspca_dev->streaming) goto err; change = reg11 & 0x01; if (change) { /* overflow */ switch (reg07) { case 0: /* max */ reg07 = sd->sensor == SENSOR_HV7131R ? 0x30 : 0x32; if (sd->reg08 != 0) { change = 3; sd->reg08--; } break; case 0x32: reg07 -= 4; break; default: reg07 -= 2; break; case 2: change = 0; /* already min */ break; } good = 0; } else { /* no overflow */ if (reg07 != 0) { /* if not max */ good++; if (good >= 10) { good = 0; change = 1; reg07 += 2; switch (reg07) { case 0x30: if (sd->sensor == SENSOR_PAS202B) reg07 += 2; break; case 0x32: case 0x34: reg07 = 0; break; } } } else { /* reg07 max */ if (sd->reg08 < sizeof jpeg_qual - 1) { good++; if (good > 10) { sd->reg08++; change = 2; } } } } if (change) { if (change & 1) { reg_w(gspca_dev, reg07, 0x0007); if (gspca_dev->usb_err < 0 || !gspca_dev->present || !gspca_dev->streaming) goto err; } if (change & 2) { reg_w(gspca_dev, sd->reg08, ZC3XX_R008_CLOCKSETTING); if (gspca_dev->usb_err < 0 || !gspca_dev->present || !gspca_dev->streaming) goto err; sd->ctrls[QUALITY].val = jpeg_qual[sd->reg08]; jpeg_set_qual(sd->jpeg_hdr, jpeg_qual[sd->reg08]); } } mutex_unlock(&gspca_dev->usb_lock); } return; err: mutex_unlock(&gspca_dev->usb_lock); } static void send_unknown(struct gspca_dev *gspca_dev, int sensor) { reg_w(gspca_dev, 0x01, 0x0000); /* bridge reset */ switch (sensor) { case SENSOR_PAS106: reg_w(gspca_dev, 0x03, 0x003a); reg_w(gspca_dev, 0x0c, 0x003b); reg_w(gspca_dev, 0x08, 0x0038); break; case SENSOR_ADCM2700: case SENSOR_GC0305: case SENSOR_OV7620: case SENSOR_MT9V111_1: case SENSOR_MT9V111_3: case SENSOR_PB0330: case SENSOR_PO2030: reg_w(gspca_dev, 0x0d, 0x003a); reg_w(gspca_dev, 0x02, 0x003b); reg_w(gspca_dev, 0x00, 0x0038); break; case SENSOR_HV7131R: case SENSOR_PAS202B: reg_w(gspca_dev, 0x03, 0x003b); reg_w(gspca_dev, 0x0c, 0x003a); reg_w(gspca_dev, 0x0b, 0x0039); if (sensor == SENSOR_PAS202B) reg_w(gspca_dev, 0x0b, 0x0038); break; } } /* start probe 2 wires */ static void start_2wr_probe(struct gspca_dev *gspca_dev, int sensor) { reg_w(gspca_dev, 0x01, 0x0000); reg_w(gspca_dev, sensor, 0x0010); reg_w(gspca_dev, 0x01, 0x0001); reg_w(gspca_dev, 0x03, 0x0012); reg_w(gspca_dev, 0x01, 0x0012); /* msleep(2); */ } static int sif_probe(struct gspca_dev *gspca_dev) { u16 checkword; start_2wr_probe(gspca_dev, 0x0f); /* PAS106 */ reg_w(gspca_dev, 0x08, 0x008d); msleep(150); checkword = ((i2c_read(gspca_dev, 0x00) & 0x0f) << 4) | ((i2c_read(gspca_dev, 0x01) & 0xf0) >> 4); PDEBUG(D_PROBE, "probe sif 0x%04x", checkword); if (checkword == 0x0007) { send_unknown(gspca_dev, SENSOR_PAS106); return 0x0f; /* PAS106 */ } return -1; } static int vga_2wr_probe(struct gspca_dev *gspca_dev) { u16 retword; start_2wr_probe(gspca_dev, 0x00); /* HV7131B */ i2c_write(gspca_dev, 0x01, 0xaa, 0x00); retword = i2c_read(gspca_dev, 0x01); if (retword != 0) return 0x00; /* HV7131B */ start_2wr_probe(gspca_dev, 0x04); /* CS2102 */ i2c_write(gspca_dev, 0x01, 0xaa, 0x00); retword = i2c_read(gspca_dev, 0x01); if (retword != 0) return 0x04; /* CS2102 */ start_2wr_probe(gspca_dev, 0x06); /* OmniVision */ reg_w(gspca_dev, 0x08, 0x008d); i2c_write(gspca_dev, 0x11, 0xaa, 0x00); retword = i2c_read(gspca_dev, 0x11); if (retword != 0) { /* (should have returned 0xaa) --> Omnivision? */ /* reg_r 0x10 -> 0x06 --> */ goto ov_check; } start_2wr_probe(gspca_dev, 0x08); /* HDCS2020 */ i2c_write(gspca_dev, 0x1c, 0x00, 0x00); i2c_write(gspca_dev, 0x15, 0xaa, 0x00); retword = i2c_read(gspca_dev, 0x15); if (retword != 0) return 0x08; /* HDCS2020 */ start_2wr_probe(gspca_dev, 0x0a); /* PB0330 */ i2c_write(gspca_dev, 0x07, 0xaa, 0xaa); retword = i2c_read(gspca_dev, 0x07); if (retword != 0) return 0x0a; /* PB0330 */ retword = i2c_read(gspca_dev, 0x03); if (retword != 0) return 0x0a; /* PB0330 ?? */ retword = i2c_read(gspca_dev, 0x04); if (retword != 0) return 0x0a; /* PB0330 ?? */ start_2wr_probe(gspca_dev, 0x0c); /* ICM105A */ i2c_write(gspca_dev, 0x01, 0x11, 0x00); retword = i2c_read(gspca_dev, 0x01); if (retword != 0) return 0x0c; /* ICM105A */ start_2wr_probe(gspca_dev, 0x0e); /* PAS202BCB */ reg_w(gspca_dev, 0x08, 0x008d); i2c_write(gspca_dev, 0x03, 0xaa, 0x00); msleep(50); retword = i2c_read(gspca_dev, 0x03); if (retword != 0) { send_unknown(gspca_dev, SENSOR_PAS202B); return 0x0e; /* PAS202BCB */ } start_2wr_probe(gspca_dev, 0x02); /* TAS5130C */ i2c_write(gspca_dev, 0x01, 0xaa, 0x00); retword = i2c_read(gspca_dev, 0x01); if (retword != 0) return 0x02; /* TAS5130C */ ov_check: reg_r(gspca_dev, 0x0010); /* ?? */ reg_r(gspca_dev, 0x0010); reg_w(gspca_dev, 0x01, 0x0000); reg_w(gspca_dev, 0x01, 0x0001); reg_w(gspca_dev, 0x06, 0x0010); /* OmniVision */ reg_w(gspca_dev, 0xa1, 0x008b); reg_w(gspca_dev, 0x08, 0x008d); msleep(500); reg_w(gspca_dev, 0x01, 0x0012); i2c_write(gspca_dev, 0x12, 0x80, 0x00); /* sensor reset */ retword = i2c_read(gspca_dev, 0x0a) << 8; retword |= i2c_read(gspca_dev, 0x0b); PDEBUG(D_PROBE, "probe 2wr ov vga 0x%04x", retword); switch (retword) { case 0x7631: /* OV7630C */ reg_w(gspca_dev, 0x06, 0x0010); break; case 0x7620: /* OV7620 */ case 0x7648: /* OV7648 */ break; default: return -1; /* not OmniVision */ } return retword; } struct sensor_by_chipset_revision { u16 revision; u8 internal_sensor_id; }; static const struct sensor_by_chipset_revision chipset_revision_sensor[] = { {0xc000, 0x12}, /* TAS5130C */ {0xc001, 0x13}, /* MT9V111 */ {0xe001, 0x13}, {0x8001, 0x13}, {0x8000, 0x14}, /* CS2102K */ {0x8400, 0x15}, /* MT9V111 */ {0xe400, 0x15}, }; static int vga_3wr_probe(struct gspca_dev *gspca_dev) { struct sd *sd = (struct sd *) gspca_dev; int i; u16 retword; /*fixme: lack of 8b=b3 (11,12)-> 10, 8b=e0 (14,15,16)-> 12 found in gspcav1*/ reg_w(gspca_dev, 0x02, 0x0010); reg_r(gspca_dev, 0x0010); reg_w(gspca_dev, 0x01, 0x0000); reg_w(gspca_dev, 0x00, 0x0010); reg_w(gspca_dev, 0x01, 0x0001); reg_w(gspca_dev, 0x91, 0x008b); reg_w(gspca_dev, 0x03, 0x0012); reg_w(gspca_dev, 0x01, 0x0012); reg_w(gspca_dev, 0x05, 0x0012); retword = i2c_read(gspca_dev, 0x14); if (retword != 0) return 0x11; /* HV7131R */ retword = i2c_read(gspca_dev, 0x15); if (retword != 0) return 0x11; /* HV7131R */ retword = i2c_read(gspca_dev, 0x16); if (retword != 0) return 0x11; /* HV7131R */ reg_w(gspca_dev, 0x02, 0x0010); retword = reg_r(gspca_dev, 0x000b) << 8; retword |= reg_r(gspca_dev, 0x000a); PDEBUG(D_PROBE, "probe 3wr vga 1 0x%04x", retword); reg_r(gspca_dev, 0x0010); if ((retword & 0xff00) == 0x6400) return 0x02; /* TAS5130C */ for (i = 0; i < ARRAY_SIZE(chipset_revision_sensor); i++) { if (chipset_revision_sensor[i].revision == retword) { sd->chip_revision = retword; send_unknown(gspca_dev, SENSOR_PB0330); return chipset_revision_sensor[i].internal_sensor_id; } } reg_w(gspca_dev, 0x01, 0x0000); /* check PB0330 */ reg_w(gspca_dev, 0x01, 0x0001); reg_w(gspca_dev, 0xdd, 0x008b); reg_w(gspca_dev, 0x0a, 0x0010); reg_w(gspca_dev, 0x03, 0x0012); reg_w(gspca_dev, 0x01, 0x0012); retword = i2c_read(gspca_dev, 0x00); if (retword != 0) { PDEBUG(D_PROBE, "probe 3wr vga type 0a"); return 0x0a; /* PB0330 */ } /* probe gc0303 / gc0305 */ reg_w(gspca_dev, 0x01, 0x0000); reg_w(gspca_dev, 0x01, 0x0001); reg_w(gspca_dev, 0x98, 0x008b); reg_w(gspca_dev, 0x01, 0x0010); reg_w(gspca_dev, 0x03, 0x0012); msleep(2); reg_w(gspca_dev, 0x01, 0x0012); retword = i2c_read(gspca_dev, 0x00); if (retword != 0) { PDEBUG(D_PROBE, "probe 3wr vga type %02x", retword); if (retword == 0x0011) /* gc0303 */ return 0x0303; if (retword == 0x0029) /* gc0305 */ send_unknown(gspca_dev, SENSOR_GC0305); return retword; } reg_w(gspca_dev, 0x01, 0x0000); /* check OmniVision */ reg_w(gspca_dev, 0x01, 0x0001); reg_w(gspca_dev, 0xa1, 0x008b); reg_w(gspca_dev, 0x08, 0x008d); reg_w(gspca_dev, 0x06, 0x0010); reg_w(gspca_dev, 0x01, 0x0012); reg_w(gspca_dev, 0x05, 0x0012); if (i2c_read(gspca_dev, 0x1c) == 0x007f /* OV7610 - manufacturer ID */ && i2c_read(gspca_dev, 0x1d) == 0x00a2) { send_unknown(gspca_dev, SENSOR_OV7620); return 0x06; /* OmniVision confirm ? */ } reg_w(gspca_dev, 0x01, 0x0000); reg_w(gspca_dev, 0x00, 0x0002); reg_w(gspca_dev, 0x01, 0x0010); reg_w(gspca_dev, 0x01, 0x0001); reg_w(gspca_dev, 0xee, 0x008b); reg_w(gspca_dev, 0x03, 0x0012); reg_w(gspca_dev, 0x01, 0x0012); reg_w(gspca_dev, 0x05, 0x0012); retword = i2c_read(gspca_dev, 0x00) << 8; /* ID 0 */ retword |= i2c_read(gspca_dev, 0x01); /* ID 1 */ PDEBUG(D_PROBE, "probe 3wr vga 2 0x%04x", retword); if (retword == 0x2030) { #ifdef GSPCA_DEBUG u8 retbyte; retbyte = i2c_read(gspca_dev, 0x02); /* revision number */ PDEBUG(D_PROBE, "sensor PO2030 rev 0x%02x", retbyte); #endif send_unknown(gspca_dev, SENSOR_PO2030); return retword; } reg_w(gspca_dev, 0x01, 0x0000); reg_w(gspca_dev, 0x0a, 0x0010); reg_w(gspca_dev, 0xd3, 0x008b); reg_w(gspca_dev, 0x01, 0x0001); reg_w(gspca_dev, 0x03, 0x0012); reg_w(gspca_dev, 0x01, 0x0012); reg_w(gspca_dev, 0x05, 0x0012); reg_w(gspca_dev, 0xd3, 0x008b); retword = i2c_read(gspca_dev, 0x01); if (retword != 0) { PDEBUG(D_PROBE, "probe 3wr vga type 0a ? ret: %04x", retword); return 0x16; /* adcm2700 (6100/6200) */ } return -1; } static int zcxx_probeSensor(struct gspca_dev *gspca_dev) { struct sd *sd = (struct sd *) gspca_dev; int sensor; switch (sd->sensor) { case SENSOR_MC501CB: return -1; /* don't probe */ case SENSOR_GC0303: /* may probe but with no write in reg 0x0010 */ return -1; /* don't probe */ case SENSOR_PAS106: sensor = sif_probe(gspca_dev); if (sensor >= 0) return sensor; break; } sensor = vga_2wr_probe(gspca_dev); if (sensor >= 0) return sensor; return vga_3wr_probe(gspca_dev); } /* this function is called at probe time */ static int sd_config(struct gspca_dev *gspca_dev, const struct usb_device_id *id) { struct sd *sd = (struct sd *) gspca_dev; if (id->idProduct == 0x301b) sd->bridge = BRIDGE_ZC301; else sd->bridge = BRIDGE_ZC303; /* define some sensors from the vendor/product */ sd->sensor = id->driver_info; gspca_dev->cam.ctrls = sd->ctrls; sd->reg08 = REG08_DEF; INIT_WORK(&sd->work, transfer_update); return 0; } /* this function is called at probe and resume time */ static int sd_init(struct gspca_dev *gspca_dev) { struct sd *sd = (struct sd *) gspca_dev; struct cam *cam; int sensor; static const u8 gamma[SENSOR_MAX] = { [SENSOR_ADCM2700] = 4, [SENSOR_CS2102] = 4, [SENSOR_CS2102K] = 5, [SENSOR_GC0303] = 3, [SENSOR_GC0305] = 4, [SENSOR_HDCS2020] = 4, [SENSOR_HV7131B] = 4, [SENSOR_HV7131R] = 4, [SENSOR_ICM105A] = 4, [SENSOR_MC501CB] = 4, [SENSOR_MT9V111_1] = 4, [SENSOR_MT9V111_3] = 4, [SENSOR_OV7620] = 3, [SENSOR_OV7630C] = 4, [SENSOR_PAS106] = 4, [SENSOR_PAS202B] = 4, [SENSOR_PB0330] = 4, [SENSOR_PO2030] = 4, [SENSOR_TAS5130C] = 3, }; static const u8 mode_tb[SENSOR_MAX] = { [SENSOR_ADCM2700] = 2, [SENSOR_CS2102] = 1, [SENSOR_CS2102K] = 1, [SENSOR_GC0303] = 1, [SENSOR_GC0305] = 1, [SENSOR_HDCS2020] = 1, [SENSOR_HV7131B] = 1, [SENSOR_HV7131R] = 1, [SENSOR_ICM105A] = 1, [SENSOR_MC501CB] = 2, [SENSOR_MT9V111_1] = 1, [SENSOR_MT9V111_3] = 1, [SENSOR_OV7620] = 2, [SENSOR_OV7630C] = 1, [SENSOR_PAS106] = 0, [SENSOR_PAS202B] = 1, [SENSOR_PB0330] = 1, [SENSOR_PO2030] = 1, [SENSOR_TAS5130C] = 1, }; static const u8 reg08_tb[SENSOR_MAX] = { [SENSOR_ADCM2700] = 1, [SENSOR_CS2102] = 3, [SENSOR_CS2102K] = 3, [SENSOR_GC0303] = 2, [SENSOR_GC0305] = 3, [SENSOR_HDCS2020] = 1, [SENSOR_HV7131B] = 3, [SENSOR_HV7131R] = 3, [SENSOR_ICM105A] = 3, [SENSOR_MC501CB] = 3, [SENSOR_MT9V111_1] = 3, [SENSOR_MT9V111_3] = 3, [SENSOR_OV7620] = 1, [SENSOR_OV7630C] = 3, [SENSOR_PAS106] = 3, [SENSOR_PAS202B] = 3, [SENSOR_PB0330] = 3, [SENSOR_PO2030] = 2, [SENSOR_TAS5130C] = 3, }; sensor = zcxx_probeSensor(gspca_dev); if (sensor >= 0) PDEBUG(D_PROBE, "probe sensor -> %04x", sensor); if ((unsigned) force_sensor < SENSOR_MAX) { sd->sensor = force_sensor; PDEBUG(D_PROBE, "sensor forced to %d", force_sensor); } else { switch (sensor) { case -1: switch (sd->sensor) { case SENSOR_MC501CB: PDEBUG(D_PROBE, "Sensor MC501CB"); break; case SENSOR_GC0303: PDEBUG(D_PROBE, "Sensor GC0303"); break; default: pr_warn("Unknown sensor - set to TAS5130C\n"); sd->sensor = SENSOR_TAS5130C; } break; case 0: /* check the sensor type */ sensor = i2c_read(gspca_dev, 0x00); PDEBUG(D_PROBE, "Sensor hv7131 type %d", sensor); switch (sensor) { case 0: /* hv7131b */ case 1: /* hv7131e */ PDEBUG(D_PROBE, "Find Sensor HV7131B"); sd->sensor = SENSOR_HV7131B; break; default: /* case 2: * hv7131r */ PDEBUG(D_PROBE, "Find Sensor HV7131R"); sd->sensor = SENSOR_HV7131R; break; } break; case 0x02: PDEBUG(D_PROBE, "Sensor TAS5130C"); sd->sensor = SENSOR_TAS5130C; break; case 0x04: PDEBUG(D_PROBE, "Find Sensor CS2102"); sd->sensor = SENSOR_CS2102; break; case 0x08: PDEBUG(D_PROBE, "Find Sensor HDCS2020"); sd->sensor = SENSOR_HDCS2020; break; case 0x0a: PDEBUG(D_PROBE, "Find Sensor PB0330. Chip revision %x", sd->chip_revision); sd->sensor = SENSOR_PB0330; break; case 0x0c: PDEBUG(D_PROBE, "Find Sensor ICM105A"); sd->sensor = SENSOR_ICM105A; break; case 0x0e: PDEBUG(D_PROBE, "Find Sensor PAS202B"); sd->sensor = SENSOR_PAS202B; break; case 0x0f: PDEBUG(D_PROBE, "Find Sensor PAS106"); sd->sensor = SENSOR_PAS106; break; case 0x10: case 0x12: PDEBUG(D_PROBE, "Find Sensor TAS5130C"); sd->sensor = SENSOR_TAS5130C; break; case 0x11: PDEBUG(D_PROBE, "Find Sensor HV7131R"); sd->sensor = SENSOR_HV7131R; break; case 0x13: case 0x15: PDEBUG(D_PROBE, "Sensor MT9V111. Chip revision %04x", sd->chip_revision); sd->sensor = sd->bridge == BRIDGE_ZC301 ? SENSOR_MT9V111_1 : SENSOR_MT9V111_3; break; case 0x14: PDEBUG(D_PROBE, "Find Sensor CS2102K?. Chip revision %x", sd->chip_revision); sd->sensor = SENSOR_CS2102K; break; case 0x16: PDEBUG(D_PROBE, "Find Sensor ADCM2700"); sd->sensor = SENSOR_ADCM2700; break; case 0x29: PDEBUG(D_PROBE, "Find Sensor GC0305"); sd->sensor = SENSOR_GC0305; break; case 0x0303: PDEBUG(D_PROBE, "Sensor GC0303"); sd->sensor = SENSOR_GC0303; break; case 0x2030: PDEBUG(D_PROBE, "Find Sensor PO2030"); sd->sensor = SENSOR_PO2030; sd->ctrls[SHARPNESS].def = 0; /* from win traces */ break; case 0x7620: PDEBUG(D_PROBE, "Find Sensor OV7620"); sd->sensor = SENSOR_OV7620; break; case 0x7631: PDEBUG(D_PROBE, "Find Sensor OV7630C"); sd->sensor = SENSOR_OV7630C; break; case 0x7648: PDEBUG(D_PROBE, "Find Sensor OV7648"); sd->sensor = SENSOR_OV7620; /* same sensor (?) */ break; default: pr_err("Unknown sensor %04x\n", sensor); return -EINVAL; } } if (sensor < 0x20) { if (sensor == -1 || sensor == 0x10 || sensor == 0x12) reg_w(gspca_dev, 0x02, 0x0010); reg_r(gspca_dev, 0x0010); } cam = &gspca_dev->cam; switch (mode_tb[sd->sensor]) { case 0: cam->cam_mode = sif_mode; cam->nmodes = ARRAY_SIZE(sif_mode); break; case 1: cam->cam_mode = vga_mode; cam->nmodes = ARRAY_SIZE(vga_mode); break; default: /* case 2: */ cam->cam_mode = broken_vga_mode; cam->nmodes = ARRAY_SIZE(broken_vga_mode); break; } sd->ctrls[GAMMA].def = gamma[sd->sensor]; sd->reg08 = reg08_tb[sd->sensor]; sd->ctrls[QUALITY].def = jpeg_qual[sd->reg08]; sd->ctrls[QUALITY].min = jpeg_qual[0]; sd->ctrls[QUALITY].max = jpeg_qual[ARRAY_SIZE(jpeg_qual) - 1]; switch (sd->sensor) { case SENSOR_HV7131R: gspca_dev->ctrl_dis = (1 << QUALITY); break; case SENSOR_OV7630C: gspca_dev->ctrl_dis = (1 << LIGHTFREQ) | (1 << EXPOSURE); break; case SENSOR_PAS202B: gspca_dev->ctrl_dis = (1 << QUALITY) | (1 << EXPOSURE); break; default: gspca_dev->ctrl_dis = (1 << EXPOSURE); break; } #if AUTOGAIN_DEF if (sd->ctrls[AUTOGAIN].val) gspca_dev->ctrl_inac = (1 << EXPOSURE); #endif /* switch off the led */ reg_w(gspca_dev, 0x01, 0x0000); return gspca_dev->usb_err; } static int sd_start(struct gspca_dev *gspca_dev) { struct sd *sd = (struct sd *) gspca_dev; int mode; static const struct usb_action *init_tb[SENSOR_MAX][2] = { [SENSOR_ADCM2700] = {adcm2700_Initial, adcm2700_InitialScale}, [SENSOR_CS2102] = {cs2102_Initial, cs2102_InitialScale}, [SENSOR_CS2102K] = {cs2102K_Initial, cs2102K_InitialScale}, [SENSOR_GC0303] = {gc0303_Initial, gc0303_InitialScale}, [SENSOR_GC0305] = {gc0305_Initial, gc0305_InitialScale}, [SENSOR_HDCS2020] = {hdcs2020_Initial, hdcs2020_InitialScale}, [SENSOR_HV7131B] = {hv7131b_Initial, hv7131b_InitialScale}, [SENSOR_HV7131R] = {hv7131r_Initial, hv7131r_InitialScale}, [SENSOR_ICM105A] = {icm105a_Initial, icm105a_InitialScale}, [SENSOR_MC501CB] = {mc501cb_Initial, mc501cb_InitialScale}, [SENSOR_MT9V111_1] = {mt9v111_1_Initial, mt9v111_1_InitialScale}, [SENSOR_MT9V111_3] = {mt9v111_3_Initial, mt9v111_3_InitialScale}, [SENSOR_OV7620] = {ov7620_Initial, ov7620_InitialScale}, [SENSOR_OV7630C] = {ov7630c_Initial, ov7630c_InitialScale}, [SENSOR_PAS106] = {pas106b_Initial, pas106b_InitialScale}, [SENSOR_PAS202B] = {pas202b_Initial, pas202b_InitialScale}, [SENSOR_PB0330] = {pb0330_Initial, pb0330_InitialScale}, [SENSOR_PO2030] = {po2030_Initial, po2030_InitialScale}, [SENSOR_TAS5130C] = {tas5130c_Initial, tas5130c_InitialScale}, }; /* create the JPEG header */ jpeg_define(sd->jpeg_hdr, gspca_dev->height, gspca_dev->width, 0x21); /* JPEG 422 */ mode = gspca_dev->cam.cam_mode[gspca_dev->curr_mode].priv; switch (sd->sensor) { case SENSOR_HV7131R: zcxx_probeSensor(gspca_dev); break; case SENSOR_PAS106: usb_exchange(gspca_dev, pas106b_Initial_com); break; } usb_exchange(gspca_dev, init_tb[sd->sensor][mode]); switch (sd->sensor) { case SENSOR_ADCM2700: case SENSOR_GC0305: case SENSOR_OV7620: case SENSOR_PO2030: case SENSOR_TAS5130C: case SENSOR_GC0303: /* msleep(100); * ?? */ reg_r(gspca_dev, 0x0002); /* --> 0x40 */ reg_w(gspca_dev, 0x09, 0x01ad); /* (from win traces) */ reg_w(gspca_dev, 0x15, 0x01ae); if (sd->sensor == SENSOR_TAS5130C) break; reg_w(gspca_dev, 0x0d, 0x003a); reg_w(gspca_dev, 0x02, 0x003b); reg_w(gspca_dev, 0x00, 0x0038); break; case SENSOR_HV7131R: case SENSOR_PAS202B: reg_w(gspca_dev, 0x03, 0x003b); reg_w(gspca_dev, 0x0c, 0x003a); reg_w(gspca_dev, 0x0b, 0x0039); if (sd->sensor == SENSOR_HV7131R) reg_w(gspca_dev, 0x50, ZC3XX_R11D_GLOBALGAIN); break; } setmatrix(gspca_dev); switch (sd->sensor) { case SENSOR_ADCM2700: case SENSOR_OV7620: reg_r(gspca_dev, 0x0008); reg_w(gspca_dev, 0x00, 0x0008); break; case SENSOR_PAS202B: case SENSOR_GC0305: case SENSOR_HV7131R: case SENSOR_TAS5130C: reg_r(gspca_dev, 0x0008); /* fall thru */ case SENSOR_PO2030: reg_w(gspca_dev, 0x03, 0x0008); break; } setsharpness(gspca_dev); /* set the gamma tables when not set */ switch (sd->sensor) { case SENSOR_CS2102K: /* gamma set in xxx_Initial */ case SENSOR_HDCS2020: case SENSOR_OV7630C: break; default: setcontrast(gspca_dev); break; } setmatrix(gspca_dev); /* one more time? */ switch (sd->sensor) { case SENSOR_OV7620: case SENSOR_PAS202B: reg_r(gspca_dev, 0x0180); /* from win */ reg_w(gspca_dev, 0x00, 0x0180); break; } setquality(gspca_dev); jpeg_set_qual(sd->jpeg_hdr, jpeg_qual[sd->reg08]); setlightfreq(gspca_dev); switch (sd->sensor) { case SENSOR_ADCM2700: reg_w(gspca_dev, 0x09, 0x01ad); /* (from win traces) */ reg_w(gspca_dev, 0x15, 0x01ae); reg_w(gspca_dev, 0x02, 0x0180); /* ms-win + */ reg_w(gspca_dev, 0x40, 0x0117); break; case SENSOR_HV7131R: setexposure(gspca_dev); reg_w(gspca_dev, 0x00, ZC3XX_R1A7_CALCGLOBALMEAN); break; case SENSOR_GC0305: case SENSOR_TAS5130C: reg_w(gspca_dev, 0x09, 0x01ad); /* (from win traces) */ reg_w(gspca_dev, 0x15, 0x01ae); /* fall thru */ case SENSOR_PAS202B: case SENSOR_PO2030: /* reg_w(gspca_dev, 0x40, ZC3XX_R117_GGAIN); in win traces */ reg_r(gspca_dev, 0x0180); break; case SENSOR_OV7620: reg_w(gspca_dev, 0x09, 0x01ad); reg_w(gspca_dev, 0x15, 0x01ae); i2c_read(gspca_dev, 0x13); /*fixme: returns 0xa3 */ i2c_write(gspca_dev, 0x13, 0xa3, 0x00); /*fixme: returned value to send? */ reg_w(gspca_dev, 0x40, 0x0117); reg_r(gspca_dev, 0x0180); break; } setautogain(gspca_dev); /* start the transfer update thread if needed */ if (gspca_dev->usb_err >= 0) { switch (sd->sensor) { case SENSOR_HV7131R: case SENSOR_PAS202B: sd->work_thread = create_singlethread_workqueue(KBUILD_MODNAME); queue_work(sd->work_thread, &sd->work); break; } } return gspca_dev->usb_err; } /* called on streamoff with alt 0 and on disconnect */ static void sd_stop0(struct gspca_dev *gspca_dev) { struct sd *sd = (struct sd *) gspca_dev; if (sd->work_thread != NULL) { mutex_unlock(&gspca_dev->usb_lock); destroy_workqueue(sd->work_thread); mutex_lock(&gspca_dev->usb_lock); sd->work_thread = NULL; } if (!gspca_dev->present) return; send_unknown(gspca_dev, sd->sensor); } static void sd_pkt_scan(struct gspca_dev *gspca_dev, u8 *data, int len) { struct sd *sd = (struct sd *) gspca_dev; /* check the JPEG end of frame */ if (len >= 3 && data[len - 3] == 0xff && data[len - 2] == 0xd9) { /*fixme: what does the last byte mean?*/ gspca_frame_add(gspca_dev, LAST_PACKET, data, len - 1); return; } /* check the JPEG start of a frame */ if (data[0] == 0xff && data[1] == 0xd8) { /* put the JPEG header in the new frame */ gspca_frame_add(gspca_dev, FIRST_PACKET, sd->jpeg_hdr, JPEG_HDR_SZ); /* remove the webcam's header: * ff d8 ff fe 00 0e 00 00 ss ss 00 01 ww ww hh hh pp pp * - 'ss ss' is the frame sequence number (BE) * - 'ww ww' and 'hh hh' are the window dimensions (BE) * - 'pp pp' is the packet sequence number (BE) */ data += 18; len -= 18; } gspca_frame_add(gspca_dev, INTER_PACKET, data, len); } static int sd_setautogain(struct gspca_dev *gspca_dev, __s32 val) { struct sd *sd = (struct sd *) gspca_dev; sd->ctrls[AUTOGAIN].val = val; if (val) { gspca_dev->ctrl_inac |= (1 << EXPOSURE); } else { gspca_dev->ctrl_inac &= ~(1 << EXPOSURE); if (gspca_dev->streaming) getexposure(gspca_dev); } if (gspca_dev->streaming) setautogain(gspca_dev); return gspca_dev->usb_err; } static int sd_querymenu(struct gspca_dev *gspca_dev, struct v4l2_querymenu *menu) { switch (menu->id) { case V4L2_CID_POWER_LINE_FREQUENCY: switch (menu->index) { case 0: /* V4L2_CID_POWER_LINE_FREQUENCY_DISABLED */ strcpy((char *) menu->name, "NoFliker"); return 0; case 1: /* V4L2_CID_POWER_LINE_FREQUENCY_50HZ */ strcpy((char *) menu->name, "50 Hz"); return 0; case 2: /* V4L2_CID_POWER_LINE_FREQUENCY_60HZ */ strcpy((char *) menu->name, "60 Hz"); return 0; } break; } return -EINVAL; } static int sd_setquality(struct gspca_dev *gspca_dev, __s32 val) { struct sd *sd = (struct sd *) gspca_dev; int i; for (i = 0; i < ARRAY_SIZE(jpeg_qual) - 1; i++) { if (val <= jpeg_qual[i]) break; } if (i > 0 && i == sd->reg08 && val < jpeg_qual[sd->reg08]) i--; sd->reg08 = i; sd->ctrls[QUALITY].val = jpeg_qual[i]; if (gspca_dev->streaming) jpeg_set_qual(sd->jpeg_hdr, sd->ctrls[QUALITY].val); return gspca_dev->usb_err; } static int sd_set_jcomp(struct gspca_dev *gspca_dev, struct v4l2_jpegcompression *jcomp) { struct sd *sd = (struct sd *) gspca_dev; sd_setquality(gspca_dev, jcomp->quality); jcomp->quality = sd->ctrls[QUALITY].val; return gspca_dev->usb_err; } static int sd_get_jcomp(struct gspca_dev *gspca_dev, struct v4l2_jpegcompression *jcomp) { struct sd *sd = (struct sd *) gspca_dev; memset(jcomp, 0, sizeof *jcomp); jcomp->quality = sd->ctrls[QUALITY].val; jcomp->jpeg_markers = V4L2_JPEG_MARKER_DHT | V4L2_JPEG_MARKER_DQT; return 0; } #if defined(CONFIG_INPUT) || defined(CONFIG_INPUT_MODULE) static int sd_int_pkt_scan(struct gspca_dev *gspca_dev, u8 *data, /* interrupt packet data */ int len) /* interrput packet length */ { if (len == 8 && data[4] == 1) { input_report_key(gspca_dev->input_dev, KEY_CAMERA, 1); input_sync(gspca_dev->input_dev); input_report_key(gspca_dev->input_dev, KEY_CAMERA, 0); input_sync(gspca_dev->input_dev); } return 0; } #endif static const struct sd_desc sd_desc = { .name = KBUILD_MODNAME, .ctrls = sd_ctrls, .nctrls = ARRAY_SIZE(sd_ctrls), .config = sd_config, .init = sd_init, .start = sd_start, .stop0 = sd_stop0, .pkt_scan = sd_pkt_scan, .querymenu = sd_querymenu, .get_jcomp = sd_get_jcomp, .set_jcomp = sd_set_jcomp, #if defined(CONFIG_INPUT) || defined(CONFIG_INPUT_MODULE) .int_pkt_scan = sd_int_pkt_scan, #endif }; static const struct usb_device_id device_table[] = { {USB_DEVICE(0x03f0, 0x1b07)}, {USB_DEVICE(0x041e, 0x041e)}, {USB_DEVICE(0x041e, 0x4017)}, {USB_DEVICE(0x041e, 0x401c), .driver_info = SENSOR_PAS106}, {USB_DEVICE(0x041e, 0x401e)}, {USB_DEVICE(0x041e, 0x401f)}, {USB_DEVICE(0x041e, 0x4022)}, {USB_DEVICE(0x041e, 0x4029)}, {USB_DEVICE(0x041e, 0x4034), .driver_info = SENSOR_PAS106}, {USB_DEVICE(0x041e, 0x4035), .driver_info = SENSOR_PAS106}, {USB_DEVICE(0x041e, 0x4036)}, {USB_DEVICE(0x041e, 0x403a)}, {USB_DEVICE(0x041e, 0x4051), .driver_info = SENSOR_GC0303}, {USB_DEVICE(0x041e, 0x4053), .driver_info = SENSOR_GC0303}, {USB_DEVICE(0x0458, 0x7007)}, {USB_DEVICE(0x0458, 0x700c)}, {USB_DEVICE(0x0458, 0x700f)}, {USB_DEVICE(0x0461, 0x0a00)}, {USB_DEVICE(0x046d, 0x089d), .driver_info = SENSOR_MC501CB}, {USB_DEVICE(0x046d, 0x08a0)}, {USB_DEVICE(0x046d, 0x08a1)}, {USB_DEVICE(0x046d, 0x08a2)}, {USB_DEVICE(0x046d, 0x08a3)}, {USB_DEVICE(0x046d, 0x08a6)}, {USB_DEVICE(0x046d, 0x08a7)}, {USB_DEVICE(0x046d, 0x08a9)}, {USB_DEVICE(0x046d, 0x08aa)}, {USB_DEVICE(0x046d, 0x08ac)}, {USB_DEVICE(0x046d, 0x08ad)}, {USB_DEVICE(0x046d, 0x08ae)}, {USB_DEVICE(0x046d, 0x08af)}, {USB_DEVICE(0x046d, 0x08b9)}, {USB_DEVICE(0x046d, 0x08d7)}, {USB_DEVICE(0x046d, 0x08d8)}, {USB_DEVICE(0x046d, 0x08d9)}, {USB_DEVICE(0x046d, 0x08da)}, {USB_DEVICE(0x046d, 0x08dd), .driver_info = SENSOR_MC501CB}, {USB_DEVICE(0x0471, 0x0325), .driver_info = SENSOR_PAS106}, {USB_DEVICE(0x0471, 0x0326), .driver_info = SENSOR_PAS106}, {USB_DEVICE(0x0471, 0x032d), .driver_info = SENSOR_PAS106}, {USB_DEVICE(0x0471, 0x032e), .driver_info = SENSOR_PAS106}, {USB_DEVICE(0x055f, 0xc005)}, {USB_DEVICE(0x055f, 0xd003)}, {USB_DEVICE(0x055f, 0xd004)}, {USB_DEVICE(0x0698, 0x2003)}, {USB_DEVICE(0x0ac8, 0x0301), .driver_info = SENSOR_PAS106}, {USB_DEVICE(0x0ac8, 0x0302), .driver_info = SENSOR_PAS106}, {USB_DEVICE(0x0ac8, 0x301b)}, {USB_DEVICE(0x0ac8, 0x303b)}, {USB_DEVICE(0x0ac8, 0x305b)}, {USB_DEVICE(0x0ac8, 0x307b)}, {USB_DEVICE(0x10fd, 0x0128)}, {USB_DEVICE(0x10fd, 0x804d)}, {USB_DEVICE(0x10fd, 0x8050)}, {} /* end of entry */ }; MODULE_DEVICE_TABLE(usb, device_table); /* -- device connect -- */ static int sd_probe(struct usb_interface *intf, const struct usb_device_id *id) { return gspca_dev_probe(intf, id, &sd_desc, sizeof(struct sd), THIS_MODULE); } /* USB driver */ static struct usb_driver sd_driver = { .name = KBUILD_MODNAME, .id_table = device_table, .probe = sd_probe, .disconnect = gspca_disconnect, #ifdef CONFIG_PM .suspend = gspca_suspend, .resume = gspca_resume, #endif }; module_usb_driver(sd_driver); module_param(force_sensor, int, 0644); MODULE_PARM_DESC(force_sensor, "Force sensor. Only for experts!!!");
gpl-2.0
sakuraba001/android_kernel_samsung_kactivelte
drivers/regulator/tps65217-regulator.c
4812
10509
/* * tps65217-regulator.c * * Regulator driver for TPS65217 PMIC * * Copyright (C) 2011 Texas Instruments Incorporated - http://www.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 version 2. * * This program is distributed "as is" WITHOUT ANY WARRANTY of any * kind, whether express or implied; 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/device.h> #include <linux/init.h> #include <linux/err.h> #include <linux/platform_device.h> #include <linux/regulator/driver.h> #include <linux/regulator/machine.h> #include <linux/mfd/tps65217.h> #define TPS65217_REGULATOR(_name, _id, _ops, _n) \ { \ .name = _name, \ .id = _id, \ .ops = &_ops, \ .n_voltages = _n, \ .type = REGULATOR_VOLTAGE, \ .owner = THIS_MODULE, \ } \ #define TPS65217_INFO(_nm, _min, _max, _f1, _f2, _t, _n, _em, _vr, _vm) \ { \ .name = _nm, \ .min_uV = _min, \ .max_uV = _max, \ .vsel_to_uv = _f1, \ .uv_to_vsel = _f2, \ .table = _t, \ .table_len = _n, \ .enable_mask = _em, \ .set_vout_reg = _vr, \ .set_vout_mask = _vm, \ } static const int LDO1_VSEL_table[] = { 1000000, 1100000, 1200000, 1250000, 1300000, 1350000, 1400000, 1500000, 1600000, 1800000, 2500000, 2750000, 2800000, 3000000, 3100000, 3300000, }; static int tps65217_vsel_to_uv1(unsigned int vsel) { int uV = 0; if (vsel > 63) return -EINVAL; if (vsel <= 24) uV = vsel * 25000 + 900000; else if (vsel <= 52) uV = (vsel - 24) * 50000 + 1500000; else if (vsel < 56) uV = (vsel - 52) * 100000 + 2900000; else uV = 3300000; return uV; } static int tps65217_uv_to_vsel1(int uV, unsigned int *vsel) { if ((uV < 0) && (uV > 3300000)) return -EINVAL; if (uV <= 1500000) *vsel = DIV_ROUND_UP(uV - 900000, 25000); else if (uV <= 2900000) *vsel = 24 + DIV_ROUND_UP(uV - 1500000, 50000); else if (uV < 3300000) *vsel = 52 + DIV_ROUND_UP(uV - 2900000, 100000); else *vsel = 56; return 0; } static int tps65217_vsel_to_uv2(unsigned int vsel) { int uV = 0; if (vsel > 31) return -EINVAL; if (vsel <= 8) uV = vsel * 50000 + 1500000; else if (vsel <= 13) uV = (vsel - 8) * 100000 + 1900000; else uV = (vsel - 13) * 50000 + 2400000; return uV; } static int tps65217_uv_to_vsel2(int uV, unsigned int *vsel) { if ((uV < 0) && (uV > 3300000)) return -EINVAL; if (uV <= 1900000) *vsel = DIV_ROUND_UP(uV - 1500000, 50000); else if (uV <= 2400000) *vsel = 8 + DIV_ROUND_UP(uV - 1900000, 100000); else *vsel = 13 + DIV_ROUND_UP(uV - 2400000, 50000); return 0; } static struct tps_info tps65217_pmic_regs[] = { TPS65217_INFO("DCDC1", 900000, 1800000, tps65217_vsel_to_uv1, tps65217_uv_to_vsel1, NULL, 64, TPS65217_ENABLE_DC1_EN, TPS65217_REG_DEFDCDC1, TPS65217_DEFDCDCX_DCDC_MASK), TPS65217_INFO("DCDC2", 900000, 3300000, tps65217_vsel_to_uv1, tps65217_uv_to_vsel1, NULL, 64, TPS65217_ENABLE_DC2_EN, TPS65217_REG_DEFDCDC2, TPS65217_DEFDCDCX_DCDC_MASK), TPS65217_INFO("DCDC3", 900000, 1500000, tps65217_vsel_to_uv1, tps65217_uv_to_vsel1, NULL, 64, TPS65217_ENABLE_DC3_EN, TPS65217_REG_DEFDCDC3, TPS65217_DEFDCDCX_DCDC_MASK), TPS65217_INFO("LDO1", 1000000, 3300000, NULL, NULL, LDO1_VSEL_table, 16, TPS65217_ENABLE_LDO1_EN, TPS65217_REG_DEFLDO1, TPS65217_DEFLDO1_LDO1_MASK), TPS65217_INFO("LDO2", 900000, 3300000, tps65217_vsel_to_uv1, tps65217_uv_to_vsel1, NULL, 64, TPS65217_ENABLE_LDO2_EN, TPS65217_REG_DEFLDO2, TPS65217_DEFLDO2_LDO2_MASK), TPS65217_INFO("LDO3", 1800000, 3300000, tps65217_vsel_to_uv2, tps65217_uv_to_vsel2, NULL, 32, TPS65217_ENABLE_LS1_EN | TPS65217_DEFLDO3_LDO3_EN, TPS65217_REG_DEFLS1, TPS65217_DEFLDO3_LDO3_MASK), TPS65217_INFO("LDO4", 1800000, 3300000, tps65217_vsel_to_uv2, tps65217_uv_to_vsel2, NULL, 32, TPS65217_ENABLE_LS2_EN | TPS65217_DEFLDO4_LDO4_EN, TPS65217_REG_DEFLS2, TPS65217_DEFLDO4_LDO4_MASK), }; static int tps65217_pmic_is_enabled(struct regulator_dev *dev) { int ret; struct tps65217 *tps = rdev_get_drvdata(dev); unsigned int data, rid = rdev_get_id(dev); if (rid < TPS65217_DCDC_1 || rid > TPS65217_LDO_4) return -EINVAL; ret = tps65217_reg_read(tps, TPS65217_REG_ENABLE, &data); if (ret) return ret; return (data & tps->info[rid]->enable_mask) ? 1 : 0; } static int tps65217_pmic_enable(struct regulator_dev *dev) { struct tps65217 *tps = rdev_get_drvdata(dev); unsigned int rid = rdev_get_id(dev); if (rid < TPS65217_DCDC_1 || rid > TPS65217_LDO_4) return -EINVAL; /* Enable the regulator and password protection is level 1 */ return tps65217_set_bits(tps, TPS65217_REG_ENABLE, tps->info[rid]->enable_mask, tps->info[rid]->enable_mask, TPS65217_PROTECT_L1); } static int tps65217_pmic_disable(struct regulator_dev *dev) { struct tps65217 *tps = rdev_get_drvdata(dev); unsigned int rid = rdev_get_id(dev); if (rid < TPS65217_DCDC_1 || rid > TPS65217_LDO_4) return -EINVAL; /* Disable the regulator and password protection is level 1 */ return tps65217_clear_bits(tps, TPS65217_REG_ENABLE, tps->info[rid]->enable_mask, TPS65217_PROTECT_L1); } static int tps65217_pmic_get_voltage_sel(struct regulator_dev *dev) { int ret; struct tps65217 *tps = rdev_get_drvdata(dev); unsigned int selector, rid = rdev_get_id(dev); if (rid < TPS65217_DCDC_1 || rid > TPS65217_LDO_4) return -EINVAL; ret = tps65217_reg_read(tps, tps->info[rid]->set_vout_reg, &selector); if (ret) return ret; selector &= tps->info[rid]->set_vout_mask; return selector; } static int tps65217_pmic_ldo1_set_voltage_sel(struct regulator_dev *dev, unsigned selector) { struct tps65217 *tps = rdev_get_drvdata(dev); int ldo = rdev_get_id(dev); if (ldo != TPS65217_LDO_1) return -EINVAL; if (selector >= tps->info[ldo]->table_len) return -EINVAL; /* Set the voltage based on vsel value and write protect level is 2 */ return tps65217_set_bits(tps, tps->info[ldo]->set_vout_reg, tps->info[ldo]->set_vout_mask, selector, TPS65217_PROTECT_L2); } static int tps65217_pmic_set_voltage(struct regulator_dev *dev, int min_uV, int max_uV, unsigned *selector) { int ret; struct tps65217 *tps = rdev_get_drvdata(dev); unsigned int rid = rdev_get_id(dev); /* LDO1 implements set_voltage_sel callback */ if (rid == TPS65217_LDO_1) return -EINVAL; if (rid < TPS65217_DCDC_1 || rid > TPS65217_LDO_4) return -EINVAL; if (min_uV < tps->info[rid]->min_uV || min_uV > tps->info[rid]->max_uV) return -EINVAL; if (max_uV < tps->info[rid]->min_uV || max_uV > tps->info[rid]->max_uV) return -EINVAL; ret = tps->info[rid]->uv_to_vsel(min_uV, selector); if (ret) return ret; /* Set the voltage based on vsel value and write protect level is 2 */ ret = tps65217_set_bits(tps, tps->info[rid]->set_vout_reg, tps->info[rid]->set_vout_mask, *selector, TPS65217_PROTECT_L2); /* Set GO bit for DCDCx to initiate voltage transistion */ switch (rid) { case TPS65217_DCDC_1 ... TPS65217_DCDC_3: ret = tps65217_set_bits(tps, TPS65217_REG_DEFSLEW, TPS65217_DEFSLEW_GO, TPS65217_DEFSLEW_GO, TPS65217_PROTECT_L2); break; } return ret; } static int tps65217_pmic_list_voltage(struct regulator_dev *dev, unsigned selector) { struct tps65217 *tps = rdev_get_drvdata(dev); unsigned int rid = rdev_get_id(dev); if (rid < TPS65217_DCDC_1 || rid > TPS65217_LDO_4) return -EINVAL; if (selector >= tps->info[rid]->table_len) return -EINVAL; if (tps->info[rid]->table) return tps->info[rid]->table[selector]; return tps->info[rid]->vsel_to_uv(selector); } /* Operations permitted on DCDCx, LDO2, LDO3 and LDO4 */ static struct regulator_ops tps65217_pmic_ops = { .is_enabled = tps65217_pmic_is_enabled, .enable = tps65217_pmic_enable, .disable = tps65217_pmic_disable, .get_voltage_sel = tps65217_pmic_get_voltage_sel, .set_voltage = tps65217_pmic_set_voltage, .list_voltage = tps65217_pmic_list_voltage, }; /* Operations permitted on LDO1 */ static struct regulator_ops tps65217_pmic_ldo1_ops = { .is_enabled = tps65217_pmic_is_enabled, .enable = tps65217_pmic_enable, .disable = tps65217_pmic_disable, .get_voltage_sel = tps65217_pmic_get_voltage_sel, .set_voltage_sel = tps65217_pmic_ldo1_set_voltage_sel, .list_voltage = tps65217_pmic_list_voltage, }; static struct regulator_desc regulators[] = { TPS65217_REGULATOR("DCDC1", TPS65217_DCDC_1, tps65217_pmic_ops, 64), TPS65217_REGULATOR("DCDC2", TPS65217_DCDC_2, tps65217_pmic_ops, 64), TPS65217_REGULATOR("DCDC3", TPS65217_DCDC_3, tps65217_pmic_ops, 64), TPS65217_REGULATOR("LDO1", TPS65217_LDO_1, tps65217_pmic_ldo1_ops, 16), TPS65217_REGULATOR("LDO2", TPS65217_LDO_2, tps65217_pmic_ops, 64), TPS65217_REGULATOR("LDO3", TPS65217_LDO_3, tps65217_pmic_ops, 32), TPS65217_REGULATOR("LDO4", TPS65217_LDO_4, tps65217_pmic_ops, 32), }; static int __devinit tps65217_regulator_probe(struct platform_device *pdev) { struct regulator_dev *rdev; struct tps65217 *tps; struct tps_info *info = &tps65217_pmic_regs[pdev->id]; /* Already set by core driver */ tps = dev_to_tps65217(pdev->dev.parent); tps->info[pdev->id] = info; rdev = regulator_register(&regulators[pdev->id], &pdev->dev, pdev->dev.platform_data, tps, NULL); if (IS_ERR(rdev)) return PTR_ERR(rdev); platform_set_drvdata(pdev, rdev); return 0; } static int __devexit tps65217_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 tps65217_regulator_driver = { .driver = { .name = "tps65217-pmic", }, .probe = tps65217_regulator_probe, .remove = __devexit_p(tps65217_regulator_remove), }; static int __init tps65217_regulator_init(void) { return platform_driver_register(&tps65217_regulator_driver); } subsys_initcall(tps65217_regulator_init); static void __exit tps65217_regulator_exit(void) { platform_driver_unregister(&tps65217_regulator_driver); } module_exit(tps65217_regulator_exit); MODULE_AUTHOR("AnilKumar Ch <anilkumar@ti.com>"); MODULE_DESCRIPTION("TPS65217 voltage regulator driver"); MODULE_ALIAS("platform:tps65217-pmic"); MODULE_LICENSE("GPL v2");
gpl-2.0
ennarr/linux-kernel
drivers/mmc/host/cb710-mmc.c
5068
22010
/* * cb710/mmc.c * * Copyright by Michał Mirosław, 2008-2009 * * 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/pci.h> #include <linux/delay.h> #include "cb710-mmc.h" static const u8 cb710_clock_divider_log2[8] = { /* 1, 2, 4, 8, 16, 32, 128, 512 */ 0, 1, 2, 3, 4, 5, 7, 9 }; #define CB710_MAX_DIVIDER_IDX \ (ARRAY_SIZE(cb710_clock_divider_log2) - 1) static const u8 cb710_src_freq_mhz[16] = { 33, 10, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85 }; static void cb710_mmc_select_clock_divider(struct mmc_host *mmc, int hz) { struct cb710_slot *slot = cb710_mmc_to_slot(mmc); struct pci_dev *pdev = cb710_slot_to_chip(slot)->pdev; u32 src_freq_idx; u32 divider_idx; int src_hz; /* on CB710 in HP nx9500: * src_freq_idx == 0 * indexes 1-7 work as written in the table * indexes 0,8-15 give no clock output */ pci_read_config_dword(pdev, 0x48, &src_freq_idx); src_freq_idx = (src_freq_idx >> 16) & 0xF; src_hz = cb710_src_freq_mhz[src_freq_idx] * 1000000; for (divider_idx = 0; divider_idx < CB710_MAX_DIVIDER_IDX; ++divider_idx) { if (hz >= src_hz >> cb710_clock_divider_log2[divider_idx]) break; } if (src_freq_idx) divider_idx |= 0x8; else if (divider_idx == 0) divider_idx = 1; cb710_pci_update_config_reg(pdev, 0x40, ~0xF0000000, divider_idx << 28); dev_dbg(cb710_slot_dev(slot), "clock set to %d Hz, wanted %d Hz; src_freq_idx = %d, divider_idx = %d|%d\n", src_hz >> cb710_clock_divider_log2[divider_idx & 7], hz, src_freq_idx, divider_idx & 7, divider_idx & 8); } static void __cb710_mmc_enable_irq(struct cb710_slot *slot, unsigned short enable, unsigned short mask) { /* clear global IE * - it gets set later if any interrupt sources are enabled */ mask |= CB710_MMC_IE_IRQ_ENABLE; /* look like interrupt is fired whenever * WORD[0x0C] & WORD[0x10] != 0; * -> bit 15 port 0x0C seems to be global interrupt enable */ enable = (cb710_read_port_16(slot, CB710_MMC_IRQ_ENABLE_PORT) & ~mask) | enable; if (enable) enable |= CB710_MMC_IE_IRQ_ENABLE; cb710_write_port_16(slot, CB710_MMC_IRQ_ENABLE_PORT, enable); } static void cb710_mmc_enable_irq(struct cb710_slot *slot, unsigned short enable, unsigned short mask) { struct cb710_mmc_reader *reader = mmc_priv(cb710_slot_to_mmc(slot)); unsigned long flags; spin_lock_irqsave(&reader->irq_lock, flags); /* this is the only thing irq_lock protects */ __cb710_mmc_enable_irq(slot, enable, mask); spin_unlock_irqrestore(&reader->irq_lock, flags); } static void cb710_mmc_reset_events(struct cb710_slot *slot) { cb710_write_port_8(slot, CB710_MMC_STATUS0_PORT, 0xFF); cb710_write_port_8(slot, CB710_MMC_STATUS1_PORT, 0xFF); cb710_write_port_8(slot, CB710_MMC_STATUS2_PORT, 0xFF); } static void cb710_mmc_enable_4bit_data(struct cb710_slot *slot, int enable) { if (enable) cb710_modify_port_8(slot, CB710_MMC_CONFIG1_PORT, CB710_MMC_C1_4BIT_DATA_BUS, 0); else cb710_modify_port_8(slot, CB710_MMC_CONFIG1_PORT, 0, CB710_MMC_C1_4BIT_DATA_BUS); } static int cb710_check_event(struct cb710_slot *slot, u8 what) { u16 status; status = cb710_read_port_16(slot, CB710_MMC_STATUS_PORT); if (status & CB710_MMC_S0_FIFO_UNDERFLOW) { /* it is just a guess, so log it */ dev_dbg(cb710_slot_dev(slot), "CHECK : ignoring bit 6 in status %04X\n", status); cb710_write_port_8(slot, CB710_MMC_STATUS0_PORT, CB710_MMC_S0_FIFO_UNDERFLOW); status &= ~CB710_MMC_S0_FIFO_UNDERFLOW; } if (status & CB710_MMC_STATUS_ERROR_EVENTS) { dev_dbg(cb710_slot_dev(slot), "CHECK : returning EIO on status %04X\n", status); cb710_write_port_8(slot, CB710_MMC_STATUS0_PORT, status & 0xFF); cb710_write_port_8(slot, CB710_MMC_STATUS1_PORT, CB710_MMC_S1_RESET); return -EIO; } /* 'what' is a bit in MMC_STATUS1 */ if ((status >> 8) & what) { cb710_write_port_8(slot, CB710_MMC_STATUS1_PORT, what); return 1; } return 0; } static int cb710_wait_for_event(struct cb710_slot *slot, u8 what) { int err = 0; unsigned limit = 2000000; /* FIXME: real timeout */ #ifdef CONFIG_CB710_DEBUG u32 e, x; e = cb710_read_port_32(slot, CB710_MMC_STATUS_PORT); #endif while (!(err = cb710_check_event(slot, what))) { if (!--limit) { cb710_dump_regs(cb710_slot_to_chip(slot), CB710_DUMP_REGS_MMC); err = -ETIMEDOUT; break; } udelay(1); } #ifdef CONFIG_CB710_DEBUG x = cb710_read_port_32(slot, CB710_MMC_STATUS_PORT); limit = 2000000 - limit; if (limit > 100) dev_dbg(cb710_slot_dev(slot), "WAIT10: waited %d loops, what %d, entry val %08X, exit val %08X\n", limit, what, e, x); #endif return err < 0 ? err : 0; } static int cb710_wait_while_busy(struct cb710_slot *slot, uint8_t mask) { unsigned limit = 500000; /* FIXME: real timeout */ int err = 0; #ifdef CONFIG_CB710_DEBUG u32 e, x; e = cb710_read_port_32(slot, CB710_MMC_STATUS_PORT); #endif while (cb710_read_port_8(slot, CB710_MMC_STATUS2_PORT) & mask) { if (!--limit) { cb710_dump_regs(cb710_slot_to_chip(slot), CB710_DUMP_REGS_MMC); err = -ETIMEDOUT; break; } udelay(1); } #ifdef CONFIG_CB710_DEBUG x = cb710_read_port_32(slot, CB710_MMC_STATUS_PORT); limit = 500000 - limit; if (limit > 100) dev_dbg(cb710_slot_dev(slot), "WAIT12: waited %d loops, mask %02X, entry val %08X, exit val %08X\n", limit, mask, e, x); #endif return err; } static void cb710_mmc_set_transfer_size(struct cb710_slot *slot, size_t count, size_t blocksize) { cb710_wait_while_busy(slot, CB710_MMC_S2_BUSY_20); cb710_write_port_32(slot, CB710_MMC_TRANSFER_SIZE_PORT, ((count - 1) << 16)|(blocksize - 1)); dev_vdbg(cb710_slot_dev(slot), "set up for %zu block%s of %zu bytes\n", count, count == 1 ? "" : "s", blocksize); } static void cb710_mmc_fifo_hack(struct cb710_slot *slot) { /* without this, received data is prepended with 8-bytes of zeroes */ u32 r1, r2; int ok = 0; r1 = cb710_read_port_32(slot, CB710_MMC_DATA_PORT); r2 = cb710_read_port_32(slot, CB710_MMC_DATA_PORT); if (cb710_read_port_8(slot, CB710_MMC_STATUS0_PORT) & CB710_MMC_S0_FIFO_UNDERFLOW) { cb710_write_port_8(slot, CB710_MMC_STATUS0_PORT, CB710_MMC_S0_FIFO_UNDERFLOW); ok = 1; } dev_dbg(cb710_slot_dev(slot), "FIFO-read-hack: expected STATUS0 bit was %s\n", ok ? "set." : "NOT SET!"); dev_dbg(cb710_slot_dev(slot), "FIFO-read-hack: dwords ignored: %08X %08X - %s\n", r1, r2, (r1|r2) ? "BAD (NOT ZERO)!" : "ok"); } static int cb710_mmc_receive_pio(struct cb710_slot *slot, struct sg_mapping_iter *miter, size_t dw_count) { if (!(cb710_read_port_8(slot, CB710_MMC_STATUS2_PORT) & CB710_MMC_S2_FIFO_READY)) { int err = cb710_wait_for_event(slot, CB710_MMC_S1_PIO_TRANSFER_DONE); if (err) return err; } cb710_sg_dwiter_write_from_io(miter, slot->iobase + CB710_MMC_DATA_PORT, dw_count); return 0; } static bool cb710_is_transfer_size_supported(struct mmc_data *data) { return !(data->blksz & 15 && (data->blocks != 1 || data->blksz != 8)); } static int cb710_mmc_receive(struct cb710_slot *slot, struct mmc_data *data) { struct sg_mapping_iter miter; size_t len, blocks = data->blocks; int err = 0; /* TODO: I don't know how/if the hardware handles non-16B-boundary blocks * except single 8B block */ if (unlikely(data->blksz & 15 && (data->blocks != 1 || data->blksz != 8))) return -EINVAL; sg_miter_start(&miter, data->sg, data->sg_len, SG_MITER_TO_SG); cb710_modify_port_8(slot, CB710_MMC_CONFIG2_PORT, 15, CB710_MMC_C2_READ_PIO_SIZE_MASK); cb710_mmc_fifo_hack(slot); while (blocks-- > 0) { len = data->blksz; while (len >= 16) { err = cb710_mmc_receive_pio(slot, &miter, 4); if (err) goto out; len -= 16; } if (!len) continue; cb710_modify_port_8(slot, CB710_MMC_CONFIG2_PORT, len - 1, CB710_MMC_C2_READ_PIO_SIZE_MASK); len = (len >= 8) ? 4 : 2; err = cb710_mmc_receive_pio(slot, &miter, len); if (err) goto out; } out: sg_miter_stop(&miter); return err; } static int cb710_mmc_send(struct cb710_slot *slot, struct mmc_data *data) { struct sg_mapping_iter miter; size_t len, blocks = data->blocks; int err = 0; /* TODO: I don't know how/if the hardware handles multiple * non-16B-boundary blocks */ if (unlikely(data->blocks > 1 && data->blksz & 15)) return -EINVAL; sg_miter_start(&miter, data->sg, data->sg_len, SG_MITER_FROM_SG); cb710_modify_port_8(slot, CB710_MMC_CONFIG2_PORT, 0, CB710_MMC_C2_READ_PIO_SIZE_MASK); while (blocks-- > 0) { len = (data->blksz + 15) >> 4; do { if (!(cb710_read_port_8(slot, CB710_MMC_STATUS2_PORT) & CB710_MMC_S2_FIFO_EMPTY)) { err = cb710_wait_for_event(slot, CB710_MMC_S1_PIO_TRANSFER_DONE); if (err) goto out; } cb710_sg_dwiter_read_to_io(&miter, slot->iobase + CB710_MMC_DATA_PORT, 4); } while (--len); } out: sg_miter_stop(&miter); return err; } static u16 cb710_encode_cmd_flags(struct cb710_mmc_reader *reader, struct mmc_command *cmd) { unsigned int flags = cmd->flags; u16 cb_flags = 0; /* Windows driver returned 0 for commands for which no response * is expected. It happened that there were only two such commands * used: MMC_GO_IDLE_STATE and MMC_GO_INACTIVE_STATE so it might * as well be a bug in that driver. * * Original driver set bit 14 for MMC/SD application * commands. There's no difference 'on the wire' and * it apparently works without it anyway. */ switch (flags & MMC_CMD_MASK) { case MMC_CMD_AC: cb_flags = CB710_MMC_CMD_AC; break; case MMC_CMD_ADTC: cb_flags = CB710_MMC_CMD_ADTC; break; case MMC_CMD_BC: cb_flags = CB710_MMC_CMD_BC; break; case MMC_CMD_BCR: cb_flags = CB710_MMC_CMD_BCR; break; } if (flags & MMC_RSP_BUSY) cb_flags |= CB710_MMC_RSP_BUSY; cb_flags |= cmd->opcode << CB710_MMC_CMD_CODE_SHIFT; if (cmd->data && (cmd->data->flags & MMC_DATA_READ)) cb_flags |= CB710_MMC_DATA_READ; if (flags & MMC_RSP_PRESENT) { /* Windows driver set 01 at bits 4,3 except for * MMC_SET_BLOCKLEN where it set 10. Maybe the * hardware can do something special about this * command? The original driver looks buggy/incomplete * anyway so we ignore this for now. * * I assume that 00 here means no response is expected. */ cb_flags |= CB710_MMC_RSP_PRESENT; if (flags & MMC_RSP_136) cb_flags |= CB710_MMC_RSP_136; if (!(flags & MMC_RSP_CRC)) cb_flags |= CB710_MMC_RSP_NO_CRC; } return cb_flags; } static void cb710_receive_response(struct cb710_slot *slot, struct mmc_command *cmd) { unsigned rsp_opcode, wanted_opcode; /* Looks like final byte with CRC is always stripped (same as SDHCI) */ if (cmd->flags & MMC_RSP_136) { u32 resp[4]; resp[0] = cb710_read_port_32(slot, CB710_MMC_RESPONSE3_PORT); resp[1] = cb710_read_port_32(slot, CB710_MMC_RESPONSE2_PORT); resp[2] = cb710_read_port_32(slot, CB710_MMC_RESPONSE1_PORT); resp[3] = cb710_read_port_32(slot, CB710_MMC_RESPONSE0_PORT); rsp_opcode = resp[0] >> 24; cmd->resp[0] = (resp[0] << 8)|(resp[1] >> 24); cmd->resp[1] = (resp[1] << 8)|(resp[2] >> 24); cmd->resp[2] = (resp[2] << 8)|(resp[3] >> 24); cmd->resp[3] = (resp[3] << 8); } else { rsp_opcode = cb710_read_port_32(slot, CB710_MMC_RESPONSE1_PORT) & 0x3F; cmd->resp[0] = cb710_read_port_32(slot, CB710_MMC_RESPONSE0_PORT); } wanted_opcode = (cmd->flags & MMC_RSP_OPCODE) ? cmd->opcode : 0x3F; if (rsp_opcode != wanted_opcode) cmd->error = -EILSEQ; } static int cb710_mmc_transfer_data(struct cb710_slot *slot, struct mmc_data *data) { int error, to; if (data->flags & MMC_DATA_READ) error = cb710_mmc_receive(slot, data); else error = cb710_mmc_send(slot, data); to = cb710_wait_for_event(slot, CB710_MMC_S1_DATA_TRANSFER_DONE); if (!error) error = to; if (!error) data->bytes_xfered = data->blksz * data->blocks; return error; } static int cb710_mmc_command(struct mmc_host *mmc, struct mmc_command *cmd) { struct cb710_slot *slot = cb710_mmc_to_slot(mmc); struct cb710_mmc_reader *reader = mmc_priv(mmc); struct mmc_data *data = cmd->data; u16 cb_cmd = cb710_encode_cmd_flags(reader, cmd); dev_dbg(cb710_slot_dev(slot), "cmd request: 0x%04X\n", cb_cmd); if (data) { if (!cb710_is_transfer_size_supported(data)) { data->error = -EINVAL; return -1; } cb710_mmc_set_transfer_size(slot, data->blocks, data->blksz); } cb710_wait_while_busy(slot, CB710_MMC_S2_BUSY_20|CB710_MMC_S2_BUSY_10); cb710_write_port_16(slot, CB710_MMC_CMD_TYPE_PORT, cb_cmd); cb710_wait_while_busy(slot, CB710_MMC_S2_BUSY_20); cb710_write_port_32(slot, CB710_MMC_CMD_PARAM_PORT, cmd->arg); cb710_mmc_reset_events(slot); cb710_wait_while_busy(slot, CB710_MMC_S2_BUSY_20); cb710_modify_port_8(slot, CB710_MMC_CONFIG0_PORT, 0x01, 0); cmd->error = cb710_wait_for_event(slot, CB710_MMC_S1_COMMAND_SENT); if (cmd->error) return -1; if (cmd->flags & MMC_RSP_PRESENT) { cb710_receive_response(slot, cmd); if (cmd->error) return -1; } if (data) data->error = cb710_mmc_transfer_data(slot, data); return 0; } static void cb710_mmc_request(struct mmc_host *mmc, struct mmc_request *mrq) { struct cb710_slot *slot = cb710_mmc_to_slot(mmc); struct cb710_mmc_reader *reader = mmc_priv(mmc); WARN_ON(reader->mrq != NULL); reader->mrq = mrq; cb710_mmc_enable_irq(slot, CB710_MMC_IE_TEST_MASK, 0); if (!cb710_mmc_command(mmc, mrq->cmd) && mrq->stop) cb710_mmc_command(mmc, mrq->stop); tasklet_schedule(&reader->finish_req_tasklet); } static int cb710_mmc_powerup(struct cb710_slot *slot) { #ifdef CONFIG_CB710_DEBUG struct cb710_chip *chip = cb710_slot_to_chip(slot); #endif int err; /* a lot of magic for now */ dev_dbg(cb710_slot_dev(slot), "bus powerup\n"); cb710_dump_regs(chip, CB710_DUMP_REGS_MMC); err = cb710_wait_while_busy(slot, CB710_MMC_S2_BUSY_20); if (unlikely(err)) return err; cb710_modify_port_8(slot, CB710_MMC_CONFIG1_PORT, 0x80, 0); cb710_modify_port_8(slot, CB710_MMC_CONFIG3_PORT, 0x80, 0); cb710_dump_regs(chip, CB710_DUMP_REGS_MMC); mdelay(1); dev_dbg(cb710_slot_dev(slot), "after delay 1\n"); cb710_dump_regs(chip, CB710_DUMP_REGS_MMC); err = cb710_wait_while_busy(slot, CB710_MMC_S2_BUSY_20); if (unlikely(err)) return err; cb710_modify_port_8(slot, CB710_MMC_CONFIG1_PORT, 0x09, 0); cb710_dump_regs(chip, CB710_DUMP_REGS_MMC); mdelay(1); dev_dbg(cb710_slot_dev(slot), "after delay 2\n"); cb710_dump_regs(chip, CB710_DUMP_REGS_MMC); err = cb710_wait_while_busy(slot, CB710_MMC_S2_BUSY_20); if (unlikely(err)) return err; cb710_modify_port_8(slot, CB710_MMC_CONFIG1_PORT, 0, 0x08); cb710_dump_regs(chip, CB710_DUMP_REGS_MMC); mdelay(2); dev_dbg(cb710_slot_dev(slot), "after delay 3\n"); cb710_dump_regs(chip, CB710_DUMP_REGS_MMC); cb710_modify_port_8(slot, CB710_MMC_CONFIG0_PORT, 0x06, 0); cb710_modify_port_8(slot, CB710_MMC_CONFIG1_PORT, 0x70, 0); cb710_modify_port_8(slot, CB710_MMC_CONFIG2_PORT, 0x80, 0); cb710_modify_port_8(slot, CB710_MMC_CONFIG3_PORT, 0x03, 0); cb710_dump_regs(chip, CB710_DUMP_REGS_MMC); err = cb710_wait_while_busy(slot, CB710_MMC_S2_BUSY_20); if (unlikely(err)) return err; /* This port behaves weird: quick byte reads of 0x08,0x09 return * 0xFF,0x00 after writing 0xFFFF to 0x08; it works correctly when * read/written from userspace... What am I missing here? * (it doesn't depend on write-to-read delay) */ cb710_write_port_16(slot, CB710_MMC_CONFIGB_PORT, 0xFFFF); cb710_modify_port_8(slot, CB710_MMC_CONFIG0_PORT, 0x06, 0); cb710_dump_regs(chip, CB710_DUMP_REGS_MMC); dev_dbg(cb710_slot_dev(slot), "bus powerup finished\n"); return cb710_check_event(slot, 0); } static void cb710_mmc_powerdown(struct cb710_slot *slot) { cb710_modify_port_8(slot, CB710_MMC_CONFIG1_PORT, 0, 0x81); cb710_modify_port_8(slot, CB710_MMC_CONFIG3_PORT, 0, 0x80); } static void cb710_mmc_set_ios(struct mmc_host *mmc, struct mmc_ios *ios) { struct cb710_slot *slot = cb710_mmc_to_slot(mmc); struct cb710_mmc_reader *reader = mmc_priv(mmc); int err; cb710_mmc_select_clock_divider(mmc, ios->clock); if (ios->power_mode != reader->last_power_mode) switch (ios->power_mode) { case MMC_POWER_ON: err = cb710_mmc_powerup(slot); if (err) { dev_warn(cb710_slot_dev(slot), "powerup failed (%d)- retrying\n", err); cb710_mmc_powerdown(slot); udelay(1); err = cb710_mmc_powerup(slot); if (err) dev_warn(cb710_slot_dev(slot), "powerup retry failed (%d) - expect errors\n", err); } reader->last_power_mode = MMC_POWER_ON; break; case MMC_POWER_OFF: cb710_mmc_powerdown(slot); reader->last_power_mode = MMC_POWER_OFF; break; case MMC_POWER_UP: default: /* ignore */; } cb710_mmc_enable_4bit_data(slot, ios->bus_width != MMC_BUS_WIDTH_1); cb710_mmc_enable_irq(slot, CB710_MMC_IE_TEST_MASK, 0); } static int cb710_mmc_get_ro(struct mmc_host *mmc) { struct cb710_slot *slot = cb710_mmc_to_slot(mmc); return cb710_read_port_8(slot, CB710_MMC_STATUS3_PORT) & CB710_MMC_S3_WRITE_PROTECTED; } static int cb710_mmc_get_cd(struct mmc_host *mmc) { struct cb710_slot *slot = cb710_mmc_to_slot(mmc); return cb710_read_port_8(slot, CB710_MMC_STATUS3_PORT) & CB710_MMC_S3_CARD_DETECTED; } static int cb710_mmc_irq_handler(struct cb710_slot *slot) { struct mmc_host *mmc = cb710_slot_to_mmc(slot); struct cb710_mmc_reader *reader = mmc_priv(mmc); u32 status, config1, config2, irqen; status = cb710_read_port_32(slot, CB710_MMC_STATUS_PORT); irqen = cb710_read_port_32(slot, CB710_MMC_IRQ_ENABLE_PORT); config2 = cb710_read_port_32(slot, CB710_MMC_CONFIGB_PORT); config1 = cb710_read_port_32(slot, CB710_MMC_CONFIG_PORT); dev_dbg(cb710_slot_dev(slot), "interrupt; status: %08X, " "ie: %08X, c2: %08X, c1: %08X\n", status, irqen, config2, config1); if (status & (CB710_MMC_S1_CARD_CHANGED << 8)) { /* ack the event */ cb710_write_port_8(slot, CB710_MMC_STATUS1_PORT, CB710_MMC_S1_CARD_CHANGED); if ((irqen & CB710_MMC_IE_CISTATUS_MASK) == CB710_MMC_IE_CISTATUS_MASK) mmc_detect_change(mmc, HZ/5); } else { dev_dbg(cb710_slot_dev(slot), "unknown interrupt (test)\n"); spin_lock(&reader->irq_lock); __cb710_mmc_enable_irq(slot, 0, CB710_MMC_IE_TEST_MASK); spin_unlock(&reader->irq_lock); } return 1; } static void cb710_mmc_finish_request_tasklet(unsigned long data) { struct mmc_host *mmc = (void *)data; struct cb710_mmc_reader *reader = mmc_priv(mmc); struct mmc_request *mrq = reader->mrq; reader->mrq = NULL; mmc_request_done(mmc, mrq); } static const struct mmc_host_ops cb710_mmc_host = { .request = cb710_mmc_request, .set_ios = cb710_mmc_set_ios, .get_ro = cb710_mmc_get_ro, .get_cd = cb710_mmc_get_cd, }; #ifdef CONFIG_PM static int cb710_mmc_suspend(struct platform_device *pdev, pm_message_t state) { struct cb710_slot *slot = cb710_pdev_to_slot(pdev); struct mmc_host *mmc = cb710_slot_to_mmc(slot); int err; err = mmc_suspend_host(mmc); if (err) return err; cb710_mmc_enable_irq(slot, 0, ~0); return 0; } static int cb710_mmc_resume(struct platform_device *pdev) { struct cb710_slot *slot = cb710_pdev_to_slot(pdev); struct mmc_host *mmc = cb710_slot_to_mmc(slot); cb710_mmc_enable_irq(slot, 0, ~0); return mmc_resume_host(mmc); } #endif /* CONFIG_PM */ static int __devinit cb710_mmc_init(struct platform_device *pdev) { struct cb710_slot *slot = cb710_pdev_to_slot(pdev); struct cb710_chip *chip = cb710_slot_to_chip(slot); struct mmc_host *mmc; struct cb710_mmc_reader *reader; int err; u32 val; mmc = mmc_alloc_host(sizeof(*reader), cb710_slot_dev(slot)); if (!mmc) return -ENOMEM; dev_set_drvdata(&pdev->dev, mmc); /* harmless (maybe) magic */ pci_read_config_dword(chip->pdev, 0x48, &val); val = cb710_src_freq_mhz[(val >> 16) & 0xF]; dev_dbg(cb710_slot_dev(slot), "source frequency: %dMHz\n", val); val *= 1000000; mmc->ops = &cb710_mmc_host; mmc->f_max = val; mmc->f_min = val >> cb710_clock_divider_log2[CB710_MAX_DIVIDER_IDX]; mmc->ocr_avail = MMC_VDD_32_33|MMC_VDD_33_34; mmc->caps = MMC_CAP_4_BIT_DATA; reader = mmc_priv(mmc); tasklet_init(&reader->finish_req_tasklet, cb710_mmc_finish_request_tasklet, (unsigned long)mmc); spin_lock_init(&reader->irq_lock); cb710_dump_regs(chip, CB710_DUMP_REGS_MMC); cb710_mmc_enable_irq(slot, 0, ~0); cb710_set_irq_handler(slot, cb710_mmc_irq_handler); err = mmc_add_host(mmc); if (unlikely(err)) goto err_free_mmc; dev_dbg(cb710_slot_dev(slot), "mmc_hostname is %s\n", mmc_hostname(mmc)); cb710_mmc_enable_irq(slot, CB710_MMC_IE_CARD_INSERTION_STATUS, 0); return 0; err_free_mmc: dev_dbg(cb710_slot_dev(slot), "mmc_add_host() failed: %d\n", err); cb710_set_irq_handler(slot, NULL); mmc_free_host(mmc); return err; } static int __devexit cb710_mmc_exit(struct platform_device *pdev) { struct cb710_slot *slot = cb710_pdev_to_slot(pdev); struct mmc_host *mmc = cb710_slot_to_mmc(slot); struct cb710_mmc_reader *reader = mmc_priv(mmc); cb710_mmc_enable_irq(slot, 0, CB710_MMC_IE_CARD_INSERTION_STATUS); mmc_remove_host(mmc); /* IRQs should be disabled now, but let's stay on the safe side */ cb710_mmc_enable_irq(slot, 0, ~0); cb710_set_irq_handler(slot, NULL); /* clear config ports - just in case */ cb710_write_port_32(slot, CB710_MMC_CONFIG_PORT, 0); cb710_write_port_16(slot, CB710_MMC_CONFIGB_PORT, 0); tasklet_kill(&reader->finish_req_tasklet); mmc_free_host(mmc); return 0; } static struct platform_driver cb710_mmc_driver = { .driver.name = "cb710-mmc", .probe = cb710_mmc_init, .remove = __devexit_p(cb710_mmc_exit), #ifdef CONFIG_PM .suspend = cb710_mmc_suspend, .resume = cb710_mmc_resume, #endif }; module_platform_driver(cb710_mmc_driver); MODULE_AUTHOR("Michał Mirosław <mirq-linux@rere.qmqm.pl>"); MODULE_DESCRIPTION("ENE CB710 memory card reader driver - MMC/SD part"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:cb710-mmc");
gpl-2.0
yetu/linux-pfla02
drivers/pcmcia/rsrc_iodyn.c
10444
3840
/* * rsrc_iodyn.c -- Resource management routines for MEM-static sockets. * * 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 initial developer of the original code is David A. Hinds * <dahinds@users.sourceforge.net>. Portions created by David A. Hinds * are Copyright (C) 1999 David A. Hinds. All Rights Reserved. * * (C) 1999 David A. Hinds */ #include <linux/slab.h> #include <linux/module.h> #include <linux/kernel.h> #include <pcmcia/ss.h> #include <pcmcia/cistpl.h> #include "cs_internal.h" struct pcmcia_align_data { unsigned long mask; unsigned long offset; }; static resource_size_t pcmcia_align(void *align_data, const struct resource *res, resource_size_t size, resource_size_t align) { struct pcmcia_align_data *data = align_data; resource_size_t start; start = (res->start & ~data->mask) + data->offset; if (start < res->start) start += data->mask + 1; #ifdef CONFIG_X86 if (res->flags & IORESOURCE_IO) { if (start & 0x300) start = (start + 0x3ff) & ~0x3ff; } #endif #ifdef CONFIG_M68K if (res->flags & IORESOURCE_IO) { if ((res->start + size - 1) >= 1024) start = res->end; } #endif return start; } static struct resource *__iodyn_find_io_region(struct pcmcia_socket *s, unsigned long base, int num, unsigned long align) { struct resource *res = pcmcia_make_resource(0, num, IORESOURCE_IO, dev_name(&s->dev)); struct pcmcia_align_data data; unsigned long min = base; int ret; data.mask = align - 1; data.offset = base & data.mask; #ifdef CONFIG_PCI if (s->cb_dev) { ret = pci_bus_alloc_resource(s->cb_dev->bus, res, num, 1, min, 0, pcmcia_align, &data); } else #endif ret = allocate_resource(&ioport_resource, res, num, min, ~0UL, 1, pcmcia_align, &data); if (ret != 0) { kfree(res); res = NULL; } return res; } static int iodyn_find_io(struct pcmcia_socket *s, unsigned int attr, unsigned int *base, unsigned int num, unsigned int align, struct resource **parent) { int i, ret = 0; /* Check for an already-allocated window that must conflict with * what was asked for. It is a hack because it does not catch all * potential conflicts, just the most obvious ones. */ for (i = 0; i < MAX_IO_WIN; i++) { if (!s->io[i].res) continue; if (!*base) continue; if ((s->io[i].res->start & (align-1)) == *base) return -EBUSY; } for (i = 0; i < MAX_IO_WIN; i++) { struct resource *res = s->io[i].res; unsigned int try; if (res && (res->flags & IORESOURCE_BITS) != (attr & IORESOURCE_BITS)) continue; if (!res) { if (align == 0) align = 0x10000; res = s->io[i].res = __iodyn_find_io_region(s, *base, num, align); if (!res) return -EINVAL; *base = res->start; s->io[i].res->flags = ((res->flags & ~IORESOURCE_BITS) | (attr & IORESOURCE_BITS)); s->io[i].InUse = num; *parent = res; return 0; } /* Try to extend top of window */ try = res->end + 1; if ((*base == 0) || (*base == try)) { if (adjust_resource(s->io[i].res, res->start, resource_size(res) + num)) continue; *base = try; s->io[i].InUse += num; *parent = res; return 0; } /* Try to extend bottom of window */ try = res->start - num; if ((*base == 0) || (*base == try)) { if (adjust_resource(s->io[i].res, res->start - num, resource_size(res) + num)) continue; *base = try; s->io[i].InUse += num; *parent = res; return 0; } } return -EINVAL; } struct pccard_resource_ops pccard_iodyn_ops = { .validate_mem = NULL, .find_io = iodyn_find_io, .find_mem = NULL, .init = static_init, .exit = NULL, }; EXPORT_SYMBOL(pccard_iodyn_ops);
gpl-2.0
mlongob/Linux-Kernel-Hack
drivers/base/regmap/regcache-lzo.c
205
8986
/* * Register cache access API - LZO caching support * * Copyright 2011 Wolfson Microelectronics plc * * Author: Dimitris Papastamos <dp@opensource.wolfsonmicro.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/slab.h> #include <linux/lzo.h> #include "internal.h" static int regcache_lzo_exit(struct regmap *map); struct regcache_lzo_ctx { void *wmem; void *dst; const void *src; size_t src_len; size_t dst_len; size_t decompressed_size; unsigned long *sync_bmp; int sync_bmp_nbits; }; #define LZO_BLOCK_NUM 8 static int regcache_lzo_block_count(struct regmap *map) { return LZO_BLOCK_NUM; } static int regcache_lzo_prepare(struct regcache_lzo_ctx *lzo_ctx) { lzo_ctx->wmem = kmalloc(LZO1X_MEM_COMPRESS, GFP_KERNEL); if (!lzo_ctx->wmem) return -ENOMEM; return 0; } static int regcache_lzo_compress(struct regcache_lzo_ctx *lzo_ctx) { size_t compress_size; int ret; ret = lzo1x_1_compress(lzo_ctx->src, lzo_ctx->src_len, lzo_ctx->dst, &compress_size, lzo_ctx->wmem); if (ret != LZO_E_OK || compress_size > lzo_ctx->dst_len) return -EINVAL; lzo_ctx->dst_len = compress_size; return 0; } static int regcache_lzo_decompress(struct regcache_lzo_ctx *lzo_ctx) { size_t dst_len; int ret; dst_len = lzo_ctx->dst_len; ret = lzo1x_decompress_safe(lzo_ctx->src, lzo_ctx->src_len, lzo_ctx->dst, &dst_len); if (ret != LZO_E_OK || dst_len != lzo_ctx->dst_len) return -EINVAL; return 0; } static int regcache_lzo_compress_cache_block(struct regmap *map, struct regcache_lzo_ctx *lzo_ctx) { int ret; lzo_ctx->dst_len = lzo1x_worst_compress(PAGE_SIZE); lzo_ctx->dst = kmalloc(lzo_ctx->dst_len, GFP_KERNEL); if (!lzo_ctx->dst) { lzo_ctx->dst_len = 0; return -ENOMEM; } ret = regcache_lzo_compress(lzo_ctx); if (ret < 0) return ret; return 0; } static int regcache_lzo_decompress_cache_block(struct regmap *map, struct regcache_lzo_ctx *lzo_ctx) { int ret; lzo_ctx->dst_len = lzo_ctx->decompressed_size; lzo_ctx->dst = kmalloc(lzo_ctx->dst_len, GFP_KERNEL); if (!lzo_ctx->dst) { lzo_ctx->dst_len = 0; return -ENOMEM; } ret = regcache_lzo_decompress(lzo_ctx); if (ret < 0) return ret; return 0; } static inline int regcache_lzo_get_blkindex(struct regmap *map, unsigned int reg) { return (reg * map->cache_word_size) / DIV_ROUND_UP(map->cache_size_raw, regcache_lzo_block_count(map)); } static inline int regcache_lzo_get_blkpos(struct regmap *map, unsigned int reg) { return reg % (DIV_ROUND_UP(map->cache_size_raw, regcache_lzo_block_count(map)) / map->cache_word_size); } static inline int regcache_lzo_get_blksize(struct regmap *map) { return DIV_ROUND_UP(map->cache_size_raw, regcache_lzo_block_count(map)); } static int regcache_lzo_init(struct regmap *map) { struct regcache_lzo_ctx **lzo_blocks; size_t bmp_size; int ret, i, blksize, blkcount; const char *p, *end; unsigned long *sync_bmp; ret = 0; blkcount = regcache_lzo_block_count(map); map->cache = kzalloc(blkcount * sizeof *lzo_blocks, GFP_KERNEL); if (!map->cache) return -ENOMEM; lzo_blocks = map->cache; /* * allocate a bitmap to be used when syncing the cache with * the hardware. Each time a register is modified, the corresponding * bit is set in the bitmap, so we know that we have to sync * that register. */ bmp_size = map->num_reg_defaults_raw; sync_bmp = kmalloc(BITS_TO_LONGS(bmp_size) * sizeof(long), GFP_KERNEL); if (!sync_bmp) { ret = -ENOMEM; goto err; } bitmap_zero(sync_bmp, bmp_size); /* allocate the lzo blocks and initialize them */ for (i = 0; i < blkcount; i++) { lzo_blocks[i] = kzalloc(sizeof **lzo_blocks, GFP_KERNEL); if (!lzo_blocks[i]) { kfree(sync_bmp); ret = -ENOMEM; goto err; } lzo_blocks[i]->sync_bmp = sync_bmp; lzo_blocks[i]->sync_bmp_nbits = bmp_size; /* alloc the working space for the compressed block */ ret = regcache_lzo_prepare(lzo_blocks[i]); if (ret < 0) goto err; } blksize = regcache_lzo_get_blksize(map); p = map->reg_defaults_raw; end = map->reg_defaults_raw + map->cache_size_raw; /* compress the register map and fill the lzo blocks */ for (i = 0; i < blkcount; i++, p += blksize) { lzo_blocks[i]->src = p; if (p + blksize > end) lzo_blocks[i]->src_len = end - p; else lzo_blocks[i]->src_len = blksize; ret = regcache_lzo_compress_cache_block(map, lzo_blocks[i]); if (ret < 0) goto err; lzo_blocks[i]->decompressed_size = lzo_blocks[i]->src_len; } return 0; err: regcache_lzo_exit(map); return ret; } static int regcache_lzo_exit(struct regmap *map) { struct regcache_lzo_ctx **lzo_blocks; int i, blkcount; lzo_blocks = map->cache; if (!lzo_blocks) return 0; blkcount = regcache_lzo_block_count(map); /* * the pointer to the bitmap used for syncing the cache * is shared amongst all lzo_blocks. Ensure it is freed * only once. */ if (lzo_blocks[0]) kfree(lzo_blocks[0]->sync_bmp); for (i = 0; i < blkcount; i++) { if (lzo_blocks[i]) { kfree(lzo_blocks[i]->wmem); kfree(lzo_blocks[i]->dst); } /* each lzo_block is a pointer returned by kmalloc or NULL */ kfree(lzo_blocks[i]); } kfree(lzo_blocks); map->cache = NULL; return 0; } static int regcache_lzo_read(struct regmap *map, unsigned int reg, unsigned int *value) { struct regcache_lzo_ctx *lzo_block, **lzo_blocks; int ret, blkindex, blkpos; size_t blksize, tmp_dst_len; void *tmp_dst; /* index of the compressed lzo block */ blkindex = regcache_lzo_get_blkindex(map, reg); /* register index within the decompressed block */ blkpos = regcache_lzo_get_blkpos(map, reg); /* size of the compressed block */ blksize = regcache_lzo_get_blksize(map); lzo_blocks = map->cache; lzo_block = lzo_blocks[blkindex]; /* save the pointer and length of the compressed block */ tmp_dst = lzo_block->dst; tmp_dst_len = lzo_block->dst_len; /* prepare the source to be the compressed block */ lzo_block->src = lzo_block->dst; lzo_block->src_len = lzo_block->dst_len; /* decompress the block */ ret = regcache_lzo_decompress_cache_block(map, lzo_block); if (ret >= 0) /* fetch the value from the cache */ *value = regcache_get_val(lzo_block->dst, blkpos, map->cache_word_size); kfree(lzo_block->dst); /* restore the pointer and length of the compressed block */ lzo_block->dst = tmp_dst; lzo_block->dst_len = tmp_dst_len; return ret; } static int regcache_lzo_write(struct regmap *map, unsigned int reg, unsigned int value) { struct regcache_lzo_ctx *lzo_block, **lzo_blocks; int ret, blkindex, blkpos; size_t blksize, tmp_dst_len; void *tmp_dst; /* index of the compressed lzo block */ blkindex = regcache_lzo_get_blkindex(map, reg); /* register index within the decompressed block */ blkpos = regcache_lzo_get_blkpos(map, reg); /* size of the compressed block */ blksize = regcache_lzo_get_blksize(map); lzo_blocks = map->cache; lzo_block = lzo_blocks[blkindex]; /* save the pointer and length of the compressed block */ tmp_dst = lzo_block->dst; tmp_dst_len = lzo_block->dst_len; /* prepare the source to be the compressed block */ lzo_block->src = lzo_block->dst; lzo_block->src_len = lzo_block->dst_len; /* decompress the block */ ret = regcache_lzo_decompress_cache_block(map, lzo_block); if (ret < 0) { kfree(lzo_block->dst); goto out; } /* write the new value to the cache */ if (regcache_set_val(lzo_block->dst, blkpos, value, map->cache_word_size)) { kfree(lzo_block->dst); goto out; } /* prepare the source to be the decompressed block */ lzo_block->src = lzo_block->dst; lzo_block->src_len = lzo_block->dst_len; /* compress the block */ ret = regcache_lzo_compress_cache_block(map, lzo_block); if (ret < 0) { kfree(lzo_block->dst); kfree(lzo_block->src); goto out; } /* set the bit so we know we have to sync this register */ set_bit(reg, lzo_block->sync_bmp); kfree(tmp_dst); kfree(lzo_block->src); return 0; out: lzo_block->dst = tmp_dst; lzo_block->dst_len = tmp_dst_len; return ret; } static int regcache_lzo_sync(struct regmap *map) { struct regcache_lzo_ctx **lzo_blocks; unsigned int val; int i; int ret; lzo_blocks = map->cache; for_each_set_bit(i, lzo_blocks[0]->sync_bmp, lzo_blocks[0]->sync_bmp_nbits) { ret = regcache_read(map, i, &val); if (ret) return ret; map->cache_bypass = 1; ret = _regmap_write(map, i, val); map->cache_bypass = 0; if (ret) return ret; dev_dbg(map->dev, "Synced register %#x, value %#x\n", i, val); } return 0; } struct regcache_ops regcache_lzo_ops = { .type = REGCACHE_COMPRESSED, .name = "lzo", .init = regcache_lzo_init, .exit = regcache_lzo_exit, .read = regcache_lzo_read, .write = regcache_lzo_write, .sync = regcache_lzo_sync };
gpl-2.0
tom--pollard/linux-raspberrypi_4.1
drivers/scsi/libiscsi.c
461
99531
/* * iSCSI lib functions * * Copyright (C) 2006 Red Hat, Inc. All rights reserved. * Copyright (C) 2004 - 2006 Mike Christie * Copyright (C) 2004 - 2005 Dmitry Yusupov * Copyright (C) 2004 - 2005 Alex Aizman * maintained by open-iscsi@googlegroups.com * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <linux/types.h> #include <linux/kfifo.h> #include <linux/delay.h> #include <linux/log2.h> #include <linux/slab.h> #include <linux/module.h> #include <asm/unaligned.h> #include <net/tcp.h> #include <scsi/scsi_cmnd.h> #include <scsi/scsi_device.h> #include <scsi/scsi_eh.h> #include <scsi/scsi_tcq.h> #include <scsi/scsi_host.h> #include <scsi/scsi.h> #include <scsi/iscsi_proto.h> #include <scsi/scsi_transport.h> #include <scsi/scsi_transport_iscsi.h> #include <scsi/libiscsi.h> static int iscsi_dbg_lib_conn; module_param_named(debug_libiscsi_conn, iscsi_dbg_lib_conn, int, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(debug_libiscsi_conn, "Turn on debugging for connections in libiscsi module. " "Set to 1 to turn on, and zero to turn off. Default is off."); static int iscsi_dbg_lib_session; module_param_named(debug_libiscsi_session, iscsi_dbg_lib_session, int, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(debug_libiscsi_session, "Turn on debugging for sessions in libiscsi module. " "Set to 1 to turn on, and zero to turn off. Default is off."); static int iscsi_dbg_lib_eh; module_param_named(debug_libiscsi_eh, iscsi_dbg_lib_eh, int, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(debug_libiscsi_eh, "Turn on debugging for error handling in libiscsi module. " "Set to 1 to turn on, and zero to turn off. Default is off."); #define ISCSI_DBG_CONN(_conn, dbg_fmt, arg...) \ do { \ if (iscsi_dbg_lib_conn) \ iscsi_conn_printk(KERN_INFO, _conn, \ "%s " dbg_fmt, \ __func__, ##arg); \ } while (0); #define ISCSI_DBG_SESSION(_session, dbg_fmt, arg...) \ do { \ if (iscsi_dbg_lib_session) \ iscsi_session_printk(KERN_INFO, _session, \ "%s " dbg_fmt, \ __func__, ##arg); \ } while (0); #define ISCSI_DBG_EH(_session, dbg_fmt, arg...) \ do { \ if (iscsi_dbg_lib_eh) \ iscsi_session_printk(KERN_INFO, _session, \ "%s " dbg_fmt, \ __func__, ##arg); \ } while (0); inline void iscsi_conn_queue_work(struct iscsi_conn *conn) { struct Scsi_Host *shost = conn->session->host; struct iscsi_host *ihost = shost_priv(shost); if (ihost->workq) queue_work(ihost->workq, &conn->xmitwork); } EXPORT_SYMBOL_GPL(iscsi_conn_queue_work); static void __iscsi_update_cmdsn(struct iscsi_session *session, uint32_t exp_cmdsn, uint32_t max_cmdsn) { /* * standard specifies this check for when to update expected and * max sequence numbers */ if (iscsi_sna_lt(max_cmdsn, exp_cmdsn - 1)) return; if (exp_cmdsn != session->exp_cmdsn && !iscsi_sna_lt(exp_cmdsn, session->exp_cmdsn)) session->exp_cmdsn = exp_cmdsn; if (max_cmdsn != session->max_cmdsn && !iscsi_sna_lt(max_cmdsn, session->max_cmdsn)) session->max_cmdsn = max_cmdsn; } void iscsi_update_cmdsn(struct iscsi_session *session, struct iscsi_nopin *hdr) { __iscsi_update_cmdsn(session, be32_to_cpu(hdr->exp_cmdsn), be32_to_cpu(hdr->max_cmdsn)); } EXPORT_SYMBOL_GPL(iscsi_update_cmdsn); /** * iscsi_prep_data_out_pdu - initialize Data-Out * @task: scsi command task * @r2t: R2T info * @hdr: iscsi data in pdu * * Notes: * Initialize Data-Out within this R2T sequence and finds * proper data_offset within this SCSI command. * * This function is called with connection lock taken. **/ void iscsi_prep_data_out_pdu(struct iscsi_task *task, struct iscsi_r2t_info *r2t, struct iscsi_data *hdr) { struct iscsi_conn *conn = task->conn; unsigned int left = r2t->data_length - r2t->sent; task->hdr_len = sizeof(struct iscsi_data); memset(hdr, 0, sizeof(struct iscsi_data)); hdr->ttt = r2t->ttt; hdr->datasn = cpu_to_be32(r2t->datasn); r2t->datasn++; hdr->opcode = ISCSI_OP_SCSI_DATA_OUT; hdr->lun = task->lun; hdr->itt = task->hdr_itt; hdr->exp_statsn = r2t->exp_statsn; hdr->offset = cpu_to_be32(r2t->data_offset + r2t->sent); if (left > conn->max_xmit_dlength) { hton24(hdr->dlength, conn->max_xmit_dlength); r2t->data_count = conn->max_xmit_dlength; hdr->flags = 0; } else { hton24(hdr->dlength, left); r2t->data_count = left; hdr->flags = ISCSI_FLAG_CMD_FINAL; } conn->dataout_pdus_cnt++; } EXPORT_SYMBOL_GPL(iscsi_prep_data_out_pdu); static int iscsi_add_hdr(struct iscsi_task *task, unsigned len) { unsigned exp_len = task->hdr_len + len; if (exp_len > task->hdr_max) { WARN_ON(1); return -EINVAL; } WARN_ON(len & (ISCSI_PAD_LEN - 1)); /* caller must pad the AHS */ task->hdr_len = exp_len; return 0; } /* * make an extended cdb AHS */ static int iscsi_prep_ecdb_ahs(struct iscsi_task *task) { struct scsi_cmnd *cmd = task->sc; unsigned rlen, pad_len; unsigned short ahslength; struct iscsi_ecdb_ahdr *ecdb_ahdr; int rc; ecdb_ahdr = iscsi_next_hdr(task); rlen = cmd->cmd_len - ISCSI_CDB_SIZE; BUG_ON(rlen > sizeof(ecdb_ahdr->ecdb)); ahslength = rlen + sizeof(ecdb_ahdr->reserved); pad_len = iscsi_padding(rlen); rc = iscsi_add_hdr(task, sizeof(ecdb_ahdr->ahslength) + sizeof(ecdb_ahdr->ahstype) + ahslength + pad_len); if (rc) return rc; if (pad_len) memset(&ecdb_ahdr->ecdb[rlen], 0, pad_len); ecdb_ahdr->ahslength = cpu_to_be16(ahslength); ecdb_ahdr->ahstype = ISCSI_AHSTYPE_CDB; ecdb_ahdr->reserved = 0; memcpy(ecdb_ahdr->ecdb, cmd->cmnd + ISCSI_CDB_SIZE, rlen); ISCSI_DBG_SESSION(task->conn->session, "iscsi_prep_ecdb_ahs: varlen_cdb_len %d " "rlen %d pad_len %d ahs_length %d iscsi_headers_size " "%u\n", cmd->cmd_len, rlen, pad_len, ahslength, task->hdr_len); return 0; } static int iscsi_prep_bidi_ahs(struct iscsi_task *task) { struct scsi_cmnd *sc = task->sc; struct iscsi_rlength_ahdr *rlen_ahdr; int rc; rlen_ahdr = iscsi_next_hdr(task); rc = iscsi_add_hdr(task, sizeof(*rlen_ahdr)); if (rc) return rc; rlen_ahdr->ahslength = cpu_to_be16(sizeof(rlen_ahdr->read_length) + sizeof(rlen_ahdr->reserved)); rlen_ahdr->ahstype = ISCSI_AHSTYPE_RLENGTH; rlen_ahdr->reserved = 0; rlen_ahdr->read_length = cpu_to_be32(scsi_in(sc)->length); ISCSI_DBG_SESSION(task->conn->session, "bidi-in rlen_ahdr->read_length(%d) " "rlen_ahdr->ahslength(%d)\n", be32_to_cpu(rlen_ahdr->read_length), be16_to_cpu(rlen_ahdr->ahslength)); return 0; } /** * iscsi_check_tmf_restrictions - check if a task is affected by TMF * @task: iscsi task * @opcode: opcode to check for * * During TMF a task has to be checked if it's affected. * All unrelated I/O can be passed through, but I/O to the * affected LUN should be restricted. * If 'fast_abort' is set we won't be sending any I/O to the * affected LUN. * Otherwise the target is waiting for all TTTs to be completed, * so we have to send all outstanding Data-Out PDUs to the target. */ static int iscsi_check_tmf_restrictions(struct iscsi_task *task, int opcode) { struct iscsi_conn *conn = task->conn; struct iscsi_tm *tmf = &conn->tmhdr; u64 hdr_lun; if (conn->tmf_state == TMF_INITIAL) return 0; if ((tmf->opcode & ISCSI_OPCODE_MASK) != ISCSI_OP_SCSI_TMFUNC) return 0; switch (ISCSI_TM_FUNC_VALUE(tmf)) { case ISCSI_TM_FUNC_LOGICAL_UNIT_RESET: /* * Allow PDUs for unrelated LUNs */ hdr_lun = scsilun_to_int(&tmf->lun); if (hdr_lun != task->sc->device->lun) return 0; /* fall through */ case ISCSI_TM_FUNC_TARGET_WARM_RESET: /* * Fail all SCSI cmd PDUs */ if (opcode != ISCSI_OP_SCSI_DATA_OUT) { iscsi_conn_printk(KERN_INFO, conn, "task [op %x/%x itt " "0x%x/0x%x] " "rejected.\n", task->hdr->opcode, opcode, task->itt, task->hdr_itt); return -EACCES; } /* * And also all data-out PDUs in response to R2T * if fast_abort is set. */ if (conn->session->fast_abort) { iscsi_conn_printk(KERN_INFO, conn, "task [op %x/%x itt " "0x%x/0x%x] fast abort.\n", task->hdr->opcode, opcode, task->itt, task->hdr_itt); return -EACCES; } break; case ISCSI_TM_FUNC_ABORT_TASK: /* * the caller has already checked if the task * they want to abort was in the pending queue so if * we are here the cmd pdu has gone out already, and * we will only hit this for data-outs */ if (opcode == ISCSI_OP_SCSI_DATA_OUT && task->hdr_itt == tmf->rtt) { ISCSI_DBG_SESSION(conn->session, "Preventing task %x/%x from sending " "data-out due to abort task in " "progress\n", task->itt, task->hdr_itt); return -EACCES; } break; } return 0; } /** * iscsi_prep_scsi_cmd_pdu - prep iscsi scsi cmd pdu * @task: iscsi task * * Prep basic iSCSI PDU fields for a scsi cmd pdu. The LLD should set * fields like dlength or final based on how much data it sends */ static int iscsi_prep_scsi_cmd_pdu(struct iscsi_task *task) { struct iscsi_conn *conn = task->conn; struct iscsi_session *session = conn->session; struct scsi_cmnd *sc = task->sc; struct iscsi_scsi_req *hdr; unsigned hdrlength, cmd_len, transfer_length; itt_t itt; int rc; rc = iscsi_check_tmf_restrictions(task, ISCSI_OP_SCSI_CMD); if (rc) return rc; if (conn->session->tt->alloc_pdu) { rc = conn->session->tt->alloc_pdu(task, ISCSI_OP_SCSI_CMD); if (rc) return rc; } hdr = (struct iscsi_scsi_req *)task->hdr; itt = hdr->itt; memset(hdr, 0, sizeof(*hdr)); if (session->tt->parse_pdu_itt) hdr->itt = task->hdr_itt = itt; else hdr->itt = task->hdr_itt = build_itt(task->itt, task->conn->session->age); task->hdr_len = 0; rc = iscsi_add_hdr(task, sizeof(*hdr)); if (rc) return rc; hdr->opcode = ISCSI_OP_SCSI_CMD; hdr->flags = ISCSI_ATTR_SIMPLE; int_to_scsilun(sc->device->lun, &hdr->lun); task->lun = hdr->lun; hdr->exp_statsn = cpu_to_be32(conn->exp_statsn); cmd_len = sc->cmd_len; if (cmd_len < ISCSI_CDB_SIZE) memset(&hdr->cdb[cmd_len], 0, ISCSI_CDB_SIZE - cmd_len); else if (cmd_len > ISCSI_CDB_SIZE) { rc = iscsi_prep_ecdb_ahs(task); if (rc) return rc; cmd_len = ISCSI_CDB_SIZE; } memcpy(hdr->cdb, sc->cmnd, cmd_len); task->imm_count = 0; if (scsi_bidi_cmnd(sc)) { hdr->flags |= ISCSI_FLAG_CMD_READ; rc = iscsi_prep_bidi_ahs(task); if (rc) return rc; } if (scsi_get_prot_op(sc) != SCSI_PROT_NORMAL) task->protected = true; transfer_length = scsi_transfer_length(sc); hdr->data_length = cpu_to_be32(transfer_length); if (sc->sc_data_direction == DMA_TO_DEVICE) { struct iscsi_r2t_info *r2t = &task->unsol_r2t; hdr->flags |= ISCSI_FLAG_CMD_WRITE; /* * Write counters: * * imm_count bytes to be sent right after * SCSI PDU Header * * unsol_count bytes(as Data-Out) to be sent * without R2T ack right after * immediate data * * r2t data_length bytes to be sent via R2T ack's * * pad_count bytes to be sent as zero-padding */ memset(r2t, 0, sizeof(*r2t)); if (session->imm_data_en) { if (transfer_length >= session->first_burst) task->imm_count = min(session->first_burst, conn->max_xmit_dlength); else task->imm_count = min(transfer_length, conn->max_xmit_dlength); hton24(hdr->dlength, task->imm_count); } else zero_data(hdr->dlength); if (!session->initial_r2t_en) { r2t->data_length = min(session->first_burst, transfer_length) - task->imm_count; r2t->data_offset = task->imm_count; r2t->ttt = cpu_to_be32(ISCSI_RESERVED_TAG); r2t->exp_statsn = cpu_to_be32(conn->exp_statsn); } if (!task->unsol_r2t.data_length) /* No unsolicit Data-Out's */ hdr->flags |= ISCSI_FLAG_CMD_FINAL; } else { hdr->flags |= ISCSI_FLAG_CMD_FINAL; zero_data(hdr->dlength); if (sc->sc_data_direction == DMA_FROM_DEVICE) hdr->flags |= ISCSI_FLAG_CMD_READ; } /* calculate size of additional header segments (AHSs) */ hdrlength = task->hdr_len - sizeof(*hdr); WARN_ON(hdrlength & (ISCSI_PAD_LEN-1)); hdrlength /= ISCSI_PAD_LEN; WARN_ON(hdrlength >= 256); hdr->hlength = hdrlength & 0xFF; hdr->cmdsn = task->cmdsn = cpu_to_be32(session->cmdsn); if (session->tt->init_task && session->tt->init_task(task)) return -EIO; task->state = ISCSI_TASK_RUNNING; session->cmdsn++; conn->scsicmd_pdus_cnt++; ISCSI_DBG_SESSION(session, "iscsi prep [%s cid %d sc %p cdb 0x%x " "itt 0x%x len %d bidi_len %d cmdsn %d win %d]\n", scsi_bidi_cmnd(sc) ? "bidirectional" : sc->sc_data_direction == DMA_TO_DEVICE ? "write" : "read", conn->id, sc, sc->cmnd[0], task->itt, transfer_length, scsi_bidi_cmnd(sc) ? scsi_in(sc)->length : 0, session->cmdsn, session->max_cmdsn - session->exp_cmdsn + 1); return 0; } /** * iscsi_free_task - free a task * @task: iscsi cmd task * * Must be called with session back_lock. * This function returns the scsi command to scsi-ml or cleans * up mgmt tasks then returns the task to the pool. */ static void iscsi_free_task(struct iscsi_task *task) { struct iscsi_conn *conn = task->conn; struct iscsi_session *session = conn->session; struct scsi_cmnd *sc = task->sc; int oldstate = task->state; ISCSI_DBG_SESSION(session, "freeing task itt 0x%x state %d sc %p\n", task->itt, task->state, task->sc); session->tt->cleanup_task(task); task->state = ISCSI_TASK_FREE; task->sc = NULL; /* * login task is preallocated so do not free */ if (conn->login_task == task) return; kfifo_in(&session->cmdpool.queue, (void*)&task, sizeof(void*)); if (sc) { /* SCSI eh reuses commands to verify us */ sc->SCp.ptr = NULL; /* * queue command may call this to free the task, so * it will decide how to return sc to scsi-ml. */ if (oldstate != ISCSI_TASK_REQUEUE_SCSIQ) sc->scsi_done(sc); } } void __iscsi_get_task(struct iscsi_task *task) { atomic_inc(&task->refcount); } EXPORT_SYMBOL_GPL(__iscsi_get_task); void __iscsi_put_task(struct iscsi_task *task) { if (atomic_dec_and_test(&task->refcount)) iscsi_free_task(task); } EXPORT_SYMBOL_GPL(__iscsi_put_task); void iscsi_put_task(struct iscsi_task *task) { struct iscsi_session *session = task->conn->session; /* regular RX path uses back_lock */ spin_lock_bh(&session->back_lock); __iscsi_put_task(task); spin_unlock_bh(&session->back_lock); } EXPORT_SYMBOL_GPL(iscsi_put_task); /** * iscsi_complete_task - finish a task * @task: iscsi cmd task * @state: state to complete task with * * Must be called with session back_lock. */ static void iscsi_complete_task(struct iscsi_task *task, int state) { struct iscsi_conn *conn = task->conn; ISCSI_DBG_SESSION(conn->session, "complete task itt 0x%x state %d sc %p\n", task->itt, task->state, task->sc); if (task->state == ISCSI_TASK_COMPLETED || task->state == ISCSI_TASK_ABRT_TMF || task->state == ISCSI_TASK_ABRT_SESS_RECOV || task->state == ISCSI_TASK_REQUEUE_SCSIQ) return; WARN_ON_ONCE(task->state == ISCSI_TASK_FREE); task->state = state; if (!list_empty(&task->running)) list_del_init(&task->running); if (conn->task == task) conn->task = NULL; if (conn->ping_task == task) conn->ping_task = NULL; /* release get from queueing */ __iscsi_put_task(task); } /** * iscsi_complete_scsi_task - finish scsi task normally * @task: iscsi task for scsi cmd * @exp_cmdsn: expected cmd sn in cpu format * @max_cmdsn: max cmd sn in cpu format * * This is used when drivers do not need or cannot perform * lower level pdu processing. * * Called with session back_lock */ void iscsi_complete_scsi_task(struct iscsi_task *task, uint32_t exp_cmdsn, uint32_t max_cmdsn) { struct iscsi_conn *conn = task->conn; ISCSI_DBG_SESSION(conn->session, "[itt 0x%x]\n", task->itt); conn->last_recv = jiffies; __iscsi_update_cmdsn(conn->session, exp_cmdsn, max_cmdsn); iscsi_complete_task(task, ISCSI_TASK_COMPLETED); } EXPORT_SYMBOL_GPL(iscsi_complete_scsi_task); /* * session back_lock must be held and if not called for a task that is * still pending or from the xmit thread, then xmit thread must * be suspended. */ static void fail_scsi_task(struct iscsi_task *task, int err) { struct iscsi_conn *conn = task->conn; struct scsi_cmnd *sc; int state; /* * if a command completes and we get a successful tmf response * we will hit this because the scsi eh abort code does not take * a ref to the task. */ sc = task->sc; if (!sc) return; if (task->state == ISCSI_TASK_PENDING) { /* * cmd never made it to the xmit thread, so we should not count * the cmd in the sequencing */ conn->session->queued_cmdsn--; /* it was never sent so just complete like normal */ state = ISCSI_TASK_COMPLETED; } else if (err == DID_TRANSPORT_DISRUPTED) state = ISCSI_TASK_ABRT_SESS_RECOV; else state = ISCSI_TASK_ABRT_TMF; sc->result = err << 16; if (!scsi_bidi_cmnd(sc)) scsi_set_resid(sc, scsi_bufflen(sc)); else { scsi_out(sc)->resid = scsi_out(sc)->length; scsi_in(sc)->resid = scsi_in(sc)->length; } /* regular RX path uses back_lock */ spin_lock_bh(&conn->session->back_lock); iscsi_complete_task(task, state); spin_unlock_bh(&conn->session->back_lock); } static int iscsi_prep_mgmt_task(struct iscsi_conn *conn, struct iscsi_task *task) { struct iscsi_session *session = conn->session; struct iscsi_hdr *hdr = task->hdr; struct iscsi_nopout *nop = (struct iscsi_nopout *)hdr; uint8_t opcode = hdr->opcode & ISCSI_OPCODE_MASK; if (conn->session->state == ISCSI_STATE_LOGGING_OUT) return -ENOTCONN; if (opcode != ISCSI_OP_LOGIN && opcode != ISCSI_OP_TEXT) nop->exp_statsn = cpu_to_be32(conn->exp_statsn); /* * pre-format CmdSN for outgoing PDU. */ nop->cmdsn = cpu_to_be32(session->cmdsn); if (hdr->itt != RESERVED_ITT) { /* * TODO: We always use immediate for normal session pdus. * If we start to send tmfs or nops as non-immediate then * we should start checking the cmdsn numbers for mgmt tasks. * * During discovery sessions iscsid sends TEXT as non immediate, * but we always only send one PDU at a time. */ if (conn->c_stage == ISCSI_CONN_STARTED && !(hdr->opcode & ISCSI_OP_IMMEDIATE)) { session->queued_cmdsn++; session->cmdsn++; } } if (session->tt->init_task && session->tt->init_task(task)) return -EIO; if ((hdr->opcode & ISCSI_OPCODE_MASK) == ISCSI_OP_LOGOUT) session->state = ISCSI_STATE_LOGGING_OUT; task->state = ISCSI_TASK_RUNNING; ISCSI_DBG_SESSION(session, "mgmtpdu [op 0x%x hdr->itt 0x%x " "datalen %d]\n", hdr->opcode & ISCSI_OPCODE_MASK, hdr->itt, task->data_count); return 0; } static struct iscsi_task * __iscsi_conn_send_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr, char *data, uint32_t data_size) { struct iscsi_session *session = conn->session; struct iscsi_host *ihost = shost_priv(session->host); uint8_t opcode = hdr->opcode & ISCSI_OPCODE_MASK; struct iscsi_task *task; itt_t itt; if (session->state == ISCSI_STATE_TERMINATE) return NULL; if (opcode == ISCSI_OP_LOGIN || opcode == ISCSI_OP_TEXT) { /* * Login and Text are sent serially, in * request-followed-by-response sequence. * Same task can be used. Same ITT must be used. * Note that login_task is preallocated at conn_create(). */ if (conn->login_task->state != ISCSI_TASK_FREE) { iscsi_conn_printk(KERN_ERR, conn, "Login/Text in " "progress. Cannot start new task.\n"); return NULL; } if (data_size > ISCSI_DEF_MAX_RECV_SEG_LEN) { iscsi_conn_printk(KERN_ERR, conn, "Invalid buffer len of %u for login task. Max len is %u\n", data_size, ISCSI_DEF_MAX_RECV_SEG_LEN); return NULL; } task = conn->login_task; } else { if (session->state != ISCSI_STATE_LOGGED_IN) return NULL; if (data_size != 0) { iscsi_conn_printk(KERN_ERR, conn, "Can not send data buffer of len %u for op 0x%x\n", data_size, opcode); return NULL; } BUG_ON(conn->c_stage == ISCSI_CONN_INITIAL_STAGE); BUG_ON(conn->c_stage == ISCSI_CONN_STOPPED); if (!kfifo_out(&session->cmdpool.queue, (void*)&task, sizeof(void*))) return NULL; } /* * released in complete pdu for task we expect a response for, and * released by the lld when it has transmitted the task for * pdus we do not expect a response for. */ atomic_set(&task->refcount, 1); task->conn = conn; task->sc = NULL; INIT_LIST_HEAD(&task->running); task->state = ISCSI_TASK_PENDING; if (data_size) { memcpy(task->data, data, data_size); task->data_count = data_size; } else task->data_count = 0; if (conn->session->tt->alloc_pdu) { if (conn->session->tt->alloc_pdu(task, hdr->opcode)) { iscsi_conn_printk(KERN_ERR, conn, "Could not allocate " "pdu for mgmt task.\n"); goto free_task; } } itt = task->hdr->itt; task->hdr_len = sizeof(struct iscsi_hdr); memcpy(task->hdr, hdr, sizeof(struct iscsi_hdr)); if (hdr->itt != RESERVED_ITT) { if (session->tt->parse_pdu_itt) task->hdr->itt = itt; else task->hdr->itt = build_itt(task->itt, task->conn->session->age); } if (!ihost->workq) { if (iscsi_prep_mgmt_task(conn, task)) goto free_task; if (session->tt->xmit_task(task)) goto free_task; } else { list_add_tail(&task->running, &conn->mgmtqueue); iscsi_conn_queue_work(conn); } return task; free_task: /* regular RX path uses back_lock */ spin_lock_bh(&session->back_lock); __iscsi_put_task(task); spin_unlock_bh(&session->back_lock); return NULL; } int iscsi_conn_send_pdu(struct iscsi_cls_conn *cls_conn, struct iscsi_hdr *hdr, char *data, uint32_t data_size) { struct iscsi_conn *conn = cls_conn->dd_data; struct iscsi_session *session = conn->session; int err = 0; spin_lock_bh(&session->frwd_lock); if (!__iscsi_conn_send_pdu(conn, hdr, data, data_size)) err = -EPERM; spin_unlock_bh(&session->frwd_lock); return err; } EXPORT_SYMBOL_GPL(iscsi_conn_send_pdu); /** * iscsi_cmd_rsp - SCSI Command Response processing * @conn: iscsi connection * @hdr: iscsi header * @task: scsi command task * @data: cmd data buffer * @datalen: len of buffer * * iscsi_cmd_rsp sets up the scsi_cmnd fields based on the PDU and * then completes the command and task. **/ static void iscsi_scsi_cmd_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr, struct iscsi_task *task, char *data, int datalen) { struct iscsi_scsi_rsp *rhdr = (struct iscsi_scsi_rsp *)hdr; struct iscsi_session *session = conn->session; struct scsi_cmnd *sc = task->sc; iscsi_update_cmdsn(session, (struct iscsi_nopin*)rhdr); conn->exp_statsn = be32_to_cpu(rhdr->statsn) + 1; sc->result = (DID_OK << 16) | rhdr->cmd_status; if (task->protected) { sector_t sector; u8 ascq; /** * Transports that didn't implement check_protection * callback but still published T10-PI support to scsi-mid * deserve this BUG_ON. **/ BUG_ON(!session->tt->check_protection); ascq = session->tt->check_protection(task, &sector); if (ascq) { sc->result = DRIVER_SENSE << 24 | SAM_STAT_CHECK_CONDITION; scsi_build_sense_buffer(1, sc->sense_buffer, ILLEGAL_REQUEST, 0x10, ascq); sc->sense_buffer[7] = 0xc; /* Additional sense length */ sc->sense_buffer[8] = 0; /* Information desc type */ sc->sense_buffer[9] = 0xa; /* Additional desc length */ sc->sense_buffer[10] = 0x80; /* Validity bit */ put_unaligned_be64(sector, &sc->sense_buffer[12]); goto out; } } if (rhdr->response != ISCSI_STATUS_CMD_COMPLETED) { sc->result = DID_ERROR << 16; goto out; } if (rhdr->cmd_status == SAM_STAT_CHECK_CONDITION) { uint16_t senselen; if (datalen < 2) { invalid_datalen: iscsi_conn_printk(KERN_ERR, conn, "Got CHECK_CONDITION but invalid data " "buffer size of %d\n", datalen); sc->result = DID_BAD_TARGET << 16; goto out; } senselen = get_unaligned_be16(data); if (datalen < senselen) goto invalid_datalen; memcpy(sc->sense_buffer, data + 2, min_t(uint16_t, senselen, SCSI_SENSE_BUFFERSIZE)); ISCSI_DBG_SESSION(session, "copied %d bytes of sense\n", min_t(uint16_t, senselen, SCSI_SENSE_BUFFERSIZE)); } if (rhdr->flags & (ISCSI_FLAG_CMD_BIDI_UNDERFLOW | ISCSI_FLAG_CMD_BIDI_OVERFLOW)) { int res_count = be32_to_cpu(rhdr->bi_residual_count); if (scsi_bidi_cmnd(sc) && res_count > 0 && (rhdr->flags & ISCSI_FLAG_CMD_BIDI_OVERFLOW || res_count <= scsi_in(sc)->length)) scsi_in(sc)->resid = res_count; else sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status; } if (rhdr->flags & (ISCSI_FLAG_CMD_UNDERFLOW | ISCSI_FLAG_CMD_OVERFLOW)) { int res_count = be32_to_cpu(rhdr->residual_count); if (res_count > 0 && (rhdr->flags & ISCSI_FLAG_CMD_OVERFLOW || res_count <= scsi_bufflen(sc))) /* write side for bidi or uni-io set_resid */ scsi_set_resid(sc, res_count); else sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status; } out: ISCSI_DBG_SESSION(session, "cmd rsp done [sc %p res %d itt 0x%x]\n", sc, sc->result, task->itt); conn->scsirsp_pdus_cnt++; iscsi_complete_task(task, ISCSI_TASK_COMPLETED); } /** * iscsi_data_in_rsp - SCSI Data-In Response processing * @conn: iscsi connection * @hdr: iscsi pdu * @task: scsi command task **/ static void iscsi_data_in_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr, struct iscsi_task *task) { struct iscsi_data_rsp *rhdr = (struct iscsi_data_rsp *)hdr; struct scsi_cmnd *sc = task->sc; if (!(rhdr->flags & ISCSI_FLAG_DATA_STATUS)) return; iscsi_update_cmdsn(conn->session, (struct iscsi_nopin *)hdr); sc->result = (DID_OK << 16) | rhdr->cmd_status; conn->exp_statsn = be32_to_cpu(rhdr->statsn) + 1; if (rhdr->flags & (ISCSI_FLAG_DATA_UNDERFLOW | ISCSI_FLAG_DATA_OVERFLOW)) { int res_count = be32_to_cpu(rhdr->residual_count); if (res_count > 0 && (rhdr->flags & ISCSI_FLAG_CMD_OVERFLOW || res_count <= scsi_in(sc)->length)) scsi_in(sc)->resid = res_count; else sc->result = (DID_BAD_TARGET << 16) | rhdr->cmd_status; } ISCSI_DBG_SESSION(conn->session, "data in with status done " "[sc %p res %d itt 0x%x]\n", sc, sc->result, task->itt); conn->scsirsp_pdus_cnt++; iscsi_complete_task(task, ISCSI_TASK_COMPLETED); } static void iscsi_tmf_rsp(struct iscsi_conn *conn, struct iscsi_hdr *hdr) { struct iscsi_tm_rsp *tmf = (struct iscsi_tm_rsp *)hdr; conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1; conn->tmfrsp_pdus_cnt++; if (conn->tmf_state != TMF_QUEUED) return; if (tmf->response == ISCSI_TMF_RSP_COMPLETE) conn->tmf_state = TMF_SUCCESS; else if (tmf->response == ISCSI_TMF_RSP_NO_TASK) conn->tmf_state = TMF_NOT_FOUND; else conn->tmf_state = TMF_FAILED; wake_up(&conn->ehwait); } static void iscsi_send_nopout(struct iscsi_conn *conn, struct iscsi_nopin *rhdr) { struct iscsi_nopout hdr; struct iscsi_task *task; if (!rhdr && conn->ping_task) return; memset(&hdr, 0, sizeof(struct iscsi_nopout)); hdr.opcode = ISCSI_OP_NOOP_OUT | ISCSI_OP_IMMEDIATE; hdr.flags = ISCSI_FLAG_CMD_FINAL; if (rhdr) { hdr.lun = rhdr->lun; hdr.ttt = rhdr->ttt; hdr.itt = RESERVED_ITT; } else hdr.ttt = RESERVED_ITT; task = __iscsi_conn_send_pdu(conn, (struct iscsi_hdr *)&hdr, NULL, 0); if (!task) iscsi_conn_printk(KERN_ERR, conn, "Could not send nopout\n"); else if (!rhdr) { /* only track our nops */ conn->ping_task = task; conn->last_ping = jiffies; } } static int iscsi_nop_out_rsp(struct iscsi_task *task, struct iscsi_nopin *nop, char *data, int datalen) { struct iscsi_conn *conn = task->conn; int rc = 0; if (conn->ping_task != task) { /* * If this is not in response to one of our * nops then it must be from userspace. */ if (iscsi_recv_pdu(conn->cls_conn, (struct iscsi_hdr *)nop, data, datalen)) rc = ISCSI_ERR_CONN_FAILED; } else mod_timer(&conn->transport_timer, jiffies + conn->recv_timeout); iscsi_complete_task(task, ISCSI_TASK_COMPLETED); return rc; } static int iscsi_handle_reject(struct iscsi_conn *conn, struct iscsi_hdr *hdr, char *data, int datalen) { struct iscsi_reject *reject = (struct iscsi_reject *)hdr; struct iscsi_hdr rejected_pdu; int opcode, rc = 0; conn->exp_statsn = be32_to_cpu(reject->statsn) + 1; if (ntoh24(reject->dlength) > datalen || ntoh24(reject->dlength) < sizeof(struct iscsi_hdr)) { iscsi_conn_printk(KERN_ERR, conn, "Cannot handle rejected " "pdu. Invalid data length (pdu dlength " "%u, datalen %d\n", ntoh24(reject->dlength), datalen); return ISCSI_ERR_PROTO; } memcpy(&rejected_pdu, data, sizeof(struct iscsi_hdr)); opcode = rejected_pdu.opcode & ISCSI_OPCODE_MASK; switch (reject->reason) { case ISCSI_REASON_DATA_DIGEST_ERROR: iscsi_conn_printk(KERN_ERR, conn, "pdu (op 0x%x itt 0x%x) rejected " "due to DataDigest error.\n", opcode, rejected_pdu.itt); break; case ISCSI_REASON_IMM_CMD_REJECT: iscsi_conn_printk(KERN_ERR, conn, "pdu (op 0x%x itt 0x%x) rejected. Too many " "immediate commands.\n", opcode, rejected_pdu.itt); /* * We only send one TMF at a time so if the target could not * handle it, then it should get fixed (RFC mandates that * a target can handle one immediate TMF per conn). * * For nops-outs, we could have sent more than one if * the target is sending us lots of nop-ins */ if (opcode != ISCSI_OP_NOOP_OUT) return 0; if (rejected_pdu.itt == cpu_to_be32(ISCSI_RESERVED_TAG)) { /* * nop-out in response to target's nop-out rejected. * Just resend. */ /* In RX path we are under back lock */ spin_unlock(&conn->session->back_lock); spin_lock(&conn->session->frwd_lock); iscsi_send_nopout(conn, (struct iscsi_nopin*)&rejected_pdu); spin_unlock(&conn->session->frwd_lock); spin_lock(&conn->session->back_lock); } else { struct iscsi_task *task; /* * Our nop as ping got dropped. We know the target * and transport are ok so just clean up */ task = iscsi_itt_to_task(conn, rejected_pdu.itt); if (!task) { iscsi_conn_printk(KERN_ERR, conn, "Invalid pdu reject. Could " "not lookup rejected task.\n"); rc = ISCSI_ERR_BAD_ITT; } else rc = iscsi_nop_out_rsp(task, (struct iscsi_nopin*)&rejected_pdu, NULL, 0); } break; default: iscsi_conn_printk(KERN_ERR, conn, "pdu (op 0x%x itt 0x%x) rejected. Reason " "code 0x%x\n", rejected_pdu.opcode, rejected_pdu.itt, reject->reason); break; } return rc; } /** * iscsi_itt_to_task - look up task by itt * @conn: iscsi connection * @itt: itt * * This should be used for mgmt tasks like login and nops, or if * the LDD's itt space does not include the session age. * * The session back_lock must be held. */ struct iscsi_task *iscsi_itt_to_task(struct iscsi_conn *conn, itt_t itt) { struct iscsi_session *session = conn->session; int i; if (itt == RESERVED_ITT) return NULL; if (session->tt->parse_pdu_itt) session->tt->parse_pdu_itt(conn, itt, &i, NULL); else i = get_itt(itt); if (i >= session->cmds_max) return NULL; return session->cmds[i]; } EXPORT_SYMBOL_GPL(iscsi_itt_to_task); /** * __iscsi_complete_pdu - complete pdu * @conn: iscsi conn * @hdr: iscsi header * @data: data buffer * @datalen: len of data buffer * * Completes pdu processing by freeing any resources allocated at * queuecommand or send generic. session back_lock must be held and verify * itt must have been called. */ int __iscsi_complete_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr, char *data, int datalen) { struct iscsi_session *session = conn->session; int opcode = hdr->opcode & ISCSI_OPCODE_MASK, rc = 0; struct iscsi_task *task; uint32_t itt; conn->last_recv = jiffies; rc = iscsi_verify_itt(conn, hdr->itt); if (rc) return rc; if (hdr->itt != RESERVED_ITT) itt = get_itt(hdr->itt); else itt = ~0U; ISCSI_DBG_SESSION(session, "[op 0x%x cid %d itt 0x%x len %d]\n", opcode, conn->id, itt, datalen); if (itt == ~0U) { iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr); switch(opcode) { case ISCSI_OP_NOOP_IN: if (datalen) { rc = ISCSI_ERR_PROTO; break; } if (hdr->ttt == cpu_to_be32(ISCSI_RESERVED_TAG)) break; /* In RX path we are under back lock */ spin_unlock(&session->back_lock); spin_lock(&session->frwd_lock); iscsi_send_nopout(conn, (struct iscsi_nopin*)hdr); spin_unlock(&session->frwd_lock); spin_lock(&session->back_lock); break; case ISCSI_OP_REJECT: rc = iscsi_handle_reject(conn, hdr, data, datalen); break; case ISCSI_OP_ASYNC_EVENT: conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1; if (iscsi_recv_pdu(conn->cls_conn, hdr, data, datalen)) rc = ISCSI_ERR_CONN_FAILED; break; default: rc = ISCSI_ERR_BAD_OPCODE; break; } goto out; } switch(opcode) { case ISCSI_OP_SCSI_CMD_RSP: case ISCSI_OP_SCSI_DATA_IN: task = iscsi_itt_to_ctask(conn, hdr->itt); if (!task) return ISCSI_ERR_BAD_ITT; task->last_xfer = jiffies; break; case ISCSI_OP_R2T: /* * LLD handles R2Ts if they need to. */ return 0; case ISCSI_OP_LOGOUT_RSP: case ISCSI_OP_LOGIN_RSP: case ISCSI_OP_TEXT_RSP: case ISCSI_OP_SCSI_TMFUNC_RSP: case ISCSI_OP_NOOP_IN: task = iscsi_itt_to_task(conn, hdr->itt); if (!task) return ISCSI_ERR_BAD_ITT; break; default: return ISCSI_ERR_BAD_OPCODE; } switch(opcode) { case ISCSI_OP_SCSI_CMD_RSP: iscsi_scsi_cmd_rsp(conn, hdr, task, data, datalen); break; case ISCSI_OP_SCSI_DATA_IN: iscsi_data_in_rsp(conn, hdr, task); break; case ISCSI_OP_LOGOUT_RSP: iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr); if (datalen) { rc = ISCSI_ERR_PROTO; break; } conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1; goto recv_pdu; case ISCSI_OP_LOGIN_RSP: case ISCSI_OP_TEXT_RSP: iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr); /* * login related PDU's exp_statsn is handled in * userspace */ goto recv_pdu; case ISCSI_OP_SCSI_TMFUNC_RSP: iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr); if (datalen) { rc = ISCSI_ERR_PROTO; break; } iscsi_tmf_rsp(conn, hdr); iscsi_complete_task(task, ISCSI_TASK_COMPLETED); break; case ISCSI_OP_NOOP_IN: iscsi_update_cmdsn(session, (struct iscsi_nopin*)hdr); if (hdr->ttt != cpu_to_be32(ISCSI_RESERVED_TAG) || datalen) { rc = ISCSI_ERR_PROTO; break; } conn->exp_statsn = be32_to_cpu(hdr->statsn) + 1; rc = iscsi_nop_out_rsp(task, (struct iscsi_nopin*)hdr, data, datalen); break; default: rc = ISCSI_ERR_BAD_OPCODE; break; } out: return rc; recv_pdu: if (iscsi_recv_pdu(conn->cls_conn, hdr, data, datalen)) rc = ISCSI_ERR_CONN_FAILED; iscsi_complete_task(task, ISCSI_TASK_COMPLETED); return rc; } EXPORT_SYMBOL_GPL(__iscsi_complete_pdu); int iscsi_complete_pdu(struct iscsi_conn *conn, struct iscsi_hdr *hdr, char *data, int datalen) { int rc; spin_lock(&conn->session->back_lock); rc = __iscsi_complete_pdu(conn, hdr, data, datalen); spin_unlock(&conn->session->back_lock); return rc; } EXPORT_SYMBOL_GPL(iscsi_complete_pdu); int iscsi_verify_itt(struct iscsi_conn *conn, itt_t itt) { struct iscsi_session *session = conn->session; int age = 0, i = 0; if (itt == RESERVED_ITT) return 0; if (session->tt->parse_pdu_itt) session->tt->parse_pdu_itt(conn, itt, &i, &age); else { i = get_itt(itt); age = ((__force u32)itt >> ISCSI_AGE_SHIFT) & ISCSI_AGE_MASK; } if (age != session->age) { iscsi_conn_printk(KERN_ERR, conn, "received itt %x expected session age (%x)\n", (__force u32)itt, session->age); return ISCSI_ERR_BAD_ITT; } if (i >= session->cmds_max) { iscsi_conn_printk(KERN_ERR, conn, "received invalid itt index %u (max cmds " "%u.\n", i, session->cmds_max); return ISCSI_ERR_BAD_ITT; } return 0; } EXPORT_SYMBOL_GPL(iscsi_verify_itt); /** * iscsi_itt_to_ctask - look up ctask by itt * @conn: iscsi connection * @itt: itt * * This should be used for cmd tasks. * * The session back_lock must be held. */ struct iscsi_task *iscsi_itt_to_ctask(struct iscsi_conn *conn, itt_t itt) { struct iscsi_task *task; if (iscsi_verify_itt(conn, itt)) return NULL; task = iscsi_itt_to_task(conn, itt); if (!task || !task->sc) return NULL; if (task->sc->SCp.phase != conn->session->age) { iscsi_session_printk(KERN_ERR, conn->session, "task's session age %d, expected %d\n", task->sc->SCp.phase, conn->session->age); return NULL; } return task; } EXPORT_SYMBOL_GPL(iscsi_itt_to_ctask); void iscsi_session_failure(struct iscsi_session *session, enum iscsi_err err) { struct iscsi_conn *conn; struct device *dev; spin_lock_bh(&session->frwd_lock); conn = session->leadconn; if (session->state == ISCSI_STATE_TERMINATE || !conn) { spin_unlock_bh(&session->frwd_lock); return; } dev = get_device(&conn->cls_conn->dev); spin_unlock_bh(&session->frwd_lock); if (!dev) return; /* * if the host is being removed bypass the connection * recovery initialization because we are going to kill * the session. */ if (err == ISCSI_ERR_INVALID_HOST) iscsi_conn_error_event(conn->cls_conn, err); else iscsi_conn_failure(conn, err); put_device(dev); } EXPORT_SYMBOL_GPL(iscsi_session_failure); void iscsi_conn_failure(struct iscsi_conn *conn, enum iscsi_err err) { struct iscsi_session *session = conn->session; spin_lock_bh(&session->frwd_lock); if (session->state == ISCSI_STATE_FAILED) { spin_unlock_bh(&session->frwd_lock); return; } if (conn->stop_stage == 0) session->state = ISCSI_STATE_FAILED; spin_unlock_bh(&session->frwd_lock); set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx); set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_rx); iscsi_conn_error_event(conn->cls_conn, err); } EXPORT_SYMBOL_GPL(iscsi_conn_failure); static int iscsi_check_cmdsn_window_closed(struct iscsi_conn *conn) { struct iscsi_session *session = conn->session; /* * Check for iSCSI window and take care of CmdSN wrap-around */ if (!iscsi_sna_lte(session->queued_cmdsn, session->max_cmdsn)) { ISCSI_DBG_SESSION(session, "iSCSI CmdSN closed. ExpCmdSn " "%u MaxCmdSN %u CmdSN %u/%u\n", session->exp_cmdsn, session->max_cmdsn, session->cmdsn, session->queued_cmdsn); return -ENOSPC; } return 0; } static int iscsi_xmit_task(struct iscsi_conn *conn) { struct iscsi_task *task = conn->task; int rc; if (test_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx)) return -ENODATA; __iscsi_get_task(task); spin_unlock_bh(&conn->session->frwd_lock); rc = conn->session->tt->xmit_task(task); spin_lock_bh(&conn->session->frwd_lock); if (!rc) { /* done with this task */ task->last_xfer = jiffies; conn->task = NULL; } /* regular RX path uses back_lock */ spin_lock(&conn->session->back_lock); __iscsi_put_task(task); spin_unlock(&conn->session->back_lock); return rc; } /** * iscsi_requeue_task - requeue task to run from session workqueue * @task: task to requeue * * LLDs that need to run a task from the session workqueue should call * this. The session frwd_lock must be held. This should only be called * by software drivers. */ void iscsi_requeue_task(struct iscsi_task *task) { struct iscsi_conn *conn = task->conn; /* * this may be on the requeue list already if the xmit_task callout * is handling the r2ts while we are adding new ones */ if (list_empty(&task->running)) list_add_tail(&task->running, &conn->requeue); iscsi_conn_queue_work(conn); } EXPORT_SYMBOL_GPL(iscsi_requeue_task); /** * iscsi_data_xmit - xmit any command into the scheduled connection * @conn: iscsi connection * * Notes: * The function can return -EAGAIN in which case the caller must * re-schedule it again later or recover. '0' return code means * successful xmit. **/ static int iscsi_data_xmit(struct iscsi_conn *conn) { struct iscsi_task *task; int rc = 0; spin_lock_bh(&conn->session->frwd_lock); if (test_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx)) { ISCSI_DBG_SESSION(conn->session, "Tx suspended!\n"); spin_unlock_bh(&conn->session->frwd_lock); return -ENODATA; } if (conn->task) { rc = iscsi_xmit_task(conn); if (rc) goto done; } /* * process mgmt pdus like nops before commands since we should * only have one nop-out as a ping from us and targets should not * overflow us with nop-ins */ check_mgmt: while (!list_empty(&conn->mgmtqueue)) { conn->task = list_entry(conn->mgmtqueue.next, struct iscsi_task, running); list_del_init(&conn->task->running); if (iscsi_prep_mgmt_task(conn, conn->task)) { /* regular RX path uses back_lock */ spin_lock_bh(&conn->session->back_lock); __iscsi_put_task(conn->task); spin_unlock_bh(&conn->session->back_lock); conn->task = NULL; continue; } rc = iscsi_xmit_task(conn); if (rc) goto done; } /* process pending command queue */ while (!list_empty(&conn->cmdqueue)) { conn->task = list_entry(conn->cmdqueue.next, struct iscsi_task, running); list_del_init(&conn->task->running); if (conn->session->state == ISCSI_STATE_LOGGING_OUT) { fail_scsi_task(conn->task, DID_IMM_RETRY); continue; } rc = iscsi_prep_scsi_cmd_pdu(conn->task); if (rc) { if (rc == -ENOMEM || rc == -EACCES) { list_add_tail(&conn->task->running, &conn->cmdqueue); conn->task = NULL; goto done; } else fail_scsi_task(conn->task, DID_ABORT); continue; } rc = iscsi_xmit_task(conn); if (rc) goto done; /* * we could continuously get new task requests so * we need to check the mgmt queue for nops that need to * be sent to aviod starvation */ if (!list_empty(&conn->mgmtqueue)) goto check_mgmt; } while (!list_empty(&conn->requeue)) { /* * we always do fastlogout - conn stop code will clean up. */ if (conn->session->state == ISCSI_STATE_LOGGING_OUT) break; task = list_entry(conn->requeue.next, struct iscsi_task, running); if (iscsi_check_tmf_restrictions(task, ISCSI_OP_SCSI_DATA_OUT)) break; conn->task = task; list_del_init(&conn->task->running); conn->task->state = ISCSI_TASK_RUNNING; rc = iscsi_xmit_task(conn); if (rc) goto done; if (!list_empty(&conn->mgmtqueue)) goto check_mgmt; } spin_unlock_bh(&conn->session->frwd_lock); return -ENODATA; done: spin_unlock_bh(&conn->session->frwd_lock); return rc; } static void iscsi_xmitworker(struct work_struct *work) { struct iscsi_conn *conn = container_of(work, struct iscsi_conn, xmitwork); int rc; /* * serialize Xmit worker on a per-connection basis. */ do { rc = iscsi_data_xmit(conn); } while (rc >= 0 || rc == -EAGAIN); } static inline struct iscsi_task *iscsi_alloc_task(struct iscsi_conn *conn, struct scsi_cmnd *sc) { struct iscsi_task *task; if (!kfifo_out(&conn->session->cmdpool.queue, (void *) &task, sizeof(void *))) return NULL; sc->SCp.phase = conn->session->age; sc->SCp.ptr = (char *) task; atomic_set(&task->refcount, 1); task->state = ISCSI_TASK_PENDING; task->conn = conn; task->sc = sc; task->have_checked_conn = false; task->last_timeout = jiffies; task->last_xfer = jiffies; task->protected = false; INIT_LIST_HEAD(&task->running); return task; } enum { FAILURE_BAD_HOST = 1, FAILURE_SESSION_FAILED, FAILURE_SESSION_FREED, FAILURE_WINDOW_CLOSED, FAILURE_OOM, FAILURE_SESSION_TERMINATE, FAILURE_SESSION_IN_RECOVERY, FAILURE_SESSION_RECOVERY_TIMEOUT, FAILURE_SESSION_LOGGING_OUT, FAILURE_SESSION_NOT_READY, }; int iscsi_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *sc) { struct iscsi_cls_session *cls_session; struct iscsi_host *ihost; int reason = 0; struct iscsi_session *session; struct iscsi_conn *conn; struct iscsi_task *task = NULL; sc->result = 0; sc->SCp.ptr = NULL; ihost = shost_priv(host); cls_session = starget_to_session(scsi_target(sc->device)); session = cls_session->dd_data; spin_lock_bh(&session->frwd_lock); reason = iscsi_session_chkready(cls_session); if (reason) { sc->result = reason; goto fault; } if (session->state != ISCSI_STATE_LOGGED_IN) { /* * to handle the race between when we set the recovery state * and block the session we requeue here (commands could * be entering our queuecommand while a block is starting * up because the block code is not locked) */ switch (session->state) { case ISCSI_STATE_FAILED: case ISCSI_STATE_IN_RECOVERY: reason = FAILURE_SESSION_IN_RECOVERY; sc->result = DID_IMM_RETRY << 16; break; case ISCSI_STATE_LOGGING_OUT: reason = FAILURE_SESSION_LOGGING_OUT; sc->result = DID_IMM_RETRY << 16; break; case ISCSI_STATE_RECOVERY_FAILED: reason = FAILURE_SESSION_RECOVERY_TIMEOUT; sc->result = DID_TRANSPORT_FAILFAST << 16; break; case ISCSI_STATE_TERMINATE: reason = FAILURE_SESSION_TERMINATE; sc->result = DID_NO_CONNECT << 16; break; default: reason = FAILURE_SESSION_FREED; sc->result = DID_NO_CONNECT << 16; } goto fault; } conn = session->leadconn; if (!conn) { reason = FAILURE_SESSION_FREED; sc->result = DID_NO_CONNECT << 16; goto fault; } if (test_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx)) { reason = FAILURE_SESSION_IN_RECOVERY; sc->result = DID_REQUEUE; goto fault; } if (iscsi_check_cmdsn_window_closed(conn)) { reason = FAILURE_WINDOW_CLOSED; goto reject; } task = iscsi_alloc_task(conn, sc); if (!task) { reason = FAILURE_OOM; goto reject; } if (!ihost->workq) { reason = iscsi_prep_scsi_cmd_pdu(task); if (reason) { if (reason == -ENOMEM || reason == -EACCES) { reason = FAILURE_OOM; goto prepd_reject; } else { sc->result = DID_ABORT << 16; goto prepd_fault; } } if (session->tt->xmit_task(task)) { session->cmdsn--; reason = FAILURE_SESSION_NOT_READY; goto prepd_reject; } } else { list_add_tail(&task->running, &conn->cmdqueue); iscsi_conn_queue_work(conn); } session->queued_cmdsn++; spin_unlock_bh(&session->frwd_lock); return 0; prepd_reject: iscsi_complete_task(task, ISCSI_TASK_REQUEUE_SCSIQ); reject: spin_unlock_bh(&session->frwd_lock); ISCSI_DBG_SESSION(session, "cmd 0x%x rejected (%d)\n", sc->cmnd[0], reason); return SCSI_MLQUEUE_TARGET_BUSY; prepd_fault: iscsi_complete_task(task, ISCSI_TASK_REQUEUE_SCSIQ); fault: spin_unlock_bh(&session->frwd_lock); ISCSI_DBG_SESSION(session, "iscsi: cmd 0x%x is not queued (%d)\n", sc->cmnd[0], reason); if (!scsi_bidi_cmnd(sc)) scsi_set_resid(sc, scsi_bufflen(sc)); else { scsi_out(sc)->resid = scsi_out(sc)->length; scsi_in(sc)->resid = scsi_in(sc)->length; } sc->scsi_done(sc); return 0; } EXPORT_SYMBOL_GPL(iscsi_queuecommand); int iscsi_target_alloc(struct scsi_target *starget) { struct iscsi_cls_session *cls_session = starget_to_session(starget); struct iscsi_session *session = cls_session->dd_data; starget->can_queue = session->scsi_cmds_max; return 0; } EXPORT_SYMBOL_GPL(iscsi_target_alloc); static void iscsi_tmf_timedout(unsigned long data) { struct iscsi_conn *conn = (struct iscsi_conn *)data; struct iscsi_session *session = conn->session; spin_lock(&session->frwd_lock); if (conn->tmf_state == TMF_QUEUED) { conn->tmf_state = TMF_TIMEDOUT; ISCSI_DBG_EH(session, "tmf timedout\n"); /* unblock eh_abort() */ wake_up(&conn->ehwait); } spin_unlock(&session->frwd_lock); } static int iscsi_exec_task_mgmt_fn(struct iscsi_conn *conn, struct iscsi_tm *hdr, int age, int timeout) { struct iscsi_session *session = conn->session; struct iscsi_task *task; task = __iscsi_conn_send_pdu(conn, (struct iscsi_hdr *)hdr, NULL, 0); if (!task) { spin_unlock_bh(&session->frwd_lock); iscsi_conn_printk(KERN_ERR, conn, "Could not send TMF.\n"); iscsi_conn_failure(conn, ISCSI_ERR_CONN_FAILED); spin_lock_bh(&session->frwd_lock); return -EPERM; } conn->tmfcmd_pdus_cnt++; conn->tmf_timer.expires = timeout * HZ + jiffies; conn->tmf_timer.function = iscsi_tmf_timedout; conn->tmf_timer.data = (unsigned long)conn; add_timer(&conn->tmf_timer); ISCSI_DBG_EH(session, "tmf set timeout\n"); spin_unlock_bh(&session->frwd_lock); mutex_unlock(&session->eh_mutex); /* * block eh thread until: * * 1) tmf response * 2) tmf timeout * 3) session is terminated or restarted or userspace has * given up on recovery */ wait_event_interruptible(conn->ehwait, age != session->age || session->state != ISCSI_STATE_LOGGED_IN || conn->tmf_state != TMF_QUEUED); if (signal_pending(current)) flush_signals(current); del_timer_sync(&conn->tmf_timer); mutex_lock(&session->eh_mutex); spin_lock_bh(&session->frwd_lock); /* if the session drops it will clean up the task */ if (age != session->age || session->state != ISCSI_STATE_LOGGED_IN) return -ENOTCONN; return 0; } /* * Fail commands. session lock held and recv side suspended and xmit * thread flushed */ static void fail_scsi_tasks(struct iscsi_conn *conn, u64 lun, int error) { struct iscsi_task *task; int i; for (i = 0; i < conn->session->cmds_max; i++) { task = conn->session->cmds[i]; if (!task->sc || task->state == ISCSI_TASK_FREE) continue; if (lun != -1 && lun != task->sc->device->lun) continue; ISCSI_DBG_SESSION(conn->session, "failing sc %p itt 0x%x state %d\n", task->sc, task->itt, task->state); fail_scsi_task(task, error); } } /** * iscsi_suspend_queue - suspend iscsi_queuecommand * @conn: iscsi conn to stop queueing IO on * * This grabs the session frwd_lock to make sure no one is in * xmit_task/queuecommand, and then sets suspend to prevent * new commands from being queued. This only needs to be called * by offload drivers that need to sync a path like ep disconnect * with the iscsi_queuecommand/xmit_task. To start IO again libiscsi * will call iscsi_start_tx and iscsi_unblock_session when in FFP. */ void iscsi_suspend_queue(struct iscsi_conn *conn) { spin_lock_bh(&conn->session->frwd_lock); set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx); spin_unlock_bh(&conn->session->frwd_lock); } EXPORT_SYMBOL_GPL(iscsi_suspend_queue); /** * iscsi_suspend_tx - suspend iscsi_data_xmit * @conn: iscsi conn tp stop processing IO on. * * This function sets the suspend bit to prevent iscsi_data_xmit * from sending new IO, and if work is queued on the xmit thread * it will wait for it to be completed. */ void iscsi_suspend_tx(struct iscsi_conn *conn) { struct Scsi_Host *shost = conn->session->host; struct iscsi_host *ihost = shost_priv(shost); set_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx); if (ihost->workq) flush_workqueue(ihost->workq); } EXPORT_SYMBOL_GPL(iscsi_suspend_tx); static void iscsi_start_tx(struct iscsi_conn *conn) { clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx); iscsi_conn_queue_work(conn); } /* * We want to make sure a ping is in flight. It has timed out. * And we are not busy processing a pdu that is making * progress but got started before the ping and is taking a while * to complete so the ping is just stuck behind it in a queue. */ static int iscsi_has_ping_timed_out(struct iscsi_conn *conn) { if (conn->ping_task && time_before_eq(conn->last_recv + (conn->recv_timeout * HZ) + (conn->ping_timeout * HZ), jiffies)) return 1; else return 0; } static enum blk_eh_timer_return iscsi_eh_cmd_timed_out(struct scsi_cmnd *sc) { enum blk_eh_timer_return rc = BLK_EH_NOT_HANDLED; struct iscsi_task *task = NULL, *running_task; struct iscsi_cls_session *cls_session; struct iscsi_session *session; struct iscsi_conn *conn; int i; cls_session = starget_to_session(scsi_target(sc->device)); session = cls_session->dd_data; ISCSI_DBG_EH(session, "scsi cmd %p timedout\n", sc); spin_lock(&session->frwd_lock); task = (struct iscsi_task *)sc->SCp.ptr; if (!task) { /* * Raced with completion. Blk layer has taken ownership * so let timeout code complete it now. */ rc = BLK_EH_HANDLED; goto done; } if (session->state != ISCSI_STATE_LOGGED_IN) { /* * We are probably in the middle of iscsi recovery so let * that complete and handle the error. */ rc = BLK_EH_RESET_TIMER; goto done; } conn = session->leadconn; if (!conn) { /* In the middle of shuting down */ rc = BLK_EH_RESET_TIMER; goto done; } /* * If we have sent (at least queued to the network layer) a pdu or * recvd one for the task since the last timeout ask for * more time. If on the next timeout we have not made progress * we can check if it is the task or connection when we send the * nop as a ping. */ if (time_after(task->last_xfer, task->last_timeout)) { ISCSI_DBG_EH(session, "Command making progress. Asking " "scsi-ml for more time to complete. " "Last data xfer at %lu. Last timeout was at " "%lu\n.", task->last_xfer, task->last_timeout); task->have_checked_conn = false; rc = BLK_EH_RESET_TIMER; goto done; } if (!conn->recv_timeout && !conn->ping_timeout) goto done; /* * if the ping timedout then we are in the middle of cleaning up * and can let the iscsi eh handle it */ if (iscsi_has_ping_timed_out(conn)) { rc = BLK_EH_RESET_TIMER; goto done; } for (i = 0; i < conn->session->cmds_max; i++) { running_task = conn->session->cmds[i]; if (!running_task->sc || running_task == task || running_task->state != ISCSI_TASK_RUNNING) continue; /* * Only check if cmds started before this one have made * progress, or this could never fail */ if (time_after(running_task->sc->jiffies_at_alloc, task->sc->jiffies_at_alloc)) continue; if (time_after(running_task->last_xfer, task->last_timeout)) { /* * This task has not made progress, but a task * started before us has transferred data since * we started/last-checked. We could be queueing * too many tasks or the LU is bad. * * If the device is bad the cmds ahead of us on * other devs will complete, and this loop will * eventually fail starting the scsi eh. */ ISCSI_DBG_EH(session, "Command has not made progress " "but commands ahead of it have. " "Asking scsi-ml for more time to " "complete. Our last xfer vs running task " "last xfer %lu/%lu. Last check %lu.\n", task->last_xfer, running_task->last_xfer, task->last_timeout); rc = BLK_EH_RESET_TIMER; goto done; } } /* Assumes nop timeout is shorter than scsi cmd timeout */ if (task->have_checked_conn) goto done; /* * Checking the transport already or nop from a cmd timeout still * running */ if (conn->ping_task) { task->have_checked_conn = true; rc = BLK_EH_RESET_TIMER; goto done; } /* Make sure there is a transport check done */ iscsi_send_nopout(conn, NULL); task->have_checked_conn = true; rc = BLK_EH_RESET_TIMER; done: if (task) task->last_timeout = jiffies; spin_unlock(&session->frwd_lock); ISCSI_DBG_EH(session, "return %s\n", rc == BLK_EH_RESET_TIMER ? "timer reset" : "nh"); return rc; } static void iscsi_check_transport_timeouts(unsigned long data) { struct iscsi_conn *conn = (struct iscsi_conn *)data; struct iscsi_session *session = conn->session; unsigned long recv_timeout, next_timeout = 0, last_recv; spin_lock(&session->frwd_lock); if (session->state != ISCSI_STATE_LOGGED_IN) goto done; recv_timeout = conn->recv_timeout; if (!recv_timeout) goto done; recv_timeout *= HZ; last_recv = conn->last_recv; if (iscsi_has_ping_timed_out(conn)) { iscsi_conn_printk(KERN_ERR, conn, "ping timeout of %d secs " "expired, recv timeout %d, last rx %lu, " "last ping %lu, now %lu\n", conn->ping_timeout, conn->recv_timeout, last_recv, conn->last_ping, jiffies); spin_unlock(&session->frwd_lock); iscsi_conn_failure(conn, ISCSI_ERR_NOP_TIMEDOUT); return; } if (time_before_eq(last_recv + recv_timeout, jiffies)) { /* send a ping to try to provoke some traffic */ ISCSI_DBG_CONN(conn, "Sending nopout as ping\n"); iscsi_send_nopout(conn, NULL); next_timeout = conn->last_ping + (conn->ping_timeout * HZ); } else next_timeout = last_recv + recv_timeout; ISCSI_DBG_CONN(conn, "Setting next tmo %lu\n", next_timeout); mod_timer(&conn->transport_timer, next_timeout); done: spin_unlock(&session->frwd_lock); } static void iscsi_prep_abort_task_pdu(struct iscsi_task *task, struct iscsi_tm *hdr) { memset(hdr, 0, sizeof(*hdr)); hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE; hdr->flags = ISCSI_TM_FUNC_ABORT_TASK & ISCSI_FLAG_TM_FUNC_MASK; hdr->flags |= ISCSI_FLAG_CMD_FINAL; hdr->lun = task->lun; hdr->rtt = task->hdr_itt; hdr->refcmdsn = task->cmdsn; } int iscsi_eh_abort(struct scsi_cmnd *sc) { struct iscsi_cls_session *cls_session; struct iscsi_session *session; struct iscsi_conn *conn; struct iscsi_task *task; struct iscsi_tm *hdr; int rc, age; cls_session = starget_to_session(scsi_target(sc->device)); session = cls_session->dd_data; ISCSI_DBG_EH(session, "aborting sc %p\n", sc); mutex_lock(&session->eh_mutex); spin_lock_bh(&session->frwd_lock); /* * if session was ISCSI_STATE_IN_RECOVERY then we may not have * got the command. */ if (!sc->SCp.ptr) { ISCSI_DBG_EH(session, "sc never reached iscsi layer or " "it completed.\n"); spin_unlock_bh(&session->frwd_lock); mutex_unlock(&session->eh_mutex); return SUCCESS; } /* * If we are not logged in or we have started a new session * then let the host reset code handle this */ if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN || sc->SCp.phase != session->age) { spin_unlock_bh(&session->frwd_lock); mutex_unlock(&session->eh_mutex); ISCSI_DBG_EH(session, "failing abort due to dropped " "session.\n"); return FAILED; } conn = session->leadconn; conn->eh_abort_cnt++; age = session->age; task = (struct iscsi_task *)sc->SCp.ptr; ISCSI_DBG_EH(session, "aborting [sc %p itt 0x%x]\n", sc, task->itt); /* task completed before time out */ if (!task->sc) { ISCSI_DBG_EH(session, "sc completed while abort in progress\n"); goto success; } if (task->state == ISCSI_TASK_PENDING) { fail_scsi_task(task, DID_ABORT); goto success; } /* only have one tmf outstanding at a time */ if (conn->tmf_state != TMF_INITIAL) goto failed; conn->tmf_state = TMF_QUEUED; hdr = &conn->tmhdr; iscsi_prep_abort_task_pdu(task, hdr); if (iscsi_exec_task_mgmt_fn(conn, hdr, age, session->abort_timeout)) { rc = FAILED; goto failed; } switch (conn->tmf_state) { case TMF_SUCCESS: spin_unlock_bh(&session->frwd_lock); /* * stop tx side incase the target had sent a abort rsp but * the initiator was still writing out data. */ iscsi_suspend_tx(conn); /* * we do not stop the recv side because targets have been * good and have never sent us a successful tmf response * then sent more data for the cmd. */ spin_lock_bh(&session->frwd_lock); fail_scsi_task(task, DID_ABORT); conn->tmf_state = TMF_INITIAL; memset(hdr, 0, sizeof(*hdr)); spin_unlock_bh(&session->frwd_lock); iscsi_start_tx(conn); goto success_unlocked; case TMF_TIMEDOUT: spin_unlock_bh(&session->frwd_lock); iscsi_conn_failure(conn, ISCSI_ERR_SCSI_EH_SESSION_RST); goto failed_unlocked; case TMF_NOT_FOUND: if (!sc->SCp.ptr) { conn->tmf_state = TMF_INITIAL; memset(hdr, 0, sizeof(*hdr)); /* task completed before tmf abort response */ ISCSI_DBG_EH(session, "sc completed while abort in " "progress\n"); goto success; } /* fall through */ default: conn->tmf_state = TMF_INITIAL; goto failed; } success: spin_unlock_bh(&session->frwd_lock); success_unlocked: ISCSI_DBG_EH(session, "abort success [sc %p itt 0x%x]\n", sc, task->itt); mutex_unlock(&session->eh_mutex); return SUCCESS; failed: spin_unlock_bh(&session->frwd_lock); failed_unlocked: ISCSI_DBG_EH(session, "abort failed [sc %p itt 0x%x]\n", sc, task ? task->itt : 0); mutex_unlock(&session->eh_mutex); return FAILED; } EXPORT_SYMBOL_GPL(iscsi_eh_abort); static void iscsi_prep_lun_reset_pdu(struct scsi_cmnd *sc, struct iscsi_tm *hdr) { memset(hdr, 0, sizeof(*hdr)); hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE; hdr->flags = ISCSI_TM_FUNC_LOGICAL_UNIT_RESET & ISCSI_FLAG_TM_FUNC_MASK; hdr->flags |= ISCSI_FLAG_CMD_FINAL; int_to_scsilun(sc->device->lun, &hdr->lun); hdr->rtt = RESERVED_ITT; } int iscsi_eh_device_reset(struct scsi_cmnd *sc) { struct iscsi_cls_session *cls_session; struct iscsi_session *session; struct iscsi_conn *conn; struct iscsi_tm *hdr; int rc = FAILED; cls_session = starget_to_session(scsi_target(sc->device)); session = cls_session->dd_data; ISCSI_DBG_EH(session, "LU Reset [sc %p lun %llu]\n", sc, sc->device->lun); mutex_lock(&session->eh_mutex); spin_lock_bh(&session->frwd_lock); /* * Just check if we are not logged in. We cannot check for * the phase because the reset could come from a ioctl. */ if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN) goto unlock; conn = session->leadconn; /* only have one tmf outstanding at a time */ if (conn->tmf_state != TMF_INITIAL) goto unlock; conn->tmf_state = TMF_QUEUED; hdr = &conn->tmhdr; iscsi_prep_lun_reset_pdu(sc, hdr); if (iscsi_exec_task_mgmt_fn(conn, hdr, session->age, session->lu_reset_timeout)) { rc = FAILED; goto unlock; } switch (conn->tmf_state) { case TMF_SUCCESS: break; case TMF_TIMEDOUT: spin_unlock_bh(&session->frwd_lock); iscsi_conn_failure(conn, ISCSI_ERR_SCSI_EH_SESSION_RST); goto done; default: conn->tmf_state = TMF_INITIAL; goto unlock; } rc = SUCCESS; spin_unlock_bh(&session->frwd_lock); iscsi_suspend_tx(conn); spin_lock_bh(&session->frwd_lock); memset(hdr, 0, sizeof(*hdr)); fail_scsi_tasks(conn, sc->device->lun, DID_ERROR); conn->tmf_state = TMF_INITIAL; spin_unlock_bh(&session->frwd_lock); iscsi_start_tx(conn); goto done; unlock: spin_unlock_bh(&session->frwd_lock); done: ISCSI_DBG_EH(session, "dev reset result = %s\n", rc == SUCCESS ? "SUCCESS" : "FAILED"); mutex_unlock(&session->eh_mutex); return rc; } EXPORT_SYMBOL_GPL(iscsi_eh_device_reset); void iscsi_session_recovery_timedout(struct iscsi_cls_session *cls_session) { struct iscsi_session *session = cls_session->dd_data; spin_lock_bh(&session->frwd_lock); if (session->state != ISCSI_STATE_LOGGED_IN) { session->state = ISCSI_STATE_RECOVERY_FAILED; if (session->leadconn) wake_up(&session->leadconn->ehwait); } spin_unlock_bh(&session->frwd_lock); } EXPORT_SYMBOL_GPL(iscsi_session_recovery_timedout); /** * iscsi_eh_session_reset - drop session and attempt relogin * @sc: scsi command * * This function will wait for a relogin, session termination from * userspace, or a recovery/replacement timeout. */ int iscsi_eh_session_reset(struct scsi_cmnd *sc) { struct iscsi_cls_session *cls_session; struct iscsi_session *session; struct iscsi_conn *conn; cls_session = starget_to_session(scsi_target(sc->device)); session = cls_session->dd_data; conn = session->leadconn; mutex_lock(&session->eh_mutex); spin_lock_bh(&session->frwd_lock); if (session->state == ISCSI_STATE_TERMINATE) { failed: ISCSI_DBG_EH(session, "failing session reset: Could not log back into " "%s, %s [age %d]\n", session->targetname, conn->persistent_address, session->age); spin_unlock_bh(&session->frwd_lock); mutex_unlock(&session->eh_mutex); return FAILED; } spin_unlock_bh(&session->frwd_lock); mutex_unlock(&session->eh_mutex); /* * we drop the lock here but the leadconn cannot be destoyed while * we are in the scsi eh */ iscsi_conn_failure(conn, ISCSI_ERR_SCSI_EH_SESSION_RST); ISCSI_DBG_EH(session, "wait for relogin\n"); wait_event_interruptible(conn->ehwait, session->state == ISCSI_STATE_TERMINATE || session->state == ISCSI_STATE_LOGGED_IN || session->state == ISCSI_STATE_RECOVERY_FAILED); if (signal_pending(current)) flush_signals(current); mutex_lock(&session->eh_mutex); spin_lock_bh(&session->frwd_lock); if (session->state == ISCSI_STATE_LOGGED_IN) { ISCSI_DBG_EH(session, "session reset succeeded for %s,%s\n", session->targetname, conn->persistent_address); } else goto failed; spin_unlock_bh(&session->frwd_lock); mutex_unlock(&session->eh_mutex); return SUCCESS; } EXPORT_SYMBOL_GPL(iscsi_eh_session_reset); static void iscsi_prep_tgt_reset_pdu(struct scsi_cmnd *sc, struct iscsi_tm *hdr) { memset(hdr, 0, sizeof(*hdr)); hdr->opcode = ISCSI_OP_SCSI_TMFUNC | ISCSI_OP_IMMEDIATE; hdr->flags = ISCSI_TM_FUNC_TARGET_WARM_RESET & ISCSI_FLAG_TM_FUNC_MASK; hdr->flags |= ISCSI_FLAG_CMD_FINAL; hdr->rtt = RESERVED_ITT; } /** * iscsi_eh_target_reset - reset target * @sc: scsi command * * This will attempt to send a warm target reset. */ int iscsi_eh_target_reset(struct scsi_cmnd *sc) { struct iscsi_cls_session *cls_session; struct iscsi_session *session; struct iscsi_conn *conn; struct iscsi_tm *hdr; int rc = FAILED; cls_session = starget_to_session(scsi_target(sc->device)); session = cls_session->dd_data; ISCSI_DBG_EH(session, "tgt Reset [sc %p tgt %s]\n", sc, session->targetname); mutex_lock(&session->eh_mutex); spin_lock_bh(&session->frwd_lock); /* * Just check if we are not logged in. We cannot check for * the phase because the reset could come from a ioctl. */ if (!session->leadconn || session->state != ISCSI_STATE_LOGGED_IN) goto unlock; conn = session->leadconn; /* only have one tmf outstanding at a time */ if (conn->tmf_state != TMF_INITIAL) goto unlock; conn->tmf_state = TMF_QUEUED; hdr = &conn->tmhdr; iscsi_prep_tgt_reset_pdu(sc, hdr); if (iscsi_exec_task_mgmt_fn(conn, hdr, session->age, session->tgt_reset_timeout)) { rc = FAILED; goto unlock; } switch (conn->tmf_state) { case TMF_SUCCESS: break; case TMF_TIMEDOUT: spin_unlock_bh(&session->frwd_lock); iscsi_conn_failure(conn, ISCSI_ERR_SCSI_EH_SESSION_RST); goto done; default: conn->tmf_state = TMF_INITIAL; goto unlock; } rc = SUCCESS; spin_unlock_bh(&session->frwd_lock); iscsi_suspend_tx(conn); spin_lock_bh(&session->frwd_lock); memset(hdr, 0, sizeof(*hdr)); fail_scsi_tasks(conn, -1, DID_ERROR); conn->tmf_state = TMF_INITIAL; spin_unlock_bh(&session->frwd_lock); iscsi_start_tx(conn); goto done; unlock: spin_unlock_bh(&session->frwd_lock); done: ISCSI_DBG_EH(session, "tgt %s reset result = %s\n", session->targetname, rc == SUCCESS ? "SUCCESS" : "FAILED"); mutex_unlock(&session->eh_mutex); return rc; } EXPORT_SYMBOL_GPL(iscsi_eh_target_reset); /** * iscsi_eh_recover_target - reset target and possibly the session * @sc: scsi command * * This will attempt to send a warm target reset. If that fails, * we will escalate to ERL0 session recovery. */ int iscsi_eh_recover_target(struct scsi_cmnd *sc) { int rc; rc = iscsi_eh_target_reset(sc); if (rc == FAILED) rc = iscsi_eh_session_reset(sc); return rc; } EXPORT_SYMBOL_GPL(iscsi_eh_recover_target); /* * Pre-allocate a pool of @max items of @item_size. By default, the pool * should be accessed via kfifo_{get,put} on q->queue. * Optionally, the caller can obtain the array of object pointers * by passing in a non-NULL @items pointer */ int iscsi_pool_init(struct iscsi_pool *q, int max, void ***items, int item_size) { int i, num_arrays = 1; memset(q, 0, sizeof(*q)); q->max = max; /* If the user passed an items pointer, he wants a copy of * the array. */ if (items) num_arrays++; q->pool = kzalloc(num_arrays * max * sizeof(void*), GFP_KERNEL); if (q->pool == NULL) return -ENOMEM; kfifo_init(&q->queue, (void*)q->pool, max * sizeof(void*)); for (i = 0; i < max; i++) { q->pool[i] = kzalloc(item_size, GFP_KERNEL); if (q->pool[i] == NULL) { q->max = i; goto enomem; } kfifo_in(&q->queue, (void*)&q->pool[i], sizeof(void*)); } if (items) { *items = q->pool + max; memcpy(*items, q->pool, max * sizeof(void *)); } return 0; enomem: iscsi_pool_free(q); return -ENOMEM; } EXPORT_SYMBOL_GPL(iscsi_pool_init); void iscsi_pool_free(struct iscsi_pool *q) { int i; for (i = 0; i < q->max; i++) kfree(q->pool[i]); kfree(q->pool); } EXPORT_SYMBOL_GPL(iscsi_pool_free); /** * iscsi_host_add - add host to system * @shost: scsi host * @pdev: parent device * * This should be called by partial offload and software iscsi drivers * to add a host to the system. */ int iscsi_host_add(struct Scsi_Host *shost, struct device *pdev) { if (!shost->can_queue) shost->can_queue = ISCSI_DEF_XMIT_CMDS_MAX; if (!shost->cmd_per_lun) shost->cmd_per_lun = ISCSI_DEF_CMD_PER_LUN; if (!shost->transportt->eh_timed_out) shost->transportt->eh_timed_out = iscsi_eh_cmd_timed_out; return scsi_add_host(shost, pdev); } EXPORT_SYMBOL_GPL(iscsi_host_add); /** * iscsi_host_alloc - allocate a host and driver data * @sht: scsi host template * @dd_data_size: driver host data size * @xmit_can_sleep: bool indicating if LLD will queue IO from a work queue * * This should be called by partial offload and software iscsi drivers. * To access the driver specific memory use the iscsi_host_priv() macro. */ struct Scsi_Host *iscsi_host_alloc(struct scsi_host_template *sht, int dd_data_size, bool xmit_can_sleep) { struct Scsi_Host *shost; struct iscsi_host *ihost; shost = scsi_host_alloc(sht, sizeof(struct iscsi_host) + dd_data_size); if (!shost) return NULL; ihost = shost_priv(shost); if (xmit_can_sleep) { snprintf(ihost->workq_name, sizeof(ihost->workq_name), "iscsi_q_%d", shost->host_no); ihost->workq = create_singlethread_workqueue(ihost->workq_name); if (!ihost->workq) goto free_host; } spin_lock_init(&ihost->lock); ihost->state = ISCSI_HOST_SETUP; ihost->num_sessions = 0; init_waitqueue_head(&ihost->session_removal_wq); return shost; free_host: scsi_host_put(shost); return NULL; } EXPORT_SYMBOL_GPL(iscsi_host_alloc); static void iscsi_notify_host_removed(struct iscsi_cls_session *cls_session) { iscsi_session_failure(cls_session->dd_data, ISCSI_ERR_INVALID_HOST); } /** * iscsi_host_remove - remove host and sessions * @shost: scsi host * * If there are any sessions left, this will initiate the removal and wait * for the completion. */ void iscsi_host_remove(struct Scsi_Host *shost) { struct iscsi_host *ihost = shost_priv(shost); unsigned long flags; spin_lock_irqsave(&ihost->lock, flags); ihost->state = ISCSI_HOST_REMOVED; spin_unlock_irqrestore(&ihost->lock, flags); iscsi_host_for_each_session(shost, iscsi_notify_host_removed); wait_event_interruptible(ihost->session_removal_wq, ihost->num_sessions == 0); if (signal_pending(current)) flush_signals(current); scsi_remove_host(shost); if (ihost->workq) destroy_workqueue(ihost->workq); } EXPORT_SYMBOL_GPL(iscsi_host_remove); void iscsi_host_free(struct Scsi_Host *shost) { struct iscsi_host *ihost = shost_priv(shost); kfree(ihost->netdev); kfree(ihost->hwaddress); kfree(ihost->initiatorname); scsi_host_put(shost); } EXPORT_SYMBOL_GPL(iscsi_host_free); static void iscsi_host_dec_session_cnt(struct Scsi_Host *shost) { struct iscsi_host *ihost = shost_priv(shost); unsigned long flags; shost = scsi_host_get(shost); if (!shost) { printk(KERN_ERR "Invalid state. Cannot notify host removal " "of session teardown event because host already " "removed.\n"); return; } spin_lock_irqsave(&ihost->lock, flags); ihost->num_sessions--; if (ihost->num_sessions == 0) wake_up(&ihost->session_removal_wq); spin_unlock_irqrestore(&ihost->lock, flags); scsi_host_put(shost); } /** * iscsi_session_setup - create iscsi cls session and host and session * @iscsit: iscsi transport template * @shost: scsi host * @cmds_max: session can queue * @cmd_task_size: LLD task private data size * @initial_cmdsn: initial CmdSN * * This can be used by software iscsi_transports that allocate * a session per scsi host. * * Callers should set cmds_max to the largest total numer (mgmt + scsi) of * tasks they support. The iscsi layer reserves ISCSI_MGMT_CMDS_MAX tasks * for nop handling and login/logout requests. */ struct iscsi_cls_session * iscsi_session_setup(struct iscsi_transport *iscsit, struct Scsi_Host *shost, uint16_t cmds_max, int dd_size, int cmd_task_size, uint32_t initial_cmdsn, unsigned int id) { struct iscsi_host *ihost = shost_priv(shost); struct iscsi_session *session; struct iscsi_cls_session *cls_session; int cmd_i, scsi_cmds, total_cmds = cmds_max; unsigned long flags; spin_lock_irqsave(&ihost->lock, flags); if (ihost->state == ISCSI_HOST_REMOVED) { spin_unlock_irqrestore(&ihost->lock, flags); return NULL; } ihost->num_sessions++; spin_unlock_irqrestore(&ihost->lock, flags); if (!total_cmds) total_cmds = ISCSI_DEF_XMIT_CMDS_MAX; /* * The iscsi layer needs some tasks for nop handling and tmfs, * so the cmds_max must at least be greater than ISCSI_MGMT_CMDS_MAX * + 1 command for scsi IO. */ if (total_cmds < ISCSI_TOTAL_CMDS_MIN) { printk(KERN_ERR "iscsi: invalid can_queue of %d. can_queue " "must be a power of two that is at least %d.\n", total_cmds, ISCSI_TOTAL_CMDS_MIN); goto dec_session_count; } if (total_cmds > ISCSI_TOTAL_CMDS_MAX) { printk(KERN_ERR "iscsi: invalid can_queue of %d. can_queue " "must be a power of 2 less than or equal to %d.\n", cmds_max, ISCSI_TOTAL_CMDS_MAX); total_cmds = ISCSI_TOTAL_CMDS_MAX; } if (!is_power_of_2(total_cmds)) { printk(KERN_ERR "iscsi: invalid can_queue of %d. can_queue " "must be a power of 2.\n", total_cmds); total_cmds = rounddown_pow_of_two(total_cmds); if (total_cmds < ISCSI_TOTAL_CMDS_MIN) return NULL; printk(KERN_INFO "iscsi: Rounding can_queue to %d.\n", total_cmds); } scsi_cmds = total_cmds - ISCSI_MGMT_CMDS_MAX; cls_session = iscsi_alloc_session(shost, iscsit, sizeof(struct iscsi_session) + dd_size); if (!cls_session) goto dec_session_count; session = cls_session->dd_data; session->cls_session = cls_session; session->host = shost; session->state = ISCSI_STATE_FREE; session->fast_abort = 1; session->tgt_reset_timeout = 30; session->lu_reset_timeout = 15; session->abort_timeout = 10; session->scsi_cmds_max = scsi_cmds; session->cmds_max = total_cmds; session->queued_cmdsn = session->cmdsn = initial_cmdsn; session->exp_cmdsn = initial_cmdsn + 1; session->max_cmdsn = initial_cmdsn + 1; session->max_r2t = 1; session->tt = iscsit; session->dd_data = cls_session->dd_data + sizeof(*session); mutex_init(&session->eh_mutex); spin_lock_init(&session->frwd_lock); spin_lock_init(&session->back_lock); /* initialize SCSI PDU commands pool */ if (iscsi_pool_init(&session->cmdpool, session->cmds_max, (void***)&session->cmds, cmd_task_size + sizeof(struct iscsi_task))) goto cmdpool_alloc_fail; /* pre-format cmds pool with ITT */ for (cmd_i = 0; cmd_i < session->cmds_max; cmd_i++) { struct iscsi_task *task = session->cmds[cmd_i]; if (cmd_task_size) task->dd_data = &task[1]; task->itt = cmd_i; task->state = ISCSI_TASK_FREE; INIT_LIST_HEAD(&task->running); } if (!try_module_get(iscsit->owner)) goto module_get_fail; if (iscsi_add_session(cls_session, id)) goto cls_session_fail; return cls_session; cls_session_fail: module_put(iscsit->owner); module_get_fail: iscsi_pool_free(&session->cmdpool); cmdpool_alloc_fail: iscsi_free_session(cls_session); dec_session_count: iscsi_host_dec_session_cnt(shost); return NULL; } EXPORT_SYMBOL_GPL(iscsi_session_setup); /** * iscsi_session_teardown - destroy session, host, and cls_session * @cls_session: iscsi session * * The driver must have called iscsi_remove_session before * calling this. */ void iscsi_session_teardown(struct iscsi_cls_session *cls_session) { struct iscsi_session *session = cls_session->dd_data; struct module *owner = cls_session->transport->owner; struct Scsi_Host *shost = session->host; iscsi_pool_free(&session->cmdpool); kfree(session->password); kfree(session->password_in); kfree(session->username); kfree(session->username_in); kfree(session->targetname); kfree(session->targetalias); kfree(session->initiatorname); kfree(session->boot_root); kfree(session->boot_nic); kfree(session->boot_target); kfree(session->ifacename); kfree(session->portal_type); kfree(session->discovery_parent_type); iscsi_destroy_session(cls_session); iscsi_host_dec_session_cnt(shost); module_put(owner); } EXPORT_SYMBOL_GPL(iscsi_session_teardown); /** * iscsi_conn_setup - create iscsi_cls_conn and iscsi_conn * @cls_session: iscsi_cls_session * @dd_size: private driver data size * @conn_idx: cid */ struct iscsi_cls_conn * iscsi_conn_setup(struct iscsi_cls_session *cls_session, int dd_size, uint32_t conn_idx) { struct iscsi_session *session = cls_session->dd_data; struct iscsi_conn *conn; struct iscsi_cls_conn *cls_conn; char *data; cls_conn = iscsi_create_conn(cls_session, sizeof(*conn) + dd_size, conn_idx); if (!cls_conn) return NULL; conn = cls_conn->dd_data; memset(conn, 0, sizeof(*conn) + dd_size); conn->dd_data = cls_conn->dd_data + sizeof(*conn); conn->session = session; conn->cls_conn = cls_conn; conn->c_stage = ISCSI_CONN_INITIAL_STAGE; conn->id = conn_idx; conn->exp_statsn = 0; conn->tmf_state = TMF_INITIAL; init_timer(&conn->transport_timer); conn->transport_timer.data = (unsigned long)conn; conn->transport_timer.function = iscsi_check_transport_timeouts; INIT_LIST_HEAD(&conn->mgmtqueue); INIT_LIST_HEAD(&conn->cmdqueue); INIT_LIST_HEAD(&conn->requeue); INIT_WORK(&conn->xmitwork, iscsi_xmitworker); /* allocate login_task used for the login/text sequences */ spin_lock_bh(&session->frwd_lock); if (!kfifo_out(&session->cmdpool.queue, (void*)&conn->login_task, sizeof(void*))) { spin_unlock_bh(&session->frwd_lock); goto login_task_alloc_fail; } spin_unlock_bh(&session->frwd_lock); data = (char *) __get_free_pages(GFP_KERNEL, get_order(ISCSI_DEF_MAX_RECV_SEG_LEN)); if (!data) goto login_task_data_alloc_fail; conn->login_task->data = conn->data = data; init_timer(&conn->tmf_timer); init_waitqueue_head(&conn->ehwait); return cls_conn; login_task_data_alloc_fail: kfifo_in(&session->cmdpool.queue, (void*)&conn->login_task, sizeof(void*)); login_task_alloc_fail: iscsi_destroy_conn(cls_conn); return NULL; } EXPORT_SYMBOL_GPL(iscsi_conn_setup); /** * iscsi_conn_teardown - teardown iscsi connection * cls_conn: iscsi class connection * * TODO: we may need to make this into a two step process * like scsi-mls remove + put host */ void iscsi_conn_teardown(struct iscsi_cls_conn *cls_conn) { struct iscsi_conn *conn = cls_conn->dd_data; struct iscsi_session *session = conn->session; unsigned long flags; del_timer_sync(&conn->transport_timer); spin_lock_bh(&session->frwd_lock); conn->c_stage = ISCSI_CONN_CLEANUP_WAIT; if (session->leadconn == conn) { /* * leading connection? then give up on recovery. */ session->state = ISCSI_STATE_TERMINATE; wake_up(&conn->ehwait); } spin_unlock_bh(&session->frwd_lock); /* * Block until all in-progress commands for this connection * time out or fail. */ for (;;) { spin_lock_irqsave(session->host->host_lock, flags); if (!atomic_read(&session->host->host_busy)) { /* OK for ERL == 0 */ spin_unlock_irqrestore(session->host->host_lock, flags); break; } spin_unlock_irqrestore(session->host->host_lock, flags); msleep_interruptible(500); iscsi_conn_printk(KERN_INFO, conn, "iscsi conn_destroy(): " "host_busy %d host_failed %d\n", atomic_read(&session->host->host_busy), session->host->host_failed); /* * force eh_abort() to unblock */ wake_up(&conn->ehwait); } /* flush queued up work because we free the connection below */ iscsi_suspend_tx(conn); spin_lock_bh(&session->frwd_lock); free_pages((unsigned long) conn->data, get_order(ISCSI_DEF_MAX_RECV_SEG_LEN)); kfree(conn->persistent_address); kfree(conn->local_ipaddr); /* regular RX path uses back_lock */ spin_lock_bh(&session->back_lock); kfifo_in(&session->cmdpool.queue, (void*)&conn->login_task, sizeof(void*)); spin_unlock_bh(&session->back_lock); if (session->leadconn == conn) session->leadconn = NULL; spin_unlock_bh(&session->frwd_lock); iscsi_destroy_conn(cls_conn); } EXPORT_SYMBOL_GPL(iscsi_conn_teardown); int iscsi_conn_start(struct iscsi_cls_conn *cls_conn) { struct iscsi_conn *conn = cls_conn->dd_data; struct iscsi_session *session = conn->session; if (!session) { iscsi_conn_printk(KERN_ERR, conn, "can't start unbound connection\n"); return -EPERM; } if ((session->imm_data_en || !session->initial_r2t_en) && session->first_burst > session->max_burst) { iscsi_conn_printk(KERN_INFO, conn, "invalid burst lengths: " "first_burst %d max_burst %d\n", session->first_burst, session->max_burst); return -EINVAL; } if (conn->ping_timeout && !conn->recv_timeout) { iscsi_conn_printk(KERN_ERR, conn, "invalid recv timeout of " "zero. Using 5 seconds\n."); conn->recv_timeout = 5; } if (conn->recv_timeout && !conn->ping_timeout) { iscsi_conn_printk(KERN_ERR, conn, "invalid ping timeout of " "zero. Using 5 seconds.\n"); conn->ping_timeout = 5; } spin_lock_bh(&session->frwd_lock); conn->c_stage = ISCSI_CONN_STARTED; session->state = ISCSI_STATE_LOGGED_IN; session->queued_cmdsn = session->cmdsn; conn->last_recv = jiffies; conn->last_ping = jiffies; if (conn->recv_timeout && conn->ping_timeout) mod_timer(&conn->transport_timer, jiffies + (conn->recv_timeout * HZ)); switch(conn->stop_stage) { case STOP_CONN_RECOVER: /* * unblock eh_abort() if it is blocked. re-try all * commands after successful recovery */ conn->stop_stage = 0; conn->tmf_state = TMF_INITIAL; session->age++; if (session->age == 16) session->age = 0; break; case STOP_CONN_TERM: conn->stop_stage = 0; break; default: break; } spin_unlock_bh(&session->frwd_lock); iscsi_unblock_session(session->cls_session); wake_up(&conn->ehwait); return 0; } EXPORT_SYMBOL_GPL(iscsi_conn_start); static void fail_mgmt_tasks(struct iscsi_session *session, struct iscsi_conn *conn) { struct iscsi_task *task; int i, state; for (i = 0; i < conn->session->cmds_max; i++) { task = conn->session->cmds[i]; if (task->sc) continue; if (task->state == ISCSI_TASK_FREE) continue; ISCSI_DBG_SESSION(conn->session, "failing mgmt itt 0x%x state %d\n", task->itt, task->state); state = ISCSI_TASK_ABRT_SESS_RECOV; if (task->state == ISCSI_TASK_PENDING) state = ISCSI_TASK_COMPLETED; iscsi_complete_task(task, state); } } static void iscsi_start_session_recovery(struct iscsi_session *session, struct iscsi_conn *conn, int flag) { int old_stop_stage; mutex_lock(&session->eh_mutex); spin_lock_bh(&session->frwd_lock); if (conn->stop_stage == STOP_CONN_TERM) { spin_unlock_bh(&session->frwd_lock); mutex_unlock(&session->eh_mutex); return; } /* * When this is called for the in_login state, we only want to clean * up the login task and connection. We do not need to block and set * the recovery state again */ if (flag == STOP_CONN_TERM) session->state = ISCSI_STATE_TERMINATE; else if (conn->stop_stage != STOP_CONN_RECOVER) session->state = ISCSI_STATE_IN_RECOVERY; old_stop_stage = conn->stop_stage; conn->stop_stage = flag; spin_unlock_bh(&session->frwd_lock); del_timer_sync(&conn->transport_timer); iscsi_suspend_tx(conn); spin_lock_bh(&session->frwd_lock); conn->c_stage = ISCSI_CONN_STOPPED; spin_unlock_bh(&session->frwd_lock); /* * for connection level recovery we should not calculate * header digest. conn->hdr_size used for optimization * in hdr_extract() and will be re-negotiated at * set_param() time. */ if (flag == STOP_CONN_RECOVER) { conn->hdrdgst_en = 0; conn->datadgst_en = 0; if (session->state == ISCSI_STATE_IN_RECOVERY && old_stop_stage != STOP_CONN_RECOVER) { ISCSI_DBG_SESSION(session, "blocking session\n"); iscsi_block_session(session->cls_session); } } /* * flush queues. */ spin_lock_bh(&session->frwd_lock); fail_scsi_tasks(conn, -1, DID_TRANSPORT_DISRUPTED); fail_mgmt_tasks(session, conn); memset(&conn->tmhdr, 0, sizeof(conn->tmhdr)); spin_unlock_bh(&session->frwd_lock); mutex_unlock(&session->eh_mutex); } void iscsi_conn_stop(struct iscsi_cls_conn *cls_conn, int flag) { struct iscsi_conn *conn = cls_conn->dd_data; struct iscsi_session *session = conn->session; switch (flag) { case STOP_CONN_RECOVER: case STOP_CONN_TERM: iscsi_start_session_recovery(session, conn, flag); break; default: iscsi_conn_printk(KERN_ERR, conn, "invalid stop flag %d\n", flag); } } EXPORT_SYMBOL_GPL(iscsi_conn_stop); int iscsi_conn_bind(struct iscsi_cls_session *cls_session, struct iscsi_cls_conn *cls_conn, int is_leading) { struct iscsi_session *session = cls_session->dd_data; struct iscsi_conn *conn = cls_conn->dd_data; spin_lock_bh(&session->frwd_lock); if (is_leading) session->leadconn = conn; spin_unlock_bh(&session->frwd_lock); /* * Unblock xmitworker(), Login Phase will pass through. */ clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_rx); clear_bit(ISCSI_SUSPEND_BIT, &conn->suspend_tx); return 0; } EXPORT_SYMBOL_GPL(iscsi_conn_bind); int iscsi_switch_str_param(char **param, char *new_val_buf) { char *new_val; if (*param) { if (!strcmp(*param, new_val_buf)) return 0; } new_val = kstrdup(new_val_buf, GFP_NOIO); if (!new_val) return -ENOMEM; kfree(*param); *param = new_val; return 0; } EXPORT_SYMBOL_GPL(iscsi_switch_str_param); int iscsi_set_param(struct iscsi_cls_conn *cls_conn, enum iscsi_param param, char *buf, int buflen) { struct iscsi_conn *conn = cls_conn->dd_data; struct iscsi_session *session = conn->session; int val; switch(param) { case ISCSI_PARAM_FAST_ABORT: sscanf(buf, "%d", &session->fast_abort); break; case ISCSI_PARAM_ABORT_TMO: sscanf(buf, "%d", &session->abort_timeout); break; case ISCSI_PARAM_LU_RESET_TMO: sscanf(buf, "%d", &session->lu_reset_timeout); break; case ISCSI_PARAM_TGT_RESET_TMO: sscanf(buf, "%d", &session->tgt_reset_timeout); break; case ISCSI_PARAM_PING_TMO: sscanf(buf, "%d", &conn->ping_timeout); break; case ISCSI_PARAM_RECV_TMO: sscanf(buf, "%d", &conn->recv_timeout); break; case ISCSI_PARAM_MAX_RECV_DLENGTH: sscanf(buf, "%d", &conn->max_recv_dlength); break; case ISCSI_PARAM_MAX_XMIT_DLENGTH: sscanf(buf, "%d", &conn->max_xmit_dlength); break; case ISCSI_PARAM_HDRDGST_EN: sscanf(buf, "%d", &conn->hdrdgst_en); break; case ISCSI_PARAM_DATADGST_EN: sscanf(buf, "%d", &conn->datadgst_en); break; case ISCSI_PARAM_INITIAL_R2T_EN: sscanf(buf, "%d", &session->initial_r2t_en); break; case ISCSI_PARAM_MAX_R2T: sscanf(buf, "%hu", &session->max_r2t); break; case ISCSI_PARAM_IMM_DATA_EN: sscanf(buf, "%d", &session->imm_data_en); break; case ISCSI_PARAM_FIRST_BURST: sscanf(buf, "%d", &session->first_burst); break; case ISCSI_PARAM_MAX_BURST: sscanf(buf, "%d", &session->max_burst); break; case ISCSI_PARAM_PDU_INORDER_EN: sscanf(buf, "%d", &session->pdu_inorder_en); break; case ISCSI_PARAM_DATASEQ_INORDER_EN: sscanf(buf, "%d", &session->dataseq_inorder_en); break; case ISCSI_PARAM_ERL: sscanf(buf, "%d", &session->erl); break; case ISCSI_PARAM_EXP_STATSN: sscanf(buf, "%u", &conn->exp_statsn); break; case ISCSI_PARAM_USERNAME: return iscsi_switch_str_param(&session->username, buf); case ISCSI_PARAM_USERNAME_IN: return iscsi_switch_str_param(&session->username_in, buf); case ISCSI_PARAM_PASSWORD: return iscsi_switch_str_param(&session->password, buf); case ISCSI_PARAM_PASSWORD_IN: return iscsi_switch_str_param(&session->password_in, buf); case ISCSI_PARAM_TARGET_NAME: return iscsi_switch_str_param(&session->targetname, buf); case ISCSI_PARAM_TARGET_ALIAS: return iscsi_switch_str_param(&session->targetalias, buf); case ISCSI_PARAM_TPGT: sscanf(buf, "%d", &session->tpgt); break; case ISCSI_PARAM_PERSISTENT_PORT: sscanf(buf, "%d", &conn->persistent_port); break; case ISCSI_PARAM_PERSISTENT_ADDRESS: return iscsi_switch_str_param(&conn->persistent_address, buf); case ISCSI_PARAM_IFACE_NAME: return iscsi_switch_str_param(&session->ifacename, buf); case ISCSI_PARAM_INITIATOR_NAME: return iscsi_switch_str_param(&session->initiatorname, buf); case ISCSI_PARAM_BOOT_ROOT: return iscsi_switch_str_param(&session->boot_root, buf); case ISCSI_PARAM_BOOT_NIC: return iscsi_switch_str_param(&session->boot_nic, buf); case ISCSI_PARAM_BOOT_TARGET: return iscsi_switch_str_param(&session->boot_target, buf); case ISCSI_PARAM_PORTAL_TYPE: return iscsi_switch_str_param(&session->portal_type, buf); case ISCSI_PARAM_DISCOVERY_PARENT_TYPE: return iscsi_switch_str_param(&session->discovery_parent_type, buf); case ISCSI_PARAM_DISCOVERY_SESS: sscanf(buf, "%d", &val); session->discovery_sess = !!val; break; case ISCSI_PARAM_LOCAL_IPADDR: return iscsi_switch_str_param(&conn->local_ipaddr, buf); default: return -ENOSYS; } return 0; } EXPORT_SYMBOL_GPL(iscsi_set_param); int iscsi_session_get_param(struct iscsi_cls_session *cls_session, enum iscsi_param param, char *buf) { struct iscsi_session *session = cls_session->dd_data; int len; switch(param) { case ISCSI_PARAM_FAST_ABORT: len = sprintf(buf, "%d\n", session->fast_abort); break; case ISCSI_PARAM_ABORT_TMO: len = sprintf(buf, "%d\n", session->abort_timeout); break; case ISCSI_PARAM_LU_RESET_TMO: len = sprintf(buf, "%d\n", session->lu_reset_timeout); break; case ISCSI_PARAM_TGT_RESET_TMO: len = sprintf(buf, "%d\n", session->tgt_reset_timeout); break; case ISCSI_PARAM_INITIAL_R2T_EN: len = sprintf(buf, "%d\n", session->initial_r2t_en); break; case ISCSI_PARAM_MAX_R2T: len = sprintf(buf, "%hu\n", session->max_r2t); break; case ISCSI_PARAM_IMM_DATA_EN: len = sprintf(buf, "%d\n", session->imm_data_en); break; case ISCSI_PARAM_FIRST_BURST: len = sprintf(buf, "%u\n", session->first_burst); break; case ISCSI_PARAM_MAX_BURST: len = sprintf(buf, "%u\n", session->max_burst); break; case ISCSI_PARAM_PDU_INORDER_EN: len = sprintf(buf, "%d\n", session->pdu_inorder_en); break; case ISCSI_PARAM_DATASEQ_INORDER_EN: len = sprintf(buf, "%d\n", session->dataseq_inorder_en); break; case ISCSI_PARAM_DEF_TASKMGMT_TMO: len = sprintf(buf, "%d\n", session->def_taskmgmt_tmo); break; case ISCSI_PARAM_ERL: len = sprintf(buf, "%d\n", session->erl); break; case ISCSI_PARAM_TARGET_NAME: len = sprintf(buf, "%s\n", session->targetname); break; case ISCSI_PARAM_TARGET_ALIAS: len = sprintf(buf, "%s\n", session->targetalias); break; case ISCSI_PARAM_TPGT: len = sprintf(buf, "%d\n", session->tpgt); break; case ISCSI_PARAM_USERNAME: len = sprintf(buf, "%s\n", session->username); break; case ISCSI_PARAM_USERNAME_IN: len = sprintf(buf, "%s\n", session->username_in); break; case ISCSI_PARAM_PASSWORD: len = sprintf(buf, "%s\n", session->password); break; case ISCSI_PARAM_PASSWORD_IN: len = sprintf(buf, "%s\n", session->password_in); break; case ISCSI_PARAM_IFACE_NAME: len = sprintf(buf, "%s\n", session->ifacename); break; case ISCSI_PARAM_INITIATOR_NAME: len = sprintf(buf, "%s\n", session->initiatorname); break; case ISCSI_PARAM_BOOT_ROOT: len = sprintf(buf, "%s\n", session->boot_root); break; case ISCSI_PARAM_BOOT_NIC: len = sprintf(buf, "%s\n", session->boot_nic); break; case ISCSI_PARAM_BOOT_TARGET: len = sprintf(buf, "%s\n", session->boot_target); break; case ISCSI_PARAM_AUTO_SND_TGT_DISABLE: len = sprintf(buf, "%u\n", session->auto_snd_tgt_disable); break; case ISCSI_PARAM_DISCOVERY_SESS: len = sprintf(buf, "%u\n", session->discovery_sess); break; case ISCSI_PARAM_PORTAL_TYPE: len = sprintf(buf, "%s\n", session->portal_type); break; case ISCSI_PARAM_CHAP_AUTH_EN: len = sprintf(buf, "%u\n", session->chap_auth_en); break; case ISCSI_PARAM_DISCOVERY_LOGOUT_EN: len = sprintf(buf, "%u\n", session->discovery_logout_en); break; case ISCSI_PARAM_BIDI_CHAP_EN: len = sprintf(buf, "%u\n", session->bidi_chap_en); break; case ISCSI_PARAM_DISCOVERY_AUTH_OPTIONAL: len = sprintf(buf, "%u\n", session->discovery_auth_optional); break; case ISCSI_PARAM_DEF_TIME2WAIT: len = sprintf(buf, "%d\n", session->time2wait); break; case ISCSI_PARAM_DEF_TIME2RETAIN: len = sprintf(buf, "%d\n", session->time2retain); break; case ISCSI_PARAM_TSID: len = sprintf(buf, "%u\n", session->tsid); break; case ISCSI_PARAM_ISID: len = sprintf(buf, "%02x%02x%02x%02x%02x%02x\n", session->isid[0], session->isid[1], session->isid[2], session->isid[3], session->isid[4], session->isid[5]); break; case ISCSI_PARAM_DISCOVERY_PARENT_IDX: len = sprintf(buf, "%u\n", session->discovery_parent_idx); break; case ISCSI_PARAM_DISCOVERY_PARENT_TYPE: if (session->discovery_parent_type) len = sprintf(buf, "%s\n", session->discovery_parent_type); else len = sprintf(buf, "\n"); break; default: return -ENOSYS; } return len; } EXPORT_SYMBOL_GPL(iscsi_session_get_param); int iscsi_conn_get_addr_param(struct sockaddr_storage *addr, enum iscsi_param param, char *buf) { struct sockaddr_in6 *sin6 = NULL; struct sockaddr_in *sin = NULL; int len; switch (addr->ss_family) { case AF_INET: sin = (struct sockaddr_in *)addr; break; case AF_INET6: sin6 = (struct sockaddr_in6 *)addr; break; default: return -EINVAL; } switch (param) { case ISCSI_PARAM_CONN_ADDRESS: case ISCSI_HOST_PARAM_IPADDRESS: if (sin) len = sprintf(buf, "%pI4\n", &sin->sin_addr.s_addr); else len = sprintf(buf, "%pI6\n", &sin6->sin6_addr); break; case ISCSI_PARAM_CONN_PORT: case ISCSI_PARAM_LOCAL_PORT: if (sin) len = sprintf(buf, "%hu\n", be16_to_cpu(sin->sin_port)); else len = sprintf(buf, "%hu\n", be16_to_cpu(sin6->sin6_port)); break; default: return -EINVAL; } return len; } EXPORT_SYMBOL_GPL(iscsi_conn_get_addr_param); int iscsi_conn_get_param(struct iscsi_cls_conn *cls_conn, enum iscsi_param param, char *buf) { struct iscsi_conn *conn = cls_conn->dd_data; int len; switch(param) { case ISCSI_PARAM_PING_TMO: len = sprintf(buf, "%u\n", conn->ping_timeout); break; case ISCSI_PARAM_RECV_TMO: len = sprintf(buf, "%u\n", conn->recv_timeout); break; case ISCSI_PARAM_MAX_RECV_DLENGTH: len = sprintf(buf, "%u\n", conn->max_recv_dlength); break; case ISCSI_PARAM_MAX_XMIT_DLENGTH: len = sprintf(buf, "%u\n", conn->max_xmit_dlength); break; case ISCSI_PARAM_HDRDGST_EN: len = sprintf(buf, "%d\n", conn->hdrdgst_en); break; case ISCSI_PARAM_DATADGST_EN: len = sprintf(buf, "%d\n", conn->datadgst_en); break; case ISCSI_PARAM_IFMARKER_EN: len = sprintf(buf, "%d\n", conn->ifmarker_en); break; case ISCSI_PARAM_OFMARKER_EN: len = sprintf(buf, "%d\n", conn->ofmarker_en); break; case ISCSI_PARAM_EXP_STATSN: len = sprintf(buf, "%u\n", conn->exp_statsn); break; case ISCSI_PARAM_PERSISTENT_PORT: len = sprintf(buf, "%d\n", conn->persistent_port); break; case ISCSI_PARAM_PERSISTENT_ADDRESS: len = sprintf(buf, "%s\n", conn->persistent_address); break; case ISCSI_PARAM_STATSN: len = sprintf(buf, "%u\n", conn->statsn); break; case ISCSI_PARAM_MAX_SEGMENT_SIZE: len = sprintf(buf, "%u\n", conn->max_segment_size); break; case ISCSI_PARAM_KEEPALIVE_TMO: len = sprintf(buf, "%u\n", conn->keepalive_tmo); break; case ISCSI_PARAM_LOCAL_PORT: len = sprintf(buf, "%u\n", conn->local_port); break; case ISCSI_PARAM_TCP_TIMESTAMP_STAT: len = sprintf(buf, "%u\n", conn->tcp_timestamp_stat); break; case ISCSI_PARAM_TCP_NAGLE_DISABLE: len = sprintf(buf, "%u\n", conn->tcp_nagle_disable); break; case ISCSI_PARAM_TCP_WSF_DISABLE: len = sprintf(buf, "%u\n", conn->tcp_wsf_disable); break; case ISCSI_PARAM_TCP_TIMER_SCALE: len = sprintf(buf, "%u\n", conn->tcp_timer_scale); break; case ISCSI_PARAM_TCP_TIMESTAMP_EN: len = sprintf(buf, "%u\n", conn->tcp_timestamp_en); break; case ISCSI_PARAM_IP_FRAGMENT_DISABLE: len = sprintf(buf, "%u\n", conn->fragment_disable); break; case ISCSI_PARAM_IPV4_TOS: len = sprintf(buf, "%u\n", conn->ipv4_tos); break; case ISCSI_PARAM_IPV6_TC: len = sprintf(buf, "%u\n", conn->ipv6_traffic_class); break; case ISCSI_PARAM_IPV6_FLOW_LABEL: len = sprintf(buf, "%u\n", conn->ipv6_flow_label); break; case ISCSI_PARAM_IS_FW_ASSIGNED_IPV6: len = sprintf(buf, "%u\n", conn->is_fw_assigned_ipv6); break; case ISCSI_PARAM_TCP_XMIT_WSF: len = sprintf(buf, "%u\n", conn->tcp_xmit_wsf); break; case ISCSI_PARAM_TCP_RECV_WSF: len = sprintf(buf, "%u\n", conn->tcp_recv_wsf); break; case ISCSI_PARAM_LOCAL_IPADDR: len = sprintf(buf, "%s\n", conn->local_ipaddr); break; default: return -ENOSYS; } return len; } EXPORT_SYMBOL_GPL(iscsi_conn_get_param); int iscsi_host_get_param(struct Scsi_Host *shost, enum iscsi_host_param param, char *buf) { struct iscsi_host *ihost = shost_priv(shost); int len; switch (param) { case ISCSI_HOST_PARAM_NETDEV_NAME: len = sprintf(buf, "%s\n", ihost->netdev); break; case ISCSI_HOST_PARAM_HWADDRESS: len = sprintf(buf, "%s\n", ihost->hwaddress); break; case ISCSI_HOST_PARAM_INITIATOR_NAME: len = sprintf(buf, "%s\n", ihost->initiatorname); break; default: return -ENOSYS; } return len; } EXPORT_SYMBOL_GPL(iscsi_host_get_param); int iscsi_host_set_param(struct Scsi_Host *shost, enum iscsi_host_param param, char *buf, int buflen) { struct iscsi_host *ihost = shost_priv(shost); switch (param) { case ISCSI_HOST_PARAM_NETDEV_NAME: return iscsi_switch_str_param(&ihost->netdev, buf); case ISCSI_HOST_PARAM_HWADDRESS: return iscsi_switch_str_param(&ihost->hwaddress, buf); case ISCSI_HOST_PARAM_INITIATOR_NAME: return iscsi_switch_str_param(&ihost->initiatorname, buf); default: return -ENOSYS; } return 0; } EXPORT_SYMBOL_GPL(iscsi_host_set_param); MODULE_AUTHOR("Mike Christie"); MODULE_DESCRIPTION("iSCSI library functions"); MODULE_LICENSE("GPL");
gpl-2.0
MassStash/htc_pme_kernel_sense_6.0
drivers/gpu/drm/nouveau/nvif/object.c
461
7521
/* * Copyright 2014 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 <bskeggs@redhat.com> */ #include "object.h" #include "client.h" #include "driver.h" #include "ioctl.h" int nvif_object_ioctl(struct nvif_object *object, void *data, u32 size, void **hack) { struct nvif_client *client = nvif_client(object); union { struct nvif_ioctl_v0 v0; } *args = data; if (size >= sizeof(*args) && args->v0.version == 0) { args->v0.owner = NVIF_IOCTL_V0_OWNER_ANY; args->v0.path_nr = 0; while (args->v0.path_nr < ARRAY_SIZE(args->v0.path)) { args->v0.path[args->v0.path_nr++] = object->handle; if (object->parent == object) break; object = object->parent; } } else return -ENOSYS; return client->driver->ioctl(client->base.priv, client->super, data, size, hack); } int nvif_object_sclass(struct nvif_object *object, u32 *oclass, int count) { struct { struct nvif_ioctl_v0 ioctl; struct nvif_ioctl_sclass_v0 sclass; } *args; u32 size = count * sizeof(args->sclass.oclass[0]); int ret; if (!(args = kmalloc(sizeof(*args) + size, GFP_KERNEL))) return -ENOMEM; args->ioctl.version = 0; args->ioctl.type = NVIF_IOCTL_V0_SCLASS; args->sclass.version = 0; args->sclass.count = count; memcpy(args->sclass.oclass, oclass, size); ret = nvif_object_ioctl(object, args, sizeof(*args) + size, NULL); ret = ret ? ret : args->sclass.count; memcpy(oclass, args->sclass.oclass, size); kfree(args); return ret; } u32 nvif_object_rd(struct nvif_object *object, int size, u64 addr) { struct { struct nvif_ioctl_v0 ioctl; struct nvif_ioctl_rd_v0 rd; } args = { .ioctl.type = NVIF_IOCTL_V0_RD, .rd.size = size, .rd.addr = addr, }; int ret = nvif_object_ioctl(object, &args, sizeof(args), NULL); if (ret) { /*XXX: warn? */ return 0; } return args.rd.data; } void nvif_object_wr(struct nvif_object *object, int size, u64 addr, u32 data) { struct { struct nvif_ioctl_v0 ioctl; struct nvif_ioctl_wr_v0 wr; } args = { .ioctl.type = NVIF_IOCTL_V0_WR, .wr.size = size, .wr.addr = addr, .wr.data = data, }; int ret = nvif_object_ioctl(object, &args, sizeof(args), NULL); if (ret) { /*XXX: warn? */ } } int nvif_object_mthd(struct nvif_object *object, u32 mthd, void *data, u32 size) { struct { struct nvif_ioctl_v0 ioctl; struct nvif_ioctl_mthd_v0 mthd; } *args; u8 stack[128]; int ret; if (sizeof(*args) + size > sizeof(stack)) { if (!(args = kmalloc(sizeof(*args) + size, GFP_KERNEL))) return -ENOMEM; } else { args = (void *)stack; } args->ioctl.version = 0; args->ioctl.type = NVIF_IOCTL_V0_MTHD; args->mthd.version = 0; args->mthd.method = mthd; memcpy(args->mthd.data, data, size); ret = nvif_object_ioctl(object, args, sizeof(*args) + size, NULL); memcpy(data, args->mthd.data, size); if (args != (void *)stack) kfree(args); return ret; } void nvif_object_unmap(struct nvif_object *object) { if (object->map.size) { struct nvif_client *client = nvif_client(object); struct { struct nvif_ioctl_v0 ioctl; struct nvif_ioctl_unmap unmap; } args = { .ioctl.type = NVIF_IOCTL_V0_UNMAP, }; if (object->map.ptr) { client->driver->unmap(client, object->map.ptr, object->map.size); object->map.ptr = NULL; } nvif_object_ioctl(object, &args, sizeof(args), NULL); object->map.size = 0; } } int nvif_object_map(struct nvif_object *object) { struct nvif_client *client = nvif_client(object); struct { struct nvif_ioctl_v0 ioctl; struct nvif_ioctl_map_v0 map; } args = { .ioctl.type = NVIF_IOCTL_V0_MAP, }; int ret = nvif_object_ioctl(object, &args, sizeof(args), NULL); if (ret == 0) { object->map.size = args.map.length; object->map.ptr = client->driver->map(client, args.map.handle, object->map.size); if (ret = -ENOMEM, object->map.ptr) return 0; nvif_object_unmap(object); } return ret; } struct ctor { struct nvif_ioctl_v0 ioctl; struct nvif_ioctl_new_v0 new; }; void nvif_object_fini(struct nvif_object *object) { struct ctor *ctor = container_of(object->data, typeof(*ctor), new.data); if (object->parent) { struct { struct nvif_ioctl_v0 ioctl; struct nvif_ioctl_del del; } args = { .ioctl.type = NVIF_IOCTL_V0_DEL, }; nvif_object_unmap(object); nvif_object_ioctl(object, &args, sizeof(args), NULL); if (object->data) { object->size = 0; object->data = NULL; kfree(ctor); } nvif_object_ref(NULL, &object->parent); } } int nvif_object_init(struct nvif_object *parent, void (*dtor)(struct nvif_object *), u32 handle, u32 oclass, void *data, u32 size, struct nvif_object *object) { struct ctor *ctor; int ret = 0; object->parent = NULL; object->object = object; nvif_object_ref(parent, &object->parent); kref_init(&object->refcount); object->handle = handle; object->oclass = oclass; object->data = NULL; object->size = 0; object->dtor = dtor; object->map.ptr = NULL; object->map.size = 0; if (object->parent) { if (!(ctor = kmalloc(sizeof(*ctor) + size, GFP_KERNEL))) { nvif_object_fini(object); return -ENOMEM; } object->data = ctor->new.data; object->size = size; memcpy(object->data, data, size); ctor->ioctl.version = 0; ctor->ioctl.type = NVIF_IOCTL_V0_NEW; ctor->new.version = 0; ctor->new.route = NVIF_IOCTL_V0_ROUTE_NVIF; ctor->new.token = (unsigned long)(void *)object; ctor->new.handle = handle; ctor->new.oclass = oclass; ret = nvif_object_ioctl(parent, ctor, sizeof(*ctor) + object->size, &object->priv); } if (ret) nvif_object_fini(object); return ret; } static void nvif_object_del(struct nvif_object *object) { nvif_object_fini(object); kfree(object); } int nvif_object_new(struct nvif_object *parent, u32 handle, u32 oclass, void *data, u32 size, struct nvif_object **pobject) { struct nvif_object *object = kzalloc(sizeof(*object), GFP_KERNEL); if (object) { int ret = nvif_object_init(parent, nvif_object_del, handle, oclass, data, size, object); if (ret) { kfree(object); object = NULL; } *pobject = object; return ret; } return -ENOMEM; } static void nvif_object_put(struct kref *kref) { struct nvif_object *object = container_of(kref, typeof(*object), refcount); object->dtor(object); } void nvif_object_ref(struct nvif_object *object, struct nvif_object **pobject) { if (object) kref_get(&object->refcount); if (*pobject) kref_put(&(*pobject)->refcount, nvif_object_put); *pobject = object; }
gpl-2.0
leedsalim/android-omap3-2.6.32
arch/arm/plat-s3c24xx/s3c2410-iotiming.c
461
11994
/* linux/arch/arm/plat-s3c24xx/s3c2410-iotiming.c * * Copyright (c) 2006,2008,2009 Simtec Electronics * http://armlinux.simtec.co.uk/ * Ben Dooks <ben@simtec.co.uk> * * S3C24XX CPU Frequency scaling - IO timing for S3C2410/S3C2440/S3C2442 * * 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/kernel.h> #include <linux/errno.h> #include <linux/cpufreq.h> #include <linux/seq_file.h> #include <linux/io.h> #include <mach/map.h> #include <mach/regs-mem.h> #include <mach/regs-clock.h> #include <plat/cpu-freq-core.h> #define print_ns(x) ((x) / 10), ((x) % 10) /** * s3c2410_print_timing - print bank timing data for debug purposes * @pfx: The prefix to put on the output * @timings: The timing inforamtion to print. */ static void s3c2410_print_timing(const char *pfx, struct s3c_iotimings *timings) { struct s3c2410_iobank_timing *bt; int bank; for (bank = 0; bank < MAX_BANKS; bank++) { bt = timings->bank[bank].io_2410; if (!bt) continue; printk(KERN_DEBUG "%s %d: Tacs=%d.%d, Tcos=%d.%d, Tacc=%d.%d, " "Tcoh=%d.%d, Tcah=%d.%d\n", pfx, bank, print_ns(bt->tacs), print_ns(bt->tcos), print_ns(bt->tacc), print_ns(bt->tcoh), print_ns(bt->tcah)); } } /** * bank_reg - convert bank number to pointer to the control register. * @bank: The IO bank number. */ static inline void __iomem *bank_reg(unsigned int bank) { return S3C2410_BANKCON0 + (bank << 2); } /** * bank_is_io - test whether bank is used for IO * @bankcon: The bank control register. * * This is a simplistic test to see if any BANKCON[x] is not an IO * bank. It currently does not take into account whether BWSCON has * an illegal width-setting in it, or if the pin connected to nCS[x] * is actually being handled as a chip-select. */ static inline int bank_is_io(unsigned long bankcon) { return !(bankcon & S3C2410_BANKCON_SDRAM); } /** * to_div - convert cycle time to divisor * @cyc: The cycle time, in 10ths of nanoseconds. * @hclk_tns: The cycle time for HCLK, in 10ths of nanoseconds. * * Convert the given cycle time into the divisor to use to obtain it from * HCLK. */ static inline unsigned int to_div(unsigned int cyc, unsigned int hclk_tns) { if (cyc == 0) return 0; return DIV_ROUND_UP(cyc, hclk_tns); } /** * calc_0124 - calculate divisor control for divisors that do /0, /1. /2 and /4 * @cyc: The cycle time, in 10ths of nanoseconds. * @hclk_tns: The cycle time for HCLK, in 10ths of nanoseconds. * @v: Pointer to register to alter. * @shift: The shift to get to the control bits. * * Calculate the divisor, and turn it into the correct control bits to * set in the result, @v. */ static unsigned int calc_0124(unsigned int cyc, unsigned long hclk_tns, unsigned long *v, int shift) { unsigned int div = to_div(cyc, hclk_tns); unsigned long val; s3c_freq_iodbg("%s: cyc=%d, hclk=%lu, shift=%d => div %d\n", __func__, cyc, hclk_tns, shift, div); switch (div) { case 0: val = 0; break; case 1: val = 1; break; case 2: val = 2; break; case 3: case 4: val = 3; break; default: return -1; } *v |= val << shift; return 0; } int calc_tacp(unsigned int cyc, unsigned long hclk, unsigned long *v) { /* Currently no support for Tacp calculations. */ return 0; } /** * calc_tacc - calculate divisor control for tacc. * @cyc: The cycle time, in 10ths of nanoseconds. * @nwait_en: IS nWAIT enabled for this bank. * @hclk_tns: The cycle time for HCLK, in 10ths of nanoseconds. * @v: Pointer to register to alter. * * Calculate the divisor control for tACC, taking into account whether * the bank has nWAIT enabled. The result is used to modify the value * pointed to by @v. */ static int calc_tacc(unsigned int cyc, int nwait_en, unsigned long hclk_tns, unsigned long *v) { unsigned int div = to_div(cyc, hclk_tns); unsigned long val; s3c_freq_iodbg("%s: cyc=%u, nwait=%d, hclk=%lu => div=%u\n", __func__, cyc, nwait_en, hclk_tns, div); /* if nWait enabled on an bank, Tacc must be at-least 4 cycles. */ if (nwait_en && div < 4) div = 4; switch (div) { case 0: val = 0; break; case 1: case 2: case 3: case 4: val = div - 1; break; case 5: case 6: val = 4; break; case 7: case 8: val = 5; break; case 9: case 10: val = 6; break; case 11: case 12: case 13: case 14: val = 7; break; default: return -1; } *v |= val << 8; return 0; } /** * s3c2410_calc_bank - calculate bank timing infromation * @cfg: The configuration we need to calculate for. * @bt: The bank timing information. * * Given the cycle timine for a bank @bt, calculate the new BANKCON * setting for the @cfg timing. This updates the timing information * ready for the cpu frequency change. */ static int s3c2410_calc_bank(struct s3c_cpufreq_config *cfg, struct s3c2410_iobank_timing *bt) { unsigned long hclk = cfg->freq.hclk_tns; unsigned long res; int ret; res = bt->bankcon; res &= (S3C2410_BANKCON_SDRAM | S3C2410_BANKCON_PMC16); /* tacp: 2,3,4,5 */ /* tcah: 0,1,2,4 */ /* tcoh: 0,1,2,4 */ /* tacc: 1,2,3,4,6,7,10,14 (>4 for nwait) */ /* tcos: 0,1,2,4 */ /* tacs: 0,1,2,4 */ ret = calc_0124(bt->tacs, hclk, &res, S3C2410_BANKCON_Tacs_SHIFT); ret |= calc_0124(bt->tcos, hclk, &res, S3C2410_BANKCON_Tcos_SHIFT); ret |= calc_0124(bt->tcah, hclk, &res, S3C2410_BANKCON_Tcah_SHIFT); ret |= calc_0124(bt->tcoh, hclk, &res, S3C2410_BANKCON_Tcoh_SHIFT); if (ret) return -EINVAL; ret |= calc_tacp(bt->tacp, hclk, &res); ret |= calc_tacc(bt->tacc, bt->nwait_en, hclk, &res); if (ret) return -EINVAL; bt->bankcon = res; return 0; } static unsigned int tacc_tab[] = { [0] = 1, [1] = 2, [2] = 3, [3] = 4, [4] = 6, [5] = 9, [6] = 10, [7] = 14, }; /** * get_tacc - turn tACC value into cycle time * @hclk_tns: The cycle time for HCLK, in 10ths of nanoseconds. * @val: The bank timing register value, shifed down. */ static unsigned int get_tacc(unsigned long hclk_tns, unsigned long val) { val &= 7; return hclk_tns * tacc_tab[val]; } /** * get_0124 - turn 0/1/2/4 divider into cycle time * @hclk_tns: The cycle time for HCLK, in 10ths of nanoseconds. * @val: The bank timing register value, shifed down. */ static unsigned int get_0124(unsigned long hclk_tns, unsigned long val) { val &= 3; return hclk_tns * ((val == 3) ? 4 : val); } /** * s3c2410_iotiming_getbank - turn BANKCON into cycle time information * @cfg: The frequency configuration * @bt: The bank timing to fill in (uses cached BANKCON) * * Given the BANKCON setting in @bt and the current frequency settings * in @cfg, update the cycle timing information. */ void s3c2410_iotiming_getbank(struct s3c_cpufreq_config *cfg, struct s3c2410_iobank_timing *bt) { unsigned long bankcon = bt->bankcon; unsigned long hclk = cfg->freq.hclk_tns; bt->tcah = get_0124(hclk, bankcon >> S3C2410_BANKCON_Tcah_SHIFT); bt->tcoh = get_0124(hclk, bankcon >> S3C2410_BANKCON_Tcoh_SHIFT); bt->tcos = get_0124(hclk, bankcon >> S3C2410_BANKCON_Tcos_SHIFT); bt->tacs = get_0124(hclk, bankcon >> S3C2410_BANKCON_Tacs_SHIFT); bt->tacc = get_tacc(hclk, bankcon >> S3C2410_BANKCON_Tacc_SHIFT); } /** * s3c2410_iotiming_debugfs - debugfs show io bank timing information * @seq: The seq_file to write output to using seq_printf(). * @cfg: The current configuration. * @iob: The IO bank information to decode. */ void s3c2410_iotiming_debugfs(struct seq_file *seq, struct s3c_cpufreq_config *cfg, union s3c_iobank *iob) { struct s3c2410_iobank_timing *bt = iob->io_2410; unsigned long bankcon = bt->bankcon; unsigned long hclk = cfg->freq.hclk_tns; unsigned int tacs; unsigned int tcos; unsigned int tacc; unsigned int tcoh; unsigned int tcah; seq_printf(seq, "BANKCON=0x%08lx\n", bankcon); tcah = get_0124(hclk, bankcon >> S3C2410_BANKCON_Tcah_SHIFT); tcoh = get_0124(hclk, bankcon >> S3C2410_BANKCON_Tcoh_SHIFT); tcos = get_0124(hclk, bankcon >> S3C2410_BANKCON_Tcos_SHIFT); tacs = get_0124(hclk, bankcon >> S3C2410_BANKCON_Tacs_SHIFT); tacc = get_tacc(hclk, bankcon >> S3C2410_BANKCON_Tacc_SHIFT); seq_printf(seq, "\tRead: Tacs=%d.%d, Tcos=%d.%d, Tacc=%d.%d, Tcoh=%d.%d, Tcah=%d.%d\n", print_ns(bt->tacs), print_ns(bt->tcos), print_ns(bt->tacc), print_ns(bt->tcoh), print_ns(bt->tcah)); seq_printf(seq, "\t Set: Tacs=%d.%d, Tcos=%d.%d, Tacc=%d.%d, Tcoh=%d.%d, Tcah=%d.%d\n", print_ns(tacs), print_ns(tcos), print_ns(tacc), print_ns(tcoh), print_ns(tcah)); } /** * s3c2410_iotiming_calc - Calculate bank timing for frequency change. * @cfg: The frequency configuration * @iot: The IO timing information to fill out. * * Calculate the new values for the banks in @iot based on the new * frequency information in @cfg. This is then used by s3c2410_iotiming_set() * to update the timing when necessary. */ int s3c2410_iotiming_calc(struct s3c_cpufreq_config *cfg, struct s3c_iotimings *iot) { struct s3c2410_iobank_timing *bt; unsigned long bankcon; int bank; int ret; for (bank = 0; bank < MAX_BANKS; bank++) { bankcon = __raw_readl(bank_reg(bank)); bt = iot->bank[bank].io_2410; if (!bt) continue; bt->bankcon = bankcon; ret = s3c2410_calc_bank(cfg, bt); if (ret) { printk(KERN_ERR "%s: cannot calculate bank %d io\n", __func__, bank); goto err; } s3c_freq_iodbg("%s: bank %d: con=%08lx\n", __func__, bank, bt->bankcon); } return 0; err: return ret; } /** * s3c2410_iotiming_set - set the IO timings from the given setup. * @cfg: The frequency configuration * @iot: The IO timing information to use. * * Set all the currently used IO bank timing information generated * by s3c2410_iotiming_calc() once the core has validated that all * the new values are within permitted bounds. */ void s3c2410_iotiming_set(struct s3c_cpufreq_config *cfg, struct s3c_iotimings *iot) { struct s3c2410_iobank_timing *bt; int bank; /* set the io timings from the specifier */ for (bank = 0; bank < MAX_BANKS; bank++) { bt = iot->bank[bank].io_2410; if (!bt) continue; __raw_writel(bt->bankcon, bank_reg(bank)); } } /** * s3c2410_iotiming_get - Get the timing information from current registers. * @cfg: The frequency configuration * @timings: The IO timing information to fill out. * * Calculate the @timings timing information from the current frequency * information in @cfg, and the new frequency configur * through all the IO banks, reading the state and then updating @iot * as necessary. * * This is used at the moment on initialisation to get the current * configuration so that boards do not have to carry their own setup * if the timings are correct on initialisation. */ int s3c2410_iotiming_get(struct s3c_cpufreq_config *cfg, struct s3c_iotimings *timings) { struct s3c2410_iobank_timing *bt; unsigned long bankcon; unsigned long bwscon; int bank; bwscon = __raw_readl(S3C2410_BWSCON); /* look through all banks to see what is currently set. */ for (bank = 0; bank < MAX_BANKS; bank++) { bankcon = __raw_readl(bank_reg(bank)); if (!bank_is_io(bankcon)) continue; s3c_freq_iodbg("%s: bank %d: con %08lx\n", __func__, bank, bankcon); bt = kzalloc(sizeof(struct s3c2410_iobank_timing), GFP_KERNEL); if (!bt) { printk(KERN_ERR "%s: no memory for bank\n", __func__); return -ENOMEM; } /* find out in nWait is enabled for bank. */ if (bank != 0) { unsigned long tmp = S3C2410_BWSCON_GET(bwscon, bank); if (tmp & S3C2410_BWSCON_WS) bt->nwait_en = 1; } timings->bank[bank].io_2410 = bt; bt->bankcon = bankcon; s3c2410_iotiming_getbank(cfg, bt); } s3c2410_print_timing("get", timings); return 0; }
gpl-2.0
dan-htc-touch/kernel_samsung_hlte
drivers/media/tdmb/tdmb_ebi.c
461
7065
/* * * drivers/media/tdmb/tdmb_ebi.c * * tdmb driver * * Copyright (C) (2011, Samsung Electronics) * * 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 "as is" WITHOUT ANY WARRANTY of any * kind, whether express or implied; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/io.h> #include <linux/of_gpio.h> #include <linux/clk.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/platform_device.h> #include <plat/gpio-cfg.h> #include <plat/regs-srom.h> #include <mach/gpio.h> #include "tdmb.h" static struct tdmb_ebi_dt_data *ebi_dt_pdata; static void __iomem *v_addr_ebi_cs_base; /* SROMC bank attributes in BW (Bus width and Wait control) register */ enum sromc_bank_attr { SROMC_DATA_16 = 0x1, /* 16-bit data bus */ SROMC_BYTE_ADDR = 0x2, /* Byte base address */ SROMC_WAIT_EN = 0x4, /* Wait enabled */ SROMC_BYTE_EN = 0x8, /* Byte access enabled */ SROMC_ATTR_MASK = 0xF }; /* SROMC bank configuration */ struct sromc_bank_cfg { unsigned csn; /* CSn # */ unsigned attr; /* SROMC bank attributes */ unsigned size; /* Size of a memory */ unsigned addr; /* Start address (physical) */ }; /* SROMC bank access timing configuration */ struct sromc_timing_cfg { u32 tacs; /* Address set-up before CSn */ u32 tcos; /* Chip selection set-up before OEn */ u32 tacc; /* Access cycle */ u32 tcoh; /* Chip selection hold on OEn */ u32 tcah; /* Address holding time after CSn */ u32 tacp; /* Page mode access cycle at Page mode */ u32 pmc; /* Page Mode config */ }; /** * sromc_enable * * Enables SROM controller (SROMC) block * */ static int sromc_enable(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct clk *clk; clk = devm_clk_get(dev, "sromc_clk"); if (IS_ERR(clk)) { DPRINTK("Failed to get tdmb_sromc clock\n"); return -1; } if (clk_prepare_enable(clk)) { DPRINTK("%s: clk_prepare_enable failed\n", __func__); return -1; } return 0; } /** * sromc_config_demux_gpio * * Configures GPIO pins for REn, WEn, LBn, UBn, address bus, and data bus * as demux mode * * Returns 0 if there is no error * */ static int sromc_config_demux_gpio(struct platform_device *pdev) { struct device *dev = &pdev->dev; struct pinctrl *pinctrl; pinctrl = devm_pinctrl_get_select_default(dev); if (IS_ERR(pinctrl)) DPRINTK("%s: Failed to configure pinctrl\n", __func__); return 0; } /** * sromc_config_access_attr * @csn: CSn number * @attr: SROMC attribute for this CSn * * Configures SROMC attribute for a CSn * */ static void sromc_config_access_attr(unsigned int csn, unsigned int attr) { unsigned int bw = 0; /* Bus width and Wait control */ DPRINTK("%s: for CSn%d\n", __func__, csn); bw = __raw_readl(S5P_SROM_BW); DPRINTK("%s: old BW setting = 0x%08X\n", __func__, bw); /* Configure BW control field for the CSn */ bw &= ~(SROMC_ATTR_MASK << (csn << 2)); bw |= (attr << (csn << 2)); writel(bw, S5P_SROM_BW); /* Verify SROMC settings */ bw = __raw_readl(S5P_SROM_BW); DPRINTK("%s: new BW setting = 0x%08X\n", __func__, bw); } /** * sromc_config_access_timing * @csn: CSn number * @tm_cfg: pointer to an sromc_timing_cfg * * Configures SROMC access timing register * */ static void sromc_config_access_timing(unsigned int csn, struct sromc_timing_cfg *tm_cfg) { void __iomem *bank_sfr = S5P_SROM_BC0 + (4 * csn); unsigned int bc = 0; /* Bank Control */ bc = __raw_readl(bank_sfr); DPRINTK("%s: old BC%d setting = 0x%08X\n", __func__, csn, bc); /* Configure memory access timing for the CSn */ bc = tm_cfg->tacs | tm_cfg->tcos | tm_cfg->tacc | tm_cfg->tcoh | tm_cfg->tcah | tm_cfg->tacp | tm_cfg->pmc; writel(bc, bank_sfr); /* Verify SROMC settings */ bc = __raw_readl(bank_sfr); DPRINTK("%s: new BC%d setting = 0x%08X\n", __func__, csn, bc); } static struct sromc_bank_cfg tdmb_sromc_bank_cfg = { .csn = 0, .attr = 0, }; static struct sromc_timing_cfg tdmb_sromc_timing_cfg = { .tacs = 0x0F << 28, .tcos = 0x02 << 24, .tacc = 0x1F << 16, .tcoh = 0x02 << 12, .tcah = 0x0F << 8, .tacp = 0x00 << 4, .pmc = 0x00 << 0, }; unsigned long tdmb_get_if_handle(void) { return (unsigned long)v_addr_ebi_cs_base; } EXPORT_SYMBOL_GPL(tdmb_get_if_handle); static int tdmb_ebi_init(struct platform_device *pdev) { struct sromc_bank_cfg *bnk_cfg; struct sromc_timing_cfg *tm_cfg; if (sromc_enable(pdev) < 0) { printk(KERN_DEBUG "tdmb_dev_init sromc_enable fail\n"); return -1; } if (sromc_config_demux_gpio(pdev) < 0) { printk(KERN_DEBUG "tdmb_dev_init sromc_config_demux_gpio fail\n"); return -1; } bnk_cfg = &tdmb_sromc_bank_cfg; sromc_config_access_attr(bnk_cfg->csn, bnk_cfg->attr); tm_cfg = &tdmb_sromc_timing_cfg; sromc_config_access_timing(bnk_cfg->csn, tm_cfg); return 0; } static struct tdmb_ebi_dt_data *get_ebi_dt_pdata(struct device *dev) { struct tdmb_ebi_dt_data *pdata; pdata = devm_kzalloc(dev, sizeof(*pdata), GFP_KERNEL); if (!pdata) { DPRINTK("%s : could not allocate memory for platform data\n", __func__); return NULL; } if (!of_property_read_u32(dev->of_node, "srom_cs_base", &pdata->cs_base)) DPRINTK("%s - srom_cs_base : 0x%x\n", __func__, pdata->cs_base); else { DPRINTK("%s - cs_base missing\n", __func__); goto fail; } if (!of_property_read_u32(dev->of_node, "srom_mem_size", &pdata->mem_size)) DPRINTK("%s - srom_mem_size : 0x%x\n", __func__, pdata->mem_size); else { DPRINTK("%s - mem_size missing\n", __func__); goto fail; } return pdata; fail: devm_kfree(dev, pdata); return NULL; } static int tdmb_sromc_remove(struct platform_device *pdev) { DPRINTK("tdmb_sromc_remove!\n"); return 0; } static int tdmb_sromc_probe(struct platform_device *pdev) { if (pdev->dev.of_node) { ebi_dt_pdata = get_ebi_dt_pdata(&pdev->dev); if (!ebi_dt_pdata) { DPRINTK("%s : ebi_dt_pdata is NULL\n", __func__); return -1; } } if (tdmb_ebi_init(pdev) < 0) { DPRINTK("%s : tdmb_ebi_init error\n", __func__); return -1; } v_addr_ebi_cs_base = ioremap(ebi_dt_pdata->cs_base, ebi_dt_pdata->mem_size); DPRINTK("%s : v_addr_ebi_cs_base 0x%p\n", __func__, v_addr_ebi_cs_base); return 0; } static const struct of_device_id sromc_match_table[] = { {.compatible = "samsung,sromc"}, {} }; static struct platform_driver tdmb_ebi_driver = { .driver = { .name = "sromc", .owner = THIS_MODULE, .of_match_table = of_match_ptr(sromc_match_table), }, .remove = tdmb_sromc_remove, }; int __init tdmb_sromc_init(void) { return platform_driver_probe(&tdmb_ebi_driver, tdmb_sromc_probe); } module_init(tdmb_sromc_init); static void __exit tdmb_sromc_exit(void) { platform_driver_unregister(&tdmb_ebi_driver); } module_exit(tdmb_sromc_exit); MODULE_AUTHOR("Samsung"); MODULE_DESCRIPTION("SROMC Driver"); MODULE_LICENSE("GPL v2");
gpl-2.0
farindk/linux-sunxi
arch/metag/kernel/devtree.c
2253
1753
/* * linux/arch/metag/kernel/devtree.c * * Copyright (C) 2012 Imagination Technologies Ltd. * * Based on ARM version: * Copyright (C) 2009 Canonical Ltd. <jeremy.kerr@canonical.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/init.h> #include <linux/export.h> #include <linux/types.h> #include <linux/bootmem.h> #include <linux/memblock.h> #include <linux/of.h> #include <linux/of_fdt.h> #include <asm/setup.h> #include <asm/page.h> #include <asm/mach/arch.h> void __init early_init_dt_add_memory_arch(u64 base, u64 size) { pr_err("%s(%llx, %llx)\n", __func__, base, size); } void * __init early_init_dt_alloc_memory_arch(u64 size, u64 align) { return alloc_bootmem_align(size, align); } static const void * __init arch_get_next_mach(const char *const **match) { static const struct machine_desc *mdesc = __arch_info_begin; const struct machine_desc *m = mdesc; if (m >= __arch_info_end) return NULL; mdesc++; *match = m->dt_compat; return m; } /** * setup_machine_fdt - Machine setup when an dtb was passed to the kernel * @dt: virtual address pointer to dt blob * * If a dtb was passed to the kernel, then use it to choose the correct * machine_desc and to setup the system. */ const struct machine_desc * __init setup_machine_fdt(void *dt) { const struct machine_desc *mdesc; /* check device tree validity */ if (!early_init_dt_scan(dt)) return NULL; mdesc = of_flat_dt_match_machine(NULL, arch_get_next_mach); if (!mdesc) dump_machine_table(); /* does not return */ pr_info("Machine name: %s\n", mdesc->name); return mdesc; }
gpl-2.0
abhishekr700/Nemesis_Kernel
drivers/misc/spear13xx_pcie_gadget.c
2253
23063
/* * drivers/misc/spear13xx_pcie_gadget.c * * Copyright (C) 2010 ST Microelectronics * Pratyush Anand<pratyush.anand@st.com> * * This file is licensed under the terms of the GNU General Public * License version 2. This program is licensed "as is" without any * warranty of any kind, whether express or implied. */ #include <linux/clk.h> #include <linux/slab.h> #include <linux/delay.h> #include <linux/io.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/platform_device.h> #include <linux/pci_regs.h> #include <linux/configfs.h> #include <mach/pcie.h> #include <mach/misc_regs.h> #define IN0_MEM_SIZE (200 * 1024 * 1024 - 1) /* In current implementation address translation is done using IN0 only. * So IN1 start address and IN0 end address has been kept same */ #define IN1_MEM_SIZE (0 * 1024 * 1024 - 1) #define IN_IO_SIZE (20 * 1024 * 1024 - 1) #define IN_CFG0_SIZE (12 * 1024 * 1024 - 1) #define IN_CFG1_SIZE (12 * 1024 * 1024 - 1) #define IN_MSG_SIZE (12 * 1024 * 1024 - 1) /* Keep default BAR size as 4K*/ /* AORAM would be mapped by default*/ #define INBOUND_ADDR_MASK (SPEAR13XX_SYSRAM1_SIZE - 1) #define INT_TYPE_NO_INT 0 #define INT_TYPE_INTX 1 #define INT_TYPE_MSI 2 struct spear_pcie_gadget_config { void __iomem *base; void __iomem *va_app_base; void __iomem *va_dbi_base; char int_type[10]; ulong requested_msi; ulong configured_msi; ulong bar0_size; ulong bar0_rw_offset; void __iomem *va_bar0_address; }; struct pcie_gadget_target { struct configfs_subsystem subsys; struct spear_pcie_gadget_config config; }; struct pcie_gadget_target_attr { struct configfs_attribute attr; ssize_t (*show)(struct spear_pcie_gadget_config *config, char *buf); ssize_t (*store)(struct spear_pcie_gadget_config *config, const char *buf, size_t count); }; static void enable_dbi_access(struct pcie_app_reg __iomem *app_reg) { /* Enable DBI access */ writel(readl(&app_reg->slv_armisc) | (1 << AXI_OP_DBI_ACCESS_ID), &app_reg->slv_armisc); writel(readl(&app_reg->slv_awmisc) | (1 << AXI_OP_DBI_ACCESS_ID), &app_reg->slv_awmisc); } static void disable_dbi_access(struct pcie_app_reg __iomem *app_reg) { /* disable DBI access */ writel(readl(&app_reg->slv_armisc) & ~(1 << AXI_OP_DBI_ACCESS_ID), &app_reg->slv_armisc); writel(readl(&app_reg->slv_awmisc) & ~(1 << AXI_OP_DBI_ACCESS_ID), &app_reg->slv_awmisc); } static void spear_dbi_read_reg(struct spear_pcie_gadget_config *config, int where, int size, u32 *val) { struct pcie_app_reg __iomem *app_reg = config->va_app_base; ulong va_address; /* Enable DBI access */ enable_dbi_access(app_reg); va_address = (ulong)config->va_dbi_base + (where & ~0x3); *val = readl(va_address); if (size == 1) *val = (*val >> (8 * (where & 3))) & 0xff; else if (size == 2) *val = (*val >> (8 * (where & 3))) & 0xffff; /* Disable DBI access */ disable_dbi_access(app_reg); } static void spear_dbi_write_reg(struct spear_pcie_gadget_config *config, int where, int size, u32 val) { struct pcie_app_reg __iomem *app_reg = config->va_app_base; ulong va_address; /* Enable DBI access */ enable_dbi_access(app_reg); va_address = (ulong)config->va_dbi_base + (where & ~0x3); if (size == 4) writel(val, va_address); else if (size == 2) writew(val, va_address + (where & 2)); else if (size == 1) writeb(val, va_address + (where & 3)); /* Disable DBI access */ disable_dbi_access(app_reg); } #define PCI_FIND_CAP_TTL 48 static int pci_find_own_next_cap_ttl(struct spear_pcie_gadget_config *config, u32 pos, int cap, int *ttl) { u32 id; while ((*ttl)--) { spear_dbi_read_reg(config, pos, 1, &pos); if (pos < 0x40) break; pos &= ~3; spear_dbi_read_reg(config, pos + PCI_CAP_LIST_ID, 1, &id); if (id == 0xff) break; if (id == cap) return pos; pos += PCI_CAP_LIST_NEXT; } return 0; } static int pci_find_own_next_cap(struct spear_pcie_gadget_config *config, u32 pos, int cap) { int ttl = PCI_FIND_CAP_TTL; return pci_find_own_next_cap_ttl(config, pos, cap, &ttl); } static int pci_find_own_cap_start(struct spear_pcie_gadget_config *config, u8 hdr_type) { u32 status; spear_dbi_read_reg(config, PCI_STATUS, 2, &status); if (!(status & PCI_STATUS_CAP_LIST)) return 0; switch (hdr_type) { case PCI_HEADER_TYPE_NORMAL: case PCI_HEADER_TYPE_BRIDGE: return PCI_CAPABILITY_LIST; case PCI_HEADER_TYPE_CARDBUS: return PCI_CB_CAPABILITY_LIST; default: return 0; } return 0; } /* * Tell if a device supports a given PCI capability. * Returns the address of the requested capability structure within the * device's PCI configuration space or 0 in case the device does not * support it. Possible values for @cap: * * %PCI_CAP_ID_PM Power Management * %PCI_CAP_ID_AGP Accelerated Graphics Port * %PCI_CAP_ID_VPD Vital Product Data * %PCI_CAP_ID_SLOTID Slot Identification * %PCI_CAP_ID_MSI Message Signalled Interrupts * %PCI_CAP_ID_CHSWP CompactPCI HotSwap * %PCI_CAP_ID_PCIX PCI-X * %PCI_CAP_ID_EXP PCI Express */ static int pci_find_own_capability(struct spear_pcie_gadget_config *config, int cap) { u32 pos; u32 hdr_type; spear_dbi_read_reg(config, PCI_HEADER_TYPE, 1, &hdr_type); pos = pci_find_own_cap_start(config, hdr_type); if (pos) pos = pci_find_own_next_cap(config, pos, cap); return pos; } static irqreturn_t spear_pcie_gadget_irq(int irq, void *dev_id) { return 0; } /* * configfs interfaces show/store functions */ static ssize_t pcie_gadget_show_link( struct spear_pcie_gadget_config *config, char *buf) { struct pcie_app_reg __iomem *app_reg = config->va_app_base; if (readl(&app_reg->app_status_1) & ((u32)1 << XMLH_LINK_UP_ID)) return sprintf(buf, "UP"); else return sprintf(buf, "DOWN"); } static ssize_t pcie_gadget_store_link( struct spear_pcie_gadget_config *config, const char *buf, size_t count) { struct pcie_app_reg __iomem *app_reg = config->va_app_base; if (sysfs_streq(buf, "UP")) writel(readl(&app_reg->app_ctrl_0) | (1 << APP_LTSSM_ENABLE_ID), &app_reg->app_ctrl_0); else if (sysfs_streq(buf, "DOWN")) writel(readl(&app_reg->app_ctrl_0) & ~(1 << APP_LTSSM_ENABLE_ID), &app_reg->app_ctrl_0); else return -EINVAL; return count; } static ssize_t pcie_gadget_show_int_type( struct spear_pcie_gadget_config *config, char *buf) { return sprintf(buf, "%s", config->int_type); } static ssize_t pcie_gadget_store_int_type( struct spear_pcie_gadget_config *config, const char *buf, size_t count) { u32 cap, vec, flags; ulong vector; if (sysfs_streq(buf, "INTA")) spear_dbi_write_reg(config, PCI_INTERRUPT_LINE, 1, 1); else if (sysfs_streq(buf, "MSI")) { vector = config->requested_msi; vec = 0; while (vector > 1) { vector /= 2; vec++; } spear_dbi_write_reg(config, PCI_INTERRUPT_LINE, 1, 0); cap = pci_find_own_capability(config, PCI_CAP_ID_MSI); spear_dbi_read_reg(config, cap + PCI_MSI_FLAGS, 1, &flags); flags &= ~PCI_MSI_FLAGS_QMASK; flags |= vec << 1; spear_dbi_write_reg(config, cap + PCI_MSI_FLAGS, 1, flags); } else return -EINVAL; strcpy(config->int_type, buf); return count; } static ssize_t pcie_gadget_show_no_of_msi( struct spear_pcie_gadget_config *config, char *buf) { struct pcie_app_reg __iomem *app_reg = config->va_app_base; u32 cap, vec, flags; ulong vector; if ((readl(&app_reg->msg_status) & (1 << CFG_MSI_EN_ID)) != (1 << CFG_MSI_EN_ID)) vector = 0; else { cap = pci_find_own_capability(config, PCI_CAP_ID_MSI); spear_dbi_read_reg(config, cap + PCI_MSI_FLAGS, 1, &flags); flags &= ~PCI_MSI_FLAGS_QSIZE; vec = flags >> 4; vector = 1; while (vec--) vector *= 2; } config->configured_msi = vector; return sprintf(buf, "%lu", vector); } static ssize_t pcie_gadget_store_no_of_msi( struct spear_pcie_gadget_config *config, const char *buf, size_t count) { if (strict_strtoul(buf, 0, &config->requested_msi)) return -EINVAL; if (config->requested_msi > 32) config->requested_msi = 32; return count; } static ssize_t pcie_gadget_store_inta( struct spear_pcie_gadget_config *config, const char *buf, size_t count) { struct pcie_app_reg __iomem *app_reg = config->va_app_base; ulong en; if (strict_strtoul(buf, 0, &en)) return -EINVAL; if (en) writel(readl(&app_reg->app_ctrl_0) | (1 << SYS_INT_ID), &app_reg->app_ctrl_0); else writel(readl(&app_reg->app_ctrl_0) & ~(1 << SYS_INT_ID), &app_reg->app_ctrl_0); return count; } static ssize_t pcie_gadget_store_send_msi( struct spear_pcie_gadget_config *config, const char *buf, size_t count) { struct pcie_app_reg __iomem *app_reg = config->va_app_base; ulong vector; u32 ven_msi; if (strict_strtoul(buf, 0, &vector)) return -EINVAL; if (!config->configured_msi) return -EINVAL; if (vector >= config->configured_msi) return -EINVAL; ven_msi = readl(&app_reg->ven_msi_1); ven_msi &= ~VEN_MSI_FUN_NUM_MASK; ven_msi |= 0 << VEN_MSI_FUN_NUM_ID; ven_msi &= ~VEN_MSI_TC_MASK; ven_msi |= 0 << VEN_MSI_TC_ID; ven_msi &= ~VEN_MSI_VECTOR_MASK; ven_msi |= vector << VEN_MSI_VECTOR_ID; /* generating interrupt for msi vector */ ven_msi |= VEN_MSI_REQ_EN; writel(ven_msi, &app_reg->ven_msi_1); udelay(1); ven_msi &= ~VEN_MSI_REQ_EN; writel(ven_msi, &app_reg->ven_msi_1); return count; } static ssize_t pcie_gadget_show_vendor_id( struct spear_pcie_gadget_config *config, char *buf) { u32 id; spear_dbi_read_reg(config, PCI_VENDOR_ID, 2, &id); return sprintf(buf, "%x", id); } static ssize_t pcie_gadget_store_vendor_id( struct spear_pcie_gadget_config *config, const char *buf, size_t count) { ulong id; if (strict_strtoul(buf, 0, &id)) return -EINVAL; spear_dbi_write_reg(config, PCI_VENDOR_ID, 2, id); return count; } static ssize_t pcie_gadget_show_device_id( struct spear_pcie_gadget_config *config, char *buf) { u32 id; spear_dbi_read_reg(config, PCI_DEVICE_ID, 2, &id); return sprintf(buf, "%x", id); } static ssize_t pcie_gadget_store_device_id( struct spear_pcie_gadget_config *config, const char *buf, size_t count) { ulong id; if (strict_strtoul(buf, 0, &id)) return -EINVAL; spear_dbi_write_reg(config, PCI_DEVICE_ID, 2, id); return count; } static ssize_t pcie_gadget_show_bar0_size( struct spear_pcie_gadget_config *config, char *buf) { return sprintf(buf, "%lx", config->bar0_size); } static ssize_t pcie_gadget_store_bar0_size( struct spear_pcie_gadget_config *config, const char *buf, size_t count) { ulong size; u32 pos, pos1; u32 no_of_bit = 0; if (strict_strtoul(buf, 0, &size)) return -EINVAL; /* min bar size is 256 */ if (size <= 0x100) size = 0x100; /* max bar size is 1MB*/ else if (size >= 0x100000) size = 0x100000; else { pos = 0; pos1 = 0; while (pos < 21) { pos = find_next_bit((ulong *)&size, 21, pos); if (pos != 21) pos1 = pos + 1; pos++; no_of_bit++; } if (no_of_bit == 2) pos1--; size = 1 << pos1; } config->bar0_size = size; spear_dbi_write_reg(config, PCIE_BAR0_MASK_REG, 4, size - 1); return count; } static ssize_t pcie_gadget_show_bar0_address( struct spear_pcie_gadget_config *config, char *buf) { struct pcie_app_reg __iomem *app_reg = config->va_app_base; u32 address = readl(&app_reg->pim0_mem_addr_start); return sprintf(buf, "%x", address); } static ssize_t pcie_gadget_store_bar0_address( struct spear_pcie_gadget_config *config, const char *buf, size_t count) { struct pcie_app_reg __iomem *app_reg = config->va_app_base; ulong address; if (strict_strtoul(buf, 0, &address)) return -EINVAL; address &= ~(config->bar0_size - 1); if (config->va_bar0_address) iounmap(config->va_bar0_address); config->va_bar0_address = ioremap(address, config->bar0_size); if (!config->va_bar0_address) return -ENOMEM; writel(address, &app_reg->pim0_mem_addr_start); return count; } static ssize_t pcie_gadget_show_bar0_rw_offset( struct spear_pcie_gadget_config *config, char *buf) { return sprintf(buf, "%lx", config->bar0_rw_offset); } static ssize_t pcie_gadget_store_bar0_rw_offset( struct spear_pcie_gadget_config *config, const char *buf, size_t count) { ulong offset; if (strict_strtoul(buf, 0, &offset)) return -EINVAL; if (offset % 4) return -EINVAL; config->bar0_rw_offset = offset; return count; } static ssize_t pcie_gadget_show_bar0_data( struct spear_pcie_gadget_config *config, char *buf) { ulong data; if (!config->va_bar0_address) return -ENOMEM; data = readl((ulong)config->va_bar0_address + config->bar0_rw_offset); return sprintf(buf, "%lx", data); } static ssize_t pcie_gadget_store_bar0_data( struct spear_pcie_gadget_config *config, const char *buf, size_t count) { ulong data; if (strict_strtoul(buf, 0, &data)) return -EINVAL; if (!config->va_bar0_address) return -ENOMEM; writel(data, (ulong)config->va_bar0_address + config->bar0_rw_offset); return count; } /* * Attribute definitions. */ #define PCIE_GADGET_TARGET_ATTR_RO(_name) \ static struct pcie_gadget_target_attr pcie_gadget_target_##_name = \ __CONFIGFS_ATTR(_name, S_IRUGO, pcie_gadget_show_##_name, NULL) #define PCIE_GADGET_TARGET_ATTR_WO(_name) \ static struct pcie_gadget_target_attr pcie_gadget_target_##_name = \ __CONFIGFS_ATTR(_name, S_IWUSR, NULL, pcie_gadget_store_##_name) #define PCIE_GADGET_TARGET_ATTR_RW(_name) \ static struct pcie_gadget_target_attr pcie_gadget_target_##_name = \ __CONFIGFS_ATTR(_name, S_IRUGO | S_IWUSR, pcie_gadget_show_##_name, \ pcie_gadget_store_##_name) PCIE_GADGET_TARGET_ATTR_RW(link); PCIE_GADGET_TARGET_ATTR_RW(int_type); PCIE_GADGET_TARGET_ATTR_RW(no_of_msi); PCIE_GADGET_TARGET_ATTR_WO(inta); PCIE_GADGET_TARGET_ATTR_WO(send_msi); PCIE_GADGET_TARGET_ATTR_RW(vendor_id); PCIE_GADGET_TARGET_ATTR_RW(device_id); PCIE_GADGET_TARGET_ATTR_RW(bar0_size); PCIE_GADGET_TARGET_ATTR_RW(bar0_address); PCIE_GADGET_TARGET_ATTR_RW(bar0_rw_offset); PCIE_GADGET_TARGET_ATTR_RW(bar0_data); static struct configfs_attribute *pcie_gadget_target_attrs[] = { &pcie_gadget_target_link.attr, &pcie_gadget_target_int_type.attr, &pcie_gadget_target_no_of_msi.attr, &pcie_gadget_target_inta.attr, &pcie_gadget_target_send_msi.attr, &pcie_gadget_target_vendor_id.attr, &pcie_gadget_target_device_id.attr, &pcie_gadget_target_bar0_size.attr, &pcie_gadget_target_bar0_address.attr, &pcie_gadget_target_bar0_rw_offset.attr, &pcie_gadget_target_bar0_data.attr, NULL, }; static struct pcie_gadget_target *to_target(struct config_item *item) { return item ? container_of(to_configfs_subsystem(to_config_group(item)), struct pcie_gadget_target, subsys) : NULL; } /* * Item operations and type for pcie_gadget_target. */ static ssize_t pcie_gadget_target_attr_show(struct config_item *item, struct configfs_attribute *attr, char *buf) { ssize_t ret = -EINVAL; struct pcie_gadget_target *target = to_target(item); struct pcie_gadget_target_attr *t_attr = container_of(attr, struct pcie_gadget_target_attr, attr); if (t_attr->show) ret = t_attr->show(&target->config, buf); return ret; } static ssize_t pcie_gadget_target_attr_store(struct config_item *item, struct configfs_attribute *attr, const char *buf, size_t count) { ssize_t ret = -EINVAL; struct pcie_gadget_target *target = to_target(item); struct pcie_gadget_target_attr *t_attr = container_of(attr, struct pcie_gadget_target_attr, attr); if (t_attr->store) ret = t_attr->store(&target->config, buf, count); return ret; } static struct configfs_item_operations pcie_gadget_target_item_ops = { .show_attribute = pcie_gadget_target_attr_show, .store_attribute = pcie_gadget_target_attr_store, }; static struct config_item_type pcie_gadget_target_type = { .ct_attrs = pcie_gadget_target_attrs, .ct_item_ops = &pcie_gadget_target_item_ops, .ct_owner = THIS_MODULE, }; static void spear13xx_pcie_device_init(struct spear_pcie_gadget_config *config) { struct pcie_app_reg __iomem *app_reg = config->va_app_base; /*setup registers for outbound translation */ writel(config->base, &app_reg->in0_mem_addr_start); writel(app_reg->in0_mem_addr_start + IN0_MEM_SIZE, &app_reg->in0_mem_addr_limit); writel(app_reg->in0_mem_addr_limit + 1, &app_reg->in1_mem_addr_start); writel(app_reg->in1_mem_addr_start + IN1_MEM_SIZE, &app_reg->in1_mem_addr_limit); writel(app_reg->in1_mem_addr_limit + 1, &app_reg->in_io_addr_start); writel(app_reg->in_io_addr_start + IN_IO_SIZE, &app_reg->in_io_addr_limit); writel(app_reg->in_io_addr_limit + 1, &app_reg->in_cfg0_addr_start); writel(app_reg->in_cfg0_addr_start + IN_CFG0_SIZE, &app_reg->in_cfg0_addr_limit); writel(app_reg->in_cfg0_addr_limit + 1, &app_reg->in_cfg1_addr_start); writel(app_reg->in_cfg1_addr_start + IN_CFG1_SIZE, &app_reg->in_cfg1_addr_limit); writel(app_reg->in_cfg1_addr_limit + 1, &app_reg->in_msg_addr_start); writel(app_reg->in_msg_addr_start + IN_MSG_SIZE, &app_reg->in_msg_addr_limit); writel(app_reg->in0_mem_addr_start, &app_reg->pom0_mem_addr_start); writel(app_reg->in1_mem_addr_start, &app_reg->pom1_mem_addr_start); writel(app_reg->in_io_addr_start, &app_reg->pom_io_addr_start); /*setup registers for inbound translation */ /* Keep AORAM mapped at BAR0 as default */ config->bar0_size = INBOUND_ADDR_MASK + 1; spear_dbi_write_reg(config, PCIE_BAR0_MASK_REG, 4, INBOUND_ADDR_MASK); spear_dbi_write_reg(config, PCI_BASE_ADDRESS_0, 4, 0xC); config->va_bar0_address = ioremap(SPEAR13XX_SYSRAM1_BASE, config->bar0_size); writel(SPEAR13XX_SYSRAM1_BASE, &app_reg->pim0_mem_addr_start); writel(0, &app_reg->pim1_mem_addr_start); writel(INBOUND_ADDR_MASK + 1, &app_reg->mem0_addr_offset_limit); writel(0x0, &app_reg->pim_io_addr_start); writel(0x0, &app_reg->pim_io_addr_start); writel(0x0, &app_reg->pim_rom_addr_start); writel(DEVICE_TYPE_EP | (1 << MISCTRL_EN_ID) | ((u32)1 << REG_TRANSLATION_ENABLE), &app_reg->app_ctrl_0); /* disable all rx interrupts */ writel(0, &app_reg->int_mask); /* Select INTA as default*/ spear_dbi_write_reg(config, PCI_INTERRUPT_LINE, 1, 1); } static int spear_pcie_gadget_probe(struct platform_device *pdev) { struct resource *res0, *res1; unsigned int status = 0; int irq; struct clk *clk; static struct pcie_gadget_target *target; struct spear_pcie_gadget_config *config; struct config_item *cg_item; struct configfs_subsystem *subsys; /* get resource for application registers*/ res0 = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res0) { dev_err(&pdev->dev, "no resource defined\n"); return -EBUSY; } if (!request_mem_region(res0->start, resource_size(res0), pdev->name)) { dev_err(&pdev->dev, "pcie gadget region already claimed\n"); return -EBUSY; } /* get resource for dbi registers*/ res1 = platform_get_resource(pdev, IORESOURCE_MEM, 1); if (!res1) { dev_err(&pdev->dev, "no resource defined\n"); goto err_rel_res0; } if (!request_mem_region(res1->start, resource_size(res1), pdev->name)) { dev_err(&pdev->dev, "pcie gadget region already claimed\n"); goto err_rel_res0; } target = kzalloc(sizeof(*target), GFP_KERNEL); if (!target) { dev_err(&pdev->dev, "out of memory\n"); status = -ENOMEM; goto err_rel_res; } cg_item = &target->subsys.su_group.cg_item; sprintf(cg_item->ci_namebuf, "pcie_gadget.%d", pdev->id); cg_item->ci_type = &pcie_gadget_target_type; config = &target->config; config->va_app_base = (void __iomem *)ioremap(res0->start, resource_size(res0)); if (!config->va_app_base) { dev_err(&pdev->dev, "ioremap fail\n"); status = -ENOMEM; goto err_kzalloc; } config->base = (void __iomem *)res1->start; config->va_dbi_base = (void __iomem *)ioremap(res1->start, resource_size(res1)); if (!config->va_dbi_base) { dev_err(&pdev->dev, "ioremap fail\n"); status = -ENOMEM; goto err_iounmap_app; } dev_set_drvdata(&pdev->dev, target); irq = platform_get_irq(pdev, 0); if (irq < 0) { dev_err(&pdev->dev, "no update irq?\n"); status = irq; goto err_iounmap; } status = request_irq(irq, spear_pcie_gadget_irq, 0, pdev->name, NULL); if (status) { dev_err(&pdev->dev, "pcie gadget interrupt IRQ%d already claimed\n", irq); goto err_iounmap; } /* Register configfs hooks */ subsys = &target->subsys; config_group_init(&subsys->su_group); mutex_init(&subsys->su_mutex); status = configfs_register_subsystem(subsys); if (status) goto err_irq; /* * init basic pcie application registers * do not enable clock if it is PCIE0.Ideally , all controller should * have been independent from others with respect to clock. But PCIE1 * and 2 depends on PCIE0.So PCIE0 clk is provided during board init. */ if (pdev->id == 1) { /* * Ideally CFG Clock should have been also enabled here. But * it is done currently during board init routne */ clk = clk_get_sys("pcie1", NULL); if (IS_ERR(clk)) { pr_err("%s:couldn't get clk for pcie1\n", __func__); goto err_irq; } if (clk_enable(clk)) { pr_err("%s:couldn't enable clk for pcie1\n", __func__); goto err_irq; } } else if (pdev->id == 2) { /* * Ideally CFG Clock should have been also enabled here. But * it is done currently during board init routne */ clk = clk_get_sys("pcie2", NULL); if (IS_ERR(clk)) { pr_err("%s:couldn't get clk for pcie2\n", __func__); goto err_irq; } if (clk_enable(clk)) { pr_err("%s:couldn't enable clk for pcie2\n", __func__); goto err_irq; } } spear13xx_pcie_device_init(config); return 0; err_irq: free_irq(irq, NULL); err_iounmap: iounmap(config->va_dbi_base); err_iounmap_app: iounmap(config->va_app_base); err_kzalloc: kfree(target); err_rel_res: release_mem_region(res1->start, resource_size(res1)); err_rel_res0: release_mem_region(res0->start, resource_size(res0)); return status; } static int spear_pcie_gadget_remove(struct platform_device *pdev) { struct resource *res0, *res1; static struct pcie_gadget_target *target; struct spear_pcie_gadget_config *config; int irq; res0 = platform_get_resource(pdev, IORESOURCE_MEM, 0); res1 = platform_get_resource(pdev, IORESOURCE_MEM, 1); irq = platform_get_irq(pdev, 0); target = dev_get_drvdata(&pdev->dev); config = &target->config; free_irq(irq, NULL); iounmap(config->va_dbi_base); iounmap(config->va_app_base); release_mem_region(res1->start, resource_size(res1)); release_mem_region(res0->start, resource_size(res0)); configfs_unregister_subsystem(&target->subsys); kfree(target); return 0; } static void spear_pcie_gadget_shutdown(struct platform_device *pdev) { } static struct platform_driver spear_pcie_gadget_driver = { .probe = spear_pcie_gadget_probe, .remove = spear_pcie_gadget_remove, .shutdown = spear_pcie_gadget_shutdown, .driver = { .name = "pcie-gadget-spear", .bus = &platform_bus_type }, }; module_platform_driver(spear_pcie_gadget_driver); MODULE_ALIAS("platform:pcie-gadget-spear"); MODULE_AUTHOR("Pratyush Anand"); MODULE_LICENSE("GPL");
gpl-2.0
Lenovo-K3/android_kernel_lenovo_msm8916
drivers/watchdog/nuc900_wdt.c
2253
8170
/* * Copyright (c) 2009 Nuvoton technology corporation. * * Wan ZongShun <mcuos.com@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation;version 2 of the License. * */ #include <linux/bitops.h> #include <linux/errno.h> #include <linux/fs.h> #include <linux/init.h> #include <linux/io.h> #include <linux/clk.h> #include <linux/kernel.h> #include <linux/miscdevice.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <linux/interrupt.h> #include <linux/types.h> #include <linux/watchdog.h> #include <linux/uaccess.h> #define REG_WTCR 0x1c #define WTCLK (0x01 << 10) #define WTE (0x01 << 7) /*wdt enable*/ #define WTIS (0x03 << 4) #define WTIF (0x01 << 3) #define WTRF (0x01 << 2) #define WTRE (0x01 << 1) #define WTR (0x01 << 0) /* * The watchdog time interval can be calculated via following formula: * WTIS real time interval (formula) * 0x00 ((2^ 14 ) * ((external crystal freq) / 256))seconds * 0x01 ((2^ 16 ) * ((external crystal freq) / 256))seconds * 0x02 ((2^ 18 ) * ((external crystal freq) / 256))seconds * 0x03 ((2^ 20 ) * ((external crystal freq) / 256))seconds * * The external crystal freq is 15Mhz in the nuc900 evaluation board. * So 0x00 = +-0.28 seconds, 0x01 = +-1.12 seconds, 0x02 = +-4.48 seconds, * 0x03 = +- 16.92 seconds.. */ #define WDT_HW_TIMEOUT 0x02 #define WDT_TIMEOUT (HZ/2) #define WDT_HEARTBEAT 15 static int heartbeat = WDT_HEARTBEAT; module_param(heartbeat, int, 0); MODULE_PARM_DESC(heartbeat, "Watchdog heartbeats in seconds. " "(default = " __MODULE_STRING(WDT_HEARTBEAT) ")"); 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 nuc900_wdt { struct resource *res; struct clk *wdt_clock; struct platform_device *pdev; void __iomem *wdt_base; char expect_close; struct timer_list timer; spinlock_t wdt_lock; unsigned long next_heartbeat; }; static unsigned long nuc900wdt_busy; static struct nuc900_wdt *nuc900_wdt; static inline void nuc900_wdt_keepalive(void) { unsigned int val; spin_lock(&nuc900_wdt->wdt_lock); val = __raw_readl(nuc900_wdt->wdt_base + REG_WTCR); val |= (WTR | WTIF); __raw_writel(val, nuc900_wdt->wdt_base + REG_WTCR); spin_unlock(&nuc900_wdt->wdt_lock); } static inline void nuc900_wdt_start(void) { unsigned int val; spin_lock(&nuc900_wdt->wdt_lock); val = __raw_readl(nuc900_wdt->wdt_base + REG_WTCR); val |= (WTRE | WTE | WTR | WTCLK | WTIF); val &= ~WTIS; val |= (WDT_HW_TIMEOUT << 0x04); __raw_writel(val, nuc900_wdt->wdt_base + REG_WTCR); spin_unlock(&nuc900_wdt->wdt_lock); nuc900_wdt->next_heartbeat = jiffies + heartbeat * HZ; mod_timer(&nuc900_wdt->timer, jiffies + WDT_TIMEOUT); } static inline void nuc900_wdt_stop(void) { unsigned int val; del_timer(&nuc900_wdt->timer); spin_lock(&nuc900_wdt->wdt_lock); val = __raw_readl(nuc900_wdt->wdt_base + REG_WTCR); val &= ~WTE; __raw_writel(val, nuc900_wdt->wdt_base + REG_WTCR); spin_unlock(&nuc900_wdt->wdt_lock); } static inline void nuc900_wdt_ping(void) { nuc900_wdt->next_heartbeat = jiffies + heartbeat * HZ; } static int nuc900_wdt_open(struct inode *inode, struct file *file) { if (test_and_set_bit(0, &nuc900wdt_busy)) return -EBUSY; nuc900_wdt_start(); return nonseekable_open(inode, file); } static int nuc900_wdt_close(struct inode *inode, struct file *file) { if (nuc900_wdt->expect_close == 42) nuc900_wdt_stop(); else { dev_crit(&nuc900_wdt->pdev->dev, "Unexpected close, not stopping watchdog!\n"); nuc900_wdt_ping(); } nuc900_wdt->expect_close = 0; clear_bit(0, &nuc900wdt_busy); return 0; } static const struct watchdog_info nuc900_wdt_info = { .identity = "nuc900 watchdog", .options = WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING | WDIOF_MAGICCLOSE, }; static long nuc900_wdt_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { void __user *argp = (void __user *)arg; int __user *p = argp; int new_value; switch (cmd) { case WDIOC_GETSUPPORT: return copy_to_user(argp, &nuc900_wdt_info, sizeof(nuc900_wdt_info)) ? -EFAULT : 0; case WDIOC_GETSTATUS: case WDIOC_GETBOOTSTATUS: return put_user(0, p); case WDIOC_KEEPALIVE: nuc900_wdt_ping(); return 0; case WDIOC_SETTIMEOUT: if (get_user(new_value, p)) return -EFAULT; heartbeat = new_value; nuc900_wdt_ping(); return put_user(new_value, p); case WDIOC_GETTIMEOUT: return put_user(heartbeat, p); default: return -ENOTTY; } } static ssize_t nuc900_wdt_write(struct file *file, const char __user *data, size_t len, loff_t *ppos) { if (!len) return 0; /* Scan for magic character */ if (!nowayout) { size_t i; nuc900_wdt->expect_close = 0; for (i = 0; i < len; i++) { char c; if (get_user(c, data + i)) return -EFAULT; if (c == 'V') { nuc900_wdt->expect_close = 42; break; } } } nuc900_wdt_ping(); return len; } static void nuc900_wdt_timer_ping(unsigned long data) { if (time_before(jiffies, nuc900_wdt->next_heartbeat)) { nuc900_wdt_keepalive(); mod_timer(&nuc900_wdt->timer, jiffies + WDT_TIMEOUT); } else dev_warn(&nuc900_wdt->pdev->dev, "Will reset the machine !\n"); } static const struct file_operations nuc900wdt_fops = { .owner = THIS_MODULE, .llseek = no_llseek, .unlocked_ioctl = nuc900_wdt_ioctl, .open = nuc900_wdt_open, .release = nuc900_wdt_close, .write = nuc900_wdt_write, }; static struct miscdevice nuc900wdt_miscdev = { .minor = WATCHDOG_MINOR, .name = "watchdog", .fops = &nuc900wdt_fops, }; static int nuc900wdt_probe(struct platform_device *pdev) { int ret = 0; nuc900_wdt = kzalloc(sizeof(struct nuc900_wdt), GFP_KERNEL); if (!nuc900_wdt) return -ENOMEM; nuc900_wdt->pdev = pdev; spin_lock_init(&nuc900_wdt->wdt_lock); nuc900_wdt->res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (nuc900_wdt->res == NULL) { dev_err(&pdev->dev, "no memory resource specified\n"); ret = -ENOENT; goto err_get; } if (!request_mem_region(nuc900_wdt->res->start, resource_size(nuc900_wdt->res), pdev->name)) { dev_err(&pdev->dev, "failed to get memory region\n"); ret = -ENOENT; goto err_get; } nuc900_wdt->wdt_base = ioremap(nuc900_wdt->res->start, resource_size(nuc900_wdt->res)); if (nuc900_wdt->wdt_base == NULL) { dev_err(&pdev->dev, "failed to ioremap() region\n"); ret = -EINVAL; goto err_req; } nuc900_wdt->wdt_clock = clk_get(&pdev->dev, NULL); if (IS_ERR(nuc900_wdt->wdt_clock)) { dev_err(&pdev->dev, "failed to find watchdog clock source\n"); ret = PTR_ERR(nuc900_wdt->wdt_clock); goto err_map; } clk_enable(nuc900_wdt->wdt_clock); setup_timer(&nuc900_wdt->timer, nuc900_wdt_timer_ping, 0); ret = misc_register(&nuc900wdt_miscdev); if (ret) { dev_err(&pdev->dev, "err register miscdev on minor=%d (%d)\n", WATCHDOG_MINOR, ret); goto err_clk; } return 0; err_clk: clk_disable(nuc900_wdt->wdt_clock); clk_put(nuc900_wdt->wdt_clock); err_map: iounmap(nuc900_wdt->wdt_base); err_req: release_mem_region(nuc900_wdt->res->start, resource_size(nuc900_wdt->res)); err_get: kfree(nuc900_wdt); return ret; } static int nuc900wdt_remove(struct platform_device *pdev) { misc_deregister(&nuc900wdt_miscdev); clk_disable(nuc900_wdt->wdt_clock); clk_put(nuc900_wdt->wdt_clock); iounmap(nuc900_wdt->wdt_base); release_mem_region(nuc900_wdt->res->start, resource_size(nuc900_wdt->res)); kfree(nuc900_wdt); return 0; } static struct platform_driver nuc900wdt_driver = { .probe = nuc900wdt_probe, .remove = nuc900wdt_remove, .driver = { .name = "nuc900-wdt", .owner = THIS_MODULE, }, }; module_platform_driver(nuc900wdt_driver); MODULE_AUTHOR("Wan ZongShun <mcuos.com@gmail.com>"); MODULE_DESCRIPTION("Watchdog driver for NUC900"); MODULE_LICENSE("GPL"); MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR); MODULE_ALIAS("platform:nuc900-wdt");
gpl-2.0
pasomnica/doubleslash-kernel-protou
drivers/scsi/sg.c
3021
71361
/* * History: * Started: Aug 9 by Lawrence Foard (entropy@world.std.com), * to allow user process control of SCSI devices. * Development Sponsored by Killy Corp. NY NY * * Original driver (sg.c): * Copyright (C) 1992 Lawrence Foard * Version 2 and 3 extensions to driver: * Copyright (C) 1998 - 2005 Douglas Gilbert * * Modified 19-JAN-1998 Richard Gooch <rgooch@atnf.csiro.au> Devfs support * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * */ static int sg_version_num = 30534; /* 2 digits for each component */ #define SG_VERSION_STR "3.5.34" /* * D. P. Gilbert (dgilbert@interlog.com, dougg@triode.net.au), notes: * - scsi logging is available via SCSI_LOG_TIMEOUT macros. First * the kernel/module needs to be built with CONFIG_SCSI_LOGGING * (otherwise the macros compile to empty statements). * */ #include <linux/module.h> #include <linux/fs.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/string.h> #include <linux/mm.h> #include <linux/errno.h> #include <linux/mtio.h> #include <linux/ioctl.h> #include <linux/slab.h> #include <linux/fcntl.h> #include <linux/init.h> #include <linux/poll.h> #include <linux/moduleparam.h> #include <linux/cdev.h> #include <linux/idr.h> #include <linux/seq_file.h> #include <linux/blkdev.h> #include <linux/delay.h> #include <linux/blktrace_api.h> #include <linux/mutex.h> #include "scsi.h" #include <scsi/scsi_dbg.h> #include <scsi/scsi_host.h> #include <scsi/scsi_driver.h> #include <scsi/scsi_ioctl.h> #include <scsi/sg.h> #include "scsi_logging.h" #ifdef CONFIG_SCSI_PROC_FS #include <linux/proc_fs.h> static char *sg_version_date = "20061027"; static int sg_proc_init(void); static void sg_proc_cleanup(void); #endif #define SG_ALLOW_DIO_DEF 0 #define SG_MAX_DEVS 32768 /* * Suppose you want to calculate the formula muldiv(x,m,d)=int(x * m / d) * Then when using 32 bit integers x * m may overflow during the calculation. * Replacing muldiv(x) by muldiv(x)=((x % d) * m) / d + int(x / d) * m * calculates the same, but prevents the overflow when both m and d * are "small" numbers (like HZ and USER_HZ). * Of course an overflow is inavoidable if the result of muldiv doesn't fit * in 32 bits. */ #define MULDIV(X,MUL,DIV) ((((X % DIV) * MUL) / DIV) + ((X / DIV) * MUL)) #define SG_DEFAULT_TIMEOUT MULDIV(SG_DEFAULT_TIMEOUT_USER, HZ, USER_HZ) int sg_big_buff = SG_DEF_RESERVED_SIZE; /* N.B. This variable is readable and writeable via /proc/scsi/sg/def_reserved_size . Each time sg_open() is called a buffer of this size (or less if there is not enough memory) will be reserved for use by this file descriptor. [Deprecated usage: this variable is also readable via /proc/sys/kernel/sg-big-buff if the sg driver is built into the kernel (i.e. it is not a module).] */ static int def_reserved_size = -1; /* picks up init parameter */ static int sg_allow_dio = SG_ALLOW_DIO_DEF; static int scatter_elem_sz = SG_SCATTER_SZ; static int scatter_elem_sz_prev = SG_SCATTER_SZ; #define SG_SECTOR_SZ 512 static int sg_add(struct device *, struct class_interface *); static void sg_remove(struct device *, struct class_interface *); static DEFINE_MUTEX(sg_mutex); static DEFINE_IDR(sg_index_idr); static DEFINE_RWLOCK(sg_index_lock); /* Also used to lock file descriptor list for device */ static struct class_interface sg_interface = { .add_dev = sg_add, .remove_dev = sg_remove, }; typedef struct sg_scatter_hold { /* holding area for scsi scatter gather info */ unsigned short k_use_sg; /* Count of kernel scatter-gather pieces */ unsigned sglist_len; /* size of malloc'd scatter-gather list ++ */ unsigned bufflen; /* Size of (aggregate) data buffer */ struct page **pages; int page_order; char dio_in_use; /* 0->indirect IO (or mmap), 1->dio */ unsigned char cmd_opcode; /* first byte of command */ } Sg_scatter_hold; struct sg_device; /* forward declarations */ struct sg_fd; typedef struct sg_request { /* SG_MAX_QUEUE requests outstanding per file */ struct sg_request *nextrp; /* NULL -> tail request (slist) */ struct sg_fd *parentfp; /* NULL -> not in use */ Sg_scatter_hold data; /* hold buffer, perhaps scatter list */ sg_io_hdr_t header; /* scsi command+info, see <scsi/sg.h> */ unsigned char sense_b[SCSI_SENSE_BUFFERSIZE]; char res_used; /* 1 -> using reserve buffer, 0 -> not ... */ char orphan; /* 1 -> drop on sight, 0 -> normal */ char sg_io_owned; /* 1 -> packet belongs to SG_IO */ volatile char done; /* 0->before bh, 1->before read, 2->read */ struct request *rq; struct bio *bio; struct execute_work ew; } Sg_request; typedef struct sg_fd { /* holds the state of a file descriptor */ struct list_head sfd_siblings; struct sg_device *parentdp; /* owning device */ wait_queue_head_t read_wait; /* queue read until command done */ rwlock_t rq_list_lock; /* protect access to list in req_arr */ int timeout; /* defaults to SG_DEFAULT_TIMEOUT */ int timeout_user; /* defaults to SG_DEFAULT_TIMEOUT_USER */ Sg_scatter_hold reserve; /* buffer held for this file descriptor */ unsigned save_scat_len; /* original length of trunc. scat. element */ Sg_request *headrp; /* head of request slist, NULL->empty */ struct fasync_struct *async_qp; /* used by asynchronous notification */ Sg_request req_arr[SG_MAX_QUEUE]; /* used as singly-linked list */ char low_dma; /* as in parent but possibly overridden to 1 */ char force_packid; /* 1 -> pack_id input to read(), 0 -> ignored */ volatile char closed; /* 1 -> fd closed but request(s) outstanding */ char cmd_q; /* 1 -> allow command queuing, 0 -> don't */ char next_cmd_len; /* 0 -> automatic (def), >0 -> use on next write() */ char keep_orphan; /* 0 -> drop orphan (def), 1 -> keep for read() */ char mmap_called; /* 0 -> mmap() never called on this fd */ struct kref f_ref; struct execute_work ew; } Sg_fd; typedef struct sg_device { /* holds the state of each scsi generic device */ struct scsi_device *device; wait_queue_head_t o_excl_wait; /* queue open() when O_EXCL in use */ int sg_tablesize; /* adapter's max scatter-gather table size */ u32 index; /* device index number */ struct list_head sfds; volatile char detached; /* 0->attached, 1->detached pending removal */ volatile char exclude; /* opened for exclusive access */ char sgdebug; /* 0->off, 1->sense, 9->dump dev, 10-> all devs */ struct gendisk *disk; struct cdev * cdev; /* char_dev [sysfs: /sys/cdev/major/sg<n>] */ struct kref d_ref; } Sg_device; /* tasklet or soft irq callback */ static void sg_rq_end_io(struct request *rq, int uptodate); static int sg_start_req(Sg_request *srp, unsigned char *cmd); static int sg_finish_rem_req(Sg_request * srp); static int sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size); static ssize_t sg_new_read(Sg_fd * sfp, char __user *buf, size_t count, Sg_request * srp); static ssize_t sg_new_write(Sg_fd *sfp, struct file *file, const char __user *buf, size_t count, int blocking, int read_only, int sg_io_owned, Sg_request **o_srp); static int sg_common_write(Sg_fd * sfp, Sg_request * srp, unsigned char *cmnd, int timeout, int blocking); static int sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer); static void sg_remove_scat(Sg_scatter_hold * schp); static void sg_build_reserve(Sg_fd * sfp, int req_size); static void sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size); static void sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp); static Sg_fd *sg_add_sfp(Sg_device * sdp, int dev); static void sg_remove_sfp(struct kref *); static Sg_request *sg_get_rq_mark(Sg_fd * sfp, int pack_id); static Sg_request *sg_add_request(Sg_fd * sfp); static int sg_remove_request(Sg_fd * sfp, Sg_request * srp); static int sg_res_in_use(Sg_fd * sfp); static Sg_device *sg_get_dev(int dev); static void sg_put_dev(Sg_device *sdp); #define SZ_SG_HEADER sizeof(struct sg_header) #define SZ_SG_IO_HDR sizeof(sg_io_hdr_t) #define SZ_SG_IOVEC sizeof(sg_iovec_t) #define SZ_SG_REQ_INFO sizeof(sg_req_info_t) static int sg_allow_access(struct file *filp, unsigned char *cmd) { struct sg_fd *sfp = filp->private_data; if (sfp->parentdp->device->type == TYPE_SCANNER) return 0; return blk_verify_command(cmd, filp->f_mode & FMODE_WRITE); } static int sg_open(struct inode *inode, struct file *filp) { int dev = iminor(inode); int flags = filp->f_flags; struct request_queue *q; Sg_device *sdp; Sg_fd *sfp; int res; int retval; mutex_lock(&sg_mutex); nonseekable_open(inode, filp); SCSI_LOG_TIMEOUT(3, printk("sg_open: dev=%d, flags=0x%x\n", dev, flags)); sdp = sg_get_dev(dev); if (IS_ERR(sdp)) { retval = PTR_ERR(sdp); sdp = NULL; goto sg_put; } /* This driver's module count bumped by fops_get in <linux/fs.h> */ /* Prevent the device driver from vanishing while we sleep */ retval = scsi_device_get(sdp->device); if (retval) goto sg_put; retval = scsi_autopm_get_device(sdp->device); if (retval) goto sdp_put; if (!((flags & O_NONBLOCK) || scsi_block_when_processing_errors(sdp->device))) { retval = -ENXIO; /* we are in error recovery for this device */ goto error_out; } if (flags & O_EXCL) { if (O_RDONLY == (flags & O_ACCMODE)) { retval = -EPERM; /* Can't lock it with read only access */ goto error_out; } if (!list_empty(&sdp->sfds) && (flags & O_NONBLOCK)) { retval = -EBUSY; goto error_out; } res = 0; __wait_event_interruptible(sdp->o_excl_wait, ((!list_empty(&sdp->sfds) || sdp->exclude) ? 0 : (sdp->exclude = 1)), res); if (res) { retval = res; /* -ERESTARTSYS because signal hit process */ goto error_out; } } else if (sdp->exclude) { /* some other fd has an exclusive lock on dev */ if (flags & O_NONBLOCK) { retval = -EBUSY; goto error_out; } res = 0; __wait_event_interruptible(sdp->o_excl_wait, (!sdp->exclude), res); if (res) { retval = res; /* -ERESTARTSYS because signal hit process */ goto error_out; } } if (sdp->detached) { retval = -ENODEV; goto error_out; } if (list_empty(&sdp->sfds)) { /* no existing opens on this device */ sdp->sgdebug = 0; q = sdp->device->request_queue; sdp->sg_tablesize = queue_max_segments(q); } if ((sfp = sg_add_sfp(sdp, dev))) filp->private_data = sfp; else { if (flags & O_EXCL) { sdp->exclude = 0; /* undo if error */ wake_up_interruptible(&sdp->o_excl_wait); } retval = -ENOMEM; goto error_out; } retval = 0; error_out: if (retval) { scsi_autopm_put_device(sdp->device); sdp_put: scsi_device_put(sdp->device); } sg_put: if (sdp) sg_put_dev(sdp); mutex_unlock(&sg_mutex); return retval; } /* Following function was formerly called 'sg_close' */ static int sg_release(struct inode *inode, struct file *filp) { Sg_device *sdp; Sg_fd *sfp; if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp))) return -ENXIO; SCSI_LOG_TIMEOUT(3, printk("sg_release: %s\n", sdp->disk->disk_name)); sfp->closed = 1; sdp->exclude = 0; wake_up_interruptible(&sdp->o_excl_wait); scsi_autopm_put_device(sdp->device); kref_put(&sfp->f_ref, sg_remove_sfp); return 0; } static ssize_t sg_read(struct file *filp, char __user *buf, size_t count, loff_t * ppos) { Sg_device *sdp; Sg_fd *sfp; Sg_request *srp; int req_pack_id = -1; sg_io_hdr_t *hp; struct sg_header *old_hdr = NULL; int retval = 0; if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp))) return -ENXIO; SCSI_LOG_TIMEOUT(3, printk("sg_read: %s, count=%d\n", sdp->disk->disk_name, (int) count)); if (!access_ok(VERIFY_WRITE, buf, count)) return -EFAULT; if (sfp->force_packid && (count >= SZ_SG_HEADER)) { old_hdr = kmalloc(SZ_SG_HEADER, GFP_KERNEL); if (!old_hdr) return -ENOMEM; if (__copy_from_user(old_hdr, buf, SZ_SG_HEADER)) { retval = -EFAULT; goto free_old_hdr; } if (old_hdr->reply_len < 0) { if (count >= SZ_SG_IO_HDR) { sg_io_hdr_t *new_hdr; new_hdr = kmalloc(SZ_SG_IO_HDR, GFP_KERNEL); if (!new_hdr) { retval = -ENOMEM; goto free_old_hdr; } retval =__copy_from_user (new_hdr, buf, SZ_SG_IO_HDR); req_pack_id = new_hdr->pack_id; kfree(new_hdr); if (retval) { retval = -EFAULT; goto free_old_hdr; } } } else req_pack_id = old_hdr->pack_id; } srp = sg_get_rq_mark(sfp, req_pack_id); if (!srp) { /* now wait on packet to arrive */ if (sdp->detached) { retval = -ENODEV; goto free_old_hdr; } if (filp->f_flags & O_NONBLOCK) { retval = -EAGAIN; goto free_old_hdr; } while (1) { retval = 0; /* following macro beats race condition */ __wait_event_interruptible(sfp->read_wait, (sdp->detached || (srp = sg_get_rq_mark(sfp, req_pack_id))), retval); if (sdp->detached) { retval = -ENODEV; goto free_old_hdr; } if (0 == retval) break; /* -ERESTARTSYS as signal hit process */ goto free_old_hdr; } } if (srp->header.interface_id != '\0') { retval = sg_new_read(sfp, buf, count, srp); goto free_old_hdr; } hp = &srp->header; if (old_hdr == NULL) { old_hdr = kmalloc(SZ_SG_HEADER, GFP_KERNEL); if (! old_hdr) { retval = -ENOMEM; goto free_old_hdr; } } memset(old_hdr, 0, SZ_SG_HEADER); old_hdr->reply_len = (int) hp->timeout; old_hdr->pack_len = old_hdr->reply_len; /* old, strange behaviour */ old_hdr->pack_id = hp->pack_id; old_hdr->twelve_byte = ((srp->data.cmd_opcode >= 0xc0) && (12 == hp->cmd_len)) ? 1 : 0; old_hdr->target_status = hp->masked_status; old_hdr->host_status = hp->host_status; old_hdr->driver_status = hp->driver_status; if ((CHECK_CONDITION & hp->masked_status) || (DRIVER_SENSE & hp->driver_status)) memcpy(old_hdr->sense_buffer, srp->sense_b, sizeof (old_hdr->sense_buffer)); switch (hp->host_status) { /* This setup of 'result' is for backward compatibility and is best ignored by the user who should use target, host + driver status */ case DID_OK: case DID_PASSTHROUGH: case DID_SOFT_ERROR: old_hdr->result = 0; break; case DID_NO_CONNECT: case DID_BUS_BUSY: case DID_TIME_OUT: old_hdr->result = EBUSY; break; case DID_BAD_TARGET: case DID_ABORT: case DID_PARITY: case DID_RESET: case DID_BAD_INTR: old_hdr->result = EIO; break; case DID_ERROR: old_hdr->result = (srp->sense_b[0] == 0 && hp->masked_status == GOOD) ? 0 : EIO; break; default: old_hdr->result = EIO; break; } /* Now copy the result back to the user buffer. */ if (count >= SZ_SG_HEADER) { if (__copy_to_user(buf, old_hdr, SZ_SG_HEADER)) { retval = -EFAULT; goto free_old_hdr; } buf += SZ_SG_HEADER; if (count > old_hdr->reply_len) count = old_hdr->reply_len; if (count > SZ_SG_HEADER) { if (sg_read_oxfer(srp, buf, count - SZ_SG_HEADER)) { retval = -EFAULT; goto free_old_hdr; } } } else count = (old_hdr->result == 0) ? 0 : -EIO; sg_finish_rem_req(srp); retval = count; free_old_hdr: kfree(old_hdr); return retval; } static ssize_t sg_new_read(Sg_fd * sfp, char __user *buf, size_t count, Sg_request * srp) { sg_io_hdr_t *hp = &srp->header; int err = 0; int len; if (count < SZ_SG_IO_HDR) { err = -EINVAL; goto err_out; } hp->sb_len_wr = 0; if ((hp->mx_sb_len > 0) && hp->sbp) { if ((CHECK_CONDITION & hp->masked_status) || (DRIVER_SENSE & hp->driver_status)) { int sb_len = SCSI_SENSE_BUFFERSIZE; sb_len = (hp->mx_sb_len > sb_len) ? sb_len : hp->mx_sb_len; len = 8 + (int) srp->sense_b[7]; /* Additional sense length field */ len = (len > sb_len) ? sb_len : len; if (copy_to_user(hp->sbp, srp->sense_b, len)) { err = -EFAULT; goto err_out; } hp->sb_len_wr = len; } } if (hp->masked_status || hp->host_status || hp->driver_status) hp->info |= SG_INFO_CHECK; if (copy_to_user(buf, hp, SZ_SG_IO_HDR)) { err = -EFAULT; goto err_out; } err_out: err = sg_finish_rem_req(srp); return (0 == err) ? count : err; } static ssize_t sg_write(struct file *filp, const char __user *buf, size_t count, loff_t * ppos) { int mxsize, cmd_size, k; int input_size, blocking; unsigned char opcode; Sg_device *sdp; Sg_fd *sfp; Sg_request *srp; struct sg_header old_hdr; sg_io_hdr_t *hp; unsigned char cmnd[MAX_COMMAND_SIZE]; if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp))) return -ENXIO; SCSI_LOG_TIMEOUT(3, printk("sg_write: %s, count=%d\n", sdp->disk->disk_name, (int) count)); if (sdp->detached) return -ENODEV; if (!((filp->f_flags & O_NONBLOCK) || scsi_block_when_processing_errors(sdp->device))) return -ENXIO; if (!access_ok(VERIFY_READ, buf, count)) return -EFAULT; /* protects following copy_from_user()s + get_user()s */ if (count < SZ_SG_HEADER) return -EIO; if (__copy_from_user(&old_hdr, buf, SZ_SG_HEADER)) return -EFAULT; blocking = !(filp->f_flags & O_NONBLOCK); if (old_hdr.reply_len < 0) return sg_new_write(sfp, filp, buf, count, blocking, 0, 0, NULL); if (count < (SZ_SG_HEADER + 6)) return -EIO; /* The minimum scsi command length is 6 bytes. */ if (!(srp = sg_add_request(sfp))) { SCSI_LOG_TIMEOUT(1, printk("sg_write: queue full\n")); return -EDOM; } buf += SZ_SG_HEADER; __get_user(opcode, buf); if (sfp->next_cmd_len > 0) { if (sfp->next_cmd_len > MAX_COMMAND_SIZE) { SCSI_LOG_TIMEOUT(1, printk("sg_write: command length too long\n")); sfp->next_cmd_len = 0; sg_remove_request(sfp, srp); return -EIO; } cmd_size = sfp->next_cmd_len; sfp->next_cmd_len = 0; /* reset so only this write() effected */ } else { cmd_size = COMMAND_SIZE(opcode); /* based on SCSI command group */ if ((opcode >= 0xc0) && old_hdr.twelve_byte) cmd_size = 12; } SCSI_LOG_TIMEOUT(4, printk( "sg_write: scsi opcode=0x%02x, cmd_size=%d\n", (int) opcode, cmd_size)); /* Determine buffer size. */ input_size = count - cmd_size; mxsize = (input_size > old_hdr.reply_len) ? input_size : old_hdr.reply_len; mxsize -= SZ_SG_HEADER; input_size -= SZ_SG_HEADER; if (input_size < 0) { sg_remove_request(sfp, srp); return -EIO; /* User did not pass enough bytes for this command. */ } hp = &srp->header; hp->interface_id = '\0'; /* indicator of old interface tunnelled */ hp->cmd_len = (unsigned char) cmd_size; hp->iovec_count = 0; hp->mx_sb_len = 0; if (input_size > 0) hp->dxfer_direction = (old_hdr.reply_len > SZ_SG_HEADER) ? SG_DXFER_TO_FROM_DEV : SG_DXFER_TO_DEV; else hp->dxfer_direction = (mxsize > 0) ? SG_DXFER_FROM_DEV : SG_DXFER_NONE; hp->dxfer_len = mxsize; if (hp->dxfer_direction == SG_DXFER_TO_DEV) hp->dxferp = (char __user *)buf + cmd_size; else hp->dxferp = NULL; hp->sbp = NULL; hp->timeout = old_hdr.reply_len; /* structure abuse ... */ hp->flags = input_size; /* structure abuse ... */ hp->pack_id = old_hdr.pack_id; hp->usr_ptr = NULL; if (__copy_from_user(cmnd, buf, cmd_size)) return -EFAULT; /* * SG_DXFER_TO_FROM_DEV is functionally equivalent to SG_DXFER_FROM_DEV, * but is is possible that the app intended SG_DXFER_TO_DEV, because there * is a non-zero input_size, so emit a warning. */ if (hp->dxfer_direction == SG_DXFER_TO_FROM_DEV) { static char cmd[TASK_COMM_LEN]; if (strcmp(current->comm, cmd) && printk_ratelimit()) { printk(KERN_WARNING "sg_write: data in/out %d/%d bytes for SCSI command 0x%x--" "guessing data in;\n " "program %s not setting count and/or reply_len properly\n", old_hdr.reply_len - (int)SZ_SG_HEADER, input_size, (unsigned int) cmnd[0], current->comm); strcpy(cmd, current->comm); } } k = sg_common_write(sfp, srp, cmnd, sfp->timeout, blocking); return (k < 0) ? k : count; } static ssize_t sg_new_write(Sg_fd *sfp, struct file *file, const char __user *buf, size_t count, int blocking, int read_only, int sg_io_owned, Sg_request **o_srp) { int k; Sg_request *srp; sg_io_hdr_t *hp; unsigned char cmnd[MAX_COMMAND_SIZE]; int timeout; unsigned long ul_timeout; if (count < SZ_SG_IO_HDR) return -EINVAL; if (!access_ok(VERIFY_READ, buf, count)) return -EFAULT; /* protects following copy_from_user()s + get_user()s */ sfp->cmd_q = 1; /* when sg_io_hdr seen, set command queuing on */ if (!(srp = sg_add_request(sfp))) { SCSI_LOG_TIMEOUT(1, printk("sg_new_write: queue full\n")); return -EDOM; } srp->sg_io_owned = sg_io_owned; hp = &srp->header; if (__copy_from_user(hp, buf, SZ_SG_IO_HDR)) { sg_remove_request(sfp, srp); return -EFAULT; } if (hp->interface_id != 'S') { sg_remove_request(sfp, srp); return -ENOSYS; } if (hp->flags & SG_FLAG_MMAP_IO) { if (hp->dxfer_len > sfp->reserve.bufflen) { sg_remove_request(sfp, srp); return -ENOMEM; /* MMAP_IO size must fit in reserve buffer */ } if (hp->flags & SG_FLAG_DIRECT_IO) { sg_remove_request(sfp, srp); return -EINVAL; /* either MMAP_IO or DIRECT_IO (not both) */ } if (sg_res_in_use(sfp)) { sg_remove_request(sfp, srp); return -EBUSY; /* reserve buffer already being used */ } } ul_timeout = msecs_to_jiffies(srp->header.timeout); timeout = (ul_timeout < INT_MAX) ? ul_timeout : INT_MAX; if ((!hp->cmdp) || (hp->cmd_len < 6) || (hp->cmd_len > sizeof (cmnd))) { sg_remove_request(sfp, srp); return -EMSGSIZE; } if (!access_ok(VERIFY_READ, hp->cmdp, hp->cmd_len)) { sg_remove_request(sfp, srp); return -EFAULT; /* protects following copy_from_user()s + get_user()s */ } if (__copy_from_user(cmnd, hp->cmdp, hp->cmd_len)) { sg_remove_request(sfp, srp); return -EFAULT; } if (read_only && sg_allow_access(file, cmnd)) { sg_remove_request(sfp, srp); return -EPERM; } k = sg_common_write(sfp, srp, cmnd, timeout, blocking); if (k < 0) return k; if (o_srp) *o_srp = srp; return count; } static int sg_common_write(Sg_fd * sfp, Sg_request * srp, unsigned char *cmnd, int timeout, int blocking) { int k, data_dir; Sg_device *sdp = sfp->parentdp; sg_io_hdr_t *hp = &srp->header; srp->data.cmd_opcode = cmnd[0]; /* hold opcode of command */ hp->status = 0; hp->masked_status = 0; hp->msg_status = 0; hp->info = 0; hp->host_status = 0; hp->driver_status = 0; hp->resid = 0; SCSI_LOG_TIMEOUT(4, printk("sg_common_write: scsi opcode=0x%02x, cmd_size=%d\n", (int) cmnd[0], (int) hp->cmd_len)); k = sg_start_req(srp, cmnd); if (k) { SCSI_LOG_TIMEOUT(1, printk("sg_common_write: start_req err=%d\n", k)); sg_finish_rem_req(srp); return k; /* probably out of space --> ENOMEM */ } if (sdp->detached) { if (srp->bio) blk_end_request_all(srp->rq, -EIO); sg_finish_rem_req(srp); return -ENODEV; } switch (hp->dxfer_direction) { case SG_DXFER_TO_FROM_DEV: case SG_DXFER_FROM_DEV: data_dir = DMA_FROM_DEVICE; break; case SG_DXFER_TO_DEV: data_dir = DMA_TO_DEVICE; break; case SG_DXFER_UNKNOWN: data_dir = DMA_BIDIRECTIONAL; break; default: data_dir = DMA_NONE; break; } hp->duration = jiffies_to_msecs(jiffies); srp->rq->timeout = timeout; kref_get(&sfp->f_ref); /* sg_rq_end_io() does kref_put(). */ blk_execute_rq_nowait(sdp->device->request_queue, sdp->disk, srp->rq, 1, sg_rq_end_io); return 0; } static int sg_ioctl(struct file *filp, unsigned int cmd_in, unsigned long arg) { void __user *p = (void __user *)arg; int __user *ip = p; int result, val, read_only; Sg_device *sdp; Sg_fd *sfp; Sg_request *srp; unsigned long iflags; if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp))) return -ENXIO; SCSI_LOG_TIMEOUT(3, printk("sg_ioctl: %s, cmd=0x%x\n", sdp->disk->disk_name, (int) cmd_in)); read_only = (O_RDWR != (filp->f_flags & O_ACCMODE)); switch (cmd_in) { case SG_IO: { int blocking = 1; /* ignore O_NONBLOCK flag */ if (sdp->detached) return -ENODEV; if (!scsi_block_when_processing_errors(sdp->device)) return -ENXIO; if (!access_ok(VERIFY_WRITE, p, SZ_SG_IO_HDR)) return -EFAULT; result = sg_new_write(sfp, filp, p, SZ_SG_IO_HDR, blocking, read_only, 1, &srp); if (result < 0) return result; while (1) { result = 0; /* following macro to beat race condition */ __wait_event_interruptible(sfp->read_wait, (srp->done || sdp->detached), result); if (sdp->detached) return -ENODEV; write_lock_irq(&sfp->rq_list_lock); if (srp->done) { srp->done = 2; write_unlock_irq(&sfp->rq_list_lock); break; } srp->orphan = 1; write_unlock_irq(&sfp->rq_list_lock); return result; /* -ERESTARTSYS because signal hit process */ } result = sg_new_read(sfp, p, SZ_SG_IO_HDR, srp); return (result < 0) ? result : 0; } case SG_SET_TIMEOUT: result = get_user(val, ip); if (result) return result; if (val < 0) return -EIO; if (val >= MULDIV (INT_MAX, USER_HZ, HZ)) val = MULDIV (INT_MAX, USER_HZ, HZ); sfp->timeout_user = val; sfp->timeout = MULDIV (val, HZ, USER_HZ); return 0; case SG_GET_TIMEOUT: /* N.B. User receives timeout as return value */ /* strange ..., for backward compatibility */ return sfp->timeout_user; case SG_SET_FORCE_LOW_DMA: result = get_user(val, ip); if (result) return result; if (val) { sfp->low_dma = 1; if ((0 == sfp->low_dma) && (0 == sg_res_in_use(sfp))) { val = (int) sfp->reserve.bufflen; sg_remove_scat(&sfp->reserve); sg_build_reserve(sfp, val); } } else { if (sdp->detached) return -ENODEV; sfp->low_dma = sdp->device->host->unchecked_isa_dma; } return 0; case SG_GET_LOW_DMA: return put_user((int) sfp->low_dma, ip); case SG_GET_SCSI_ID: if (!access_ok(VERIFY_WRITE, p, sizeof (sg_scsi_id_t))) return -EFAULT; else { sg_scsi_id_t __user *sg_idp = p; if (sdp->detached) return -ENODEV; __put_user((int) sdp->device->host->host_no, &sg_idp->host_no); __put_user((int) sdp->device->channel, &sg_idp->channel); __put_user((int) sdp->device->id, &sg_idp->scsi_id); __put_user((int) sdp->device->lun, &sg_idp->lun); __put_user((int) sdp->device->type, &sg_idp->scsi_type); __put_user((short) sdp->device->host->cmd_per_lun, &sg_idp->h_cmd_per_lun); __put_user((short) sdp->device->queue_depth, &sg_idp->d_queue_depth); __put_user(0, &sg_idp->unused[0]); __put_user(0, &sg_idp->unused[1]); return 0; } case SG_SET_FORCE_PACK_ID: result = get_user(val, ip); if (result) return result; sfp->force_packid = val ? 1 : 0; return 0; case SG_GET_PACK_ID: if (!access_ok(VERIFY_WRITE, ip, sizeof (int))) return -EFAULT; read_lock_irqsave(&sfp->rq_list_lock, iflags); for (srp = sfp->headrp; srp; srp = srp->nextrp) { if ((1 == srp->done) && (!srp->sg_io_owned)) { read_unlock_irqrestore(&sfp->rq_list_lock, iflags); __put_user(srp->header.pack_id, ip); return 0; } } read_unlock_irqrestore(&sfp->rq_list_lock, iflags); __put_user(-1, ip); return 0; case SG_GET_NUM_WAITING: read_lock_irqsave(&sfp->rq_list_lock, iflags); for (val = 0, srp = sfp->headrp; srp; srp = srp->nextrp) { if ((1 == srp->done) && (!srp->sg_io_owned)) ++val; } read_unlock_irqrestore(&sfp->rq_list_lock, iflags); return put_user(val, ip); case SG_GET_SG_TABLESIZE: return put_user(sdp->sg_tablesize, ip); case SG_SET_RESERVED_SIZE: result = get_user(val, ip); if (result) return result; if (val < 0) return -EINVAL; val = min_t(int, val, queue_max_sectors(sdp->device->request_queue) * 512); if (val != sfp->reserve.bufflen) { if (sg_res_in_use(sfp) || sfp->mmap_called) return -EBUSY; sg_remove_scat(&sfp->reserve); sg_build_reserve(sfp, val); } return 0; case SG_GET_RESERVED_SIZE: val = min_t(int, sfp->reserve.bufflen, queue_max_sectors(sdp->device->request_queue) * 512); return put_user(val, ip); case SG_SET_COMMAND_Q: result = get_user(val, ip); if (result) return result; sfp->cmd_q = val ? 1 : 0; return 0; case SG_GET_COMMAND_Q: return put_user((int) sfp->cmd_q, ip); case SG_SET_KEEP_ORPHAN: result = get_user(val, ip); if (result) return result; sfp->keep_orphan = val; return 0; case SG_GET_KEEP_ORPHAN: return put_user((int) sfp->keep_orphan, ip); case SG_NEXT_CMD_LEN: result = get_user(val, ip); if (result) return result; sfp->next_cmd_len = (val > 0) ? val : 0; return 0; case SG_GET_VERSION_NUM: return put_user(sg_version_num, ip); case SG_GET_ACCESS_COUNT: /* faked - we don't have a real access count anymore */ val = (sdp->device ? 1 : 0); return put_user(val, ip); case SG_GET_REQUEST_TABLE: if (!access_ok(VERIFY_WRITE, p, SZ_SG_REQ_INFO * SG_MAX_QUEUE)) return -EFAULT; else { sg_req_info_t *rinfo; unsigned int ms; rinfo = kmalloc(SZ_SG_REQ_INFO * SG_MAX_QUEUE, GFP_KERNEL); if (!rinfo) return -ENOMEM; read_lock_irqsave(&sfp->rq_list_lock, iflags); for (srp = sfp->headrp, val = 0; val < SG_MAX_QUEUE; ++val, srp = srp ? srp->nextrp : srp) { memset(&rinfo[val], 0, SZ_SG_REQ_INFO); if (srp) { rinfo[val].req_state = srp->done + 1; rinfo[val].problem = srp->header.masked_status & srp->header.host_status & srp->header.driver_status; if (srp->done) rinfo[val].duration = srp->header.duration; else { ms = jiffies_to_msecs(jiffies); rinfo[val].duration = (ms > srp->header.duration) ? (ms - srp->header.duration) : 0; } rinfo[val].orphan = srp->orphan; rinfo[val].sg_io_owned = srp->sg_io_owned; rinfo[val].pack_id = srp->header.pack_id; rinfo[val].usr_ptr = srp->header.usr_ptr; } } read_unlock_irqrestore(&sfp->rq_list_lock, iflags); result = __copy_to_user(p, rinfo, SZ_SG_REQ_INFO * SG_MAX_QUEUE); result = result ? -EFAULT : 0; kfree(rinfo); return result; } case SG_EMULATED_HOST: if (sdp->detached) return -ENODEV; return put_user(sdp->device->host->hostt->emulated, ip); case SG_SCSI_RESET: if (sdp->detached) return -ENODEV; if (filp->f_flags & O_NONBLOCK) { if (scsi_host_in_recovery(sdp->device->host)) return -EBUSY; } else if (!scsi_block_when_processing_errors(sdp->device)) return -EBUSY; result = get_user(val, ip); if (result) return result; if (SG_SCSI_RESET_NOTHING == val) return 0; switch (val) { case SG_SCSI_RESET_DEVICE: val = SCSI_TRY_RESET_DEVICE; break; case SG_SCSI_RESET_TARGET: val = SCSI_TRY_RESET_TARGET; break; case SG_SCSI_RESET_BUS: val = SCSI_TRY_RESET_BUS; break; case SG_SCSI_RESET_HOST: val = SCSI_TRY_RESET_HOST; break; default: return -EINVAL; } if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO)) return -EACCES; return (scsi_reset_provider(sdp->device, val) == SUCCESS) ? 0 : -EIO; case SCSI_IOCTL_SEND_COMMAND: if (sdp->detached) return -ENODEV; if (read_only) { unsigned char opcode = WRITE_6; Scsi_Ioctl_Command __user *siocp = p; if (copy_from_user(&opcode, siocp->data, 1)) return -EFAULT; if (sg_allow_access(filp, &opcode)) return -EPERM; } return sg_scsi_ioctl(sdp->device->request_queue, NULL, filp->f_mode, p); case SG_SET_DEBUG: result = get_user(val, ip); if (result) return result; sdp->sgdebug = (char) val; return 0; case SCSI_IOCTL_GET_IDLUN: case SCSI_IOCTL_GET_BUS_NUMBER: case SCSI_IOCTL_PROBE_HOST: case SG_GET_TRANSFORM: if (sdp->detached) return -ENODEV; return scsi_ioctl(sdp->device, cmd_in, p); case BLKSECTGET: return put_user(queue_max_sectors(sdp->device->request_queue) * 512, ip); case BLKTRACESETUP: return blk_trace_setup(sdp->device->request_queue, sdp->disk->disk_name, MKDEV(SCSI_GENERIC_MAJOR, sdp->index), NULL, (char *)arg); case BLKTRACESTART: return blk_trace_startstop(sdp->device->request_queue, 1); case BLKTRACESTOP: return blk_trace_startstop(sdp->device->request_queue, 0); case BLKTRACETEARDOWN: return blk_trace_remove(sdp->device->request_queue); default: if (read_only) return -EPERM; /* don't know so take safe approach */ return scsi_ioctl(sdp->device, cmd_in, p); } } static long sg_unlocked_ioctl(struct file *filp, unsigned int cmd_in, unsigned long arg) { int ret; mutex_lock(&sg_mutex); ret = sg_ioctl(filp, cmd_in, arg); mutex_unlock(&sg_mutex); return ret; } #ifdef CONFIG_COMPAT static long sg_compat_ioctl(struct file *filp, unsigned int cmd_in, unsigned long arg) { Sg_device *sdp; Sg_fd *sfp; struct scsi_device *sdev; if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp))) return -ENXIO; sdev = sdp->device; if (sdev->host->hostt->compat_ioctl) { int ret; ret = sdev->host->hostt->compat_ioctl(sdev, cmd_in, (void __user *)arg); return ret; } return -ENOIOCTLCMD; } #endif static unsigned int sg_poll(struct file *filp, poll_table * wait) { unsigned int res = 0; Sg_device *sdp; Sg_fd *sfp; Sg_request *srp; int count = 0; unsigned long iflags; if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)) || sfp->closed) return POLLERR; poll_wait(filp, &sfp->read_wait, wait); read_lock_irqsave(&sfp->rq_list_lock, iflags); for (srp = sfp->headrp; srp; srp = srp->nextrp) { /* if any read waiting, flag it */ if ((0 == res) && (1 == srp->done) && (!srp->sg_io_owned)) res = POLLIN | POLLRDNORM; ++count; } read_unlock_irqrestore(&sfp->rq_list_lock, iflags); if (sdp->detached) res |= POLLHUP; else if (!sfp->cmd_q) { if (0 == count) res |= POLLOUT | POLLWRNORM; } else if (count < SG_MAX_QUEUE) res |= POLLOUT | POLLWRNORM; SCSI_LOG_TIMEOUT(3, printk("sg_poll: %s, res=0x%x\n", sdp->disk->disk_name, (int) res)); return res; } static int sg_fasync(int fd, struct file *filp, int mode) { Sg_device *sdp; Sg_fd *sfp; if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp))) return -ENXIO; SCSI_LOG_TIMEOUT(3, printk("sg_fasync: %s, mode=%d\n", sdp->disk->disk_name, mode)); return fasync_helper(fd, filp, mode, &sfp->async_qp); } static int sg_vma_fault(struct vm_area_struct *vma, struct vm_fault *vmf) { Sg_fd *sfp; unsigned long offset, len, sa; Sg_scatter_hold *rsv_schp; int k, length; if ((NULL == vma) || (!(sfp = (Sg_fd *) vma->vm_private_data))) return VM_FAULT_SIGBUS; rsv_schp = &sfp->reserve; offset = vmf->pgoff << PAGE_SHIFT; if (offset >= rsv_schp->bufflen) return VM_FAULT_SIGBUS; SCSI_LOG_TIMEOUT(3, printk("sg_vma_fault: offset=%lu, scatg=%d\n", offset, rsv_schp->k_use_sg)); sa = vma->vm_start; length = 1 << (PAGE_SHIFT + rsv_schp->page_order); for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) { len = vma->vm_end - sa; len = (len < length) ? len : length; if (offset < len) { struct page *page = nth_page(rsv_schp->pages[k], offset >> PAGE_SHIFT); get_page(page); /* increment page count */ vmf->page = page; return 0; /* success */ } sa += len; offset -= len; } return VM_FAULT_SIGBUS; } static const struct vm_operations_struct sg_mmap_vm_ops = { .fault = sg_vma_fault, }; static int sg_mmap(struct file *filp, struct vm_area_struct *vma) { Sg_fd *sfp; unsigned long req_sz, len, sa; Sg_scatter_hold *rsv_schp; int k, length; if ((!filp) || (!vma) || (!(sfp = (Sg_fd *) filp->private_data))) return -ENXIO; req_sz = vma->vm_end - vma->vm_start; SCSI_LOG_TIMEOUT(3, printk("sg_mmap starting, vm_start=%p, len=%d\n", (void *) vma->vm_start, (int) req_sz)); if (vma->vm_pgoff) return -EINVAL; /* want no offset */ rsv_schp = &sfp->reserve; if (req_sz > rsv_schp->bufflen) return -ENOMEM; /* cannot map more than reserved buffer */ sa = vma->vm_start; length = 1 << (PAGE_SHIFT + rsv_schp->page_order); for (k = 0; k < rsv_schp->k_use_sg && sa < vma->vm_end; k++) { len = vma->vm_end - sa; len = (len < length) ? len : length; sa += len; } sfp->mmap_called = 1; vma->vm_flags |= VM_RESERVED; vma->vm_private_data = sfp; vma->vm_ops = &sg_mmap_vm_ops; return 0; } static void sg_rq_end_io_usercontext(struct work_struct *work) { struct sg_request *srp = container_of(work, struct sg_request, ew.work); struct sg_fd *sfp = srp->parentfp; sg_finish_rem_req(srp); kref_put(&sfp->f_ref, sg_remove_sfp); } /* * This function is a "bottom half" handler that is called by the mid * level when a command is completed (or has failed). */ static void sg_rq_end_io(struct request *rq, int uptodate) { struct sg_request *srp = rq->end_io_data; Sg_device *sdp; Sg_fd *sfp; unsigned long iflags; unsigned int ms; char *sense; int result, resid, done = 1; if (WARN_ON(srp->done != 0)) return; sfp = srp->parentfp; if (WARN_ON(sfp == NULL)) return; sdp = sfp->parentdp; if (unlikely(sdp->detached)) printk(KERN_INFO "sg_rq_end_io: device detached\n"); sense = rq->sense; result = rq->errors; resid = rq->resid_len; SCSI_LOG_TIMEOUT(4, printk("sg_cmd_done: %s, pack_id=%d, res=0x%x\n", sdp->disk->disk_name, srp->header.pack_id, result)); srp->header.resid = resid; ms = jiffies_to_msecs(jiffies); srp->header.duration = (ms > srp->header.duration) ? (ms - srp->header.duration) : 0; if (0 != result) { struct scsi_sense_hdr sshdr; srp->header.status = 0xff & result; srp->header.masked_status = status_byte(result); srp->header.msg_status = msg_byte(result); srp->header.host_status = host_byte(result); srp->header.driver_status = driver_byte(result); if ((sdp->sgdebug > 0) && ((CHECK_CONDITION == srp->header.masked_status) || (COMMAND_TERMINATED == srp->header.masked_status))) __scsi_print_sense("sg_cmd_done", sense, SCSI_SENSE_BUFFERSIZE); /* Following if statement is a patch supplied by Eric Youngdale */ if (driver_byte(result) != 0 && scsi_normalize_sense(sense, SCSI_SENSE_BUFFERSIZE, &sshdr) && !scsi_sense_is_deferred(&sshdr) && sshdr.sense_key == UNIT_ATTENTION && sdp->device->removable) { /* Detected possible disc change. Set the bit - this */ /* may be used if there are filesystems using this device */ sdp->device->changed = 1; } } /* Rely on write phase to clean out srp status values, so no "else" */ write_lock_irqsave(&sfp->rq_list_lock, iflags); if (unlikely(srp->orphan)) { if (sfp->keep_orphan) srp->sg_io_owned = 0; else done = 0; } srp->done = done; write_unlock_irqrestore(&sfp->rq_list_lock, iflags); if (likely(done)) { /* Now wake up any sg_read() that is waiting for this * packet. */ wake_up_interruptible(&sfp->read_wait); kill_fasync(&sfp->async_qp, SIGPOLL, POLL_IN); kref_put(&sfp->f_ref, sg_remove_sfp); } else { INIT_WORK(&srp->ew.work, sg_rq_end_io_usercontext); schedule_work(&srp->ew.work); } } static const struct file_operations sg_fops = { .owner = THIS_MODULE, .read = sg_read, .write = sg_write, .poll = sg_poll, .unlocked_ioctl = sg_unlocked_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = sg_compat_ioctl, #endif .open = sg_open, .mmap = sg_mmap, .release = sg_release, .fasync = sg_fasync, .llseek = no_llseek, }; static struct class *sg_sysfs_class; static int sg_sysfs_valid = 0; static Sg_device *sg_alloc(struct gendisk *disk, struct scsi_device *scsidp) { struct request_queue *q = scsidp->request_queue; Sg_device *sdp; unsigned long iflags; int error; u32 k; sdp = kzalloc(sizeof(Sg_device), GFP_KERNEL); if (!sdp) { printk(KERN_WARNING "kmalloc Sg_device failure\n"); return ERR_PTR(-ENOMEM); } if (!idr_pre_get(&sg_index_idr, GFP_KERNEL)) { printk(KERN_WARNING "idr expansion Sg_device failure\n"); error = -ENOMEM; goto out; } write_lock_irqsave(&sg_index_lock, iflags); error = idr_get_new(&sg_index_idr, sdp, &k); if (error) { write_unlock_irqrestore(&sg_index_lock, iflags); printk(KERN_WARNING "idr allocation Sg_device failure: %d\n", error); goto out; } if (unlikely(k >= SG_MAX_DEVS)) goto overflow; SCSI_LOG_TIMEOUT(3, printk("sg_alloc: dev=%d \n", k)); sprintf(disk->disk_name, "sg%d", k); disk->first_minor = k; sdp->disk = disk; sdp->device = scsidp; INIT_LIST_HEAD(&sdp->sfds); init_waitqueue_head(&sdp->o_excl_wait); sdp->sg_tablesize = queue_max_segments(q); sdp->index = k; kref_init(&sdp->d_ref); write_unlock_irqrestore(&sg_index_lock, iflags); error = 0; out: if (error) { kfree(sdp); return ERR_PTR(error); } return sdp; overflow: idr_remove(&sg_index_idr, k); write_unlock_irqrestore(&sg_index_lock, iflags); sdev_printk(KERN_WARNING, scsidp, "Unable to attach sg device type=%d, minor " "number exceeds %d\n", scsidp->type, SG_MAX_DEVS - 1); error = -ENODEV; goto out; } static int sg_add(struct device *cl_dev, struct class_interface *cl_intf) { struct scsi_device *scsidp = to_scsi_device(cl_dev->parent); struct gendisk *disk; Sg_device *sdp = NULL; struct cdev * cdev = NULL; int error; unsigned long iflags; disk = alloc_disk(1); if (!disk) { printk(KERN_WARNING "alloc_disk failed\n"); return -ENOMEM; } disk->major = SCSI_GENERIC_MAJOR; error = -ENOMEM; cdev = cdev_alloc(); if (!cdev) { printk(KERN_WARNING "cdev_alloc failed\n"); goto out; } cdev->owner = THIS_MODULE; cdev->ops = &sg_fops; sdp = sg_alloc(disk, scsidp); if (IS_ERR(sdp)) { printk(KERN_WARNING "sg_alloc failed\n"); error = PTR_ERR(sdp); goto out; } error = cdev_add(cdev, MKDEV(SCSI_GENERIC_MAJOR, sdp->index), 1); if (error) goto cdev_add_err; sdp->cdev = cdev; if (sg_sysfs_valid) { struct device *sg_class_member; sg_class_member = device_create(sg_sysfs_class, cl_dev->parent, MKDEV(SCSI_GENERIC_MAJOR, sdp->index), sdp, "%s", disk->disk_name); if (IS_ERR(sg_class_member)) { printk(KERN_ERR "sg_add: " "device_create failed\n"); error = PTR_ERR(sg_class_member); goto cdev_add_err; } error = sysfs_create_link(&scsidp->sdev_gendev.kobj, &sg_class_member->kobj, "generic"); if (error) printk(KERN_ERR "sg_add: unable to make symlink " "'generic' back to sg%d\n", sdp->index); } else printk(KERN_WARNING "sg_add: sg_sys Invalid\n"); sdev_printk(KERN_NOTICE, scsidp, "Attached scsi generic sg%d type %d\n", sdp->index, scsidp->type); dev_set_drvdata(cl_dev, sdp); return 0; cdev_add_err: write_lock_irqsave(&sg_index_lock, iflags); idr_remove(&sg_index_idr, sdp->index); write_unlock_irqrestore(&sg_index_lock, iflags); kfree(sdp); out: put_disk(disk); if (cdev) cdev_del(cdev); return error; } static void sg_device_destroy(struct kref *kref) { struct sg_device *sdp = container_of(kref, struct sg_device, d_ref); unsigned long flags; /* CAUTION! Note that the device can still be found via idr_find() * even though the refcount is 0. Therefore, do idr_remove() BEFORE * any other cleanup. */ write_lock_irqsave(&sg_index_lock, flags); idr_remove(&sg_index_idr, sdp->index); write_unlock_irqrestore(&sg_index_lock, flags); SCSI_LOG_TIMEOUT(3, printk("sg_device_destroy: %s\n", sdp->disk->disk_name)); put_disk(sdp->disk); kfree(sdp); } static void sg_remove(struct device *cl_dev, struct class_interface *cl_intf) { struct scsi_device *scsidp = to_scsi_device(cl_dev->parent); Sg_device *sdp = dev_get_drvdata(cl_dev); unsigned long iflags; Sg_fd *sfp; if (!sdp || sdp->detached) return; SCSI_LOG_TIMEOUT(3, printk("sg_remove: %s\n", sdp->disk->disk_name)); /* Need a write lock to set sdp->detached. */ write_lock_irqsave(&sg_index_lock, iflags); sdp->detached = 1; list_for_each_entry(sfp, &sdp->sfds, sfd_siblings) { wake_up_interruptible(&sfp->read_wait); kill_fasync(&sfp->async_qp, SIGPOLL, POLL_HUP); } write_unlock_irqrestore(&sg_index_lock, iflags); sysfs_remove_link(&scsidp->sdev_gendev.kobj, "generic"); device_destroy(sg_sysfs_class, MKDEV(SCSI_GENERIC_MAJOR, sdp->index)); cdev_del(sdp->cdev); sdp->cdev = NULL; sg_put_dev(sdp); } module_param_named(scatter_elem_sz, scatter_elem_sz, int, S_IRUGO | S_IWUSR); module_param_named(def_reserved_size, def_reserved_size, int, S_IRUGO | S_IWUSR); module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR); MODULE_AUTHOR("Douglas Gilbert"); MODULE_DESCRIPTION("SCSI generic (sg) driver"); MODULE_LICENSE("GPL"); MODULE_VERSION(SG_VERSION_STR); MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR); MODULE_PARM_DESC(scatter_elem_sz, "scatter gather element " "size (default: max(SG_SCATTER_SZ, PAGE_SIZE))"); MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd"); MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))"); static int __init init_sg(void) { int rc; if (scatter_elem_sz < PAGE_SIZE) { scatter_elem_sz = PAGE_SIZE; scatter_elem_sz_prev = scatter_elem_sz; } if (def_reserved_size >= 0) sg_big_buff = def_reserved_size; else def_reserved_size = sg_big_buff; rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0), SG_MAX_DEVS, "sg"); if (rc) return rc; sg_sysfs_class = class_create(THIS_MODULE, "scsi_generic"); if ( IS_ERR(sg_sysfs_class) ) { rc = PTR_ERR(sg_sysfs_class); goto err_out; } sg_sysfs_valid = 1; rc = scsi_register_interface(&sg_interface); if (0 == rc) { #ifdef CONFIG_SCSI_PROC_FS sg_proc_init(); #endif /* CONFIG_SCSI_PROC_FS */ return 0; } class_destroy(sg_sysfs_class); err_out: unregister_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0), SG_MAX_DEVS); return rc; } static void __exit exit_sg(void) { #ifdef CONFIG_SCSI_PROC_FS sg_proc_cleanup(); #endif /* CONFIG_SCSI_PROC_FS */ scsi_unregister_interface(&sg_interface); class_destroy(sg_sysfs_class); sg_sysfs_valid = 0; unregister_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0), SG_MAX_DEVS); idr_destroy(&sg_index_idr); } static int sg_start_req(Sg_request *srp, unsigned char *cmd) { int res; struct request *rq; Sg_fd *sfp = srp->parentfp; sg_io_hdr_t *hp = &srp->header; int dxfer_len = (int) hp->dxfer_len; int dxfer_dir = hp->dxfer_direction; unsigned int iov_count = hp->iovec_count; Sg_scatter_hold *req_schp = &srp->data; Sg_scatter_hold *rsv_schp = &sfp->reserve; struct request_queue *q = sfp->parentdp->device->request_queue; struct rq_map_data *md, map_data; int rw = hp->dxfer_direction == SG_DXFER_TO_DEV ? WRITE : READ; SCSI_LOG_TIMEOUT(4, printk(KERN_INFO "sg_start_req: dxfer_len=%d\n", dxfer_len)); rq = blk_get_request(q, rw, GFP_ATOMIC); if (!rq) return -ENOMEM; memcpy(rq->cmd, cmd, hp->cmd_len); rq->cmd_len = hp->cmd_len; rq->cmd_type = REQ_TYPE_BLOCK_PC; srp->rq = rq; rq->end_io_data = srp; rq->sense = srp->sense_b; rq->retries = SG_DEFAULT_RETRIES; if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE)) return 0; if (sg_allow_dio && hp->flags & SG_FLAG_DIRECT_IO && dxfer_dir != SG_DXFER_UNKNOWN && !iov_count && !sfp->parentdp->device->host->unchecked_isa_dma && blk_rq_aligned(q, (unsigned long)hp->dxferp, dxfer_len)) md = NULL; else md = &map_data; if (md) { if (!sg_res_in_use(sfp) && dxfer_len <= rsv_schp->bufflen) sg_link_reserve(sfp, srp, dxfer_len); else { res = sg_build_indirect(req_schp, sfp, dxfer_len); if (res) return res; } md->pages = req_schp->pages; md->page_order = req_schp->page_order; md->nr_entries = req_schp->k_use_sg; md->offset = 0; md->null_mapped = hp->dxferp ? 0 : 1; if (dxfer_dir == SG_DXFER_TO_FROM_DEV) md->from_user = 1; else md->from_user = 0; } if (iov_count) { int len, size = sizeof(struct sg_iovec) * iov_count; struct iovec *iov; iov = memdup_user(hp->dxferp, size); if (IS_ERR(iov)) return PTR_ERR(iov); len = iov_length(iov, iov_count); if (hp->dxfer_len < len) { iov_count = iov_shorten(iov, iov_count, hp->dxfer_len); len = hp->dxfer_len; } res = blk_rq_map_user_iov(q, rq, md, (struct sg_iovec *)iov, iov_count, len, GFP_ATOMIC); kfree(iov); } else res = blk_rq_map_user(q, rq, md, hp->dxferp, hp->dxfer_len, GFP_ATOMIC); if (!res) { srp->bio = rq->bio; if (!md) { req_schp->dio_in_use = 1; hp->info |= SG_INFO_DIRECT_IO; } } return res; } static int sg_finish_rem_req(Sg_request * srp) { int ret = 0; Sg_fd *sfp = srp->parentfp; Sg_scatter_hold *req_schp = &srp->data; SCSI_LOG_TIMEOUT(4, printk("sg_finish_rem_req: res_used=%d\n", (int) srp->res_used)); if (srp->rq) { if (srp->bio) ret = blk_rq_unmap_user(srp->bio); blk_put_request(srp->rq); } if (srp->res_used) sg_unlink_reserve(sfp, srp); else sg_remove_scat(req_schp); sg_remove_request(sfp, srp); return ret; } static int sg_build_sgat(Sg_scatter_hold * schp, const Sg_fd * sfp, int tablesize) { int sg_bufflen = tablesize * sizeof(struct page *); gfp_t gfp_flags = GFP_ATOMIC | __GFP_NOWARN; schp->pages = kzalloc(sg_bufflen, gfp_flags); if (!schp->pages) return -ENOMEM; schp->sglist_len = sg_bufflen; return tablesize; /* number of scat_gath elements allocated */ } static int sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size) { int ret_sz = 0, i, k, rem_sz, num, mx_sc_elems; int sg_tablesize = sfp->parentdp->sg_tablesize; int blk_size = buff_size, order; gfp_t gfp_mask = GFP_ATOMIC | __GFP_COMP | __GFP_NOWARN; if (blk_size < 0) return -EFAULT; if (0 == blk_size) ++blk_size; /* don't know why */ /* round request up to next highest SG_SECTOR_SZ byte boundary */ blk_size = ALIGN(blk_size, SG_SECTOR_SZ); SCSI_LOG_TIMEOUT(4, printk("sg_build_indirect: buff_size=%d, blk_size=%d\n", buff_size, blk_size)); /* N.B. ret_sz carried into this block ... */ mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize); if (mx_sc_elems < 0) return mx_sc_elems; /* most likely -ENOMEM */ num = scatter_elem_sz; if (unlikely(num != scatter_elem_sz_prev)) { if (num < PAGE_SIZE) { scatter_elem_sz = PAGE_SIZE; scatter_elem_sz_prev = PAGE_SIZE; } else scatter_elem_sz_prev = num; } if (sfp->low_dma) gfp_mask |= GFP_DMA; if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO)) gfp_mask |= __GFP_ZERO; order = get_order(num); retry: ret_sz = 1 << (PAGE_SHIFT + order); for (k = 0, rem_sz = blk_size; rem_sz > 0 && k < mx_sc_elems; k++, rem_sz -= ret_sz) { num = (rem_sz > scatter_elem_sz_prev) ? scatter_elem_sz_prev : rem_sz; schp->pages[k] = alloc_pages(gfp_mask, order); if (!schp->pages[k]) goto out; if (num == scatter_elem_sz_prev) { if (unlikely(ret_sz > scatter_elem_sz_prev)) { scatter_elem_sz = ret_sz; scatter_elem_sz_prev = ret_sz; } } SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k=%d, num=%d, " "ret_sz=%d\n", k, num, ret_sz)); } /* end of for loop */ schp->page_order = order; schp->k_use_sg = k; SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k_use_sg=%d, " "rem_sz=%d\n", k, rem_sz)); schp->bufflen = blk_size; if (rem_sz > 0) /* must have failed */ return -ENOMEM; return 0; out: for (i = 0; i < k; i++) __free_pages(schp->pages[i], order); if (--order >= 0) goto retry; return -ENOMEM; } static void sg_remove_scat(Sg_scatter_hold * schp) { SCSI_LOG_TIMEOUT(4, printk("sg_remove_scat: k_use_sg=%d\n", schp->k_use_sg)); if (schp->pages && schp->sglist_len > 0) { if (!schp->dio_in_use) { int k; for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) { SCSI_LOG_TIMEOUT(5, printk( "sg_remove_scat: k=%d, pg=0x%p\n", k, schp->pages[k])); __free_pages(schp->pages[k], schp->page_order); } kfree(schp->pages); } } memset(schp, 0, sizeof (*schp)); } static int sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer) { Sg_scatter_hold *schp = &srp->data; int k, num; SCSI_LOG_TIMEOUT(4, printk("sg_read_oxfer: num_read_xfer=%d\n", num_read_xfer)); if ((!outp) || (num_read_xfer <= 0)) return 0; num = 1 << (PAGE_SHIFT + schp->page_order); for (k = 0; k < schp->k_use_sg && schp->pages[k]; k++) { if (num > num_read_xfer) { if (__copy_to_user(outp, page_address(schp->pages[k]), num_read_xfer)) return -EFAULT; break; } else { if (__copy_to_user(outp, page_address(schp->pages[k]), num)) return -EFAULT; num_read_xfer -= num; if (num_read_xfer <= 0) break; outp += num; } } return 0; } static void sg_build_reserve(Sg_fd * sfp, int req_size) { Sg_scatter_hold *schp = &sfp->reserve; SCSI_LOG_TIMEOUT(4, printk("sg_build_reserve: req_size=%d\n", req_size)); do { if (req_size < PAGE_SIZE) req_size = PAGE_SIZE; if (0 == sg_build_indirect(schp, sfp, req_size)) return; else sg_remove_scat(schp); req_size >>= 1; /* divide by 2 */ } while (req_size > (PAGE_SIZE / 2)); } static void sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size) { Sg_scatter_hold *req_schp = &srp->data; Sg_scatter_hold *rsv_schp = &sfp->reserve; int k, num, rem; srp->res_used = 1; SCSI_LOG_TIMEOUT(4, printk("sg_link_reserve: size=%d\n", size)); rem = size; num = 1 << (PAGE_SHIFT + rsv_schp->page_order); for (k = 0; k < rsv_schp->k_use_sg; k++) { if (rem <= num) { req_schp->k_use_sg = k + 1; req_schp->sglist_len = rsv_schp->sglist_len; req_schp->pages = rsv_schp->pages; req_schp->bufflen = size; req_schp->page_order = rsv_schp->page_order; break; } else rem -= num; } if (k >= rsv_schp->k_use_sg) SCSI_LOG_TIMEOUT(1, printk("sg_link_reserve: BAD size\n")); } static void sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp) { Sg_scatter_hold *req_schp = &srp->data; SCSI_LOG_TIMEOUT(4, printk("sg_unlink_reserve: req->k_use_sg=%d\n", (int) req_schp->k_use_sg)); req_schp->k_use_sg = 0; req_schp->bufflen = 0; req_schp->pages = NULL; req_schp->page_order = 0; req_schp->sglist_len = 0; sfp->save_scat_len = 0; srp->res_used = 0; } static Sg_request * sg_get_rq_mark(Sg_fd * sfp, int pack_id) { Sg_request *resp; unsigned long iflags; write_lock_irqsave(&sfp->rq_list_lock, iflags); for (resp = sfp->headrp; resp; resp = resp->nextrp) { /* look for requests that are ready + not SG_IO owned */ if ((1 == resp->done) && (!resp->sg_io_owned) && ((-1 == pack_id) || (resp->header.pack_id == pack_id))) { resp->done = 2; /* guard against other readers */ break; } } write_unlock_irqrestore(&sfp->rq_list_lock, iflags); return resp; } /* always adds to end of list */ static Sg_request * sg_add_request(Sg_fd * sfp) { int k; unsigned long iflags; Sg_request *resp; Sg_request *rp = sfp->req_arr; write_lock_irqsave(&sfp->rq_list_lock, iflags); resp = sfp->headrp; if (!resp) { memset(rp, 0, sizeof (Sg_request)); rp->parentfp = sfp; resp = rp; sfp->headrp = resp; } else { if (0 == sfp->cmd_q) resp = NULL; /* command queuing disallowed */ else { for (k = 0; k < SG_MAX_QUEUE; ++k, ++rp) { if (!rp->parentfp) break; } if (k < SG_MAX_QUEUE) { memset(rp, 0, sizeof (Sg_request)); rp->parentfp = sfp; while (resp->nextrp) resp = resp->nextrp; resp->nextrp = rp; resp = rp; } else resp = NULL; } } if (resp) { resp->nextrp = NULL; resp->header.duration = jiffies_to_msecs(jiffies); } write_unlock_irqrestore(&sfp->rq_list_lock, iflags); return resp; } /* Return of 1 for found; 0 for not found */ static int sg_remove_request(Sg_fd * sfp, Sg_request * srp) { Sg_request *prev_rp; Sg_request *rp; unsigned long iflags; int res = 0; if ((!sfp) || (!srp) || (!sfp->headrp)) return res; write_lock_irqsave(&sfp->rq_list_lock, iflags); prev_rp = sfp->headrp; if (srp == prev_rp) { sfp->headrp = prev_rp->nextrp; prev_rp->parentfp = NULL; res = 1; } else { while ((rp = prev_rp->nextrp)) { if (srp == rp) { prev_rp->nextrp = rp->nextrp; rp->parentfp = NULL; res = 1; break; } prev_rp = rp; } } write_unlock_irqrestore(&sfp->rq_list_lock, iflags); return res; } static Sg_fd * sg_add_sfp(Sg_device * sdp, int dev) { Sg_fd *sfp; unsigned long iflags; int bufflen; sfp = kzalloc(sizeof(*sfp), GFP_ATOMIC | __GFP_NOWARN); if (!sfp) return NULL; init_waitqueue_head(&sfp->read_wait); rwlock_init(&sfp->rq_list_lock); kref_init(&sfp->f_ref); sfp->timeout = SG_DEFAULT_TIMEOUT; sfp->timeout_user = SG_DEFAULT_TIMEOUT_USER; sfp->force_packid = SG_DEF_FORCE_PACK_ID; sfp->low_dma = (SG_DEF_FORCE_LOW_DMA == 0) ? sdp->device->host->unchecked_isa_dma : 1; sfp->cmd_q = SG_DEF_COMMAND_Q; sfp->keep_orphan = SG_DEF_KEEP_ORPHAN; sfp->parentdp = sdp; write_lock_irqsave(&sg_index_lock, iflags); list_add_tail(&sfp->sfd_siblings, &sdp->sfds); write_unlock_irqrestore(&sg_index_lock, iflags); SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp: sfp=0x%p\n", sfp)); if (unlikely(sg_big_buff != def_reserved_size)) sg_big_buff = def_reserved_size; bufflen = min_t(int, sg_big_buff, queue_max_sectors(sdp->device->request_queue) * 512); sg_build_reserve(sfp, bufflen); SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp: bufflen=%d, k_use_sg=%d\n", sfp->reserve.bufflen, sfp->reserve.k_use_sg)); kref_get(&sdp->d_ref); __module_get(THIS_MODULE); return sfp; } static void sg_remove_sfp_usercontext(struct work_struct *work) { struct sg_fd *sfp = container_of(work, struct sg_fd, ew.work); struct sg_device *sdp = sfp->parentdp; /* Cleanup any responses which were never read(). */ while (sfp->headrp) sg_finish_rem_req(sfp->headrp); if (sfp->reserve.bufflen > 0) { SCSI_LOG_TIMEOUT(6, printk("sg_remove_sfp: bufflen=%d, k_use_sg=%d\n", (int) sfp->reserve.bufflen, (int) sfp->reserve.k_use_sg)); sg_remove_scat(&sfp->reserve); } SCSI_LOG_TIMEOUT(6, printk("sg_remove_sfp: %s, sfp=0x%p\n", sdp->disk->disk_name, sfp)); kfree(sfp); scsi_device_put(sdp->device); sg_put_dev(sdp); module_put(THIS_MODULE); } static void sg_remove_sfp(struct kref *kref) { struct sg_fd *sfp = container_of(kref, struct sg_fd, f_ref); struct sg_device *sdp = sfp->parentdp; unsigned long iflags; write_lock_irqsave(&sg_index_lock, iflags); list_del(&sfp->sfd_siblings); write_unlock_irqrestore(&sg_index_lock, iflags); wake_up_interruptible(&sdp->o_excl_wait); INIT_WORK(&sfp->ew.work, sg_remove_sfp_usercontext); schedule_work(&sfp->ew.work); } static int sg_res_in_use(Sg_fd * sfp) { const Sg_request *srp; unsigned long iflags; read_lock_irqsave(&sfp->rq_list_lock, iflags); for (srp = sfp->headrp; srp; srp = srp->nextrp) if (srp->res_used) break; read_unlock_irqrestore(&sfp->rq_list_lock, iflags); return srp ? 1 : 0; } #ifdef CONFIG_SCSI_PROC_FS static int sg_idr_max_id(int id, void *p, void *data) { int *k = data; if (*k < id) *k = id; return 0; } static int sg_last_dev(void) { int k = -1; unsigned long iflags; read_lock_irqsave(&sg_index_lock, iflags); idr_for_each(&sg_index_idr, sg_idr_max_id, &k); read_unlock_irqrestore(&sg_index_lock, iflags); return k + 1; /* origin 1 */ } #endif /* must be called with sg_index_lock held */ static Sg_device *sg_lookup_dev(int dev) { return idr_find(&sg_index_idr, dev); } static Sg_device *sg_get_dev(int dev) { struct sg_device *sdp; unsigned long flags; read_lock_irqsave(&sg_index_lock, flags); sdp = sg_lookup_dev(dev); if (!sdp) sdp = ERR_PTR(-ENXIO); else if (sdp->detached) { /* If sdp->detached, then the refcount may already be 0, in * which case it would be a bug to do kref_get(). */ sdp = ERR_PTR(-ENODEV); } else kref_get(&sdp->d_ref); read_unlock_irqrestore(&sg_index_lock, flags); return sdp; } static void sg_put_dev(struct sg_device *sdp) { kref_put(&sdp->d_ref, sg_device_destroy); } #ifdef CONFIG_SCSI_PROC_FS static struct proc_dir_entry *sg_proc_sgp = NULL; static char sg_proc_sg_dirname[] = "scsi/sg"; static int sg_proc_seq_show_int(struct seq_file *s, void *v); static int sg_proc_single_open_adio(struct inode *inode, struct file *file); static ssize_t sg_proc_write_adio(struct file *filp, const char __user *buffer, size_t count, loff_t *off); static const struct file_operations adio_fops = { .owner = THIS_MODULE, .open = sg_proc_single_open_adio, .read = seq_read, .llseek = seq_lseek, .write = sg_proc_write_adio, .release = single_release, }; static int sg_proc_single_open_dressz(struct inode *inode, struct file *file); static ssize_t sg_proc_write_dressz(struct file *filp, const char __user *buffer, size_t count, loff_t *off); static const struct file_operations dressz_fops = { .owner = THIS_MODULE, .open = sg_proc_single_open_dressz, .read = seq_read, .llseek = seq_lseek, .write = sg_proc_write_dressz, .release = single_release, }; static int sg_proc_seq_show_version(struct seq_file *s, void *v); static int sg_proc_single_open_version(struct inode *inode, struct file *file); static const struct file_operations version_fops = { .owner = THIS_MODULE, .open = sg_proc_single_open_version, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static int sg_proc_seq_show_devhdr(struct seq_file *s, void *v); static int sg_proc_single_open_devhdr(struct inode *inode, struct file *file); static const struct file_operations devhdr_fops = { .owner = THIS_MODULE, .open = sg_proc_single_open_devhdr, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static int sg_proc_seq_show_dev(struct seq_file *s, void *v); static int sg_proc_open_dev(struct inode *inode, struct file *file); static void * dev_seq_start(struct seq_file *s, loff_t *pos); static void * dev_seq_next(struct seq_file *s, void *v, loff_t *pos); static void dev_seq_stop(struct seq_file *s, void *v); static const struct file_operations dev_fops = { .owner = THIS_MODULE, .open = sg_proc_open_dev, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static const struct seq_operations dev_seq_ops = { .start = dev_seq_start, .next = dev_seq_next, .stop = dev_seq_stop, .show = sg_proc_seq_show_dev, }; static int sg_proc_seq_show_devstrs(struct seq_file *s, void *v); static int sg_proc_open_devstrs(struct inode *inode, struct file *file); static const struct file_operations devstrs_fops = { .owner = THIS_MODULE, .open = sg_proc_open_devstrs, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static const struct seq_operations devstrs_seq_ops = { .start = dev_seq_start, .next = dev_seq_next, .stop = dev_seq_stop, .show = sg_proc_seq_show_devstrs, }; static int sg_proc_seq_show_debug(struct seq_file *s, void *v); static int sg_proc_open_debug(struct inode *inode, struct file *file); static const struct file_operations debug_fops = { .owner = THIS_MODULE, .open = sg_proc_open_debug, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static const struct seq_operations debug_seq_ops = { .start = dev_seq_start, .next = dev_seq_next, .stop = dev_seq_stop, .show = sg_proc_seq_show_debug, }; struct sg_proc_leaf { const char * name; const struct file_operations * fops; }; static struct sg_proc_leaf sg_proc_leaf_arr[] = { {"allow_dio", &adio_fops}, {"debug", &debug_fops}, {"def_reserved_size", &dressz_fops}, {"device_hdr", &devhdr_fops}, {"devices", &dev_fops}, {"device_strs", &devstrs_fops}, {"version", &version_fops} }; static int sg_proc_init(void) { int k, mask; int num_leaves = ARRAY_SIZE(sg_proc_leaf_arr); struct sg_proc_leaf * leaf; sg_proc_sgp = proc_mkdir(sg_proc_sg_dirname, NULL); if (!sg_proc_sgp) return 1; for (k = 0; k < num_leaves; ++k) { leaf = &sg_proc_leaf_arr[k]; mask = leaf->fops->write ? S_IRUGO | S_IWUSR : S_IRUGO; proc_create(leaf->name, mask, sg_proc_sgp, leaf->fops); } return 0; } static void sg_proc_cleanup(void) { int k; int num_leaves = ARRAY_SIZE(sg_proc_leaf_arr); if (!sg_proc_sgp) return; for (k = 0; k < num_leaves; ++k) remove_proc_entry(sg_proc_leaf_arr[k].name, sg_proc_sgp); remove_proc_entry(sg_proc_sg_dirname, NULL); } static int sg_proc_seq_show_int(struct seq_file *s, void *v) { seq_printf(s, "%d\n", *((int *)s->private)); return 0; } static int sg_proc_single_open_adio(struct inode *inode, struct file *file) { return single_open(file, sg_proc_seq_show_int, &sg_allow_dio); } static ssize_t sg_proc_write_adio(struct file *filp, const char __user *buffer, size_t count, loff_t *off) { int num; char buff[11]; if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO)) return -EACCES; num = (count < 10) ? count : 10; if (copy_from_user(buff, buffer, num)) return -EFAULT; buff[num] = '\0'; sg_allow_dio = simple_strtoul(buff, NULL, 10) ? 1 : 0; return count; } static int sg_proc_single_open_dressz(struct inode *inode, struct file *file) { return single_open(file, sg_proc_seq_show_int, &sg_big_buff); } static ssize_t sg_proc_write_dressz(struct file *filp, const char __user *buffer, size_t count, loff_t *off) { int num; unsigned long k = ULONG_MAX; char buff[11]; if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO)) return -EACCES; num = (count < 10) ? count : 10; if (copy_from_user(buff, buffer, num)) return -EFAULT; buff[num] = '\0'; k = simple_strtoul(buff, NULL, 10); if (k <= 1048576) { /* limit "big buff" to 1 MB */ sg_big_buff = k; return count; } return -ERANGE; } static int sg_proc_seq_show_version(struct seq_file *s, void *v) { seq_printf(s, "%d\t%s [%s]\n", sg_version_num, SG_VERSION_STR, sg_version_date); return 0; } static int sg_proc_single_open_version(struct inode *inode, struct file *file) { return single_open(file, sg_proc_seq_show_version, NULL); } static int sg_proc_seq_show_devhdr(struct seq_file *s, void *v) { seq_printf(s, "host\tchan\tid\tlun\ttype\topens\tqdepth\tbusy\t" "online\n"); return 0; } static int sg_proc_single_open_devhdr(struct inode *inode, struct file *file) { return single_open(file, sg_proc_seq_show_devhdr, NULL); } struct sg_proc_deviter { loff_t index; size_t max; }; static void * dev_seq_start(struct seq_file *s, loff_t *pos) { struct sg_proc_deviter * it = kmalloc(sizeof(*it), GFP_KERNEL); s->private = it; if (! it) return NULL; it->index = *pos; it->max = sg_last_dev(); if (it->index >= it->max) return NULL; return it; } static void * dev_seq_next(struct seq_file *s, void *v, loff_t *pos) { struct sg_proc_deviter * it = s->private; *pos = ++it->index; return (it->index < it->max) ? it : NULL; } static void dev_seq_stop(struct seq_file *s, void *v) { kfree(s->private); } static int sg_proc_open_dev(struct inode *inode, struct file *file) { return seq_open(file, &dev_seq_ops); } static int sg_proc_seq_show_dev(struct seq_file *s, void *v) { struct sg_proc_deviter * it = (struct sg_proc_deviter *) v; Sg_device *sdp; struct scsi_device *scsidp; unsigned long iflags; read_lock_irqsave(&sg_index_lock, iflags); sdp = it ? sg_lookup_dev(it->index) : NULL; if (sdp && (scsidp = sdp->device) && (!sdp->detached)) seq_printf(s, "%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n", scsidp->host->host_no, scsidp->channel, scsidp->id, scsidp->lun, (int) scsidp->type, 1, (int) scsidp->queue_depth, (int) scsidp->device_busy, (int) scsi_device_online(scsidp)); else seq_printf(s, "-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\n"); read_unlock_irqrestore(&sg_index_lock, iflags); return 0; } static int sg_proc_open_devstrs(struct inode *inode, struct file *file) { return seq_open(file, &devstrs_seq_ops); } static int sg_proc_seq_show_devstrs(struct seq_file *s, void *v) { struct sg_proc_deviter * it = (struct sg_proc_deviter *) v; Sg_device *sdp; struct scsi_device *scsidp; unsigned long iflags; read_lock_irqsave(&sg_index_lock, iflags); sdp = it ? sg_lookup_dev(it->index) : NULL; if (sdp && (scsidp = sdp->device) && (!sdp->detached)) seq_printf(s, "%8.8s\t%16.16s\t%4.4s\n", scsidp->vendor, scsidp->model, scsidp->rev); else seq_printf(s, "<no active device>\n"); read_unlock_irqrestore(&sg_index_lock, iflags); return 0; } /* must be called while holding sg_index_lock */ static void sg_proc_debug_helper(struct seq_file *s, Sg_device * sdp) { int k, m, new_interface, blen, usg; Sg_request *srp; Sg_fd *fp; const sg_io_hdr_t *hp; const char * cp; unsigned int ms; k = 0; list_for_each_entry(fp, &sdp->sfds, sfd_siblings) { k++; read_lock(&fp->rq_list_lock); /* irqs already disabled */ seq_printf(s, " FD(%d): timeout=%dms bufflen=%d " "(res)sgat=%d low_dma=%d\n", k, jiffies_to_msecs(fp->timeout), fp->reserve.bufflen, (int) fp->reserve.k_use_sg, (int) fp->low_dma); seq_printf(s, " cmd_q=%d f_packid=%d k_orphan=%d closed=%d\n", (int) fp->cmd_q, (int) fp->force_packid, (int) fp->keep_orphan, (int) fp->closed); for (m = 0, srp = fp->headrp; srp != NULL; ++m, srp = srp->nextrp) { hp = &srp->header; new_interface = (hp->interface_id == '\0') ? 0 : 1; if (srp->res_used) { if (new_interface && (SG_FLAG_MMAP_IO & hp->flags)) cp = " mmap>> "; else cp = " rb>> "; } else { if (SG_INFO_DIRECT_IO_MASK & hp->info) cp = " dio>> "; else cp = " "; } seq_printf(s, cp); blen = srp->data.bufflen; usg = srp->data.k_use_sg; seq_printf(s, srp->done ? ((1 == srp->done) ? "rcv:" : "fin:") : "act:"); seq_printf(s, " id=%d blen=%d", srp->header.pack_id, blen); if (srp->done) seq_printf(s, " dur=%d", hp->duration); else { ms = jiffies_to_msecs(jiffies); seq_printf(s, " t_o/elap=%d/%d", (new_interface ? hp->timeout : jiffies_to_msecs(fp->timeout)), (ms > hp->duration ? ms - hp->duration : 0)); } seq_printf(s, "ms sgat=%d op=0x%02x\n", usg, (int) srp->data.cmd_opcode); } if (0 == m) seq_printf(s, " No requests active\n"); read_unlock(&fp->rq_list_lock); } } static int sg_proc_open_debug(struct inode *inode, struct file *file) { return seq_open(file, &debug_seq_ops); } static int sg_proc_seq_show_debug(struct seq_file *s, void *v) { struct sg_proc_deviter * it = (struct sg_proc_deviter *) v; Sg_device *sdp; unsigned long iflags; if (it && (0 == it->index)) { seq_printf(s, "max_active_device=%d(origin 1)\n", (int)it->max); seq_printf(s, " def_reserved_size=%d\n", sg_big_buff); } read_lock_irqsave(&sg_index_lock, iflags); sdp = it ? sg_lookup_dev(it->index) : NULL; if (sdp && !list_empty(&sdp->sfds)) { struct scsi_device *scsidp = sdp->device; seq_printf(s, " >>> device=%s ", sdp->disk->disk_name); if (sdp->detached) seq_printf(s, "detached pending close "); else seq_printf (s, "scsi%d chan=%d id=%d lun=%d em=%d", scsidp->host->host_no, scsidp->channel, scsidp->id, scsidp->lun, scsidp->host->hostt->emulated); seq_printf(s, " sg_tablesize=%d excl=%d\n", sdp->sg_tablesize, sdp->exclude); sg_proc_debug_helper(s, sdp); } read_unlock_irqrestore(&sg_index_lock, iflags); return 0; } #endif /* CONFIG_SCSI_PROC_FS */ module_init(init_sg); module_exit(exit_sg);
gpl-2.0
shimabde/android_kernel_samsung_galaxys2plus-common
drivers/isdn/hardware/eicon/maintidi.c
4301
68416
/* * Copyright (c) Eicon Networks, 2000. * This source file is supplied for the use with Eicon Networks range of DIVA Server Adapters. * Eicon File Revision : 1.9 * 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 OF ANY KIND WHATSOEVER INCLUDING ANY 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 "platform.h" #include "kst_ifc.h" #include "di_defs.h" #include "maintidi.h" #include "pc.h" #include "man_defs.h" extern void diva_mnt_internal_dprintf (dword drv_id, dword type, char* p, ...); #define MODEM_PARSE_ENTRIES 16 /* amount of variables of interest */ #define FAX_PARSE_ENTRIES 12 /* amount of variables of interest */ #define LINE_PARSE_ENTRIES 15 /* amount of variables of interest */ #define STAT_PARSE_ENTRIES 70 /* amount of variables of interest */ /* LOCAL FUNCTIONS */ static int DivaSTraceLibraryStart (void* hLib); static int DivaSTraceLibraryStop (void* hLib); static int SuperTraceLibraryFinit (void* hLib); static void* SuperTraceGetHandle (void* hLib); static int SuperTraceMessageInput (void* hLib); static int SuperTraceSetAudioTap (void* hLib, int Channel, int on); static int SuperTraceSetBChannel (void* hLib, int Channel, int on); static int SuperTraceSetDChannel (void* hLib, int on); static int SuperTraceSetInfo (void* hLib, int on); static int SuperTraceClearCall (void* hLib, int Channel); static int SuperTraceGetOutgoingCallStatistics (void* hLib); static int SuperTraceGetIncomingCallStatistics (void* hLib); static int SuperTraceGetModemStatistics (void* hLib); static int SuperTraceGetFaxStatistics (void* hLib); static int SuperTraceGetBLayer1Statistics (void* hLib); static int SuperTraceGetBLayer2Statistics (void* hLib); static int SuperTraceGetDLayer1Statistics (void* hLib); static int SuperTraceGetDLayer2Statistics (void* hLib); /* LOCAL FUNCTIONS */ static int ScheduleNextTraceRequest (diva_strace_context_t* pLib); static int process_idi_event (diva_strace_context_t* pLib, diva_man_var_header_t* pVar); static int process_idi_info (diva_strace_context_t* pLib, diva_man_var_header_t* pVar); static int diva_modem_event (diva_strace_context_t* pLib, int Channel); static int diva_fax_event (diva_strace_context_t* pLib, int Channel); static int diva_line_event (diva_strace_context_t* pLib, int Channel); static int diva_modem_info (diva_strace_context_t* pLib, int Channel, diva_man_var_header_t* pVar); static int diva_fax_info (diva_strace_context_t* pLib, int Channel, diva_man_var_header_t* pVar); static int diva_line_info (diva_strace_context_t* pLib, int Channel, diva_man_var_header_t* pVar); static int diva_ifc_statistics (diva_strace_context_t* pLib, diva_man_var_header_t* pVar); static diva_man_var_header_t* get_next_var (diva_man_var_header_t* pVar); static diva_man_var_header_t* find_var (diva_man_var_header_t* pVar, const char* name); static int diva_strace_read_int (diva_man_var_header_t* pVar, int* var); static int diva_strace_read_uint (diva_man_var_header_t* pVar, dword* var); static int diva_strace_read_asz (diva_man_var_header_t* pVar, char* var); static int diva_strace_read_asc (diva_man_var_header_t* pVar, char* var); static int diva_strace_read_ie (diva_man_var_header_t* pVar, diva_trace_ie_t* var); static void diva_create_parse_table (diva_strace_context_t* pLib); static void diva_trace_error (diva_strace_context_t* pLib, int error, const char* file, int line); static void diva_trace_notify_user (diva_strace_context_t* pLib, int Channel, int notify_subject); static int diva_trace_read_variable (diva_man_var_header_t* pVar, void* variable); /* Initialize the library and return context of the created trace object that will represent the IDI adapter. Return 0 on error. */ diva_strace_library_interface_t* DivaSTraceLibraryCreateInstance (int Adapter, const diva_trace_library_user_interface_t* user_proc, byte* pmem) { diva_strace_context_t* pLib = (diva_strace_context_t*)pmem; int i; if (!pLib) { return NULL; } pmem += sizeof(*pLib); memset(pLib, 0x00, sizeof(*pLib)); pLib->Adapter = Adapter; /* Set up Library Interface */ pLib->instance.hLib = pLib; pLib->instance.DivaSTraceLibraryStart = DivaSTraceLibraryStart; pLib->instance.DivaSTraceLibraryStop = DivaSTraceLibraryStop; pLib->instance.DivaSTraceLibraryFinit = SuperTraceLibraryFinit; pLib->instance.DivaSTraceMessageInput = SuperTraceMessageInput; pLib->instance.DivaSTraceGetHandle = SuperTraceGetHandle; pLib->instance.DivaSTraceSetAudioTap = SuperTraceSetAudioTap; pLib->instance.DivaSTraceSetBChannel = SuperTraceSetBChannel; pLib->instance.DivaSTraceSetDChannel = SuperTraceSetDChannel; pLib->instance.DivaSTraceSetInfo = SuperTraceSetInfo; pLib->instance.DivaSTraceGetOutgoingCallStatistics = \ SuperTraceGetOutgoingCallStatistics; pLib->instance.DivaSTraceGetIncomingCallStatistics = \ SuperTraceGetIncomingCallStatistics; pLib->instance.DivaSTraceGetModemStatistics = \ SuperTraceGetModemStatistics; pLib->instance.DivaSTraceGetFaxStatistics = \ SuperTraceGetFaxStatistics; pLib->instance.DivaSTraceGetBLayer1Statistics = \ SuperTraceGetBLayer1Statistics; pLib->instance.DivaSTraceGetBLayer2Statistics = \ SuperTraceGetBLayer2Statistics; pLib->instance.DivaSTraceGetDLayer1Statistics = \ SuperTraceGetDLayer1Statistics; pLib->instance.DivaSTraceGetDLayer2Statistics = \ SuperTraceGetDLayer2Statistics; pLib->instance.DivaSTraceClearCall = SuperTraceClearCall; if (user_proc) { pLib->user_proc_table.user_context = user_proc->user_context; pLib->user_proc_table.notify_proc = user_proc->notify_proc; pLib->user_proc_table.trace_proc = user_proc->trace_proc; pLib->user_proc_table.error_notify_proc = user_proc->error_notify_proc; } if (!(pLib->hAdapter = SuperTraceOpenAdapter (Adapter))) { diva_mnt_internal_dprintf (0, DLI_ERR, "Can not open XDI adapter"); return NULL; } pLib->Channels = SuperTraceGetNumberOfChannels (pLib->hAdapter); /* Calculate amount of parte table entites necessary to translate information from all events of onterest */ pLib->parse_entries = (MODEM_PARSE_ENTRIES + FAX_PARSE_ENTRIES + \ STAT_PARSE_ENTRIES + \ LINE_PARSE_ENTRIES + 1) * pLib->Channels; pLib->parse_table = (diva_strace_path2action_t*)pmem; for (i = 0; i < 30; i++) { pLib->lines[i].pInterface = &pLib->Interface; pLib->lines[i].pInterfaceStat = &pLib->InterfaceStat; } pLib->e.R = &pLib->RData; pLib->req_busy = 1; pLib->rc_ok = ASSIGN_OK; diva_create_parse_table (pLib); return ((diva_strace_library_interface_t*)pLib); } static int DivaSTraceLibraryStart (void* hLib) { diva_strace_context_t* pLib = (diva_strace_context_t*)hLib; return (SuperTraceASSIGN (pLib->hAdapter, pLib->buffer)); } /* Return (-1) on error Return (0) if was initiated or pending Return (1) if removal is complete */ static int DivaSTraceLibraryStop (void* hLib) { diva_strace_context_t* pLib = (diva_strace_context_t*)hLib; if (!pLib->e.Id) { /* Was never started/assigned */ return (1); } switch (pLib->removal_state) { case 0: pLib->removal_state = 1; ScheduleNextTraceRequest(pLib); break; case 3: return (1); } return (0); } static int SuperTraceLibraryFinit (void* hLib) { diva_strace_context_t* pLib = (diva_strace_context_t*)hLib; if (pLib) { if (pLib->hAdapter) { SuperTraceCloseAdapter (pLib->hAdapter); } return (0); } return (-1); } static void* SuperTraceGetHandle (void* hLib) { diva_strace_context_t* pLib = (diva_strace_context_t*)hLib; return (&pLib->e); } /* After library handle object is gone in signaled state this function should be called and will pick up incoming IDI messages (return codes and indications). */ static int SuperTraceMessageInput (void* hLib) { diva_strace_context_t* pLib = (diva_strace_context_t*)hLib; int ret = 0; byte Rc, Ind; if (pLib->e.complete == 255) { /* Process return code */ pLib->req_busy = 0; Rc = pLib->e.Rc; pLib->e.Rc = 0; if (pLib->removal_state == 2) { pLib->removal_state = 3; return (0); } if (Rc != pLib->rc_ok) { int ignore = 0; /* Auto-detect amount of events/channels and features */ if (pLib->general_b_ch_event == 1) { pLib->general_b_ch_event = 2; ignore = 1; } else if (pLib->general_fax_event == 1) { pLib->general_fax_event = 2; ignore = 1; } else if (pLib->general_mdm_event == 1) { pLib->general_mdm_event = 2; ignore = 1; } else if ((pLib->ChannelsTraceActive < pLib->Channels) && pLib->ChannelsTraceActive) { pLib->ChannelsTraceActive = pLib->Channels; ignore = 1; } else if (pLib->ModemTraceActive < pLib->Channels) { pLib->ModemTraceActive = pLib->Channels; ignore = 1; } else if (pLib->FaxTraceActive < pLib->Channels) { pLib->FaxTraceActive = pLib->Channels; ignore = 1; } else if (pLib->audio_trace_init == 2) { ignore = 1; pLib->audio_trace_init = 1; } else if (pLib->eye_pattern_pending) { pLib->eye_pattern_pending = 0; ignore = 1; } else if (pLib->audio_tap_pending) { pLib->audio_tap_pending = 0; ignore = 1; } if (!ignore) { return (-1); /* request failed */ } } else { if (pLib->general_b_ch_event == 1) { pLib->ChannelsTraceActive = pLib->Channels; pLib->general_b_ch_event = 2; } else if (pLib->general_fax_event == 1) { pLib->general_fax_event = 2; pLib->FaxTraceActive = pLib->Channels; } else if (pLib->general_mdm_event == 1) { pLib->general_mdm_event = 2; pLib->ModemTraceActive = pLib->Channels; } } if (pLib->audio_trace_init == 2) { pLib->audio_trace_init = 1; } pLib->rc_ok = 0xff; /* default OK after assign was done */ if ((ret = ScheduleNextTraceRequest(pLib))) { return (-1); } } else { /* Process indication Always 'RNR' indication if return code is pending */ Ind = pLib->e.Ind; pLib->e.Ind = 0; if (pLib->removal_state) { pLib->e.RNum = 0; pLib->e.RNR = 2; } else if (pLib->req_busy) { pLib->e.RNum = 0; pLib->e.RNR = 1; } else { if (pLib->e.complete != 0x02) { /* Look-ahead call, set up buffers */ pLib->e.RNum = 1; pLib->e.R->P = (byte*)&pLib->buffer[0]; pLib->e.R->PLength = (word)(sizeof(pLib->buffer) - 1); } else { /* Indication reception complete, process it now */ byte* p = (byte*)&pLib->buffer[0]; pLib->buffer[pLib->e.R->PLength] = 0; /* terminate I.E. with zero */ switch (Ind) { case MAN_COMBI_IND: { int total_length = pLib->e.R->PLength; word this_ind_length; while (total_length > 3 && *p) { Ind = *p++; this_ind_length = (word)p[0] | ((word)p[1] << 8); p += 2; switch (Ind) { case MAN_INFO_IND: if (process_idi_info (pLib, (diva_man_var_header_t*)p)) { return (-1); } break; case MAN_EVENT_IND: if (process_idi_event (pLib, (diva_man_var_header_t*)p)) { return (-1); } break; case MAN_TRACE_IND: if (pLib->trace_on == 1) { /* Ignore first trace event that is result of EVENT_ON operation */ pLib->trace_on++; } else { /* Delivery XLOG buffer to application */ if (pLib->user_proc_table.trace_proc) { (*(pLib->user_proc_table.trace_proc))(pLib->user_proc_table.user_context, &pLib->instance, pLib->Adapter, p, this_ind_length); } } break; default: diva_mnt_internal_dprintf (0, DLI_ERR, "Unknown IDI Ind (DMA mode): %02x", Ind); } p += (this_ind_length+1); total_length -= (4 + this_ind_length); } } break; case MAN_INFO_IND: if (process_idi_info (pLib, (diva_man_var_header_t*)p)) { return (-1); } break; case MAN_EVENT_IND: if (process_idi_event (pLib, (diva_man_var_header_t*)p)) { return (-1); } break; case MAN_TRACE_IND: if (pLib->trace_on == 1) { /* Ignore first trace event that is result of EVENT_ON operation */ pLib->trace_on++; } else { /* Delivery XLOG buffer to application */ if (pLib->user_proc_table.trace_proc) { (*(pLib->user_proc_table.trace_proc))(pLib->user_proc_table.user_context, &pLib->instance, pLib->Adapter, p, pLib->e.R->PLength); } } break; default: diva_mnt_internal_dprintf (0, DLI_ERR, "Unknown IDI Ind: %02x", Ind); } } } } if ((ret = ScheduleNextTraceRequest(pLib))) { return (-1); } return (ret); } /* Internal state machine responsible for scheduling of requests */ static int ScheduleNextTraceRequest (diva_strace_context_t* pLib) { char name[64]; int ret = 0; int i; if (pLib->req_busy) { return (0); } if (pLib->removal_state == 1) { if (SuperTraceREMOVE (pLib->hAdapter)) { pLib->removal_state = 3; } else { pLib->req_busy = 1; pLib->removal_state = 2; } return (0); } if (pLib->removal_state) { return (0); } if (!pLib->general_b_ch_event) { if ((ret = SuperTraceTraceOnRequest(pLib->hAdapter, "State\\B Event", pLib->buffer))) { return (-1); } pLib->general_b_ch_event = 1; pLib->req_busy = 1; return (0); } if (!pLib->general_fax_event) { if ((ret = SuperTraceTraceOnRequest(pLib->hAdapter, "State\\FAX Event", pLib->buffer))) { return (-1); } pLib->general_fax_event = 1; pLib->req_busy = 1; return (0); } if (!pLib->general_mdm_event) { if ((ret = SuperTraceTraceOnRequest(pLib->hAdapter, "State\\Modem Event", pLib->buffer))) { return (-1); } pLib->general_mdm_event = 1; pLib->req_busy = 1; return (0); } if (pLib->ChannelsTraceActive < pLib->Channels) { pLib->ChannelsTraceActive++; sprintf (name, "State\\B%d\\Line", pLib->ChannelsTraceActive); if ((ret = SuperTraceTraceOnRequest(pLib->hAdapter, name, pLib->buffer))) { pLib->ChannelsTraceActive--; return (-1); } pLib->req_busy = 1; return (0); } if (pLib->ModemTraceActive < pLib->Channels) { pLib->ModemTraceActive++; sprintf (name, "State\\B%d\\Modem\\Event", pLib->ModemTraceActive); if ((ret = SuperTraceTraceOnRequest(pLib->hAdapter, name, pLib->buffer))) { pLib->ModemTraceActive--; return (-1); } pLib->req_busy = 1; return (0); } if (pLib->FaxTraceActive < pLib->Channels) { pLib->FaxTraceActive++; sprintf (name, "State\\B%d\\FAX\\Event", pLib->FaxTraceActive); if ((ret = SuperTraceTraceOnRequest(pLib->hAdapter, name, pLib->buffer))) { pLib->FaxTraceActive--; return (-1); } pLib->req_busy = 1; return (0); } if (!pLib->trace_mask_init) { word tmp = 0x0000; if (SuperTraceWriteVar (pLib->hAdapter, pLib->buffer, "Trace\\Event Enable", &tmp, 0x87, /* MI_BITFLD */ sizeof(tmp))) { return (-1); } pLib->trace_mask_init = 1; pLib->req_busy = 1; return (0); } if (!pLib->audio_trace_init) { dword tmp = 0x00000000; if (SuperTraceWriteVar (pLib->hAdapter, pLib->buffer, "Trace\\AudioCh# Enable", &tmp, 0x87, /* MI_BITFLD */ sizeof(tmp))) { return (-1); } pLib->audio_trace_init = 2; pLib->req_busy = 1; return (0); } if (!pLib->bchannel_init) { dword tmp = 0x00000000; if (SuperTraceWriteVar (pLib->hAdapter, pLib->buffer, "Trace\\B-Ch# Enable", &tmp, 0x87, /* MI_BITFLD */ sizeof(tmp))) { return (-1); } pLib->bchannel_init = 1; pLib->req_busy = 1; return (0); } if (!pLib->trace_length_init) { word tmp = 30; if (SuperTraceWriteVar (pLib->hAdapter, pLib->buffer, "Trace\\Max Log Length", &tmp, 0x82, /* MI_UINT */ sizeof(tmp))) { return (-1); } pLib->trace_length_init = 1; pLib->req_busy = 1; return (0); } if (!pLib->trace_on) { if (SuperTraceTraceOnRequest (pLib->hAdapter, "Trace\\Log Buffer", pLib->buffer)) { return (-1); } pLib->trace_on = 1; pLib->req_busy = 1; return (0); } if (pLib->trace_event_mask != pLib->current_trace_event_mask) { if (SuperTraceWriteVar (pLib->hAdapter, pLib->buffer, "Trace\\Event Enable", &pLib->trace_event_mask, 0x87, /* MI_BITFLD */ sizeof(pLib->trace_event_mask))) { return (-1); } pLib->current_trace_event_mask = pLib->trace_event_mask; pLib->req_busy = 1; return (0); } if ((pLib->audio_tap_pending >= 0) && (pLib->audio_tap_mask != pLib->current_audio_tap_mask)) { if (SuperTraceWriteVar (pLib->hAdapter, pLib->buffer, "Trace\\AudioCh# Enable", &pLib->audio_tap_mask, 0x87, /* MI_BITFLD */ sizeof(pLib->audio_tap_mask))) { return (-1); } pLib->current_audio_tap_mask = pLib->audio_tap_mask; pLib->audio_tap_pending = 1; pLib->req_busy = 1; return (0); } if ((pLib->eye_pattern_pending >= 0) && (pLib->audio_tap_mask != pLib->current_eye_pattern_mask)) { if (SuperTraceWriteVar (pLib->hAdapter, pLib->buffer, "Trace\\EyeCh# Enable", &pLib->audio_tap_mask, 0x87, /* MI_BITFLD */ sizeof(pLib->audio_tap_mask))) { return (-1); } pLib->current_eye_pattern_mask = pLib->audio_tap_mask; pLib->eye_pattern_pending = 1; pLib->req_busy = 1; return (0); } if (pLib->bchannel_trace_mask != pLib->current_bchannel_trace_mask) { if (SuperTraceWriteVar (pLib->hAdapter, pLib->buffer, "Trace\\B-Ch# Enable", &pLib->bchannel_trace_mask, 0x87, /* MI_BITFLD */ sizeof(pLib->bchannel_trace_mask))) { return (-1); } pLib->current_bchannel_trace_mask = pLib->bchannel_trace_mask; pLib->req_busy = 1; return (0); } if (!pLib->trace_events_down) { if (SuperTraceTraceOnRequest (pLib->hAdapter, "Events Down", pLib->buffer)) { return (-1); } pLib->trace_events_down = 1; pLib->req_busy = 1; return (0); } if (!pLib->l1_trace) { if (SuperTraceTraceOnRequest (pLib->hAdapter, "State\\Layer1", pLib->buffer)) { return (-1); } pLib->l1_trace = 1; pLib->req_busy = 1; return (0); } if (!pLib->l2_trace) { if (SuperTraceTraceOnRequest (pLib->hAdapter, "State\\Layer2 No1", pLib->buffer)) { return (-1); } pLib->l2_trace = 1; pLib->req_busy = 1; return (0); } for (i = 0; i < 30; i++) { if (pLib->pending_line_status & (1L << i)) { sprintf (name, "State\\B%d", i+1); if (SuperTraceReadRequest (pLib->hAdapter, name, pLib->buffer)) { return (-1); } pLib->pending_line_status &= ~(1L << i); pLib->req_busy = 1; return (0); } if (pLib->pending_modem_status & (1L << i)) { sprintf (name, "State\\B%d\\Modem", i+1); if (SuperTraceReadRequest (pLib->hAdapter, name, pLib->buffer)) { return (-1); } pLib->pending_modem_status &= ~(1L << i); pLib->req_busy = 1; return (0); } if (pLib->pending_fax_status & (1L << i)) { sprintf (name, "State\\B%d\\FAX", i+1); if (SuperTraceReadRequest (pLib->hAdapter, name, pLib->buffer)) { return (-1); } pLib->pending_fax_status &= ~(1L << i); pLib->req_busy = 1; return (0); } if (pLib->clear_call_command & (1L << i)) { sprintf (name, "State\\B%d\\Clear Call", i+1); if (SuperTraceExecuteRequest (pLib->hAdapter, name, pLib->buffer)) { return (-1); } pLib->clear_call_command &= ~(1L << i); pLib->req_busy = 1; return (0); } } if (pLib->outgoing_ifc_stats) { if (SuperTraceReadRequest (pLib->hAdapter, "Statistics\\Outgoing Calls", pLib->buffer)) { return (-1); } pLib->outgoing_ifc_stats = 0; pLib->req_busy = 1; return (0); } if (pLib->incoming_ifc_stats) { if (SuperTraceReadRequest (pLib->hAdapter, "Statistics\\Incoming Calls", pLib->buffer)) { return (-1); } pLib->incoming_ifc_stats = 0; pLib->req_busy = 1; return (0); } if (pLib->modem_ifc_stats) { if (SuperTraceReadRequest (pLib->hAdapter, "Statistics\\Modem", pLib->buffer)) { return (-1); } pLib->modem_ifc_stats = 0; pLib->req_busy = 1; return (0); } if (pLib->fax_ifc_stats) { if (SuperTraceReadRequest (pLib->hAdapter, "Statistics\\FAX", pLib->buffer)) { return (-1); } pLib->fax_ifc_stats = 0; pLib->req_busy = 1; return (0); } if (pLib->b1_ifc_stats) { if (SuperTraceReadRequest (pLib->hAdapter, "Statistics\\B-Layer1", pLib->buffer)) { return (-1); } pLib->b1_ifc_stats = 0; pLib->req_busy = 1; return (0); } if (pLib->b2_ifc_stats) { if (SuperTraceReadRequest (pLib->hAdapter, "Statistics\\B-Layer2", pLib->buffer)) { return (-1); } pLib->b2_ifc_stats = 0; pLib->req_busy = 1; return (0); } if (pLib->d1_ifc_stats) { if (SuperTraceReadRequest (pLib->hAdapter, "Statistics\\D-Layer1", pLib->buffer)) { return (-1); } pLib->d1_ifc_stats = 0; pLib->req_busy = 1; return (0); } if (pLib->d2_ifc_stats) { if (SuperTraceReadRequest (pLib->hAdapter, "Statistics\\D-Layer2", pLib->buffer)) { return (-1); } pLib->d2_ifc_stats = 0; pLib->req_busy = 1; return (0); } if (!pLib->IncomingCallsCallsActive) { pLib->IncomingCallsCallsActive = 1; sprintf (name, "%s", "Statistics\\Incoming Calls\\Calls"); if ((ret = SuperTraceTraceOnRequest(pLib->hAdapter, name, pLib->buffer))) { pLib->IncomingCallsCallsActive = 0; return (-1); } pLib->req_busy = 1; return (0); } if (!pLib->IncomingCallsConnectedActive) { pLib->IncomingCallsConnectedActive = 1; sprintf (name, "%s", "Statistics\\Incoming Calls\\Connected"); if ((ret = SuperTraceTraceOnRequest(pLib->hAdapter, name, pLib->buffer))) { pLib->IncomingCallsConnectedActive = 0; return (-1); } pLib->req_busy = 1; return (0); } if (!pLib->OutgoingCallsCallsActive) { pLib->OutgoingCallsCallsActive = 1; sprintf (name, "%s", "Statistics\\Outgoing Calls\\Calls"); if ((ret = SuperTraceTraceOnRequest(pLib->hAdapter, name, pLib->buffer))) { pLib->OutgoingCallsCallsActive = 0; return (-1); } pLib->req_busy = 1; return (0); } if (!pLib->OutgoingCallsConnectedActive) { pLib->OutgoingCallsConnectedActive = 1; sprintf (name, "%s", "Statistics\\Outgoing Calls\\Connected"); if ((ret = SuperTraceTraceOnRequest(pLib->hAdapter, name, pLib->buffer))) { pLib->OutgoingCallsConnectedActive = 0; return (-1); } pLib->req_busy = 1; return (0); } return (0); } static int process_idi_event (diva_strace_context_t* pLib, diva_man_var_header_t* pVar) { const char* path = (char*)&pVar->path_length+1; char name[64]; int i; if (!strncmp("State\\B Event", path, pVar->path_length)) { dword ch_id; if (!diva_trace_read_variable (pVar, &ch_id)) { if (!pLib->line_init_event && !pLib->pending_line_status) { for (i = 1; i <= pLib->Channels; i++) { diva_line_event(pLib, i); } return (0); } else if (ch_id && ch_id <= pLib->Channels) { return (diva_line_event(pLib, (int)ch_id)); } return (0); } return (-1); } if (!strncmp("State\\FAX Event", path, pVar->path_length)) { dword ch_id; if (!diva_trace_read_variable (pVar, &ch_id)) { if (!pLib->pending_fax_status && !pLib->fax_init_event) { for (i = 1; i <= pLib->Channels; i++) { diva_fax_event(pLib, i); } return (0); } else if (ch_id && ch_id <= pLib->Channels) { return (diva_fax_event(pLib, (int)ch_id)); } return (0); } return (-1); } if (!strncmp("State\\Modem Event", path, pVar->path_length)) { dword ch_id; if (!diva_trace_read_variable (pVar, &ch_id)) { if (!pLib->pending_modem_status && !pLib->modem_init_event) { for (i = 1; i <= pLib->Channels; i++) { diva_modem_event(pLib, i); } return (0); } else if (ch_id && ch_id <= pLib->Channels) { return (diva_modem_event(pLib, (int)ch_id)); } return (0); } return (-1); } /* First look for Line Event */ for (i = 1; i <= pLib->Channels; i++) { sprintf (name, "State\\B%d\\Line", i); if (find_var (pVar, name)) { return (diva_line_event(pLib, i)); } } /* Look for Moden Progress Event */ for (i = 1; i <= pLib->Channels; i++) { sprintf (name, "State\\B%d\\Modem\\Event", i); if (find_var (pVar, name)) { return (diva_modem_event (pLib, i)); } } /* Look for Fax Event */ for (i = 1; i <= pLib->Channels; i++) { sprintf (name, "State\\B%d\\FAX\\Event", i); if (find_var (pVar, name)) { return (diva_fax_event (pLib, i)); } } /* Notification about loss of events */ if (!strncmp("Events Down", path, pVar->path_length)) { if (pLib->trace_events_down == 1) { pLib->trace_events_down = 2; } else { diva_trace_error (pLib, 1, "Events Down", 0); } return (0); } if (!strncmp("State\\Layer1", path, pVar->path_length)) { diva_strace_read_asz (pVar, &pLib->lines[0].pInterface->Layer1[0]); if (pLib->l1_trace == 1) { pLib->l1_trace = 2; } else { diva_trace_notify_user (pLib, 0, DIVA_SUPER_TRACE_INTERFACE_CHANGE); } return (0); } if (!strncmp("State\\Layer2 No1", path, pVar->path_length)) { char* tmp = &pLib->lines[0].pInterface->Layer2[0]; dword l2_state; if (diva_strace_read_uint(pVar, &l2_state)) return -1; switch (l2_state) { case 0: strcpy (tmp, "Idle"); break; case 1: strcpy (tmp, "Layer2 UP"); break; case 2: strcpy (tmp, "Layer2 Disconnecting"); break; case 3: strcpy (tmp, "Layer2 Connecting"); break; case 4: strcpy (tmp, "SPID Initializing"); break; case 5: strcpy (tmp, "SPID Initialised"); break; case 6: strcpy (tmp, "Layer2 Connecting"); break; case 7: strcpy (tmp, "Auto SPID Stopped"); break; case 8: strcpy (tmp, "Auto SPID Idle"); break; case 9: strcpy (tmp, "Auto SPID Requested"); break; case 10: strcpy (tmp, "Auto SPID Delivery"); break; case 11: strcpy (tmp, "Auto SPID Complete"); break; default: sprintf (tmp, "U:%d", (int)l2_state); } if (pLib->l2_trace == 1) { pLib->l2_trace = 2; } else { diva_trace_notify_user (pLib, 0, DIVA_SUPER_TRACE_INTERFACE_CHANGE); } return (0); } if (!strncmp("Statistics\\Incoming Calls\\Calls", path, pVar->path_length) || !strncmp("Statistics\\Incoming Calls\\Connected", path, pVar->path_length)) { return (SuperTraceGetIncomingCallStatistics (pLib)); } if (!strncmp("Statistics\\Outgoing Calls\\Calls", path, pVar->path_length) || !strncmp("Statistics\\Outgoing Calls\\Connected", path, pVar->path_length)) { return (SuperTraceGetOutgoingCallStatistics (pLib)); } return (-1); } static int diva_line_event (diva_strace_context_t* pLib, int Channel) { pLib->pending_line_status |= (1L << (Channel-1)); return (0); } static int diva_modem_event (diva_strace_context_t* pLib, int Channel) { pLib->pending_modem_status |= (1L << (Channel-1)); return (0); } static int diva_fax_event (diva_strace_context_t* pLib, int Channel) { pLib->pending_fax_status |= (1L << (Channel-1)); return (0); } /* Process INFO indications that arrive from the card Uses path of first I.E. to detect the source of the infication */ static int process_idi_info (diva_strace_context_t* pLib, diva_man_var_header_t* pVar) { const char* path = (char*)&pVar->path_length+1; char name[64]; int i, len; /* First look for Modem Status Info */ for (i = pLib->Channels; i > 0; i--) { len = sprintf (name, "State\\B%d\\Modem", i); if (!strncmp(name, path, len)) { return (diva_modem_info (pLib, i, pVar)); } } /* Look for Fax Status Info */ for (i = pLib->Channels; i > 0; i--) { len = sprintf (name, "State\\B%d\\FAX", i); if (!strncmp(name, path, len)) { return (diva_fax_info (pLib, i, pVar)); } } /* Look for Line Status Info */ for (i = pLib->Channels; i > 0; i--) { len = sprintf (name, "State\\B%d", i); if (!strncmp(name, path, len)) { return (diva_line_info (pLib, i, pVar)); } } if (!diva_ifc_statistics (pLib, pVar)) { return (0); } return (-1); } /* MODEM INSTANCE STATE UPDATE Update Modem Status Information and issue notification to user, that will inform about change in the state of modem instance, that is associuated with this channel */ static int diva_modem_info (diva_strace_context_t* pLib, int Channel, diva_man_var_header_t* pVar) { diva_man_var_header_t* cur; int i, nr = Channel - 1; for (i = pLib->modem_parse_entry_first[nr]; i <= pLib->modem_parse_entry_last[nr]; i++) { if ((cur = find_var (pVar, pLib->parse_table[i].path))) { if (diva_trace_read_variable (cur, pLib->parse_table[i].variable)) { diva_trace_error (pLib, -3 , __FILE__, __LINE__); return (-1); } } else { diva_trace_error (pLib, -2 , __FILE__, __LINE__); return (-1); } } /* We do not use first event to notify user - this is the event that is generated as result of EVENT ON operation and is used only to initialize internal variables of application */ if (pLib->modem_init_event & (1L << nr)) { diva_trace_notify_user (pLib, nr, DIVA_SUPER_TRACE_NOTIFY_MODEM_CHANGE); } else { pLib->modem_init_event |= (1L << nr); } return (0); } static int diva_fax_info (diva_strace_context_t* pLib, int Channel, diva_man_var_header_t* pVar) { diva_man_var_header_t* cur; int i, nr = Channel - 1; for (i = pLib->fax_parse_entry_first[nr]; i <= pLib->fax_parse_entry_last[nr]; i++) { if ((cur = find_var (pVar, pLib->parse_table[i].path))) { if (diva_trace_read_variable (cur, pLib->parse_table[i].variable)) { diva_trace_error (pLib, -3 , __FILE__, __LINE__); return (-1); } } else { diva_trace_error (pLib, -2 , __FILE__, __LINE__); return (-1); } } /* We do not use first event to notify user - this is the event that is generated as result of EVENT ON operation and is used only to initialize internal variables of application */ if (pLib->fax_init_event & (1L << nr)) { diva_trace_notify_user (pLib, nr, DIVA_SUPER_TRACE_NOTIFY_FAX_CHANGE); } else { pLib->fax_init_event |= (1L << nr); } return (0); } /* LINE STATE UPDATE Update Line Status Information and issue notification to user, that will inform about change in the line state. */ static int diva_line_info (diva_strace_context_t* pLib, int Channel, diva_man_var_header_t* pVar) { diva_man_var_header_t* cur; int i, nr = Channel - 1; for (i = pLib->line_parse_entry_first[nr]; i <= pLib->line_parse_entry_last[nr]; i++) { if ((cur = find_var (pVar, pLib->parse_table[i].path))) { if (diva_trace_read_variable (cur, pLib->parse_table[i].variable)) { diva_trace_error (pLib, -3 , __FILE__, __LINE__); return (-1); } } else { diva_trace_error (pLib, -2 , __FILE__, __LINE__); return (-1); } } /* We do not use first event to notify user - this is the event that is generated as result of EVENT ON operation and is used only to initialize internal variables of application Exception is is if the line is "online". In this case we have to notify user about this confition. */ if (pLib->line_init_event & (1L << nr)) { diva_trace_notify_user (pLib, nr, DIVA_SUPER_TRACE_NOTIFY_LINE_CHANGE); } else { pLib->line_init_event |= (1L << nr); if (strcmp (&pLib->lines[nr].Line[0], "Idle")) { diva_trace_notify_user (pLib, nr, DIVA_SUPER_TRACE_NOTIFY_LINE_CHANGE); } } return (0); } /* Move position to next vatianle in the chain */ static diva_man_var_header_t* get_next_var (diva_man_var_header_t* pVar) { byte* msg = (byte*)pVar; byte* start; int msg_length; if (*msg != ESC) return NULL; start = msg + 2; msg_length = *(msg+1); msg = (start+msg_length); if (*msg != ESC) return NULL; return ((diva_man_var_header_t*)msg); } /* Move position to variable with given name */ static diva_man_var_header_t* find_var (diva_man_var_header_t* pVar, const char* name) { const char* path; do { path = (char*)&pVar->path_length+1; if (!strncmp (name, path, pVar->path_length)) { break; } } while ((pVar = get_next_var (pVar))); return (pVar); } static void diva_create_line_parse_table (diva_strace_context_t* pLib, int Channel) { diva_trace_line_state_t* pLine = &pLib->lines[Channel]; int nr = Channel+1; if ((pLib->cur_parse_entry + LINE_PARSE_ENTRIES) >= pLib->parse_entries) { diva_trace_error (pLib, -1, __FILE__, __LINE__); return; } pLine->ChannelNumber = nr; pLib->line_parse_entry_first[Channel] = pLib->cur_parse_entry; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\Framing", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pLine->Framing[0]; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\Line", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pLine->Line[0]; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\Layer2", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pLine->Layer2[0]; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\Layer3", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pLine->Layer3[0]; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\Remote Address", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLine->RemoteAddress[0]; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\Remote SubAddr", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLine->RemoteSubAddress[0]; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\Local Address", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLine->LocalAddress[0]; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\Local SubAddr", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLine->LocalSubAddress[0]; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\BC", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pLine->call_BC; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\HLC", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pLine->call_HLC; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\LLC", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pLine->call_LLC; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\Charges", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pLine->Charges; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\Call Reference", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pLine->CallReference; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\Last Disc Cause", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLine->LastDisconnecCause; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\User ID", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pLine->UserID[0]; pLib->line_parse_entry_last[Channel] = pLib->cur_parse_entry - 1; } static void diva_create_fax_parse_table (diva_strace_context_t* pLib, int Channel) { diva_trace_fax_state_t* pFax = &pLib->lines[Channel].fax; int nr = Channel+1; if ((pLib->cur_parse_entry + FAX_PARSE_ENTRIES) >= pLib->parse_entries) { diva_trace_error (pLib, -1, __FILE__, __LINE__); return; } pFax->ChannelNumber = nr; pLib->fax_parse_entry_first[Channel] = pLib->cur_parse_entry; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\FAX\\Event", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pFax->Event; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\FAX\\Page Counter", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pFax->Page_Counter; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\FAX\\Features", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pFax->Features; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\FAX\\Station ID", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pFax->Station_ID[0]; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\FAX\\Subaddress", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pFax->Subaddress[0]; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\FAX\\Password", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pFax->Password[0]; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\FAX\\Speed", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pFax->Speed; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\FAX\\Resolution", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pFax->Resolution; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\FAX\\Paper Width", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pFax->Paper_Width; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\FAX\\Paper Length", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pFax->Paper_Length; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\FAX\\Scanline Time", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pFax->Scanline_Time; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\FAX\\Disc Reason", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pFax->Disc_Reason; pLib->fax_parse_entry_last[Channel] = pLib->cur_parse_entry - 1; } static void diva_create_modem_parse_table (diva_strace_context_t* pLib, int Channel) { diva_trace_modem_state_t* pModem = &pLib->lines[Channel].modem; int nr = Channel+1; if ((pLib->cur_parse_entry + MODEM_PARSE_ENTRIES) >= pLib->parse_entries) { diva_trace_error (pLib, -1, __FILE__, __LINE__); return; } pModem->ChannelNumber = nr; pLib->modem_parse_entry_first[Channel] = pLib->cur_parse_entry; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\Modem\\Event", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pModem->Event; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\Modem\\Norm", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pModem->Norm; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\Modem\\Options", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pModem->Options; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\Modem\\TX Speed", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pModem->TxSpeed; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\Modem\\RX Speed", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pModem->RxSpeed; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\Modem\\Roundtrip ms", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pModem->RoundtripMsec; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\Modem\\Symbol Rate", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pModem->SymbolRate; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\Modem\\RX Level dBm", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pModem->RxLeveldBm; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\Modem\\Echo Level dBm", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pModem->EchoLeveldBm; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\Modem\\SNR dB", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pModem->SNRdb; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\Modem\\MAE", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pModem->MAE; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\Modem\\Local Retrains", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pModem->LocalRetrains; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\Modem\\Remote Retrains", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pModem->RemoteRetrains; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\Modem\\Local Resyncs", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pModem->LocalResyncs; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\Modem\\Remote Resyncs", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pModem->RemoteResyncs; sprintf (pLib->parse_table[pLib->cur_parse_entry].path, "State\\B%d\\Modem\\Disc Reason", nr); pLib->parse_table[pLib->cur_parse_entry++].variable = &pModem->DiscReason; pLib->modem_parse_entry_last[Channel] = pLib->cur_parse_entry - 1; } static void diva_create_parse_table (diva_strace_context_t* pLib) { int i; for (i = 0; i < pLib->Channels; i++) { diva_create_line_parse_table (pLib, i); diva_create_modem_parse_table (pLib, i); diva_create_fax_parse_table (pLib, i); } pLib->statistic_parse_first = pLib->cur_parse_entry; /* Outgoing Calls */ strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\Outgoing Calls\\Calls"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.outg.Calls; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\Outgoing Calls\\Connected"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.outg.Connected; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\Outgoing Calls\\User Busy"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.outg.User_Busy; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\Outgoing Calls\\No Answer"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.outg.No_Answer; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\Outgoing Calls\\Wrong Number"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.outg.Wrong_Number; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\Outgoing Calls\\Call Rejected"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.outg.Call_Rejected; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\Outgoing Calls\\Other Failures"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.outg.Other_Failures; /* Incoming Calls */ strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\Incoming Calls\\Calls"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.inc.Calls; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\Incoming Calls\\Connected"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.inc.Connected; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\Incoming Calls\\User Busy"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.inc.User_Busy; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\Incoming Calls\\Call Rejected"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.inc.Call_Rejected; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\Incoming Calls\\Wrong Number"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.inc.Wrong_Number; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\Incoming Calls\\Incompatible Dst"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.inc.Incompatible_Dst; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\Incoming Calls\\Out of Order"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.inc.Out_of_Order; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\Incoming Calls\\Ignored"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.inc.Ignored; /* Modem Statistics */ pLib->mdm_statistic_parse_first = pLib->cur_parse_entry; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\Modem\\Disc Normal"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.mdm.Disc_Normal; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\Modem\\Disc Unspecified"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.mdm.Disc_Unspecified; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\Modem\\Disc Busy Tone"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.mdm.Disc_Busy_Tone; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\Modem\\Disc Congestion"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.mdm.Disc_Congestion; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\Modem\\Disc Carr. Wait"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.mdm.Disc_Carr_Wait; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\Modem\\Disc Trn Timeout"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.mdm.Disc_Trn_Timeout; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\Modem\\Disc Incompat."); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.mdm.Disc_Incompat; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\Modem\\Disc Frame Rej."); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.mdm.Disc_Frame_Rej; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\Modem\\Disc V42bis"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.mdm.Disc_V42bis; pLib->mdm_statistic_parse_last = pLib->cur_parse_entry - 1; /* Fax Statistics */ pLib->fax_statistic_parse_first = pLib->cur_parse_entry; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\FAX\\Disc Normal"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.fax.Disc_Normal; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\FAX\\Disc Not Ident."); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.fax.Disc_Not_Ident; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\FAX\\Disc No Response"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.fax.Disc_No_Response; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\FAX\\Disc Retries"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.fax.Disc_Retries; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\FAX\\Disc Unexp. Msg."); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.fax.Disc_Unexp_Msg; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\FAX\\Disc No Polling."); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.fax.Disc_No_Polling; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\FAX\\Disc Training"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.fax.Disc_Training; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\FAX\\Disc Unexpected"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.fax.Disc_Unexpected; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\FAX\\Disc Application"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.fax.Disc_Application; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\FAX\\Disc Incompat."); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.fax.Disc_Incompat; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\FAX\\Disc No Command"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.fax.Disc_No_Command; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\FAX\\Disc Long Msg"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.fax.Disc_Long_Msg; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\FAX\\Disc Supervisor"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.fax.Disc_Supervisor; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\FAX\\Disc SUB SEP PWD"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.fax.Disc_SUB_SEP_PWD; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\FAX\\Disc Invalid Msg"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.fax.Disc_Invalid_Msg; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\FAX\\Disc Page Coding"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.fax.Disc_Page_Coding; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\FAX\\Disc App Timeout"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.fax.Disc_App_Timeout; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\FAX\\Disc Unspecified"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.fax.Disc_Unspecified; pLib->fax_statistic_parse_last = pLib->cur_parse_entry - 1; /* B-Layer1" */ strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\B-Layer1\\X-Frames"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.b1.X_Frames; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\B-Layer1\\X-Bytes"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.b1.X_Bytes; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\B-Layer1\\X-Errors"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.b1.X_Errors; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\B-Layer1\\R-Frames"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.b1.R_Frames; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\B-Layer1\\R-Bytes"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.b1.R_Bytes; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\B-Layer1\\R-Errors"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.b1.R_Errors; /* B-Layer2 */ strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\B-Layer2\\X-Frames"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.b2.X_Frames; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\B-Layer2\\X-Bytes"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.b2.X_Bytes; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\B-Layer2\\X-Errors"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.b2.X_Errors; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\B-Layer2\\R-Frames"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.b2.R_Frames; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\B-Layer2\\R-Bytes"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.b2.R_Bytes; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\B-Layer2\\R-Errors"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.b2.R_Errors; /* D-Layer1 */ strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\D-Layer1\\X-Frames"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.d1.X_Frames; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\D-Layer1\\X-Bytes"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.d1.X_Bytes; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\D-Layer1\\X-Errors"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.d1.X_Errors; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\D-Layer1\\R-Frames"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.d1.R_Frames; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\D-Layer1\\R-Bytes"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.d1.R_Bytes; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\D-Layer1\\R-Errors"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.d1.R_Errors; /* D-Layer2 */ strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\D-Layer2\\X-Frames"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.d2.X_Frames; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\D-Layer2\\X-Bytes"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.d2.X_Bytes; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\D-Layer2\\X-Errors"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.d2.X_Errors; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\D-Layer2\\R-Frames"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.d2.R_Frames; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\D-Layer2\\R-Bytes"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.d2.R_Bytes; strcpy (pLib->parse_table[pLib->cur_parse_entry].path, "Statistics\\D-Layer2\\R-Errors"); pLib->parse_table[pLib->cur_parse_entry++].variable = \ &pLib->InterfaceStat.d2.R_Errors; pLib->statistic_parse_last = pLib->cur_parse_entry - 1; } static void diva_trace_error (diva_strace_context_t* pLib, int error, const char* file, int line) { if (pLib->user_proc_table.error_notify_proc) { (*(pLib->user_proc_table.error_notify_proc))(\ pLib->user_proc_table.user_context, &pLib->instance, pLib->Adapter, error, file, line); } } /* Delivery notification to user */ static void diva_trace_notify_user (diva_strace_context_t* pLib, int Channel, int notify_subject) { if (pLib->user_proc_table.notify_proc) { (*(pLib->user_proc_table.notify_proc))(pLib->user_proc_table.user_context, &pLib->instance, pLib->Adapter, &pLib->lines[Channel], notify_subject); } } /* Read variable value to they destination based on the variable type */ static int diva_trace_read_variable (diva_man_var_header_t* pVar, void* variable) { switch (pVar->type) { case 0x03: /* MI_ASCIIZ - syting */ return (diva_strace_read_asz (pVar, (char*)variable)); case 0x04: /* MI_ASCII - string */ return (diva_strace_read_asc (pVar, (char*)variable)); case 0x05: /* MI_NUMBER - counted sequence of bytes */ return (diva_strace_read_ie (pVar, (diva_trace_ie_t*)variable)); case 0x81: /* MI_INT - signed integer */ return (diva_strace_read_int (pVar, (int*)variable)); case 0x82: /* MI_UINT - unsigned integer */ return (diva_strace_read_uint (pVar, (dword*)variable)); case 0x83: /* MI_HINT - unsigned integer, hex representetion */ return (diva_strace_read_uint (pVar, (dword*)variable)); case 0x87: /* MI_BITFLD - unsigned integer, bit representation */ return (diva_strace_read_uint (pVar, (dword*)variable)); } /* This type of variable is not handled, indicate error Or one problem in management interface, or in application recodeing table, or this application should handle it. */ return (-1); } /* Read signed integer to destination */ static int diva_strace_read_int (diva_man_var_header_t* pVar, int* var) { byte* ptr = (char*)&pVar->path_length; int value; ptr += (pVar->path_length + 1); switch (pVar->value_length) { case 1: value = *(char*)ptr; break; case 2: value = (short)GET_WORD(ptr); break; case 4: value = (int)GET_DWORD(ptr); break; default: return (-1); } *var = value; return (0); } static int diva_strace_read_uint (diva_man_var_header_t* pVar, dword* var) { byte* ptr = (char*)&pVar->path_length; dword value; ptr += (pVar->path_length + 1); switch (pVar->value_length) { case 1: value = (byte)(*ptr); break; case 2: value = (word)GET_WORD(ptr); break; case 3: value = (dword)GET_DWORD(ptr); value &= 0x00ffffff; break; case 4: value = (dword)GET_DWORD(ptr); break; default: return (-1); } *var = value; return (0); } /* Read zero terminated ASCII string */ static int diva_strace_read_asz (diva_man_var_header_t* pVar, char* var) { char* ptr = (char*)&pVar->path_length; int length; ptr += (pVar->path_length + 1); if (!(length = pVar->value_length)) { length = strlen (ptr); } memcpy (var, ptr, length); var[length] = 0; return (0); } /* Read counted (with leading length byte) ASCII string */ static int diva_strace_read_asc (diva_man_var_header_t* pVar, char* var) { char* ptr = (char*)&pVar->path_length; ptr += (pVar->path_length + 1); memcpy (var, ptr+1, *ptr); var[(int)*ptr] = 0; return (0); } /* Read one information element - i.e. one string of byte values with one length byte in front */ static int diva_strace_read_ie (diva_man_var_header_t* pVar, diva_trace_ie_t* var) { char* ptr = (char*)&pVar->path_length; ptr += (pVar->path_length + 1); var->length = *ptr; memcpy (&var->data[0], ptr+1, *ptr); return (0); } static int SuperTraceSetAudioTap (void* hLib, int Channel, int on) { diva_strace_context_t* pLib = (diva_strace_context_t*)hLib; if ((Channel < 1) || (Channel > pLib->Channels)) { return (-1); } Channel--; if (on) { pLib->audio_tap_mask |= (1L << Channel); } else { pLib->audio_tap_mask &= ~(1L << Channel); } /* EYE patterns have TM_M_DATA set as additional condition */ if (pLib->audio_tap_mask) { pLib->trace_event_mask |= TM_M_DATA; } else { pLib->trace_event_mask &= ~TM_M_DATA; } return (ScheduleNextTraceRequest (pLib)); } static int SuperTraceSetBChannel (void* hLib, int Channel, int on) { diva_strace_context_t* pLib = (diva_strace_context_t*)hLib; if ((Channel < 1) || (Channel > pLib->Channels)) { return (-1); } Channel--; if (on) { pLib->bchannel_trace_mask |= (1L << Channel); } else { pLib->bchannel_trace_mask &= ~(1L << Channel); } return (ScheduleNextTraceRequest (pLib)); } static int SuperTraceSetDChannel (void* hLib, int on) { diva_strace_context_t* pLib = (diva_strace_context_t*)hLib; if (on) { pLib->trace_event_mask |= (TM_D_CHAN | TM_C_COMM | TM_DL_ERR | TM_LAYER1); } else { pLib->trace_event_mask &= ~(TM_D_CHAN | TM_C_COMM | TM_DL_ERR | TM_LAYER1); } return (ScheduleNextTraceRequest (pLib)); } static int SuperTraceSetInfo (void* hLib, int on) { diva_strace_context_t* pLib = (diva_strace_context_t*)hLib; if (on) { pLib->trace_event_mask |= TM_STRING; } else { pLib->trace_event_mask &= ~TM_STRING; } return (ScheduleNextTraceRequest (pLib)); } static int SuperTraceClearCall (void* hLib, int Channel) { diva_strace_context_t* pLib = (diva_strace_context_t*)hLib; if ((Channel < 1) || (Channel > pLib->Channels)) { return (-1); } Channel--; pLib->clear_call_command |= (1L << Channel); return (ScheduleNextTraceRequest (pLib)); } /* Parse and update cumulative statistice */ static int diva_ifc_statistics (diva_strace_context_t* pLib, diva_man_var_header_t* pVar) { diva_man_var_header_t* cur; int i, one_updated = 0, mdm_updated = 0, fax_updated = 0; for (i = pLib->statistic_parse_first; i <= pLib->statistic_parse_last; i++) { if ((cur = find_var (pVar, pLib->parse_table[i].path))) { if (diva_trace_read_variable (cur, pLib->parse_table[i].variable)) { diva_trace_error (pLib, -3 , __FILE__, __LINE__); return (-1); } one_updated = 1; if ((i >= pLib->mdm_statistic_parse_first) && (i <= pLib->mdm_statistic_parse_last)) { mdm_updated = 1; } if ((i >= pLib->fax_statistic_parse_first) && (i <= pLib->fax_statistic_parse_last)) { fax_updated = 1; } } } /* We do not use first event to notify user - this is the event that is generated as result of EVENT ON operation and is used only to initialize internal variables of application */ if (mdm_updated) { diva_trace_notify_user (pLib, 0, DIVA_SUPER_TRACE_NOTIFY_MDM_STAT_CHANGE); } else if (fax_updated) { diva_trace_notify_user (pLib, 0, DIVA_SUPER_TRACE_NOTIFY_FAX_STAT_CHANGE); } else if (one_updated) { diva_trace_notify_user (pLib, 0, DIVA_SUPER_TRACE_NOTIFY_STAT_CHANGE); } return (one_updated ? 0 : -1); } static int SuperTraceGetOutgoingCallStatistics (void* hLib) { diva_strace_context_t* pLib = (diva_strace_context_t*)hLib; pLib->outgoing_ifc_stats = 1; return (ScheduleNextTraceRequest (pLib)); } static int SuperTraceGetIncomingCallStatistics (void* hLib) { diva_strace_context_t* pLib = (diva_strace_context_t*)hLib; pLib->incoming_ifc_stats = 1; return (ScheduleNextTraceRequest (pLib)); } static int SuperTraceGetModemStatistics (void* hLib) { diva_strace_context_t* pLib = (diva_strace_context_t*)hLib; pLib->modem_ifc_stats = 1; return (ScheduleNextTraceRequest (pLib)); } static int SuperTraceGetFaxStatistics (void* hLib) { diva_strace_context_t* pLib = (diva_strace_context_t*)hLib; pLib->fax_ifc_stats = 1; return (ScheduleNextTraceRequest (pLib)); } static int SuperTraceGetBLayer1Statistics (void* hLib) { diva_strace_context_t* pLib = (diva_strace_context_t*)hLib; pLib->b1_ifc_stats = 1; return (ScheduleNextTraceRequest (pLib)); } static int SuperTraceGetBLayer2Statistics (void* hLib) { diva_strace_context_t* pLib = (diva_strace_context_t*)hLib; pLib->b2_ifc_stats = 1; return (ScheduleNextTraceRequest (pLib)); } static int SuperTraceGetDLayer1Statistics (void* hLib) { diva_strace_context_t* pLib = (diva_strace_context_t*)hLib; pLib->d1_ifc_stats = 1; return (ScheduleNextTraceRequest (pLib)); } static int SuperTraceGetDLayer2Statistics (void* hLib) { diva_strace_context_t* pLib = (diva_strace_context_t*)hLib; pLib->d2_ifc_stats = 1; return (ScheduleNextTraceRequest (pLib)); } dword DivaSTraceGetMemotyRequirement (int channels) { dword parse_entries = (MODEM_PARSE_ENTRIES + FAX_PARSE_ENTRIES + \ STAT_PARSE_ENTRIES + \ LINE_PARSE_ENTRIES + 1) * channels; return (sizeof(diva_strace_context_t) + \ (parse_entries * sizeof(diva_strace_path2action_t))); }
gpl-2.0
sakuraba001/android_kernel_samsung_kactivelte
drivers/md/multipath.c
4813
14469
/* * multipath.c : Multiple Devices driver for Linux * * Copyright (C) 1999, 2000, 2001 Ingo Molnar, Red Hat * * Copyright (C) 1996, 1997, 1998 Ingo Molnar, Miguel de Icaza, Gadi Oxman * * MULTIPATH management functions. * * derived from raid1.c. * * 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. * * You should have received a copy of the GNU General Public License * (for example /usr/src/linux/COPYING); if not, write to the Free * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <linux/blkdev.h> #include <linux/module.h> #include <linux/raid/md_u.h> #include <linux/seq_file.h> #include <linux/slab.h> #include "md.h" #include "multipath.h" #define MAX_WORK_PER_DISK 128 #define NR_RESERVED_BUFS 32 static int multipath_map (struct mpconf *conf) { int i, disks = conf->raid_disks; /* * Later we do read balancing on the read side * now we use the first available disk. */ rcu_read_lock(); for (i = 0; i < disks; i++) { struct md_rdev *rdev = rcu_dereference(conf->multipaths[i].rdev); if (rdev && test_bit(In_sync, &rdev->flags)) { atomic_inc(&rdev->nr_pending); rcu_read_unlock(); return i; } } rcu_read_unlock(); printk(KERN_ERR "multipath_map(): no more operational IO paths?\n"); return (-1); } static void multipath_reschedule_retry (struct multipath_bh *mp_bh) { unsigned long flags; struct mddev *mddev = mp_bh->mddev; struct mpconf *conf = mddev->private; spin_lock_irqsave(&conf->device_lock, flags); list_add(&mp_bh->retry_list, &conf->retry_list); spin_unlock_irqrestore(&conf->device_lock, flags); md_wakeup_thread(mddev->thread); } /* * multipath_end_bh_io() is called when we have finished servicing a multipathed * operation and are ready to return a success/failure code to the buffer * cache layer. */ static void multipath_end_bh_io (struct multipath_bh *mp_bh, int err) { struct bio *bio = mp_bh->master_bio; struct mpconf *conf = mp_bh->mddev->private; bio_endio(bio, err); mempool_free(mp_bh, conf->pool); } static void multipath_end_request(struct bio *bio, int error) { int uptodate = test_bit(BIO_UPTODATE, &bio->bi_flags); struct multipath_bh *mp_bh = bio->bi_private; struct mpconf *conf = mp_bh->mddev->private; struct md_rdev *rdev = conf->multipaths[mp_bh->path].rdev; if (uptodate) multipath_end_bh_io(mp_bh, 0); else if (!(bio->bi_rw & REQ_RAHEAD)) { /* * oops, IO error: */ char b[BDEVNAME_SIZE]; md_error (mp_bh->mddev, rdev); printk(KERN_ERR "multipath: %s: rescheduling sector %llu\n", bdevname(rdev->bdev,b), (unsigned long long)bio->bi_sector); multipath_reschedule_retry(mp_bh); } else multipath_end_bh_io(mp_bh, error); rdev_dec_pending(rdev, conf->mddev); } static void multipath_make_request(struct mddev *mddev, struct bio * bio) { struct mpconf *conf = mddev->private; struct multipath_bh * mp_bh; struct multipath_info *multipath; if (unlikely(bio->bi_rw & REQ_FLUSH)) { md_flush_request(mddev, bio); return; } mp_bh = mempool_alloc(conf->pool, GFP_NOIO); mp_bh->master_bio = bio; mp_bh->mddev = mddev; mp_bh->path = multipath_map(conf); if (mp_bh->path < 0) { bio_endio(bio, -EIO); mempool_free(mp_bh, conf->pool); return; } multipath = conf->multipaths + mp_bh->path; mp_bh->bio = *bio; mp_bh->bio.bi_sector += multipath->rdev->data_offset; mp_bh->bio.bi_bdev = multipath->rdev->bdev; mp_bh->bio.bi_rw |= REQ_FAILFAST_TRANSPORT; mp_bh->bio.bi_end_io = multipath_end_request; mp_bh->bio.bi_private = mp_bh; generic_make_request(&mp_bh->bio); return; } static void multipath_status (struct seq_file *seq, struct mddev *mddev) { struct mpconf *conf = mddev->private; int i; seq_printf (seq, " [%d/%d] [", conf->raid_disks, conf->raid_disks - mddev->degraded); for (i = 0; i < conf->raid_disks; i++) seq_printf (seq, "%s", conf->multipaths[i].rdev && test_bit(In_sync, &conf->multipaths[i].rdev->flags) ? "U" : "_"); seq_printf (seq, "]"); } static int multipath_congested(void *data, int bits) { struct mddev *mddev = data; struct mpconf *conf = mddev->private; int i, ret = 0; if (mddev_congested(mddev, bits)) return 1; rcu_read_lock(); for (i = 0; i < mddev->raid_disks ; i++) { struct md_rdev *rdev = rcu_dereference(conf->multipaths[i].rdev); if (rdev && !test_bit(Faulty, &rdev->flags)) { struct request_queue *q = bdev_get_queue(rdev->bdev); ret |= bdi_congested(&q->backing_dev_info, bits); /* Just like multipath_map, we just check the * first available device */ break; } } rcu_read_unlock(); return ret; } /* * Careful, this can execute in IRQ contexts as well! */ static void multipath_error (struct mddev *mddev, struct md_rdev *rdev) { struct mpconf *conf = mddev->private; char b[BDEVNAME_SIZE]; if (conf->raid_disks - mddev->degraded <= 1) { /* * Uh oh, we can do nothing if this is our last path, but * first check if this is a queued request for a device * which has just failed. */ printk(KERN_ALERT "multipath: only one IO path left and IO error.\n"); /* leave it active... it's all we have */ return; } /* * Mark disk as unusable */ if (test_and_clear_bit(In_sync, &rdev->flags)) { unsigned long flags; spin_lock_irqsave(&conf->device_lock, flags); mddev->degraded++; spin_unlock_irqrestore(&conf->device_lock, flags); } set_bit(Faulty, &rdev->flags); set_bit(MD_CHANGE_DEVS, &mddev->flags); printk(KERN_ALERT "multipath: IO failure on %s," " disabling IO path.\n" "multipath: Operation continuing" " on %d IO paths.\n", bdevname(rdev->bdev, b), conf->raid_disks - mddev->degraded); } static void print_multipath_conf (struct mpconf *conf) { int i; struct multipath_info *tmp; printk("MULTIPATH conf printout:\n"); if (!conf) { printk("(conf==NULL)\n"); return; } printk(" --- wd:%d rd:%d\n", conf->raid_disks - conf->mddev->degraded, conf->raid_disks); for (i = 0; i < conf->raid_disks; i++) { char b[BDEVNAME_SIZE]; tmp = conf->multipaths + i; if (tmp->rdev) printk(" disk%d, o:%d, dev:%s\n", i,!test_bit(Faulty, &tmp->rdev->flags), bdevname(tmp->rdev->bdev,b)); } } static int multipath_add_disk(struct mddev *mddev, struct md_rdev *rdev) { struct mpconf *conf = mddev->private; struct request_queue *q; int err = -EEXIST; int path; struct multipath_info *p; int first = 0; int last = mddev->raid_disks - 1; if (rdev->raid_disk >= 0) first = last = rdev->raid_disk; print_multipath_conf(conf); for (path = first; path <= last; path++) if ((p=conf->multipaths+path)->rdev == NULL) { q = rdev->bdev->bd_disk->queue; disk_stack_limits(mddev->gendisk, rdev->bdev, rdev->data_offset << 9); /* as we don't honour merge_bvec_fn, we must never risk * violating it, so limit ->max_segments to one, lying * within a single page. * (Note: it is very unlikely that a device with * merge_bvec_fn will be involved in multipath.) */ if (q->merge_bvec_fn) { blk_queue_max_segments(mddev->queue, 1); blk_queue_segment_boundary(mddev->queue, PAGE_CACHE_SIZE - 1); } spin_lock_irq(&conf->device_lock); mddev->degraded--; rdev->raid_disk = path; set_bit(In_sync, &rdev->flags); spin_unlock_irq(&conf->device_lock); rcu_assign_pointer(p->rdev, rdev); err = 0; md_integrity_add_rdev(rdev, mddev); break; } print_multipath_conf(conf); return err; } static int multipath_remove_disk(struct mddev *mddev, struct md_rdev *rdev) { struct mpconf *conf = mddev->private; int err = 0; int number = rdev->raid_disk; struct multipath_info *p = conf->multipaths + number; print_multipath_conf(conf); if (rdev == p->rdev) { if (test_bit(In_sync, &rdev->flags) || atomic_read(&rdev->nr_pending)) { printk(KERN_ERR "hot-remove-disk, slot %d is identified" " but is still operational!\n", number); err = -EBUSY; goto abort; } p->rdev = NULL; synchronize_rcu(); if (atomic_read(&rdev->nr_pending)) { /* lost the race, try later */ err = -EBUSY; p->rdev = rdev; goto abort; } err = md_integrity_register(mddev); } abort: print_multipath_conf(conf); return err; } /* * This is a kernel thread which: * * 1. Retries failed read operations on working multipaths. * 2. Updates the raid superblock when problems encounter. * 3. Performs writes following reads for array syncronising. */ static void multipathd (struct mddev *mddev) { struct multipath_bh *mp_bh; struct bio *bio; unsigned long flags; struct mpconf *conf = mddev->private; struct list_head *head = &conf->retry_list; md_check_recovery(mddev); for (;;) { char b[BDEVNAME_SIZE]; spin_lock_irqsave(&conf->device_lock, flags); if (list_empty(head)) break; mp_bh = list_entry(head->prev, struct multipath_bh, retry_list); list_del(head->prev); spin_unlock_irqrestore(&conf->device_lock, flags); bio = &mp_bh->bio; bio->bi_sector = mp_bh->master_bio->bi_sector; if ((mp_bh->path = multipath_map (conf))<0) { printk(KERN_ALERT "multipath: %s: unrecoverable IO read" " error for block %llu\n", bdevname(bio->bi_bdev,b), (unsigned long long)bio->bi_sector); multipath_end_bh_io(mp_bh, -EIO); } else { printk(KERN_ERR "multipath: %s: redirecting sector %llu" " to another IO path\n", bdevname(bio->bi_bdev,b), (unsigned long long)bio->bi_sector); *bio = *(mp_bh->master_bio); bio->bi_sector += conf->multipaths[mp_bh->path].rdev->data_offset; bio->bi_bdev = conf->multipaths[mp_bh->path].rdev->bdev; bio->bi_rw |= REQ_FAILFAST_TRANSPORT; bio->bi_end_io = multipath_end_request; bio->bi_private = mp_bh; generic_make_request(bio); } } spin_unlock_irqrestore(&conf->device_lock, flags); } static sector_t multipath_size(struct mddev *mddev, sector_t sectors, int raid_disks) { WARN_ONCE(sectors || raid_disks, "%s does not support generic reshape\n", __func__); return mddev->dev_sectors; } static int multipath_run (struct mddev *mddev) { struct mpconf *conf; int disk_idx; struct multipath_info *disk; struct md_rdev *rdev; int working_disks; if (md_check_no_bitmap(mddev)) return -EINVAL; if (mddev->level != LEVEL_MULTIPATH) { printk("multipath: %s: raid level not set to multipath IO (%d)\n", mdname(mddev), mddev->level); goto out; } /* * copy the already verified devices into our private MULTIPATH * bookkeeping area. [whatever we allocate in multipath_run(), * should be freed in multipath_stop()] */ conf = kzalloc(sizeof(struct mpconf), GFP_KERNEL); mddev->private = conf; if (!conf) { printk(KERN_ERR "multipath: couldn't allocate memory for %s\n", mdname(mddev)); goto out; } conf->multipaths = kzalloc(sizeof(struct multipath_info)*mddev->raid_disks, GFP_KERNEL); if (!conf->multipaths) { printk(KERN_ERR "multipath: couldn't allocate memory for %s\n", mdname(mddev)); goto out_free_conf; } working_disks = 0; rdev_for_each(rdev, mddev) { disk_idx = rdev->raid_disk; if (disk_idx < 0 || disk_idx >= mddev->raid_disks) continue; disk = conf->multipaths + disk_idx; disk->rdev = rdev; disk_stack_limits(mddev->gendisk, rdev->bdev, rdev->data_offset << 9); /* as we don't honour merge_bvec_fn, we must never risk * violating it, not that we ever expect a device with * a merge_bvec_fn to be involved in multipath */ if (rdev->bdev->bd_disk->queue->merge_bvec_fn) { blk_queue_max_segments(mddev->queue, 1); blk_queue_segment_boundary(mddev->queue, PAGE_CACHE_SIZE - 1); } if (!test_bit(Faulty, &rdev->flags)) working_disks++; } conf->raid_disks = mddev->raid_disks; conf->mddev = mddev; spin_lock_init(&conf->device_lock); INIT_LIST_HEAD(&conf->retry_list); if (!working_disks) { printk(KERN_ERR "multipath: no operational IO paths for %s\n", mdname(mddev)); goto out_free_conf; } mddev->degraded = conf->raid_disks - working_disks; conf->pool = mempool_create_kmalloc_pool(NR_RESERVED_BUFS, sizeof(struct multipath_bh)); if (conf->pool == NULL) { printk(KERN_ERR "multipath: couldn't allocate memory for %s\n", mdname(mddev)); goto out_free_conf; } { mddev->thread = md_register_thread(multipathd, mddev, NULL); if (!mddev->thread) { printk(KERN_ERR "multipath: couldn't allocate thread" " for %s\n", mdname(mddev)); goto out_free_conf; } } printk(KERN_INFO "multipath: array %s active with %d out of %d IO paths\n", mdname(mddev), conf->raid_disks - mddev->degraded, mddev->raid_disks); /* * Ok, everything is just fine now */ md_set_array_sectors(mddev, multipath_size(mddev, 0, 0)); mddev->queue->backing_dev_info.congested_fn = multipath_congested; mddev->queue->backing_dev_info.congested_data = mddev; if (md_integrity_register(mddev)) goto out_free_conf; return 0; out_free_conf: if (conf->pool) mempool_destroy(conf->pool); kfree(conf->multipaths); kfree(conf); mddev->private = NULL; out: return -EIO; } static int multipath_stop (struct mddev *mddev) { struct mpconf *conf = mddev->private; md_unregister_thread(&mddev->thread); blk_sync_queue(mddev->queue); /* the unplug fn references 'conf'*/ mempool_destroy(conf->pool); kfree(conf->multipaths); kfree(conf); mddev->private = NULL; return 0; } static struct md_personality multipath_personality = { .name = "multipath", .level = LEVEL_MULTIPATH, .owner = THIS_MODULE, .make_request = multipath_make_request, .run = multipath_run, .stop = multipath_stop, .status = multipath_status, .error_handler = multipath_error, .hot_add_disk = multipath_add_disk, .hot_remove_disk= multipath_remove_disk, .size = multipath_size, }; static int __init multipath_init (void) { return register_md_personality (&multipath_personality); } static void __exit multipath_exit (void) { unregister_md_personality (&multipath_personality); } module_init(multipath_init); module_exit(multipath_exit); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("simple multi-path personality for MD"); MODULE_ALIAS("md-personality-7"); /* MULTIPATH */ MODULE_ALIAS("md-multipath"); MODULE_ALIAS("md-level--4");
gpl-2.0
sac23/Sacs_Stock_Kernel
drivers/spi/spi-pxa2xx-pci.c
4813
4053
/* * CE4100's SPI device is more or less the same one as found on PXA * */ #include <linux/pci.h> #include <linux/platform_device.h> #include <linux/of_device.h> #include <linux/module.h> #include <linux/spi/pxa2xx_spi.h> struct ce4100_info { struct ssp_device ssp; struct platform_device *spi_pdev; }; static DEFINE_MUTEX(ssp_lock); static LIST_HEAD(ssp_list); struct ssp_device *pxa_ssp_request(int port, const char *label) { struct ssp_device *ssp = NULL; mutex_lock(&ssp_lock); list_for_each_entry(ssp, &ssp_list, node) { if (ssp->port_id == port && ssp->use_count == 0) { ssp->use_count++; ssp->label = label; break; } } mutex_unlock(&ssp_lock); if (&ssp->node == &ssp_list) return NULL; return ssp; } EXPORT_SYMBOL_GPL(pxa_ssp_request); void pxa_ssp_free(struct ssp_device *ssp) { mutex_lock(&ssp_lock); if (ssp->use_count) { ssp->use_count--; ssp->label = NULL; } else dev_err(&ssp->pdev->dev, "device already free\n"); mutex_unlock(&ssp_lock); } EXPORT_SYMBOL_GPL(pxa_ssp_free); static int __devinit ce4100_spi_probe(struct pci_dev *dev, const struct pci_device_id *ent) { int ret; resource_size_t phys_beg; resource_size_t phys_len; struct ce4100_info *spi_info; struct platform_device *pdev; struct pxa2xx_spi_master spi_pdata; struct ssp_device *ssp; ret = pci_enable_device(dev); if (ret) return ret; phys_beg = pci_resource_start(dev, 0); phys_len = pci_resource_len(dev, 0); if (!request_mem_region(phys_beg, phys_len, "CE4100 SPI")) { dev_err(&dev->dev, "Can't request register space.\n"); ret = -EBUSY; return ret; } pdev = platform_device_alloc("pxa2xx-spi", dev->devfn); spi_info = kzalloc(sizeof(*spi_info), GFP_KERNEL); if (!pdev || !spi_info ) { ret = -ENOMEM; goto err_nomem; } memset(&spi_pdata, 0, sizeof(spi_pdata)); spi_pdata.num_chipselect = dev->devfn; ret = platform_device_add_data(pdev, &spi_pdata, sizeof(spi_pdata)); if (ret) goto err_nomem; pdev->dev.parent = &dev->dev; pdev->dev.of_node = dev->dev.of_node; ssp = &spi_info->ssp; ssp->phys_base = pci_resource_start(dev, 0); ssp->mmio_base = ioremap(phys_beg, phys_len); if (!ssp->mmio_base) { dev_err(&pdev->dev, "failed to ioremap() registers\n"); ret = -EIO; goto err_nomem; } ssp->irq = dev->irq; ssp->port_id = pdev->id; ssp->type = PXA25x_SSP; mutex_lock(&ssp_lock); list_add(&ssp->node, &ssp_list); mutex_unlock(&ssp_lock); pci_set_drvdata(dev, spi_info); ret = platform_device_add(pdev); if (ret) goto err_dev_add; return ret; err_dev_add: pci_set_drvdata(dev, NULL); mutex_lock(&ssp_lock); list_del(&ssp->node); mutex_unlock(&ssp_lock); iounmap(ssp->mmio_base); err_nomem: release_mem_region(phys_beg, phys_len); platform_device_put(pdev); kfree(spi_info); return ret; } static void __devexit ce4100_spi_remove(struct pci_dev *dev) { struct ce4100_info *spi_info; struct ssp_device *ssp; spi_info = pci_get_drvdata(dev); ssp = &spi_info->ssp; platform_device_unregister(spi_info->spi_pdev); iounmap(ssp->mmio_base); release_mem_region(pci_resource_start(dev, 0), pci_resource_len(dev, 0)); mutex_lock(&ssp_lock); list_del(&ssp->node); mutex_unlock(&ssp_lock); pci_set_drvdata(dev, NULL); pci_disable_device(dev); kfree(spi_info); } static DEFINE_PCI_DEVICE_TABLE(ce4100_spi_devices) = { { PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x2e6a) }, { }, }; MODULE_DEVICE_TABLE(pci, ce4100_spi_devices); static struct pci_driver ce4100_spi_driver = { .name = "ce4100_spi", .id_table = ce4100_spi_devices, .probe = ce4100_spi_probe, .remove = __devexit_p(ce4100_spi_remove), }; static int __init ce4100_spi_init(void) { return pci_register_driver(&ce4100_spi_driver); } module_init(ce4100_spi_init); static void __exit ce4100_spi_exit(void) { pci_unregister_driver(&ce4100_spi_driver); } module_exit(ce4100_spi_exit); MODULE_DESCRIPTION("CE4100 PCI-SPI glue code for PXA's driver"); MODULE_LICENSE("GPL v2"); MODULE_AUTHOR("Sebastian Andrzej Siewior <bigeasy@linutronix.de>");
gpl-2.0
Tesla-M-Devices/android_kernel_motorola_msm8226
drivers/atm/he.c
5069
78520
/* he.c ForeRunnerHE ATM Adapter driver for ATM on Linux Copyright (C) 1999-2001 Naval Research Laboratory This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* he.c ForeRunnerHE ATM Adapter driver for ATM on Linux Copyright (C) 1999-2001 Naval Research Laboratory Permission to use, copy, modify and distribute this software and its documentation is hereby granted, provided that both the copyright notice and this permission notice appear in all copies of the software, derivative works or modified versions, and any portions thereof, and that both notices appear in supporting documentation. NRL ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS" CONDITION AND DISCLAIMS ANY LIABILITY OF ANY KIND FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. This driver was written using the "Programmer's Reference Manual for ForeRunnerHE(tm)", MANU0361-01 - Rev. A, 08/21/98. AUTHORS: chas williams <chas@cmf.nrl.navy.mil> eric kinzie <ekinzie@cmf.nrl.navy.mil> NOTES: 4096 supported 'connections' group 0 is used for all traffic interrupt queue 0 is used for all interrupts aal0 support (based on work from ulrich.u.muller@nokia.com) */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/skbuff.h> #include <linux/pci.h> #include <linux/errno.h> #include <linux/types.h> #include <linux/string.h> #include <linux/delay.h> #include <linux/init.h> #include <linux/mm.h> #include <linux/sched.h> #include <linux/timer.h> #include <linux/interrupt.h> #include <linux/dma-mapping.h> #include <linux/bitmap.h> #include <linux/slab.h> #include <asm/io.h> #include <asm/byteorder.h> #include <asm/uaccess.h> #include <linux/atmdev.h> #include <linux/atm.h> #include <linux/sonet.h> #undef USE_SCATTERGATHER #undef USE_CHECKSUM_HW /* still confused about this */ /* #undef HE_DEBUG */ #include "he.h" #include "suni.h" #include <linux/atm_he.h> #define hprintk(fmt,args...) printk(KERN_ERR DEV_LABEL "%d: " fmt, he_dev->number , ##args) #ifdef HE_DEBUG #define HPRINTK(fmt,args...) printk(KERN_DEBUG DEV_LABEL "%d: " fmt, he_dev->number , ##args) #else /* !HE_DEBUG */ #define HPRINTK(fmt,args...) do { } while (0) #endif /* HE_DEBUG */ /* declarations */ static int he_open(struct atm_vcc *vcc); static void he_close(struct atm_vcc *vcc); static int he_send(struct atm_vcc *vcc, struct sk_buff *skb); static int he_ioctl(struct atm_dev *dev, unsigned int cmd, void __user *arg); static irqreturn_t he_irq_handler(int irq, void *dev_id); static void he_tasklet(unsigned long data); static int he_proc_read(struct atm_dev *dev,loff_t *pos,char *page); static int he_start(struct atm_dev *dev); static void he_stop(struct he_dev *dev); static void he_phy_put(struct atm_dev *, unsigned char, unsigned long); static unsigned char he_phy_get(struct atm_dev *, unsigned long); static u8 read_prom_byte(struct he_dev *he_dev, int addr); /* globals */ static struct he_dev *he_devs; static bool disable64; static short nvpibits = -1; static short nvcibits = -1; static short rx_skb_reserve = 16; static bool irq_coalesce = 1; static bool sdh = 0; /* Read from EEPROM = 0000 0011b */ static unsigned int readtab[] = { CS_HIGH | CLK_HIGH, CS_LOW | CLK_LOW, CLK_HIGH, /* 0 */ CLK_LOW, CLK_HIGH, /* 0 */ CLK_LOW, CLK_HIGH, /* 0 */ CLK_LOW, CLK_HIGH, /* 0 */ CLK_LOW, CLK_HIGH, /* 0 */ CLK_LOW, CLK_HIGH, /* 0 */ CLK_LOW | SI_HIGH, CLK_HIGH | SI_HIGH, /* 1 */ CLK_LOW | SI_HIGH, CLK_HIGH | SI_HIGH /* 1 */ }; /* Clock to read from/write to the EEPROM */ static unsigned int clocktab[] = { CLK_LOW, CLK_HIGH, CLK_LOW, CLK_HIGH, CLK_LOW, CLK_HIGH, CLK_LOW, CLK_HIGH, CLK_LOW, CLK_HIGH, CLK_LOW, CLK_HIGH, CLK_LOW, CLK_HIGH, CLK_LOW, CLK_HIGH, CLK_LOW }; static struct atmdev_ops he_ops = { .open = he_open, .close = he_close, .ioctl = he_ioctl, .send = he_send, .phy_put = he_phy_put, .phy_get = he_phy_get, .proc_read = he_proc_read, .owner = THIS_MODULE }; #define he_writel(dev, val, reg) do { writel(val, (dev)->membase + (reg)); wmb(); } while (0) #define he_readl(dev, reg) readl((dev)->membase + (reg)) /* section 2.12 connection memory access */ static __inline__ void he_writel_internal(struct he_dev *he_dev, unsigned val, unsigned addr, unsigned flags) { he_writel(he_dev, val, CON_DAT); (void) he_readl(he_dev, CON_DAT); /* flush posted writes */ he_writel(he_dev, flags | CON_CTL_WRITE | CON_CTL_ADDR(addr), CON_CTL); while (he_readl(he_dev, CON_CTL) & CON_CTL_BUSY); } #define he_writel_rcm(dev, val, reg) \ he_writel_internal(dev, val, reg, CON_CTL_RCM) #define he_writel_tcm(dev, val, reg) \ he_writel_internal(dev, val, reg, CON_CTL_TCM) #define he_writel_mbox(dev, val, reg) \ he_writel_internal(dev, val, reg, CON_CTL_MBOX) static unsigned he_readl_internal(struct he_dev *he_dev, unsigned addr, unsigned flags) { he_writel(he_dev, flags | CON_CTL_READ | CON_CTL_ADDR(addr), CON_CTL); while (he_readl(he_dev, CON_CTL) & CON_CTL_BUSY); return he_readl(he_dev, CON_DAT); } #define he_readl_rcm(dev, reg) \ he_readl_internal(dev, reg, CON_CTL_RCM) #define he_readl_tcm(dev, reg) \ he_readl_internal(dev, reg, CON_CTL_TCM) #define he_readl_mbox(dev, reg) \ he_readl_internal(dev, reg, CON_CTL_MBOX) /* figure 2.2 connection id */ #define he_mkcid(dev, vpi, vci) (((vpi << (dev)->vcibits) | vci) & 0x1fff) /* 2.5.1 per connection transmit state registers */ #define he_writel_tsr0(dev, val, cid) \ he_writel_tcm(dev, val, CONFIG_TSRA | (cid << 3) | 0) #define he_readl_tsr0(dev, cid) \ he_readl_tcm(dev, CONFIG_TSRA | (cid << 3) | 0) #define he_writel_tsr1(dev, val, cid) \ he_writel_tcm(dev, val, CONFIG_TSRA | (cid << 3) | 1) #define he_writel_tsr2(dev, val, cid) \ he_writel_tcm(dev, val, CONFIG_TSRA | (cid << 3) | 2) #define he_writel_tsr3(dev, val, cid) \ he_writel_tcm(dev, val, CONFIG_TSRA | (cid << 3) | 3) #define he_writel_tsr4(dev, val, cid) \ he_writel_tcm(dev, val, CONFIG_TSRA | (cid << 3) | 4) /* from page 2-20 * * NOTE While the transmit connection is active, bits 23 through 0 * of this register must not be written by the host. Byte * enables should be used during normal operation when writing * the most significant byte. */ #define he_writel_tsr4_upper(dev, val, cid) \ he_writel_internal(dev, val, CONFIG_TSRA | (cid << 3) | 4, \ CON_CTL_TCM \ | CON_BYTE_DISABLE_2 \ | CON_BYTE_DISABLE_1 \ | CON_BYTE_DISABLE_0) #define he_readl_tsr4(dev, cid) \ he_readl_tcm(dev, CONFIG_TSRA | (cid << 3) | 4) #define he_writel_tsr5(dev, val, cid) \ he_writel_tcm(dev, val, CONFIG_TSRA | (cid << 3) | 5) #define he_writel_tsr6(dev, val, cid) \ he_writel_tcm(dev, val, CONFIG_TSRA | (cid << 3) | 6) #define he_writel_tsr7(dev, val, cid) \ he_writel_tcm(dev, val, CONFIG_TSRA | (cid << 3) | 7) #define he_writel_tsr8(dev, val, cid) \ he_writel_tcm(dev, val, CONFIG_TSRB | (cid << 2) | 0) #define he_writel_tsr9(dev, val, cid) \ he_writel_tcm(dev, val, CONFIG_TSRB | (cid << 2) | 1) #define he_writel_tsr10(dev, val, cid) \ he_writel_tcm(dev, val, CONFIG_TSRB | (cid << 2) | 2) #define he_writel_tsr11(dev, val, cid) \ he_writel_tcm(dev, val, CONFIG_TSRB | (cid << 2) | 3) #define he_writel_tsr12(dev, val, cid) \ he_writel_tcm(dev, val, CONFIG_TSRC | (cid << 1) | 0) #define he_writel_tsr13(dev, val, cid) \ he_writel_tcm(dev, val, CONFIG_TSRC | (cid << 1) | 1) #define he_writel_tsr14(dev, val, cid) \ he_writel_tcm(dev, val, CONFIG_TSRD | cid) #define he_writel_tsr14_upper(dev, val, cid) \ he_writel_internal(dev, val, CONFIG_TSRD | cid, \ CON_CTL_TCM \ | CON_BYTE_DISABLE_2 \ | CON_BYTE_DISABLE_1 \ | CON_BYTE_DISABLE_0) /* 2.7.1 per connection receive state registers */ #define he_writel_rsr0(dev, val, cid) \ he_writel_rcm(dev, val, 0x00000 | (cid << 3) | 0) #define he_readl_rsr0(dev, cid) \ he_readl_rcm(dev, 0x00000 | (cid << 3) | 0) #define he_writel_rsr1(dev, val, cid) \ he_writel_rcm(dev, val, 0x00000 | (cid << 3) | 1) #define he_writel_rsr2(dev, val, cid) \ he_writel_rcm(dev, val, 0x00000 | (cid << 3) | 2) #define he_writel_rsr3(dev, val, cid) \ he_writel_rcm(dev, val, 0x00000 | (cid << 3) | 3) #define he_writel_rsr4(dev, val, cid) \ he_writel_rcm(dev, val, 0x00000 | (cid << 3) | 4) #define he_writel_rsr5(dev, val, cid) \ he_writel_rcm(dev, val, 0x00000 | (cid << 3) | 5) #define he_writel_rsr6(dev, val, cid) \ he_writel_rcm(dev, val, 0x00000 | (cid << 3) | 6) #define he_writel_rsr7(dev, val, cid) \ he_writel_rcm(dev, val, 0x00000 | (cid << 3) | 7) static __inline__ struct atm_vcc* __find_vcc(struct he_dev *he_dev, unsigned cid) { struct hlist_head *head; struct atm_vcc *vcc; struct hlist_node *node; struct sock *s; short vpi; int vci; vpi = cid >> he_dev->vcibits; vci = cid & ((1 << he_dev->vcibits) - 1); head = &vcc_hash[vci & (VCC_HTABLE_SIZE -1)]; sk_for_each(s, node, head) { vcc = atm_sk(s); if (vcc->dev == he_dev->atm_dev && vcc->vci == vci && vcc->vpi == vpi && vcc->qos.rxtp.traffic_class != ATM_NONE) { return vcc; } } return NULL; } static int __devinit he_init_one(struct pci_dev *pci_dev, const struct pci_device_id *pci_ent) { struct atm_dev *atm_dev = NULL; struct he_dev *he_dev = NULL; int err = 0; printk(KERN_INFO "ATM he driver\n"); if (pci_enable_device(pci_dev)) return -EIO; if (pci_set_dma_mask(pci_dev, DMA_BIT_MASK(32)) != 0) { printk(KERN_WARNING "he: no suitable dma available\n"); err = -EIO; goto init_one_failure; } atm_dev = atm_dev_register(DEV_LABEL, &pci_dev->dev, &he_ops, -1, NULL); if (!atm_dev) { err = -ENODEV; goto init_one_failure; } pci_set_drvdata(pci_dev, atm_dev); he_dev = kzalloc(sizeof(struct he_dev), GFP_KERNEL); if (!he_dev) { err = -ENOMEM; goto init_one_failure; } he_dev->pci_dev = pci_dev; he_dev->atm_dev = atm_dev; he_dev->atm_dev->dev_data = he_dev; atm_dev->dev_data = he_dev; he_dev->number = atm_dev->number; tasklet_init(&he_dev->tasklet, he_tasklet, (unsigned long) he_dev); spin_lock_init(&he_dev->global_lock); if (he_start(atm_dev)) { he_stop(he_dev); err = -ENODEV; goto init_one_failure; } he_dev->next = NULL; if (he_devs) he_dev->next = he_devs; he_devs = he_dev; return 0; init_one_failure: if (atm_dev) atm_dev_deregister(atm_dev); kfree(he_dev); pci_disable_device(pci_dev); return err; } static void __devexit he_remove_one (struct pci_dev *pci_dev) { struct atm_dev *atm_dev; struct he_dev *he_dev; atm_dev = pci_get_drvdata(pci_dev); he_dev = HE_DEV(atm_dev); /* need to remove from he_devs */ he_stop(he_dev); atm_dev_deregister(atm_dev); kfree(he_dev); pci_set_drvdata(pci_dev, NULL); pci_disable_device(pci_dev); } static unsigned rate_to_atmf(unsigned rate) /* cps to atm forum format */ { #define NONZERO (1 << 14) unsigned exp = 0; if (rate == 0) return 0; rate <<= 9; while (rate > 0x3ff) { ++exp; rate >>= 1; } return (NONZERO | (exp << 9) | (rate & 0x1ff)); } static void __devinit he_init_rx_lbfp0(struct he_dev *he_dev) { unsigned i, lbm_offset, lbufd_index, lbuf_addr, lbuf_count; unsigned lbufs_per_row = he_dev->cells_per_row / he_dev->cells_per_lbuf; unsigned lbuf_bufsize = he_dev->cells_per_lbuf * ATM_CELL_PAYLOAD; unsigned row_offset = he_dev->r0_startrow * he_dev->bytes_per_row; lbufd_index = 0; lbm_offset = he_readl(he_dev, RCMLBM_BA); he_writel(he_dev, lbufd_index, RLBF0_H); for (i = 0, lbuf_count = 0; i < he_dev->r0_numbuffs; ++i) { lbufd_index += 2; lbuf_addr = (row_offset + (lbuf_count * lbuf_bufsize)) / 32; he_writel_rcm(he_dev, lbuf_addr, lbm_offset); he_writel_rcm(he_dev, lbufd_index, lbm_offset + 1); if (++lbuf_count == lbufs_per_row) { lbuf_count = 0; row_offset += he_dev->bytes_per_row; } lbm_offset += 4; } he_writel(he_dev, lbufd_index - 2, RLBF0_T); he_writel(he_dev, he_dev->r0_numbuffs, RLBF0_C); } static void __devinit he_init_rx_lbfp1(struct he_dev *he_dev) { unsigned i, lbm_offset, lbufd_index, lbuf_addr, lbuf_count; unsigned lbufs_per_row = he_dev->cells_per_row / he_dev->cells_per_lbuf; unsigned lbuf_bufsize = he_dev->cells_per_lbuf * ATM_CELL_PAYLOAD; unsigned row_offset = he_dev->r1_startrow * he_dev->bytes_per_row; lbufd_index = 1; lbm_offset = he_readl(he_dev, RCMLBM_BA) + (2 * lbufd_index); he_writel(he_dev, lbufd_index, RLBF1_H); for (i = 0, lbuf_count = 0; i < he_dev->r1_numbuffs; ++i) { lbufd_index += 2; lbuf_addr = (row_offset + (lbuf_count * lbuf_bufsize)) / 32; he_writel_rcm(he_dev, lbuf_addr, lbm_offset); he_writel_rcm(he_dev, lbufd_index, lbm_offset + 1); if (++lbuf_count == lbufs_per_row) { lbuf_count = 0; row_offset += he_dev->bytes_per_row; } lbm_offset += 4; } he_writel(he_dev, lbufd_index - 2, RLBF1_T); he_writel(he_dev, he_dev->r1_numbuffs, RLBF1_C); } static void __devinit he_init_tx_lbfp(struct he_dev *he_dev) { unsigned i, lbm_offset, lbufd_index, lbuf_addr, lbuf_count; unsigned lbufs_per_row = he_dev->cells_per_row / he_dev->cells_per_lbuf; unsigned lbuf_bufsize = he_dev->cells_per_lbuf * ATM_CELL_PAYLOAD; unsigned row_offset = he_dev->tx_startrow * he_dev->bytes_per_row; lbufd_index = he_dev->r0_numbuffs + he_dev->r1_numbuffs; lbm_offset = he_readl(he_dev, RCMLBM_BA) + (2 * lbufd_index); he_writel(he_dev, lbufd_index, TLBF_H); for (i = 0, lbuf_count = 0; i < he_dev->tx_numbuffs; ++i) { lbufd_index += 1; lbuf_addr = (row_offset + (lbuf_count * lbuf_bufsize)) / 32; he_writel_rcm(he_dev, lbuf_addr, lbm_offset); he_writel_rcm(he_dev, lbufd_index, lbm_offset + 1); if (++lbuf_count == lbufs_per_row) { lbuf_count = 0; row_offset += he_dev->bytes_per_row; } lbm_offset += 2; } he_writel(he_dev, lbufd_index - 1, TLBF_T); } static int __devinit he_init_tpdrq(struct he_dev *he_dev) { he_dev->tpdrq_base = pci_alloc_consistent(he_dev->pci_dev, CONFIG_TPDRQ_SIZE * sizeof(struct he_tpdrq), &he_dev->tpdrq_phys); if (he_dev->tpdrq_base == NULL) { hprintk("failed to alloc tpdrq\n"); return -ENOMEM; } memset(he_dev->tpdrq_base, 0, CONFIG_TPDRQ_SIZE * sizeof(struct he_tpdrq)); he_dev->tpdrq_tail = he_dev->tpdrq_base; he_dev->tpdrq_head = he_dev->tpdrq_base; he_writel(he_dev, he_dev->tpdrq_phys, TPDRQ_B_H); he_writel(he_dev, 0, TPDRQ_T); he_writel(he_dev, CONFIG_TPDRQ_SIZE - 1, TPDRQ_S); return 0; } static void __devinit he_init_cs_block(struct he_dev *he_dev) { unsigned clock, rate, delta; int reg; /* 5.1.7 cs block initialization */ for (reg = 0; reg < 0x20; ++reg) he_writel_mbox(he_dev, 0x0, CS_STTIM0 + reg); /* rate grid timer reload values */ clock = he_is622(he_dev) ? 66667000 : 50000000; rate = he_dev->atm_dev->link_rate; delta = rate / 16 / 2; for (reg = 0; reg < 0x10; ++reg) { /* 2.4 internal transmit function * * we initialize the first row in the rate grid. * values are period (in clock cycles) of timer */ unsigned period = clock / rate; he_writel_mbox(he_dev, period, CS_TGRLD0 + reg); rate -= delta; } if (he_is622(he_dev)) { /* table 5.2 (4 cells per lbuf) */ he_writel_mbox(he_dev, 0x000800fa, CS_ERTHR0); he_writel_mbox(he_dev, 0x000c33cb, CS_ERTHR1); he_writel_mbox(he_dev, 0x0010101b, CS_ERTHR2); he_writel_mbox(he_dev, 0x00181dac, CS_ERTHR3); he_writel_mbox(he_dev, 0x00280600, CS_ERTHR4); /* table 5.3, 5.4, 5.5, 5.6, 5.7 */ he_writel_mbox(he_dev, 0x023de8b3, CS_ERCTL0); he_writel_mbox(he_dev, 0x1801, CS_ERCTL1); he_writel_mbox(he_dev, 0x68b3, CS_ERCTL2); he_writel_mbox(he_dev, 0x1280, CS_ERSTAT0); he_writel_mbox(he_dev, 0x68b3, CS_ERSTAT1); he_writel_mbox(he_dev, 0x14585, CS_RTFWR); he_writel_mbox(he_dev, 0x4680, CS_RTATR); /* table 5.8 */ he_writel_mbox(he_dev, 0x00159ece, CS_TFBSET); he_writel_mbox(he_dev, 0x68b3, CS_WCRMAX); he_writel_mbox(he_dev, 0x5eb3, CS_WCRMIN); he_writel_mbox(he_dev, 0xe8b3, CS_WCRINC); he_writel_mbox(he_dev, 0xdeb3, CS_WCRDEC); he_writel_mbox(he_dev, 0x68b3, CS_WCRCEIL); /* table 5.9 */ he_writel_mbox(he_dev, 0x5, CS_OTPPER); he_writel_mbox(he_dev, 0x14, CS_OTWPER); } else { /* table 5.1 (4 cells per lbuf) */ he_writel_mbox(he_dev, 0x000400ea, CS_ERTHR0); he_writel_mbox(he_dev, 0x00063388, CS_ERTHR1); he_writel_mbox(he_dev, 0x00081018, CS_ERTHR2); he_writel_mbox(he_dev, 0x000c1dac, CS_ERTHR3); he_writel_mbox(he_dev, 0x0014051a, CS_ERTHR4); /* table 5.3, 5.4, 5.5, 5.6, 5.7 */ he_writel_mbox(he_dev, 0x0235e4b1, CS_ERCTL0); he_writel_mbox(he_dev, 0x4701, CS_ERCTL1); he_writel_mbox(he_dev, 0x64b1, CS_ERCTL2); he_writel_mbox(he_dev, 0x1280, CS_ERSTAT0); he_writel_mbox(he_dev, 0x64b1, CS_ERSTAT1); he_writel_mbox(he_dev, 0xf424, CS_RTFWR); he_writel_mbox(he_dev, 0x4680, CS_RTATR); /* table 5.8 */ he_writel_mbox(he_dev, 0x000563b7, CS_TFBSET); he_writel_mbox(he_dev, 0x64b1, CS_WCRMAX); he_writel_mbox(he_dev, 0x5ab1, CS_WCRMIN); he_writel_mbox(he_dev, 0xe4b1, CS_WCRINC); he_writel_mbox(he_dev, 0xdab1, CS_WCRDEC); he_writel_mbox(he_dev, 0x64b1, CS_WCRCEIL); /* table 5.9 */ he_writel_mbox(he_dev, 0x6, CS_OTPPER); he_writel_mbox(he_dev, 0x1e, CS_OTWPER); } he_writel_mbox(he_dev, 0x8, CS_OTTLIM); for (reg = 0; reg < 0x8; ++reg) he_writel_mbox(he_dev, 0x0, CS_HGRRT0 + reg); } static int __devinit he_init_cs_block_rcm(struct he_dev *he_dev) { unsigned (*rategrid)[16][16]; unsigned rate, delta; int i, j, reg; unsigned rate_atmf, exp, man; unsigned long long rate_cps; int mult, buf, buf_limit = 4; rategrid = kmalloc( sizeof(unsigned) * 16 * 16, GFP_KERNEL); if (!rategrid) return -ENOMEM; /* initialize rate grid group table */ for (reg = 0x0; reg < 0xff; ++reg) he_writel_rcm(he_dev, 0x0, CONFIG_RCMABR + reg); /* initialize rate controller groups */ for (reg = 0x100; reg < 0x1ff; ++reg) he_writel_rcm(he_dev, 0x0, CONFIG_RCMABR + reg); /* initialize tNrm lookup table */ /* the manual makes reference to a routine in a sample driver for proper configuration; fortunately, we only need this in order to support abr connection */ /* initialize rate to group table */ rate = he_dev->atm_dev->link_rate; delta = rate / 32; /* * 2.4 transmit internal functions * * we construct a copy of the rate grid used by the scheduler * in order to construct the rate to group table below */ for (j = 0; j < 16; j++) { (*rategrid)[0][j] = rate; rate -= delta; } for (i = 1; i < 16; i++) for (j = 0; j < 16; j++) if (i > 14) (*rategrid)[i][j] = (*rategrid)[i - 1][j] / 4; else (*rategrid)[i][j] = (*rategrid)[i - 1][j] / 2; /* * 2.4 transmit internal function * * this table maps the upper 5 bits of exponent and mantissa * of the atm forum representation of the rate into an index * on rate grid */ rate_atmf = 0; while (rate_atmf < 0x400) { man = (rate_atmf & 0x1f) << 4; exp = rate_atmf >> 5; /* instead of '/ 512', use '>> 9' to prevent a call to divdu3 on x86 platforms */ rate_cps = (unsigned long long) (1 << exp) * (man + 512) >> 9; if (rate_cps < 10) rate_cps = 10; /* 2.2.1 minimum payload rate is 10 cps */ for (i = 255; i > 0; i--) if ((*rategrid)[i/16][i%16] >= rate_cps) break; /* pick nearest rate instead? */ /* * each table entry is 16 bits: (rate grid index (8 bits) * and a buffer limit (8 bits) * there are two table entries in each 32-bit register */ #ifdef notdef buf = rate_cps * he_dev->tx_numbuffs / (he_dev->atm_dev->link_rate * 2); #else /* this is pretty, but avoids _divdu3 and is mostly correct */ mult = he_dev->atm_dev->link_rate / ATM_OC3_PCR; if (rate_cps > (272 * mult)) buf = 4; else if (rate_cps > (204 * mult)) buf = 3; else if (rate_cps > (136 * mult)) buf = 2; else if (rate_cps > (68 * mult)) buf = 1; else buf = 0; #endif if (buf > buf_limit) buf = buf_limit; reg = (reg << 16) | ((i << 8) | buf); #define RTGTBL_OFFSET 0x400 if (rate_atmf & 0x1) he_writel_rcm(he_dev, reg, CONFIG_RCMABR + RTGTBL_OFFSET + (rate_atmf >> 1)); ++rate_atmf; } kfree(rategrid); return 0; } static int __devinit he_init_group(struct he_dev *he_dev, int group) { struct he_buff *heb, *next; dma_addr_t mapping; int i; he_writel(he_dev, 0x0, G0_RBPS_S + (group * 32)); he_writel(he_dev, 0x0, G0_RBPS_T + (group * 32)); he_writel(he_dev, 0x0, G0_RBPS_QI + (group * 32)); he_writel(he_dev, RBP_THRESH(0x1) | RBP_QSIZE(0x0), G0_RBPS_BS + (group * 32)); /* bitmap table */ he_dev->rbpl_table = kmalloc(BITS_TO_LONGS(RBPL_TABLE_SIZE) * sizeof(unsigned long), GFP_KERNEL); if (!he_dev->rbpl_table) { hprintk("unable to allocate rbpl bitmap table\n"); return -ENOMEM; } bitmap_zero(he_dev->rbpl_table, RBPL_TABLE_SIZE); /* rbpl_virt 64-bit pointers */ he_dev->rbpl_virt = kmalloc(RBPL_TABLE_SIZE * sizeof(struct he_buff *), GFP_KERNEL); if (!he_dev->rbpl_virt) { hprintk("unable to allocate rbpl virt table\n"); goto out_free_rbpl_table; } /* large buffer pool */ he_dev->rbpl_pool = pci_pool_create("rbpl", he_dev->pci_dev, CONFIG_RBPL_BUFSIZE, 64, 0); if (he_dev->rbpl_pool == NULL) { hprintk("unable to create rbpl pool\n"); goto out_free_rbpl_virt; } he_dev->rbpl_base = pci_alloc_consistent(he_dev->pci_dev, CONFIG_RBPL_SIZE * sizeof(struct he_rbp), &he_dev->rbpl_phys); if (he_dev->rbpl_base == NULL) { hprintk("failed to alloc rbpl_base\n"); goto out_destroy_rbpl_pool; } memset(he_dev->rbpl_base, 0, CONFIG_RBPL_SIZE * sizeof(struct he_rbp)); INIT_LIST_HEAD(&he_dev->rbpl_outstanding); for (i = 0; i < CONFIG_RBPL_SIZE; ++i) { heb = pci_pool_alloc(he_dev->rbpl_pool, GFP_KERNEL|GFP_DMA, &mapping); if (!heb) goto out_free_rbpl; heb->mapping = mapping; list_add(&heb->entry, &he_dev->rbpl_outstanding); set_bit(i, he_dev->rbpl_table); he_dev->rbpl_virt[i] = heb; he_dev->rbpl_hint = i + 1; he_dev->rbpl_base[i].idx = i << RBP_IDX_OFFSET; he_dev->rbpl_base[i].phys = mapping + offsetof(struct he_buff, data); } he_dev->rbpl_tail = &he_dev->rbpl_base[CONFIG_RBPL_SIZE - 1]; he_writel(he_dev, he_dev->rbpl_phys, G0_RBPL_S + (group * 32)); he_writel(he_dev, RBPL_MASK(he_dev->rbpl_tail), G0_RBPL_T + (group * 32)); he_writel(he_dev, (CONFIG_RBPL_BUFSIZE - sizeof(struct he_buff))/4, G0_RBPL_BS + (group * 32)); he_writel(he_dev, RBP_THRESH(CONFIG_RBPL_THRESH) | RBP_QSIZE(CONFIG_RBPL_SIZE - 1) | RBP_INT_ENB, G0_RBPL_QI + (group * 32)); /* rx buffer ready queue */ he_dev->rbrq_base = pci_alloc_consistent(he_dev->pci_dev, CONFIG_RBRQ_SIZE * sizeof(struct he_rbrq), &he_dev->rbrq_phys); if (he_dev->rbrq_base == NULL) { hprintk("failed to allocate rbrq\n"); goto out_free_rbpl; } memset(he_dev->rbrq_base, 0, CONFIG_RBRQ_SIZE * sizeof(struct he_rbrq)); he_dev->rbrq_head = he_dev->rbrq_base; he_writel(he_dev, he_dev->rbrq_phys, G0_RBRQ_ST + (group * 16)); he_writel(he_dev, 0, G0_RBRQ_H + (group * 16)); he_writel(he_dev, RBRQ_THRESH(CONFIG_RBRQ_THRESH) | RBRQ_SIZE(CONFIG_RBRQ_SIZE - 1), G0_RBRQ_Q + (group * 16)); if (irq_coalesce) { hprintk("coalescing interrupts\n"); he_writel(he_dev, RBRQ_TIME(768) | RBRQ_COUNT(7), G0_RBRQ_I + (group * 16)); } else he_writel(he_dev, RBRQ_TIME(0) | RBRQ_COUNT(1), G0_RBRQ_I + (group * 16)); /* tx buffer ready queue */ he_dev->tbrq_base = pci_alloc_consistent(he_dev->pci_dev, CONFIG_TBRQ_SIZE * sizeof(struct he_tbrq), &he_dev->tbrq_phys); if (he_dev->tbrq_base == NULL) { hprintk("failed to allocate tbrq\n"); goto out_free_rbpq_base; } memset(he_dev->tbrq_base, 0, CONFIG_TBRQ_SIZE * sizeof(struct he_tbrq)); he_dev->tbrq_head = he_dev->tbrq_base; he_writel(he_dev, he_dev->tbrq_phys, G0_TBRQ_B_T + (group * 16)); he_writel(he_dev, 0, G0_TBRQ_H + (group * 16)); he_writel(he_dev, CONFIG_TBRQ_SIZE - 1, G0_TBRQ_S + (group * 16)); he_writel(he_dev, CONFIG_TBRQ_THRESH, G0_TBRQ_THRESH + (group * 16)); return 0; out_free_rbpq_base: pci_free_consistent(he_dev->pci_dev, CONFIG_RBRQ_SIZE * sizeof(struct he_rbrq), he_dev->rbrq_base, he_dev->rbrq_phys); out_free_rbpl: list_for_each_entry_safe(heb, next, &he_dev->rbpl_outstanding, entry) pci_pool_free(he_dev->rbpl_pool, heb, heb->mapping); pci_free_consistent(he_dev->pci_dev, CONFIG_RBPL_SIZE * sizeof(struct he_rbp), he_dev->rbpl_base, he_dev->rbpl_phys); out_destroy_rbpl_pool: pci_pool_destroy(he_dev->rbpl_pool); out_free_rbpl_virt: kfree(he_dev->rbpl_virt); out_free_rbpl_table: kfree(he_dev->rbpl_table); return -ENOMEM; } static int __devinit he_init_irq(struct he_dev *he_dev) { int i; /* 2.9.3.5 tail offset for each interrupt queue is located after the end of the interrupt queue */ he_dev->irq_base = pci_alloc_consistent(he_dev->pci_dev, (CONFIG_IRQ_SIZE+1) * sizeof(struct he_irq), &he_dev->irq_phys); if (he_dev->irq_base == NULL) { hprintk("failed to allocate irq\n"); return -ENOMEM; } he_dev->irq_tailoffset = (unsigned *) &he_dev->irq_base[CONFIG_IRQ_SIZE]; *he_dev->irq_tailoffset = 0; he_dev->irq_head = he_dev->irq_base; he_dev->irq_tail = he_dev->irq_base; for (i = 0; i < CONFIG_IRQ_SIZE; ++i) he_dev->irq_base[i].isw = ITYPE_INVALID; he_writel(he_dev, he_dev->irq_phys, IRQ0_BASE); he_writel(he_dev, IRQ_SIZE(CONFIG_IRQ_SIZE) | IRQ_THRESH(CONFIG_IRQ_THRESH), IRQ0_HEAD); he_writel(he_dev, IRQ_INT_A | IRQ_TYPE_LINE, IRQ0_CNTL); he_writel(he_dev, 0x0, IRQ0_DATA); he_writel(he_dev, 0x0, IRQ1_BASE); he_writel(he_dev, 0x0, IRQ1_HEAD); he_writel(he_dev, 0x0, IRQ1_CNTL); he_writel(he_dev, 0x0, IRQ1_DATA); he_writel(he_dev, 0x0, IRQ2_BASE); he_writel(he_dev, 0x0, IRQ2_HEAD); he_writel(he_dev, 0x0, IRQ2_CNTL); he_writel(he_dev, 0x0, IRQ2_DATA); he_writel(he_dev, 0x0, IRQ3_BASE); he_writel(he_dev, 0x0, IRQ3_HEAD); he_writel(he_dev, 0x0, IRQ3_CNTL); he_writel(he_dev, 0x0, IRQ3_DATA); /* 2.9.3.2 interrupt queue mapping registers */ he_writel(he_dev, 0x0, GRP_10_MAP); he_writel(he_dev, 0x0, GRP_32_MAP); he_writel(he_dev, 0x0, GRP_54_MAP); he_writel(he_dev, 0x0, GRP_76_MAP); if (request_irq(he_dev->pci_dev->irq, he_irq_handler, IRQF_SHARED, DEV_LABEL, he_dev)) { hprintk("irq %d already in use\n", he_dev->pci_dev->irq); return -EINVAL; } he_dev->irq = he_dev->pci_dev->irq; return 0; } static int __devinit he_start(struct atm_dev *dev) { struct he_dev *he_dev; struct pci_dev *pci_dev; unsigned long membase; u16 command; u32 gen_cntl_0, host_cntl, lb_swap; u8 cache_size, timer; unsigned err; unsigned int status, reg; int i, group; he_dev = HE_DEV(dev); pci_dev = he_dev->pci_dev; membase = pci_resource_start(pci_dev, 0); HPRINTK("membase = 0x%lx irq = %d.\n", membase, pci_dev->irq); /* * pci bus controller initialization */ /* 4.3 pci bus controller-specific initialization */ if (pci_read_config_dword(pci_dev, GEN_CNTL_0, &gen_cntl_0) != 0) { hprintk("can't read GEN_CNTL_0\n"); return -EINVAL; } gen_cntl_0 |= (MRL_ENB | MRM_ENB | IGNORE_TIMEOUT); if (pci_write_config_dword(pci_dev, GEN_CNTL_0, gen_cntl_0) != 0) { hprintk("can't write GEN_CNTL_0.\n"); return -EINVAL; } if (pci_read_config_word(pci_dev, PCI_COMMAND, &command) != 0) { hprintk("can't read PCI_COMMAND.\n"); return -EINVAL; } command |= (PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER | PCI_COMMAND_INVALIDATE); if (pci_write_config_word(pci_dev, PCI_COMMAND, command) != 0) { hprintk("can't enable memory.\n"); return -EINVAL; } if (pci_read_config_byte(pci_dev, PCI_CACHE_LINE_SIZE, &cache_size)) { hprintk("can't read cache line size?\n"); return -EINVAL; } if (cache_size < 16) { cache_size = 16; if (pci_write_config_byte(pci_dev, PCI_CACHE_LINE_SIZE, cache_size)) hprintk("can't set cache line size to %d\n", cache_size); } if (pci_read_config_byte(pci_dev, PCI_LATENCY_TIMER, &timer)) { hprintk("can't read latency timer?\n"); return -EINVAL; } /* from table 3.9 * * LAT_TIMER = 1 + AVG_LAT + BURST_SIZE/BUS_SIZE * * AVG_LAT: The average first data read/write latency [maximum 16 clock cycles] * BURST_SIZE: 1536 bytes (read) for 622, 768 bytes (read) for 155 [192 clock cycles] * */ #define LAT_TIMER 209 if (timer < LAT_TIMER) { HPRINTK("latency timer was %d, setting to %d\n", timer, LAT_TIMER); timer = LAT_TIMER; if (pci_write_config_byte(pci_dev, PCI_LATENCY_TIMER, timer)) hprintk("can't set latency timer to %d\n", timer); } if (!(he_dev->membase = ioremap(membase, HE_REGMAP_SIZE))) { hprintk("can't set up page mapping\n"); return -EINVAL; } /* 4.4 card reset */ he_writel(he_dev, 0x0, RESET_CNTL); he_writel(he_dev, 0xff, RESET_CNTL); udelay(16*1000); /* 16 ms */ status = he_readl(he_dev, RESET_CNTL); if ((status & BOARD_RST_STATUS) == 0) { hprintk("reset failed\n"); return -EINVAL; } /* 4.5 set bus width */ host_cntl = he_readl(he_dev, HOST_CNTL); if (host_cntl & PCI_BUS_SIZE64) gen_cntl_0 |= ENBL_64; else gen_cntl_0 &= ~ENBL_64; if (disable64 == 1) { hprintk("disabling 64-bit pci bus transfers\n"); gen_cntl_0 &= ~ENBL_64; } if (gen_cntl_0 & ENBL_64) hprintk("64-bit transfers enabled\n"); pci_write_config_dword(pci_dev, GEN_CNTL_0, gen_cntl_0); /* 4.7 read prom contents */ for (i = 0; i < PROD_ID_LEN; ++i) he_dev->prod_id[i] = read_prom_byte(he_dev, PROD_ID + i); he_dev->media = read_prom_byte(he_dev, MEDIA); for (i = 0; i < 6; ++i) dev->esi[i] = read_prom_byte(he_dev, MAC_ADDR + i); hprintk("%s%s, %x:%x:%x:%x:%x:%x\n", he_dev->prod_id, he_dev->media & 0x40 ? "SM" : "MM", dev->esi[0], dev->esi[1], dev->esi[2], dev->esi[3], dev->esi[4], dev->esi[5]); he_dev->atm_dev->link_rate = he_is622(he_dev) ? ATM_OC12_PCR : ATM_OC3_PCR; /* 4.6 set host endianess */ lb_swap = he_readl(he_dev, LB_SWAP); if (he_is622(he_dev)) lb_swap &= ~XFER_SIZE; /* 4 cells */ else lb_swap |= XFER_SIZE; /* 8 cells */ #ifdef __BIG_ENDIAN lb_swap |= DESC_WR_SWAP | INTR_SWAP | BIG_ENDIAN_HOST; #else lb_swap &= ~(DESC_WR_SWAP | INTR_SWAP | BIG_ENDIAN_HOST | DATA_WR_SWAP | DATA_RD_SWAP | DESC_RD_SWAP); #endif /* __BIG_ENDIAN */ he_writel(he_dev, lb_swap, LB_SWAP); /* 4.8 sdram controller initialization */ he_writel(he_dev, he_is622(he_dev) ? LB_64_ENB : 0x0, SDRAM_CTL); /* 4.9 initialize rnum value */ lb_swap |= SWAP_RNUM_MAX(0xf); he_writel(he_dev, lb_swap, LB_SWAP); /* 4.10 initialize the interrupt queues */ if ((err = he_init_irq(he_dev)) != 0) return err; /* 4.11 enable pci bus controller state machines */ host_cntl |= (OUTFF_ENB | CMDFF_ENB | QUICK_RD_RETRY | QUICK_WR_RETRY | PERR_INT_ENB); he_writel(he_dev, host_cntl, HOST_CNTL); gen_cntl_0 |= INT_PROC_ENBL|INIT_ENB; pci_write_config_dword(pci_dev, GEN_CNTL_0, gen_cntl_0); /* * atm network controller initialization */ /* 5.1.1 generic configuration state */ /* * local (cell) buffer memory map * * HE155 HE622 * * 0 ____________1023 bytes 0 _______________________2047 bytes * | | | | | * | utility | | rx0 | | * 5|____________| 255|___________________| u | * 6| | 256| | t | * | | | | i | * | rx0 | row | tx | l | * | | | | i | * | | 767|___________________| t | * 517|____________| 768| | y | * row 518| | | rx1 | | * | | 1023|___________________|___| * | | * | tx | * | | * | | * 1535|____________| * 1536| | * | rx1 | * 2047|____________| * */ /* total 4096 connections */ he_dev->vcibits = CONFIG_DEFAULT_VCIBITS; he_dev->vpibits = CONFIG_DEFAULT_VPIBITS; if (nvpibits != -1 && nvcibits != -1 && nvpibits+nvcibits != HE_MAXCIDBITS) { hprintk("nvpibits + nvcibits != %d\n", HE_MAXCIDBITS); return -ENODEV; } if (nvpibits != -1) { he_dev->vpibits = nvpibits; he_dev->vcibits = HE_MAXCIDBITS - nvpibits; } if (nvcibits != -1) { he_dev->vcibits = nvcibits; he_dev->vpibits = HE_MAXCIDBITS - nvcibits; } if (he_is622(he_dev)) { he_dev->cells_per_row = 40; he_dev->bytes_per_row = 2048; he_dev->r0_numrows = 256; he_dev->tx_numrows = 512; he_dev->r1_numrows = 256; he_dev->r0_startrow = 0; he_dev->tx_startrow = 256; he_dev->r1_startrow = 768; } else { he_dev->cells_per_row = 20; he_dev->bytes_per_row = 1024; he_dev->r0_numrows = 512; he_dev->tx_numrows = 1018; he_dev->r1_numrows = 512; he_dev->r0_startrow = 6; he_dev->tx_startrow = 518; he_dev->r1_startrow = 1536; } he_dev->cells_per_lbuf = 4; he_dev->buffer_limit = 4; he_dev->r0_numbuffs = he_dev->r0_numrows * he_dev->cells_per_row / he_dev->cells_per_lbuf; if (he_dev->r0_numbuffs > 2560) he_dev->r0_numbuffs = 2560; he_dev->r1_numbuffs = he_dev->r1_numrows * he_dev->cells_per_row / he_dev->cells_per_lbuf; if (he_dev->r1_numbuffs > 2560) he_dev->r1_numbuffs = 2560; he_dev->tx_numbuffs = he_dev->tx_numrows * he_dev->cells_per_row / he_dev->cells_per_lbuf; if (he_dev->tx_numbuffs > 5120) he_dev->tx_numbuffs = 5120; /* 5.1.2 configure hardware dependent registers */ he_writel(he_dev, SLICE_X(0x2) | ARB_RNUM_MAX(0xf) | TH_PRTY(0x3) | RH_PRTY(0x3) | TL_PRTY(0x2) | RL_PRTY(0x1) | (he_is622(he_dev) ? BUS_MULTI(0x28) : BUS_MULTI(0x46)) | (he_is622(he_dev) ? NET_PREF(0x50) : NET_PREF(0x8c)), LBARB); he_writel(he_dev, BANK_ON | (he_is622(he_dev) ? (REF_RATE(0x384) | WIDE_DATA) : REF_RATE(0x150)), SDRAMCON); he_writel(he_dev, (he_is622(he_dev) ? RM_BANK_WAIT(1) : RM_BANK_WAIT(0)) | RM_RW_WAIT(1), RCMCONFIG); he_writel(he_dev, (he_is622(he_dev) ? TM_BANK_WAIT(2) : TM_BANK_WAIT(1)) | TM_RW_WAIT(1), TCMCONFIG); he_writel(he_dev, he_dev->cells_per_lbuf * ATM_CELL_PAYLOAD, LB_CONFIG); he_writel(he_dev, (he_is622(he_dev) ? UT_RD_DELAY(8) : UT_RD_DELAY(0)) | (he_is622(he_dev) ? RC_UT_MODE(0) : RC_UT_MODE(1)) | RX_VALVP(he_dev->vpibits) | RX_VALVC(he_dev->vcibits), RC_CONFIG); he_writel(he_dev, DRF_THRESH(0x20) | (he_is622(he_dev) ? TX_UT_MODE(0) : TX_UT_MODE(1)) | TX_VCI_MASK(he_dev->vcibits) | LBFREE_CNT(he_dev->tx_numbuffs), TX_CONFIG); he_writel(he_dev, 0x0, TXAAL5_PROTO); he_writel(he_dev, PHY_INT_ENB | (he_is622(he_dev) ? PTMR_PRE(67 - 1) : PTMR_PRE(50 - 1)), RH_CONFIG); /* 5.1.3 initialize connection memory */ for (i = 0; i < TCM_MEM_SIZE; ++i) he_writel_tcm(he_dev, 0, i); for (i = 0; i < RCM_MEM_SIZE; ++i) he_writel_rcm(he_dev, 0, i); /* * transmit connection memory map * * tx memory * 0x0 ___________________ * | | * | | * | TSRa | * | | * | | * 0x8000|___________________| * | | * | TSRb | * 0xc000|___________________| * | | * | TSRc | * 0xe000|___________________| * | TSRd | * 0xf000|___________________| * | tmABR | * 0x10000|___________________| * | | * | tmTPD | * |___________________| * | | * .... * 0x1ffff|___________________| * * */ he_writel(he_dev, CONFIG_TSRB, TSRB_BA); he_writel(he_dev, CONFIG_TSRC, TSRC_BA); he_writel(he_dev, CONFIG_TSRD, TSRD_BA); he_writel(he_dev, CONFIG_TMABR, TMABR_BA); he_writel(he_dev, CONFIG_TPDBA, TPD_BA); /* * receive connection memory map * * 0x0 ___________________ * | | * | | * | RSRa | * | | * | | * 0x8000|___________________| * | | * | rx0/1 | * | LBM | link lists of local * | tx | buffer memory * | | * 0xd000|___________________| * | | * | rmABR | * 0xe000|___________________| * | | * | RSRb | * |___________________| * | | * .... * 0xffff|___________________| */ he_writel(he_dev, 0x08000, RCMLBM_BA); he_writel(he_dev, 0x0e000, RCMRSRB_BA); he_writel(he_dev, 0x0d800, RCMABR_BA); /* 5.1.4 initialize local buffer free pools linked lists */ he_init_rx_lbfp0(he_dev); he_init_rx_lbfp1(he_dev); he_writel(he_dev, 0x0, RLBC_H); he_writel(he_dev, 0x0, RLBC_T); he_writel(he_dev, 0x0, RLBC_H2); he_writel(he_dev, 512, RXTHRSH); /* 10% of r0+r1 buffers */ he_writel(he_dev, 256, LITHRSH); /* 5% of r0+r1 buffers */ he_init_tx_lbfp(he_dev); he_writel(he_dev, he_is622(he_dev) ? 0x104780 : 0x800, UBUFF_BA); /* 5.1.5 initialize intermediate receive queues */ if (he_is622(he_dev)) { he_writel(he_dev, 0x000f, G0_INMQ_S); he_writel(he_dev, 0x200f, G0_INMQ_L); he_writel(he_dev, 0x001f, G1_INMQ_S); he_writel(he_dev, 0x201f, G1_INMQ_L); he_writel(he_dev, 0x002f, G2_INMQ_S); he_writel(he_dev, 0x202f, G2_INMQ_L); he_writel(he_dev, 0x003f, G3_INMQ_S); he_writel(he_dev, 0x203f, G3_INMQ_L); he_writel(he_dev, 0x004f, G4_INMQ_S); he_writel(he_dev, 0x204f, G4_INMQ_L); he_writel(he_dev, 0x005f, G5_INMQ_S); he_writel(he_dev, 0x205f, G5_INMQ_L); he_writel(he_dev, 0x006f, G6_INMQ_S); he_writel(he_dev, 0x206f, G6_INMQ_L); he_writel(he_dev, 0x007f, G7_INMQ_S); he_writel(he_dev, 0x207f, G7_INMQ_L); } else { he_writel(he_dev, 0x0000, G0_INMQ_S); he_writel(he_dev, 0x0008, G0_INMQ_L); he_writel(he_dev, 0x0001, G1_INMQ_S); he_writel(he_dev, 0x0009, G1_INMQ_L); he_writel(he_dev, 0x0002, G2_INMQ_S); he_writel(he_dev, 0x000a, G2_INMQ_L); he_writel(he_dev, 0x0003, G3_INMQ_S); he_writel(he_dev, 0x000b, G3_INMQ_L); he_writel(he_dev, 0x0004, G4_INMQ_S); he_writel(he_dev, 0x000c, G4_INMQ_L); he_writel(he_dev, 0x0005, G5_INMQ_S); he_writel(he_dev, 0x000d, G5_INMQ_L); he_writel(he_dev, 0x0006, G6_INMQ_S); he_writel(he_dev, 0x000e, G6_INMQ_L); he_writel(he_dev, 0x0007, G7_INMQ_S); he_writel(he_dev, 0x000f, G7_INMQ_L); } /* 5.1.6 application tunable parameters */ he_writel(he_dev, 0x0, MCC); he_writel(he_dev, 0x0, OEC); he_writel(he_dev, 0x0, DCC); he_writel(he_dev, 0x0, CEC); /* 5.1.7 cs block initialization */ he_init_cs_block(he_dev); /* 5.1.8 cs block connection memory initialization */ if (he_init_cs_block_rcm(he_dev) < 0) return -ENOMEM; /* 5.1.10 initialize host structures */ he_init_tpdrq(he_dev); he_dev->tpd_pool = pci_pool_create("tpd", he_dev->pci_dev, sizeof(struct he_tpd), TPD_ALIGNMENT, 0); if (he_dev->tpd_pool == NULL) { hprintk("unable to create tpd pci_pool\n"); return -ENOMEM; } INIT_LIST_HEAD(&he_dev->outstanding_tpds); if (he_init_group(he_dev, 0) != 0) return -ENOMEM; for (group = 1; group < HE_NUM_GROUPS; ++group) { he_writel(he_dev, 0x0, G0_RBPS_S + (group * 32)); he_writel(he_dev, 0x0, G0_RBPS_T + (group * 32)); he_writel(he_dev, 0x0, G0_RBPS_QI + (group * 32)); he_writel(he_dev, RBP_THRESH(0x1) | RBP_QSIZE(0x0), G0_RBPS_BS + (group * 32)); he_writel(he_dev, 0x0, G0_RBPL_S + (group * 32)); he_writel(he_dev, 0x0, G0_RBPL_T + (group * 32)); he_writel(he_dev, RBP_THRESH(0x1) | RBP_QSIZE(0x0), G0_RBPL_QI + (group * 32)); he_writel(he_dev, 0x0, G0_RBPL_BS + (group * 32)); he_writel(he_dev, 0x0, G0_RBRQ_ST + (group * 16)); he_writel(he_dev, 0x0, G0_RBRQ_H + (group * 16)); he_writel(he_dev, RBRQ_THRESH(0x1) | RBRQ_SIZE(0x0), G0_RBRQ_Q + (group * 16)); he_writel(he_dev, 0x0, G0_RBRQ_I + (group * 16)); he_writel(he_dev, 0x0, G0_TBRQ_B_T + (group * 16)); he_writel(he_dev, 0x0, G0_TBRQ_H + (group * 16)); he_writel(he_dev, TBRQ_THRESH(0x1), G0_TBRQ_THRESH + (group * 16)); he_writel(he_dev, 0x0, G0_TBRQ_S + (group * 16)); } /* host status page */ he_dev->hsp = pci_alloc_consistent(he_dev->pci_dev, sizeof(struct he_hsp), &he_dev->hsp_phys); if (he_dev->hsp == NULL) { hprintk("failed to allocate host status page\n"); return -ENOMEM; } memset(he_dev->hsp, 0, sizeof(struct he_hsp)); he_writel(he_dev, he_dev->hsp_phys, HSP_BA); /* initialize framer */ #ifdef CONFIG_ATM_HE_USE_SUNI if (he_isMM(he_dev)) suni_init(he_dev->atm_dev); if (he_dev->atm_dev->phy && he_dev->atm_dev->phy->start) he_dev->atm_dev->phy->start(he_dev->atm_dev); #endif /* CONFIG_ATM_HE_USE_SUNI */ if (sdh) { /* this really should be in suni.c but for now... */ int val; val = he_phy_get(he_dev->atm_dev, SUNI_TPOP_APM); val = (val & ~SUNI_TPOP_APM_S) | (SUNI_TPOP_S_SDH << SUNI_TPOP_APM_S_SHIFT); he_phy_put(he_dev->atm_dev, val, SUNI_TPOP_APM); he_phy_put(he_dev->atm_dev, SUNI_TACP_IUCHP_CLP, SUNI_TACP_IUCHP); } /* 5.1.12 enable transmit and receive */ reg = he_readl_mbox(he_dev, CS_ERCTL0); reg |= TX_ENABLE|ER_ENABLE; he_writel_mbox(he_dev, reg, CS_ERCTL0); reg = he_readl(he_dev, RC_CONFIG); reg |= RX_ENABLE; he_writel(he_dev, reg, RC_CONFIG); for (i = 0; i < HE_NUM_CS_STPER; ++i) { he_dev->cs_stper[i].inuse = 0; he_dev->cs_stper[i].pcr = -1; } he_dev->total_bw = 0; /* atm linux initialization */ he_dev->atm_dev->ci_range.vpi_bits = he_dev->vpibits; he_dev->atm_dev->ci_range.vci_bits = he_dev->vcibits; he_dev->irq_peak = 0; he_dev->rbrq_peak = 0; he_dev->rbpl_peak = 0; he_dev->tbrq_peak = 0; HPRINTK("hell bent for leather!\n"); return 0; } static void he_stop(struct he_dev *he_dev) { struct he_buff *heb, *next; struct pci_dev *pci_dev; u32 gen_cntl_0, reg; u16 command; pci_dev = he_dev->pci_dev; /* disable interrupts */ if (he_dev->membase) { pci_read_config_dword(pci_dev, GEN_CNTL_0, &gen_cntl_0); gen_cntl_0 &= ~(INT_PROC_ENBL | INIT_ENB); pci_write_config_dword(pci_dev, GEN_CNTL_0, gen_cntl_0); tasklet_disable(&he_dev->tasklet); /* disable recv and transmit */ reg = he_readl_mbox(he_dev, CS_ERCTL0); reg &= ~(TX_ENABLE|ER_ENABLE); he_writel_mbox(he_dev, reg, CS_ERCTL0); reg = he_readl(he_dev, RC_CONFIG); reg &= ~(RX_ENABLE); he_writel(he_dev, reg, RC_CONFIG); } #ifdef CONFIG_ATM_HE_USE_SUNI if (he_dev->atm_dev->phy && he_dev->atm_dev->phy->stop) he_dev->atm_dev->phy->stop(he_dev->atm_dev); #endif /* CONFIG_ATM_HE_USE_SUNI */ if (he_dev->irq) free_irq(he_dev->irq, he_dev); if (he_dev->irq_base) pci_free_consistent(he_dev->pci_dev, (CONFIG_IRQ_SIZE+1) * sizeof(struct he_irq), he_dev->irq_base, he_dev->irq_phys); if (he_dev->hsp) pci_free_consistent(he_dev->pci_dev, sizeof(struct he_hsp), he_dev->hsp, he_dev->hsp_phys); if (he_dev->rbpl_base) { list_for_each_entry_safe(heb, next, &he_dev->rbpl_outstanding, entry) pci_pool_free(he_dev->rbpl_pool, heb, heb->mapping); pci_free_consistent(he_dev->pci_dev, CONFIG_RBPL_SIZE * sizeof(struct he_rbp), he_dev->rbpl_base, he_dev->rbpl_phys); } kfree(he_dev->rbpl_virt); kfree(he_dev->rbpl_table); if (he_dev->rbpl_pool) pci_pool_destroy(he_dev->rbpl_pool); if (he_dev->rbrq_base) pci_free_consistent(he_dev->pci_dev, CONFIG_RBRQ_SIZE * sizeof(struct he_rbrq), he_dev->rbrq_base, he_dev->rbrq_phys); if (he_dev->tbrq_base) pci_free_consistent(he_dev->pci_dev, CONFIG_TBRQ_SIZE * sizeof(struct he_tbrq), he_dev->tbrq_base, he_dev->tbrq_phys); if (he_dev->tpdrq_base) pci_free_consistent(he_dev->pci_dev, CONFIG_TBRQ_SIZE * sizeof(struct he_tbrq), he_dev->tpdrq_base, he_dev->tpdrq_phys); if (he_dev->tpd_pool) pci_pool_destroy(he_dev->tpd_pool); if (he_dev->pci_dev) { pci_read_config_word(he_dev->pci_dev, PCI_COMMAND, &command); command &= ~(PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER); pci_write_config_word(he_dev->pci_dev, PCI_COMMAND, command); } if (he_dev->membase) iounmap(he_dev->membase); } static struct he_tpd * __alloc_tpd(struct he_dev *he_dev) { struct he_tpd *tpd; dma_addr_t mapping; tpd = pci_pool_alloc(he_dev->tpd_pool, GFP_ATOMIC|GFP_DMA, &mapping); if (tpd == NULL) return NULL; tpd->status = TPD_ADDR(mapping); tpd->reserved = 0; tpd->iovec[0].addr = 0; tpd->iovec[0].len = 0; tpd->iovec[1].addr = 0; tpd->iovec[1].len = 0; tpd->iovec[2].addr = 0; tpd->iovec[2].len = 0; return tpd; } #define AAL5_LEN(buf,len) \ ((((unsigned char *)(buf))[(len)-6] << 8) | \ (((unsigned char *)(buf))[(len)-5])) /* 2.10.1.2 receive * * aal5 packets can optionally return the tcp checksum in the lower * 16 bits of the crc (RSR0_TCP_CKSUM) */ #define TCP_CKSUM(buf,len) \ ((((unsigned char *)(buf))[(len)-2] << 8) | \ (((unsigned char *)(buf))[(len-1)])) static int he_service_rbrq(struct he_dev *he_dev, int group) { struct he_rbrq *rbrq_tail = (struct he_rbrq *) ((unsigned long)he_dev->rbrq_base | he_dev->hsp->group[group].rbrq_tail); unsigned cid, lastcid = -1; struct sk_buff *skb; struct atm_vcc *vcc = NULL; struct he_vcc *he_vcc; struct he_buff *heb, *next; int i; int pdus_assembled = 0; int updated = 0; read_lock(&vcc_sklist_lock); while (he_dev->rbrq_head != rbrq_tail) { ++updated; HPRINTK("%p rbrq%d 0x%x len=%d cid=0x%x %s%s%s%s%s%s\n", he_dev->rbrq_head, group, RBRQ_ADDR(he_dev->rbrq_head), RBRQ_BUFLEN(he_dev->rbrq_head), RBRQ_CID(he_dev->rbrq_head), RBRQ_CRC_ERR(he_dev->rbrq_head) ? " CRC_ERR" : "", RBRQ_LEN_ERR(he_dev->rbrq_head) ? " LEN_ERR" : "", RBRQ_END_PDU(he_dev->rbrq_head) ? " END_PDU" : "", RBRQ_AAL5_PROT(he_dev->rbrq_head) ? " AAL5_PROT" : "", RBRQ_CON_CLOSED(he_dev->rbrq_head) ? " CON_CLOSED" : "", RBRQ_HBUF_ERR(he_dev->rbrq_head) ? " HBUF_ERR" : ""); i = RBRQ_ADDR(he_dev->rbrq_head) >> RBP_IDX_OFFSET; heb = he_dev->rbpl_virt[i]; cid = RBRQ_CID(he_dev->rbrq_head); if (cid != lastcid) vcc = __find_vcc(he_dev, cid); lastcid = cid; if (vcc == NULL || (he_vcc = HE_VCC(vcc)) == NULL) { hprintk("vcc/he_vcc == NULL (cid 0x%x)\n", cid); if (!RBRQ_HBUF_ERR(he_dev->rbrq_head)) { clear_bit(i, he_dev->rbpl_table); list_del(&heb->entry); pci_pool_free(he_dev->rbpl_pool, heb, heb->mapping); } goto next_rbrq_entry; } if (RBRQ_HBUF_ERR(he_dev->rbrq_head)) { hprintk("HBUF_ERR! (cid 0x%x)\n", cid); atomic_inc(&vcc->stats->rx_drop); goto return_host_buffers; } heb->len = RBRQ_BUFLEN(he_dev->rbrq_head) * 4; clear_bit(i, he_dev->rbpl_table); list_move_tail(&heb->entry, &he_vcc->buffers); he_vcc->pdu_len += heb->len; if (RBRQ_CON_CLOSED(he_dev->rbrq_head)) { lastcid = -1; HPRINTK("wake_up rx_waitq (cid 0x%x)\n", cid); wake_up(&he_vcc->rx_waitq); goto return_host_buffers; } if (!RBRQ_END_PDU(he_dev->rbrq_head)) goto next_rbrq_entry; if (RBRQ_LEN_ERR(he_dev->rbrq_head) || RBRQ_CRC_ERR(he_dev->rbrq_head)) { HPRINTK("%s%s (%d.%d)\n", RBRQ_CRC_ERR(he_dev->rbrq_head) ? "CRC_ERR " : "", RBRQ_LEN_ERR(he_dev->rbrq_head) ? "LEN_ERR" : "", vcc->vpi, vcc->vci); atomic_inc(&vcc->stats->rx_err); goto return_host_buffers; } skb = atm_alloc_charge(vcc, he_vcc->pdu_len + rx_skb_reserve, GFP_ATOMIC); if (!skb) { HPRINTK("charge failed (%d.%d)\n", vcc->vpi, vcc->vci); goto return_host_buffers; } if (rx_skb_reserve > 0) skb_reserve(skb, rx_skb_reserve); __net_timestamp(skb); list_for_each_entry(heb, &he_vcc->buffers, entry) memcpy(skb_put(skb, heb->len), &heb->data, heb->len); switch (vcc->qos.aal) { case ATM_AAL0: /* 2.10.1.5 raw cell receive */ skb->len = ATM_AAL0_SDU; skb_set_tail_pointer(skb, skb->len); break; case ATM_AAL5: /* 2.10.1.2 aal5 receive */ skb->len = AAL5_LEN(skb->data, he_vcc->pdu_len); skb_set_tail_pointer(skb, skb->len); #ifdef USE_CHECKSUM_HW if (vcc->vpi == 0 && vcc->vci >= ATM_NOT_RSV_VCI) { skb->ip_summed = CHECKSUM_COMPLETE; skb->csum = TCP_CKSUM(skb->data, he_vcc->pdu_len); } #endif break; } #ifdef should_never_happen if (skb->len > vcc->qos.rxtp.max_sdu) hprintk("pdu_len (%d) > vcc->qos.rxtp.max_sdu (%d)! cid 0x%x\n", skb->len, vcc->qos.rxtp.max_sdu, cid); #endif #ifdef notdef ATM_SKB(skb)->vcc = vcc; #endif spin_unlock(&he_dev->global_lock); vcc->push(vcc, skb); spin_lock(&he_dev->global_lock); atomic_inc(&vcc->stats->rx); return_host_buffers: ++pdus_assembled; list_for_each_entry_safe(heb, next, &he_vcc->buffers, entry) pci_pool_free(he_dev->rbpl_pool, heb, heb->mapping); INIT_LIST_HEAD(&he_vcc->buffers); he_vcc->pdu_len = 0; next_rbrq_entry: he_dev->rbrq_head = (struct he_rbrq *) ((unsigned long) he_dev->rbrq_base | RBRQ_MASK(he_dev->rbrq_head + 1)); } read_unlock(&vcc_sklist_lock); if (updated) { if (updated > he_dev->rbrq_peak) he_dev->rbrq_peak = updated; he_writel(he_dev, RBRQ_MASK(he_dev->rbrq_head), G0_RBRQ_H + (group * 16)); } return pdus_assembled; } static void he_service_tbrq(struct he_dev *he_dev, int group) { struct he_tbrq *tbrq_tail = (struct he_tbrq *) ((unsigned long)he_dev->tbrq_base | he_dev->hsp->group[group].tbrq_tail); struct he_tpd *tpd; int slot, updated = 0; struct he_tpd *__tpd; /* 2.1.6 transmit buffer return queue */ while (he_dev->tbrq_head != tbrq_tail) { ++updated; HPRINTK("tbrq%d 0x%x%s%s\n", group, TBRQ_TPD(he_dev->tbrq_head), TBRQ_EOS(he_dev->tbrq_head) ? " EOS" : "", TBRQ_MULTIPLE(he_dev->tbrq_head) ? " MULTIPLE" : ""); tpd = NULL; list_for_each_entry(__tpd, &he_dev->outstanding_tpds, entry) { if (TPD_ADDR(__tpd->status) == TBRQ_TPD(he_dev->tbrq_head)) { tpd = __tpd; list_del(&__tpd->entry); break; } } if (tpd == NULL) { hprintk("unable to locate tpd for dma buffer %x\n", TBRQ_TPD(he_dev->tbrq_head)); goto next_tbrq_entry; } if (TBRQ_EOS(he_dev->tbrq_head)) { HPRINTK("wake_up(tx_waitq) cid 0x%x\n", he_mkcid(he_dev, tpd->vcc->vpi, tpd->vcc->vci)); if (tpd->vcc) wake_up(&HE_VCC(tpd->vcc)->tx_waitq); goto next_tbrq_entry; } for (slot = 0; slot < TPD_MAXIOV; ++slot) { if (tpd->iovec[slot].addr) pci_unmap_single(he_dev->pci_dev, tpd->iovec[slot].addr, tpd->iovec[slot].len & TPD_LEN_MASK, PCI_DMA_TODEVICE); if (tpd->iovec[slot].len & TPD_LST) break; } if (tpd->skb) { /* && !TBRQ_MULTIPLE(he_dev->tbrq_head) */ if (tpd->vcc && tpd->vcc->pop) tpd->vcc->pop(tpd->vcc, tpd->skb); else dev_kfree_skb_any(tpd->skb); } next_tbrq_entry: if (tpd) pci_pool_free(he_dev->tpd_pool, tpd, TPD_ADDR(tpd->status)); he_dev->tbrq_head = (struct he_tbrq *) ((unsigned long) he_dev->tbrq_base | TBRQ_MASK(he_dev->tbrq_head + 1)); } if (updated) { if (updated > he_dev->tbrq_peak) he_dev->tbrq_peak = updated; he_writel(he_dev, TBRQ_MASK(he_dev->tbrq_head), G0_TBRQ_H + (group * 16)); } } static void he_service_rbpl(struct he_dev *he_dev, int group) { struct he_rbp *new_tail; struct he_rbp *rbpl_head; struct he_buff *heb; dma_addr_t mapping; int i; int moved = 0; rbpl_head = (struct he_rbp *) ((unsigned long)he_dev->rbpl_base | RBPL_MASK(he_readl(he_dev, G0_RBPL_S))); for (;;) { new_tail = (struct he_rbp *) ((unsigned long)he_dev->rbpl_base | RBPL_MASK(he_dev->rbpl_tail+1)); /* table 3.42 -- rbpl_tail should never be set to rbpl_head */ if (new_tail == rbpl_head) break; i = find_next_zero_bit(he_dev->rbpl_table, RBPL_TABLE_SIZE, he_dev->rbpl_hint); if (i > (RBPL_TABLE_SIZE - 1)) { i = find_first_zero_bit(he_dev->rbpl_table, RBPL_TABLE_SIZE); if (i > (RBPL_TABLE_SIZE - 1)) break; } he_dev->rbpl_hint = i + 1; heb = pci_pool_alloc(he_dev->rbpl_pool, GFP_ATOMIC|GFP_DMA, &mapping); if (!heb) break; heb->mapping = mapping; list_add(&heb->entry, &he_dev->rbpl_outstanding); he_dev->rbpl_virt[i] = heb; set_bit(i, he_dev->rbpl_table); new_tail->idx = i << RBP_IDX_OFFSET; new_tail->phys = mapping + offsetof(struct he_buff, data); he_dev->rbpl_tail = new_tail; ++moved; } if (moved) he_writel(he_dev, RBPL_MASK(he_dev->rbpl_tail), G0_RBPL_T); } static void he_tasklet(unsigned long data) { unsigned long flags; struct he_dev *he_dev = (struct he_dev *) data; int group, type; int updated = 0; HPRINTK("tasklet (0x%lx)\n", data); spin_lock_irqsave(&he_dev->global_lock, flags); while (he_dev->irq_head != he_dev->irq_tail) { ++updated; type = ITYPE_TYPE(he_dev->irq_head->isw); group = ITYPE_GROUP(he_dev->irq_head->isw); switch (type) { case ITYPE_RBRQ_THRESH: HPRINTK("rbrq%d threshold\n", group); /* fall through */ case ITYPE_RBRQ_TIMER: if (he_service_rbrq(he_dev, group)) he_service_rbpl(he_dev, group); break; case ITYPE_TBRQ_THRESH: HPRINTK("tbrq%d threshold\n", group); /* fall through */ case ITYPE_TPD_COMPLETE: he_service_tbrq(he_dev, group); break; case ITYPE_RBPL_THRESH: he_service_rbpl(he_dev, group); break; case ITYPE_RBPS_THRESH: /* shouldn't happen unless small buffers enabled */ break; case ITYPE_PHY: HPRINTK("phy interrupt\n"); #ifdef CONFIG_ATM_HE_USE_SUNI spin_unlock_irqrestore(&he_dev->global_lock, flags); if (he_dev->atm_dev->phy && he_dev->atm_dev->phy->interrupt) he_dev->atm_dev->phy->interrupt(he_dev->atm_dev); spin_lock_irqsave(&he_dev->global_lock, flags); #endif break; case ITYPE_OTHER: switch (type|group) { case ITYPE_PARITY: hprintk("parity error\n"); break; case ITYPE_ABORT: hprintk("abort 0x%x\n", he_readl(he_dev, ABORT_ADDR)); break; } break; case ITYPE_TYPE(ITYPE_INVALID): /* see 8.1.1 -- check all queues */ HPRINTK("isw not updated 0x%x\n", he_dev->irq_head->isw); he_service_rbrq(he_dev, 0); he_service_rbpl(he_dev, 0); he_service_tbrq(he_dev, 0); break; default: hprintk("bad isw 0x%x?\n", he_dev->irq_head->isw); } he_dev->irq_head->isw = ITYPE_INVALID; he_dev->irq_head = (struct he_irq *) NEXT_ENTRY(he_dev->irq_base, he_dev->irq_head, IRQ_MASK); } if (updated) { if (updated > he_dev->irq_peak) he_dev->irq_peak = updated; he_writel(he_dev, IRQ_SIZE(CONFIG_IRQ_SIZE) | IRQ_THRESH(CONFIG_IRQ_THRESH) | IRQ_TAIL(he_dev->irq_tail), IRQ0_HEAD); (void) he_readl(he_dev, INT_FIFO); /* 8.1.2 controller errata; flush posted writes */ } spin_unlock_irqrestore(&he_dev->global_lock, flags); } static irqreturn_t he_irq_handler(int irq, void *dev_id) { unsigned long flags; struct he_dev *he_dev = (struct he_dev * )dev_id; int handled = 0; if (he_dev == NULL) return IRQ_NONE; spin_lock_irqsave(&he_dev->global_lock, flags); he_dev->irq_tail = (struct he_irq *) (((unsigned long)he_dev->irq_base) | (*he_dev->irq_tailoffset << 2)); if (he_dev->irq_tail == he_dev->irq_head) { HPRINTK("tailoffset not updated?\n"); he_dev->irq_tail = (struct he_irq *) ((unsigned long)he_dev->irq_base | ((he_readl(he_dev, IRQ0_BASE) & IRQ_MASK) << 2)); (void) he_readl(he_dev, INT_FIFO); /* 8.1.2 controller errata */ } #ifdef DEBUG if (he_dev->irq_head == he_dev->irq_tail /* && !IRQ_PENDING */) hprintk("spurious (or shared) interrupt?\n"); #endif if (he_dev->irq_head != he_dev->irq_tail) { handled = 1; tasklet_schedule(&he_dev->tasklet); he_writel(he_dev, INT_CLEAR_A, INT_FIFO); /* clear interrupt */ (void) he_readl(he_dev, INT_FIFO); /* flush posted writes */ } spin_unlock_irqrestore(&he_dev->global_lock, flags); return IRQ_RETVAL(handled); } static __inline__ void __enqueue_tpd(struct he_dev *he_dev, struct he_tpd *tpd, unsigned cid) { struct he_tpdrq *new_tail; HPRINTK("tpdrq %p cid 0x%x -> tpdrq_tail %p\n", tpd, cid, he_dev->tpdrq_tail); /* new_tail = he_dev->tpdrq_tail; */ new_tail = (struct he_tpdrq *) ((unsigned long) he_dev->tpdrq_base | TPDRQ_MASK(he_dev->tpdrq_tail+1)); /* * check to see if we are about to set the tail == head * if true, update the head pointer from the adapter * to see if this is really the case (reading the queue * head for every enqueue would be unnecessarily slow) */ if (new_tail == he_dev->tpdrq_head) { he_dev->tpdrq_head = (struct he_tpdrq *) (((unsigned long)he_dev->tpdrq_base) | TPDRQ_MASK(he_readl(he_dev, TPDRQ_B_H))); if (new_tail == he_dev->tpdrq_head) { int slot; hprintk("tpdrq full (cid 0x%x)\n", cid); /* * FIXME * push tpd onto a transmit backlog queue * after service_tbrq, service the backlog * for now, we just drop the pdu */ for (slot = 0; slot < TPD_MAXIOV; ++slot) { if (tpd->iovec[slot].addr) pci_unmap_single(he_dev->pci_dev, tpd->iovec[slot].addr, tpd->iovec[slot].len & TPD_LEN_MASK, PCI_DMA_TODEVICE); } if (tpd->skb) { if (tpd->vcc->pop) tpd->vcc->pop(tpd->vcc, tpd->skb); else dev_kfree_skb_any(tpd->skb); atomic_inc(&tpd->vcc->stats->tx_err); } pci_pool_free(he_dev->tpd_pool, tpd, TPD_ADDR(tpd->status)); return; } } /* 2.1.5 transmit packet descriptor ready queue */ list_add_tail(&tpd->entry, &he_dev->outstanding_tpds); he_dev->tpdrq_tail->tpd = TPD_ADDR(tpd->status); he_dev->tpdrq_tail->cid = cid; wmb(); he_dev->tpdrq_tail = new_tail; he_writel(he_dev, TPDRQ_MASK(he_dev->tpdrq_tail), TPDRQ_T); (void) he_readl(he_dev, TPDRQ_T); /* flush posted writes */ } static int he_open(struct atm_vcc *vcc) { unsigned long flags; struct he_dev *he_dev = HE_DEV(vcc->dev); struct he_vcc *he_vcc; int err = 0; unsigned cid, rsr0, rsr1, rsr4, tsr0, tsr0_aal, tsr4, period, reg, clock; short vpi = vcc->vpi; int vci = vcc->vci; if (vci == ATM_VCI_UNSPEC || vpi == ATM_VPI_UNSPEC) return 0; HPRINTK("open vcc %p %d.%d\n", vcc, vpi, vci); set_bit(ATM_VF_ADDR, &vcc->flags); cid = he_mkcid(he_dev, vpi, vci); he_vcc = kmalloc(sizeof(struct he_vcc), GFP_ATOMIC); if (he_vcc == NULL) { hprintk("unable to allocate he_vcc during open\n"); return -ENOMEM; } INIT_LIST_HEAD(&he_vcc->buffers); he_vcc->pdu_len = 0; he_vcc->rc_index = -1; init_waitqueue_head(&he_vcc->rx_waitq); init_waitqueue_head(&he_vcc->tx_waitq); vcc->dev_data = he_vcc; if (vcc->qos.txtp.traffic_class != ATM_NONE) { int pcr_goal; pcr_goal = atm_pcr_goal(&vcc->qos.txtp); if (pcr_goal == 0) pcr_goal = he_dev->atm_dev->link_rate; if (pcr_goal < 0) /* means round down, technically */ pcr_goal = -pcr_goal; HPRINTK("open tx cid 0x%x pcr_goal %d\n", cid, pcr_goal); switch (vcc->qos.aal) { case ATM_AAL5: tsr0_aal = TSR0_AAL5; tsr4 = TSR4_AAL5; break; case ATM_AAL0: tsr0_aal = TSR0_AAL0_SDU; tsr4 = TSR4_AAL0_SDU; break; default: err = -EINVAL; goto open_failed; } spin_lock_irqsave(&he_dev->global_lock, flags); tsr0 = he_readl_tsr0(he_dev, cid); spin_unlock_irqrestore(&he_dev->global_lock, flags); if (TSR0_CONN_STATE(tsr0) != 0) { hprintk("cid 0x%x not idle (tsr0 = 0x%x)\n", cid, tsr0); err = -EBUSY; goto open_failed; } switch (vcc->qos.txtp.traffic_class) { case ATM_UBR: /* 2.3.3.1 open connection ubr */ tsr0 = TSR0_UBR | TSR0_GROUP(0) | tsr0_aal | TSR0_USE_WMIN | TSR0_UPDATE_GER; break; case ATM_CBR: /* 2.3.3.2 open connection cbr */ /* 8.2.3 cbr scheduler wrap problem -- limit to 90% total link rate */ if ((he_dev->total_bw + pcr_goal) > (he_dev->atm_dev->link_rate * 9 / 10)) { err = -EBUSY; goto open_failed; } spin_lock_irqsave(&he_dev->global_lock, flags); /* also protects he_dev->cs_stper[] */ /* find an unused cs_stper register */ for (reg = 0; reg < HE_NUM_CS_STPER; ++reg) if (he_dev->cs_stper[reg].inuse == 0 || he_dev->cs_stper[reg].pcr == pcr_goal) break; if (reg == HE_NUM_CS_STPER) { err = -EBUSY; spin_unlock_irqrestore(&he_dev->global_lock, flags); goto open_failed; } he_dev->total_bw += pcr_goal; he_vcc->rc_index = reg; ++he_dev->cs_stper[reg].inuse; he_dev->cs_stper[reg].pcr = pcr_goal; clock = he_is622(he_dev) ? 66667000 : 50000000; period = clock / pcr_goal; HPRINTK("rc_index = %d period = %d\n", reg, period); he_writel_mbox(he_dev, rate_to_atmf(period/2), CS_STPER0 + reg); spin_unlock_irqrestore(&he_dev->global_lock, flags); tsr0 = TSR0_CBR | TSR0_GROUP(0) | tsr0_aal | TSR0_RC_INDEX(reg); break; default: err = -EINVAL; goto open_failed; } spin_lock_irqsave(&he_dev->global_lock, flags); he_writel_tsr0(he_dev, tsr0, cid); he_writel_tsr4(he_dev, tsr4 | 1, cid); he_writel_tsr1(he_dev, TSR1_MCR(rate_to_atmf(0)) | TSR1_PCR(rate_to_atmf(pcr_goal)), cid); he_writel_tsr2(he_dev, TSR2_ACR(rate_to_atmf(pcr_goal)), cid); he_writel_tsr9(he_dev, TSR9_OPEN_CONN, cid); he_writel_tsr3(he_dev, 0x0, cid); he_writel_tsr5(he_dev, 0x0, cid); he_writel_tsr6(he_dev, 0x0, cid); he_writel_tsr7(he_dev, 0x0, cid); he_writel_tsr8(he_dev, 0x0, cid); he_writel_tsr10(he_dev, 0x0, cid); he_writel_tsr11(he_dev, 0x0, cid); he_writel_tsr12(he_dev, 0x0, cid); he_writel_tsr13(he_dev, 0x0, cid); he_writel_tsr14(he_dev, 0x0, cid); (void) he_readl_tsr0(he_dev, cid); /* flush posted writes */ spin_unlock_irqrestore(&he_dev->global_lock, flags); } if (vcc->qos.rxtp.traffic_class != ATM_NONE) { unsigned aal; HPRINTK("open rx cid 0x%x (rx_waitq %p)\n", cid, &HE_VCC(vcc)->rx_waitq); switch (vcc->qos.aal) { case ATM_AAL5: aal = RSR0_AAL5; break; case ATM_AAL0: aal = RSR0_RAWCELL; break; default: err = -EINVAL; goto open_failed; } spin_lock_irqsave(&he_dev->global_lock, flags); rsr0 = he_readl_rsr0(he_dev, cid); if (rsr0 & RSR0_OPEN_CONN) { spin_unlock_irqrestore(&he_dev->global_lock, flags); hprintk("cid 0x%x not idle (rsr0 = 0x%x)\n", cid, rsr0); err = -EBUSY; goto open_failed; } rsr1 = RSR1_GROUP(0) | RSR1_RBPL_ONLY; rsr4 = RSR4_GROUP(0) | RSR4_RBPL_ONLY; rsr0 = vcc->qos.rxtp.traffic_class == ATM_UBR ? (RSR0_EPD_ENABLE|RSR0_PPD_ENABLE) : 0; #ifdef USE_CHECKSUM_HW if (vpi == 0 && vci >= ATM_NOT_RSV_VCI) rsr0 |= RSR0_TCP_CKSUM; #endif he_writel_rsr4(he_dev, rsr4, cid); he_writel_rsr1(he_dev, rsr1, cid); /* 5.1.11 last parameter initialized should be the open/closed indication in rsr0 */ he_writel_rsr0(he_dev, rsr0 | RSR0_START_PDU | RSR0_OPEN_CONN | aal, cid); (void) he_readl_rsr0(he_dev, cid); /* flush posted writes */ spin_unlock_irqrestore(&he_dev->global_lock, flags); } open_failed: if (err) { kfree(he_vcc); clear_bit(ATM_VF_ADDR, &vcc->flags); } else set_bit(ATM_VF_READY, &vcc->flags); return err; } static void he_close(struct atm_vcc *vcc) { unsigned long flags; DECLARE_WAITQUEUE(wait, current); struct he_dev *he_dev = HE_DEV(vcc->dev); struct he_tpd *tpd; unsigned cid; struct he_vcc *he_vcc = HE_VCC(vcc); #define MAX_RETRY 30 int retry = 0, sleep = 1, tx_inuse; HPRINTK("close vcc %p %d.%d\n", vcc, vcc->vpi, vcc->vci); clear_bit(ATM_VF_READY, &vcc->flags); cid = he_mkcid(he_dev, vcc->vpi, vcc->vci); if (vcc->qos.rxtp.traffic_class != ATM_NONE) { int timeout; HPRINTK("close rx cid 0x%x\n", cid); /* 2.7.2.2 close receive operation */ /* wait for previous close (if any) to finish */ spin_lock_irqsave(&he_dev->global_lock, flags); while (he_readl(he_dev, RCC_STAT) & RCC_BUSY) { HPRINTK("close cid 0x%x RCC_BUSY\n", cid); udelay(250); } set_current_state(TASK_UNINTERRUPTIBLE); add_wait_queue(&he_vcc->rx_waitq, &wait); he_writel_rsr0(he_dev, RSR0_CLOSE_CONN, cid); (void) he_readl_rsr0(he_dev, cid); /* flush posted writes */ he_writel_mbox(he_dev, cid, RXCON_CLOSE); spin_unlock_irqrestore(&he_dev->global_lock, flags); timeout = schedule_timeout(30*HZ); remove_wait_queue(&he_vcc->rx_waitq, &wait); set_current_state(TASK_RUNNING); if (timeout == 0) hprintk("close rx timeout cid 0x%x\n", cid); HPRINTK("close rx cid 0x%x complete\n", cid); } if (vcc->qos.txtp.traffic_class != ATM_NONE) { volatile unsigned tsr4, tsr0; int timeout; HPRINTK("close tx cid 0x%x\n", cid); /* 2.1.2 * * ... the host must first stop queueing packets to the TPDRQ * on the connection to be closed, then wait for all outstanding * packets to be transmitted and their buffers returned to the * TBRQ. When the last packet on the connection arrives in the * TBRQ, the host issues the close command to the adapter. */ while (((tx_inuse = atomic_read(&sk_atm(vcc)->sk_wmem_alloc)) > 1) && (retry < MAX_RETRY)) { msleep(sleep); if (sleep < 250) sleep = sleep * 2; ++retry; } if (tx_inuse > 1) hprintk("close tx cid 0x%x tx_inuse = %d\n", cid, tx_inuse); /* 2.3.1.1 generic close operations with flush */ spin_lock_irqsave(&he_dev->global_lock, flags); he_writel_tsr4_upper(he_dev, TSR4_FLUSH_CONN, cid); /* also clears TSR4_SESSION_ENDED */ switch (vcc->qos.txtp.traffic_class) { case ATM_UBR: he_writel_tsr1(he_dev, TSR1_MCR(rate_to_atmf(200000)) | TSR1_PCR(0), cid); break; case ATM_CBR: he_writel_tsr14_upper(he_dev, TSR14_DELETE, cid); break; } (void) he_readl_tsr4(he_dev, cid); /* flush posted writes */ tpd = __alloc_tpd(he_dev); if (tpd == NULL) { hprintk("close tx he_alloc_tpd failed cid 0x%x\n", cid); goto close_tx_incomplete; } tpd->status |= TPD_EOS | TPD_INT; tpd->skb = NULL; tpd->vcc = vcc; wmb(); set_current_state(TASK_UNINTERRUPTIBLE); add_wait_queue(&he_vcc->tx_waitq, &wait); __enqueue_tpd(he_dev, tpd, cid); spin_unlock_irqrestore(&he_dev->global_lock, flags); timeout = schedule_timeout(30*HZ); remove_wait_queue(&he_vcc->tx_waitq, &wait); set_current_state(TASK_RUNNING); spin_lock_irqsave(&he_dev->global_lock, flags); if (timeout == 0) { hprintk("close tx timeout cid 0x%x\n", cid); goto close_tx_incomplete; } while (!((tsr4 = he_readl_tsr4(he_dev, cid)) & TSR4_SESSION_ENDED)) { HPRINTK("close tx cid 0x%x !TSR4_SESSION_ENDED (tsr4 = 0x%x)\n", cid, tsr4); udelay(250); } while (TSR0_CONN_STATE(tsr0 = he_readl_tsr0(he_dev, cid)) != 0) { HPRINTK("close tx cid 0x%x TSR0_CONN_STATE != 0 (tsr0 = 0x%x)\n", cid, tsr0); udelay(250); } close_tx_incomplete: if (vcc->qos.txtp.traffic_class == ATM_CBR) { int reg = he_vcc->rc_index; HPRINTK("cs_stper reg = %d\n", reg); if (he_dev->cs_stper[reg].inuse == 0) hprintk("cs_stper[%d].inuse = 0!\n", reg); else --he_dev->cs_stper[reg].inuse; he_dev->total_bw -= he_dev->cs_stper[reg].pcr; } spin_unlock_irqrestore(&he_dev->global_lock, flags); HPRINTK("close tx cid 0x%x complete\n", cid); } kfree(he_vcc); clear_bit(ATM_VF_ADDR, &vcc->flags); } static int he_send(struct atm_vcc *vcc, struct sk_buff *skb) { unsigned long flags; struct he_dev *he_dev = HE_DEV(vcc->dev); unsigned cid = he_mkcid(he_dev, vcc->vpi, vcc->vci); struct he_tpd *tpd; #ifdef USE_SCATTERGATHER int i, slot = 0; #endif #define HE_TPD_BUFSIZE 0xffff HPRINTK("send %d.%d\n", vcc->vpi, vcc->vci); if ((skb->len > HE_TPD_BUFSIZE) || ((vcc->qos.aal == ATM_AAL0) && (skb->len != ATM_AAL0_SDU))) { hprintk("buffer too large (or small) -- %d bytes\n", skb->len ); if (vcc->pop) vcc->pop(vcc, skb); else dev_kfree_skb_any(skb); atomic_inc(&vcc->stats->tx_err); return -EINVAL; } #ifndef USE_SCATTERGATHER if (skb_shinfo(skb)->nr_frags) { hprintk("no scatter/gather support\n"); if (vcc->pop) vcc->pop(vcc, skb); else dev_kfree_skb_any(skb); atomic_inc(&vcc->stats->tx_err); return -EINVAL; } #endif spin_lock_irqsave(&he_dev->global_lock, flags); tpd = __alloc_tpd(he_dev); if (tpd == NULL) { if (vcc->pop) vcc->pop(vcc, skb); else dev_kfree_skb_any(skb); atomic_inc(&vcc->stats->tx_err); spin_unlock_irqrestore(&he_dev->global_lock, flags); return -ENOMEM; } if (vcc->qos.aal == ATM_AAL5) tpd->status |= TPD_CELLTYPE(TPD_USERCELL); else { char *pti_clp = (void *) (skb->data + 3); int clp, pti; pti = (*pti_clp & ATM_HDR_PTI_MASK) >> ATM_HDR_PTI_SHIFT; clp = (*pti_clp & ATM_HDR_CLP); tpd->status |= TPD_CELLTYPE(pti); if (clp) tpd->status |= TPD_CLP; skb_pull(skb, ATM_AAL0_SDU - ATM_CELL_PAYLOAD); } #ifdef USE_SCATTERGATHER tpd->iovec[slot].addr = pci_map_single(he_dev->pci_dev, skb->data, skb_headlen(skb), PCI_DMA_TODEVICE); tpd->iovec[slot].len = skb_headlen(skb); ++slot; for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { skb_frag_t *frag = &skb_shinfo(skb)->frags[i]; if (slot == TPD_MAXIOV) { /* queue tpd; start new tpd */ tpd->vcc = vcc; tpd->skb = NULL; /* not the last fragment so dont ->push() yet */ wmb(); __enqueue_tpd(he_dev, tpd, cid); tpd = __alloc_tpd(he_dev); if (tpd == NULL) { if (vcc->pop) vcc->pop(vcc, skb); else dev_kfree_skb_any(skb); atomic_inc(&vcc->stats->tx_err); spin_unlock_irqrestore(&he_dev->global_lock, flags); return -ENOMEM; } tpd->status |= TPD_USERCELL; slot = 0; } tpd->iovec[slot].addr = pci_map_single(he_dev->pci_dev, (void *) page_address(frag->page) + frag->page_offset, frag->size, PCI_DMA_TODEVICE); tpd->iovec[slot].len = frag->size; ++slot; } tpd->iovec[slot - 1].len |= TPD_LST; #else tpd->address0 = pci_map_single(he_dev->pci_dev, skb->data, skb->len, PCI_DMA_TODEVICE); tpd->length0 = skb->len | TPD_LST; #endif tpd->status |= TPD_INT; tpd->vcc = vcc; tpd->skb = skb; wmb(); ATM_SKB(skb)->vcc = vcc; __enqueue_tpd(he_dev, tpd, cid); spin_unlock_irqrestore(&he_dev->global_lock, flags); atomic_inc(&vcc->stats->tx); return 0; } static int he_ioctl(struct atm_dev *atm_dev, unsigned int cmd, void __user *arg) { unsigned long flags; struct he_dev *he_dev = HE_DEV(atm_dev); struct he_ioctl_reg reg; int err = 0; switch (cmd) { case HE_GET_REG: if (!capable(CAP_NET_ADMIN)) return -EPERM; if (copy_from_user(&reg, arg, sizeof(struct he_ioctl_reg))) return -EFAULT; spin_lock_irqsave(&he_dev->global_lock, flags); switch (reg.type) { case HE_REGTYPE_PCI: if (reg.addr >= HE_REGMAP_SIZE) { err = -EINVAL; break; } reg.val = he_readl(he_dev, reg.addr); break; case HE_REGTYPE_RCM: reg.val = he_readl_rcm(he_dev, reg.addr); break; case HE_REGTYPE_TCM: reg.val = he_readl_tcm(he_dev, reg.addr); break; case HE_REGTYPE_MBOX: reg.val = he_readl_mbox(he_dev, reg.addr); break; default: err = -EINVAL; break; } spin_unlock_irqrestore(&he_dev->global_lock, flags); if (err == 0) if (copy_to_user(arg, &reg, sizeof(struct he_ioctl_reg))) return -EFAULT; break; default: #ifdef CONFIG_ATM_HE_USE_SUNI if (atm_dev->phy && atm_dev->phy->ioctl) err = atm_dev->phy->ioctl(atm_dev, cmd, arg); #else /* CONFIG_ATM_HE_USE_SUNI */ err = -EINVAL; #endif /* CONFIG_ATM_HE_USE_SUNI */ break; } return err; } static void he_phy_put(struct atm_dev *atm_dev, unsigned char val, unsigned long addr) { unsigned long flags; struct he_dev *he_dev = HE_DEV(atm_dev); HPRINTK("phy_put(val 0x%x, addr 0x%lx)\n", val, addr); spin_lock_irqsave(&he_dev->global_lock, flags); he_writel(he_dev, val, FRAMER + (addr*4)); (void) he_readl(he_dev, FRAMER + (addr*4)); /* flush posted writes */ spin_unlock_irqrestore(&he_dev->global_lock, flags); } static unsigned char he_phy_get(struct atm_dev *atm_dev, unsigned long addr) { unsigned long flags; struct he_dev *he_dev = HE_DEV(atm_dev); unsigned reg; spin_lock_irqsave(&he_dev->global_lock, flags); reg = he_readl(he_dev, FRAMER + (addr*4)); spin_unlock_irqrestore(&he_dev->global_lock, flags); HPRINTK("phy_get(addr 0x%lx) =0x%x\n", addr, reg); return reg; } static int he_proc_read(struct atm_dev *dev, loff_t *pos, char *page) { unsigned long flags; struct he_dev *he_dev = HE_DEV(dev); int left, i; #ifdef notdef struct he_rbrq *rbrq_tail; struct he_tpdrq *tpdrq_head; int rbpl_head, rbpl_tail; #endif static long mcc = 0, oec = 0, dcc = 0, cec = 0; left = *pos; if (!left--) return sprintf(page, "ATM he driver\n"); if (!left--) return sprintf(page, "%s%s\n\n", he_dev->prod_id, he_dev->media & 0x40 ? "SM" : "MM"); if (!left--) return sprintf(page, "Mismatched Cells VPI/VCI Not Open Dropped Cells RCM Dropped Cells\n"); spin_lock_irqsave(&he_dev->global_lock, flags); mcc += he_readl(he_dev, MCC); oec += he_readl(he_dev, OEC); dcc += he_readl(he_dev, DCC); cec += he_readl(he_dev, CEC); spin_unlock_irqrestore(&he_dev->global_lock, flags); if (!left--) return sprintf(page, "%16ld %16ld %13ld %17ld\n\n", mcc, oec, dcc, cec); if (!left--) return sprintf(page, "irq_size = %d inuse = ? peak = %d\n", CONFIG_IRQ_SIZE, he_dev->irq_peak); if (!left--) return sprintf(page, "tpdrq_size = %d inuse = ?\n", CONFIG_TPDRQ_SIZE); if (!left--) return sprintf(page, "rbrq_size = %d inuse = ? peak = %d\n", CONFIG_RBRQ_SIZE, he_dev->rbrq_peak); if (!left--) return sprintf(page, "tbrq_size = %d peak = %d\n", CONFIG_TBRQ_SIZE, he_dev->tbrq_peak); #ifdef notdef rbpl_head = RBPL_MASK(he_readl(he_dev, G0_RBPL_S)); rbpl_tail = RBPL_MASK(he_readl(he_dev, G0_RBPL_T)); inuse = rbpl_head - rbpl_tail; if (inuse < 0) inuse += CONFIG_RBPL_SIZE * sizeof(struct he_rbp); inuse /= sizeof(struct he_rbp); if (!left--) return sprintf(page, "rbpl_size = %d inuse = %d\n\n", CONFIG_RBPL_SIZE, inuse); #endif if (!left--) return sprintf(page, "rate controller periods (cbr)\n pcr #vc\n"); for (i = 0; i < HE_NUM_CS_STPER; ++i) if (!left--) return sprintf(page, "cs_stper%-2d %8ld %3d\n", i, he_dev->cs_stper[i].pcr, he_dev->cs_stper[i].inuse); if (!left--) return sprintf(page, "total bw (cbr): %d (limit %d)\n", he_dev->total_bw, he_dev->atm_dev->link_rate * 10 / 9); return 0; } /* eeprom routines -- see 4.7 */ static u8 read_prom_byte(struct he_dev *he_dev, int addr) { u32 val = 0, tmp_read = 0; int i, j = 0; u8 byte_read = 0; val = readl(he_dev->membase + HOST_CNTL); val &= 0xFFFFE0FF; /* Turn on write enable */ val |= 0x800; he_writel(he_dev, val, HOST_CNTL); /* Send READ instruction */ for (i = 0; i < ARRAY_SIZE(readtab); i++) { he_writel(he_dev, val | readtab[i], HOST_CNTL); udelay(EEPROM_DELAY); } /* Next, we need to send the byte address to read from */ for (i = 7; i >= 0; i--) { he_writel(he_dev, val | clocktab[j++] | (((addr >> i) & 1) << 9), HOST_CNTL); udelay(EEPROM_DELAY); he_writel(he_dev, val | clocktab[j++] | (((addr >> i) & 1) << 9), HOST_CNTL); udelay(EEPROM_DELAY); } j = 0; val &= 0xFFFFF7FF; /* Turn off write enable */ he_writel(he_dev, val, HOST_CNTL); /* Now, we can read data from the EEPROM by clocking it in */ for (i = 7; i >= 0; i--) { he_writel(he_dev, val | clocktab[j++], HOST_CNTL); udelay(EEPROM_DELAY); tmp_read = he_readl(he_dev, HOST_CNTL); byte_read |= (unsigned char) ((tmp_read & ID_DOUT) >> ID_DOFFSET << i); he_writel(he_dev, val | clocktab[j++], HOST_CNTL); udelay(EEPROM_DELAY); } he_writel(he_dev, val | ID_CS, HOST_CNTL); udelay(EEPROM_DELAY); return byte_read; } MODULE_LICENSE("GPL"); MODULE_AUTHOR("chas williams <chas@cmf.nrl.navy.mil>"); MODULE_DESCRIPTION("ForeRunnerHE ATM Adapter driver"); module_param(disable64, bool, 0); MODULE_PARM_DESC(disable64, "disable 64-bit pci bus transfers"); module_param(nvpibits, short, 0); MODULE_PARM_DESC(nvpibits, "numbers of bits for vpi (default 0)"); module_param(nvcibits, short, 0); MODULE_PARM_DESC(nvcibits, "numbers of bits for vci (default 12)"); module_param(rx_skb_reserve, short, 0); MODULE_PARM_DESC(rx_skb_reserve, "padding for receive skb (default 16)"); module_param(irq_coalesce, bool, 0); MODULE_PARM_DESC(irq_coalesce, "use interrupt coalescing (default 1)"); module_param(sdh, bool, 0); MODULE_PARM_DESC(sdh, "use SDH framing (default 0)"); static struct pci_device_id he_pci_tbl[] = { { PCI_VDEVICE(FORE, PCI_DEVICE_ID_FORE_HE), 0 }, { 0, } }; MODULE_DEVICE_TABLE(pci, he_pci_tbl); static struct pci_driver he_driver = { .name = "he", .probe = he_init_one, .remove = __devexit_p(he_remove_one), .id_table = he_pci_tbl, }; static int __init he_init(void) { return pci_register_driver(&he_driver); } static void __exit he_cleanup(void) { pci_unregister_driver(&he_driver); } module_init(he_init); module_exit(he_cleanup);
gpl-2.0
TeamBliss-Devices/android_kernel_asus_flo
drivers/cpufreq/e_powersaver.c
5069
12700
/* * Based on documentation provided by Dave Jones. Thanks! * * Licensed under the terms of the GNU GPL License version 2. * * BIG FAT DISCLAIMER: Work in progress code. Possibly *dangerous* */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/init.h> #include <linux/cpufreq.h> #include <linux/ioport.h> #include <linux/slab.h> #include <linux/timex.h> #include <linux/io.h> #include <linux/delay.h> #include <asm/cpu_device_id.h> #include <asm/msr.h> #include <asm/tsc.h> #if defined CONFIG_ACPI_PROCESSOR || defined CONFIG_ACPI_PROCESSOR_MODULE #include <linux/acpi.h> #include <acpi/processor.h> #endif #define EPS_BRAND_C7M 0 #define EPS_BRAND_C7 1 #define EPS_BRAND_EDEN 2 #define EPS_BRAND_C3 3 #define EPS_BRAND_C7D 4 struct eps_cpu_data { u32 fsb; #if defined CONFIG_ACPI_PROCESSOR || defined CONFIG_ACPI_PROCESSOR_MODULE u32 bios_limit; #endif struct cpufreq_frequency_table freq_table[]; }; static struct eps_cpu_data *eps_cpu[NR_CPUS]; /* Module parameters */ static int freq_failsafe_off; static int voltage_failsafe_off; static int set_max_voltage; #if defined CONFIG_ACPI_PROCESSOR || defined CONFIG_ACPI_PROCESSOR_MODULE static int ignore_acpi_limit; static struct acpi_processor_performance *eps_acpi_cpu_perf; /* Minimum necessary to get acpi_processor_get_bios_limit() working */ static int eps_acpi_init(void) { eps_acpi_cpu_perf = kzalloc(sizeof(struct acpi_processor_performance), GFP_KERNEL); if (!eps_acpi_cpu_perf) return -ENOMEM; if (!zalloc_cpumask_var(&eps_acpi_cpu_perf->shared_cpu_map, GFP_KERNEL)) { kfree(eps_acpi_cpu_perf); eps_acpi_cpu_perf = NULL; return -ENOMEM; } if (acpi_processor_register_performance(eps_acpi_cpu_perf, 0)) { free_cpumask_var(eps_acpi_cpu_perf->shared_cpu_map); kfree(eps_acpi_cpu_perf); eps_acpi_cpu_perf = NULL; return -EIO; } return 0; } static int eps_acpi_exit(struct cpufreq_policy *policy) { if (eps_acpi_cpu_perf) { acpi_processor_unregister_performance(eps_acpi_cpu_perf, 0); free_cpumask_var(eps_acpi_cpu_perf->shared_cpu_map); kfree(eps_acpi_cpu_perf); eps_acpi_cpu_perf = NULL; } return 0; } #endif static unsigned int eps_get(unsigned int cpu) { struct eps_cpu_data *centaur; u32 lo, hi; if (cpu) return 0; centaur = eps_cpu[cpu]; if (centaur == NULL) return 0; /* Return current frequency */ rdmsr(MSR_IA32_PERF_STATUS, lo, hi); return centaur->fsb * ((lo >> 8) & 0xff); } static int eps_set_state(struct eps_cpu_data *centaur, unsigned int cpu, u32 dest_state) { struct cpufreq_freqs freqs; u32 lo, hi; int err = 0; int i; freqs.old = eps_get(cpu); freqs.new = centaur->fsb * ((dest_state >> 8) & 0xff); freqs.cpu = cpu; cpufreq_notify_transition(&freqs, CPUFREQ_PRECHANGE); /* Wait while CPU is busy */ rdmsr(MSR_IA32_PERF_STATUS, lo, hi); i = 0; while (lo & ((1 << 16) | (1 << 17))) { udelay(16); rdmsr(MSR_IA32_PERF_STATUS, lo, hi); i++; if (unlikely(i > 64)) { err = -ENODEV; goto postchange; } } /* Set new multiplier and voltage */ wrmsr(MSR_IA32_PERF_CTL, dest_state & 0xffff, 0); /* Wait until transition end */ i = 0; do { udelay(16); rdmsr(MSR_IA32_PERF_STATUS, lo, hi); i++; if (unlikely(i > 64)) { err = -ENODEV; goto postchange; } } while (lo & ((1 << 16) | (1 << 17))); /* Return current frequency */ postchange: rdmsr(MSR_IA32_PERF_STATUS, lo, hi); freqs.new = centaur->fsb * ((lo >> 8) & 0xff); #ifdef DEBUG { u8 current_multiplier, current_voltage; /* Print voltage and multiplier */ rdmsr(MSR_IA32_PERF_STATUS, lo, hi); current_voltage = lo & 0xff; printk(KERN_INFO "eps: Current voltage = %dmV\n", current_voltage * 16 + 700); current_multiplier = (lo >> 8) & 0xff; printk(KERN_INFO "eps: Current multiplier = %d\n", current_multiplier); } #endif cpufreq_notify_transition(&freqs, CPUFREQ_POSTCHANGE); return err; } static int eps_target(struct cpufreq_policy *policy, unsigned int target_freq, unsigned int relation) { struct eps_cpu_data *centaur; unsigned int newstate = 0; unsigned int cpu = policy->cpu; unsigned int dest_state; int ret; if (unlikely(eps_cpu[cpu] == NULL)) return -ENODEV; centaur = eps_cpu[cpu]; if (unlikely(cpufreq_frequency_table_target(policy, &eps_cpu[cpu]->freq_table[0], target_freq, relation, &newstate))) { return -EINVAL; } /* Make frequency transition */ dest_state = centaur->freq_table[newstate].index & 0xffff; ret = eps_set_state(centaur, cpu, dest_state); if (ret) printk(KERN_ERR "eps: Timeout!\n"); return ret; } static int eps_verify(struct cpufreq_policy *policy) { return cpufreq_frequency_table_verify(policy, &eps_cpu[policy->cpu]->freq_table[0]); } static int eps_cpu_init(struct cpufreq_policy *policy) { unsigned int i; u32 lo, hi; u64 val; u8 current_multiplier, current_voltage; u8 max_multiplier, max_voltage; u8 min_multiplier, min_voltage; u8 brand = 0; u32 fsb; struct eps_cpu_data *centaur; struct cpuinfo_x86 *c = &cpu_data(0); struct cpufreq_frequency_table *f_table; int k, step, voltage; int ret; int states; #if defined CONFIG_ACPI_PROCESSOR || defined CONFIG_ACPI_PROCESSOR_MODULE unsigned int limit; #endif if (policy->cpu != 0) return -ENODEV; /* Check brand */ printk(KERN_INFO "eps: Detected VIA "); switch (c->x86_model) { case 10: rdmsr(0x1153, lo, hi); brand = (((lo >> 2) ^ lo) >> 18) & 3; printk(KERN_CONT "Model A "); break; case 13: rdmsr(0x1154, lo, hi); brand = (((lo >> 4) ^ (lo >> 2))) & 0x000000ff; printk(KERN_CONT "Model D "); break; } switch (brand) { case EPS_BRAND_C7M: printk(KERN_CONT "C7-M\n"); break; case EPS_BRAND_C7: printk(KERN_CONT "C7\n"); break; case EPS_BRAND_EDEN: printk(KERN_CONT "Eden\n"); break; case EPS_BRAND_C7D: printk(KERN_CONT "C7-D\n"); break; case EPS_BRAND_C3: printk(KERN_CONT "C3\n"); return -ENODEV; break; } /* Enable Enhanced PowerSaver */ rdmsrl(MSR_IA32_MISC_ENABLE, val); if (!(val & MSR_IA32_MISC_ENABLE_ENHANCED_SPEEDSTEP)) { val |= MSR_IA32_MISC_ENABLE_ENHANCED_SPEEDSTEP; wrmsrl(MSR_IA32_MISC_ENABLE, val); /* Can be locked at 0 */ rdmsrl(MSR_IA32_MISC_ENABLE, val); if (!(val & MSR_IA32_MISC_ENABLE_ENHANCED_SPEEDSTEP)) { printk(KERN_INFO "eps: Can't enable Enhanced PowerSaver\n"); return -ENODEV; } } /* Print voltage and multiplier */ rdmsr(MSR_IA32_PERF_STATUS, lo, hi); current_voltage = lo & 0xff; printk(KERN_INFO "eps: Current voltage = %dmV\n", current_voltage * 16 + 700); current_multiplier = (lo >> 8) & 0xff; printk(KERN_INFO "eps: Current multiplier = %d\n", current_multiplier); /* Print limits */ max_voltage = hi & 0xff; printk(KERN_INFO "eps: Highest voltage = %dmV\n", max_voltage * 16 + 700); max_multiplier = (hi >> 8) & 0xff; printk(KERN_INFO "eps: Highest multiplier = %d\n", max_multiplier); min_voltage = (hi >> 16) & 0xff; printk(KERN_INFO "eps: Lowest voltage = %dmV\n", min_voltage * 16 + 700); min_multiplier = (hi >> 24) & 0xff; printk(KERN_INFO "eps: Lowest multiplier = %d\n", min_multiplier); /* Sanity checks */ if (current_multiplier == 0 || max_multiplier == 0 || min_multiplier == 0) return -EINVAL; if (current_multiplier > max_multiplier || max_multiplier <= min_multiplier) return -EINVAL; if (current_voltage > 0x1f || max_voltage > 0x1f) return -EINVAL; if (max_voltage < min_voltage || current_voltage < min_voltage || current_voltage > max_voltage) return -EINVAL; /* Check for systems using underclocked CPU */ if (!freq_failsafe_off && max_multiplier != current_multiplier) { printk(KERN_INFO "eps: Your processor is running at different " "frequency then its maximum. Aborting.\n"); printk(KERN_INFO "eps: You can use freq_failsafe_off option " "to disable this check.\n"); return -EINVAL; } if (!voltage_failsafe_off && max_voltage != current_voltage) { printk(KERN_INFO "eps: Your processor is running at different " "voltage then its maximum. Aborting.\n"); printk(KERN_INFO "eps: You can use voltage_failsafe_off " "option to disable this check.\n"); return -EINVAL; } /* Calc FSB speed */ fsb = cpu_khz / current_multiplier; #if defined CONFIG_ACPI_PROCESSOR || defined CONFIG_ACPI_PROCESSOR_MODULE /* Check for ACPI processor speed limit */ if (!ignore_acpi_limit && !eps_acpi_init()) { if (!acpi_processor_get_bios_limit(policy->cpu, &limit)) { printk(KERN_INFO "eps: ACPI limit %u.%uGHz\n", limit/1000000, (limit%1000000)/10000); eps_acpi_exit(policy); /* Check if max_multiplier is in BIOS limits */ if (limit && max_multiplier * fsb > limit) { printk(KERN_INFO "eps: Aborting.\n"); return -EINVAL; } } } #endif /* Allow user to set lower maximum voltage then that reported * by processor */ if (brand == EPS_BRAND_C7M && set_max_voltage) { u32 v; /* Change mV to something hardware can use */ v = (set_max_voltage - 700) / 16; /* Check if voltage is within limits */ if (v >= min_voltage && v <= max_voltage) { printk(KERN_INFO "eps: Setting %dmV as maximum.\n", v * 16 + 700); max_voltage = v; } } /* Calc number of p-states supported */ if (brand == EPS_BRAND_C7M) states = max_multiplier - min_multiplier + 1; else states = 2; /* Allocate private data and frequency table for current cpu */ centaur = kzalloc(sizeof(struct eps_cpu_data) + (states + 1) * sizeof(struct cpufreq_frequency_table), GFP_KERNEL); if (!centaur) return -ENOMEM; eps_cpu[0] = centaur; /* Copy basic values */ centaur->fsb = fsb; #if defined CONFIG_ACPI_PROCESSOR || defined CONFIG_ACPI_PROCESSOR_MODULE centaur->bios_limit = limit; #endif /* Fill frequency and MSR value table */ f_table = &centaur->freq_table[0]; if (brand != EPS_BRAND_C7M) { f_table[0].frequency = fsb * min_multiplier; f_table[0].index = (min_multiplier << 8) | min_voltage; f_table[1].frequency = fsb * max_multiplier; f_table[1].index = (max_multiplier << 8) | max_voltage; f_table[2].frequency = CPUFREQ_TABLE_END; } else { k = 0; step = ((max_voltage - min_voltage) * 256) / (max_multiplier - min_multiplier); for (i = min_multiplier; i <= max_multiplier; i++) { voltage = (k * step) / 256 + min_voltage; f_table[k].frequency = fsb * i; f_table[k].index = (i << 8) | voltage; k++; } f_table[k].frequency = CPUFREQ_TABLE_END; } policy->cpuinfo.transition_latency = 140000; /* 844mV -> 700mV in ns */ policy->cur = fsb * current_multiplier; ret = cpufreq_frequency_table_cpuinfo(policy, &centaur->freq_table[0]); if (ret) { kfree(centaur); return ret; } cpufreq_frequency_table_get_attr(&centaur->freq_table[0], policy->cpu); return 0; } static int eps_cpu_exit(struct cpufreq_policy *policy) { unsigned int cpu = policy->cpu; /* Bye */ cpufreq_frequency_table_put_attr(policy->cpu); kfree(eps_cpu[cpu]); eps_cpu[cpu] = NULL; return 0; } static struct freq_attr *eps_attr[] = { &cpufreq_freq_attr_scaling_available_freqs, NULL, }; static struct cpufreq_driver eps_driver = { .verify = eps_verify, .target = eps_target, .init = eps_cpu_init, .exit = eps_cpu_exit, .get = eps_get, .name = "e_powersaver", .owner = THIS_MODULE, .attr = eps_attr, }; /* This driver will work only on Centaur C7 processors with * Enhanced SpeedStep/PowerSaver registers */ static const struct x86_cpu_id eps_cpu_id[] = { { X86_VENDOR_CENTAUR, 6, X86_MODEL_ANY, X86_FEATURE_EST }, {} }; MODULE_DEVICE_TABLE(x86cpu, eps_cpu_id); static int __init eps_init(void) { if (!x86_match_cpu(eps_cpu_id) || boot_cpu_data.x86_model < 10) return -ENODEV; if (cpufreq_register_driver(&eps_driver)) return -EINVAL; return 0; } static void __exit eps_exit(void) { cpufreq_unregister_driver(&eps_driver); } /* Allow user to overclock his machine or to change frequency to higher after * unloading module */ module_param(freq_failsafe_off, int, 0644); MODULE_PARM_DESC(freq_failsafe_off, "Disable current vs max frequency check"); module_param(voltage_failsafe_off, int, 0644); MODULE_PARM_DESC(voltage_failsafe_off, "Disable current vs max voltage check"); #if defined CONFIG_ACPI_PROCESSOR || defined CONFIG_ACPI_PROCESSOR_MODULE module_param(ignore_acpi_limit, int, 0644); MODULE_PARM_DESC(ignore_acpi_limit, "Don't check ACPI's processor speed limit"); #endif module_param(set_max_voltage, int, 0644); MODULE_PARM_DESC(set_max_voltage, "Set maximum CPU voltage (mV) C7-M only"); MODULE_AUTHOR("Rafal Bilski <rafalbilski@interia.pl>"); MODULE_DESCRIPTION("Enhanced PowerSaver driver for VIA C7 CPU's."); MODULE_LICENSE("GPL"); module_init(eps_init); module_exit(eps_exit);
gpl-2.0
bestgames1/android_kernel_samsung_kylepro
drivers/uio/uio_pci_generic.c
5069
3515
/* uio_pci_generic - generic UIO driver for PCI 2.3 devices * * Copyright (C) 2009 Red Hat, Inc. * Author: Michael S. Tsirkin <mst@redhat.com> * * This work is licensed under the terms of the GNU GPL, version 2. * * Since the driver does not declare any device ids, you must allocate * id and bind the device to the driver yourself. For example: * * # echo "8086 10f5" > /sys/bus/pci/drivers/uio_pci_generic/new_id * # echo -n 0000:00:19.0 > /sys/bus/pci/drivers/e1000e/unbind * # echo -n 0000:00:19.0 > /sys/bus/pci/drivers/uio_pci_generic/bind * # ls -l /sys/bus/pci/devices/0000:00:19.0/driver * .../0000:00:19.0/driver -> ../../../bus/pci/drivers/uio_pci_generic * * Driver won't bind to devices which do not support the Interrupt Disable Bit * in the command register. All devices compliant to PCI 2.3 (circa 2002) and * all compliant PCI Express devices should support this bit. */ #include <linux/device.h> #include <linux/module.h> #include <linux/pci.h> #include <linux/slab.h> #include <linux/uio_driver.h> #define DRIVER_VERSION "0.01.0" #define DRIVER_AUTHOR "Michael S. Tsirkin <mst@redhat.com>" #define DRIVER_DESC "Generic UIO driver for PCI 2.3 devices" struct uio_pci_generic_dev { struct uio_info info; struct pci_dev *pdev; }; static inline struct uio_pci_generic_dev * to_uio_pci_generic_dev(struct uio_info *info) { return container_of(info, struct uio_pci_generic_dev, info); } /* Interrupt handler. Read/modify/write the command register to disable * the interrupt. */ static irqreturn_t irqhandler(int irq, struct uio_info *info) { struct uio_pci_generic_dev *gdev = to_uio_pci_generic_dev(info); if (!pci_check_and_mask_intx(gdev->pdev)) return IRQ_NONE; /* UIO core will signal the user process. */ return IRQ_HANDLED; } static int __devinit probe(struct pci_dev *pdev, const struct pci_device_id *id) { struct uio_pci_generic_dev *gdev; int err; err = pci_enable_device(pdev); if (err) { dev_err(&pdev->dev, "%s: pci_enable_device failed: %d\n", __func__, err); return err; } if (!pdev->irq) { dev_warn(&pdev->dev, "No IRQ assigned to device: " "no support for interrupts?\n"); pci_disable_device(pdev); return -ENODEV; } if (!pci_intx_mask_supported(pdev)) { err = -ENODEV; goto err_verify; } gdev = kzalloc(sizeof(struct uio_pci_generic_dev), GFP_KERNEL); if (!gdev) { err = -ENOMEM; goto err_alloc; } gdev->info.name = "uio_pci_generic"; gdev->info.version = DRIVER_VERSION; gdev->info.irq = pdev->irq; gdev->info.irq_flags = IRQF_SHARED; gdev->info.handler = irqhandler; gdev->pdev = pdev; if (uio_register_device(&pdev->dev, &gdev->info)) goto err_register; pci_set_drvdata(pdev, gdev); return 0; err_register: kfree(gdev); err_alloc: err_verify: pci_disable_device(pdev); return err; } static void remove(struct pci_dev *pdev) { struct uio_pci_generic_dev *gdev = pci_get_drvdata(pdev); uio_unregister_device(&gdev->info); pci_disable_device(pdev); kfree(gdev); } static struct pci_driver driver = { .name = "uio_pci_generic", .id_table = NULL, /* only dynamic id's */ .probe = probe, .remove = remove, }; static int __init init(void) { pr_info(DRIVER_DESC " version: " DRIVER_VERSION "\n"); return pci_register_driver(&driver); } static void __exit cleanup(void) { pci_unregister_driver(&driver); } module_init(init); module_exit(cleanup); MODULE_VERSION(DRIVER_VERSION); MODULE_LICENSE("GPL v2"); MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION(DRIVER_DESC);
gpl-2.0
dark-falcon/android_kernel_motorola_msm8916
samples/uhid/uhid-example.c
7117
8303
/* * UHID Example * * Copyright (c) 2012 David Herrmann <dh.herrmann@googlemail.com> * * The code may be used by anyone for any purpose, * and can serve as a starting point for developing * applications using uhid. */ /* UHID Example * This example emulates a basic 3 buttons mouse with wheel over UHID. Run this * program as root and then use the following keys to control the mouse: * q: Quit the application * 1: Toggle left button (down, up, ...) * 2: Toggle right button * 3: Toggle middle button * a: Move mouse left * d: Move mouse right * w: Move mouse up * s: Move mouse down * r: Move wheel up * f: Move wheel down * * If uhid is not available as /dev/uhid, then you can pass a different path as * first argument. * If <linux/uhid.h> is not installed in /usr, then compile this with: * gcc -o ./uhid_test -Wall -I./include ./samples/uhid/uhid-example.c * And ignore the warning about kernel headers. However, it is recommended to * use the installed uhid.h if available. */ #include <errno.h> #include <fcntl.h> #include <poll.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <termios.h> #include <unistd.h> #include <linux/uhid.h> /* HID Report Desciptor * We emulate a basic 3 button mouse with wheel. This is the report-descriptor * as the kernel will parse it: * * INPUT[INPUT] * Field(0) * Physical(GenericDesktop.Pointer) * Application(GenericDesktop.Mouse) * Usage(3) * Button.0001 * Button.0002 * Button.0003 * Logical Minimum(0) * Logical Maximum(1) * Report Size(1) * Report Count(3) * Report Offset(0) * Flags( Variable Absolute ) * Field(1) * Physical(GenericDesktop.Pointer) * Application(GenericDesktop.Mouse) * Usage(3) * GenericDesktop.X * GenericDesktop.Y * GenericDesktop.Wheel * Logical Minimum(-128) * Logical Maximum(127) * Report Size(8) * Report Count(3) * Report Offset(8) * Flags( Variable Relative ) * * This is the mapping that we expect: * Button.0001 ---> Key.LeftBtn * Button.0002 ---> Key.RightBtn * Button.0003 ---> Key.MiddleBtn * GenericDesktop.X ---> Relative.X * GenericDesktop.Y ---> Relative.Y * GenericDesktop.Wheel ---> Relative.Wheel * * This information can be verified by reading /sys/kernel/debug/hid/<dev>/rdesc * This file should print the same information as showed above. */ static unsigned char rdesc[] = { 0x05, 0x01, 0x09, 0x02, 0xa1, 0x01, 0x09, 0x01, 0xa1, 0x00, 0x05, 0x09, 0x19, 0x01, 0x29, 0x03, 0x15, 0x00, 0x25, 0x01, 0x95, 0x03, 0x75, 0x01, 0x81, 0x02, 0x95, 0x01, 0x75, 0x05, 0x81, 0x01, 0x05, 0x01, 0x09, 0x30, 0x09, 0x31, 0x09, 0x38, 0x15, 0x80, 0x25, 0x7f, 0x75, 0x08, 0x95, 0x03, 0x81, 0x06, 0xc0, 0xc0, }; static int uhid_write(int fd, const struct uhid_event *ev) { ssize_t ret; ret = write(fd, ev, sizeof(*ev)); if (ret < 0) { fprintf(stderr, "Cannot write to uhid: %m\n"); return -errno; } else if (ret != sizeof(*ev)) { fprintf(stderr, "Wrong size written to uhid: %ld != %lu\n", ret, sizeof(ev)); return -EFAULT; } else { return 0; } } static int create(int fd) { struct uhid_event ev; memset(&ev, 0, sizeof(ev)); ev.type = UHID_CREATE; strcpy((char*)ev.u.create.name, "test-uhid-device"); ev.u.create.rd_data = rdesc; ev.u.create.rd_size = sizeof(rdesc); ev.u.create.bus = BUS_USB; ev.u.create.vendor = 0x15d9; ev.u.create.product = 0x0a37; ev.u.create.version = 0; ev.u.create.country = 0; return uhid_write(fd, &ev); } static void destroy(int fd) { struct uhid_event ev; memset(&ev, 0, sizeof(ev)); ev.type = UHID_DESTROY; uhid_write(fd, &ev); } static int event(int fd) { struct uhid_event ev; ssize_t ret; memset(&ev, 0, sizeof(ev)); ret = read(fd, &ev, sizeof(ev)); if (ret == 0) { fprintf(stderr, "Read HUP on uhid-cdev\n"); return -EFAULT; } else if (ret < 0) { fprintf(stderr, "Cannot read uhid-cdev: %m\n"); return -errno; } else if (ret != sizeof(ev)) { fprintf(stderr, "Invalid size read from uhid-dev: %ld != %lu\n", ret, sizeof(ev)); return -EFAULT; } switch (ev.type) { case UHID_START: fprintf(stderr, "UHID_START from uhid-dev\n"); break; case UHID_STOP: fprintf(stderr, "UHID_STOP from uhid-dev\n"); break; case UHID_OPEN: fprintf(stderr, "UHID_OPEN from uhid-dev\n"); break; case UHID_CLOSE: fprintf(stderr, "UHID_CLOSE from uhid-dev\n"); break; case UHID_OUTPUT: fprintf(stderr, "UHID_OUTPUT from uhid-dev\n"); break; case UHID_OUTPUT_EV: fprintf(stderr, "UHID_OUTPUT_EV from uhid-dev\n"); break; default: fprintf(stderr, "Invalid event from uhid-dev: %u\n", ev.type); } return 0; } static bool btn1_down; static bool btn2_down; static bool btn3_down; static signed char abs_hor; static signed char abs_ver; static signed char wheel; static int send_event(int fd) { struct uhid_event ev; memset(&ev, 0, sizeof(ev)); ev.type = UHID_INPUT; ev.u.input.size = 4; if (btn1_down) ev.u.input.data[0] |= 0x1; if (btn2_down) ev.u.input.data[0] |= 0x2; if (btn3_down) ev.u.input.data[0] |= 0x4; ev.u.input.data[1] = abs_hor; ev.u.input.data[2] = abs_ver; ev.u.input.data[3] = wheel; return uhid_write(fd, &ev); } static int keyboard(int fd) { char buf[128]; ssize_t ret, i; ret = read(STDIN_FILENO, buf, sizeof(buf)); if (ret == 0) { fprintf(stderr, "Read HUP on stdin\n"); return -EFAULT; } else if (ret < 0) { fprintf(stderr, "Cannot read stdin: %m\n"); return -errno; } for (i = 0; i < ret; ++i) { switch (buf[i]) { case '1': btn1_down = !btn1_down; ret = send_event(fd); if (ret) return ret; break; case '2': btn2_down = !btn2_down; ret = send_event(fd); if (ret) return ret; break; case '3': btn3_down = !btn3_down; ret = send_event(fd); if (ret) return ret; break; case 'a': abs_hor = -20; ret = send_event(fd); abs_hor = 0; if (ret) return ret; break; case 'd': abs_hor = 20; ret = send_event(fd); abs_hor = 0; if (ret) return ret; break; case 'w': abs_ver = -20; ret = send_event(fd); abs_ver = 0; if (ret) return ret; break; case 's': abs_ver = 20; ret = send_event(fd); abs_ver = 0; if (ret) return ret; break; case 'r': wheel = 1; ret = send_event(fd); wheel = 0; if (ret) return ret; break; case 'f': wheel = -1; ret = send_event(fd); wheel = 0; if (ret) return ret; break; case 'q': return -ECANCELED; default: fprintf(stderr, "Invalid input: %c\n", buf[i]); } } return 0; } int main(int argc, char **argv) { int fd; const char *path = "/dev/uhid"; struct pollfd pfds[2]; int ret; struct termios state; ret = tcgetattr(STDIN_FILENO, &state); if (ret) { fprintf(stderr, "Cannot get tty state\n"); } else { state.c_lflag &= ~ICANON; state.c_cc[VMIN] = 1; ret = tcsetattr(STDIN_FILENO, TCSANOW, &state); if (ret) fprintf(stderr, "Cannot set tty state\n"); } if (argc >= 2) { if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) { fprintf(stderr, "Usage: %s [%s]\n", argv[0], path); return EXIT_SUCCESS; } else { path = argv[1]; } } fprintf(stderr, "Open uhid-cdev %s\n", path); fd = open(path, O_RDWR | O_CLOEXEC); if (fd < 0) { fprintf(stderr, "Cannot open uhid-cdev %s: %m\n", path); return EXIT_FAILURE; } fprintf(stderr, "Create uhid device\n"); ret = create(fd); if (ret) { close(fd); return EXIT_FAILURE; } pfds[0].fd = STDIN_FILENO; pfds[0].events = POLLIN; pfds[1].fd = fd; pfds[1].events = POLLIN; fprintf(stderr, "Press 'q' to quit...\n"); while (1) { ret = poll(pfds, 2, -1); if (ret < 0) { fprintf(stderr, "Cannot poll for fds: %m\n"); break; } if (pfds[0].revents & POLLHUP) { fprintf(stderr, "Received HUP on stdin\n"); break; } if (pfds[1].revents & POLLHUP) { fprintf(stderr, "Received HUP on uhid-cdev\n"); break; } if (pfds[0].revents & POLLIN) { ret = keyboard(fd); if (ret) break; } if (pfds[1].revents & POLLIN) { ret = event(fd); if (ret) break; } } fprintf(stderr, "Destroy uhid device\n"); destroy(fd); return EXIT_SUCCESS; }
gpl-2.0
Ant-Droid/android_kernel_moto_shamu
samples/uhid/uhid-example.c
7117
8303
/* * UHID Example * * Copyright (c) 2012 David Herrmann <dh.herrmann@googlemail.com> * * The code may be used by anyone for any purpose, * and can serve as a starting point for developing * applications using uhid. */ /* UHID Example * This example emulates a basic 3 buttons mouse with wheel over UHID. Run this * program as root and then use the following keys to control the mouse: * q: Quit the application * 1: Toggle left button (down, up, ...) * 2: Toggle right button * 3: Toggle middle button * a: Move mouse left * d: Move mouse right * w: Move mouse up * s: Move mouse down * r: Move wheel up * f: Move wheel down * * If uhid is not available as /dev/uhid, then you can pass a different path as * first argument. * If <linux/uhid.h> is not installed in /usr, then compile this with: * gcc -o ./uhid_test -Wall -I./include ./samples/uhid/uhid-example.c * And ignore the warning about kernel headers. However, it is recommended to * use the installed uhid.h if available. */ #include <errno.h> #include <fcntl.h> #include <poll.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <termios.h> #include <unistd.h> #include <linux/uhid.h> /* HID Report Desciptor * We emulate a basic 3 button mouse with wheel. This is the report-descriptor * as the kernel will parse it: * * INPUT[INPUT] * Field(0) * Physical(GenericDesktop.Pointer) * Application(GenericDesktop.Mouse) * Usage(3) * Button.0001 * Button.0002 * Button.0003 * Logical Minimum(0) * Logical Maximum(1) * Report Size(1) * Report Count(3) * Report Offset(0) * Flags( Variable Absolute ) * Field(1) * Physical(GenericDesktop.Pointer) * Application(GenericDesktop.Mouse) * Usage(3) * GenericDesktop.X * GenericDesktop.Y * GenericDesktop.Wheel * Logical Minimum(-128) * Logical Maximum(127) * Report Size(8) * Report Count(3) * Report Offset(8) * Flags( Variable Relative ) * * This is the mapping that we expect: * Button.0001 ---> Key.LeftBtn * Button.0002 ---> Key.RightBtn * Button.0003 ---> Key.MiddleBtn * GenericDesktop.X ---> Relative.X * GenericDesktop.Y ---> Relative.Y * GenericDesktop.Wheel ---> Relative.Wheel * * This information can be verified by reading /sys/kernel/debug/hid/<dev>/rdesc * This file should print the same information as showed above. */ static unsigned char rdesc[] = { 0x05, 0x01, 0x09, 0x02, 0xa1, 0x01, 0x09, 0x01, 0xa1, 0x00, 0x05, 0x09, 0x19, 0x01, 0x29, 0x03, 0x15, 0x00, 0x25, 0x01, 0x95, 0x03, 0x75, 0x01, 0x81, 0x02, 0x95, 0x01, 0x75, 0x05, 0x81, 0x01, 0x05, 0x01, 0x09, 0x30, 0x09, 0x31, 0x09, 0x38, 0x15, 0x80, 0x25, 0x7f, 0x75, 0x08, 0x95, 0x03, 0x81, 0x06, 0xc0, 0xc0, }; static int uhid_write(int fd, const struct uhid_event *ev) { ssize_t ret; ret = write(fd, ev, sizeof(*ev)); if (ret < 0) { fprintf(stderr, "Cannot write to uhid: %m\n"); return -errno; } else if (ret != sizeof(*ev)) { fprintf(stderr, "Wrong size written to uhid: %ld != %lu\n", ret, sizeof(ev)); return -EFAULT; } else { return 0; } } static int create(int fd) { struct uhid_event ev; memset(&ev, 0, sizeof(ev)); ev.type = UHID_CREATE; strcpy((char*)ev.u.create.name, "test-uhid-device"); ev.u.create.rd_data = rdesc; ev.u.create.rd_size = sizeof(rdesc); ev.u.create.bus = BUS_USB; ev.u.create.vendor = 0x15d9; ev.u.create.product = 0x0a37; ev.u.create.version = 0; ev.u.create.country = 0; return uhid_write(fd, &ev); } static void destroy(int fd) { struct uhid_event ev; memset(&ev, 0, sizeof(ev)); ev.type = UHID_DESTROY; uhid_write(fd, &ev); } static int event(int fd) { struct uhid_event ev; ssize_t ret; memset(&ev, 0, sizeof(ev)); ret = read(fd, &ev, sizeof(ev)); if (ret == 0) { fprintf(stderr, "Read HUP on uhid-cdev\n"); return -EFAULT; } else if (ret < 0) { fprintf(stderr, "Cannot read uhid-cdev: %m\n"); return -errno; } else if (ret != sizeof(ev)) { fprintf(stderr, "Invalid size read from uhid-dev: %ld != %lu\n", ret, sizeof(ev)); return -EFAULT; } switch (ev.type) { case UHID_START: fprintf(stderr, "UHID_START from uhid-dev\n"); break; case UHID_STOP: fprintf(stderr, "UHID_STOP from uhid-dev\n"); break; case UHID_OPEN: fprintf(stderr, "UHID_OPEN from uhid-dev\n"); break; case UHID_CLOSE: fprintf(stderr, "UHID_CLOSE from uhid-dev\n"); break; case UHID_OUTPUT: fprintf(stderr, "UHID_OUTPUT from uhid-dev\n"); break; case UHID_OUTPUT_EV: fprintf(stderr, "UHID_OUTPUT_EV from uhid-dev\n"); break; default: fprintf(stderr, "Invalid event from uhid-dev: %u\n", ev.type); } return 0; } static bool btn1_down; static bool btn2_down; static bool btn3_down; static signed char abs_hor; static signed char abs_ver; static signed char wheel; static int send_event(int fd) { struct uhid_event ev; memset(&ev, 0, sizeof(ev)); ev.type = UHID_INPUT; ev.u.input.size = 4; if (btn1_down) ev.u.input.data[0] |= 0x1; if (btn2_down) ev.u.input.data[0] |= 0x2; if (btn3_down) ev.u.input.data[0] |= 0x4; ev.u.input.data[1] = abs_hor; ev.u.input.data[2] = abs_ver; ev.u.input.data[3] = wheel; return uhid_write(fd, &ev); } static int keyboard(int fd) { char buf[128]; ssize_t ret, i; ret = read(STDIN_FILENO, buf, sizeof(buf)); if (ret == 0) { fprintf(stderr, "Read HUP on stdin\n"); return -EFAULT; } else if (ret < 0) { fprintf(stderr, "Cannot read stdin: %m\n"); return -errno; } for (i = 0; i < ret; ++i) { switch (buf[i]) { case '1': btn1_down = !btn1_down; ret = send_event(fd); if (ret) return ret; break; case '2': btn2_down = !btn2_down; ret = send_event(fd); if (ret) return ret; break; case '3': btn3_down = !btn3_down; ret = send_event(fd); if (ret) return ret; break; case 'a': abs_hor = -20; ret = send_event(fd); abs_hor = 0; if (ret) return ret; break; case 'd': abs_hor = 20; ret = send_event(fd); abs_hor = 0; if (ret) return ret; break; case 'w': abs_ver = -20; ret = send_event(fd); abs_ver = 0; if (ret) return ret; break; case 's': abs_ver = 20; ret = send_event(fd); abs_ver = 0; if (ret) return ret; break; case 'r': wheel = 1; ret = send_event(fd); wheel = 0; if (ret) return ret; break; case 'f': wheel = -1; ret = send_event(fd); wheel = 0; if (ret) return ret; break; case 'q': return -ECANCELED; default: fprintf(stderr, "Invalid input: %c\n", buf[i]); } } return 0; } int main(int argc, char **argv) { int fd; const char *path = "/dev/uhid"; struct pollfd pfds[2]; int ret; struct termios state; ret = tcgetattr(STDIN_FILENO, &state); if (ret) { fprintf(stderr, "Cannot get tty state\n"); } else { state.c_lflag &= ~ICANON; state.c_cc[VMIN] = 1; ret = tcsetattr(STDIN_FILENO, TCSANOW, &state); if (ret) fprintf(stderr, "Cannot set tty state\n"); } if (argc >= 2) { if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) { fprintf(stderr, "Usage: %s [%s]\n", argv[0], path); return EXIT_SUCCESS; } else { path = argv[1]; } } fprintf(stderr, "Open uhid-cdev %s\n", path); fd = open(path, O_RDWR | O_CLOEXEC); if (fd < 0) { fprintf(stderr, "Cannot open uhid-cdev %s: %m\n", path); return EXIT_FAILURE; } fprintf(stderr, "Create uhid device\n"); ret = create(fd); if (ret) { close(fd); return EXIT_FAILURE; } pfds[0].fd = STDIN_FILENO; pfds[0].events = POLLIN; pfds[1].fd = fd; pfds[1].events = POLLIN; fprintf(stderr, "Press 'q' to quit...\n"); while (1) { ret = poll(pfds, 2, -1); if (ret < 0) { fprintf(stderr, "Cannot poll for fds: %m\n"); break; } if (pfds[0].revents & POLLHUP) { fprintf(stderr, "Received HUP on stdin\n"); break; } if (pfds[1].revents & POLLHUP) { fprintf(stderr, "Received HUP on uhid-cdev\n"); break; } if (pfds[0].revents & POLLIN) { ret = keyboard(fd); if (ret) break; } if (pfds[1].revents & POLLIN) { ret = event(fd); if (ret) break; } } fprintf(stderr, "Destroy uhid device\n"); destroy(fd); return EXIT_SUCCESS; }
gpl-2.0
Arc-Team/android_kernel_samsung_jflte
drivers/video/matrox/matroxfb_maven.c
8141
30049
/* * * Hardware accelerated Matrox Millennium I, II, Mystique, G100, G200, G400 and G450. * * (c) 1998-2002 Petr Vandrovec <vandrove@vc.cvut.cz> * * Portions Copyright (c) 2001 Matrox Graphics Inc. * * Version: 1.65 2002/08/14 * * See matroxfb_base.c for contributors. * */ #include "matroxfb_maven.h" #include "matroxfb_misc.h" #include "matroxfb_DAC1064.h" #include <linux/i2c.h> #include <linux/matroxfb.h> #include <linux/slab.h> #include <asm/div64.h> #define MGATVO_B 1 #define MGATVO_C 2 static const struct maven_gamma { unsigned char reg83; unsigned char reg84; unsigned char reg85; unsigned char reg86; unsigned char reg87; unsigned char reg88; unsigned char reg89; unsigned char reg8a; unsigned char reg8b; } maven_gamma[] = { { 131, 57, 223, 15, 117, 212, 251, 91, 156}, { 133, 61, 128, 63, 180, 147, 195, 100, 180}, { 131, 19, 63, 31, 50, 66, 171, 64, 176}, { 0, 0, 0, 31, 16, 16, 16, 100, 200}, { 8, 23, 47, 73, 147, 244, 220, 80, 195}, { 22, 43, 64, 80, 147, 115, 58, 85, 168}, { 34, 60, 80, 214, 147, 212, 188, 85, 167}, { 45, 77, 96, 216, 147, 99, 91, 85, 159}, { 56, 76, 112, 107, 147, 212, 148, 64, 144}, { 65, 91, 128, 137, 147, 196, 17, 69, 148}, { 72, 104, 136, 138, 147, 180, 245, 73, 147}, { 87, 116, 143, 126, 16, 83, 229, 77, 144}, { 95, 119, 152, 254, 244, 83, 221, 77, 151}, { 100, 129, 159, 156, 244, 148, 197, 77, 160}, { 105, 141, 167, 247, 244, 132, 181, 84, 166}, { 105, 147, 168, 247, 244, 245, 181, 90, 170}, { 120, 153, 175, 248, 212, 229, 165, 90, 180}, { 119, 156, 176, 248, 244, 229, 84, 74, 160}, { 119, 158, 183, 248, 244, 229, 149, 78, 165} }; /* Definition of the various controls */ struct mctl { struct v4l2_queryctrl desc; size_t control; }; #define BLMIN 0x0FF #define WLMAX 0x3FF static const struct mctl maven_controls[] = { { { V4L2_CID_BRIGHTNESS, V4L2_CTRL_TYPE_INTEGER, "brightness", 0, WLMAX - BLMIN, 1, 379 - BLMIN, 0, }, offsetof(struct matrox_fb_info, altout.tvo_params.brightness) }, { { V4L2_CID_CONTRAST, V4L2_CTRL_TYPE_INTEGER, "contrast", 0, 1023, 1, 127, 0, }, offsetof(struct matrox_fb_info, altout.tvo_params.contrast) }, { { V4L2_CID_SATURATION, V4L2_CTRL_TYPE_INTEGER, "saturation", 0, 255, 1, 155, 0, }, offsetof(struct matrox_fb_info, altout.tvo_params.saturation) }, { { V4L2_CID_HUE, V4L2_CTRL_TYPE_INTEGER, "hue", 0, 255, 1, 0, 0, }, offsetof(struct matrox_fb_info, altout.tvo_params.hue) }, { { V4L2_CID_GAMMA, V4L2_CTRL_TYPE_INTEGER, "gamma", 0, ARRAY_SIZE(maven_gamma) - 1, 1, 3, 0, }, offsetof(struct matrox_fb_info, altout.tvo_params.gamma) }, { { MATROXFB_CID_TESTOUT, V4L2_CTRL_TYPE_BOOLEAN, "test output", 0, 1, 1, 0, 0, }, offsetof(struct matrox_fb_info, altout.tvo_params.testout) }, { { MATROXFB_CID_DEFLICKER, V4L2_CTRL_TYPE_INTEGER, "deflicker mode", 0, 2, 1, 0, 0, }, offsetof(struct matrox_fb_info, altout.tvo_params.deflicker) }, }; #define MAVCTRLS ARRAY_SIZE(maven_controls) /* Return: positive number: id found -EINVAL: id not found, return failure -ENOENT: id not found, create fake disabled control */ static int get_ctrl_id(__u32 v4l2_id) { int i; for (i = 0; i < MAVCTRLS; i++) { if (v4l2_id < maven_controls[i].desc.id) { if (maven_controls[i].desc.id == 0x08000000) { return -EINVAL; } return -ENOENT; } if (v4l2_id == maven_controls[i].desc.id) { return i; } } return -EINVAL; } struct maven_data { struct matrox_fb_info* primary_head; struct i2c_client *client; int version; }; static int* get_ctrl_ptr(struct maven_data* md, int idx) { return (int*)((char*)(md->primary_head) + maven_controls[idx].control); } static int maven_get_reg(struct i2c_client* c, char reg) { char dst; struct i2c_msg msgs[] = {{ c->addr, I2C_M_REV_DIR_ADDR, sizeof(reg), &reg }, { c->addr, I2C_M_RD | I2C_M_NOSTART, sizeof(dst), &dst }}; s32 err; err = i2c_transfer(c->adapter, msgs, 2); if (err < 0) printk(KERN_INFO "ReadReg(%d) failed\n", reg); return dst & 0xFF; } static int maven_set_reg(struct i2c_client* c, int reg, int val) { s32 err; err = i2c_smbus_write_byte_data(c, reg, val); if (err) printk(KERN_INFO "WriteReg(%d) failed\n", reg); return err; } static int maven_set_reg_pair(struct i2c_client* c, int reg, int val) { s32 err; err = i2c_smbus_write_word_data(c, reg, val); if (err) printk(KERN_INFO "WriteRegPair(%d) failed\n", reg); return err; } static const struct matrox_pll_features maven_pll = { 50000, 27000, 4, 127, 2, 31, 3 }; struct matrox_pll_features2 { unsigned int vco_freq_min; unsigned int vco_freq_max; unsigned int feed_div_min; unsigned int feed_div_max; unsigned int in_div_min; unsigned int in_div_max; unsigned int post_shift_max; }; struct matrox_pll_ctl { unsigned int ref_freq; unsigned int den; }; static const struct matrox_pll_features2 maven1000_pll = { 50000000, 300000000, 5, 128, 3, 32, 3 }; static const struct matrox_pll_ctl maven_PAL = { 540000, 50 }; static const struct matrox_pll_ctl maven_NTSC = { 450450, /* 27027000/60 == 27000000/59.94005994 */ 60 }; static int matroxfb_PLL_mavenclock(const struct matrox_pll_features2* pll, const struct matrox_pll_ctl* ctl, unsigned int htotal, unsigned int vtotal, unsigned int* in, unsigned int* feed, unsigned int* post, unsigned int* h2) { unsigned int besth2 = 0; unsigned int fxtal = ctl->ref_freq; unsigned int fmin = pll->vco_freq_min / ctl->den; unsigned int fwant; unsigned int p; unsigned int scrlen; unsigned int fmax; DBG(__func__) scrlen = htotal * (vtotal - 1); fwant = htotal * vtotal; fmax = pll->vco_freq_max / ctl->den; dprintk(KERN_DEBUG "want: %u, xtal: %u, h: %u, v: %u, fmax: %u\n", fwant, fxtal, htotal, vtotal, fmax); for (p = 1; p <= pll->post_shift_max; p++) { if (fwant * 2 > fmax) break; fwant *= 2; } if (fwant > fmax) return 0; for (; p-- > 0; fwant >>= 1) { unsigned int m; if (fwant < fmin) break; for (m = pll->in_div_min; m <= pll->in_div_max; m++) { unsigned int n; unsigned int dvd; unsigned int ln; n = (fwant * m) / fxtal; if (n < pll->feed_div_min) continue; if (n > pll->feed_div_max) break; ln = fxtal * n; dvd = m << p; if (ln % dvd) continue; ln = ln / dvd; if (ln < scrlen + 2) continue; ln = ln - scrlen; if (ln > htotal) continue; dprintk(KERN_DEBUG "Match: %u / %u / %u / %u\n", n, m, p, ln); if (ln > besth2) { dprintk(KERN_DEBUG "Better...\n"); *h2 = besth2 = ln; *post = p; *in = m; *feed = n; } } } /* if h2/post/in/feed have not been assigned, return zero (error) */ if (besth2 < 2) return 0; dprintk(KERN_ERR "clk: %02X %02X %02X %d %d\n", *in, *feed, *post, fxtal, fwant); return fxtal * (*feed) / (*in) * ctl->den; } static int matroxfb_mavenclock(const struct matrox_pll_ctl *ctl, unsigned int htotal, unsigned int vtotal, unsigned int* in, unsigned int* feed, unsigned int* post, unsigned int* htotal2) { unsigned int fvco; unsigned int uninitialized_var(p); fvco = matroxfb_PLL_mavenclock(&maven1000_pll, ctl, htotal, vtotal, in, feed, &p, htotal2); if (!fvco) return -EINVAL; p = (1 << p) - 1; if (fvco <= 100000000) ; else if (fvco <= 140000000) p |= 0x08; else if (fvco <= 180000000) p |= 0x10; else p |= 0x18; *post = p; return 0; } static void DAC1064_calcclock(unsigned int freq, unsigned int fmax, unsigned int* in, unsigned int* feed, unsigned int* post) { unsigned int fvco; unsigned int p; fvco = matroxfb_PLL_calcclock(&maven_pll, freq, fmax, in, feed, &p); p = (1 << p) - 1; if (fvco <= 100000) ; else if (fvco <= 140000) p |= 0x08; else if (fvco <= 180000) p |= 0x10; else p |= 0x18; *post = p; return; } static unsigned char maven_compute_deflicker (const struct maven_data* md) { unsigned char df; df = (md->version == MGATVO_B?0x40:0x00); switch (md->primary_head->altout.tvo_params.deflicker) { case 0: /* df |= 0x00; */ break; case 1: df |= 0xB1; break; case 2: df |= 0xA2; break; } return df; } static void maven_compute_bwlevel (const struct maven_data* md, int *bl, int *wl) { const int b = md->primary_head->altout.tvo_params.brightness + BLMIN; const int c = md->primary_head->altout.tvo_params.contrast; *bl = max(b - c, BLMIN); *wl = min(b + c, WLMAX); } static const struct maven_gamma* maven_compute_gamma (const struct maven_data* md) { return maven_gamma + md->primary_head->altout.tvo_params.gamma; } static void maven_init_TVdata(const struct maven_data* md, struct mavenregs* data) { static struct mavenregs palregs = { { 0x2A, 0x09, 0x8A, 0xCB, /* 00: chroma subcarrier */ 0x00, 0x00, /* ? not written */ 0x00, /* modified by code (F9 written...) */ 0x00, /* ? not written */ 0x7E, /* 08 */ 0x44, /* 09 */ 0x9C, /* 0A */ 0x2E, /* 0B */ 0x21, /* 0C */ 0x00, /* ? not written */ 0x3F, 0x03, /* 0E-0F */ 0x3F, 0x03, /* 10-11 */ 0x1A, /* 12 */ 0x2A, /* 13 */ 0x1C, 0x3D, 0x14, /* 14-16 */ 0x9C, 0x01, /* 17-18 */ 0x00, /* 19 */ 0xFE, /* 1A */ 0x7E, /* 1B */ 0x60, /* 1C */ 0x05, /* 1D */ 0x89, 0x03, /* 1E-1F */ 0x72, /* 20 */ 0x07, /* 21 */ 0x72, /* 22 */ 0x00, /* 23 */ 0x00, /* 24 */ 0x00, /* 25 */ 0x08, /* 26 */ 0x04, /* 27 */ 0x00, /* 28 */ 0x1A, /* 29 */ 0x55, 0x01, /* 2A-2B */ 0x26, /* 2C */ 0x07, 0x7E, /* 2D-2E */ 0x02, 0x54, /* 2F-30 */ 0xB0, 0x00, /* 31-32 */ 0x14, /* 33 */ 0x49, /* 34 */ 0x00, /* 35 written multiple times */ 0x00, /* 36 not written */ 0xA3, /* 37 */ 0xC8, /* 38 */ 0x22, /* 39 */ 0x02, /* 3A */ 0x22, /* 3B */ 0x3F, 0x03, /* 3C-3D */ 0x00, /* 3E written multiple times */ 0x00, /* 3F not written */ }, MATROXFB_OUTPUT_MODE_PAL, 625, 50 }; static struct mavenregs ntscregs = { { 0x21, 0xF0, 0x7C, 0x1F, /* 00: chroma subcarrier */ 0x00, 0x00, /* ? not written */ 0x00, /* modified by code (F9 written...) */ 0x00, /* ? not written */ 0x7E, /* 08 */ 0x43, /* 09 */ 0x7E, /* 0A */ 0x3D, /* 0B */ 0x00, /* 0C */ 0x00, /* ? not written */ 0x41, 0x00, /* 0E-0F */ 0x3C, 0x00, /* 10-11 */ 0x17, /* 12 */ 0x21, /* 13 */ 0x1B, 0x1B, 0x24, /* 14-16 */ 0x83, 0x01, /* 17-18 */ 0x00, /* 19 */ 0x0F, /* 1A */ 0x0F, /* 1B */ 0x60, /* 1C */ 0x05, /* 1D */ 0x89, 0x02, /* 1E-1F */ 0x5F, /* 20 */ 0x04, /* 21 */ 0x5F, /* 22 */ 0x01, /* 23 */ 0x02, /* 24 */ 0x00, /* 25 */ 0x0A, /* 26 */ 0x05, /* 27 */ 0x00, /* 28 */ 0x10, /* 29 */ 0xFF, 0x03, /* 2A-2B */ 0x24, /* 2C */ 0x0F, 0x78, /* 2D-2E */ 0x00, 0x00, /* 2F-30 */ 0xB2, 0x04, /* 31-32 */ 0x14, /* 33 */ 0x02, /* 34 */ 0x00, /* 35 written multiple times */ 0x00, /* 36 not written */ 0xA3, /* 37 */ 0xC8, /* 38 */ 0x15, /* 39 */ 0x05, /* 3A */ 0x3B, /* 3B */ 0x3C, 0x00, /* 3C-3D */ 0x00, /* 3E written multiple times */ 0x00, /* never written */ }, MATROXFB_OUTPUT_MODE_NTSC, 525, 60 }; struct matrox_fb_info *minfo = md->primary_head; if (minfo->outputs[1].mode == MATROXFB_OUTPUT_MODE_PAL) *data = palregs; else *data = ntscregs; /* Set deflicker */ data->regs[0x93] = maven_compute_deflicker(md); /* set gamma */ { const struct maven_gamma* g; g = maven_compute_gamma(md); data->regs[0x83] = g->reg83; data->regs[0x84] = g->reg84; data->regs[0x85] = g->reg85; data->regs[0x86] = g->reg86; data->regs[0x87] = g->reg87; data->regs[0x88] = g->reg88; data->regs[0x89] = g->reg89; data->regs[0x8A] = g->reg8a; data->regs[0x8B] = g->reg8b; } /* Set contrast / brightness */ { int bl, wl; maven_compute_bwlevel (md, &bl, &wl); data->regs[0x0e] = bl >> 2; data->regs[0x0f] = bl & 3; data->regs[0x1e] = wl >> 2; data->regs[0x1f] = wl & 3; } /* Set saturation */ { data->regs[0x20] = data->regs[0x22] = minfo->altout.tvo_params.saturation; } /* Set HUE */ data->regs[0x25] = minfo->altout.tvo_params.hue; return; } #define LR(x) maven_set_reg(c, (x), m->regs[(x)]) #define LRP(x) maven_set_reg_pair(c, (x), m->regs[(x)] | (m->regs[(x)+1] << 8)) static void maven_init_TV(struct i2c_client* c, const struct mavenregs* m) { int val; maven_set_reg(c, 0x3E, 0x01); maven_get_reg(c, 0x82); /* fetch oscillator state? */ maven_set_reg(c, 0x8C, 0x00); maven_get_reg(c, 0x94); /* get 0x82 */ maven_set_reg(c, 0x94, 0xA2); /* xmiscctrl */ maven_set_reg_pair(c, 0x8E, 0x1EFF); maven_set_reg(c, 0xC6, 0x01); /* removed code... */ maven_get_reg(c, 0x06); maven_set_reg(c, 0x06, 0xF9); /* or read |= 0xF0 ? */ /* removed code here... */ /* real code begins here? */ /* chroma subcarrier */ LR(0x00); LR(0x01); LR(0x02); LR(0x03); LR(0x04); LR(0x2C); LR(0x08); LR(0x0A); LR(0x09); LR(0x29); LRP(0x31); LRP(0x17); LR(0x0B); LR(0x0C); if (m->mode == MATROXFB_OUTPUT_MODE_PAL) { maven_set_reg(c, 0x35, 0x10); /* ... */ } else { maven_set_reg(c, 0x35, 0x0F); /* ... */ } LRP(0x10); LRP(0x0E); LRP(0x1E); LR(0x20); /* saturation #1 */ LR(0x22); /* saturation #2 */ LR(0x25); /* hue */ LR(0x34); LR(0x33); LR(0x19); LR(0x12); LR(0x3B); LR(0x13); LR(0x39); LR(0x1D); LR(0x3A); LR(0x24); LR(0x14); LR(0x15); LR(0x16); LRP(0x2D); LRP(0x2F); LR(0x1A); LR(0x1B); LR(0x1C); LR(0x23); LR(0x26); LR(0x28); LR(0x27); LR(0x21); LRP(0x2A); if (m->mode == MATROXFB_OUTPUT_MODE_PAL) maven_set_reg(c, 0x35, 0x1D); /* ... */ else maven_set_reg(c, 0x35, 0x1C); LRP(0x3C); LR(0x37); LR(0x38); maven_set_reg(c, 0xB3, 0x01); maven_get_reg(c, 0xB0); /* read 0x80 */ maven_set_reg(c, 0xB0, 0x08); /* ugh... */ maven_get_reg(c, 0xB9); /* read 0x7C */ maven_set_reg(c, 0xB9, 0x78); maven_get_reg(c, 0xBF); /* read 0x00 */ maven_set_reg(c, 0xBF, 0x02); maven_get_reg(c, 0x94); /* read 0x82 */ maven_set_reg(c, 0x94, 0xB3); LR(0x80); /* 04 1A 91 or 05 21 91 */ LR(0x81); LR(0x82); maven_set_reg(c, 0x8C, 0x20); maven_get_reg(c, 0x8D); maven_set_reg(c, 0x8D, 0x10); LR(0x90); /* 4D 50 52 or 4E 05 45 */ LR(0x91); LR(0x92); LRP(0x9A); /* 0049 or 004F */ LRP(0x9C); /* 0004 or 0004 */ LRP(0x9E); /* 0458 or 045E */ LRP(0xA0); /* 05DA or 051B */ LRP(0xA2); /* 00CC or 00CF */ LRP(0xA4); /* 007D or 007F */ LRP(0xA6); /* 007C or 007E */ LRP(0xA8); /* 03CB or 03CE */ LRP(0x98); /* 0000 or 0000 */ LRP(0xAE); /* 0044 or 003A */ LRP(0x96); /* 05DA or 051B */ LRP(0xAA); /* 04BC or 046A */ LRP(0xAC); /* 004D or 004E */ LR(0xBE); LR(0xC2); maven_get_reg(c, 0x8D); maven_set_reg(c, 0x8D, 0x04); LR(0x20); /* saturation #1 */ LR(0x22); /* saturation #2 */ LR(0x93); /* whoops */ LR(0x20); /* oh, saturation #1 again */ LR(0x22); /* oh, saturation #2 again */ LR(0x25); /* hue */ LRP(0x0E); LRP(0x1E); LRP(0x0E); /* problems with memory? */ LRP(0x1E); /* yes, matrox must have problems in memory area... */ /* load gamma correction stuff */ LR(0x83); LR(0x84); LR(0x85); LR(0x86); LR(0x87); LR(0x88); LR(0x89); LR(0x8A); LR(0x8B); val = maven_get_reg(c, 0x8D); val &= 0x14; /* 0x10 or anything ored with it */ maven_set_reg(c, 0x8D, val); LR(0x33); LR(0x19); LR(0x12); LR(0x3B); LR(0x13); LR(0x39); LR(0x1D); LR(0x3A); LR(0x24); LR(0x14); LR(0x15); LR(0x16); LRP(0x2D); LRP(0x2F); LR(0x1A); LR(0x1B); LR(0x1C); LR(0x23); LR(0x26); LR(0x28); LR(0x27); LR(0x21); LRP(0x2A); if (m->mode == MATROXFB_OUTPUT_MODE_PAL) maven_set_reg(c, 0x35, 0x1D); else maven_set_reg(c, 0x35, 0x1C); LRP(0x3C); LR(0x37); LR(0x38); maven_get_reg(c, 0xB0); LR(0xB0); /* output mode */ LR(0x90); LR(0xBE); LR(0xC2); LRP(0x9A); LRP(0xA2); LRP(0x9E); LRP(0xA6); LRP(0xAA); LRP(0xAC); maven_set_reg(c, 0x3E, 0x00); maven_set_reg(c, 0x95, 0x20); } static int maven_find_exact_clocks(unsigned int ht, unsigned int vt, struct mavenregs* m) { unsigned int x; unsigned int err = ~0; /* 1:1 */ m->regs[0x80] = 0x0F; m->regs[0x81] = 0x07; m->regs[0x82] = 0x81; for (x = 0; x < 8; x++) { unsigned int c; unsigned int uninitialized_var(a), uninitialized_var(b), uninitialized_var(h2); unsigned int h = ht + 2 + x; if (!matroxfb_mavenclock((m->mode == MATROXFB_OUTPUT_MODE_PAL) ? &maven_PAL : &maven_NTSC, h, vt, &a, &b, &c, &h2)) { unsigned int diff = h - h2; if (diff < err) { err = diff; m->regs[0x80] = a - 1; m->regs[0x81] = b - 1; m->regs[0x82] = c | 0x80; m->hcorr = h2 - 2; m->htotal = h - 2; } } } return err != ~0U; } static inline int maven_compute_timming(struct maven_data* md, struct my_timming* mt, struct mavenregs* m) { unsigned int tmpi; unsigned int a, bv, c; struct matrox_fb_info *minfo = md->primary_head; m->mode = minfo->outputs[1].mode; if (m->mode != MATROXFB_OUTPUT_MODE_MONITOR) { unsigned int lmargin; unsigned int umargin; unsigned int vslen; unsigned int hcrt; unsigned int slen; maven_init_TVdata(md, m); if (maven_find_exact_clocks(mt->HTotal, mt->VTotal, m) == 0) return -EINVAL; lmargin = mt->HTotal - mt->HSyncEnd; slen = mt->HSyncEnd - mt->HSyncStart; hcrt = mt->HTotal - slen - mt->delay; umargin = mt->VTotal - mt->VSyncEnd; vslen = mt->VSyncEnd - mt->VSyncStart; if (m->hcorr < mt->HTotal) hcrt += m->hcorr; if (hcrt > mt->HTotal) hcrt -= mt->HTotal; if (hcrt + 2 > mt->HTotal) hcrt = 0; /* or issue warning? */ /* last (first? middle?) line in picture can have different length */ /* hlen - 2 */ m->regs[0x96] = m->hcorr; m->regs[0x97] = m->hcorr >> 8; /* ... */ m->regs[0x98] = 0x00; m->regs[0x99] = 0x00; /* hblanking end */ m->regs[0x9A] = lmargin; /* 100% */ m->regs[0x9B] = lmargin >> 8; /* 100% */ /* who knows */ m->regs[0x9C] = 0x04; m->regs[0x9D] = 0x00; /* htotal - 2 */ m->regs[0xA0] = m->htotal; m->regs[0xA1] = m->htotal >> 8; /* vblanking end */ m->regs[0xA2] = mt->VTotal - mt->VSyncStart - 1; /* stop vblanking */ m->regs[0xA3] = (mt->VTotal - mt->VSyncStart - 1) >> 8; /* something end... [A6]+1..[A8] */ if (md->version == MGATVO_B) { m->regs[0xA4] = 0x04; m->regs[0xA5] = 0x00; } else { m->regs[0xA4] = 0x01; m->regs[0xA5] = 0x00; } /* something start... 0..[A4]-1 */ m->regs[0xA6] = 0x00; m->regs[0xA7] = 0x00; /* vertical line count - 1 */ m->regs[0xA8] = mt->VTotal - 1; m->regs[0xA9] = (mt->VTotal - 1) >> 8; /* horizontal vidrst pos */ m->regs[0xAA] = hcrt; /* 0 <= hcrt <= htotal - 2 */ m->regs[0xAB] = hcrt >> 8; /* vertical vidrst pos */ m->regs[0xAC] = mt->VTotal - 2; m->regs[0xAD] = (mt->VTotal - 2) >> 8; /* moves picture up/down and so on... */ m->regs[0xAE] = 0x01; /* Fix this... 0..VTotal */ m->regs[0xAF] = 0x00; { int hdec; int hlen; unsigned int ibmin = 4 + lmargin + mt->HDisplay; unsigned int ib; int i; /* Verify! */ /* Where 94208 came from? */ if (mt->HTotal) hdec = 94208 / (mt->HTotal); else hdec = 0x81; if (hdec > 0x81) hdec = 0x81; if (hdec < 0x41) hdec = 0x41; hdec--; hlen = 98304 - 128 - ((lmargin + mt->HDisplay - 8) * hdec); if (hlen < 0) hlen = 0; hlen = hlen >> 8; if (hlen > 0xFF) hlen = 0xFF; /* Now we have to compute input buffer length. If you want any picture, it must be between 4 + lmargin + xres and 94208 / hdec If you want perfect picture even on the top of screen, it must be also 0x3C0000 * i / hdec + Q - R / hdec where R Qmin Qmax 0x07000 0x5AE 0x5BF 0x08000 0x5CF 0x5FF 0x0C000 0x653 0x67F 0x10000 0x6F8 0x6FF */ i = 1; do { ib = ((0x3C0000 * i - 0x8000)/ hdec + 0x05E7) >> 8; i++; } while (ib < ibmin); if (ib >= m->htotal + 2) { ib = ibmin; } m->regs[0x90] = hdec; /* < 0x40 || > 0x80 is bad... 0x80 is questionable */ m->regs[0xC2] = hlen; /* 'valid' input line length */ m->regs[0x9E] = ib; m->regs[0x9F] = ib >> 8; } { int vdec; int vlen; #define MATROX_USE64BIT_DIVIDE if (mt->VTotal) { #ifdef MATROX_USE64BIT_DIVIDE u64 f1; u32 a; u32 b; a = m->vlines * (m->htotal + 2); b = (mt->VTotal - 1) * (m->htotal + 2) + m->hcorr + 2; f1 = ((u64)a) << 15; /* *32768 */ do_div(f1, b); vdec = f1; #else vdec = m->vlines * 32768 / mt->VTotal; #endif } else vdec = 0x8000; if (vdec > 0x8000) vdec = 0x8000; vlen = (vslen + umargin + mt->VDisplay) * vdec; vlen = (vlen >> 16) - 146; /* FIXME: 146?! */ if (vlen < 0) vlen = 0; if (vlen > 0xFF) vlen = 0xFF; vdec--; m->regs[0x91] = vdec; m->regs[0x92] = vdec >> 8; m->regs[0xBE] = vlen; } m->regs[0xB0] = 0x08; /* output: SVideo/Composite */ return 0; } DAC1064_calcclock(mt->pixclock, 450000, &a, &bv, &c); m->regs[0x80] = a; m->regs[0x81] = bv; m->regs[0x82] = c | 0x80; m->regs[0xB3] = 0x01; m->regs[0x94] = 0xB2; /* htotal... */ m->regs[0x96] = mt->HTotal; m->regs[0x97] = mt->HTotal >> 8; /* ?? */ m->regs[0x98] = 0x00; m->regs[0x99] = 0x00; /* hsync len */ tmpi = mt->HSyncEnd - mt->HSyncStart; m->regs[0x9A] = tmpi; m->regs[0x9B] = tmpi >> 8; /* hblank end */ tmpi = mt->HTotal - mt->HSyncStart; m->regs[0x9C] = tmpi; m->regs[0x9D] = tmpi >> 8; /* hblank start */ tmpi += mt->HDisplay; m->regs[0x9E] = tmpi; m->regs[0x9F] = tmpi >> 8; /* htotal + 1 */ tmpi = mt->HTotal + 1; m->regs[0xA0] = tmpi; m->regs[0xA1] = tmpi >> 8; /* vsync?! */ tmpi = mt->VSyncEnd - mt->VSyncStart - 1; m->regs[0xA2] = tmpi; m->regs[0xA3] = tmpi >> 8; /* ignored? */ tmpi = mt->VTotal - mt->VSyncStart; m->regs[0xA4] = tmpi; m->regs[0xA5] = tmpi >> 8; /* ignored? */ tmpi = mt->VTotal - 1; m->regs[0xA6] = tmpi; m->regs[0xA7] = tmpi >> 8; /* vtotal - 1 */ m->regs[0xA8] = tmpi; m->regs[0xA9] = tmpi >> 8; /* hor vidrst */ tmpi = mt->HTotal - mt->delay; m->regs[0xAA] = tmpi; m->regs[0xAB] = tmpi >> 8; /* vert vidrst */ tmpi = mt->VTotal - 2; m->regs[0xAC] = tmpi; m->regs[0xAD] = tmpi >> 8; /* ignored? */ m->regs[0xAE] = 0x00; m->regs[0xAF] = 0x00; m->regs[0xB0] = 0x03; /* output: monitor */ m->regs[0xB1] = 0xA0; /* ??? */ m->regs[0x8C] = 0x20; /* must be set... */ m->regs[0x8D] = 0x04; /* defaults to 0x10: test signal */ m->regs[0xB9] = 0x1A; /* defaults to 0x2C: too bright */ m->regs[0xBF] = 0x22; /* makes picture stable */ return 0; } static int maven_program_timming(struct maven_data* md, const struct mavenregs* m) { struct i2c_client *c = md->client; if (m->mode == MATROXFB_OUTPUT_MODE_MONITOR) { LR(0x80); LR(0x81); LR(0x82); LR(0xB3); LR(0x94); LRP(0x96); LRP(0x98); LRP(0x9A); LRP(0x9C); LRP(0x9E); LRP(0xA0); LRP(0xA2); LRP(0xA4); LRP(0xA6); LRP(0xA8); LRP(0xAA); LRP(0xAC); LRP(0xAE); LR(0xB0); /* output: monitor */ LR(0xB1); /* ??? */ LR(0x8C); /* must be set... */ LR(0x8D); /* defaults to 0x10: test signal */ LR(0xB9); /* defaults to 0x2C: too bright */ LR(0xBF); /* makes picture stable */ } else { maven_init_TV(c, m); } return 0; } static inline int maven_resync(struct maven_data* md) { struct i2c_client *c = md->client; maven_set_reg(c, 0x95, 0x20); /* start whole thing */ return 0; } static int maven_get_queryctrl (struct maven_data* md, struct v4l2_queryctrl *p) { int i; i = get_ctrl_id(p->id); if (i >= 0) { *p = maven_controls[i].desc; return 0; } if (i == -ENOENT) { static const struct v4l2_queryctrl disctrl = { .flags = V4L2_CTRL_FLAG_DISABLED }; i = p->id; *p = disctrl; p->id = i; sprintf(p->name, "Ctrl #%08X", i); return 0; } return -EINVAL; } static int maven_set_control (struct maven_data* md, struct v4l2_control *p) { int i; i = get_ctrl_id(p->id); if (i < 0) return -EINVAL; /* * Check if changed. */ if (p->value == *get_ctrl_ptr(md, i)) return 0; /* * Check limits. */ if (p->value > maven_controls[i].desc.maximum) return -EINVAL; if (p->value < maven_controls[i].desc.minimum) return -EINVAL; /* * Store new value. */ *get_ctrl_ptr(md, i) = p->value; switch (p->id) { case V4L2_CID_BRIGHTNESS: case V4L2_CID_CONTRAST: { int blacklevel, whitelevel; maven_compute_bwlevel(md, &blacklevel, &whitelevel); blacklevel = (blacklevel >> 2) | ((blacklevel & 3) << 8); whitelevel = (whitelevel >> 2) | ((whitelevel & 3) << 8); maven_set_reg_pair(md->client, 0x0e, blacklevel); maven_set_reg_pair(md->client, 0x1e, whitelevel); } break; case V4L2_CID_SATURATION: { maven_set_reg(md->client, 0x20, p->value); maven_set_reg(md->client, 0x22, p->value); } break; case V4L2_CID_HUE: { maven_set_reg(md->client, 0x25, p->value); } break; case V4L2_CID_GAMMA: { const struct maven_gamma* g; g = maven_compute_gamma(md); maven_set_reg(md->client, 0x83, g->reg83); maven_set_reg(md->client, 0x84, g->reg84); maven_set_reg(md->client, 0x85, g->reg85); maven_set_reg(md->client, 0x86, g->reg86); maven_set_reg(md->client, 0x87, g->reg87); maven_set_reg(md->client, 0x88, g->reg88); maven_set_reg(md->client, 0x89, g->reg89); maven_set_reg(md->client, 0x8a, g->reg8a); maven_set_reg(md->client, 0x8b, g->reg8b); } break; case MATROXFB_CID_TESTOUT: { unsigned char val = maven_get_reg(md->client, 0x8d); if (p->value) val |= 0x10; else val &= ~0x10; maven_set_reg(md->client, 0x8d, val); } break; case MATROXFB_CID_DEFLICKER: { maven_set_reg(md->client, 0x93, maven_compute_deflicker(md)); } break; } return 0; } static int maven_get_control (struct maven_data* md, struct v4l2_control *p) { int i; i = get_ctrl_id(p->id); if (i < 0) return -EINVAL; p->value = *get_ctrl_ptr(md, i); return 0; } /******************************************************/ static int maven_out_compute(void* md, struct my_timming* mt) { #define mdinfo ((struct maven_data*)md) #define minfo (mdinfo->primary_head) return maven_compute_timming(md, mt, &minfo->hw.maven); #undef minfo #undef mdinfo } static int maven_out_program(void* md) { #define mdinfo ((struct maven_data*)md) #define minfo (mdinfo->primary_head) return maven_program_timming(md, &minfo->hw.maven); #undef minfo #undef mdinfo } static int maven_out_start(void* md) { return maven_resync(md); } static int maven_out_verify_mode(void* md, u_int32_t arg) { switch (arg) { case MATROXFB_OUTPUT_MODE_PAL: case MATROXFB_OUTPUT_MODE_NTSC: case MATROXFB_OUTPUT_MODE_MONITOR: return 0; } return -EINVAL; } static int maven_out_get_queryctrl(void* md, struct v4l2_queryctrl* p) { return maven_get_queryctrl(md, p); } static int maven_out_get_ctrl(void* md, struct v4l2_control* p) { return maven_get_control(md, p); } static int maven_out_set_ctrl(void* md, struct v4l2_control* p) { return maven_set_control(md, p); } static struct matrox_altout maven_altout = { .name = "Secondary output", .compute = maven_out_compute, .program = maven_out_program, .start = maven_out_start, .verifymode = maven_out_verify_mode, .getqueryctrl = maven_out_get_queryctrl, .getctrl = maven_out_get_ctrl, .setctrl = maven_out_set_ctrl, }; static int maven_init_client(struct i2c_client* clnt) { struct maven_data* md = i2c_get_clientdata(clnt); struct matrox_fb_info *minfo = container_of(clnt->adapter, struct i2c_bit_adapter, adapter)->minfo; md->primary_head = minfo; md->client = clnt; down_write(&minfo->altout.lock); minfo->outputs[1].output = &maven_altout; minfo->outputs[1].src = minfo->outputs[1].default_src; minfo->outputs[1].data = md; minfo->outputs[1].mode = MATROXFB_OUTPUT_MODE_MONITOR; up_write(&minfo->altout.lock); if (maven_get_reg(clnt, 0xB2) < 0x14) { md->version = MGATVO_B; /* Tweak some things for this old chip */ } else { md->version = MGATVO_C; } /* * Set all parameters to its initial values. */ { unsigned int i; for (i = 0; i < MAVCTRLS; ++i) { *get_ctrl_ptr(md, i) = maven_controls[i].desc.default_value; } } return 0; } static int maven_shutdown_client(struct i2c_client* clnt) { struct maven_data* md = i2c_get_clientdata(clnt); if (md->primary_head) { struct matrox_fb_info *minfo = md->primary_head; down_write(&minfo->altout.lock); minfo->outputs[1].src = MATROXFB_SRC_NONE; minfo->outputs[1].output = NULL; minfo->outputs[1].data = NULL; minfo->outputs[1].mode = MATROXFB_OUTPUT_MODE_MONITOR; up_write(&minfo->altout.lock); md->primary_head = NULL; } return 0; } static int maven_probe(struct i2c_client *client, const struct i2c_device_id *id) { struct i2c_adapter *adapter = client->adapter; int err = -ENODEV; struct maven_data* data; if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_WRITE_WORD_DATA | I2C_FUNC_SMBUS_BYTE_DATA | I2C_FUNC_PROTOCOL_MANGLING)) goto ERROR0; if (!(data = kzalloc(sizeof(*data), GFP_KERNEL))) { err = -ENOMEM; goto ERROR0; } i2c_set_clientdata(client, data); err = maven_init_client(client); if (err) goto ERROR4; return 0; ERROR4:; kfree(data); ERROR0:; return err; } static int maven_remove(struct i2c_client *client) { maven_shutdown_client(client); kfree(i2c_get_clientdata(client)); return 0; } static const struct i2c_device_id maven_id[] = { { "maven", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, maven_id); static struct i2c_driver maven_driver={ .driver = { .name = "maven", }, .probe = maven_probe, .remove = maven_remove, .id_table = maven_id, }; static int __init matroxfb_maven_init(void) { return i2c_add_driver(&maven_driver); } static void __exit matroxfb_maven_exit(void) { i2c_del_driver(&maven_driver); } MODULE_AUTHOR("(c) 1999-2002 Petr Vandrovec <vandrove@vc.cvut.cz>"); MODULE_DESCRIPTION("Matrox G200/G400 Matrox MGA-TVO driver"); MODULE_LICENSE("GPL"); module_init(matroxfb_maven_init); module_exit(matroxfb_maven_exit); /* we do not have __setup() yet */
gpl-2.0
Emotroid-Team/emotion_kernel_tw_edge
drivers/isdn/capi/kcapi_proc.c
9677
7547
/* * Kernel CAPI 2.0 Module - /proc/capi handling * * Copyright 1999 by Carsten Paeth <calle@calle.de> * Copyright 2002 by Kai Germaschewski <kai@germaschewski.name> * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * */ #include "kcapi.h" #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/init.h> #include <linux/export.h> static char *state2str(unsigned short state) { switch (state) { case CAPI_CTR_DETECTED: return "detected"; case CAPI_CTR_LOADING: return "loading"; case CAPI_CTR_RUNNING: return "running"; default: return "???"; } } // /proc/capi // =========================================================================== // /proc/capi/controller: // cnr driver cardstate name driverinfo // /proc/capi/contrstats: // cnr nrecvctlpkt nrecvdatapkt nsentctlpkt nsentdatapkt // --------------------------------------------------------------------------- static void *controller_start(struct seq_file *seq, loff_t *pos) __acquires(capi_controller_lock) { mutex_lock(&capi_controller_lock); if (*pos < CAPI_MAXCONTR) return &capi_controller[*pos]; return NULL; } static void *controller_next(struct seq_file *seq, void *v, loff_t *pos) { ++*pos; if (*pos < CAPI_MAXCONTR) return &capi_controller[*pos]; return NULL; } static void controller_stop(struct seq_file *seq, void *v) __releases(capi_controller_lock) { mutex_unlock(&capi_controller_lock); } static int controller_show(struct seq_file *seq, void *v) { struct capi_ctr *ctr = *(struct capi_ctr **) v; if (!ctr) return 0; seq_printf(seq, "%d %-10s %-8s %-16s %s\n", ctr->cnr, ctr->driver_name, state2str(ctr->state), ctr->name, ctr->procinfo ? ctr->procinfo(ctr) : ""); return 0; } static int contrstats_show(struct seq_file *seq, void *v) { struct capi_ctr *ctr = *(struct capi_ctr **) v; if (!ctr) return 0; seq_printf(seq, "%d %lu %lu %lu %lu\n", ctr->cnr, ctr->nrecvctlpkt, ctr->nrecvdatapkt, ctr->nsentctlpkt, ctr->nsentdatapkt); return 0; } static const struct seq_operations seq_controller_ops = { .start = controller_start, .next = controller_next, .stop = controller_stop, .show = controller_show, }; static const struct seq_operations seq_contrstats_ops = { .start = controller_start, .next = controller_next, .stop = controller_stop, .show = contrstats_show, }; static int seq_controller_open(struct inode *inode, struct file *file) { return seq_open(file, &seq_controller_ops); } static int seq_contrstats_open(struct inode *inode, struct file *file) { return seq_open(file, &seq_contrstats_ops); } static const struct file_operations proc_controller_ops = { .owner = THIS_MODULE, .open = seq_controller_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static const struct file_operations proc_contrstats_ops = { .owner = THIS_MODULE, .open = seq_contrstats_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; // /proc/capi/applications: // applid l3cnt dblkcnt dblklen #ncci recvqueuelen // /proc/capi/applstats: // applid nrecvctlpkt nrecvdatapkt nsentctlpkt nsentdatapkt // --------------------------------------------------------------------------- static void *applications_start(struct seq_file *seq, loff_t *pos) __acquires(capi_controller_lock) { mutex_lock(&capi_controller_lock); if (*pos < CAPI_MAXAPPL) return &capi_applications[*pos]; return NULL; } static void * applications_next(struct seq_file *seq, void *v, loff_t *pos) { ++*pos; if (*pos < CAPI_MAXAPPL) return &capi_applications[*pos]; return NULL; } static void applications_stop(struct seq_file *seq, void *v) __releases(capi_controller_lock) { mutex_unlock(&capi_controller_lock); } static int applications_show(struct seq_file *seq, void *v) { struct capi20_appl *ap = *(struct capi20_appl **) v; if (!ap) return 0; seq_printf(seq, "%u %d %d %d\n", ap->applid, ap->rparam.level3cnt, ap->rparam.datablkcnt, ap->rparam.datablklen); return 0; } static int applstats_show(struct seq_file *seq, void *v) { struct capi20_appl *ap = *(struct capi20_appl **) v; if (!ap) return 0; seq_printf(seq, "%u %lu %lu %lu %lu\n", ap->applid, ap->nrecvctlpkt, ap->nrecvdatapkt, ap->nsentctlpkt, ap->nsentdatapkt); return 0; } static const struct seq_operations seq_applications_ops = { .start = applications_start, .next = applications_next, .stop = applications_stop, .show = applications_show, }; static const struct seq_operations seq_applstats_ops = { .start = applications_start, .next = applications_next, .stop = applications_stop, .show = applstats_show, }; static int seq_applications_open(struct inode *inode, struct file *file) { return seq_open(file, &seq_applications_ops); } static int seq_applstats_open(struct inode *inode, struct file *file) { return seq_open(file, &seq_applstats_ops); } static const struct file_operations proc_applications_ops = { .owner = THIS_MODULE, .open = seq_applications_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static const struct file_operations proc_applstats_ops = { .owner = THIS_MODULE, .open = seq_applstats_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; // --------------------------------------------------------------------------- static void *capi_driver_start(struct seq_file *seq, loff_t *pos) __acquires(&capi_drivers_lock) { mutex_lock(&capi_drivers_lock); return seq_list_start(&capi_drivers, *pos); } static void *capi_driver_next(struct seq_file *seq, void *v, loff_t *pos) { return seq_list_next(v, &capi_drivers, pos); } static void capi_driver_stop(struct seq_file *seq, void *v) __releases(&capi_drivers_lock) { mutex_unlock(&capi_drivers_lock); } static int capi_driver_show(struct seq_file *seq, void *v) { struct capi_driver *drv = list_entry(v, struct capi_driver, list); seq_printf(seq, "%-32s %s\n", drv->name, drv->revision); return 0; } static const struct seq_operations seq_capi_driver_ops = { .start = capi_driver_start, .next = capi_driver_next, .stop = capi_driver_stop, .show = capi_driver_show, }; static int seq_capi_driver_open(struct inode *inode, struct file *file) { int err; err = seq_open(file, &seq_capi_driver_ops); return err; } static const struct file_operations proc_driver_ops = { .owner = THIS_MODULE, .open = seq_capi_driver_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; // --------------------------------------------------------------------------- void __init kcapi_proc_init(void) { proc_mkdir("capi", NULL); proc_mkdir("capi/controllers", NULL); proc_create("capi/controller", 0, NULL, &proc_controller_ops); proc_create("capi/contrstats", 0, NULL, &proc_contrstats_ops); proc_create("capi/applications", 0, NULL, &proc_applications_ops); proc_create("capi/applstats", 0, NULL, &proc_applstats_ops); proc_create("capi/driver", 0, NULL, &proc_driver_ops); } void __exit kcapi_proc_exit(void) { remove_proc_entry("capi/driver", NULL); remove_proc_entry("capi/controller", NULL); remove_proc_entry("capi/contrstats", NULL); remove_proc_entry("capi/applications", NULL); remove_proc_entry("capi/applstats", NULL); remove_proc_entry("capi/controllers", NULL); remove_proc_entry("capi", NULL); }
gpl-2.0
haoyangw/android_kernel_xiaomi_dior
arch/ia64/kernel/sal.c
14029
10741
/* * System Abstraction Layer (SAL) interface routines. * * Copyright (C) 1998, 1999, 2001, 2003 Hewlett-Packard Co * David Mosberger-Tang <davidm@hpl.hp.com> * Copyright (C) 1999 VA Linux Systems * Copyright (C) 1999 Walt Drummond <drummond@valinux.com> */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/module.h> #include <linux/spinlock.h> #include <linux/string.h> #include <asm/delay.h> #include <asm/page.h> #include <asm/sal.h> #include <asm/pal.h> __cacheline_aligned DEFINE_SPINLOCK(sal_lock); unsigned long sal_platform_features; unsigned short sal_revision; unsigned short sal_version; #define SAL_MAJOR(x) ((x) >> 8) #define SAL_MINOR(x) ((x) & 0xff) static struct { void *addr; /* function entry point */ void *gpval; /* gp value to use */ } pdesc; static long default_handler (void) { return -1; } ia64_sal_handler ia64_sal = (ia64_sal_handler) default_handler; ia64_sal_desc_ptc_t *ia64_ptc_domain_info; const char * ia64_sal_strerror (long status) { const char *str; switch (status) { case 0: str = "Call completed without error"; break; case 1: str = "Effect a warm boot of the system to complete " "the update"; break; case -1: str = "Not implemented"; break; case -2: str = "Invalid argument"; break; case -3: str = "Call completed with error"; break; case -4: str = "Virtual address not registered"; break; case -5: str = "No information available"; break; case -6: str = "Insufficient space to add the entry"; break; case -7: str = "Invalid entry_addr value"; break; case -8: str = "Invalid interrupt vector"; break; case -9: str = "Requested memory not available"; break; case -10: str = "Unable to write to the NVM device"; break; case -11: str = "Invalid partition type specified"; break; case -12: str = "Invalid NVM_Object id specified"; break; case -13: str = "NVM_Object already has the maximum number " "of partitions"; break; case -14: str = "Insufficient space in partition for the " "requested write sub-function"; break; case -15: str = "Insufficient data buffer space for the " "requested read record sub-function"; break; case -16: str = "Scratch buffer required for the write/delete " "sub-function"; break; case -17: str = "Insufficient space in the NVM_Object for the " "requested create sub-function"; break; case -18: str = "Invalid value specified in the partition_rec " "argument"; break; case -19: str = "Record oriented I/O not supported for this " "partition"; break; case -20: str = "Bad format of record to be written or " "required keyword variable not " "specified"; break; default: str = "Unknown SAL status code"; break; } return str; } void __init ia64_sal_handler_init (void *entry_point, void *gpval) { /* fill in the SAL procedure descriptor and point ia64_sal to it: */ pdesc.addr = entry_point; pdesc.gpval = gpval; ia64_sal = (ia64_sal_handler) &pdesc; } static void __init check_versions (struct ia64_sal_systab *systab) { sal_revision = (systab->sal_rev_major << 8) | systab->sal_rev_minor; sal_version = (systab->sal_b_rev_major << 8) | systab->sal_b_rev_minor; /* Check for broken firmware */ if ((sal_revision == SAL_VERSION_CODE(49, 29)) && (sal_version == SAL_VERSION_CODE(49, 29))) { /* * Old firmware for zx2000 prototypes have this weird version number, * reset it to something sane. */ sal_revision = SAL_VERSION_CODE(2, 8); sal_version = SAL_VERSION_CODE(0, 0); } if (ia64_platform_is("sn2") && (sal_revision == SAL_VERSION_CODE(2, 9))) /* * SGI Altix has hard-coded version 2.9 in their prom * but they actually implement 3.2, so let's fix it here. */ sal_revision = SAL_VERSION_CODE(3, 2); } static void __init sal_desc_entry_point (void *p) { struct ia64_sal_desc_entry_point *ep = p; ia64_pal_handler_init(__va(ep->pal_proc)); ia64_sal_handler_init(__va(ep->sal_proc), __va(ep->gp)); } #ifdef CONFIG_SMP static void __init set_smp_redirect (int flag) { #ifndef CONFIG_HOTPLUG_CPU if (no_int_routing) smp_int_redirect &= ~flag; else smp_int_redirect |= flag; #else /* * For CPU Hotplug we dont want to do any chipset supported * interrupt redirection. The reason is this would require that * All interrupts be stopped and hard bind the irq to a cpu. * Later when the interrupt is fired we need to set the redir hint * on again in the vector. This is cumbersome for something that the * user mode irq balancer will solve anyways. */ no_int_routing=1; smp_int_redirect &= ~flag; #endif } #else #define set_smp_redirect(flag) do { } while (0) #endif static void __init sal_desc_platform_feature (void *p) { struct ia64_sal_desc_platform_feature *pf = p; sal_platform_features = pf->feature_mask; printk(KERN_INFO "SAL Platform features:"); if (!sal_platform_features) { printk(" None\n"); return; } if (sal_platform_features & IA64_SAL_PLATFORM_FEATURE_BUS_LOCK) printk(" BusLock"); if (sal_platform_features & IA64_SAL_PLATFORM_FEATURE_IRQ_REDIR_HINT) { printk(" IRQ_Redirection"); set_smp_redirect(SMP_IRQ_REDIRECTION); } if (sal_platform_features & IA64_SAL_PLATFORM_FEATURE_IPI_REDIR_HINT) { printk(" IPI_Redirection"); set_smp_redirect(SMP_IPI_REDIRECTION); } if (sal_platform_features & IA64_SAL_PLATFORM_FEATURE_ITC_DRIFT) printk(" ITC_Drift"); printk("\n"); } #ifdef CONFIG_SMP static void __init sal_desc_ap_wakeup (void *p) { struct ia64_sal_desc_ap_wakeup *ap = p; switch (ap->mechanism) { case IA64_SAL_AP_EXTERNAL_INT: ap_wakeup_vector = ap->vector; printk(KERN_INFO "SAL: AP wakeup using external interrupt " "vector 0x%lx\n", ap_wakeup_vector); break; default: printk(KERN_ERR "SAL: AP wakeup mechanism unsupported!\n"); break; } } static void __init chk_nointroute_opt(void) { char *cp; for (cp = boot_command_line; *cp; ) { if (memcmp(cp, "nointroute", 10) == 0) { no_int_routing = 1; printk ("no_int_routing on\n"); break; } else { while (*cp != ' ' && *cp) ++cp; while (*cp == ' ') ++cp; } } } #else static void __init sal_desc_ap_wakeup(void *p) { } #endif /* * HP rx5670 firmware polls for interrupts during SAL_CACHE_FLUSH by reading * cr.ivr, but it never writes cr.eoi. This leaves any interrupt marked as * "in-service" and masks other interrupts of equal or lower priority. * * HP internal defect reports: F1859, F2775, F3031. */ static int sal_cache_flush_drops_interrupts; static int __init force_pal_cache_flush(char *str) { sal_cache_flush_drops_interrupts = 1; return 0; } early_param("force_pal_cache_flush", force_pal_cache_flush); void __init check_sal_cache_flush (void) { unsigned long flags; int cpu; u64 vector, cache_type = 3; struct ia64_sal_retval isrv; if (sal_cache_flush_drops_interrupts) return; cpu = get_cpu(); local_irq_save(flags); /* * Send ourselves a timer interrupt, wait until it's reported, and see * if SAL_CACHE_FLUSH drops it. */ platform_send_ipi(cpu, IA64_TIMER_VECTOR, IA64_IPI_DM_INT, 0); while (!ia64_get_irr(IA64_TIMER_VECTOR)) cpu_relax(); SAL_CALL(isrv, SAL_CACHE_FLUSH, cache_type, 0, 0, 0, 0, 0, 0); if (isrv.status) printk(KERN_ERR "SAL_CAL_FLUSH failed with %ld\n", isrv.status); if (ia64_get_irr(IA64_TIMER_VECTOR)) { vector = ia64_get_ivr(); ia64_eoi(); WARN_ON(vector != IA64_TIMER_VECTOR); } else { sal_cache_flush_drops_interrupts = 1; printk(KERN_ERR "SAL: SAL_CACHE_FLUSH drops interrupts; " "PAL_CACHE_FLUSH will be used instead\n"); ia64_eoi(); } local_irq_restore(flags); put_cpu(); } s64 ia64_sal_cache_flush (u64 cache_type) { struct ia64_sal_retval isrv; if (sal_cache_flush_drops_interrupts) { unsigned long flags; u64 progress; s64 rc; progress = 0; local_irq_save(flags); rc = ia64_pal_cache_flush(cache_type, PAL_CACHE_FLUSH_INVALIDATE, &progress, NULL); local_irq_restore(flags); return rc; } SAL_CALL(isrv, SAL_CACHE_FLUSH, cache_type, 0, 0, 0, 0, 0, 0); return isrv.status; } EXPORT_SYMBOL_GPL(ia64_sal_cache_flush); void __init ia64_sal_init (struct ia64_sal_systab *systab) { char *p; int i; if (!systab) { printk(KERN_WARNING "Hmm, no SAL System Table.\n"); return; } if (strncmp(systab->signature, "SST_", 4) != 0) printk(KERN_ERR "bad signature in system table!"); check_versions(systab); #ifdef CONFIG_SMP chk_nointroute_opt(); #endif /* revisions are coded in BCD, so %x does the job for us */ printk(KERN_INFO "SAL %x.%x: %.32s %.32s%sversion %x.%x\n", SAL_MAJOR(sal_revision), SAL_MINOR(sal_revision), systab->oem_id, systab->product_id, systab->product_id[0] ? " " : "", SAL_MAJOR(sal_version), SAL_MINOR(sal_version)); p = (char *) (systab + 1); for (i = 0; i < systab->entry_count; i++) { /* * The first byte of each entry type contains the type * descriptor. */ switch (*p) { case SAL_DESC_ENTRY_POINT: sal_desc_entry_point(p); break; case SAL_DESC_PLATFORM_FEATURE: sal_desc_platform_feature(p); break; case SAL_DESC_PTC: ia64_ptc_domain_info = (ia64_sal_desc_ptc_t *)p; break; case SAL_DESC_AP_WAKEUP: sal_desc_ap_wakeup(p); break; } p += SAL_DESC_SIZE(*p); } } int ia64_sal_oemcall(struct ia64_sal_retval *isrvp, u64 oemfunc, u64 arg1, u64 arg2, u64 arg3, u64 arg4, u64 arg5, u64 arg6, u64 arg7) { if (oemfunc < IA64_SAL_OEMFUNC_MIN || oemfunc > IA64_SAL_OEMFUNC_MAX) return -1; SAL_CALL(*isrvp, oemfunc, arg1, arg2, arg3, arg4, arg5, arg6, arg7); return 0; } EXPORT_SYMBOL(ia64_sal_oemcall); int ia64_sal_oemcall_nolock(struct ia64_sal_retval *isrvp, u64 oemfunc, u64 arg1, u64 arg2, u64 arg3, u64 arg4, u64 arg5, u64 arg6, u64 arg7) { if (oemfunc < IA64_SAL_OEMFUNC_MIN || oemfunc > IA64_SAL_OEMFUNC_MAX) return -1; SAL_CALL_NOLOCK(*isrvp, oemfunc, arg1, arg2, arg3, arg4, arg5, arg6, arg7); return 0; } EXPORT_SYMBOL(ia64_sal_oemcall_nolock); int ia64_sal_oemcall_reentrant(struct ia64_sal_retval *isrvp, u64 oemfunc, u64 arg1, u64 arg2, u64 arg3, u64 arg4, u64 arg5, u64 arg6, u64 arg7) { if (oemfunc < IA64_SAL_OEMFUNC_MIN || oemfunc > IA64_SAL_OEMFUNC_MAX) return -1; SAL_CALL_REENTRANT(*isrvp, oemfunc, arg1, arg2, arg3, arg4, arg5, arg6, arg7); return 0; } EXPORT_SYMBOL(ia64_sal_oemcall_reentrant); long ia64_sal_freq_base (unsigned long which, unsigned long *ticks_per_second, unsigned long *drift_info) { struct ia64_sal_retval isrv; SAL_CALL(isrv, SAL_FREQ_BASE, which, 0, 0, 0, 0, 0, 0); *ticks_per_second = isrv.v0; *drift_info = isrv.v1; return isrv.status; } EXPORT_SYMBOL_GPL(ia64_sal_freq_base);
gpl-2.0
wwenigma/cocktail-kernel-msm7x30
drivers/scsi/fnic/fnic_res.c
14541
12229
/* * Copyright 2008 Cisco Systems, Inc. All rights reserved. * Copyright 2007 Nuova Systems, Inc. All rights reserved. * * This program is free software; you may 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. * * 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/errno.h> #include <linux/types.h> #include <linux/pci.h> #include "wq_enet_desc.h" #include "rq_enet_desc.h" #include "cq_enet_desc.h" #include "vnic_resource.h" #include "vnic_dev.h" #include "vnic_wq.h" #include "vnic_rq.h" #include "vnic_cq.h" #include "vnic_intr.h" #include "vnic_stats.h" #include "vnic_nic.h" #include "fnic.h" int fnic_get_vnic_config(struct fnic *fnic) { struct vnic_fc_config *c = &fnic->config; int err; #define GET_CONFIG(m) \ do { \ err = vnic_dev_spec(fnic->vdev, \ offsetof(struct vnic_fc_config, m), \ sizeof(c->m), &c->m); \ if (err) { \ shost_printk(KERN_ERR, fnic->lport->host, \ "Error getting %s, %d\n", #m, \ err); \ return err; \ } \ } while (0); GET_CONFIG(node_wwn); GET_CONFIG(port_wwn); GET_CONFIG(wq_enet_desc_count); GET_CONFIG(wq_copy_desc_count); GET_CONFIG(rq_desc_count); GET_CONFIG(maxdatafieldsize); GET_CONFIG(ed_tov); GET_CONFIG(ra_tov); GET_CONFIG(intr_timer); GET_CONFIG(intr_timer_type); GET_CONFIG(flags); GET_CONFIG(flogi_retries); GET_CONFIG(flogi_timeout); GET_CONFIG(plogi_retries); GET_CONFIG(plogi_timeout); GET_CONFIG(io_throttle_count); GET_CONFIG(link_down_timeout); GET_CONFIG(port_down_timeout); GET_CONFIG(port_down_io_retries); GET_CONFIG(luns_per_tgt); c->wq_enet_desc_count = min_t(u32, VNIC_FNIC_WQ_DESCS_MAX, max_t(u32, VNIC_FNIC_WQ_DESCS_MIN, c->wq_enet_desc_count)); c->wq_enet_desc_count = ALIGN(c->wq_enet_desc_count, 16); c->wq_copy_desc_count = min_t(u32, VNIC_FNIC_WQ_COPY_DESCS_MAX, max_t(u32, VNIC_FNIC_WQ_COPY_DESCS_MIN, c->wq_copy_desc_count)); c->wq_copy_desc_count = ALIGN(c->wq_copy_desc_count, 16); c->rq_desc_count = min_t(u32, VNIC_FNIC_RQ_DESCS_MAX, max_t(u32, VNIC_FNIC_RQ_DESCS_MIN, c->rq_desc_count)); c->rq_desc_count = ALIGN(c->rq_desc_count, 16); c->maxdatafieldsize = min_t(u16, VNIC_FNIC_MAXDATAFIELDSIZE_MAX, max_t(u16, VNIC_FNIC_MAXDATAFIELDSIZE_MIN, c->maxdatafieldsize)); c->ed_tov = min_t(u32, VNIC_FNIC_EDTOV_MAX, max_t(u32, VNIC_FNIC_EDTOV_MIN, c->ed_tov)); c->ra_tov = min_t(u32, VNIC_FNIC_RATOV_MAX, max_t(u32, VNIC_FNIC_RATOV_MIN, c->ra_tov)); c->flogi_retries = min_t(u32, VNIC_FNIC_FLOGI_RETRIES_MAX, c->flogi_retries); c->flogi_timeout = min_t(u32, VNIC_FNIC_FLOGI_TIMEOUT_MAX, max_t(u32, VNIC_FNIC_FLOGI_TIMEOUT_MIN, c->flogi_timeout)); c->plogi_retries = min_t(u32, VNIC_FNIC_PLOGI_RETRIES_MAX, c->plogi_retries); c->plogi_timeout = min_t(u32, VNIC_FNIC_PLOGI_TIMEOUT_MAX, max_t(u32, VNIC_FNIC_PLOGI_TIMEOUT_MIN, c->plogi_timeout)); c->io_throttle_count = min_t(u32, VNIC_FNIC_IO_THROTTLE_COUNT_MAX, max_t(u32, VNIC_FNIC_IO_THROTTLE_COUNT_MIN, c->io_throttle_count)); c->link_down_timeout = min_t(u32, VNIC_FNIC_LINK_DOWN_TIMEOUT_MAX, c->link_down_timeout); c->port_down_timeout = min_t(u32, VNIC_FNIC_PORT_DOWN_TIMEOUT_MAX, c->port_down_timeout); c->port_down_io_retries = min_t(u32, VNIC_FNIC_PORT_DOWN_IO_RETRIES_MAX, c->port_down_io_retries); c->luns_per_tgt = min_t(u32, VNIC_FNIC_LUNS_PER_TARGET_MAX, max_t(u32, VNIC_FNIC_LUNS_PER_TARGET_MIN, c->luns_per_tgt)); c->intr_timer = min_t(u16, VNIC_INTR_TIMER_MAX, c->intr_timer); c->intr_timer_type = c->intr_timer_type; shost_printk(KERN_INFO, fnic->lport->host, "vNIC MAC addr %pM " "wq/wq_copy/rq %d/%d/%d\n", fnic->ctlr.ctl_src_addr, c->wq_enet_desc_count, c->wq_copy_desc_count, c->rq_desc_count); shost_printk(KERN_INFO, fnic->lport->host, "vNIC node wwn %llx port wwn %llx\n", c->node_wwn, c->port_wwn); shost_printk(KERN_INFO, fnic->lport->host, "vNIC ed_tov %d ra_tov %d\n", c->ed_tov, c->ra_tov); shost_printk(KERN_INFO, fnic->lport->host, "vNIC mtu %d intr timer %d\n", c->maxdatafieldsize, c->intr_timer); shost_printk(KERN_INFO, fnic->lport->host, "vNIC flags 0x%x luns per tgt %d\n", c->flags, c->luns_per_tgt); shost_printk(KERN_INFO, fnic->lport->host, "vNIC flogi_retries %d flogi timeout %d\n", c->flogi_retries, c->flogi_timeout); shost_printk(KERN_INFO, fnic->lport->host, "vNIC plogi retries %d plogi timeout %d\n", c->plogi_retries, c->plogi_timeout); shost_printk(KERN_INFO, fnic->lport->host, "vNIC io throttle count %d link dn timeout %d\n", c->io_throttle_count, c->link_down_timeout); shost_printk(KERN_INFO, fnic->lport->host, "vNIC port dn io retries %d port dn timeout %d\n", c->port_down_io_retries, c->port_down_timeout); return 0; } int fnic_set_nic_config(struct fnic *fnic, u8 rss_default_cpu, u8 rss_hash_type, u8 rss_hash_bits, u8 rss_base_cpu, u8 rss_enable, u8 tso_ipid_split_en, u8 ig_vlan_strip_en) { u64 a0, a1; u32 nic_cfg; int wait = 1000; vnic_set_nic_cfg(&nic_cfg, rss_default_cpu, rss_hash_type, rss_hash_bits, rss_base_cpu, rss_enable, tso_ipid_split_en, ig_vlan_strip_en); a0 = nic_cfg; a1 = 0; return vnic_dev_cmd(fnic->vdev, CMD_NIC_CFG, &a0, &a1, wait); } void fnic_get_res_counts(struct fnic *fnic) { fnic->wq_count = vnic_dev_get_res_count(fnic->vdev, RES_TYPE_WQ); fnic->raw_wq_count = fnic->wq_count - 1; fnic->wq_copy_count = fnic->wq_count - fnic->raw_wq_count; fnic->rq_count = vnic_dev_get_res_count(fnic->vdev, RES_TYPE_RQ); fnic->cq_count = vnic_dev_get_res_count(fnic->vdev, RES_TYPE_CQ); fnic->intr_count = vnic_dev_get_res_count(fnic->vdev, RES_TYPE_INTR_CTRL); } void fnic_free_vnic_resources(struct fnic *fnic) { unsigned int i; for (i = 0; i < fnic->raw_wq_count; i++) vnic_wq_free(&fnic->wq[i]); for (i = 0; i < fnic->wq_copy_count; i++) vnic_wq_copy_free(&fnic->wq_copy[i]); for (i = 0; i < fnic->rq_count; i++) vnic_rq_free(&fnic->rq[i]); for (i = 0; i < fnic->cq_count; i++) vnic_cq_free(&fnic->cq[i]); for (i = 0; i < fnic->intr_count; i++) vnic_intr_free(&fnic->intr[i]); } int fnic_alloc_vnic_resources(struct fnic *fnic) { enum vnic_dev_intr_mode intr_mode; unsigned int mask_on_assertion; unsigned int interrupt_offset; unsigned int error_interrupt_enable; unsigned int error_interrupt_offset; unsigned int i, cq_index; unsigned int wq_copy_cq_desc_count; int err; intr_mode = vnic_dev_get_intr_mode(fnic->vdev); shost_printk(KERN_INFO, fnic->lport->host, "vNIC interrupt mode: %s\n", intr_mode == VNIC_DEV_INTR_MODE_INTX ? "legacy PCI INTx" : intr_mode == VNIC_DEV_INTR_MODE_MSI ? "MSI" : intr_mode == VNIC_DEV_INTR_MODE_MSIX ? "MSI-X" : "unknown"); shost_printk(KERN_INFO, fnic->lport->host, "vNIC resources avail: " "wq %d cp_wq %d raw_wq %d rq %d cq %d intr %d\n", fnic->wq_count, fnic->wq_copy_count, fnic->raw_wq_count, fnic->rq_count, fnic->cq_count, fnic->intr_count); /* Allocate Raw WQ used for FCS frames */ for (i = 0; i < fnic->raw_wq_count; i++) { err = vnic_wq_alloc(fnic->vdev, &fnic->wq[i], i, fnic->config.wq_enet_desc_count, sizeof(struct wq_enet_desc)); if (err) goto err_out_cleanup; } /* Allocate Copy WQs used for SCSI IOs */ for (i = 0; i < fnic->wq_copy_count; i++) { err = vnic_wq_copy_alloc(fnic->vdev, &fnic->wq_copy[i], (fnic->raw_wq_count + i), fnic->config.wq_copy_desc_count, sizeof(struct fcpio_host_req)); if (err) goto err_out_cleanup; } /* RQ for receiving FCS frames */ for (i = 0; i < fnic->rq_count; i++) { err = vnic_rq_alloc(fnic->vdev, &fnic->rq[i], i, fnic->config.rq_desc_count, sizeof(struct rq_enet_desc)); if (err) goto err_out_cleanup; } /* CQ for each RQ */ for (i = 0; i < fnic->rq_count; i++) { cq_index = i; err = vnic_cq_alloc(fnic->vdev, &fnic->cq[cq_index], cq_index, fnic->config.rq_desc_count, sizeof(struct cq_enet_rq_desc)); if (err) goto err_out_cleanup; } /* CQ for each WQ */ for (i = 0; i < fnic->raw_wq_count; i++) { cq_index = fnic->rq_count + i; err = vnic_cq_alloc(fnic->vdev, &fnic->cq[cq_index], cq_index, fnic->config.wq_enet_desc_count, sizeof(struct cq_enet_wq_desc)); if (err) goto err_out_cleanup; } /* CQ for each COPY WQ */ wq_copy_cq_desc_count = (fnic->config.wq_copy_desc_count * 3); for (i = 0; i < fnic->wq_copy_count; i++) { cq_index = fnic->raw_wq_count + fnic->rq_count + i; err = vnic_cq_alloc(fnic->vdev, &fnic->cq[cq_index], cq_index, wq_copy_cq_desc_count, sizeof(struct fcpio_fw_req)); if (err) goto err_out_cleanup; } for (i = 0; i < fnic->intr_count; i++) { err = vnic_intr_alloc(fnic->vdev, &fnic->intr[i], i); if (err) goto err_out_cleanup; } fnic->legacy_pba = vnic_dev_get_res(fnic->vdev, RES_TYPE_INTR_PBA_LEGACY, 0); if (!fnic->legacy_pba && intr_mode == VNIC_DEV_INTR_MODE_INTX) { shost_printk(KERN_ERR, fnic->lport->host, "Failed to hook legacy pba resource\n"); err = -ENODEV; goto err_out_cleanup; } /* * Init RQ/WQ resources. * * RQ[0 to n-1] point to CQ[0 to n-1] * WQ[0 to m-1] point to CQ[n to n+m-1] * WQ_COPY[0 to k-1] points to CQ[n+m to n+m+k-1] * * Note for copy wq we always initialize with cq_index = 0 * * Error interrupt is not enabled for MSI. */ switch (intr_mode) { case VNIC_DEV_INTR_MODE_INTX: case VNIC_DEV_INTR_MODE_MSIX: error_interrupt_enable = 1; error_interrupt_offset = fnic->err_intr_offset; break; default: error_interrupt_enable = 0; error_interrupt_offset = 0; break; } for (i = 0; i < fnic->rq_count; i++) { cq_index = i; vnic_rq_init(&fnic->rq[i], cq_index, error_interrupt_enable, error_interrupt_offset); } for (i = 0; i < fnic->raw_wq_count; i++) { cq_index = i + fnic->rq_count; vnic_wq_init(&fnic->wq[i], cq_index, error_interrupt_enable, error_interrupt_offset); } for (i = 0; i < fnic->wq_copy_count; i++) { vnic_wq_copy_init(&fnic->wq_copy[i], 0 /* cq_index 0 - always */, error_interrupt_enable, error_interrupt_offset); } for (i = 0; i < fnic->cq_count; i++) { switch (intr_mode) { case VNIC_DEV_INTR_MODE_MSIX: interrupt_offset = i; break; default: interrupt_offset = 0; break; } vnic_cq_init(&fnic->cq[i], 0 /* flow_control_enable */, 1 /* color_enable */, 0 /* cq_head */, 0 /* cq_tail */, 1 /* cq_tail_color */, 1 /* interrupt_enable */, 1 /* cq_entry_enable */, 0 /* cq_message_enable */, interrupt_offset, 0 /* cq_message_addr */); } /* * Init INTR resources * * mask_on_assertion is not used for INTx due to the level- * triggered nature of INTx */ switch (intr_mode) { case VNIC_DEV_INTR_MODE_MSI: case VNIC_DEV_INTR_MODE_MSIX: mask_on_assertion = 1; break; default: mask_on_assertion = 0; break; } for (i = 0; i < fnic->intr_count; i++) { vnic_intr_init(&fnic->intr[i], fnic->config.intr_timer, fnic->config.intr_timer_type, mask_on_assertion); } /* init the stats memory by making the first call here */ err = vnic_dev_stats_dump(fnic->vdev, &fnic->stats); if (err) { shost_printk(KERN_ERR, fnic->lport->host, "vnic_dev_stats_dump failed - x%x\n", err); goto err_out_cleanup; } /* Clear LIF stats */ vnic_dev_stats_clear(fnic->vdev); return 0; err_out_cleanup: fnic_free_vnic_resources(fnic); return err; }
gpl-2.0
jemmy655/linux
net/llc/llc_c_ev.c
15053
21776
/* * llc_c_ev.c - Connection component state transition event qualifiers * * A 'state' consists of a number of possible event matching functions, * the actions associated with each being executed when that event is * matched; a 'state machine' accepts events in a serial fashion from an * event queue. Each event is passed to each successive event matching * function until a match is made (the event matching function returns * success, or '0') or the list of event matching functions is exhausted. * If a match is made, the actions associated with the event are executed * and the state is changed to that event's transition state. Before some * events are recognized, even after a match has been made, a certain * number of 'event qualifier' functions must also be executed. If these * all execute successfully, then the event is finally executed. * * These event functions must return 0 for success, to show a matched * event, of 1 if the event does not match. Event qualifier functions * must return a 0 for success or a non-zero for failure. Each function * is simply responsible for verifying one single thing and returning * either a success or failure. * * All of followed event functions are described in 802.2 LLC Protocol * standard document except two functions that we added that will explain * in their comments, at below. * * Copyright (c) 1997 by Procom Technology, Inc. * 2001-2003 by Arnaldo Carvalho de Melo <acme@conectiva.com.br> * * This program can be redistributed or modified under the terms of the * GNU General Public License as published by the Free Software Foundation. * This program is distributed without any warranty or implied warranty * of merchantability or fitness for a particular purpose. * * See the GNU General Public License for more details. */ #include <linux/netdevice.h> #include <net/llc_conn.h> #include <net/llc_sap.h> #include <net/sock.h> #include <net/llc_c_ac.h> #include <net/llc_c_ev.h> #include <net/llc_pdu.h> #if 1 #define dprintk(args...) printk(KERN_DEBUG args) #else #define dprintk(args...) #endif /** * llc_util_ns_inside_rx_window - check if sequence number is in rx window * @ns: sequence number of received pdu. * @vr: sequence number which receiver expects to receive. * @rw: receive window size of receiver. * * Checks if sequence number of received PDU is in range of receive * window. Returns 0 for success, 1 otherwise */ static u16 llc_util_ns_inside_rx_window(u8 ns, u8 vr, u8 rw) { return !llc_circular_between(vr, ns, (vr + rw - 1) % LLC_2_SEQ_NBR_MODULO); } /** * llc_util_nr_inside_tx_window - check if sequence number is in tx window * @sk: current connection. * @nr: N(R) of received PDU. * * This routine checks if N(R) of received PDU is in range of transmit * window; on the other hand checks if received PDU acknowledges some * outstanding PDUs that are in transmit window. Returns 0 for success, 1 * otherwise. */ static u16 llc_util_nr_inside_tx_window(struct sock *sk, u8 nr) { u8 nr1, nr2; struct sk_buff *skb; struct llc_pdu_sn *pdu; struct llc_sock *llc = llc_sk(sk); int rc = 0; if (llc->dev->flags & IFF_LOOPBACK) goto out; rc = 1; if (skb_queue_empty(&llc->pdu_unack_q)) goto out; skb = skb_peek(&llc->pdu_unack_q); pdu = llc_pdu_sn_hdr(skb); nr1 = LLC_I_GET_NS(pdu); skb = skb_peek_tail(&llc->pdu_unack_q); pdu = llc_pdu_sn_hdr(skb); nr2 = LLC_I_GET_NS(pdu); rc = !llc_circular_between(nr1, nr, (nr2 + 1) % LLC_2_SEQ_NBR_MODULO); out: return rc; } int llc_conn_ev_conn_req(struct sock *sk, struct sk_buff *skb) { const struct llc_conn_state_ev *ev = llc_conn_ev(skb); return ev->prim == LLC_CONN_PRIM && ev->prim_type == LLC_PRIM_TYPE_REQ ? 0 : 1; } int llc_conn_ev_data_req(struct sock *sk, struct sk_buff *skb) { const struct llc_conn_state_ev *ev = llc_conn_ev(skb); return ev->prim == LLC_DATA_PRIM && ev->prim_type == LLC_PRIM_TYPE_REQ ? 0 : 1; } int llc_conn_ev_disc_req(struct sock *sk, struct sk_buff *skb) { const struct llc_conn_state_ev *ev = llc_conn_ev(skb); return ev->prim == LLC_DISC_PRIM && ev->prim_type == LLC_PRIM_TYPE_REQ ? 0 : 1; } int llc_conn_ev_rst_req(struct sock *sk, struct sk_buff *skb) { const struct llc_conn_state_ev *ev = llc_conn_ev(skb); return ev->prim == LLC_RESET_PRIM && ev->prim_type == LLC_PRIM_TYPE_REQ ? 0 : 1; } int llc_conn_ev_local_busy_detected(struct sock *sk, struct sk_buff *skb) { const struct llc_conn_state_ev *ev = llc_conn_ev(skb); return ev->type == LLC_CONN_EV_TYPE_SIMPLE && ev->prim_type == LLC_CONN_EV_LOCAL_BUSY_DETECTED ? 0 : 1; } int llc_conn_ev_local_busy_cleared(struct sock *sk, struct sk_buff *skb) { const struct llc_conn_state_ev *ev = llc_conn_ev(skb); return ev->type == LLC_CONN_EV_TYPE_SIMPLE && ev->prim_type == LLC_CONN_EV_LOCAL_BUSY_CLEARED ? 0 : 1; } int llc_conn_ev_rx_bad_pdu(struct sock *sk, struct sk_buff *skb) { return 1; } int llc_conn_ev_rx_disc_cmd_pbit_set_x(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb); return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_U(pdu) && LLC_U_PDU_CMD(pdu) == LLC_2_PDU_CMD_DISC ? 0 : 1; } int llc_conn_ev_rx_dm_rsp_fbit_set_x(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb); return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_U(pdu) && LLC_U_PDU_RSP(pdu) == LLC_2_PDU_RSP_DM ? 0 : 1; } int llc_conn_ev_rx_frmr_rsp_fbit_set_x(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb); return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_U(pdu) && LLC_U_PDU_RSP(pdu) == LLC_2_PDU_RSP_FRMR ? 0 : 1; } int llc_conn_ev_rx_i_cmd_pbit_set_0(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb); return llc_conn_space(sk, skb) && LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_I(pdu) && LLC_I_PF_IS_0(pdu) && LLC_I_GET_NS(pdu) == llc_sk(sk)->vR ? 0 : 1; } int llc_conn_ev_rx_i_cmd_pbit_set_1(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb); return llc_conn_space(sk, skb) && LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_I(pdu) && LLC_I_PF_IS_1(pdu) && LLC_I_GET_NS(pdu) == llc_sk(sk)->vR ? 0 : 1; } int llc_conn_ev_rx_i_cmd_pbit_set_0_unexpd_ns(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb); const u8 vr = llc_sk(sk)->vR; const u8 ns = LLC_I_GET_NS(pdu); return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_I(pdu) && LLC_I_PF_IS_0(pdu) && ns != vr && !llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1; } int llc_conn_ev_rx_i_cmd_pbit_set_1_unexpd_ns(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb); const u8 vr = llc_sk(sk)->vR; const u8 ns = LLC_I_GET_NS(pdu); return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_I(pdu) && LLC_I_PF_IS_1(pdu) && ns != vr && !llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1; } int llc_conn_ev_rx_i_cmd_pbit_set_x_inval_ns(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_sn * pdu = llc_pdu_sn_hdr(skb); const u8 vr = llc_sk(sk)->vR; const u8 ns = LLC_I_GET_NS(pdu); const u16 rc = LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_I(pdu) && ns != vr && llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1; if (!rc) dprintk("%s: matched, state=%d, ns=%d, vr=%d\n", __func__, llc_sk(sk)->state, ns, vr); return rc; } int llc_conn_ev_rx_i_rsp_fbit_set_0(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb); return llc_conn_space(sk, skb) && LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) && LLC_I_PF_IS_0(pdu) && LLC_I_GET_NS(pdu) == llc_sk(sk)->vR ? 0 : 1; } int llc_conn_ev_rx_i_rsp_fbit_set_1(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb); return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) && LLC_I_PF_IS_1(pdu) && LLC_I_GET_NS(pdu) == llc_sk(sk)->vR ? 0 : 1; } int llc_conn_ev_rx_i_rsp_fbit_set_x(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb); return llc_conn_space(sk, skb) && LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) && LLC_I_GET_NS(pdu) == llc_sk(sk)->vR ? 0 : 1; } int llc_conn_ev_rx_i_rsp_fbit_set_0_unexpd_ns(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb); const u8 vr = llc_sk(sk)->vR; const u8 ns = LLC_I_GET_NS(pdu); return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) && LLC_I_PF_IS_0(pdu) && ns != vr && !llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1; } int llc_conn_ev_rx_i_rsp_fbit_set_1_unexpd_ns(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb); const u8 vr = llc_sk(sk)->vR; const u8 ns = LLC_I_GET_NS(pdu); return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) && LLC_I_PF_IS_1(pdu) && ns != vr && !llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1; } int llc_conn_ev_rx_i_rsp_fbit_set_x_unexpd_ns(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb); const u8 vr = llc_sk(sk)->vR; const u8 ns = LLC_I_GET_NS(pdu); return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) && ns != vr && !llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1; } int llc_conn_ev_rx_i_rsp_fbit_set_x_inval_ns(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb); const u8 vr = llc_sk(sk)->vR; const u8 ns = LLC_I_GET_NS(pdu); const u16 rc = LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_I(pdu) && ns != vr && llc_util_ns_inside_rx_window(ns, vr, llc_sk(sk)->rw) ? 0 : 1; if (!rc) dprintk("%s: matched, state=%d, ns=%d, vr=%d\n", __func__, llc_sk(sk)->state, ns, vr); return rc; } int llc_conn_ev_rx_rej_cmd_pbit_set_0(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb); return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_S(pdu) && LLC_S_PF_IS_0(pdu) && LLC_S_PDU_CMD(pdu) == LLC_2_PDU_CMD_REJ ? 0 : 1; } int llc_conn_ev_rx_rej_cmd_pbit_set_1(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb); return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_S(pdu) && LLC_S_PF_IS_1(pdu) && LLC_S_PDU_CMD(pdu) == LLC_2_PDU_CMD_REJ ? 0 : 1; } int llc_conn_ev_rx_rej_rsp_fbit_set_0(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb); return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) && LLC_S_PF_IS_0(pdu) && LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_REJ ? 0 : 1; } int llc_conn_ev_rx_rej_rsp_fbit_set_1(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb); return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) && LLC_S_PF_IS_1(pdu) && LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_REJ ? 0 : 1; } int llc_conn_ev_rx_rej_rsp_fbit_set_x(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb); return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) && LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_REJ ? 0 : 1; } int llc_conn_ev_rx_rnr_cmd_pbit_set_0(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb); return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_S(pdu) && LLC_S_PF_IS_0(pdu) && LLC_S_PDU_CMD(pdu) == LLC_2_PDU_CMD_RNR ? 0 : 1; } int llc_conn_ev_rx_rnr_cmd_pbit_set_1(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb); return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_S(pdu) && LLC_S_PF_IS_1(pdu) && LLC_S_PDU_CMD(pdu) == LLC_2_PDU_CMD_RNR ? 0 : 1; } int llc_conn_ev_rx_rnr_rsp_fbit_set_0(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb); return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) && LLC_S_PF_IS_0(pdu) && LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_RNR ? 0 : 1; } int llc_conn_ev_rx_rnr_rsp_fbit_set_1(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb); return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) && LLC_S_PF_IS_1(pdu) && LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_RNR ? 0 : 1; } int llc_conn_ev_rx_rr_cmd_pbit_set_0(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb); return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_S(pdu) && LLC_S_PF_IS_0(pdu) && LLC_S_PDU_CMD(pdu) == LLC_2_PDU_CMD_RR ? 0 : 1; } int llc_conn_ev_rx_rr_cmd_pbit_set_1(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb); return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_S(pdu) && LLC_S_PF_IS_1(pdu) && LLC_S_PDU_CMD(pdu) == LLC_2_PDU_CMD_RR ? 0 : 1; } int llc_conn_ev_rx_rr_rsp_fbit_set_0(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb); return llc_conn_space(sk, skb) && LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) && LLC_S_PF_IS_0(pdu) && LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_RR ? 0 : 1; } int llc_conn_ev_rx_rr_rsp_fbit_set_1(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb); return llc_conn_space(sk, skb) && LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_S(pdu) && LLC_S_PF_IS_1(pdu) && LLC_S_PDU_RSP(pdu) == LLC_2_PDU_RSP_RR ? 0 : 1; } int llc_conn_ev_rx_sabme_cmd_pbit_set_x(struct sock *sk, struct sk_buff *skb) { const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb); return LLC_PDU_IS_CMD(pdu) && LLC_PDU_TYPE_IS_U(pdu) && LLC_U_PDU_CMD(pdu) == LLC_2_PDU_CMD_SABME ? 0 : 1; } int llc_conn_ev_rx_ua_rsp_fbit_set_x(struct sock *sk, struct sk_buff *skb) { struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb); return LLC_PDU_IS_RSP(pdu) && LLC_PDU_TYPE_IS_U(pdu) && LLC_U_PDU_RSP(pdu) == LLC_2_PDU_RSP_UA ? 0 : 1; } int llc_conn_ev_rx_xxx_cmd_pbit_set_1(struct sock *sk, struct sk_buff *skb) { u16 rc = 1; const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb); if (LLC_PDU_IS_CMD(pdu)) { if (LLC_PDU_TYPE_IS_I(pdu) || LLC_PDU_TYPE_IS_S(pdu)) { if (LLC_I_PF_IS_1(pdu)) rc = 0; } else if (LLC_PDU_TYPE_IS_U(pdu) && LLC_U_PF_IS_1(pdu)) rc = 0; } return rc; } int llc_conn_ev_rx_xxx_cmd_pbit_set_x(struct sock *sk, struct sk_buff *skb) { u16 rc = 1; const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb); if (LLC_PDU_IS_CMD(pdu)) { if (LLC_PDU_TYPE_IS_I(pdu) || LLC_PDU_TYPE_IS_S(pdu)) rc = 0; else if (LLC_PDU_TYPE_IS_U(pdu)) switch (LLC_U_PDU_CMD(pdu)) { case LLC_2_PDU_CMD_SABME: case LLC_2_PDU_CMD_DISC: rc = 0; break; } } return rc; } int llc_conn_ev_rx_xxx_rsp_fbit_set_x(struct sock *sk, struct sk_buff *skb) { u16 rc = 1; const struct llc_pdu_un *pdu = llc_pdu_un_hdr(skb); if (LLC_PDU_IS_RSP(pdu)) { if (LLC_PDU_TYPE_IS_I(pdu) || LLC_PDU_TYPE_IS_S(pdu)) rc = 0; else if (LLC_PDU_TYPE_IS_U(pdu)) switch (LLC_U_PDU_RSP(pdu)) { case LLC_2_PDU_RSP_UA: case LLC_2_PDU_RSP_DM: case LLC_2_PDU_RSP_FRMR: rc = 0; break; } } return rc; } int llc_conn_ev_rx_zzz_cmd_pbit_set_x_inval_nr(struct sock *sk, struct sk_buff *skb) { u16 rc = 1; const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb); const u8 vs = llc_sk(sk)->vS; const u8 nr = LLC_I_GET_NR(pdu); if (LLC_PDU_IS_CMD(pdu) && (LLC_PDU_TYPE_IS_I(pdu) || LLC_PDU_TYPE_IS_S(pdu)) && nr != vs && llc_util_nr_inside_tx_window(sk, nr)) { dprintk("%s: matched, state=%d, vs=%d, nr=%d\n", __func__, llc_sk(sk)->state, vs, nr); rc = 0; } return rc; } int llc_conn_ev_rx_zzz_rsp_fbit_set_x_inval_nr(struct sock *sk, struct sk_buff *skb) { u16 rc = 1; const struct llc_pdu_sn *pdu = llc_pdu_sn_hdr(skb); const u8 vs = llc_sk(sk)->vS; const u8 nr = LLC_I_GET_NR(pdu); if (LLC_PDU_IS_RSP(pdu) && (LLC_PDU_TYPE_IS_I(pdu) || LLC_PDU_TYPE_IS_S(pdu)) && nr != vs && llc_util_nr_inside_tx_window(sk, nr)) { rc = 0; dprintk("%s: matched, state=%d, vs=%d, nr=%d\n", __func__, llc_sk(sk)->state, vs, nr); } return rc; } int llc_conn_ev_rx_any_frame(struct sock *sk, struct sk_buff *skb) { return 0; } int llc_conn_ev_p_tmr_exp(struct sock *sk, struct sk_buff *skb) { const struct llc_conn_state_ev *ev = llc_conn_ev(skb); return ev->type != LLC_CONN_EV_TYPE_P_TMR; } int llc_conn_ev_ack_tmr_exp(struct sock *sk, struct sk_buff *skb) { const struct llc_conn_state_ev *ev = llc_conn_ev(skb); return ev->type != LLC_CONN_EV_TYPE_ACK_TMR; } int llc_conn_ev_rej_tmr_exp(struct sock *sk, struct sk_buff *skb) { const struct llc_conn_state_ev *ev = llc_conn_ev(skb); return ev->type != LLC_CONN_EV_TYPE_REJ_TMR; } int llc_conn_ev_busy_tmr_exp(struct sock *sk, struct sk_buff *skb) { const struct llc_conn_state_ev *ev = llc_conn_ev(skb); return ev->type != LLC_CONN_EV_TYPE_BUSY_TMR; } int llc_conn_ev_init_p_f_cycle(struct sock *sk, struct sk_buff *skb) { return 1; } int llc_conn_ev_tx_buffer_full(struct sock *sk, struct sk_buff *skb) { const struct llc_conn_state_ev *ev = llc_conn_ev(skb); return ev->type == LLC_CONN_EV_TYPE_SIMPLE && ev->prim_type == LLC_CONN_EV_TX_BUFF_FULL ? 0 : 1; } /* Event qualifier functions * * these functions simply verify the value of a state flag associated with * the connection and return either a 0 for success or a non-zero value * for not-success; verify the event is the type we expect */ int llc_conn_ev_qlfy_data_flag_eq_1(struct sock *sk, struct sk_buff *skb) { return llc_sk(sk)->data_flag != 1; } int llc_conn_ev_qlfy_data_flag_eq_0(struct sock *sk, struct sk_buff *skb) { return llc_sk(sk)->data_flag; } int llc_conn_ev_qlfy_data_flag_eq_2(struct sock *sk, struct sk_buff *skb) { return llc_sk(sk)->data_flag != 2; } int llc_conn_ev_qlfy_p_flag_eq_1(struct sock *sk, struct sk_buff *skb) { return llc_sk(sk)->p_flag != 1; } /** * conn_ev_qlfy_last_frame_eq_1 - checks if frame is last in tx window * @sk: current connection structure. * @skb: current event. * * This function determines when frame which is sent, is last frame of * transmit window, if it is then this function return zero else return * one. This function is used for sending last frame of transmit window * as I-format command with p-bit set to one. Returns 0 if frame is last * frame, 1 otherwise. */ int llc_conn_ev_qlfy_last_frame_eq_1(struct sock *sk, struct sk_buff *skb) { return !(skb_queue_len(&llc_sk(sk)->pdu_unack_q) + 1 == llc_sk(sk)->k); } /** * conn_ev_qlfy_last_frame_eq_0 - checks if frame isn't last in tx window * @sk: current connection structure. * @skb: current event. * * This function determines when frame which is sent, isn't last frame of * transmit window, if it isn't then this function return zero else return * one. Returns 0 if frame isn't last frame, 1 otherwise. */ int llc_conn_ev_qlfy_last_frame_eq_0(struct sock *sk, struct sk_buff *skb) { return skb_queue_len(&llc_sk(sk)->pdu_unack_q) + 1 == llc_sk(sk)->k; } int llc_conn_ev_qlfy_p_flag_eq_0(struct sock *sk, struct sk_buff *skb) { return llc_sk(sk)->p_flag; } int llc_conn_ev_qlfy_p_flag_eq_f(struct sock *sk, struct sk_buff *skb) { u8 f_bit; llc_pdu_decode_pf_bit(skb, &f_bit); return llc_sk(sk)->p_flag == f_bit ? 0 : 1; } int llc_conn_ev_qlfy_remote_busy_eq_0(struct sock *sk, struct sk_buff *skb) { return llc_sk(sk)->remote_busy_flag; } int llc_conn_ev_qlfy_remote_busy_eq_1(struct sock *sk, struct sk_buff *skb) { return !llc_sk(sk)->remote_busy_flag; } int llc_conn_ev_qlfy_retry_cnt_lt_n2(struct sock *sk, struct sk_buff *skb) { return !(llc_sk(sk)->retry_count < llc_sk(sk)->n2); } int llc_conn_ev_qlfy_retry_cnt_gte_n2(struct sock *sk, struct sk_buff *skb) { return !(llc_sk(sk)->retry_count >= llc_sk(sk)->n2); } int llc_conn_ev_qlfy_s_flag_eq_1(struct sock *sk, struct sk_buff *skb) { return !llc_sk(sk)->s_flag; } int llc_conn_ev_qlfy_s_flag_eq_0(struct sock *sk, struct sk_buff *skb) { return llc_sk(sk)->s_flag; } int llc_conn_ev_qlfy_cause_flag_eq_1(struct sock *sk, struct sk_buff *skb) { return !llc_sk(sk)->cause_flag; } int llc_conn_ev_qlfy_cause_flag_eq_0(struct sock *sk, struct sk_buff *skb) { return llc_sk(sk)->cause_flag; } int llc_conn_ev_qlfy_set_status_conn(struct sock *sk, struct sk_buff *skb) { struct llc_conn_state_ev *ev = llc_conn_ev(skb); ev->status = LLC_STATUS_CONN; return 0; } int llc_conn_ev_qlfy_set_status_disc(struct sock *sk, struct sk_buff *skb) { struct llc_conn_state_ev *ev = llc_conn_ev(skb); ev->status = LLC_STATUS_DISC; return 0; } int llc_conn_ev_qlfy_set_status_failed(struct sock *sk, struct sk_buff *skb) { struct llc_conn_state_ev *ev = llc_conn_ev(skb); ev->status = LLC_STATUS_FAILED; return 0; } int llc_conn_ev_qlfy_set_status_remote_busy(struct sock *sk, struct sk_buff *skb) { struct llc_conn_state_ev *ev = llc_conn_ev(skb); ev->status = LLC_STATUS_REMOTE_BUSY; return 0; } int llc_conn_ev_qlfy_set_status_refuse(struct sock *sk, struct sk_buff *skb) { struct llc_conn_state_ev *ev = llc_conn_ev(skb); ev->status = LLC_STATUS_REFUSE; return 0; } int llc_conn_ev_qlfy_set_status_conflict(struct sock *sk, struct sk_buff *skb) { struct llc_conn_state_ev *ev = llc_conn_ev(skb); ev->status = LLC_STATUS_CONFLICT; return 0; } int llc_conn_ev_qlfy_set_status_rst_done(struct sock *sk, struct sk_buff *skb) { struct llc_conn_state_ev *ev = llc_conn_ev(skb); ev->status = LLC_STATUS_RESET_DONE; return 0; }
gpl-2.0
dankocher/android_kernel_lge_w7ds
drivers/input/touchscreen/synaptics_dsx/synaptics_dsx_rmi_hid_i2c.c
206
17387
/* * Synaptics DSX touchscreen driver * * Copyright (C) 2012 Synaptics Incorporated * * Copyright (C) 2012 Alexandra Chin <alexandra.chin@tw.synaptics.com> * Copyright (C) 2012 Scott Lin <scott.lin@tw.synaptics.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/interrupt.h> #include <linux/i2c.h> #include <linux/delay.h> #include <linux/input.h> #include <linux/gpio.h> #include <linux/types.h> #include <linux/platform_device.h> #include <linux/input/synaptics_dsx.h> #include "synaptics_dsx_core.h" #define SYN_I2C_RETRY_TIMES 10 #define REPORT_ID_GET_BLOB 0x07 #define REPORT_ID_WRITE 0x09 #define REPORT_ID_READ_ADDRESS 0x0a #define REPORT_ID_READ_DATA 0x0b #define REPORT_ID_SET_RMI_MODE 0x0f #define PREFIX_USAGE_PAGE_1BYTE 0x05 #define PREFIX_USAGE_PAGE_2BYTES 0x06 #define PREFIX_USAGE 0x09 #define PREFIX_REPORT_ID 0x85 #define PREFIX_REPORT_COUNT_1BYTE 0x95 #define PREFIX_REPORT_COUNT_2BYTES 0x96 #define USAGE_GET_BLOB 0xc5 #define USAGE_WRITE 0x02 #define USAGE_READ_ADDRESS 0x03 #define USAGE_READ_DATA 0x04 #define USAGE_SET_MODE 0x06 #define FEATURE_REPORT_TYPE 0x03 #define VENDOR_DEFINED_PAGE 0xff00 #define BLOB_REPORT_SIZE 256 #define RESET_COMMAND 0x01 #define GET_REPORT_COMMAND 0x02 #define SET_REPORT_COMMAND 0x03 #define SET_POWER_COMMAND 0x08 #define FINGER_MODE 0x00 #define RMI_MODE 0x02 struct hid_report_info { unsigned char get_blob_id; unsigned char write_id; unsigned char read_addr_id; unsigned char read_data_id; unsigned char set_mode_id; unsigned int blob_size; }; static struct hid_report_info hid_report; struct hid_device_descriptor { unsigned short device_descriptor_length; unsigned short format_version; unsigned short report_descriptor_length; unsigned short report_descriptor_index; unsigned short input_register_index; unsigned short input_report_max_length; unsigned short output_register_index; unsigned short output_report_max_length; unsigned short command_register_index; unsigned short data_register_index; unsigned short vendor_id; unsigned short product_id; unsigned short version_id; unsigned int reserved; }; static struct hid_device_descriptor hid_dd; struct i2c_rw_buffer { unsigned char *read; unsigned char *write; unsigned short read_size; unsigned short write_size; }; static struct i2c_rw_buffer buffer; static int do_i2c_transfer(struct i2c_client *client, struct i2c_msg *msg) { unsigned char retry; for (retry = 0; retry < SYN_I2C_RETRY_TIMES; retry++) { if (i2c_transfer(client->adapter, msg, 1) == 1) break; dev_err(&client->dev, "%s: I2C retry %d\n", __func__, retry + 1); msleep(20); } if (retry == SYN_I2C_RETRY_TIMES) { dev_err(&client->dev, "%s: I2C transfer over retry limit\n", __func__); return -EIO; } return 0; } static int check_buffer(unsigned char **buffer, unsigned short *buffer_size, unsigned short length) { if (*buffer_size < length) { if (*buffer_size) kfree(*buffer); *buffer = kzalloc(length, GFP_KERNEL); if (!(*buffer)) return -ENOMEM; *buffer_size = length; } return 0; } static int generic_read(struct i2c_client *client, unsigned short length) { int retval; struct i2c_msg msg[] = { { .addr = client->addr, .flags = I2C_M_RD, .len = length, } }; check_buffer(&buffer.read, &buffer.read_size, length); msg[0].buf = buffer.read; retval = do_i2c_transfer(client, msg); return retval; } static int generic_write(struct i2c_client *client, unsigned short length) { int retval; struct i2c_msg msg[] = { { .addr = client->addr, .flags = 0, .len = length, .buf = buffer.write, } }; retval = do_i2c_transfer(client, msg); return retval; } static void traverse_report_descriptor(unsigned int *index) { unsigned char size; unsigned char *buf = buffer.read; size = buf[*index] & MASK_2BIT; switch (size) { case 0: /* 0 bytes */ *index += 1; break; case 1: /* 1 byte */ *index += 2; break; case 2: /* 2 bytes */ *index += 3; break; case 3: /* 4 bytes */ *index += 5; break; default: break; } return; } static void find_blob_size(unsigned int index) { unsigned int ii = index; unsigned char *buf = buffer.read; while (ii < hid_dd.report_descriptor_length) { if (buf[ii] == PREFIX_REPORT_COUNT_1BYTE) { hid_report.blob_size = buf[ii + 1]; return; } else if (buf[ii] == PREFIX_REPORT_COUNT_2BYTES) { hid_report.blob_size = buf[ii + 1] | (buf[ii + 2] << 8); return; } traverse_report_descriptor(&ii); } return; } static void find_reports(unsigned int index) { unsigned int ii = index; unsigned char *buf = buffer.read; static unsigned int report_id_index; static unsigned char report_id; static unsigned short usage_page; if (buf[ii] == PREFIX_REPORT_ID) { report_id = buf[ii + 1]; report_id_index = ii; return; } if (buf[ii] == PREFIX_USAGE_PAGE_1BYTE) { usage_page = buf[ii + 1]; return; } else if (buf[ii] == PREFIX_USAGE_PAGE_2BYTES) { usage_page = buf[ii + 1] | (buf[ii + 2] << 8); return; } if ((usage_page == VENDOR_DEFINED_PAGE) && (buf[ii] == PREFIX_USAGE)) { switch (buf[ii + 1]) { case USAGE_GET_BLOB: hid_report.get_blob_id = report_id; find_blob_size(report_id_index); break; case USAGE_WRITE: hid_report.write_id = report_id; break; case USAGE_READ_ADDRESS: hid_report.read_addr_id = report_id; break; case USAGE_READ_DATA: hid_report.read_data_id = report_id; break; case USAGE_SET_MODE: hid_report.set_mode_id = report_id; break; default: break; } } return; } static int parse_report_descriptor(struct synaptics_rmi4_data *rmi4_data) { int retval; unsigned int ii = 0; unsigned char *buf; struct i2c_client *i2c = to_i2c_client(rmi4_data->pdev->dev.parent); buffer.write[0] = hid_dd.report_descriptor_index & MASK_8BIT; buffer.write[1] = hid_dd.report_descriptor_index >> 8; retval = generic_write(i2c, 2); if (retval < 0) return retval; retval = generic_read(i2c, hid_dd.report_descriptor_length); if (retval < 0) return retval; buf = buffer.read; hid_report.get_blob_id = REPORT_ID_GET_BLOB; hid_report.write_id = REPORT_ID_WRITE; hid_report.read_addr_id = REPORT_ID_READ_ADDRESS; hid_report.read_data_id = REPORT_ID_READ_DATA; hid_report.set_mode_id = REPORT_ID_SET_RMI_MODE; hid_report.blob_size = BLOB_REPORT_SIZE; while (ii < hid_dd.report_descriptor_length) { find_reports(ii); traverse_report_descriptor(&ii); } return 0; } static int switch_to_rmi(struct synaptics_rmi4_data *rmi4_data) { int retval; struct i2c_client *i2c = to_i2c_client(rmi4_data->pdev->dev.parent); mutex_lock(&rmi4_data->rmi4_io_ctrl_mutex); check_buffer(&buffer.write, &buffer.write_size, 11); /* set rmi mode */ buffer.write[0] = hid_dd.command_register_index & MASK_8BIT; buffer.write[1] = hid_dd.command_register_index >> 8; buffer.write[2] = (FEATURE_REPORT_TYPE << 4) | hid_report.set_mode_id; buffer.write[3] = SET_REPORT_COMMAND; buffer.write[4] = hid_report.set_mode_id; buffer.write[5] = hid_dd.data_register_index & MASK_8BIT; buffer.write[6] = hid_dd.data_register_index >> 8; buffer.write[7] = 0x04; buffer.write[8] = 0x00; buffer.write[9] = hid_report.set_mode_id; buffer.write[10] = RMI_MODE; retval = generic_write(i2c, 11); mutex_unlock(&rmi4_data->rmi4_io_ctrl_mutex); return retval; } static int check_report_mode(struct synaptics_rmi4_data *rmi4_data) { int retval; unsigned short report_size; struct i2c_client *i2c = to_i2c_client(rmi4_data->pdev->dev.parent); mutex_lock(&rmi4_data->rmi4_io_ctrl_mutex); check_buffer(&buffer.write, &buffer.write_size, 7); buffer.write[0] = hid_dd.command_register_index & MASK_8BIT; buffer.write[1] = hid_dd.command_register_index >> 8; buffer.write[2] = (FEATURE_REPORT_TYPE << 4) | hid_report.set_mode_id; buffer.write[3] = GET_REPORT_COMMAND; buffer.write[4] = hid_report.set_mode_id; buffer.write[5] = hid_dd.data_register_index & MASK_8BIT; buffer.write[6] = hid_dd.data_register_index >> 8; retval = generic_write(i2c, 7); if (retval < 0) goto exit; retval = generic_read(i2c, 2); if (retval < 0) goto exit; report_size = (buffer.read[1] << 8) | buffer.read[0]; retval = generic_write(i2c, 7); if (retval < 0) goto exit; retval = generic_read(i2c, report_size); if (retval < 0) goto exit; retval = buffer.read[3]; dev_dbg(rmi4_data->pdev->dev.parent, "%s: Report mode = %d\n", __func__, retval); exit: mutex_unlock(&rmi4_data->rmi4_io_ctrl_mutex); return retval; } static int hid_i2c_init(struct synaptics_rmi4_data *rmi4_data) { int retval; struct i2c_client *i2c = to_i2c_client(rmi4_data->pdev->dev.parent); const struct synaptics_dsx_board_data *bdata = rmi4_data->hw_if->board_data; mutex_lock(&rmi4_data->rmi4_io_ctrl_mutex); check_buffer(&buffer.write, &buffer.write_size, 6); /* read device descriptor */ buffer.write[0] = bdata->device_descriptor_addr & MASK_8BIT; buffer.write[1] = bdata->device_descriptor_addr >> 8; retval = generic_write(i2c, 2); if (retval < 0) goto exit; retval = generic_read(i2c, sizeof(hid_dd)); if (retval < 0) goto exit; memcpy((unsigned char *)&hid_dd, buffer.read, sizeof(hid_dd)); retval = parse_report_descriptor(rmi4_data); if (retval < 0) goto exit; /* set power */ buffer.write[0] = hid_dd.command_register_index & MASK_8BIT; buffer.write[1] = hid_dd.command_register_index >> 8; buffer.write[2] = 0x00; buffer.write[3] = SET_POWER_COMMAND; retval = generic_write(i2c, 4); if (retval < 0) goto exit; /* reset */ buffer.write[0] = hid_dd.command_register_index & MASK_8BIT; buffer.write[1] = hid_dd.command_register_index >> 8; buffer.write[2] = 0x00; buffer.write[3] = RESET_COMMAND; retval = generic_write(i2c, 4); if (retval < 0) goto exit; while (gpio_get_value(bdata->irq_gpio)) msleep(20); retval = generic_read(i2c, hid_dd.input_report_max_length); if (retval < 0) goto exit; /* get blob */ buffer.write[0] = hid_dd.command_register_index & MASK_8BIT; buffer.write[1] = hid_dd.command_register_index >> 8; buffer.write[2] = (FEATURE_REPORT_TYPE << 4) | hid_report.get_blob_id; buffer.write[3] = 0x02; buffer.write[4] = hid_dd.data_register_index & MASK_8BIT; buffer.write[5] = hid_dd.data_register_index >> 8; retval = generic_write(i2c, 6); if (retval < 0) goto exit; msleep(20); retval = generic_read(i2c, hid_report.blob_size + 3); if (retval < 0) goto exit; exit: mutex_unlock(&rmi4_data->rmi4_io_ctrl_mutex); if (retval < 0) { dev_err(rmi4_data->pdev->dev.parent, "%s: Failed to initialize HID/I2C interface\n", __func__); return retval; } retval = switch_to_rmi(rmi4_data); return retval; } static int synaptics_rmi4_i2c_read(struct synaptics_rmi4_data *rmi4_data, unsigned short addr, unsigned char *data, unsigned short length) { int retval; unsigned char retry; unsigned char recover = 1; unsigned short report_length; struct i2c_client *i2c = to_i2c_client(rmi4_data->pdev->dev.parent); struct i2c_msg msg[] = { { .addr = i2c->addr, .flags = 0, .len = hid_dd.output_report_max_length + 2, }, { .addr = i2c->addr, .flags = I2C_M_RD, .len = length + 4, }, }; recover: mutex_lock(&rmi4_data->rmi4_io_ctrl_mutex); check_buffer(&buffer.write, &buffer.write_size, hid_dd.output_report_max_length + 2); msg[0].buf = buffer.write; buffer.write[0] = hid_dd.output_register_index & MASK_8BIT; buffer.write[1] = hid_dd.output_register_index >> 8; buffer.write[2] = hid_dd.output_report_max_length & MASK_8BIT; buffer.write[3] = hid_dd.output_report_max_length >> 8; buffer.write[4] = hid_report.read_addr_id; buffer.write[5] = 0x00; buffer.write[6] = addr & MASK_8BIT; buffer.write[7] = addr >> 8; buffer.write[8] = length & MASK_8BIT; buffer.write[9] = length >> 8; check_buffer(&buffer.read, &buffer.read_size, length + 4); msg[1].buf = buffer.read; retval = do_i2c_transfer(i2c, &msg[0]); if (retval != 0) goto exit; retry = 0; do { retval = do_i2c_transfer(i2c, &msg[1]); if (retval == 0) retval = length; else goto exit; report_length = (buffer.read[1] << 8) | buffer.read[0]; if (report_length == hid_dd.input_report_max_length) { memcpy(&data[0], &buffer.read[4], length); goto exit; } msleep(20); retry++; } while (retry < SYN_I2C_RETRY_TIMES); dev_err(rmi4_data->pdev->dev.parent, "%s: Failed to receive read report\n", __func__); retval = -EIO; exit: mutex_unlock(&rmi4_data->rmi4_io_ctrl_mutex); if ((retval != length) && (recover == 1)) { recover = 0; if (check_report_mode(rmi4_data) != RMI_MODE) { retval = hid_i2c_init(rmi4_data); if (retval == 0) goto recover; } } return retval; } static int synaptics_rmi4_i2c_write(struct synaptics_rmi4_data *rmi4_data, unsigned short addr, unsigned char *data, unsigned short length) { int retval; unsigned char recover = 1; unsigned char msg_length; struct i2c_client *i2c = to_i2c_client(rmi4_data->pdev->dev.parent); struct i2c_msg msg[] = { { .addr = i2c->addr, .flags = 0, } }; if ((length + 10) < (hid_dd.output_report_max_length + 2)) msg_length = hid_dd.output_report_max_length + 2; else msg_length = length + 10; recover: mutex_lock(&rmi4_data->rmi4_io_ctrl_mutex); check_buffer(&buffer.write, &buffer.write_size, msg_length); msg[0].len = msg_length; msg[0].buf = buffer.write; buffer.write[0] = hid_dd.output_register_index & MASK_8BIT; buffer.write[1] = hid_dd.output_register_index >> 8; buffer.write[2] = hid_dd.output_report_max_length & MASK_8BIT; buffer.write[3] = hid_dd.output_report_max_length >> 8; buffer.write[4] = hid_report.write_id; buffer.write[5] = 0x00; buffer.write[6] = addr & MASK_8BIT; buffer.write[7] = addr >> 8; buffer.write[8] = length & MASK_8BIT; buffer.write[9] = length >> 8; memcpy(&buffer.write[10], &data[0], length); retval = do_i2c_transfer(i2c, msg); if (retval == 0) retval = length; mutex_unlock(&rmi4_data->rmi4_io_ctrl_mutex); if ((retval != length) && (recover == 1)) { recover = 0; if (check_report_mode(rmi4_data) != RMI_MODE) { retval = hid_i2c_init(rmi4_data); if (retval == 0) goto recover; } } return retval; } static struct synaptics_dsx_bus_access bus_access = { .type = BUS_I2C, .read = synaptics_rmi4_i2c_read, .write = synaptics_rmi4_i2c_write, }; static struct synaptics_dsx_hw_interface hw_if; static struct platform_device *synaptics_dsx_i2c_device; static void synaptics_rmi4_i2c_dev_release(struct device *dev) { kfree(synaptics_dsx_i2c_device); return; } static int synaptics_rmi4_i2c_probe(struct i2c_client *client, const struct i2c_device_id *dev_id) { int retval; if (!i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_BYTE_DATA)) { dev_err(&client->dev, "%s: SMBus byte data commands not supported by host\n", __func__); return -EIO; } synaptics_dsx_i2c_device = kzalloc( sizeof(struct platform_device), GFP_KERNEL); if (!synaptics_dsx_i2c_device) { dev_err(&client->dev, "%s: Failed to allocate memory for synaptics_dsx_i2c_device\n", __func__); return -ENOMEM; } hw_if.board_data = client->dev.platform_data; hw_if.bus_access = &bus_access; hw_if.bl_hw_init = switch_to_rmi; hw_if.ui_hw_init = hid_i2c_init; synaptics_dsx_i2c_device->name = PLATFORM_DRIVER_NAME; synaptics_dsx_i2c_device->id = 0; synaptics_dsx_i2c_device->num_resources = 0; synaptics_dsx_i2c_device->dev.parent = &client->dev; synaptics_dsx_i2c_device->dev.platform_data = &hw_if; synaptics_dsx_i2c_device->dev.release = synaptics_rmi4_i2c_dev_release; retval = platform_device_register(synaptics_dsx_i2c_device); if (retval) { dev_err(&client->dev, "%s: Failed to register platform device\n", __func__); return -ENODEV; } return 0; } static int synaptics_rmi4_i2c_remove(struct i2c_client *client) { if (buffer.read_size) kfree(buffer.read); if (buffer.write_size) kfree(buffer.write); platform_device_unregister(synaptics_dsx_i2c_device); return 0; } static const struct i2c_device_id synaptics_rmi4_id_table[] = { {I2C_DRIVER_NAME, 0}, {}, }; MODULE_DEVICE_TABLE(i2c, synaptics_rmi4_id_table); static struct i2c_driver synaptics_rmi4_i2c_driver = { .driver = { .name = I2C_DRIVER_NAME, .owner = THIS_MODULE, }, .probe = synaptics_rmi4_i2c_probe, .remove = __devexit_p(synaptics_rmi4_i2c_remove), .id_table = synaptics_rmi4_id_table, }; int synaptics_rmi4_bus_init(void) { return i2c_add_driver(&synaptics_rmi4_i2c_driver); } EXPORT_SYMBOL(synaptics_rmi4_bus_init); void synaptics_rmi4_bus_exit(void) { i2c_del_driver(&synaptics_rmi4_i2c_driver); return; } EXPORT_SYMBOL(synaptics_rmi4_bus_exit); MODULE_AUTHOR("Synaptics, Inc."); MODULE_DESCRIPTION("Synaptics DSX I2C Bus Support Module"); MODULE_LICENSE("GPL v2");
gpl-2.0
DezG/buildroot-linux-kernel-m3
arch/alpha/kernel/irq_srm.c
1486
1618
/* * Handle interrupts from the SRM, assuming no additional weirdness. */ #include <linux/init.h> #include <linux/sched.h> #include <linux/irq.h> #include "proto.h" #include "irq_impl.h" /* * Is the palcode SMP safe? In other words: can we call cserve_ena/dis * at the same time in multiple CPUs? To be safe I added a spinlock * but it can be removed trivially if the palcode is robust against smp. */ DEFINE_SPINLOCK(srm_irq_lock); static inline void srm_enable_irq(unsigned int irq) { spin_lock(&srm_irq_lock); cserve_ena(irq - 16); spin_unlock(&srm_irq_lock); } static void srm_disable_irq(unsigned int irq) { spin_lock(&srm_irq_lock); cserve_dis(irq - 16); spin_unlock(&srm_irq_lock); } static unsigned int srm_startup_irq(unsigned int irq) { srm_enable_irq(irq); return 0; } static void srm_end_irq(unsigned int irq) { if (!(irq_desc[irq].status & (IRQ_DISABLED|IRQ_INPROGRESS))) srm_enable_irq(irq); } /* Handle interrupts from the SRM, assuming no additional weirdness. */ static struct irq_chip srm_irq_type = { .name = "SRM", .startup = srm_startup_irq, .shutdown = srm_disable_irq, .enable = srm_enable_irq, .disable = srm_disable_irq, .ack = srm_disable_irq, .end = srm_end_irq, }; void __init init_srm_irqs(long max, unsigned long ignore_mask) { long i; if (NR_IRQS <= 16) return; for (i = 16; i < max; ++i) { if (i < 64 && ((ignore_mask >> i) & 1)) continue; irq_desc[i].status = IRQ_DISABLED | IRQ_LEVEL; irq_desc[i].chip = &srm_irq_type; } } void srm_device_interrupt(unsigned long vector) { int irq = (vector - 0x800) >> 4; handle_irq(irq); }
gpl-2.0
romracer/atrix-kernel
arch/x86/vdso/vclock_gettime.c
1742
4269
/* * Copyright 2006 Andi Kleen, SUSE Labs. * Subject to the GNU Public License, v.2 * * Fast user context implementation of clock_gettime and gettimeofday. * * The code should have no internal unresolved relocations. * Check with readelf after changing. * Also alternative() doesn't work. */ /* Disable profiling for userspace code: */ #define DISABLE_BRANCH_PROFILING #include <linux/kernel.h> #include <linux/posix-timers.h> #include <linux/time.h> #include <linux/string.h> #include <asm/vsyscall.h> #include <asm/vgtod.h> #include <asm/timex.h> #include <asm/hpet.h> #include <asm/unistd.h> #include <asm/io.h> #include "vextern.h" #define gtod vdso_vsyscall_gtod_data notrace static long vdso_fallback_gettime(long clock, struct timespec *ts) { long ret; asm("syscall" : "=a" (ret) : "0" (__NR_clock_gettime),"D" (clock), "S" (ts) : "memory"); return ret; } notrace static inline long vgetns(void) { long v; cycles_t (*vread)(void); vread = gtod->clock.vread; v = (vread() - gtod->clock.cycle_last) & gtod->clock.mask; return (v * gtod->clock.mult) >> gtod->clock.shift; } notrace static noinline int do_realtime(struct timespec *ts) { unsigned long seq, ns; do { seq = read_seqbegin(&gtod->lock); ts->tv_sec = gtod->wall_time_sec; ts->tv_nsec = gtod->wall_time_nsec; ns = vgetns(); } while (unlikely(read_seqretry(&gtod->lock, seq))); timespec_add_ns(ts, ns); return 0; } /* Copy of the version in kernel/time.c which we cannot directly access */ notrace static void vset_normalized_timespec(struct timespec *ts, long sec, long nsec) { while (nsec >= NSEC_PER_SEC) { nsec -= NSEC_PER_SEC; ++sec; } while (nsec < 0) { nsec += NSEC_PER_SEC; --sec; } ts->tv_sec = sec; ts->tv_nsec = nsec; } notrace static noinline int do_monotonic(struct timespec *ts) { unsigned long seq, ns, secs; do { seq = read_seqbegin(&gtod->lock); secs = gtod->wall_time_sec; ns = gtod->wall_time_nsec + vgetns(); secs += gtod->wall_to_monotonic.tv_sec; ns += gtod->wall_to_monotonic.tv_nsec; } while (unlikely(read_seqretry(&gtod->lock, seq))); vset_normalized_timespec(ts, secs, ns); return 0; } notrace static noinline int do_realtime_coarse(struct timespec *ts) { unsigned long seq; do { seq = read_seqbegin(&gtod->lock); ts->tv_sec = gtod->wall_time_coarse.tv_sec; ts->tv_nsec = gtod->wall_time_coarse.tv_nsec; } while (unlikely(read_seqretry(&gtod->lock, seq))); return 0; } notrace static noinline int do_monotonic_coarse(struct timespec *ts) { unsigned long seq, ns, secs; do { seq = read_seqbegin(&gtod->lock); secs = gtod->wall_time_coarse.tv_sec; ns = gtod->wall_time_coarse.tv_nsec; secs += gtod->wall_to_monotonic.tv_sec; ns += gtod->wall_to_monotonic.tv_nsec; } while (unlikely(read_seqretry(&gtod->lock, seq))); vset_normalized_timespec(ts, secs, ns); return 0; } notrace int __vdso_clock_gettime(clockid_t clock, struct timespec *ts) { if (likely(gtod->sysctl_enabled)) switch (clock) { case CLOCK_REALTIME: if (likely(gtod->clock.vread)) return do_realtime(ts); break; case CLOCK_MONOTONIC: if (likely(gtod->clock.vread)) return do_monotonic(ts); break; case CLOCK_REALTIME_COARSE: return do_realtime_coarse(ts); case CLOCK_MONOTONIC_COARSE: return do_monotonic_coarse(ts); } return vdso_fallback_gettime(clock, ts); } int clock_gettime(clockid_t, struct timespec *) __attribute__((weak, alias("__vdso_clock_gettime"))); notrace int __vdso_gettimeofday(struct timeval *tv, struct timezone *tz) { long ret; if (likely(gtod->sysctl_enabled && gtod->clock.vread)) { if (likely(tv != NULL)) { BUILD_BUG_ON(offsetof(struct timeval, tv_usec) != offsetof(struct timespec, tv_nsec) || sizeof(*tv) != sizeof(struct timespec)); do_realtime((struct timespec *)tv); tv->tv_usec /= 1000; } if (unlikely(tz != NULL)) { /* Avoid memcpy. Some old compilers fail to inline it */ tz->tz_minuteswest = gtod->sys_tz.tz_minuteswest; tz->tz_dsttime = gtod->sys_tz.tz_dsttime; } return 0; } asm("syscall" : "=a" (ret) : "0" (__NR_gettimeofday), "D" (tv), "S" (tz) : "memory"); return ret; } int gettimeofday(struct timeval *, struct timezone *) __attribute__((weak, alias("__vdso_gettimeofday")));
gpl-2.0
blackbox87/zte_skate_gb_kernel
arch/um/kernel/trap.c
1742
6088
/* * Copyright (C) 2000 - 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com) * Licensed under the GPL */ #include <linux/mm.h> #include <linux/sched.h> #include <linux/hardirq.h> #include <asm/current.h> #include <asm/pgtable.h> #include <asm/tlbflush.h> #include "arch.h" #include "as-layout.h" #include "kern_util.h" #include "os.h" #include "skas.h" #include "sysdep/sigcontext.h" /* * Note this is constrained to return 0, -EFAULT, -EACCESS, -ENOMEM by * segv(). */ int handle_page_fault(unsigned long address, unsigned long ip, int is_write, int is_user, int *code_out) { struct mm_struct *mm = current->mm; struct vm_area_struct *vma; pgd_t *pgd; pud_t *pud; pmd_t *pmd; pte_t *pte; int err = -EFAULT; *code_out = SEGV_MAPERR; /* * If the fault was during atomic operation, don't take the fault, just * fail. */ if (in_atomic()) goto out_nosemaphore; down_read(&mm->mmap_sem); vma = find_vma(mm, address); if (!vma) goto out; else if (vma->vm_start <= address) goto good_area; else if (!(vma->vm_flags & VM_GROWSDOWN)) goto out; else if (is_user && !ARCH_IS_STACKGROW(address)) goto out; else if (expand_stack(vma, address)) goto out; good_area: *code_out = SEGV_ACCERR; if (is_write && !(vma->vm_flags & VM_WRITE)) goto out; /* Don't require VM_READ|VM_EXEC for write faults! */ if (!is_write && !(vma->vm_flags & (VM_READ | VM_EXEC))) goto out; do { int fault; fault = handle_mm_fault(mm, vma, address, is_write ? FAULT_FLAG_WRITE : 0); if (unlikely(fault & VM_FAULT_ERROR)) { if (fault & VM_FAULT_OOM) { goto out_of_memory; } else if (fault & VM_FAULT_SIGBUS) { err = -EACCES; goto out; } BUG(); } if (fault & VM_FAULT_MAJOR) current->maj_flt++; else current->min_flt++; pgd = pgd_offset(mm, address); pud = pud_offset(pgd, address); pmd = pmd_offset(pud, address); pte = pte_offset_kernel(pmd, address); } while (!pte_present(*pte)); err = 0; /* * The below warning was added in place of * pte_mkyoung(); if (is_write) pte_mkdirty(); * If it's triggered, we'd see normally a hang here (a clean pte is * marked read-only to emulate the dirty bit). * However, the generic code can mark a PTE writable but clean on a * concurrent read fault, triggering this harmlessly. So comment it out. */ #if 0 WARN_ON(!pte_young(*pte) || (is_write && !pte_dirty(*pte))); #endif flush_tlb_page(vma, address); out: up_read(&mm->mmap_sem); out_nosemaphore: return err; out_of_memory: /* * We ran out of memory, call the OOM killer, and return the userspace * (which will retry the fault, or kill us if we got oom-killed). */ up_read(&mm->mmap_sem); pagefault_out_of_memory(); return 0; } static void bad_segv(struct faultinfo fi, unsigned long ip) { struct siginfo si; si.si_signo = SIGSEGV; si.si_code = SEGV_ACCERR; si.si_addr = (void __user *) FAULT_ADDRESS(fi); current->thread.arch.faultinfo = fi; force_sig_info(SIGSEGV, &si, current); } void fatal_sigsegv(void) { force_sigsegv(SIGSEGV, current); do_signal(); /* * This is to tell gcc that we're not returning - do_signal * can, in general, return, but in this case, it's not, since * we just got a fatal SIGSEGV queued. */ os_dump_core(); } void segv_handler(int sig, struct uml_pt_regs *regs) { struct faultinfo * fi = UPT_FAULTINFO(regs); if (UPT_IS_USER(regs) && !SEGV_IS_FIXABLE(fi)) { bad_segv(*fi, UPT_IP(regs)); return; } segv(*fi, UPT_IP(regs), UPT_IS_USER(regs), regs); } /* * We give a *copy* of the faultinfo in the regs to segv. * This must be done, since nesting SEGVs could overwrite * the info in the regs. A pointer to the info then would * give us bad data! */ unsigned long segv(struct faultinfo fi, unsigned long ip, int is_user, struct uml_pt_regs *regs) { struct siginfo si; jmp_buf *catcher; int err; int is_write = FAULT_WRITE(fi); unsigned long address = FAULT_ADDRESS(fi); if (!is_user && (address >= start_vm) && (address < end_vm)) { flush_tlb_kernel_vm(); return 0; } else if (current->mm == NULL) { show_regs(container_of(regs, struct pt_regs, regs)); panic("Segfault with no mm"); } if (SEGV_IS_FIXABLE(&fi) || SEGV_MAYBE_FIXABLE(&fi)) err = handle_page_fault(address, ip, is_write, is_user, &si.si_code); else { err = -EFAULT; /* * A thread accessed NULL, we get a fault, but CR2 is invalid. * This code is used in __do_copy_from_user() of TT mode. * XXX tt mode is gone, so maybe this isn't needed any more */ address = 0; } catcher = current->thread.fault_catcher; if (!err) return 0; else if (catcher != NULL) { current->thread.fault_addr = (void *) address; UML_LONGJMP(catcher, 1); } else if (current->thread.fault_addr != NULL) panic("fault_addr set but no fault catcher"); else if (!is_user && arch_fixup(ip, regs)) return 0; if (!is_user) { show_regs(container_of(regs, struct pt_regs, regs)); panic("Kernel mode fault at addr 0x%lx, ip 0x%lx", address, ip); } if (err == -EACCES) { si.si_signo = SIGBUS; si.si_errno = 0; si.si_code = BUS_ADRERR; si.si_addr = (void __user *)address; current->thread.arch.faultinfo = fi; force_sig_info(SIGBUS, &si, current); } else { BUG_ON(err != -EFAULT); si.si_signo = SIGSEGV; si.si_addr = (void __user *) address; current->thread.arch.faultinfo = fi; force_sig_info(SIGSEGV, &si, current); } return 0; } void relay_signal(int sig, struct uml_pt_regs *regs) { if (!UPT_IS_USER(regs)) { if (sig == SIGBUS) printk(KERN_ERR "Bus error - the host /dev/shm or /tmp " "mount likely just ran out of space\n"); panic("Kernel mode signal %d", sig); } arch_examine_signal(sig, regs); current->thread.arch.faultinfo = *UPT_FAULTINFO(regs); force_sig(sig, current); } void bus_handler(int sig, struct uml_pt_regs *regs) { if (current->thread.fault_catcher != NULL) UML_LONGJMP(current->thread.fault_catcher, 1); else relay_signal(sig, regs); } void winch(int sig, struct uml_pt_regs *regs) { do_IRQ(WINCH_IRQ, regs); } void trap_init(void) { }
gpl-2.0
FireLord1/android_kernel_samsung_logan2g
drivers/atm/fore200e.c
2510
90835
/* A FORE Systems 200E-series driver for ATM on Linux. Christophe Lizzi (lizzi@cnam.fr), October 1999-March 2003. Based on the PCA-200E driver from Uwe Dannowski (Uwe.Dannowski@inf.tu-dresden.de). This driver simultaneously supports PCA-200E and SBA-200E adapters on i386, alpha (untested), powerpc, sparc and sparc64 architectures. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/kernel.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/capability.h> #include <linux/interrupt.h> #include <linux/bitops.h> #include <linux/pci.h> #include <linux/module.h> #include <linux/atmdev.h> #include <linux/sonet.h> #include <linux/atm_suni.h> #include <linux/dma-mapping.h> #include <linux/delay.h> #include <linux/firmware.h> #include <asm/io.h> #include <asm/string.h> #include <asm/page.h> #include <asm/irq.h> #include <asm/dma.h> #include <asm/byteorder.h> #include <asm/uaccess.h> #include <asm/atomic.h> #ifdef CONFIG_SBUS #include <linux/of.h> #include <linux/of_device.h> #include <asm/idprom.h> #include <asm/openprom.h> #include <asm/oplib.h> #include <asm/pgtable.h> #endif #if defined(CONFIG_ATM_FORE200E_USE_TASKLET) /* defer interrupt work to a tasklet */ #define FORE200E_USE_TASKLET #endif #if 0 /* enable the debugging code of the buffer supply queues */ #define FORE200E_BSQ_DEBUG #endif #if 1 /* ensure correct handling of 52-byte AAL0 SDUs expected by atmdump-like apps */ #define FORE200E_52BYTE_AAL0_SDU #endif #include "fore200e.h" #include "suni.h" #define FORE200E_VERSION "0.3e" #define FORE200E "fore200e: " #if 0 /* override .config */ #define CONFIG_ATM_FORE200E_DEBUG 1 #endif #if defined(CONFIG_ATM_FORE200E_DEBUG) && (CONFIG_ATM_FORE200E_DEBUG > 0) #define DPRINTK(level, format, args...) do { if (CONFIG_ATM_FORE200E_DEBUG >= (level)) \ printk(FORE200E format, ##args); } while (0) #else #define DPRINTK(level, format, args...) do {} while (0) #endif #define FORE200E_ALIGN(addr, alignment) \ ((((unsigned long)(addr) + (alignment - 1)) & ~(alignment - 1)) - (unsigned long)(addr)) #define FORE200E_DMA_INDEX(dma_addr, type, index) ((dma_addr) + (index) * sizeof(type)) #define FORE200E_INDEX(virt_addr, type, index) (&((type *)(virt_addr))[ index ]) #define FORE200E_NEXT_ENTRY(index, modulo) (index = ((index) + 1) % (modulo)) #if 1 #define ASSERT(expr) if (!(expr)) { \ printk(FORE200E "assertion failed! %s[%d]: %s\n", \ __func__, __LINE__, #expr); \ panic(FORE200E "%s", __func__); \ } #else #define ASSERT(expr) do {} while (0) #endif static const struct atmdev_ops fore200e_ops; static const struct fore200e_bus fore200e_bus[]; static LIST_HEAD(fore200e_boards); MODULE_AUTHOR("Christophe Lizzi - credits to Uwe Dannowski and Heikki Vatiainen"); MODULE_DESCRIPTION("FORE Systems 200E-series ATM driver - version " FORE200E_VERSION); MODULE_SUPPORTED_DEVICE("PCA-200E, SBA-200E"); static const int fore200e_rx_buf_nbr[ BUFFER_SCHEME_NBR ][ BUFFER_MAGN_NBR ] = { { BUFFER_S1_NBR, BUFFER_L1_NBR }, { BUFFER_S2_NBR, BUFFER_L2_NBR } }; static const int fore200e_rx_buf_size[ BUFFER_SCHEME_NBR ][ BUFFER_MAGN_NBR ] = { { BUFFER_S1_SIZE, BUFFER_L1_SIZE }, { BUFFER_S2_SIZE, BUFFER_L2_SIZE } }; #if defined(CONFIG_ATM_FORE200E_DEBUG) && (CONFIG_ATM_FORE200E_DEBUG > 0) static const char* fore200e_traffic_class[] = { "NONE", "UBR", "CBR", "VBR", "ABR", "ANY" }; #endif #if 0 /* currently unused */ static int fore200e_fore2atm_aal(enum fore200e_aal aal) { switch(aal) { case FORE200E_AAL0: return ATM_AAL0; case FORE200E_AAL34: return ATM_AAL34; case FORE200E_AAL5: return ATM_AAL5; } return -EINVAL; } #endif static enum fore200e_aal fore200e_atm2fore_aal(int aal) { switch(aal) { case ATM_AAL0: return FORE200E_AAL0; case ATM_AAL34: return FORE200E_AAL34; case ATM_AAL1: case ATM_AAL2: case ATM_AAL5: return FORE200E_AAL5; } return -EINVAL; } static char* fore200e_irq_itoa(int irq) { static char str[8]; sprintf(str, "%d", irq); return str; } /* allocate and align a chunk of memory intended to hold the data behing exchanged between the driver and the adapter (using streaming DVMA) */ static int fore200e_chunk_alloc(struct fore200e* fore200e, struct chunk* chunk, int size, int alignment, int direction) { unsigned long offset = 0; if (alignment <= sizeof(int)) alignment = 0; chunk->alloc_size = size + alignment; chunk->align_size = size; chunk->direction = direction; chunk->alloc_addr = kzalloc(chunk->alloc_size, GFP_KERNEL | GFP_DMA); if (chunk->alloc_addr == NULL) return -ENOMEM; if (alignment > 0) offset = FORE200E_ALIGN(chunk->alloc_addr, alignment); chunk->align_addr = chunk->alloc_addr + offset; chunk->dma_addr = fore200e->bus->dma_map(fore200e, chunk->align_addr, chunk->align_size, direction); return 0; } /* free a chunk of memory */ static void fore200e_chunk_free(struct fore200e* fore200e, struct chunk* chunk) { fore200e->bus->dma_unmap(fore200e, chunk->dma_addr, chunk->dma_size, chunk->direction); kfree(chunk->alloc_addr); } static void fore200e_spin(int msecs) { unsigned long timeout = jiffies + msecs_to_jiffies(msecs); while (time_before(jiffies, timeout)); } static int fore200e_poll(struct fore200e* fore200e, volatile u32* addr, u32 val, int msecs) { unsigned long timeout = jiffies + msecs_to_jiffies(msecs); int ok; mb(); do { if ((ok = (*addr == val)) || (*addr & STATUS_ERROR)) break; } while (time_before(jiffies, timeout)); #if 1 if (!ok) { printk(FORE200E "cmd polling failed, got status 0x%08x, expected 0x%08x\n", *addr, val); } #endif return ok; } static int fore200e_io_poll(struct fore200e* fore200e, volatile u32 __iomem *addr, u32 val, int msecs) { unsigned long timeout = jiffies + msecs_to_jiffies(msecs); int ok; do { if ((ok = (fore200e->bus->read(addr) == val))) break; } while (time_before(jiffies, timeout)); #if 1 if (!ok) { printk(FORE200E "I/O polling failed, got status 0x%08x, expected 0x%08x\n", fore200e->bus->read(addr), val); } #endif return ok; } static void fore200e_free_rx_buf(struct fore200e* fore200e) { int scheme, magn, nbr; struct buffer* buffer; for (scheme = 0; scheme < BUFFER_SCHEME_NBR; scheme++) { for (magn = 0; magn < BUFFER_MAGN_NBR; magn++) { if ((buffer = fore200e->host_bsq[ scheme ][ magn ].buffer) != NULL) { for (nbr = 0; nbr < fore200e_rx_buf_nbr[ scheme ][ magn ]; nbr++) { struct chunk* data = &buffer[ nbr ].data; if (data->alloc_addr != NULL) fore200e_chunk_free(fore200e, data); } } } } } static void fore200e_uninit_bs_queue(struct fore200e* fore200e) { int scheme, magn; for (scheme = 0; scheme < BUFFER_SCHEME_NBR; scheme++) { for (magn = 0; magn < BUFFER_MAGN_NBR; magn++) { struct chunk* status = &fore200e->host_bsq[ scheme ][ magn ].status; struct chunk* rbd_block = &fore200e->host_bsq[ scheme ][ magn ].rbd_block; if (status->alloc_addr) fore200e->bus->dma_chunk_free(fore200e, status); if (rbd_block->alloc_addr) fore200e->bus->dma_chunk_free(fore200e, rbd_block); } } } static int fore200e_reset(struct fore200e* fore200e, int diag) { int ok; fore200e->cp_monitor = fore200e->virt_base + FORE200E_CP_MONITOR_OFFSET; fore200e->bus->write(BSTAT_COLD_START, &fore200e->cp_monitor->bstat); fore200e->bus->reset(fore200e); if (diag) { ok = fore200e_io_poll(fore200e, &fore200e->cp_monitor->bstat, BSTAT_SELFTEST_OK, 1000); if (ok == 0) { printk(FORE200E "device %s self-test failed\n", fore200e->name); return -ENODEV; } printk(FORE200E "device %s self-test passed\n", fore200e->name); fore200e->state = FORE200E_STATE_RESET; } return 0; } static void fore200e_shutdown(struct fore200e* fore200e) { printk(FORE200E "removing device %s at 0x%lx, IRQ %s\n", fore200e->name, fore200e->phys_base, fore200e_irq_itoa(fore200e->irq)); if (fore200e->state > FORE200E_STATE_RESET) { /* first, reset the board to prevent further interrupts or data transfers */ fore200e_reset(fore200e, 0); } /* then, release all allocated resources */ switch(fore200e->state) { case FORE200E_STATE_COMPLETE: kfree(fore200e->stats); case FORE200E_STATE_IRQ: free_irq(fore200e->irq, fore200e->atm_dev); case FORE200E_STATE_ALLOC_BUF: fore200e_free_rx_buf(fore200e); case FORE200E_STATE_INIT_BSQ: fore200e_uninit_bs_queue(fore200e); case FORE200E_STATE_INIT_RXQ: fore200e->bus->dma_chunk_free(fore200e, &fore200e->host_rxq.status); fore200e->bus->dma_chunk_free(fore200e, &fore200e->host_rxq.rpd); case FORE200E_STATE_INIT_TXQ: fore200e->bus->dma_chunk_free(fore200e, &fore200e->host_txq.status); fore200e->bus->dma_chunk_free(fore200e, &fore200e->host_txq.tpd); case FORE200E_STATE_INIT_CMDQ: fore200e->bus->dma_chunk_free(fore200e, &fore200e->host_cmdq.status); case FORE200E_STATE_INITIALIZE: /* nothing to do for that state */ case FORE200E_STATE_START_FW: /* nothing to do for that state */ case FORE200E_STATE_RESET: /* nothing to do for that state */ case FORE200E_STATE_MAP: fore200e->bus->unmap(fore200e); case FORE200E_STATE_CONFIGURE: /* nothing to do for that state */ case FORE200E_STATE_REGISTER: /* XXX shouldn't we *start* by deregistering the device? */ atm_dev_deregister(fore200e->atm_dev); case FORE200E_STATE_BLANK: /* nothing to do for that state */ break; } } #ifdef CONFIG_PCI static u32 fore200e_pca_read(volatile u32 __iomem *addr) { /* on big-endian hosts, the board is configured to convert the endianess of slave RAM accesses */ return le32_to_cpu(readl(addr)); } static void fore200e_pca_write(u32 val, volatile u32 __iomem *addr) { /* on big-endian hosts, the board is configured to convert the endianess of slave RAM accesses */ writel(cpu_to_le32(val), addr); } static u32 fore200e_pca_dma_map(struct fore200e* fore200e, void* virt_addr, int size, int direction) { u32 dma_addr = pci_map_single((struct pci_dev*)fore200e->bus_dev, virt_addr, size, direction); DPRINTK(3, "PCI DVMA mapping: virt_addr = 0x%p, size = %d, direction = %d, --> dma_addr = 0x%08x\n", virt_addr, size, direction, dma_addr); return dma_addr; } static void fore200e_pca_dma_unmap(struct fore200e* fore200e, u32 dma_addr, int size, int direction) { DPRINTK(3, "PCI DVMA unmapping: dma_addr = 0x%08x, size = %d, direction = %d\n", dma_addr, size, direction); pci_unmap_single((struct pci_dev*)fore200e->bus_dev, dma_addr, size, direction); } static void fore200e_pca_dma_sync_for_cpu(struct fore200e* fore200e, u32 dma_addr, int size, int direction) { DPRINTK(3, "PCI DVMA sync: dma_addr = 0x%08x, size = %d, direction = %d\n", dma_addr, size, direction); pci_dma_sync_single_for_cpu((struct pci_dev*)fore200e->bus_dev, dma_addr, size, direction); } static void fore200e_pca_dma_sync_for_device(struct fore200e* fore200e, u32 dma_addr, int size, int direction) { DPRINTK(3, "PCI DVMA sync: dma_addr = 0x%08x, size = %d, direction = %d\n", dma_addr, size, direction); pci_dma_sync_single_for_device((struct pci_dev*)fore200e->bus_dev, dma_addr, size, direction); } /* allocate a DMA consistent chunk of memory intended to act as a communication mechanism (to hold descriptors, status, queues, etc.) shared by the driver and the adapter */ static int fore200e_pca_dma_chunk_alloc(struct fore200e* fore200e, struct chunk* chunk, int size, int nbr, int alignment) { /* returned chunks are page-aligned */ chunk->alloc_size = size * nbr; chunk->alloc_addr = pci_alloc_consistent((struct pci_dev*)fore200e->bus_dev, chunk->alloc_size, &chunk->dma_addr); if ((chunk->alloc_addr == NULL) || (chunk->dma_addr == 0)) return -ENOMEM; chunk->align_addr = chunk->alloc_addr; return 0; } /* free a DMA consistent chunk of memory */ static void fore200e_pca_dma_chunk_free(struct fore200e* fore200e, struct chunk* chunk) { pci_free_consistent((struct pci_dev*)fore200e->bus_dev, chunk->alloc_size, chunk->alloc_addr, chunk->dma_addr); } static int fore200e_pca_irq_check(struct fore200e* fore200e) { /* this is a 1 bit register */ int irq_posted = readl(fore200e->regs.pca.psr); #if defined(CONFIG_ATM_FORE200E_DEBUG) && (CONFIG_ATM_FORE200E_DEBUG == 2) if (irq_posted && (readl(fore200e->regs.pca.hcr) & PCA200E_HCR_OUTFULL)) { DPRINTK(2,"FIFO OUT full, device %d\n", fore200e->atm_dev->number); } #endif return irq_posted; } static void fore200e_pca_irq_ack(struct fore200e* fore200e) { writel(PCA200E_HCR_CLRINTR, fore200e->regs.pca.hcr); } static void fore200e_pca_reset(struct fore200e* fore200e) { writel(PCA200E_HCR_RESET, fore200e->regs.pca.hcr); fore200e_spin(10); writel(0, fore200e->regs.pca.hcr); } static int __devinit fore200e_pca_map(struct fore200e* fore200e) { DPRINTK(2, "device %s being mapped in memory\n", fore200e->name); fore200e->virt_base = ioremap(fore200e->phys_base, PCA200E_IOSPACE_LENGTH); if (fore200e->virt_base == NULL) { printk(FORE200E "can't map device %s\n", fore200e->name); return -EFAULT; } DPRINTK(1, "device %s mapped to 0x%p\n", fore200e->name, fore200e->virt_base); /* gain access to the PCA specific registers */ fore200e->regs.pca.hcr = fore200e->virt_base + PCA200E_HCR_OFFSET; fore200e->regs.pca.imr = fore200e->virt_base + PCA200E_IMR_OFFSET; fore200e->regs.pca.psr = fore200e->virt_base + PCA200E_PSR_OFFSET; fore200e->state = FORE200E_STATE_MAP; return 0; } static void fore200e_pca_unmap(struct fore200e* fore200e) { DPRINTK(2, "device %s being unmapped from memory\n", fore200e->name); if (fore200e->virt_base != NULL) iounmap(fore200e->virt_base); } static int __devinit fore200e_pca_configure(struct fore200e* fore200e) { struct pci_dev* pci_dev = (struct pci_dev*)fore200e->bus_dev; u8 master_ctrl, latency; DPRINTK(2, "device %s being configured\n", fore200e->name); if ((pci_dev->irq == 0) || (pci_dev->irq == 0xFF)) { printk(FORE200E "incorrect IRQ setting - misconfigured PCI-PCI bridge?\n"); return -EIO; } pci_read_config_byte(pci_dev, PCA200E_PCI_MASTER_CTRL, &master_ctrl); master_ctrl = master_ctrl #if defined(__BIG_ENDIAN) /* request the PCA board to convert the endianess of slave RAM accesses */ | PCA200E_CTRL_CONVERT_ENDIAN #endif #if 0 | PCA200E_CTRL_DIS_CACHE_RD | PCA200E_CTRL_DIS_WRT_INVAL | PCA200E_CTRL_ENA_CONT_REQ_MODE | PCA200E_CTRL_2_CACHE_WRT_INVAL #endif | PCA200E_CTRL_LARGE_PCI_BURSTS; pci_write_config_byte(pci_dev, PCA200E_PCI_MASTER_CTRL, master_ctrl); /* raise latency from 32 (default) to 192, as this seems to prevent NIC lockups (under heavy rx loads) due to continuous 'FIFO OUT full' condition. this may impact the performances of other PCI devices on the same bus, though */ latency = 192; pci_write_config_byte(pci_dev, PCI_LATENCY_TIMER, latency); fore200e->state = FORE200E_STATE_CONFIGURE; return 0; } static int __init fore200e_pca_prom_read(struct fore200e* fore200e, struct prom_data* prom) { struct host_cmdq* cmdq = &fore200e->host_cmdq; struct host_cmdq_entry* entry = &cmdq->host_entry[ cmdq->head ]; struct prom_opcode opcode; int ok; u32 prom_dma; FORE200E_NEXT_ENTRY(cmdq->head, QUEUE_SIZE_CMD); opcode.opcode = OPCODE_GET_PROM; opcode.pad = 0; prom_dma = fore200e->bus->dma_map(fore200e, prom, sizeof(struct prom_data), DMA_FROM_DEVICE); fore200e->bus->write(prom_dma, &entry->cp_entry->cmd.prom_block.prom_haddr); *entry->status = STATUS_PENDING; fore200e->bus->write(*(u32*)&opcode, (u32 __iomem *)&entry->cp_entry->cmd.prom_block.opcode); ok = fore200e_poll(fore200e, entry->status, STATUS_COMPLETE, 400); *entry->status = STATUS_FREE; fore200e->bus->dma_unmap(fore200e, prom_dma, sizeof(struct prom_data), DMA_FROM_DEVICE); if (ok == 0) { printk(FORE200E "unable to get PROM data from device %s\n", fore200e->name); return -EIO; } #if defined(__BIG_ENDIAN) #define swap_here(addr) (*((u32*)(addr)) = swab32( *((u32*)(addr)) )) /* MAC address is stored as little-endian */ swap_here(&prom->mac_addr[0]); swap_here(&prom->mac_addr[4]); #endif return 0; } static int fore200e_pca_proc_read(struct fore200e* fore200e, char *page) { struct pci_dev* pci_dev = (struct pci_dev*)fore200e->bus_dev; return sprintf(page, " PCI bus/slot/function:\t%d/%d/%d\n", pci_dev->bus->number, PCI_SLOT(pci_dev->devfn), PCI_FUNC(pci_dev->devfn)); } #endif /* CONFIG_PCI */ #ifdef CONFIG_SBUS static u32 fore200e_sba_read(volatile u32 __iomem *addr) { return sbus_readl(addr); } static void fore200e_sba_write(u32 val, volatile u32 __iomem *addr) { sbus_writel(val, addr); } static u32 fore200e_sba_dma_map(struct fore200e *fore200e, void* virt_addr, int size, int direction) { struct platform_device *op = fore200e->bus_dev; u32 dma_addr; dma_addr = dma_map_single(&op->dev, virt_addr, size, direction); DPRINTK(3, "SBUS DVMA mapping: virt_addr = 0x%p, size = %d, direction = %d --> dma_addr = 0x%08x\n", virt_addr, size, direction, dma_addr); return dma_addr; } static void fore200e_sba_dma_unmap(struct fore200e *fore200e, u32 dma_addr, int size, int direction) { struct platform_device *op = fore200e->bus_dev; DPRINTK(3, "SBUS DVMA unmapping: dma_addr = 0x%08x, size = %d, direction = %d,\n", dma_addr, size, direction); dma_unmap_single(&op->dev, dma_addr, size, direction); } static void fore200e_sba_dma_sync_for_cpu(struct fore200e *fore200e, u32 dma_addr, int size, int direction) { struct platform_device *op = fore200e->bus_dev; DPRINTK(3, "SBUS DVMA sync: dma_addr = 0x%08x, size = %d, direction = %d\n", dma_addr, size, direction); dma_sync_single_for_cpu(&op->dev, dma_addr, size, direction); } static void fore200e_sba_dma_sync_for_device(struct fore200e *fore200e, u32 dma_addr, int size, int direction) { struct platform_device *op = fore200e->bus_dev; DPRINTK(3, "SBUS DVMA sync: dma_addr = 0x%08x, size = %d, direction = %d\n", dma_addr, size, direction); dma_sync_single_for_device(&op->dev, dma_addr, size, direction); } /* Allocate a DVMA consistent chunk of memory intended to act as a communication mechanism * (to hold descriptors, status, queues, etc.) shared by the driver and the adapter. */ static int fore200e_sba_dma_chunk_alloc(struct fore200e *fore200e, struct chunk *chunk, int size, int nbr, int alignment) { struct platform_device *op = fore200e->bus_dev; chunk->alloc_size = chunk->align_size = size * nbr; /* returned chunks are page-aligned */ chunk->alloc_addr = dma_alloc_coherent(&op->dev, chunk->alloc_size, &chunk->dma_addr, GFP_ATOMIC); if ((chunk->alloc_addr == NULL) || (chunk->dma_addr == 0)) return -ENOMEM; chunk->align_addr = chunk->alloc_addr; return 0; } /* free a DVMA consistent chunk of memory */ static void fore200e_sba_dma_chunk_free(struct fore200e *fore200e, struct chunk *chunk) { struct platform_device *op = fore200e->bus_dev; dma_free_coherent(&op->dev, chunk->alloc_size, chunk->alloc_addr, chunk->dma_addr); } static void fore200e_sba_irq_enable(struct fore200e *fore200e) { u32 hcr = fore200e->bus->read(fore200e->regs.sba.hcr) & SBA200E_HCR_STICKY; fore200e->bus->write(hcr | SBA200E_HCR_INTR_ENA, fore200e->regs.sba.hcr); } static int fore200e_sba_irq_check(struct fore200e *fore200e) { return fore200e->bus->read(fore200e->regs.sba.hcr) & SBA200E_HCR_INTR_REQ; } static void fore200e_sba_irq_ack(struct fore200e *fore200e) { u32 hcr = fore200e->bus->read(fore200e->regs.sba.hcr) & SBA200E_HCR_STICKY; fore200e->bus->write(hcr | SBA200E_HCR_INTR_CLR, fore200e->regs.sba.hcr); } static void fore200e_sba_reset(struct fore200e *fore200e) { fore200e->bus->write(SBA200E_HCR_RESET, fore200e->regs.sba.hcr); fore200e_spin(10); fore200e->bus->write(0, fore200e->regs.sba.hcr); } static int __init fore200e_sba_map(struct fore200e *fore200e) { struct platform_device *op = fore200e->bus_dev; unsigned int bursts; /* gain access to the SBA specific registers */ fore200e->regs.sba.hcr = of_ioremap(&op->resource[0], 0, SBA200E_HCR_LENGTH, "SBA HCR"); fore200e->regs.sba.bsr = of_ioremap(&op->resource[1], 0, SBA200E_BSR_LENGTH, "SBA BSR"); fore200e->regs.sba.isr = of_ioremap(&op->resource[2], 0, SBA200E_ISR_LENGTH, "SBA ISR"); fore200e->virt_base = of_ioremap(&op->resource[3], 0, SBA200E_RAM_LENGTH, "SBA RAM"); if (!fore200e->virt_base) { printk(FORE200E "unable to map RAM of device %s\n", fore200e->name); return -EFAULT; } DPRINTK(1, "device %s mapped to 0x%p\n", fore200e->name, fore200e->virt_base); fore200e->bus->write(0x02, fore200e->regs.sba.isr); /* XXX hardwired interrupt level */ /* get the supported DVMA burst sizes */ bursts = of_getintprop_default(op->dev.of_node->parent, "burst-sizes", 0x00); if (sbus_can_dma_64bit()) sbus_set_sbus64(&op->dev, bursts); fore200e->state = FORE200E_STATE_MAP; return 0; } static void fore200e_sba_unmap(struct fore200e *fore200e) { struct platform_device *op = fore200e->bus_dev; of_iounmap(&op->resource[0], fore200e->regs.sba.hcr, SBA200E_HCR_LENGTH); of_iounmap(&op->resource[1], fore200e->regs.sba.bsr, SBA200E_BSR_LENGTH); of_iounmap(&op->resource[2], fore200e->regs.sba.isr, SBA200E_ISR_LENGTH); of_iounmap(&op->resource[3], fore200e->virt_base, SBA200E_RAM_LENGTH); } static int __init fore200e_sba_configure(struct fore200e *fore200e) { fore200e->state = FORE200E_STATE_CONFIGURE; return 0; } static int __init fore200e_sba_prom_read(struct fore200e *fore200e, struct prom_data *prom) { struct platform_device *op = fore200e->bus_dev; const u8 *prop; int len; prop = of_get_property(op->dev.of_node, "madaddrlo2", &len); if (!prop) return -ENODEV; memcpy(&prom->mac_addr[4], prop, 4); prop = of_get_property(op->dev.of_node, "madaddrhi4", &len); if (!prop) return -ENODEV; memcpy(&prom->mac_addr[2], prop, 4); prom->serial_number = of_getintprop_default(op->dev.of_node, "serialnumber", 0); prom->hw_revision = of_getintprop_default(op->dev.of_node, "promversion", 0); return 0; } static int fore200e_sba_proc_read(struct fore200e *fore200e, char *page) { struct platform_device *op = fore200e->bus_dev; const struct linux_prom_registers *regs; regs = of_get_property(op->dev.of_node, "reg", NULL); return sprintf(page, " SBUS slot/device:\t\t%d/'%s'\n", (regs ? regs->which_io : 0), op->dev.of_node->name); } #endif /* CONFIG_SBUS */ static void fore200e_tx_irq(struct fore200e* fore200e) { struct host_txq* txq = &fore200e->host_txq; struct host_txq_entry* entry; struct atm_vcc* vcc; struct fore200e_vc_map* vc_map; if (fore200e->host_txq.txing == 0) return; for (;;) { entry = &txq->host_entry[ txq->tail ]; if ((*entry->status & STATUS_COMPLETE) == 0) { break; } DPRINTK(3, "TX COMPLETED: entry = %p [tail = %d], vc_map = %p, skb = %p\n", entry, txq->tail, entry->vc_map, entry->skb); /* free copy of misaligned data */ kfree(entry->data); /* remove DMA mapping */ fore200e->bus->dma_unmap(fore200e, entry->tpd->tsd[ 0 ].buffer, entry->tpd->tsd[ 0 ].length, DMA_TO_DEVICE); vc_map = entry->vc_map; /* vcc closed since the time the entry was submitted for tx? */ if ((vc_map->vcc == NULL) || (test_bit(ATM_VF_READY, &vc_map->vcc->flags) == 0)) { DPRINTK(1, "no ready vcc found for PDU sent on device %d\n", fore200e->atm_dev->number); dev_kfree_skb_any(entry->skb); } else { ASSERT(vc_map->vcc); /* vcc closed then immediately re-opened? */ if (vc_map->incarn != entry->incarn) { /* when a vcc is closed, some PDUs may be still pending in the tx queue. if the same vcc is immediately re-opened, those pending PDUs must not be popped after the completion of their emission, as they refer to the prior incarnation of that vcc. otherwise, sk_atm(vcc)->sk_wmem_alloc would be decremented by the size of the (unrelated) skb, possibly leading to a negative sk->sk_wmem_alloc count, ultimately freezing the vcc. we thus bind the tx entry to the current incarnation of the vcc when the entry is submitted for tx. When the tx later completes, if the incarnation number of the tx entry does not match the one of the vcc, then this implies that the vcc has been closed then re-opened. we thus just drop the skb here. */ DPRINTK(1, "vcc closed-then-re-opened; dropping PDU sent on device %d\n", fore200e->atm_dev->number); dev_kfree_skb_any(entry->skb); } else { vcc = vc_map->vcc; ASSERT(vcc); /* notify tx completion */ if (vcc->pop) { vcc->pop(vcc, entry->skb); } else { dev_kfree_skb_any(entry->skb); } #if 1 /* race fixed by the above incarnation mechanism, but... */ if (atomic_read(&sk_atm(vcc)->sk_wmem_alloc) < 0) { atomic_set(&sk_atm(vcc)->sk_wmem_alloc, 0); } #endif /* check error condition */ if (*entry->status & STATUS_ERROR) atomic_inc(&vcc->stats->tx_err); else atomic_inc(&vcc->stats->tx); } } *entry->status = STATUS_FREE; fore200e->host_txq.txing--; FORE200E_NEXT_ENTRY(txq->tail, QUEUE_SIZE_TX); } } #ifdef FORE200E_BSQ_DEBUG int bsq_audit(int where, struct host_bsq* bsq, int scheme, int magn) { struct buffer* buffer; int count = 0; buffer = bsq->freebuf; while (buffer) { if (buffer->supplied) { printk(FORE200E "bsq_audit(%d): queue %d.%d, buffer %ld supplied but in free list!\n", where, scheme, magn, buffer->index); } if (buffer->magn != magn) { printk(FORE200E "bsq_audit(%d): queue %d.%d, buffer %ld, unexpected magn = %d\n", where, scheme, magn, buffer->index, buffer->magn); } if (buffer->scheme != scheme) { printk(FORE200E "bsq_audit(%d): queue %d.%d, buffer %ld, unexpected scheme = %d\n", where, scheme, magn, buffer->index, buffer->scheme); } if ((buffer->index < 0) || (buffer->index >= fore200e_rx_buf_nbr[ scheme ][ magn ])) { printk(FORE200E "bsq_audit(%d): queue %d.%d, out of range buffer index = %ld !\n", where, scheme, magn, buffer->index); } count++; buffer = buffer->next; } if (count != bsq->freebuf_count) { printk(FORE200E "bsq_audit(%d): queue %d.%d, %d bufs in free list, but freebuf_count = %d\n", where, scheme, magn, count, bsq->freebuf_count); } return 0; } #endif static void fore200e_supply(struct fore200e* fore200e) { int scheme, magn, i; struct host_bsq* bsq; struct host_bsq_entry* entry; struct buffer* buffer; for (scheme = 0; scheme < BUFFER_SCHEME_NBR; scheme++) { for (magn = 0; magn < BUFFER_MAGN_NBR; magn++) { bsq = &fore200e->host_bsq[ scheme ][ magn ]; #ifdef FORE200E_BSQ_DEBUG bsq_audit(1, bsq, scheme, magn); #endif while (bsq->freebuf_count >= RBD_BLK_SIZE) { DPRINTK(2, "supplying %d rx buffers to queue %d / %d, freebuf_count = %d\n", RBD_BLK_SIZE, scheme, magn, bsq->freebuf_count); entry = &bsq->host_entry[ bsq->head ]; for (i = 0; i < RBD_BLK_SIZE; i++) { /* take the first buffer in the free buffer list */ buffer = bsq->freebuf; if (!buffer) { printk(FORE200E "no more free bufs in queue %d.%d, but freebuf_count = %d\n", scheme, magn, bsq->freebuf_count); return; } bsq->freebuf = buffer->next; #ifdef FORE200E_BSQ_DEBUG if (buffer->supplied) printk(FORE200E "queue %d.%d, buffer %lu already supplied\n", scheme, magn, buffer->index); buffer->supplied = 1; #endif entry->rbd_block->rbd[ i ].buffer_haddr = buffer->data.dma_addr; entry->rbd_block->rbd[ i ].handle = FORE200E_BUF2HDL(buffer); } FORE200E_NEXT_ENTRY(bsq->head, QUEUE_SIZE_BS); /* decrease accordingly the number of free rx buffers */ bsq->freebuf_count -= RBD_BLK_SIZE; *entry->status = STATUS_PENDING; fore200e->bus->write(entry->rbd_block_dma, &entry->cp_entry->rbd_block_haddr); } } } } static int fore200e_push_rpd(struct fore200e* fore200e, struct atm_vcc* vcc, struct rpd* rpd) { struct sk_buff* skb; struct buffer* buffer; struct fore200e_vcc* fore200e_vcc; int i, pdu_len = 0; #ifdef FORE200E_52BYTE_AAL0_SDU u32 cell_header = 0; #endif ASSERT(vcc); fore200e_vcc = FORE200E_VCC(vcc); ASSERT(fore200e_vcc); #ifdef FORE200E_52BYTE_AAL0_SDU if ((vcc->qos.aal == ATM_AAL0) && (vcc->qos.rxtp.max_sdu == ATM_AAL0_SDU)) { cell_header = (rpd->atm_header.gfc << ATM_HDR_GFC_SHIFT) | (rpd->atm_header.vpi << ATM_HDR_VPI_SHIFT) | (rpd->atm_header.vci << ATM_HDR_VCI_SHIFT) | (rpd->atm_header.plt << ATM_HDR_PTI_SHIFT) | rpd->atm_header.clp; pdu_len = 4; } #endif /* compute total PDU length */ for (i = 0; i < rpd->nseg; i++) pdu_len += rpd->rsd[ i ].length; skb = alloc_skb(pdu_len, GFP_ATOMIC); if (skb == NULL) { DPRINTK(2, "unable to alloc new skb, rx PDU length = %d\n", pdu_len); atomic_inc(&vcc->stats->rx_drop); return -ENOMEM; } __net_timestamp(skb); #ifdef FORE200E_52BYTE_AAL0_SDU if (cell_header) { *((u32*)skb_put(skb, 4)) = cell_header; } #endif /* reassemble segments */ for (i = 0; i < rpd->nseg; i++) { /* rebuild rx buffer address from rsd handle */ buffer = FORE200E_HDL2BUF(rpd->rsd[ i ].handle); /* Make device DMA transfer visible to CPU. */ fore200e->bus->dma_sync_for_cpu(fore200e, buffer->data.dma_addr, rpd->rsd[ i ].length, DMA_FROM_DEVICE); memcpy(skb_put(skb, rpd->rsd[ i ].length), buffer->data.align_addr, rpd->rsd[ i ].length); /* Now let the device get at it again. */ fore200e->bus->dma_sync_for_device(fore200e, buffer->data.dma_addr, rpd->rsd[ i ].length, DMA_FROM_DEVICE); } DPRINTK(3, "rx skb: len = %d, truesize = %d\n", skb->len, skb->truesize); if (pdu_len < fore200e_vcc->rx_min_pdu) fore200e_vcc->rx_min_pdu = pdu_len; if (pdu_len > fore200e_vcc->rx_max_pdu) fore200e_vcc->rx_max_pdu = pdu_len; fore200e_vcc->rx_pdu++; /* push PDU */ if (atm_charge(vcc, skb->truesize) == 0) { DPRINTK(2, "receive buffers saturated for %d.%d.%d - PDU dropped\n", vcc->itf, vcc->vpi, vcc->vci); dev_kfree_skb_any(skb); atomic_inc(&vcc->stats->rx_drop); return -ENOMEM; } ASSERT(atomic_read(&sk_atm(vcc)->sk_wmem_alloc) >= 0); vcc->push(vcc, skb); atomic_inc(&vcc->stats->rx); ASSERT(atomic_read(&sk_atm(vcc)->sk_wmem_alloc) >= 0); return 0; } static void fore200e_collect_rpd(struct fore200e* fore200e, struct rpd* rpd) { struct host_bsq* bsq; struct buffer* buffer; int i; for (i = 0; i < rpd->nseg; i++) { /* rebuild rx buffer address from rsd handle */ buffer = FORE200E_HDL2BUF(rpd->rsd[ i ].handle); bsq = &fore200e->host_bsq[ buffer->scheme ][ buffer->magn ]; #ifdef FORE200E_BSQ_DEBUG bsq_audit(2, bsq, buffer->scheme, buffer->magn); if (buffer->supplied == 0) printk(FORE200E "queue %d.%d, buffer %ld was not supplied\n", buffer->scheme, buffer->magn, buffer->index); buffer->supplied = 0; #endif /* re-insert the buffer into the free buffer list */ buffer->next = bsq->freebuf; bsq->freebuf = buffer; /* then increment the number of free rx buffers */ bsq->freebuf_count++; } } static void fore200e_rx_irq(struct fore200e* fore200e) { struct host_rxq* rxq = &fore200e->host_rxq; struct host_rxq_entry* entry; struct atm_vcc* vcc; struct fore200e_vc_map* vc_map; for (;;) { entry = &rxq->host_entry[ rxq->head ]; /* no more received PDUs */ if ((*entry->status & STATUS_COMPLETE) == 0) break; vc_map = FORE200E_VC_MAP(fore200e, entry->rpd->atm_header.vpi, entry->rpd->atm_header.vci); if ((vc_map->vcc == NULL) || (test_bit(ATM_VF_READY, &vc_map->vcc->flags) == 0)) { DPRINTK(1, "no ready VC found for PDU received on %d.%d.%d\n", fore200e->atm_dev->number, entry->rpd->atm_header.vpi, entry->rpd->atm_header.vci); } else { vcc = vc_map->vcc; ASSERT(vcc); if ((*entry->status & STATUS_ERROR) == 0) { fore200e_push_rpd(fore200e, vcc, entry->rpd); } else { DPRINTK(2, "damaged PDU on %d.%d.%d\n", fore200e->atm_dev->number, entry->rpd->atm_header.vpi, entry->rpd->atm_header.vci); atomic_inc(&vcc->stats->rx_err); } } FORE200E_NEXT_ENTRY(rxq->head, QUEUE_SIZE_RX); fore200e_collect_rpd(fore200e, entry->rpd); /* rewrite the rpd address to ack the received PDU */ fore200e->bus->write(entry->rpd_dma, &entry->cp_entry->rpd_haddr); *entry->status = STATUS_FREE; fore200e_supply(fore200e); } } #ifndef FORE200E_USE_TASKLET static void fore200e_irq(struct fore200e* fore200e) { unsigned long flags; spin_lock_irqsave(&fore200e->q_lock, flags); fore200e_rx_irq(fore200e); spin_unlock_irqrestore(&fore200e->q_lock, flags); spin_lock_irqsave(&fore200e->q_lock, flags); fore200e_tx_irq(fore200e); spin_unlock_irqrestore(&fore200e->q_lock, flags); } #endif static irqreturn_t fore200e_interrupt(int irq, void* dev) { struct fore200e* fore200e = FORE200E_DEV((struct atm_dev*)dev); if (fore200e->bus->irq_check(fore200e) == 0) { DPRINTK(3, "interrupt NOT triggered by device %d\n", fore200e->atm_dev->number); return IRQ_NONE; } DPRINTK(3, "interrupt triggered by device %d\n", fore200e->atm_dev->number); #ifdef FORE200E_USE_TASKLET tasklet_schedule(&fore200e->tx_tasklet); tasklet_schedule(&fore200e->rx_tasklet); #else fore200e_irq(fore200e); #endif fore200e->bus->irq_ack(fore200e); return IRQ_HANDLED; } #ifdef FORE200E_USE_TASKLET static void fore200e_tx_tasklet(unsigned long data) { struct fore200e* fore200e = (struct fore200e*) data; unsigned long flags; DPRINTK(3, "tx tasklet scheduled for device %d\n", fore200e->atm_dev->number); spin_lock_irqsave(&fore200e->q_lock, flags); fore200e_tx_irq(fore200e); spin_unlock_irqrestore(&fore200e->q_lock, flags); } static void fore200e_rx_tasklet(unsigned long data) { struct fore200e* fore200e = (struct fore200e*) data; unsigned long flags; DPRINTK(3, "rx tasklet scheduled for device %d\n", fore200e->atm_dev->number); spin_lock_irqsave(&fore200e->q_lock, flags); fore200e_rx_irq((struct fore200e*) data); spin_unlock_irqrestore(&fore200e->q_lock, flags); } #endif static int fore200e_select_scheme(struct atm_vcc* vcc) { /* fairly balance the VCs over (identical) buffer schemes */ int scheme = vcc->vci % 2 ? BUFFER_SCHEME_ONE : BUFFER_SCHEME_TWO; DPRINTK(1, "VC %d.%d.%d uses buffer scheme %d\n", vcc->itf, vcc->vpi, vcc->vci, scheme); return scheme; } static int fore200e_activate_vcin(struct fore200e* fore200e, int activate, struct atm_vcc* vcc, int mtu) { struct host_cmdq* cmdq = &fore200e->host_cmdq; struct host_cmdq_entry* entry = &cmdq->host_entry[ cmdq->head ]; struct activate_opcode activ_opcode; struct deactivate_opcode deactiv_opcode; struct vpvc vpvc; int ok; enum fore200e_aal aal = fore200e_atm2fore_aal(vcc->qos.aal); FORE200E_NEXT_ENTRY(cmdq->head, QUEUE_SIZE_CMD); if (activate) { FORE200E_VCC(vcc)->scheme = fore200e_select_scheme(vcc); activ_opcode.opcode = OPCODE_ACTIVATE_VCIN; activ_opcode.aal = aal; activ_opcode.scheme = FORE200E_VCC(vcc)->scheme; activ_opcode.pad = 0; } else { deactiv_opcode.opcode = OPCODE_DEACTIVATE_VCIN; deactiv_opcode.pad = 0; } vpvc.vci = vcc->vci; vpvc.vpi = vcc->vpi; *entry->status = STATUS_PENDING; if (activate) { #ifdef FORE200E_52BYTE_AAL0_SDU mtu = 48; #endif /* the MTU is not used by the cp, except in the case of AAL0 */ fore200e->bus->write(mtu, &entry->cp_entry->cmd.activate_block.mtu); fore200e->bus->write(*(u32*)&vpvc, (u32 __iomem *)&entry->cp_entry->cmd.activate_block.vpvc); fore200e->bus->write(*(u32*)&activ_opcode, (u32 __iomem *)&entry->cp_entry->cmd.activate_block.opcode); } else { fore200e->bus->write(*(u32*)&vpvc, (u32 __iomem *)&entry->cp_entry->cmd.deactivate_block.vpvc); fore200e->bus->write(*(u32*)&deactiv_opcode, (u32 __iomem *)&entry->cp_entry->cmd.deactivate_block.opcode); } ok = fore200e_poll(fore200e, entry->status, STATUS_COMPLETE, 400); *entry->status = STATUS_FREE; if (ok == 0) { printk(FORE200E "unable to %s VC %d.%d.%d\n", activate ? "open" : "close", vcc->itf, vcc->vpi, vcc->vci); return -EIO; } DPRINTK(1, "VC %d.%d.%d %sed\n", vcc->itf, vcc->vpi, vcc->vci, activate ? "open" : "clos"); return 0; } #define FORE200E_MAX_BACK2BACK_CELLS 255 /* XXX depends on CDVT */ static void fore200e_rate_ctrl(struct atm_qos* qos, struct tpd_rate* rate) { if (qos->txtp.max_pcr < ATM_OC3_PCR) { /* compute the data cells to idle cells ratio from the tx PCR */ rate->data_cells = qos->txtp.max_pcr * FORE200E_MAX_BACK2BACK_CELLS / ATM_OC3_PCR; rate->idle_cells = FORE200E_MAX_BACK2BACK_CELLS - rate->data_cells; } else { /* disable rate control */ rate->data_cells = rate->idle_cells = 0; } } static int fore200e_open(struct atm_vcc *vcc) { struct fore200e* fore200e = FORE200E_DEV(vcc->dev); struct fore200e_vcc* fore200e_vcc; struct fore200e_vc_map* vc_map; unsigned long flags; int vci = vcc->vci; short vpi = vcc->vpi; ASSERT((vpi >= 0) && (vpi < 1<<FORE200E_VPI_BITS)); ASSERT((vci >= 0) && (vci < 1<<FORE200E_VCI_BITS)); spin_lock_irqsave(&fore200e->q_lock, flags); vc_map = FORE200E_VC_MAP(fore200e, vpi, vci); if (vc_map->vcc) { spin_unlock_irqrestore(&fore200e->q_lock, flags); printk(FORE200E "VC %d.%d.%d already in use\n", fore200e->atm_dev->number, vpi, vci); return -EINVAL; } vc_map->vcc = vcc; spin_unlock_irqrestore(&fore200e->q_lock, flags); fore200e_vcc = kzalloc(sizeof(struct fore200e_vcc), GFP_ATOMIC); if (fore200e_vcc == NULL) { vc_map->vcc = NULL; return -ENOMEM; } DPRINTK(2, "opening %d.%d.%d:%d QoS = (tx: cl=%s, pcr=%d-%d, cdv=%d, max_sdu=%d; " "rx: cl=%s, pcr=%d-%d, cdv=%d, max_sdu=%d)\n", vcc->itf, vcc->vpi, vcc->vci, fore200e_atm2fore_aal(vcc->qos.aal), fore200e_traffic_class[ vcc->qos.txtp.traffic_class ], vcc->qos.txtp.min_pcr, vcc->qos.txtp.max_pcr, vcc->qos.txtp.max_cdv, vcc->qos.txtp.max_sdu, fore200e_traffic_class[ vcc->qos.rxtp.traffic_class ], vcc->qos.rxtp.min_pcr, vcc->qos.rxtp.max_pcr, vcc->qos.rxtp.max_cdv, vcc->qos.rxtp.max_sdu); /* pseudo-CBR bandwidth requested? */ if ((vcc->qos.txtp.traffic_class == ATM_CBR) && (vcc->qos.txtp.max_pcr > 0)) { mutex_lock(&fore200e->rate_mtx); if (fore200e->available_cell_rate < vcc->qos.txtp.max_pcr) { mutex_unlock(&fore200e->rate_mtx); kfree(fore200e_vcc); vc_map->vcc = NULL; return -EAGAIN; } /* reserve bandwidth */ fore200e->available_cell_rate -= vcc->qos.txtp.max_pcr; mutex_unlock(&fore200e->rate_mtx); } vcc->itf = vcc->dev->number; set_bit(ATM_VF_PARTIAL,&vcc->flags); set_bit(ATM_VF_ADDR, &vcc->flags); vcc->dev_data = fore200e_vcc; if (fore200e_activate_vcin(fore200e, 1, vcc, vcc->qos.rxtp.max_sdu) < 0) { vc_map->vcc = NULL; clear_bit(ATM_VF_ADDR, &vcc->flags); clear_bit(ATM_VF_PARTIAL,&vcc->flags); vcc->dev_data = NULL; fore200e->available_cell_rate += vcc->qos.txtp.max_pcr; kfree(fore200e_vcc); return -EINVAL; } /* compute rate control parameters */ if ((vcc->qos.txtp.traffic_class == ATM_CBR) && (vcc->qos.txtp.max_pcr > 0)) { fore200e_rate_ctrl(&vcc->qos, &fore200e_vcc->rate); set_bit(ATM_VF_HASQOS, &vcc->flags); DPRINTK(3, "tx on %d.%d.%d:%d, tx PCR = %d, rx PCR = %d, data_cells = %u, idle_cells = %u\n", vcc->itf, vcc->vpi, vcc->vci, fore200e_atm2fore_aal(vcc->qos.aal), vcc->qos.txtp.max_pcr, vcc->qos.rxtp.max_pcr, fore200e_vcc->rate.data_cells, fore200e_vcc->rate.idle_cells); } fore200e_vcc->tx_min_pdu = fore200e_vcc->rx_min_pdu = MAX_PDU_SIZE + 1; fore200e_vcc->tx_max_pdu = fore200e_vcc->rx_max_pdu = 0; fore200e_vcc->tx_pdu = fore200e_vcc->rx_pdu = 0; /* new incarnation of the vcc */ vc_map->incarn = ++fore200e->incarn_count; /* VC unusable before this flag is set */ set_bit(ATM_VF_READY, &vcc->flags); return 0; } static void fore200e_close(struct atm_vcc* vcc) { struct fore200e* fore200e = FORE200E_DEV(vcc->dev); struct fore200e_vcc* fore200e_vcc; struct fore200e_vc_map* vc_map; unsigned long flags; ASSERT(vcc); ASSERT((vcc->vpi >= 0) && (vcc->vpi < 1<<FORE200E_VPI_BITS)); ASSERT((vcc->vci >= 0) && (vcc->vci < 1<<FORE200E_VCI_BITS)); DPRINTK(2, "closing %d.%d.%d:%d\n", vcc->itf, vcc->vpi, vcc->vci, fore200e_atm2fore_aal(vcc->qos.aal)); clear_bit(ATM_VF_READY, &vcc->flags); fore200e_activate_vcin(fore200e, 0, vcc, 0); spin_lock_irqsave(&fore200e->q_lock, flags); vc_map = FORE200E_VC_MAP(fore200e, vcc->vpi, vcc->vci); /* the vc is no longer considered as "in use" by fore200e_open() */ vc_map->vcc = NULL; vcc->itf = vcc->vci = vcc->vpi = 0; fore200e_vcc = FORE200E_VCC(vcc); vcc->dev_data = NULL; spin_unlock_irqrestore(&fore200e->q_lock, flags); /* release reserved bandwidth, if any */ if ((vcc->qos.txtp.traffic_class == ATM_CBR) && (vcc->qos.txtp.max_pcr > 0)) { mutex_lock(&fore200e->rate_mtx); fore200e->available_cell_rate += vcc->qos.txtp.max_pcr; mutex_unlock(&fore200e->rate_mtx); clear_bit(ATM_VF_HASQOS, &vcc->flags); } clear_bit(ATM_VF_ADDR, &vcc->flags); clear_bit(ATM_VF_PARTIAL,&vcc->flags); ASSERT(fore200e_vcc); kfree(fore200e_vcc); } static int fore200e_send(struct atm_vcc *vcc, struct sk_buff *skb) { struct fore200e* fore200e = FORE200E_DEV(vcc->dev); struct fore200e_vcc* fore200e_vcc = FORE200E_VCC(vcc); struct fore200e_vc_map* vc_map; struct host_txq* txq = &fore200e->host_txq; struct host_txq_entry* entry; struct tpd* tpd; struct tpd_haddr tpd_haddr; int retry = CONFIG_ATM_FORE200E_TX_RETRY; int tx_copy = 0; int tx_len = skb->len; u32* cell_header = NULL; unsigned char* skb_data; int skb_len; unsigned char* data; unsigned long flags; ASSERT(vcc); ASSERT(atomic_read(&sk_atm(vcc)->sk_wmem_alloc) >= 0); ASSERT(fore200e); ASSERT(fore200e_vcc); if (!test_bit(ATM_VF_READY, &vcc->flags)) { DPRINTK(1, "VC %d.%d.%d not ready for tx\n", vcc->itf, vcc->vpi, vcc->vpi); dev_kfree_skb_any(skb); return -EINVAL; } #ifdef FORE200E_52BYTE_AAL0_SDU if ((vcc->qos.aal == ATM_AAL0) && (vcc->qos.txtp.max_sdu == ATM_AAL0_SDU)) { cell_header = (u32*) skb->data; skb_data = skb->data + 4; /* skip 4-byte cell header */ skb_len = tx_len = skb->len - 4; DPRINTK(3, "user-supplied cell header = 0x%08x\n", *cell_header); } else #endif { skb_data = skb->data; skb_len = skb->len; } if (((unsigned long)skb_data) & 0x3) { DPRINTK(2, "misaligned tx PDU on device %s\n", fore200e->name); tx_copy = 1; tx_len = skb_len; } if ((vcc->qos.aal == ATM_AAL0) && (skb_len % ATM_CELL_PAYLOAD)) { /* this simply NUKES the PCA board */ DPRINTK(2, "incomplete tx AAL0 PDU on device %s\n", fore200e->name); tx_copy = 1; tx_len = ((skb_len / ATM_CELL_PAYLOAD) + 1) * ATM_CELL_PAYLOAD; } if (tx_copy) { data = kmalloc(tx_len, GFP_ATOMIC | GFP_DMA); if (data == NULL) { if (vcc->pop) { vcc->pop(vcc, skb); } else { dev_kfree_skb_any(skb); } return -ENOMEM; } memcpy(data, skb_data, skb_len); if (skb_len < tx_len) memset(data + skb_len, 0x00, tx_len - skb_len); } else { data = skb_data; } vc_map = FORE200E_VC_MAP(fore200e, vcc->vpi, vcc->vci); ASSERT(vc_map->vcc == vcc); retry_here: spin_lock_irqsave(&fore200e->q_lock, flags); entry = &txq->host_entry[ txq->head ]; if ((*entry->status != STATUS_FREE) || (txq->txing >= QUEUE_SIZE_TX - 2)) { /* try to free completed tx queue entries */ fore200e_tx_irq(fore200e); if (*entry->status != STATUS_FREE) { spin_unlock_irqrestore(&fore200e->q_lock, flags); /* retry once again? */ if (--retry > 0) { udelay(50); goto retry_here; } atomic_inc(&vcc->stats->tx_err); fore200e->tx_sat++; DPRINTK(2, "tx queue of device %s is saturated, PDU dropped - heartbeat is %08x\n", fore200e->name, fore200e->cp_queues->heartbeat); if (vcc->pop) { vcc->pop(vcc, skb); } else { dev_kfree_skb_any(skb); } if (tx_copy) kfree(data); return -ENOBUFS; } } entry->incarn = vc_map->incarn; entry->vc_map = vc_map; entry->skb = skb; entry->data = tx_copy ? data : NULL; tpd = entry->tpd; tpd->tsd[ 0 ].buffer = fore200e->bus->dma_map(fore200e, data, tx_len, DMA_TO_DEVICE); tpd->tsd[ 0 ].length = tx_len; FORE200E_NEXT_ENTRY(txq->head, QUEUE_SIZE_TX); txq->txing++; /* The dma_map call above implies a dma_sync so the device can use it, * thus no explicit dma_sync call is necessary here. */ DPRINTK(3, "tx on %d.%d.%d:%d, len = %u (%u)\n", vcc->itf, vcc->vpi, vcc->vci, fore200e_atm2fore_aal(vcc->qos.aal), tpd->tsd[0].length, skb_len); if (skb_len < fore200e_vcc->tx_min_pdu) fore200e_vcc->tx_min_pdu = skb_len; if (skb_len > fore200e_vcc->tx_max_pdu) fore200e_vcc->tx_max_pdu = skb_len; fore200e_vcc->tx_pdu++; /* set tx rate control information */ tpd->rate.data_cells = fore200e_vcc->rate.data_cells; tpd->rate.idle_cells = fore200e_vcc->rate.idle_cells; if (cell_header) { tpd->atm_header.clp = (*cell_header & ATM_HDR_CLP); tpd->atm_header.plt = (*cell_header & ATM_HDR_PTI_MASK) >> ATM_HDR_PTI_SHIFT; tpd->atm_header.vci = (*cell_header & ATM_HDR_VCI_MASK) >> ATM_HDR_VCI_SHIFT; tpd->atm_header.vpi = (*cell_header & ATM_HDR_VPI_MASK) >> ATM_HDR_VPI_SHIFT; tpd->atm_header.gfc = (*cell_header & ATM_HDR_GFC_MASK) >> ATM_HDR_GFC_SHIFT; } else { /* set the ATM header, common to all cells conveying the PDU */ tpd->atm_header.clp = 0; tpd->atm_header.plt = 0; tpd->atm_header.vci = vcc->vci; tpd->atm_header.vpi = vcc->vpi; tpd->atm_header.gfc = 0; } tpd->spec.length = tx_len; tpd->spec.nseg = 1; tpd->spec.aal = fore200e_atm2fore_aal(vcc->qos.aal); tpd->spec.intr = 1; tpd_haddr.size = sizeof(struct tpd) / (1<<TPD_HADDR_SHIFT); /* size is expressed in 32 byte blocks */ tpd_haddr.pad = 0; tpd_haddr.haddr = entry->tpd_dma >> TPD_HADDR_SHIFT; /* shift the address, as we are in a bitfield */ *entry->status = STATUS_PENDING; fore200e->bus->write(*(u32*)&tpd_haddr, (u32 __iomem *)&entry->cp_entry->tpd_haddr); spin_unlock_irqrestore(&fore200e->q_lock, flags); return 0; } static int fore200e_getstats(struct fore200e* fore200e) { struct host_cmdq* cmdq = &fore200e->host_cmdq; struct host_cmdq_entry* entry = &cmdq->host_entry[ cmdq->head ]; struct stats_opcode opcode; int ok; u32 stats_dma_addr; if (fore200e->stats == NULL) { fore200e->stats = kzalloc(sizeof(struct stats), GFP_KERNEL | GFP_DMA); if (fore200e->stats == NULL) return -ENOMEM; } stats_dma_addr = fore200e->bus->dma_map(fore200e, fore200e->stats, sizeof(struct stats), DMA_FROM_DEVICE); FORE200E_NEXT_ENTRY(cmdq->head, QUEUE_SIZE_CMD); opcode.opcode = OPCODE_GET_STATS; opcode.pad = 0; fore200e->bus->write(stats_dma_addr, &entry->cp_entry->cmd.stats_block.stats_haddr); *entry->status = STATUS_PENDING; fore200e->bus->write(*(u32*)&opcode, (u32 __iomem *)&entry->cp_entry->cmd.stats_block.opcode); ok = fore200e_poll(fore200e, entry->status, STATUS_COMPLETE, 400); *entry->status = STATUS_FREE; fore200e->bus->dma_unmap(fore200e, stats_dma_addr, sizeof(struct stats), DMA_FROM_DEVICE); if (ok == 0) { printk(FORE200E "unable to get statistics from device %s\n", fore200e->name); return -EIO; } return 0; } static int fore200e_getsockopt(struct atm_vcc* vcc, int level, int optname, void __user *optval, int optlen) { /* struct fore200e* fore200e = FORE200E_DEV(vcc->dev); */ DPRINTK(2, "getsockopt %d.%d.%d, level = %d, optname = 0x%x, optval = 0x%p, optlen = %d\n", vcc->itf, vcc->vpi, vcc->vci, level, optname, optval, optlen); return -EINVAL; } static int fore200e_setsockopt(struct atm_vcc* vcc, int level, int optname, void __user *optval, unsigned int optlen) { /* struct fore200e* fore200e = FORE200E_DEV(vcc->dev); */ DPRINTK(2, "setsockopt %d.%d.%d, level = %d, optname = 0x%x, optval = 0x%p, optlen = %d\n", vcc->itf, vcc->vpi, vcc->vci, level, optname, optval, optlen); return -EINVAL; } #if 0 /* currently unused */ static int fore200e_get_oc3(struct fore200e* fore200e, struct oc3_regs* regs) { struct host_cmdq* cmdq = &fore200e->host_cmdq; struct host_cmdq_entry* entry = &cmdq->host_entry[ cmdq->head ]; struct oc3_opcode opcode; int ok; u32 oc3_regs_dma_addr; oc3_regs_dma_addr = fore200e->bus->dma_map(fore200e, regs, sizeof(struct oc3_regs), DMA_FROM_DEVICE); FORE200E_NEXT_ENTRY(cmdq->head, QUEUE_SIZE_CMD); opcode.opcode = OPCODE_GET_OC3; opcode.reg = 0; opcode.value = 0; opcode.mask = 0; fore200e->bus->write(oc3_regs_dma_addr, &entry->cp_entry->cmd.oc3_block.regs_haddr); *entry->status = STATUS_PENDING; fore200e->bus->write(*(u32*)&opcode, (u32*)&entry->cp_entry->cmd.oc3_block.opcode); ok = fore200e_poll(fore200e, entry->status, STATUS_COMPLETE, 400); *entry->status = STATUS_FREE; fore200e->bus->dma_unmap(fore200e, oc3_regs_dma_addr, sizeof(struct oc3_regs), DMA_FROM_DEVICE); if (ok == 0) { printk(FORE200E "unable to get OC-3 regs of device %s\n", fore200e->name); return -EIO; } return 0; } #endif static int fore200e_set_oc3(struct fore200e* fore200e, u32 reg, u32 value, u32 mask) { struct host_cmdq* cmdq = &fore200e->host_cmdq; struct host_cmdq_entry* entry = &cmdq->host_entry[ cmdq->head ]; struct oc3_opcode opcode; int ok; DPRINTK(2, "set OC-3 reg = 0x%02x, value = 0x%02x, mask = 0x%02x\n", reg, value, mask); FORE200E_NEXT_ENTRY(cmdq->head, QUEUE_SIZE_CMD); opcode.opcode = OPCODE_SET_OC3; opcode.reg = reg; opcode.value = value; opcode.mask = mask; fore200e->bus->write(0, &entry->cp_entry->cmd.oc3_block.regs_haddr); *entry->status = STATUS_PENDING; fore200e->bus->write(*(u32*)&opcode, (u32 __iomem *)&entry->cp_entry->cmd.oc3_block.opcode); ok = fore200e_poll(fore200e, entry->status, STATUS_COMPLETE, 400); *entry->status = STATUS_FREE; if (ok == 0) { printk(FORE200E "unable to set OC-3 reg 0x%02x of device %s\n", reg, fore200e->name); return -EIO; } return 0; } static int fore200e_setloop(struct fore200e* fore200e, int loop_mode) { u32 mct_value, mct_mask; int error; if (!capable(CAP_NET_ADMIN)) return -EPERM; switch (loop_mode) { case ATM_LM_NONE: mct_value = 0; mct_mask = SUNI_MCT_DLE | SUNI_MCT_LLE; break; case ATM_LM_LOC_PHY: mct_value = mct_mask = SUNI_MCT_DLE; break; case ATM_LM_RMT_PHY: mct_value = mct_mask = SUNI_MCT_LLE; break; default: return -EINVAL; } error = fore200e_set_oc3(fore200e, SUNI_MCT, mct_value, mct_mask); if (error == 0) fore200e->loop_mode = loop_mode; return error; } static int fore200e_fetch_stats(struct fore200e* fore200e, struct sonet_stats __user *arg) { struct sonet_stats tmp; if (fore200e_getstats(fore200e) < 0) return -EIO; tmp.section_bip = be32_to_cpu(fore200e->stats->oc3.section_bip8_errors); tmp.line_bip = be32_to_cpu(fore200e->stats->oc3.line_bip24_errors); tmp.path_bip = be32_to_cpu(fore200e->stats->oc3.path_bip8_errors); tmp.line_febe = be32_to_cpu(fore200e->stats->oc3.line_febe_errors); tmp.path_febe = be32_to_cpu(fore200e->stats->oc3.path_febe_errors); tmp.corr_hcs = be32_to_cpu(fore200e->stats->oc3.corr_hcs_errors); tmp.uncorr_hcs = be32_to_cpu(fore200e->stats->oc3.ucorr_hcs_errors); tmp.tx_cells = be32_to_cpu(fore200e->stats->aal0.cells_transmitted) + be32_to_cpu(fore200e->stats->aal34.cells_transmitted) + be32_to_cpu(fore200e->stats->aal5.cells_transmitted); tmp.rx_cells = be32_to_cpu(fore200e->stats->aal0.cells_received) + be32_to_cpu(fore200e->stats->aal34.cells_received) + be32_to_cpu(fore200e->stats->aal5.cells_received); if (arg) return copy_to_user(arg, &tmp, sizeof(struct sonet_stats)) ? -EFAULT : 0; return 0; } static int fore200e_ioctl(struct atm_dev* dev, unsigned int cmd, void __user * arg) { struct fore200e* fore200e = FORE200E_DEV(dev); DPRINTK(2, "ioctl cmd = 0x%x (%u), arg = 0x%p (%lu)\n", cmd, cmd, arg, (unsigned long)arg); switch (cmd) { case SONET_GETSTAT: return fore200e_fetch_stats(fore200e, (struct sonet_stats __user *)arg); case SONET_GETDIAG: return put_user(0, (int __user *)arg) ? -EFAULT : 0; case ATM_SETLOOP: return fore200e_setloop(fore200e, (int)(unsigned long)arg); case ATM_GETLOOP: return put_user(fore200e->loop_mode, (int __user *)arg) ? -EFAULT : 0; case ATM_QUERYLOOP: return put_user(ATM_LM_LOC_PHY | ATM_LM_RMT_PHY, (int __user *)arg) ? -EFAULT : 0; } return -ENOSYS; /* not implemented */ } static int fore200e_change_qos(struct atm_vcc* vcc,struct atm_qos* qos, int flags) { struct fore200e_vcc* fore200e_vcc = FORE200E_VCC(vcc); struct fore200e* fore200e = FORE200E_DEV(vcc->dev); if (!test_bit(ATM_VF_READY, &vcc->flags)) { DPRINTK(1, "VC %d.%d.%d not ready for QoS change\n", vcc->itf, vcc->vpi, vcc->vpi); return -EINVAL; } DPRINTK(2, "change_qos %d.%d.%d, " "(tx: cl=%s, pcr=%d-%d, cdv=%d, max_sdu=%d; " "rx: cl=%s, pcr=%d-%d, cdv=%d, max_sdu=%d), flags = 0x%x\n" "available_cell_rate = %u", vcc->itf, vcc->vpi, vcc->vci, fore200e_traffic_class[ qos->txtp.traffic_class ], qos->txtp.min_pcr, qos->txtp.max_pcr, qos->txtp.max_cdv, qos->txtp.max_sdu, fore200e_traffic_class[ qos->rxtp.traffic_class ], qos->rxtp.min_pcr, qos->rxtp.max_pcr, qos->rxtp.max_cdv, qos->rxtp.max_sdu, flags, fore200e->available_cell_rate); if ((qos->txtp.traffic_class == ATM_CBR) && (qos->txtp.max_pcr > 0)) { mutex_lock(&fore200e->rate_mtx); if (fore200e->available_cell_rate + vcc->qos.txtp.max_pcr < qos->txtp.max_pcr) { mutex_unlock(&fore200e->rate_mtx); return -EAGAIN; } fore200e->available_cell_rate += vcc->qos.txtp.max_pcr; fore200e->available_cell_rate -= qos->txtp.max_pcr; mutex_unlock(&fore200e->rate_mtx); memcpy(&vcc->qos, qos, sizeof(struct atm_qos)); /* update rate control parameters */ fore200e_rate_ctrl(qos, &fore200e_vcc->rate); set_bit(ATM_VF_HASQOS, &vcc->flags); return 0; } return -EINVAL; } static int __devinit fore200e_irq_request(struct fore200e* fore200e) { if (request_irq(fore200e->irq, fore200e_interrupt, IRQF_SHARED, fore200e->name, fore200e->atm_dev) < 0) { printk(FORE200E "unable to reserve IRQ %s for device %s\n", fore200e_irq_itoa(fore200e->irq), fore200e->name); return -EBUSY; } printk(FORE200E "IRQ %s reserved for device %s\n", fore200e_irq_itoa(fore200e->irq), fore200e->name); #ifdef FORE200E_USE_TASKLET tasklet_init(&fore200e->tx_tasklet, fore200e_tx_tasklet, (unsigned long)fore200e); tasklet_init(&fore200e->rx_tasklet, fore200e_rx_tasklet, (unsigned long)fore200e); #endif fore200e->state = FORE200E_STATE_IRQ; return 0; } static int __devinit fore200e_get_esi(struct fore200e* fore200e) { struct prom_data* prom = kzalloc(sizeof(struct prom_data), GFP_KERNEL | GFP_DMA); int ok, i; if (!prom) return -ENOMEM; ok = fore200e->bus->prom_read(fore200e, prom); if (ok < 0) { kfree(prom); return -EBUSY; } printk(FORE200E "device %s, rev. %c, S/N: %d, ESI: %pM\n", fore200e->name, (prom->hw_revision & 0xFF) + '@', /* probably meaningless with SBA boards */ prom->serial_number & 0xFFFF, &prom->mac_addr[2]); for (i = 0; i < ESI_LEN; i++) { fore200e->esi[ i ] = fore200e->atm_dev->esi[ i ] = prom->mac_addr[ i + 2 ]; } kfree(prom); return 0; } static int __devinit fore200e_alloc_rx_buf(struct fore200e* fore200e) { int scheme, magn, nbr, size, i; struct host_bsq* bsq; struct buffer* buffer; for (scheme = 0; scheme < BUFFER_SCHEME_NBR; scheme++) { for (magn = 0; magn < BUFFER_MAGN_NBR; magn++) { bsq = &fore200e->host_bsq[ scheme ][ magn ]; nbr = fore200e_rx_buf_nbr[ scheme ][ magn ]; size = fore200e_rx_buf_size[ scheme ][ magn ]; DPRINTK(2, "rx buffers %d / %d are being allocated\n", scheme, magn); /* allocate the array of receive buffers */ buffer = bsq->buffer = kzalloc(nbr * sizeof(struct buffer), GFP_KERNEL); if (buffer == NULL) return -ENOMEM; bsq->freebuf = NULL; for (i = 0; i < nbr; i++) { buffer[ i ].scheme = scheme; buffer[ i ].magn = magn; #ifdef FORE200E_BSQ_DEBUG buffer[ i ].index = i; buffer[ i ].supplied = 0; #endif /* allocate the receive buffer body */ if (fore200e_chunk_alloc(fore200e, &buffer[ i ].data, size, fore200e->bus->buffer_alignment, DMA_FROM_DEVICE) < 0) { while (i > 0) fore200e_chunk_free(fore200e, &buffer[ --i ].data); kfree(buffer); return -ENOMEM; } /* insert the buffer into the free buffer list */ buffer[ i ].next = bsq->freebuf; bsq->freebuf = &buffer[ i ]; } /* all the buffers are free, initially */ bsq->freebuf_count = nbr; #ifdef FORE200E_BSQ_DEBUG bsq_audit(3, bsq, scheme, magn); #endif } } fore200e->state = FORE200E_STATE_ALLOC_BUF; return 0; } static int __devinit fore200e_init_bs_queue(struct fore200e* fore200e) { int scheme, magn, i; struct host_bsq* bsq; struct cp_bsq_entry __iomem * cp_entry; for (scheme = 0; scheme < BUFFER_SCHEME_NBR; scheme++) { for (magn = 0; magn < BUFFER_MAGN_NBR; magn++) { DPRINTK(2, "buffer supply queue %d / %d is being initialized\n", scheme, magn); bsq = &fore200e->host_bsq[ scheme ][ magn ]; /* allocate and align the array of status words */ if (fore200e->bus->dma_chunk_alloc(fore200e, &bsq->status, sizeof(enum status), QUEUE_SIZE_BS, fore200e->bus->status_alignment) < 0) { return -ENOMEM; } /* allocate and align the array of receive buffer descriptors */ if (fore200e->bus->dma_chunk_alloc(fore200e, &bsq->rbd_block, sizeof(struct rbd_block), QUEUE_SIZE_BS, fore200e->bus->descr_alignment) < 0) { fore200e->bus->dma_chunk_free(fore200e, &bsq->status); return -ENOMEM; } /* get the base address of the cp resident buffer supply queue entries */ cp_entry = fore200e->virt_base + fore200e->bus->read(&fore200e->cp_queues->cp_bsq[ scheme ][ magn ]); /* fill the host resident and cp resident buffer supply queue entries */ for (i = 0; i < QUEUE_SIZE_BS; i++) { bsq->host_entry[ i ].status = FORE200E_INDEX(bsq->status.align_addr, enum status, i); bsq->host_entry[ i ].rbd_block = FORE200E_INDEX(bsq->rbd_block.align_addr, struct rbd_block, i); bsq->host_entry[ i ].rbd_block_dma = FORE200E_DMA_INDEX(bsq->rbd_block.dma_addr, struct rbd_block, i); bsq->host_entry[ i ].cp_entry = &cp_entry[ i ]; *bsq->host_entry[ i ].status = STATUS_FREE; fore200e->bus->write(FORE200E_DMA_INDEX(bsq->status.dma_addr, enum status, i), &cp_entry[ i ].status_haddr); } } } fore200e->state = FORE200E_STATE_INIT_BSQ; return 0; } static int __devinit fore200e_init_rx_queue(struct fore200e* fore200e) { struct host_rxq* rxq = &fore200e->host_rxq; struct cp_rxq_entry __iomem * cp_entry; int i; DPRINTK(2, "receive queue is being initialized\n"); /* allocate and align the array of status words */ if (fore200e->bus->dma_chunk_alloc(fore200e, &rxq->status, sizeof(enum status), QUEUE_SIZE_RX, fore200e->bus->status_alignment) < 0) { return -ENOMEM; } /* allocate and align the array of receive PDU descriptors */ if (fore200e->bus->dma_chunk_alloc(fore200e, &rxq->rpd, sizeof(struct rpd), QUEUE_SIZE_RX, fore200e->bus->descr_alignment) < 0) { fore200e->bus->dma_chunk_free(fore200e, &rxq->status); return -ENOMEM; } /* get the base address of the cp resident rx queue entries */ cp_entry = fore200e->virt_base + fore200e->bus->read(&fore200e->cp_queues->cp_rxq); /* fill the host resident and cp resident rx entries */ for (i=0; i < QUEUE_SIZE_RX; i++) { rxq->host_entry[ i ].status = FORE200E_INDEX(rxq->status.align_addr, enum status, i); rxq->host_entry[ i ].rpd = FORE200E_INDEX(rxq->rpd.align_addr, struct rpd, i); rxq->host_entry[ i ].rpd_dma = FORE200E_DMA_INDEX(rxq->rpd.dma_addr, struct rpd, i); rxq->host_entry[ i ].cp_entry = &cp_entry[ i ]; *rxq->host_entry[ i ].status = STATUS_FREE; fore200e->bus->write(FORE200E_DMA_INDEX(rxq->status.dma_addr, enum status, i), &cp_entry[ i ].status_haddr); fore200e->bus->write(FORE200E_DMA_INDEX(rxq->rpd.dma_addr, struct rpd, i), &cp_entry[ i ].rpd_haddr); } /* set the head entry of the queue */ rxq->head = 0; fore200e->state = FORE200E_STATE_INIT_RXQ; return 0; } static int __devinit fore200e_init_tx_queue(struct fore200e* fore200e) { struct host_txq* txq = &fore200e->host_txq; struct cp_txq_entry __iomem * cp_entry; int i; DPRINTK(2, "transmit queue is being initialized\n"); /* allocate and align the array of status words */ if (fore200e->bus->dma_chunk_alloc(fore200e, &txq->status, sizeof(enum status), QUEUE_SIZE_TX, fore200e->bus->status_alignment) < 0) { return -ENOMEM; } /* allocate and align the array of transmit PDU descriptors */ if (fore200e->bus->dma_chunk_alloc(fore200e, &txq->tpd, sizeof(struct tpd), QUEUE_SIZE_TX, fore200e->bus->descr_alignment) < 0) { fore200e->bus->dma_chunk_free(fore200e, &txq->status); return -ENOMEM; } /* get the base address of the cp resident tx queue entries */ cp_entry = fore200e->virt_base + fore200e->bus->read(&fore200e->cp_queues->cp_txq); /* fill the host resident and cp resident tx entries */ for (i=0; i < QUEUE_SIZE_TX; i++) { txq->host_entry[ i ].status = FORE200E_INDEX(txq->status.align_addr, enum status, i); txq->host_entry[ i ].tpd = FORE200E_INDEX(txq->tpd.align_addr, struct tpd, i); txq->host_entry[ i ].tpd_dma = FORE200E_DMA_INDEX(txq->tpd.dma_addr, struct tpd, i); txq->host_entry[ i ].cp_entry = &cp_entry[ i ]; *txq->host_entry[ i ].status = STATUS_FREE; fore200e->bus->write(FORE200E_DMA_INDEX(txq->status.dma_addr, enum status, i), &cp_entry[ i ].status_haddr); /* although there is a one-to-one mapping of tx queue entries and tpds, we do not write here the DMA (physical) base address of each tpd into the related cp resident entry, because the cp relies on this write operation to detect that a new pdu has been submitted for tx */ } /* set the head and tail entries of the queue */ txq->head = 0; txq->tail = 0; fore200e->state = FORE200E_STATE_INIT_TXQ; return 0; } static int __devinit fore200e_init_cmd_queue(struct fore200e* fore200e) { struct host_cmdq* cmdq = &fore200e->host_cmdq; struct cp_cmdq_entry __iomem * cp_entry; int i; DPRINTK(2, "command queue is being initialized\n"); /* allocate and align the array of status words */ if (fore200e->bus->dma_chunk_alloc(fore200e, &cmdq->status, sizeof(enum status), QUEUE_SIZE_CMD, fore200e->bus->status_alignment) < 0) { return -ENOMEM; } /* get the base address of the cp resident cmd queue entries */ cp_entry = fore200e->virt_base + fore200e->bus->read(&fore200e->cp_queues->cp_cmdq); /* fill the host resident and cp resident cmd entries */ for (i=0; i < QUEUE_SIZE_CMD; i++) { cmdq->host_entry[ i ].status = FORE200E_INDEX(cmdq->status.align_addr, enum status, i); cmdq->host_entry[ i ].cp_entry = &cp_entry[ i ]; *cmdq->host_entry[ i ].status = STATUS_FREE; fore200e->bus->write(FORE200E_DMA_INDEX(cmdq->status.dma_addr, enum status, i), &cp_entry[ i ].status_haddr); } /* set the head entry of the queue */ cmdq->head = 0; fore200e->state = FORE200E_STATE_INIT_CMDQ; return 0; } static void __devinit fore200e_param_bs_queue(struct fore200e* fore200e, enum buffer_scheme scheme, enum buffer_magn magn, int queue_length, int pool_size, int supply_blksize) { struct bs_spec __iomem * bs_spec = &fore200e->cp_queues->init.bs_spec[ scheme ][ magn ]; fore200e->bus->write(queue_length, &bs_spec->queue_length); fore200e->bus->write(fore200e_rx_buf_size[ scheme ][ magn ], &bs_spec->buffer_size); fore200e->bus->write(pool_size, &bs_spec->pool_size); fore200e->bus->write(supply_blksize, &bs_spec->supply_blksize); } static int __devinit fore200e_initialize(struct fore200e* fore200e) { struct cp_queues __iomem * cpq; int ok, scheme, magn; DPRINTK(2, "device %s being initialized\n", fore200e->name); mutex_init(&fore200e->rate_mtx); spin_lock_init(&fore200e->q_lock); cpq = fore200e->cp_queues = fore200e->virt_base + FORE200E_CP_QUEUES_OFFSET; /* enable cp to host interrupts */ fore200e->bus->write(1, &cpq->imask); if (fore200e->bus->irq_enable) fore200e->bus->irq_enable(fore200e); fore200e->bus->write(NBR_CONNECT, &cpq->init.num_connect); fore200e->bus->write(QUEUE_SIZE_CMD, &cpq->init.cmd_queue_len); fore200e->bus->write(QUEUE_SIZE_RX, &cpq->init.rx_queue_len); fore200e->bus->write(QUEUE_SIZE_TX, &cpq->init.tx_queue_len); fore200e->bus->write(RSD_EXTENSION, &cpq->init.rsd_extension); fore200e->bus->write(TSD_EXTENSION, &cpq->init.tsd_extension); for (scheme = 0; scheme < BUFFER_SCHEME_NBR; scheme++) for (magn = 0; magn < BUFFER_MAGN_NBR; magn++) fore200e_param_bs_queue(fore200e, scheme, magn, QUEUE_SIZE_BS, fore200e_rx_buf_nbr[ scheme ][ magn ], RBD_BLK_SIZE); /* issue the initialize command */ fore200e->bus->write(STATUS_PENDING, &cpq->init.status); fore200e->bus->write(OPCODE_INITIALIZE, &cpq->init.opcode); ok = fore200e_io_poll(fore200e, &cpq->init.status, STATUS_COMPLETE, 3000); if (ok == 0) { printk(FORE200E "device %s initialization failed\n", fore200e->name); return -ENODEV; } printk(FORE200E "device %s initialized\n", fore200e->name); fore200e->state = FORE200E_STATE_INITIALIZE; return 0; } static void __devinit fore200e_monitor_putc(struct fore200e* fore200e, char c) { struct cp_monitor __iomem * monitor = fore200e->cp_monitor; #if 0 printk("%c", c); #endif fore200e->bus->write(((u32) c) | FORE200E_CP_MONITOR_UART_AVAIL, &monitor->soft_uart.send); } static int __devinit fore200e_monitor_getc(struct fore200e* fore200e) { struct cp_monitor __iomem * monitor = fore200e->cp_monitor; unsigned long timeout = jiffies + msecs_to_jiffies(50); int c; while (time_before(jiffies, timeout)) { c = (int) fore200e->bus->read(&monitor->soft_uart.recv); if (c & FORE200E_CP_MONITOR_UART_AVAIL) { fore200e->bus->write(FORE200E_CP_MONITOR_UART_FREE, &monitor->soft_uart.recv); #if 0 printk("%c", c & 0xFF); #endif return c & 0xFF; } } return -1; } static void __devinit fore200e_monitor_puts(struct fore200e* fore200e, char* str) { while (*str) { /* the i960 monitor doesn't accept any new character if it has something to say */ while (fore200e_monitor_getc(fore200e) >= 0); fore200e_monitor_putc(fore200e, *str++); } while (fore200e_monitor_getc(fore200e) >= 0); } #ifdef __LITTLE_ENDIAN #define FW_EXT ".bin" #else #define FW_EXT "_ecd.bin2" #endif static int __devinit fore200e_load_and_start_fw(struct fore200e* fore200e) { const struct firmware *firmware; struct device *device; struct fw_header *fw_header; const __le32 *fw_data; u32 fw_size; u32 __iomem *load_addr; char buf[48]; int err = -ENODEV; if (strcmp(fore200e->bus->model_name, "PCA-200E") == 0) device = &((struct pci_dev *) fore200e->bus_dev)->dev; #ifdef CONFIG_SBUS else if (strcmp(fore200e->bus->model_name, "SBA-200E") == 0) device = &((struct platform_device *) fore200e->bus_dev)->dev; #endif else return err; sprintf(buf, "%s%s", fore200e->bus->proc_name, FW_EXT); if ((err = request_firmware(&firmware, buf, device)) < 0) { printk(FORE200E "problem loading firmware image %s\n", fore200e->bus->model_name); return err; } fw_data = (__le32 *) firmware->data; fw_size = firmware->size / sizeof(u32); fw_header = (struct fw_header *) firmware->data; load_addr = fore200e->virt_base + le32_to_cpu(fw_header->load_offset); DPRINTK(2, "device %s firmware being loaded at 0x%p (%d words)\n", fore200e->name, load_addr, fw_size); if (le32_to_cpu(fw_header->magic) != FW_HEADER_MAGIC) { printk(FORE200E "corrupted %s firmware image\n", fore200e->bus->model_name); goto release; } for (; fw_size--; fw_data++, load_addr++) fore200e->bus->write(le32_to_cpu(*fw_data), load_addr); DPRINTK(2, "device %s firmware being started\n", fore200e->name); #if defined(__sparc_v9__) /* reported to be required by SBA cards on some sparc64 hosts */ fore200e_spin(100); #endif sprintf(buf, "\rgo %x\r", le32_to_cpu(fw_header->start_offset)); fore200e_monitor_puts(fore200e, buf); if (fore200e_io_poll(fore200e, &fore200e->cp_monitor->bstat, BSTAT_CP_RUNNING, 1000) == 0) { printk(FORE200E "device %s firmware didn't start\n", fore200e->name); goto release; } printk(FORE200E "device %s firmware started\n", fore200e->name); fore200e->state = FORE200E_STATE_START_FW; err = 0; release: release_firmware(firmware); return err; } static int __devinit fore200e_register(struct fore200e* fore200e, struct device *parent) { struct atm_dev* atm_dev; DPRINTK(2, "device %s being registered\n", fore200e->name); atm_dev = atm_dev_register(fore200e->bus->proc_name, parent, &fore200e_ops, -1, NULL); if (atm_dev == NULL) { printk(FORE200E "unable to register device %s\n", fore200e->name); return -ENODEV; } atm_dev->dev_data = fore200e; fore200e->atm_dev = atm_dev; atm_dev->ci_range.vpi_bits = FORE200E_VPI_BITS; atm_dev->ci_range.vci_bits = FORE200E_VCI_BITS; fore200e->available_cell_rate = ATM_OC3_PCR; fore200e->state = FORE200E_STATE_REGISTER; return 0; } static int __devinit fore200e_init(struct fore200e* fore200e, struct device *parent) { if (fore200e_register(fore200e, parent) < 0) return -ENODEV; if (fore200e->bus->configure(fore200e) < 0) return -ENODEV; if (fore200e->bus->map(fore200e) < 0) return -ENODEV; if (fore200e_reset(fore200e, 1) < 0) return -ENODEV; if (fore200e_load_and_start_fw(fore200e) < 0) return -ENODEV; if (fore200e_initialize(fore200e) < 0) return -ENODEV; if (fore200e_init_cmd_queue(fore200e) < 0) return -ENOMEM; if (fore200e_init_tx_queue(fore200e) < 0) return -ENOMEM; if (fore200e_init_rx_queue(fore200e) < 0) return -ENOMEM; if (fore200e_init_bs_queue(fore200e) < 0) return -ENOMEM; if (fore200e_alloc_rx_buf(fore200e) < 0) return -ENOMEM; if (fore200e_get_esi(fore200e) < 0) return -EIO; if (fore200e_irq_request(fore200e) < 0) return -EBUSY; fore200e_supply(fore200e); /* all done, board initialization is now complete */ fore200e->state = FORE200E_STATE_COMPLETE; return 0; } #ifdef CONFIG_SBUS static const struct of_device_id fore200e_sba_match[]; static int __devinit fore200e_sba_probe(struct platform_device *op) { const struct of_device_id *match; const struct fore200e_bus *bus; struct fore200e *fore200e; static int index = 0; int err; match = of_match_device(fore200e_sba_match, &op->dev); if (!match) return -EINVAL; bus = match->data; fore200e = kzalloc(sizeof(struct fore200e), GFP_KERNEL); if (!fore200e) return -ENOMEM; fore200e->bus = bus; fore200e->bus_dev = op; fore200e->irq = op->archdata.irqs[0]; fore200e->phys_base = op->resource[0].start; sprintf(fore200e->name, "%s-%d", bus->model_name, index); err = fore200e_init(fore200e, &op->dev); if (err < 0) { fore200e_shutdown(fore200e); kfree(fore200e); return err; } index++; dev_set_drvdata(&op->dev, fore200e); return 0; } static int __devexit fore200e_sba_remove(struct platform_device *op) { struct fore200e *fore200e = dev_get_drvdata(&op->dev); fore200e_shutdown(fore200e); kfree(fore200e); return 0; } static const struct of_device_id fore200e_sba_match[] = { { .name = SBA200E_PROM_NAME, .data = (void *) &fore200e_bus[1], }, {}, }; MODULE_DEVICE_TABLE(of, fore200e_sba_match); static struct platform_driver fore200e_sba_driver = { .driver = { .name = "fore_200e", .owner = THIS_MODULE, .of_match_table = fore200e_sba_match, }, .probe = fore200e_sba_probe, .remove = __devexit_p(fore200e_sba_remove), }; #endif #ifdef CONFIG_PCI static int __devinit fore200e_pca_detect(struct pci_dev *pci_dev, const struct pci_device_id *pci_ent) { const struct fore200e_bus* bus = (struct fore200e_bus*) pci_ent->driver_data; struct fore200e* fore200e; int err = 0; static int index = 0; if (pci_enable_device(pci_dev)) { err = -EINVAL; goto out; } fore200e = kzalloc(sizeof(struct fore200e), GFP_KERNEL); if (fore200e == NULL) { err = -ENOMEM; goto out_disable; } fore200e->bus = bus; fore200e->bus_dev = pci_dev; fore200e->irq = pci_dev->irq; fore200e->phys_base = pci_resource_start(pci_dev, 0); sprintf(fore200e->name, "%s-%d", bus->model_name, index - 1); pci_set_master(pci_dev); printk(FORE200E "device %s found at 0x%lx, IRQ %s\n", fore200e->bus->model_name, fore200e->phys_base, fore200e_irq_itoa(fore200e->irq)); sprintf(fore200e->name, "%s-%d", bus->model_name, index); err = fore200e_init(fore200e, &pci_dev->dev); if (err < 0) { fore200e_shutdown(fore200e); goto out_free; } ++index; pci_set_drvdata(pci_dev, fore200e); out: return err; out_free: kfree(fore200e); out_disable: pci_disable_device(pci_dev); goto out; } static void __devexit fore200e_pca_remove_one(struct pci_dev *pci_dev) { struct fore200e *fore200e; fore200e = pci_get_drvdata(pci_dev); fore200e_shutdown(fore200e); kfree(fore200e); pci_disable_device(pci_dev); } static struct pci_device_id fore200e_pca_tbl[] = { { PCI_VENDOR_ID_FORE, PCI_DEVICE_ID_FORE_PCA200E, PCI_ANY_ID, PCI_ANY_ID, 0, 0, (unsigned long) &fore200e_bus[0] }, { 0, } }; MODULE_DEVICE_TABLE(pci, fore200e_pca_tbl); static struct pci_driver fore200e_pca_driver = { .name = "fore_200e", .probe = fore200e_pca_detect, .remove = __devexit_p(fore200e_pca_remove_one), .id_table = fore200e_pca_tbl, }; #endif static int __init fore200e_module_init(void) { int err; printk(FORE200E "FORE Systems 200E-series ATM driver - version " FORE200E_VERSION "\n"); #ifdef CONFIG_SBUS err = platform_driver_register(&fore200e_sba_driver); if (err) return err; #endif #ifdef CONFIG_PCI err = pci_register_driver(&fore200e_pca_driver); #endif #ifdef CONFIG_SBUS if (err) platform_driver_unregister(&fore200e_sba_driver); #endif return err; } static void __exit fore200e_module_cleanup(void) { #ifdef CONFIG_PCI pci_unregister_driver(&fore200e_pca_driver); #endif #ifdef CONFIG_SBUS platform_driver_unregister(&fore200e_sba_driver); #endif } static int fore200e_proc_read(struct atm_dev *dev, loff_t* pos, char* page) { struct fore200e* fore200e = FORE200E_DEV(dev); struct fore200e_vcc* fore200e_vcc; struct atm_vcc* vcc; int i, len, left = *pos; unsigned long flags; if (!left--) { if (fore200e_getstats(fore200e) < 0) return -EIO; len = sprintf(page,"\n" " device:\n" " internal name:\t\t%s\n", fore200e->name); /* print bus-specific information */ if (fore200e->bus->proc_read) len += fore200e->bus->proc_read(fore200e, page + len); len += sprintf(page + len, " interrupt line:\t\t%s\n" " physical base address:\t0x%p\n" " virtual base address:\t0x%p\n" " factory address (ESI):\t%pM\n" " board serial number:\t\t%d\n\n", fore200e_irq_itoa(fore200e->irq), (void*)fore200e->phys_base, fore200e->virt_base, fore200e->esi, fore200e->esi[4] * 256 + fore200e->esi[5]); return len; } if (!left--) return sprintf(page, " free small bufs, scheme 1:\t%d\n" " free large bufs, scheme 1:\t%d\n" " free small bufs, scheme 2:\t%d\n" " free large bufs, scheme 2:\t%d\n", fore200e->host_bsq[ BUFFER_SCHEME_ONE ][ BUFFER_MAGN_SMALL ].freebuf_count, fore200e->host_bsq[ BUFFER_SCHEME_ONE ][ BUFFER_MAGN_LARGE ].freebuf_count, fore200e->host_bsq[ BUFFER_SCHEME_TWO ][ BUFFER_MAGN_SMALL ].freebuf_count, fore200e->host_bsq[ BUFFER_SCHEME_TWO ][ BUFFER_MAGN_LARGE ].freebuf_count); if (!left--) { u32 hb = fore200e->bus->read(&fore200e->cp_queues->heartbeat); len = sprintf(page,"\n\n" " cell processor:\n" " heartbeat state:\t\t"); if (hb >> 16 != 0xDEAD) len += sprintf(page + len, "0x%08x\n", hb); else len += sprintf(page + len, "*** FATAL ERROR %04x ***\n", hb & 0xFFFF); return len; } if (!left--) { static const char* media_name[] = { "unshielded twisted pair", "multimode optical fiber ST", "multimode optical fiber SC", "single-mode optical fiber ST", "single-mode optical fiber SC", "unknown" }; static const char* oc3_mode[] = { "normal operation", "diagnostic loopback", "line loopback", "unknown" }; u32 fw_release = fore200e->bus->read(&fore200e->cp_queues->fw_release); u32 mon960_release = fore200e->bus->read(&fore200e->cp_queues->mon960_release); u32 oc3_revision = fore200e->bus->read(&fore200e->cp_queues->oc3_revision); u32 media_index = FORE200E_MEDIA_INDEX(fore200e->bus->read(&fore200e->cp_queues->media_type)); u32 oc3_index; if (media_index > 4) media_index = 5; switch (fore200e->loop_mode) { case ATM_LM_NONE: oc3_index = 0; break; case ATM_LM_LOC_PHY: oc3_index = 1; break; case ATM_LM_RMT_PHY: oc3_index = 2; break; default: oc3_index = 3; } return sprintf(page, " firmware release:\t\t%d.%d.%d\n" " monitor release:\t\t%d.%d\n" " media type:\t\t\t%s\n" " OC-3 revision:\t\t0x%x\n" " OC-3 mode:\t\t\t%s", fw_release >> 16, fw_release << 16 >> 24, fw_release << 24 >> 24, mon960_release >> 16, mon960_release << 16 >> 16, media_name[ media_index ], oc3_revision, oc3_mode[ oc3_index ]); } if (!left--) { struct cp_monitor __iomem * cp_monitor = fore200e->cp_monitor; return sprintf(page, "\n\n" " monitor:\n" " version number:\t\t%d\n" " boot status word:\t\t0x%08x\n", fore200e->bus->read(&cp_monitor->mon_version), fore200e->bus->read(&cp_monitor->bstat)); } if (!left--) return sprintf(page, "\n" " device statistics:\n" " 4b5b:\n" " crc_header_errors:\t\t%10u\n" " framing_errors:\t\t%10u\n", be32_to_cpu(fore200e->stats->phy.crc_header_errors), be32_to_cpu(fore200e->stats->phy.framing_errors)); if (!left--) return sprintf(page, "\n" " OC-3:\n" " section_bip8_errors:\t%10u\n" " path_bip8_errors:\t\t%10u\n" " line_bip24_errors:\t\t%10u\n" " line_febe_errors:\t\t%10u\n" " path_febe_errors:\t\t%10u\n" " corr_hcs_errors:\t\t%10u\n" " ucorr_hcs_errors:\t\t%10u\n", be32_to_cpu(fore200e->stats->oc3.section_bip8_errors), be32_to_cpu(fore200e->stats->oc3.path_bip8_errors), be32_to_cpu(fore200e->stats->oc3.line_bip24_errors), be32_to_cpu(fore200e->stats->oc3.line_febe_errors), be32_to_cpu(fore200e->stats->oc3.path_febe_errors), be32_to_cpu(fore200e->stats->oc3.corr_hcs_errors), be32_to_cpu(fore200e->stats->oc3.ucorr_hcs_errors)); if (!left--) return sprintf(page,"\n" " ATM:\t\t\t\t cells\n" " TX:\t\t\t%10u\n" " RX:\t\t\t%10u\n" " vpi out of range:\t\t%10u\n" " vpi no conn:\t\t%10u\n" " vci out of range:\t\t%10u\n" " vci no conn:\t\t%10u\n", be32_to_cpu(fore200e->stats->atm.cells_transmitted), be32_to_cpu(fore200e->stats->atm.cells_received), be32_to_cpu(fore200e->stats->atm.vpi_bad_range), be32_to_cpu(fore200e->stats->atm.vpi_no_conn), be32_to_cpu(fore200e->stats->atm.vci_bad_range), be32_to_cpu(fore200e->stats->atm.vci_no_conn)); if (!left--) return sprintf(page,"\n" " AAL0:\t\t\t cells\n" " TX:\t\t\t%10u\n" " RX:\t\t\t%10u\n" " dropped:\t\t\t%10u\n", be32_to_cpu(fore200e->stats->aal0.cells_transmitted), be32_to_cpu(fore200e->stats->aal0.cells_received), be32_to_cpu(fore200e->stats->aal0.cells_dropped)); if (!left--) return sprintf(page,"\n" " AAL3/4:\n" " SAR sublayer:\t\t cells\n" " TX:\t\t\t%10u\n" " RX:\t\t\t%10u\n" " dropped:\t\t\t%10u\n" " CRC errors:\t\t%10u\n" " protocol errors:\t\t%10u\n\n" " CS sublayer:\t\t PDUs\n" " TX:\t\t\t%10u\n" " RX:\t\t\t%10u\n" " dropped:\t\t\t%10u\n" " protocol errors:\t\t%10u\n", be32_to_cpu(fore200e->stats->aal34.cells_transmitted), be32_to_cpu(fore200e->stats->aal34.cells_received), be32_to_cpu(fore200e->stats->aal34.cells_dropped), be32_to_cpu(fore200e->stats->aal34.cells_crc_errors), be32_to_cpu(fore200e->stats->aal34.cells_protocol_errors), be32_to_cpu(fore200e->stats->aal34.cspdus_transmitted), be32_to_cpu(fore200e->stats->aal34.cspdus_received), be32_to_cpu(fore200e->stats->aal34.cspdus_dropped), be32_to_cpu(fore200e->stats->aal34.cspdus_protocol_errors)); if (!left--) return sprintf(page,"\n" " AAL5:\n" " SAR sublayer:\t\t cells\n" " TX:\t\t\t%10u\n" " RX:\t\t\t%10u\n" " dropped:\t\t\t%10u\n" " congestions:\t\t%10u\n\n" " CS sublayer:\t\t PDUs\n" " TX:\t\t\t%10u\n" " RX:\t\t\t%10u\n" " dropped:\t\t\t%10u\n" " CRC errors:\t\t%10u\n" " protocol errors:\t\t%10u\n", be32_to_cpu(fore200e->stats->aal5.cells_transmitted), be32_to_cpu(fore200e->stats->aal5.cells_received), be32_to_cpu(fore200e->stats->aal5.cells_dropped), be32_to_cpu(fore200e->stats->aal5.congestion_experienced), be32_to_cpu(fore200e->stats->aal5.cspdus_transmitted), be32_to_cpu(fore200e->stats->aal5.cspdus_received), be32_to_cpu(fore200e->stats->aal5.cspdus_dropped), be32_to_cpu(fore200e->stats->aal5.cspdus_crc_errors), be32_to_cpu(fore200e->stats->aal5.cspdus_protocol_errors)); if (!left--) return sprintf(page,"\n" " AUX:\t\t allocation failures\n" " small b1:\t\t\t%10u\n" " large b1:\t\t\t%10u\n" " small b2:\t\t\t%10u\n" " large b2:\t\t\t%10u\n" " RX PDUs:\t\t\t%10u\n" " TX PDUs:\t\t\t%10lu\n", be32_to_cpu(fore200e->stats->aux.small_b1_failed), be32_to_cpu(fore200e->stats->aux.large_b1_failed), be32_to_cpu(fore200e->stats->aux.small_b2_failed), be32_to_cpu(fore200e->stats->aux.large_b2_failed), be32_to_cpu(fore200e->stats->aux.rpd_alloc_failed), fore200e->tx_sat); if (!left--) return sprintf(page,"\n" " receive carrier:\t\t\t%s\n", fore200e->stats->aux.receive_carrier ? "ON" : "OFF!"); if (!left--) { return sprintf(page,"\n" " VCCs:\n address VPI VCI AAL " "TX PDUs TX min/max size RX PDUs RX min/max size\n"); } for (i = 0; i < NBR_CONNECT; i++) { vcc = fore200e->vc_map[i].vcc; if (vcc == NULL) continue; spin_lock_irqsave(&fore200e->q_lock, flags); if (vcc && test_bit(ATM_VF_READY, &vcc->flags) && !left--) { fore200e_vcc = FORE200E_VCC(vcc); ASSERT(fore200e_vcc); len = sprintf(page, " %08x %03d %05d %1d %09lu %05d/%05d %09lu %05d/%05d\n", (u32)(unsigned long)vcc, vcc->vpi, vcc->vci, fore200e_atm2fore_aal(vcc->qos.aal), fore200e_vcc->tx_pdu, fore200e_vcc->tx_min_pdu > 0xFFFF ? 0 : fore200e_vcc->tx_min_pdu, fore200e_vcc->tx_max_pdu, fore200e_vcc->rx_pdu, fore200e_vcc->rx_min_pdu > 0xFFFF ? 0 : fore200e_vcc->rx_min_pdu, fore200e_vcc->rx_max_pdu); spin_unlock_irqrestore(&fore200e->q_lock, flags); return len; } spin_unlock_irqrestore(&fore200e->q_lock, flags); } return 0; } module_init(fore200e_module_init); module_exit(fore200e_module_cleanup); static const struct atmdev_ops fore200e_ops = { .open = fore200e_open, .close = fore200e_close, .ioctl = fore200e_ioctl, .getsockopt = fore200e_getsockopt, .setsockopt = fore200e_setsockopt, .send = fore200e_send, .change_qos = fore200e_change_qos, .proc_read = fore200e_proc_read, .owner = THIS_MODULE }; static const struct fore200e_bus fore200e_bus[] = { #ifdef CONFIG_PCI { "PCA-200E", "pca200e", 32, 4, 32, fore200e_pca_read, fore200e_pca_write, fore200e_pca_dma_map, fore200e_pca_dma_unmap, fore200e_pca_dma_sync_for_cpu, fore200e_pca_dma_sync_for_device, fore200e_pca_dma_chunk_alloc, fore200e_pca_dma_chunk_free, fore200e_pca_configure, fore200e_pca_map, fore200e_pca_reset, fore200e_pca_prom_read, fore200e_pca_unmap, NULL, fore200e_pca_irq_check, fore200e_pca_irq_ack, fore200e_pca_proc_read, }, #endif #ifdef CONFIG_SBUS { "SBA-200E", "sba200e", 32, 64, 32, fore200e_sba_read, fore200e_sba_write, fore200e_sba_dma_map, fore200e_sba_dma_unmap, fore200e_sba_dma_sync_for_cpu, fore200e_sba_dma_sync_for_device, fore200e_sba_dma_chunk_alloc, fore200e_sba_dma_chunk_free, fore200e_sba_configure, fore200e_sba_map, fore200e_sba_reset, fore200e_sba_prom_read, fore200e_sba_unmap, fore200e_sba_irq_enable, fore200e_sba_irq_check, fore200e_sba_irq_ack, fore200e_sba_proc_read, }, #endif {} }; MODULE_LICENSE("GPL"); #ifdef CONFIG_PCI #ifdef __LITTLE_ENDIAN__ MODULE_FIRMWARE("pca200e.bin"); #else MODULE_FIRMWARE("pca200e_ecd.bin2"); #endif #endif /* CONFIG_PCI */ #ifdef CONFIG_SBUS MODULE_FIRMWARE("sba200e_ecd.bin2"); #endif
gpl-2.0
nk111/htc-kernel-msm7x30
drivers/net/tulip/timer.c
2766
5007
/* drivers/net/tulip/timer.c Copyright 2000,2001 The Linux Kernel Team Written/copyright 1994-2001 by Donald Becker. This software may be used and distributed according to the terms of the GNU General Public License, incorporated herein by reference. Please refer to Documentation/DocBook/tulip-user.{pdf,ps,html} for more information on this driver. Please submit bugs to http://bugzilla.kernel.org/ . */ #include "tulip.h" void tulip_media_task(struct work_struct *work) { struct tulip_private *tp = container_of(work, struct tulip_private, media_work); struct net_device *dev = tp->dev; void __iomem *ioaddr = tp->base_addr; u32 csr12 = ioread32(ioaddr + CSR12); int next_tick = 2*HZ; unsigned long flags; if (tulip_debug > 2) { netdev_dbg(dev, "Media selection tick, %s, status %08x mode %08x SIA %08x %08x %08x %08x\n", medianame[dev->if_port], ioread32(ioaddr + CSR5), ioread32(ioaddr + CSR6), csr12, ioread32(ioaddr + CSR13), ioread32(ioaddr + CSR14), ioread32(ioaddr + CSR15)); } switch (tp->chip_id) { case DC21140: case DC21142: case MX98713: case COMPEX9881: case DM910X: default: { struct medialeaf *mleaf; unsigned char *p; if (tp->mtable == NULL) { /* No EEPROM info, use generic code. */ /* Not much that can be done. Assume this a generic MII or SYM transceiver. */ next_tick = 60*HZ; if (tulip_debug > 2) netdev_dbg(dev, "network media monitor CSR6 %08x CSR12 0x%02x\n", ioread32(ioaddr + CSR6), csr12 & 0xff); break; } mleaf = &tp->mtable->mleaf[tp->cur_index]; p = mleaf->leafdata; switch (mleaf->type) { case 0: case 4: { /* Type 0 serial or 4 SYM transceiver. Check the link beat bit. */ int offset = mleaf->type == 4 ? 5 : 2; s8 bitnum = p[offset]; if (p[offset+1] & 0x80) { if (tulip_debug > 1) netdev_dbg(dev, "Transceiver monitor tick CSR12=%#02x, no media sense\n", csr12); if (mleaf->type == 4) { if (mleaf->media == 3 && (csr12 & 0x02)) goto select_next_media; } break; } if (tulip_debug > 2) netdev_dbg(dev, "Transceiver monitor tick: CSR12=%#02x bit %d is %d, expecting %d\n", csr12, (bitnum >> 1) & 7, (csr12 & (1 << ((bitnum >> 1) & 7))) != 0, (bitnum >= 0)); /* Check that the specified bit has the proper value. */ if ((bitnum < 0) != ((csr12 & (1 << ((bitnum >> 1) & 7))) != 0)) { if (tulip_debug > 2) netdev_dbg(dev, "Link beat detected for %s\n", medianame[mleaf->media & MEDIA_MASK]); if ((p[2] & 0x61) == 0x01) /* Bogus Znyx board. */ goto actually_mii; netif_carrier_on(dev); break; } netif_carrier_off(dev); if (tp->medialock) break; select_next_media: if (--tp->cur_index < 0) { /* We start again, but should instead look for default. */ tp->cur_index = tp->mtable->leafcount - 1; } dev->if_port = tp->mtable->mleaf[tp->cur_index].media; if (tulip_media_cap[dev->if_port] & MediaIsFD) goto select_next_media; /* Skip FD entries. */ if (tulip_debug > 1) netdev_dbg(dev, "No link beat on media %s, trying transceiver type %s\n", medianame[mleaf->media & MEDIA_MASK], medianame[tp->mtable->mleaf[tp->cur_index].media]); tulip_select_media(dev, 0); /* Restart the transmit process. */ tulip_restart_rxtx(tp); next_tick = (24*HZ)/10; break; } case 1: case 3: /* 21140, 21142 MII */ actually_mii: if (tulip_check_duplex(dev) < 0) { netif_carrier_off(dev); next_tick = 3*HZ; } else { netif_carrier_on(dev); next_tick = 60*HZ; } break; case 2: /* 21142 serial block has no link beat. */ default: break; } } break; } spin_lock_irqsave(&tp->lock, flags); if (tp->timeout_recovery) { tulip_tx_timeout_complete(tp, ioaddr); tp->timeout_recovery = 0; } spin_unlock_irqrestore(&tp->lock, flags); /* mod_timer synchronizes us with potential add_timer calls * from interrupts. */ mod_timer(&tp->timer, RUN_AT(next_tick)); } void mxic_timer(unsigned long data) { struct net_device *dev = (struct net_device *)data; struct tulip_private *tp = netdev_priv(dev); void __iomem *ioaddr = tp->base_addr; int next_tick = 60*HZ; if (tulip_debug > 3) { dev_info(&dev->dev, "MXIC negotiation status %08x\n", ioread32(ioaddr + CSR12)); } if (next_tick) { mod_timer(&tp->timer, RUN_AT(next_tick)); } } void comet_timer(unsigned long data) { struct net_device *dev = (struct net_device *)data; struct tulip_private *tp = netdev_priv(dev); int next_tick = 60*HZ; if (tulip_debug > 1) netdev_dbg(dev, "Comet link status %04x partner capability %04x\n", tulip_mdio_read(dev, tp->phys[0], 1), tulip_mdio_read(dev, tp->phys[0], 5)); /* mod_timer synchronizes us with potential add_timer calls * from interrupts. */ if (tulip_check_duplex(dev) < 0) { netif_carrier_off(dev); } else { netif_carrier_on(dev); } mod_timer(&tp->timer, RUN_AT(next_tick)); }
gpl-2.0
syhost/android_kernel_pantech_adr910l
fs/ceph/addr.c
2766
32316
#include <linux/ceph/ceph_debug.h> #include <linux/backing-dev.h> #include <linux/fs.h> #include <linux/mm.h> #include <linux/pagemap.h> #include <linux/writeback.h> /* generic_writepages */ #include <linux/slab.h> #include <linux/pagevec.h> #include <linux/task_io_accounting_ops.h> #include "super.h" #include "mds_client.h" #include <linux/ceph/osd_client.h> /* * Ceph address space ops. * * There are a few funny things going on here. * * The page->private field is used to reference a struct * ceph_snap_context for _every_ dirty page. This indicates which * snapshot the page was logically dirtied in, and thus which snap * context needs to be associated with the osd write during writeback. * * Similarly, struct ceph_inode_info maintains a set of counters to * count dirty pages on the inode. In the absence of snapshots, * i_wrbuffer_ref == i_wrbuffer_ref_head == the dirty page count. * * When a snapshot is taken (that is, when the client receives * notification that a snapshot was taken), each inode with caps and * with dirty pages (dirty pages implies there is a cap) gets a new * ceph_cap_snap in the i_cap_snaps list (which is sorted in ascending * order, new snaps go to the tail). The i_wrbuffer_ref_head count is * moved to capsnap->dirty. (Unless a sync write is currently in * progress. In that case, the capsnap is said to be "pending", new * writes cannot start, and the capsnap isn't "finalized" until the * write completes (or fails) and a final size/mtime for the inode for * that snap can be settled upon.) i_wrbuffer_ref_head is reset to 0. * * On writeback, we must submit writes to the osd IN SNAP ORDER. So, * we look for the first capsnap in i_cap_snaps and write out pages in * that snap context _only_. Then we move on to the next capsnap, * eventually reaching the "live" or "head" context (i.e., pages that * are not yet snapped) and are writing the most recently dirtied * pages. * * Invalidate and so forth must take care to ensure the dirty page * accounting is preserved. */ #define CONGESTION_ON_THRESH(congestion_kb) (congestion_kb >> (PAGE_SHIFT-10)) #define CONGESTION_OFF_THRESH(congestion_kb) \ (CONGESTION_ON_THRESH(congestion_kb) - \ (CONGESTION_ON_THRESH(congestion_kb) >> 2)) /* * Dirty a page. Optimistically adjust accounting, on the assumption * that we won't race with invalidate. If we do, readjust. */ static int ceph_set_page_dirty(struct page *page) { struct address_space *mapping = page->mapping; struct inode *inode; struct ceph_inode_info *ci; int undo = 0; struct ceph_snap_context *snapc; if (unlikely(!mapping)) return !TestSetPageDirty(page); if (TestSetPageDirty(page)) { dout("%p set_page_dirty %p idx %lu -- already dirty\n", mapping->host, page, page->index); return 0; } inode = mapping->host; ci = ceph_inode(inode); /* * Note that we're grabbing a snapc ref here without holding * any locks! */ snapc = ceph_get_snap_context(ci->i_snap_realm->cached_context); /* dirty the head */ spin_lock(&inode->i_lock); if (ci->i_head_snapc == NULL) ci->i_head_snapc = ceph_get_snap_context(snapc); ++ci->i_wrbuffer_ref_head; if (ci->i_wrbuffer_ref == 0) ihold(inode); ++ci->i_wrbuffer_ref; dout("%p set_page_dirty %p idx %lu head %d/%d -> %d/%d " "snapc %p seq %lld (%d snaps)\n", mapping->host, page, page->index, ci->i_wrbuffer_ref-1, ci->i_wrbuffer_ref_head-1, ci->i_wrbuffer_ref, ci->i_wrbuffer_ref_head, snapc, snapc->seq, snapc->num_snaps); spin_unlock(&inode->i_lock); /* now adjust page */ spin_lock_irq(&mapping->tree_lock); if (page->mapping) { /* Race with truncate? */ WARN_ON_ONCE(!PageUptodate(page)); account_page_dirtied(page, page->mapping); radix_tree_tag_set(&mapping->page_tree, page_index(page), PAGECACHE_TAG_DIRTY); /* * Reference snap context in page->private. Also set * PagePrivate so that we get invalidatepage callback. */ page->private = (unsigned long)snapc; SetPagePrivate(page); } else { dout("ANON set_page_dirty %p (raced truncate?)\n", page); undo = 1; } spin_unlock_irq(&mapping->tree_lock); if (undo) /* whoops, we failed to dirty the page */ ceph_put_wrbuffer_cap_refs(ci, 1, snapc); __mark_inode_dirty(mapping->host, I_DIRTY_PAGES); BUG_ON(!PageDirty(page)); return 1; } /* * If we are truncating the full page (i.e. offset == 0), adjust the * dirty page counters appropriately. Only called if there is private * data on the page. */ static void ceph_invalidatepage(struct page *page, unsigned long offset) { struct inode *inode; struct ceph_inode_info *ci; struct ceph_snap_context *snapc = (void *)page->private; BUG_ON(!PageLocked(page)); BUG_ON(!page->private); BUG_ON(!PagePrivate(page)); BUG_ON(!page->mapping); inode = page->mapping->host; /* * We can get non-dirty pages here due to races between * set_page_dirty and truncate_complete_page; just spit out a * warning, in case we end up with accounting problems later. */ if (!PageDirty(page)) pr_err("%p invalidatepage %p page not dirty\n", inode, page); if (offset == 0) ClearPageChecked(page); ci = ceph_inode(inode); if (offset == 0) { dout("%p invalidatepage %p idx %lu full dirty page %lu\n", inode, page, page->index, offset); ceph_put_wrbuffer_cap_refs(ci, 1, snapc); ceph_put_snap_context(snapc); page->private = 0; ClearPagePrivate(page); } else { dout("%p invalidatepage %p idx %lu partial dirty page\n", inode, page, page->index); } } /* just a sanity check */ static int ceph_releasepage(struct page *page, gfp_t g) { struct inode *inode = page->mapping ? page->mapping->host : NULL; dout("%p releasepage %p idx %lu\n", inode, page, page->index); WARN_ON(PageDirty(page)); WARN_ON(page->private); WARN_ON(PagePrivate(page)); return 0; } /* * read a single page, without unlocking it. */ static int readpage_nounlock(struct file *filp, struct page *page) { struct inode *inode = filp->f_dentry->d_inode; struct ceph_inode_info *ci = ceph_inode(inode); struct ceph_osd_client *osdc = &ceph_inode_to_client(inode)->client->osdc; int err = 0; u64 len = PAGE_CACHE_SIZE; dout("readpage inode %p file %p page %p index %lu\n", inode, filp, page, page->index); err = ceph_osdc_readpages(osdc, ceph_vino(inode), &ci->i_layout, page->index << PAGE_CACHE_SHIFT, &len, ci->i_truncate_seq, ci->i_truncate_size, &page, 1, 0); if (err == -ENOENT) err = 0; if (err < 0) { SetPageError(page); goto out; } else if (err < PAGE_CACHE_SIZE) { /* zero fill remainder of page */ zero_user_segment(page, err, PAGE_CACHE_SIZE); } SetPageUptodate(page); out: return err < 0 ? err : 0; } static int ceph_readpage(struct file *filp, struct page *page) { int r = readpage_nounlock(filp, page); unlock_page(page); return r; } /* * Build a vector of contiguous pages from the provided page list. */ static struct page **page_vector_from_list(struct list_head *page_list, unsigned *nr_pages) { struct page **pages; struct page *page; int next_index, contig_pages = 0; /* build page vector */ pages = kmalloc(sizeof(*pages) * *nr_pages, GFP_NOFS); if (!pages) return ERR_PTR(-ENOMEM); BUG_ON(list_empty(page_list)); next_index = list_entry(page_list->prev, struct page, lru)->index; list_for_each_entry_reverse(page, page_list, lru) { if (page->index == next_index) { dout("readpages page %d %p\n", contig_pages, page); pages[contig_pages] = page; contig_pages++; next_index++; } else { break; } } *nr_pages = contig_pages; return pages; } /* * Read multiple pages. Leave pages we don't read + unlock in page_list; * the caller (VM) cleans them up. */ static int ceph_readpages(struct file *file, struct address_space *mapping, struct list_head *page_list, unsigned nr_pages) { struct inode *inode = file->f_dentry->d_inode; struct ceph_inode_info *ci = ceph_inode(inode); struct ceph_osd_client *osdc = &ceph_inode_to_client(inode)->client->osdc; int rc = 0; struct page **pages; loff_t offset; u64 len; dout("readpages %p file %p nr_pages %d\n", inode, file, nr_pages); pages = page_vector_from_list(page_list, &nr_pages); if (IS_ERR(pages)) return PTR_ERR(pages); /* guess read extent */ offset = pages[0]->index << PAGE_CACHE_SHIFT; len = nr_pages << PAGE_CACHE_SHIFT; rc = ceph_osdc_readpages(osdc, ceph_vino(inode), &ci->i_layout, offset, &len, ci->i_truncate_seq, ci->i_truncate_size, pages, nr_pages, 0); if (rc == -ENOENT) rc = 0; if (rc < 0) goto out; for (; !list_empty(page_list) && len > 0; rc -= PAGE_CACHE_SIZE, len -= PAGE_CACHE_SIZE) { struct page *page = list_entry(page_list->prev, struct page, lru); list_del(&page->lru); if (rc < (int)PAGE_CACHE_SIZE) { /* zero (remainder of) page */ int s = rc < 0 ? 0 : rc; zero_user_segment(page, s, PAGE_CACHE_SIZE); } if (add_to_page_cache_lru(page, mapping, page->index, GFP_NOFS)) { page_cache_release(page); dout("readpages %p add_to_page_cache failed %p\n", inode, page); continue; } dout("readpages %p adding %p idx %lu\n", inode, page, page->index); flush_dcache_page(page); SetPageUptodate(page); unlock_page(page); page_cache_release(page); } rc = 0; out: kfree(pages); return rc; } /* * Get ref for the oldest snapc for an inode with dirty data... that is, the * only snap context we are allowed to write back. */ static struct ceph_snap_context *get_oldest_context(struct inode *inode, u64 *snap_size) { struct ceph_inode_info *ci = ceph_inode(inode); struct ceph_snap_context *snapc = NULL; struct ceph_cap_snap *capsnap = NULL; spin_lock(&inode->i_lock); list_for_each_entry(capsnap, &ci->i_cap_snaps, ci_item) { dout(" cap_snap %p snapc %p has %d dirty pages\n", capsnap, capsnap->context, capsnap->dirty_pages); if (capsnap->dirty_pages) { snapc = ceph_get_snap_context(capsnap->context); if (snap_size) *snap_size = capsnap->size; break; } } if (!snapc && ci->i_wrbuffer_ref_head) { snapc = ceph_get_snap_context(ci->i_head_snapc); dout(" head snapc %p has %d dirty pages\n", snapc, ci->i_wrbuffer_ref_head); } spin_unlock(&inode->i_lock); return snapc; } /* * Write a single page, but leave the page locked. * * If we get a write error, set the page error bit, but still adjust the * dirty page accounting (i.e., page is no longer dirty). */ static int writepage_nounlock(struct page *page, struct writeback_control *wbc) { struct inode *inode; struct ceph_inode_info *ci; struct ceph_fs_client *fsc; struct ceph_osd_client *osdc; loff_t page_off = page->index << PAGE_CACHE_SHIFT; int len = PAGE_CACHE_SIZE; loff_t i_size; int err = 0; struct ceph_snap_context *snapc, *oldest; u64 snap_size = 0; long writeback_stat; dout("writepage %p idx %lu\n", page, page->index); if (!page->mapping || !page->mapping->host) { dout("writepage %p - no mapping\n", page); return -EFAULT; } inode = page->mapping->host; ci = ceph_inode(inode); fsc = ceph_inode_to_client(inode); osdc = &fsc->client->osdc; /* verify this is a writeable snap context */ snapc = (void *)page->private; if (snapc == NULL) { dout("writepage %p page %p not dirty?\n", inode, page); goto out; } oldest = get_oldest_context(inode, &snap_size); if (snapc->seq > oldest->seq) { dout("writepage %p page %p snapc %p not writeable - noop\n", inode, page, (void *)page->private); /* we should only noop if called by kswapd */ WARN_ON((current->flags & PF_MEMALLOC) == 0); ceph_put_snap_context(oldest); goto out; } ceph_put_snap_context(oldest); /* is this a partial page at end of file? */ if (snap_size) i_size = snap_size; else i_size = i_size_read(inode); if (i_size < page_off + len) len = i_size - page_off; dout("writepage %p page %p index %lu on %llu~%u snapc %p\n", inode, page, page->index, page_off, len, snapc); writeback_stat = atomic_long_inc_return(&fsc->writeback_count); if (writeback_stat > CONGESTION_ON_THRESH(fsc->mount_options->congestion_kb)) set_bdi_congested(&fsc->backing_dev_info, BLK_RW_ASYNC); set_page_writeback(page); err = ceph_osdc_writepages(osdc, ceph_vino(inode), &ci->i_layout, snapc, page_off, len, ci->i_truncate_seq, ci->i_truncate_size, &inode->i_mtime, &page, 1, 0, 0, true); if (err < 0) { dout("writepage setting page/mapping error %d %p\n", err, page); SetPageError(page); mapping_set_error(&inode->i_data, err); if (wbc) wbc->pages_skipped++; } else { dout("writepage cleaned page %p\n", page); err = 0; /* vfs expects us to return 0 */ } page->private = 0; ClearPagePrivate(page); end_page_writeback(page); ceph_put_wrbuffer_cap_refs(ci, 1, snapc); ceph_put_snap_context(snapc); /* page's reference */ out: return err; } static int ceph_writepage(struct page *page, struct writeback_control *wbc) { int err; struct inode *inode = page->mapping->host; BUG_ON(!inode); ihold(inode); err = writepage_nounlock(page, wbc); unlock_page(page); iput(inode); return err; } /* * lame release_pages helper. release_pages() isn't exported to * modules. */ static void ceph_release_pages(struct page **pages, int num) { struct pagevec pvec; int i; pagevec_init(&pvec, 0); for (i = 0; i < num; i++) { if (pagevec_add(&pvec, pages[i]) == 0) pagevec_release(&pvec); } pagevec_release(&pvec); } /* * async writeback completion handler. * * If we get an error, set the mapping error bit, but not the individual * page error bits. */ static void writepages_finish(struct ceph_osd_request *req, struct ceph_msg *msg) { struct inode *inode = req->r_inode; struct ceph_osd_reply_head *replyhead; struct ceph_osd_op *op; struct ceph_inode_info *ci = ceph_inode(inode); unsigned wrote; struct page *page; int i; struct ceph_snap_context *snapc = req->r_snapc; struct address_space *mapping = inode->i_mapping; __s32 rc = -EIO; u64 bytes = 0; struct ceph_fs_client *fsc = ceph_inode_to_client(inode); long writeback_stat; unsigned issued = ceph_caps_issued(ci); /* parse reply */ replyhead = msg->front.iov_base; WARN_ON(le32_to_cpu(replyhead->num_ops) == 0); op = (void *)(replyhead + 1); rc = le32_to_cpu(replyhead->result); bytes = le64_to_cpu(op->extent.length); if (rc >= 0) { /* * Assume we wrote the pages we originally sent. The * osd might reply with fewer pages if our writeback * raced with a truncation and was adjusted at the osd, * so don't believe the reply. */ wrote = req->r_num_pages; } else { wrote = 0; mapping_set_error(mapping, rc); } dout("writepages_finish %p rc %d bytes %llu wrote %d (pages)\n", inode, rc, bytes, wrote); /* clean all pages */ for (i = 0; i < req->r_num_pages; i++) { page = req->r_pages[i]; BUG_ON(!page); WARN_ON(!PageUptodate(page)); writeback_stat = atomic_long_dec_return(&fsc->writeback_count); if (writeback_stat < CONGESTION_OFF_THRESH(fsc->mount_options->congestion_kb)) clear_bdi_congested(&fsc->backing_dev_info, BLK_RW_ASYNC); ceph_put_snap_context((void *)page->private); page->private = 0; ClearPagePrivate(page); dout("unlocking %d %p\n", i, page); end_page_writeback(page); /* * We lost the cache cap, need to truncate the page before * it is unlocked, otherwise we'd truncate it later in the * page truncation thread, possibly losing some data that * raced its way in */ if ((issued & (CEPH_CAP_FILE_CACHE|CEPH_CAP_FILE_LAZYIO)) == 0) generic_error_remove_page(inode->i_mapping, page); unlock_page(page); } dout("%p wrote+cleaned %d pages\n", inode, wrote); ceph_put_wrbuffer_cap_refs(ci, req->r_num_pages, snapc); ceph_release_pages(req->r_pages, req->r_num_pages); if (req->r_pages_from_pool) mempool_free(req->r_pages, ceph_sb_to_client(inode->i_sb)->wb_pagevec_pool); else kfree(req->r_pages); ceph_osdc_put_request(req); } /* * allocate a page vec, either directly, or if necessary, via a the * mempool. we avoid the mempool if we can because req->r_num_pages * may be less than the maximum write size. */ static void alloc_page_vec(struct ceph_fs_client *fsc, struct ceph_osd_request *req) { req->r_pages = kmalloc(sizeof(struct page *) * req->r_num_pages, GFP_NOFS); if (!req->r_pages) { req->r_pages = mempool_alloc(fsc->wb_pagevec_pool, GFP_NOFS); req->r_pages_from_pool = 1; WARN_ON(!req->r_pages); } } /* * initiate async writeback */ static int ceph_writepages_start(struct address_space *mapping, struct writeback_control *wbc) { struct inode *inode = mapping->host; struct ceph_inode_info *ci = ceph_inode(inode); struct ceph_fs_client *fsc; pgoff_t index, start, end; int range_whole = 0; int should_loop = 1; pgoff_t max_pages = 0, max_pages_ever = 0; struct ceph_snap_context *snapc = NULL, *last_snapc = NULL, *pgsnapc; struct pagevec pvec; int done = 0; int rc = 0; unsigned wsize = 1 << inode->i_blkbits; struct ceph_osd_request *req = NULL; int do_sync; u64 snap_size = 0; /* * Include a 'sync' in the OSD request if this is a data * integrity write (e.g., O_SYNC write or fsync()), or if our * cap is being revoked. */ do_sync = wbc->sync_mode == WB_SYNC_ALL; if (ceph_caps_revoking(ci, CEPH_CAP_FILE_BUFFER)) do_sync = 1; dout("writepages_start %p dosync=%d (mode=%s)\n", inode, do_sync, wbc->sync_mode == WB_SYNC_NONE ? "NONE" : (wbc->sync_mode == WB_SYNC_ALL ? "ALL" : "HOLD")); fsc = ceph_inode_to_client(inode); if (fsc->mount_state == CEPH_MOUNT_SHUTDOWN) { pr_warning("writepage_start %p on forced umount\n", inode); return -EIO; /* we're in a forced umount, don't write! */ } if (fsc->mount_options->wsize && fsc->mount_options->wsize < wsize) wsize = fsc->mount_options->wsize; if (wsize < PAGE_CACHE_SIZE) wsize = PAGE_CACHE_SIZE; max_pages_ever = wsize >> PAGE_CACHE_SHIFT; pagevec_init(&pvec, 0); /* where to start/end? */ if (wbc->range_cyclic) { start = mapping->writeback_index; /* Start from prev offset */ end = -1; dout(" cyclic, start at %lu\n", start); } else { start = wbc->range_start >> PAGE_CACHE_SHIFT; end = wbc->range_end >> PAGE_CACHE_SHIFT; if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX) range_whole = 1; should_loop = 0; dout(" not cyclic, %lu to %lu\n", start, end); } index = start; retry: /* find oldest snap context with dirty data */ ceph_put_snap_context(snapc); snapc = get_oldest_context(inode, &snap_size); if (!snapc) { /* hmm, why does writepages get called when there is no dirty data? */ dout(" no snap context with dirty data?\n"); goto out; } dout(" oldest snapc is %p seq %lld (%d snaps)\n", snapc, snapc->seq, snapc->num_snaps); if (last_snapc && snapc != last_snapc) { /* if we switched to a newer snapc, restart our scan at the * start of the original file range. */ dout(" snapc differs from last pass, restarting at %lu\n", index); index = start; } last_snapc = snapc; while (!done && index <= end) { unsigned i; int first; pgoff_t next; int pvec_pages, locked_pages; struct page *page; int want; u64 offset, len; struct ceph_osd_request_head *reqhead; struct ceph_osd_op *op; long writeback_stat; next = 0; locked_pages = 0; max_pages = max_pages_ever; get_more_pages: first = -1; want = min(end - index, min((pgoff_t)PAGEVEC_SIZE, max_pages - (pgoff_t)locked_pages) - 1) + 1; pvec_pages = pagevec_lookup_tag(&pvec, mapping, &index, PAGECACHE_TAG_DIRTY, want); dout("pagevec_lookup_tag got %d\n", pvec_pages); if (!pvec_pages && !locked_pages) break; for (i = 0; i < pvec_pages && locked_pages < max_pages; i++) { page = pvec.pages[i]; dout("? %p idx %lu\n", page, page->index); if (locked_pages == 0) lock_page(page); /* first page */ else if (!trylock_page(page)) break; /* only dirty pages, or our accounting breaks */ if (unlikely(!PageDirty(page)) || unlikely(page->mapping != mapping)) { dout("!dirty or !mapping %p\n", page); unlock_page(page); break; } if (!wbc->range_cyclic && page->index > end) { dout("end of range %p\n", page); done = 1; unlock_page(page); break; } if (next && (page->index != next)) { dout("not consecutive %p\n", page); unlock_page(page); break; } if (wbc->sync_mode != WB_SYNC_NONE) { dout("waiting on writeback %p\n", page); wait_on_page_writeback(page); } if ((snap_size && page_offset(page) > snap_size) || (!snap_size && page_offset(page) > i_size_read(inode))) { dout("%p page eof %llu\n", page, snap_size ? snap_size : i_size_read(inode)); done = 1; unlock_page(page); break; } if (PageWriteback(page)) { dout("%p under writeback\n", page); unlock_page(page); break; } /* only if matching snap context */ pgsnapc = (void *)page->private; if (pgsnapc->seq > snapc->seq) { dout("page snapc %p %lld > oldest %p %lld\n", pgsnapc, pgsnapc->seq, snapc, snapc->seq); unlock_page(page); if (!locked_pages) continue; /* keep looking for snap */ break; } if (!clear_page_dirty_for_io(page)) { dout("%p !clear_page_dirty_for_io\n", page); unlock_page(page); break; } /* ok */ if (locked_pages == 0) { /* prepare async write request */ offset = (unsigned long long)page->index << PAGE_CACHE_SHIFT; len = wsize; req = ceph_osdc_new_request(&fsc->client->osdc, &ci->i_layout, ceph_vino(inode), offset, &len, CEPH_OSD_OP_WRITE, CEPH_OSD_FLAG_WRITE | CEPH_OSD_FLAG_ONDISK, snapc, do_sync, ci->i_truncate_seq, ci->i_truncate_size, &inode->i_mtime, true, 1, 0); if (!req) { rc = -ENOMEM; unlock_page(page); break; } max_pages = req->r_num_pages; alloc_page_vec(fsc, req); req->r_callback = writepages_finish; req->r_inode = inode; } /* note position of first page in pvec */ if (first < 0) first = i; dout("%p will write page %p idx %lu\n", inode, page, page->index); writeback_stat = atomic_long_inc_return(&fsc->writeback_count); if (writeback_stat > CONGESTION_ON_THRESH( fsc->mount_options->congestion_kb)) { set_bdi_congested(&fsc->backing_dev_info, BLK_RW_ASYNC); } set_page_writeback(page); req->r_pages[locked_pages] = page; locked_pages++; next = page->index + 1; } /* did we get anything? */ if (!locked_pages) goto release_pvec_pages; if (i) { int j; BUG_ON(!locked_pages || first < 0); if (pvec_pages && i == pvec_pages && locked_pages < max_pages) { dout("reached end pvec, trying for more\n"); pagevec_reinit(&pvec); goto get_more_pages; } /* shift unused pages over in the pvec... we * will need to release them below. */ for (j = i; j < pvec_pages; j++) { dout(" pvec leftover page %p\n", pvec.pages[j]); pvec.pages[j-i+first] = pvec.pages[j]; } pvec.nr -= i-first; } /* submit the write */ offset = req->r_pages[0]->index << PAGE_CACHE_SHIFT; len = min((snap_size ? snap_size : i_size_read(inode)) - offset, (u64)locked_pages << PAGE_CACHE_SHIFT); dout("writepages got %d pages at %llu~%llu\n", locked_pages, offset, len); /* revise final length, page count */ req->r_num_pages = locked_pages; reqhead = req->r_request->front.iov_base; op = (void *)(reqhead + 1); op->extent.length = cpu_to_le64(len); op->payload_len = cpu_to_le32(len); req->r_request->hdr.data_len = cpu_to_le32(len); rc = ceph_osdc_start_request(&fsc->client->osdc, req, true); BUG_ON(rc); req = NULL; /* continue? */ index = next; wbc->nr_to_write -= locked_pages; if (wbc->nr_to_write <= 0) done = 1; release_pvec_pages: dout("pagevec_release on %d pages (%p)\n", (int)pvec.nr, pvec.nr ? pvec.pages[0] : NULL); pagevec_release(&pvec); if (locked_pages && !done) goto retry; } if (should_loop && !done) { /* more to do; loop back to beginning of file */ dout("writepages looping back to beginning of file\n"); should_loop = 0; index = 0; goto retry; } if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0)) mapping->writeback_index = index; out: if (req) ceph_osdc_put_request(req); ceph_put_snap_context(snapc); dout("writepages done, rc = %d\n", rc); return rc; } /* * See if a given @snapc is either writeable, or already written. */ static int context_is_writeable_or_written(struct inode *inode, struct ceph_snap_context *snapc) { struct ceph_snap_context *oldest = get_oldest_context(inode, NULL); int ret = !oldest || snapc->seq <= oldest->seq; ceph_put_snap_context(oldest); return ret; } /* * We are only allowed to write into/dirty the page if the page is * clean, or already dirty within the same snap context. * * called with page locked. * return success with page locked, * or any failure (incl -EAGAIN) with page unlocked. */ static int ceph_update_writeable_page(struct file *file, loff_t pos, unsigned len, struct page *page) { struct inode *inode = file->f_dentry->d_inode; struct ceph_inode_info *ci = ceph_inode(inode); struct ceph_mds_client *mdsc = ceph_inode_to_client(inode)->mdsc; loff_t page_off = pos & PAGE_CACHE_MASK; int pos_in_page = pos & ~PAGE_CACHE_MASK; int end_in_page = pos_in_page + len; loff_t i_size; int r; struct ceph_snap_context *snapc, *oldest; retry_locked: /* writepages currently holds page lock, but if we change that later, */ wait_on_page_writeback(page); /* check snap context */ BUG_ON(!ci->i_snap_realm); down_read(&mdsc->snap_rwsem); BUG_ON(!ci->i_snap_realm->cached_context); snapc = (void *)page->private; if (snapc && snapc != ci->i_head_snapc) { /* * this page is already dirty in another (older) snap * context! is it writeable now? */ oldest = get_oldest_context(inode, NULL); up_read(&mdsc->snap_rwsem); if (snapc->seq > oldest->seq) { ceph_put_snap_context(oldest); dout(" page %p snapc %p not current or oldest\n", page, snapc); /* * queue for writeback, and wait for snapc to * be writeable or written */ snapc = ceph_get_snap_context(snapc); unlock_page(page); ceph_queue_writeback(inode); r = wait_event_interruptible(ci->i_cap_wq, context_is_writeable_or_written(inode, snapc)); ceph_put_snap_context(snapc); if (r == -ERESTARTSYS) return r; return -EAGAIN; } ceph_put_snap_context(oldest); /* yay, writeable, do it now (without dropping page lock) */ dout(" page %p snapc %p not current, but oldest\n", page, snapc); if (!clear_page_dirty_for_io(page)) goto retry_locked; r = writepage_nounlock(page, NULL); if (r < 0) goto fail_nosnap; goto retry_locked; } if (PageUptodate(page)) { dout(" page %p already uptodate\n", page); return 0; } /* full page? */ if (pos_in_page == 0 && len == PAGE_CACHE_SIZE) return 0; /* past end of file? */ i_size = inode->i_size; /* caller holds i_mutex */ if (i_size + len > inode->i_sb->s_maxbytes) { /* file is too big */ r = -EINVAL; goto fail; } if (page_off >= i_size || (pos_in_page == 0 && (pos+len) >= i_size && end_in_page - pos_in_page != PAGE_CACHE_SIZE)) { dout(" zeroing %p 0 - %d and %d - %d\n", page, pos_in_page, end_in_page, (int)PAGE_CACHE_SIZE); zero_user_segments(page, 0, pos_in_page, end_in_page, PAGE_CACHE_SIZE); return 0; } /* we need to read it. */ up_read(&mdsc->snap_rwsem); r = readpage_nounlock(file, page); if (r < 0) goto fail_nosnap; goto retry_locked; fail: up_read(&mdsc->snap_rwsem); fail_nosnap: unlock_page(page); return r; } /* * We are only allowed to write into/dirty the page if the page is * clean, or already dirty within the same snap context. */ static int ceph_write_begin(struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned flags, struct page **pagep, void **fsdata) { struct inode *inode = file->f_dentry->d_inode; struct page *page; pgoff_t index = pos >> PAGE_CACHE_SHIFT; int r; do { /* get a page */ page = grab_cache_page_write_begin(mapping, index, 0); if (!page) return -ENOMEM; *pagep = page; dout("write_begin file %p inode %p page %p %d~%d\n", file, inode, page, (int)pos, (int)len); r = ceph_update_writeable_page(file, pos, len, page); } while (r == -EAGAIN); return r; } /* * we don't do anything in here that simple_write_end doesn't do * except adjust dirty page accounting and drop read lock on * mdsc->snap_rwsem. */ static int ceph_write_end(struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned copied, struct page *page, void *fsdata) { struct inode *inode = file->f_dentry->d_inode; struct ceph_fs_client *fsc = ceph_inode_to_client(inode); struct ceph_mds_client *mdsc = fsc->mdsc; unsigned from = pos & (PAGE_CACHE_SIZE - 1); int check_cap = 0; dout("write_end file %p inode %p page %p %d~%d (%d)\n", file, inode, page, (int)pos, (int)copied, (int)len); /* zero the stale part of the page if we did a short copy */ if (copied < len) zero_user_segment(page, from+copied, len); /* did file size increase? */ /* (no need for i_size_read(); we caller holds i_mutex */ if (pos+copied > inode->i_size) check_cap = ceph_inode_set_size(inode, pos+copied); if (!PageUptodate(page)) SetPageUptodate(page); set_page_dirty(page); unlock_page(page); up_read(&mdsc->snap_rwsem); page_cache_release(page); if (check_cap) ceph_check_caps(ceph_inode(inode), CHECK_CAPS_AUTHONLY, NULL); return copied; } /* * we set .direct_IO to indicate direct io is supported, but since we * intercept O_DIRECT reads and writes early, this function should * never get called. */ static ssize_t ceph_direct_io(int rw, struct kiocb *iocb, const struct iovec *iov, loff_t pos, unsigned long nr_segs) { WARN_ON(1); return -EINVAL; } const struct address_space_operations ceph_aops = { .readpage = ceph_readpage, .readpages = ceph_readpages, .writepage = ceph_writepage, .writepages = ceph_writepages_start, .write_begin = ceph_write_begin, .write_end = ceph_write_end, .set_page_dirty = ceph_set_page_dirty, .invalidatepage = ceph_invalidatepage, .releasepage = ceph_releasepage, .direct_IO = ceph_direct_io, }; /* * vm ops */ /* * Reuse write_begin here for simplicity. */ static int ceph_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf) { struct inode *inode = vma->vm_file->f_dentry->d_inode; struct page *page = vmf->page; struct ceph_mds_client *mdsc = ceph_inode_to_client(inode)->mdsc; loff_t off = page->index << PAGE_CACHE_SHIFT; loff_t size, len; int ret; size = i_size_read(inode); if (off + PAGE_CACHE_SIZE <= size) len = PAGE_CACHE_SIZE; else len = size & ~PAGE_CACHE_MASK; dout("page_mkwrite %p %llu~%llu page %p idx %lu\n", inode, off, len, page, page->index); lock_page(page); ret = VM_FAULT_NOPAGE; if ((off > size) || (page->mapping != inode->i_mapping)) goto out; ret = ceph_update_writeable_page(vma->vm_file, off, len, page); if (ret == 0) { /* success. we'll keep the page locked. */ set_page_dirty(page); up_read(&mdsc->snap_rwsem); ret = VM_FAULT_LOCKED; } else { if (ret == -ENOMEM) ret = VM_FAULT_OOM; else ret = VM_FAULT_SIGBUS; } out: dout("page_mkwrite %p %llu~%llu = %d\n", inode, off, len, ret); if (ret != VM_FAULT_LOCKED) unlock_page(page); return ret; } static struct vm_operations_struct ceph_vmops = { .fault = filemap_fault, .page_mkwrite = ceph_page_mkwrite, }; int ceph_mmap(struct file *file, struct vm_area_struct *vma) { struct address_space *mapping = file->f_mapping; if (!mapping->a_ops->readpage) return -ENOEXEC; file_accessed(file); vma->vm_ops = &ceph_vmops; vma->vm_flags |= VM_CAN_NONLINEAR; return 0; }
gpl-2.0
Quallenauge/kernel-archosg9
drivers/net/tulip/timer.c
2766
5007
/* drivers/net/tulip/timer.c Copyright 2000,2001 The Linux Kernel Team Written/copyright 1994-2001 by Donald Becker. This software may be used and distributed according to the terms of the GNU General Public License, incorporated herein by reference. Please refer to Documentation/DocBook/tulip-user.{pdf,ps,html} for more information on this driver. Please submit bugs to http://bugzilla.kernel.org/ . */ #include "tulip.h" void tulip_media_task(struct work_struct *work) { struct tulip_private *tp = container_of(work, struct tulip_private, media_work); struct net_device *dev = tp->dev; void __iomem *ioaddr = tp->base_addr; u32 csr12 = ioread32(ioaddr + CSR12); int next_tick = 2*HZ; unsigned long flags; if (tulip_debug > 2) { netdev_dbg(dev, "Media selection tick, %s, status %08x mode %08x SIA %08x %08x %08x %08x\n", medianame[dev->if_port], ioread32(ioaddr + CSR5), ioread32(ioaddr + CSR6), csr12, ioread32(ioaddr + CSR13), ioread32(ioaddr + CSR14), ioread32(ioaddr + CSR15)); } switch (tp->chip_id) { case DC21140: case DC21142: case MX98713: case COMPEX9881: case DM910X: default: { struct medialeaf *mleaf; unsigned char *p; if (tp->mtable == NULL) { /* No EEPROM info, use generic code. */ /* Not much that can be done. Assume this a generic MII or SYM transceiver. */ next_tick = 60*HZ; if (tulip_debug > 2) netdev_dbg(dev, "network media monitor CSR6 %08x CSR12 0x%02x\n", ioread32(ioaddr + CSR6), csr12 & 0xff); break; } mleaf = &tp->mtable->mleaf[tp->cur_index]; p = mleaf->leafdata; switch (mleaf->type) { case 0: case 4: { /* Type 0 serial or 4 SYM transceiver. Check the link beat bit. */ int offset = mleaf->type == 4 ? 5 : 2; s8 bitnum = p[offset]; if (p[offset+1] & 0x80) { if (tulip_debug > 1) netdev_dbg(dev, "Transceiver monitor tick CSR12=%#02x, no media sense\n", csr12); if (mleaf->type == 4) { if (mleaf->media == 3 && (csr12 & 0x02)) goto select_next_media; } break; } if (tulip_debug > 2) netdev_dbg(dev, "Transceiver monitor tick: CSR12=%#02x bit %d is %d, expecting %d\n", csr12, (bitnum >> 1) & 7, (csr12 & (1 << ((bitnum >> 1) & 7))) != 0, (bitnum >= 0)); /* Check that the specified bit has the proper value. */ if ((bitnum < 0) != ((csr12 & (1 << ((bitnum >> 1) & 7))) != 0)) { if (tulip_debug > 2) netdev_dbg(dev, "Link beat detected for %s\n", medianame[mleaf->media & MEDIA_MASK]); if ((p[2] & 0x61) == 0x01) /* Bogus Znyx board. */ goto actually_mii; netif_carrier_on(dev); break; } netif_carrier_off(dev); if (tp->medialock) break; select_next_media: if (--tp->cur_index < 0) { /* We start again, but should instead look for default. */ tp->cur_index = tp->mtable->leafcount - 1; } dev->if_port = tp->mtable->mleaf[tp->cur_index].media; if (tulip_media_cap[dev->if_port] & MediaIsFD) goto select_next_media; /* Skip FD entries. */ if (tulip_debug > 1) netdev_dbg(dev, "No link beat on media %s, trying transceiver type %s\n", medianame[mleaf->media & MEDIA_MASK], medianame[tp->mtable->mleaf[tp->cur_index].media]); tulip_select_media(dev, 0); /* Restart the transmit process. */ tulip_restart_rxtx(tp); next_tick = (24*HZ)/10; break; } case 1: case 3: /* 21140, 21142 MII */ actually_mii: if (tulip_check_duplex(dev) < 0) { netif_carrier_off(dev); next_tick = 3*HZ; } else { netif_carrier_on(dev); next_tick = 60*HZ; } break; case 2: /* 21142 serial block has no link beat. */ default: break; } } break; } spin_lock_irqsave(&tp->lock, flags); if (tp->timeout_recovery) { tulip_tx_timeout_complete(tp, ioaddr); tp->timeout_recovery = 0; } spin_unlock_irqrestore(&tp->lock, flags); /* mod_timer synchronizes us with potential add_timer calls * from interrupts. */ mod_timer(&tp->timer, RUN_AT(next_tick)); } void mxic_timer(unsigned long data) { struct net_device *dev = (struct net_device *)data; struct tulip_private *tp = netdev_priv(dev); void __iomem *ioaddr = tp->base_addr; int next_tick = 60*HZ; if (tulip_debug > 3) { dev_info(&dev->dev, "MXIC negotiation status %08x\n", ioread32(ioaddr + CSR12)); } if (next_tick) { mod_timer(&tp->timer, RUN_AT(next_tick)); } } void comet_timer(unsigned long data) { struct net_device *dev = (struct net_device *)data; struct tulip_private *tp = netdev_priv(dev); int next_tick = 60*HZ; if (tulip_debug > 1) netdev_dbg(dev, "Comet link status %04x partner capability %04x\n", tulip_mdio_read(dev, tp->phys[0], 1), tulip_mdio_read(dev, tp->phys[0], 5)); /* mod_timer synchronizes us with potential add_timer calls * from interrupts. */ if (tulip_check_duplex(dev) < 0) { netif_carrier_off(dev); } else { netif_carrier_on(dev); } mod_timer(&tp->timer, RUN_AT(next_tick)); }
gpl-2.0
IngenicSemiconductor/KERNEL-NPM801
arch/mips/kernel/spinlock_test.c
3790
2381
#include <linux/init.h> #include <linux/kthread.h> #include <linux/hrtimer.h> #include <linux/fs.h> #include <linux/debugfs.h> #include <linux/module.h> #include <linux/spinlock.h> static int ss_get(void *data, u64 *val) { ktime_t start, finish; int loops; int cont; DEFINE_RAW_SPINLOCK(ss_spin); loops = 1000000; cont = 1; start = ktime_get(); while (cont) { raw_spin_lock(&ss_spin); loops--; if (loops == 0) cont = 0; raw_spin_unlock(&ss_spin); } finish = ktime_get(); *val = ktime_us_delta(finish, start); return 0; } DEFINE_SIMPLE_ATTRIBUTE(fops_ss, ss_get, NULL, "%llu\n"); struct spin_multi_state { raw_spinlock_t lock; atomic_t start_wait; atomic_t enter_wait; atomic_t exit_wait; int loops; }; struct spin_multi_per_thread { struct spin_multi_state *state; ktime_t start; }; static int multi_other(void *data) { int loops; int cont; struct spin_multi_per_thread *pt = data; struct spin_multi_state *s = pt->state; loops = s->loops; cont = 1; atomic_dec(&s->enter_wait); while (atomic_read(&s->enter_wait)) ; /* spin */ pt->start = ktime_get(); atomic_dec(&s->start_wait); while (atomic_read(&s->start_wait)) ; /* spin */ while (cont) { raw_spin_lock(&s->lock); loops--; if (loops == 0) cont = 0; raw_spin_unlock(&s->lock); } atomic_dec(&s->exit_wait); while (atomic_read(&s->exit_wait)) ; /* spin */ return 0; } static int multi_get(void *data, u64 *val) { ktime_t finish; struct spin_multi_state ms; struct spin_multi_per_thread t1, t2; ms.lock = __RAW_SPIN_LOCK_UNLOCKED("multi_get"); ms.loops = 1000000; atomic_set(&ms.start_wait, 2); atomic_set(&ms.enter_wait, 2); atomic_set(&ms.exit_wait, 2); t1.state = &ms; t2.state = &ms; kthread_run(multi_other, &t2, "multi_get"); multi_other(&t1); finish = ktime_get(); *val = ktime_us_delta(finish, t1.start); return 0; } DEFINE_SIMPLE_ATTRIBUTE(fops_multi, multi_get, NULL, "%llu\n"); extern struct dentry *mips_debugfs_dir; static int __init spinlock_test(void) { struct dentry *d; if (!mips_debugfs_dir) return -ENODEV; d = debugfs_create_file("spin_single", S_IRUGO, mips_debugfs_dir, NULL, &fops_ss); if (!d) return -ENOMEM; d = debugfs_create_file("spin_multi", S_IRUGO, mips_debugfs_dir, NULL, &fops_multi); if (!d) return -ENOMEM; return 0; } device_initcall(spinlock_test);
gpl-2.0
ryukiri/DracoKernel
arch/mips/kernel/spinlock_test.c
3790
2381
#include <linux/init.h> #include <linux/kthread.h> #include <linux/hrtimer.h> #include <linux/fs.h> #include <linux/debugfs.h> #include <linux/module.h> #include <linux/spinlock.h> static int ss_get(void *data, u64 *val) { ktime_t start, finish; int loops; int cont; DEFINE_RAW_SPINLOCK(ss_spin); loops = 1000000; cont = 1; start = ktime_get(); while (cont) { raw_spin_lock(&ss_spin); loops--; if (loops == 0) cont = 0; raw_spin_unlock(&ss_spin); } finish = ktime_get(); *val = ktime_us_delta(finish, start); return 0; } DEFINE_SIMPLE_ATTRIBUTE(fops_ss, ss_get, NULL, "%llu\n"); struct spin_multi_state { raw_spinlock_t lock; atomic_t start_wait; atomic_t enter_wait; atomic_t exit_wait; int loops; }; struct spin_multi_per_thread { struct spin_multi_state *state; ktime_t start; }; static int multi_other(void *data) { int loops; int cont; struct spin_multi_per_thread *pt = data; struct spin_multi_state *s = pt->state; loops = s->loops; cont = 1; atomic_dec(&s->enter_wait); while (atomic_read(&s->enter_wait)) ; /* spin */ pt->start = ktime_get(); atomic_dec(&s->start_wait); while (atomic_read(&s->start_wait)) ; /* spin */ while (cont) { raw_spin_lock(&s->lock); loops--; if (loops == 0) cont = 0; raw_spin_unlock(&s->lock); } atomic_dec(&s->exit_wait); while (atomic_read(&s->exit_wait)) ; /* spin */ return 0; } static int multi_get(void *data, u64 *val) { ktime_t finish; struct spin_multi_state ms; struct spin_multi_per_thread t1, t2; ms.lock = __RAW_SPIN_LOCK_UNLOCKED("multi_get"); ms.loops = 1000000; atomic_set(&ms.start_wait, 2); atomic_set(&ms.enter_wait, 2); atomic_set(&ms.exit_wait, 2); t1.state = &ms; t2.state = &ms; kthread_run(multi_other, &t2, "multi_get"); multi_other(&t1); finish = ktime_get(); *val = ktime_us_delta(finish, t1.start); return 0; } DEFINE_SIMPLE_ATTRIBUTE(fops_multi, multi_get, NULL, "%llu\n"); extern struct dentry *mips_debugfs_dir; static int __init spinlock_test(void) { struct dentry *d; if (!mips_debugfs_dir) return -ENODEV; d = debugfs_create_file("spin_single", S_IRUGO, mips_debugfs_dir, NULL, &fops_ss); if (!d) return -ENOMEM; d = debugfs_create_file("spin_multi", S_IRUGO, mips_debugfs_dir, NULL, &fops_multi); if (!d) return -ENOMEM; return 0; } device_initcall(spinlock_test);
gpl-2.0
TEAM-Gummy/Gummy_kernel_grouper
arch/sh/drivers/dma/dma-pvr2.c
3790
2438
/* * arch/sh/drivers/dma/dma-pvr2.c * * NEC PowerVR 2 (Dreamcast) DMA support * * Copyright (C) 2003, 2004 Paul Mundt * * This file is subject to the terms and conditions of the GNU General Public * License. See the file "COPYING" in the main directory of this archive * for more details. */ #include <linux/init.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/interrupt.h> #include <mach/sysasic.h> #include <mach/dma.h> #include <asm/dma.h> #include <asm/io.h> static unsigned int xfer_complete; static int count; static irqreturn_t pvr2_dma_interrupt(int irq, void *dev_id) { if (get_dma_residue(PVR2_CASCADE_CHAN)) { printk(KERN_WARNING "DMA: SH DMAC did not complete transfer " "on channel %d, waiting..\n", PVR2_CASCADE_CHAN); dma_wait_for_completion(PVR2_CASCADE_CHAN); } if (count++ < 10) pr_debug("Got a pvr2 dma interrupt for channel %d\n", irq - HW_EVENT_PVR2_DMA); xfer_complete = 1; return IRQ_HANDLED; } static int pvr2_request_dma(struct dma_channel *chan) { if (__raw_readl(PVR2_DMA_MODE) != 0) return -EBUSY; __raw_writel(0, PVR2_DMA_LMMODE0); return 0; } static int pvr2_get_dma_residue(struct dma_channel *chan) { return xfer_complete == 0; } static int pvr2_xfer_dma(struct dma_channel *chan) { if (chan->sar || !chan->dar) return -EINVAL; xfer_complete = 0; __raw_writel(chan->dar, PVR2_DMA_ADDR); __raw_writel(chan->count, PVR2_DMA_COUNT); __raw_writel(chan->mode & DMA_MODE_MASK, PVR2_DMA_MODE); return 0; } static struct irqaction pvr2_dma_irq = { .name = "pvr2 DMA handler", .handler = pvr2_dma_interrupt, .flags = IRQF_DISABLED, }; static struct dma_ops pvr2_dma_ops = { .request = pvr2_request_dma, .get_residue = pvr2_get_dma_residue, .xfer = pvr2_xfer_dma, }; static struct dma_info pvr2_dma_info = { .name = "pvr2_dmac", .nr_channels = 1, .ops = &pvr2_dma_ops, .flags = DMAC_CHANNELS_TEI_CAPABLE, }; static int __init pvr2_dma_init(void) { setup_irq(HW_EVENT_PVR2_DMA, &pvr2_dma_irq); request_dma(PVR2_CASCADE_CHAN, "pvr2 cascade"); return register_dmac(&pvr2_dma_info); } static void __exit pvr2_dma_exit(void) { free_dma(PVR2_CASCADE_CHAN); free_irq(HW_EVENT_PVR2_DMA, 0); unregister_dmac(&pvr2_dma_info); } subsys_initcall(pvr2_dma_init); module_exit(pvr2_dma_exit); MODULE_AUTHOR("Paul Mundt <lethal@linux-sh.org>"); MODULE_DESCRIPTION("NEC PowerVR 2 DMA driver"); MODULE_LICENSE("GPL");
gpl-2.0
voodik/android_kernel_hardkernel_odroidxu
net/bridge/netfilter/ebtables.c
4302
63137
/* * ebtables * * Author: * Bart De Schuymer <bdschuym@pandora.be> * * ebtables.c,v 2.0, July, 2002 * * This code is stongly inspired on the iptables code which is * Copyright (C) 1999 Paul `Rusty' Russell & Michael J. Neuling * * 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/kmod.h> #include <linux/module.h> #include <linux/vmalloc.h> #include <linux/netfilter/x_tables.h> #include <linux/netfilter_bridge/ebtables.h> #include <linux/spinlock.h> #include <linux/mutex.h> #include <linux/slab.h> #include <asm/uaccess.h> #include <linux/smp.h> #include <linux/cpumask.h> #include <net/sock.h> /* needed for logical [in,out]-dev filtering */ #include "../br_private.h" #define BUGPRINT(format, args...) printk("kernel msg: ebtables bug: please "\ "report to author: "format, ## args) /* #define BUGPRINT(format, args...) */ /* * Each cpu has its own set of counters, so there is no need for write_lock in * the softirq * For reading or updating the counters, the user context needs to * get a write_lock */ /* The size of each set of counters is altered to get cache alignment */ #define SMP_ALIGN(x) (((x) + SMP_CACHE_BYTES-1) & ~(SMP_CACHE_BYTES-1)) #define COUNTER_OFFSET(n) (SMP_ALIGN(n * sizeof(struct ebt_counter))) #define COUNTER_BASE(c, n, cpu) ((struct ebt_counter *)(((char *)c) + \ COUNTER_OFFSET(n) * cpu)) static DEFINE_MUTEX(ebt_mutex); #ifdef CONFIG_COMPAT static void ebt_standard_compat_from_user(void *dst, const void *src) { int v = *(compat_int_t *)src; if (v >= 0) v += xt_compat_calc_jump(NFPROTO_BRIDGE, v); memcpy(dst, &v, sizeof(v)); } static int ebt_standard_compat_to_user(void __user *dst, const void *src) { compat_int_t cv = *(int *)src; if (cv >= 0) cv -= xt_compat_calc_jump(NFPROTO_BRIDGE, cv); return copy_to_user(dst, &cv, sizeof(cv)) ? -EFAULT : 0; } #endif static struct xt_target ebt_standard_target = { .name = "standard", .revision = 0, .family = NFPROTO_BRIDGE, .targetsize = sizeof(int), #ifdef CONFIG_COMPAT .compatsize = sizeof(compat_int_t), .compat_from_user = ebt_standard_compat_from_user, .compat_to_user = ebt_standard_compat_to_user, #endif }; static inline int ebt_do_watcher(const struct ebt_entry_watcher *w, struct sk_buff *skb, struct xt_action_param *par) { par->target = w->u.watcher; par->targinfo = w->data; w->u.watcher->target(skb, par); /* watchers don't give a verdict */ return 0; } static inline int ebt_do_match(struct ebt_entry_match *m, const struct sk_buff *skb, struct xt_action_param *par) { par->match = m->u.match; par->matchinfo = m->data; return m->u.match->match(skb, par) ? EBT_MATCH : EBT_NOMATCH; } static inline int ebt_dev_check(const char *entry, const struct net_device *device) { int i = 0; const char *devname; if (*entry == '\0') return 0; if (!device) return 1; devname = device->name; /* 1 is the wildcard token */ while (entry[i] != '\0' && entry[i] != 1 && entry[i] == devname[i]) i++; return (devname[i] != entry[i] && entry[i] != 1); } #define FWINV2(bool,invflg) ((bool) ^ !!(e->invflags & invflg)) /* process standard matches */ static inline int ebt_basic_match(const struct ebt_entry *e, const struct sk_buff *skb, const struct net_device *in, const struct net_device *out) { const struct ethhdr *h = eth_hdr(skb); const struct net_bridge_port *p; __be16 ethproto; int verdict, i; if (vlan_tx_tag_present(skb)) ethproto = htons(ETH_P_8021Q); else ethproto = h->h_proto; if (e->bitmask & EBT_802_3) { if (FWINV2(ntohs(ethproto) >= 1536, EBT_IPROTO)) return 1; } else if (!(e->bitmask & EBT_NOPROTO) && FWINV2(e->ethproto != ethproto, EBT_IPROTO)) return 1; if (FWINV2(ebt_dev_check(e->in, in), EBT_IIN)) return 1; if (FWINV2(ebt_dev_check(e->out, out), EBT_IOUT)) return 1; /* rcu_read_lock()ed by nf_hook_slow */ if (in && (p = br_port_get_rcu(in)) != NULL && FWINV2(ebt_dev_check(e->logical_in, p->br->dev), EBT_ILOGICALIN)) return 1; if (out && (p = br_port_get_rcu(out)) != NULL && FWINV2(ebt_dev_check(e->logical_out, p->br->dev), EBT_ILOGICALOUT)) return 1; if (e->bitmask & EBT_SOURCEMAC) { verdict = 0; for (i = 0; i < 6; i++) verdict |= (h->h_source[i] ^ e->sourcemac[i]) & e->sourcemsk[i]; if (FWINV2(verdict != 0, EBT_ISOURCE) ) return 1; } if (e->bitmask & EBT_DESTMAC) { verdict = 0; for (i = 0; i < 6; i++) verdict |= (h->h_dest[i] ^ e->destmac[i]) & e->destmsk[i]; if (FWINV2(verdict != 0, EBT_IDEST) ) return 1; } return 0; } static inline __pure struct ebt_entry *ebt_next_entry(const struct ebt_entry *entry) { return (void *)entry + entry->next_offset; } /* Do some firewalling */ unsigned int ebt_do_table (unsigned int hook, struct sk_buff *skb, const struct net_device *in, const struct net_device *out, struct ebt_table *table) { int i, nentries; struct ebt_entry *point; struct ebt_counter *counter_base, *cb_base; const struct ebt_entry_target *t; int verdict, sp = 0; struct ebt_chainstack *cs; struct ebt_entries *chaininfo; const char *base; const struct ebt_table_info *private; struct xt_action_param acpar; acpar.family = NFPROTO_BRIDGE; acpar.in = in; acpar.out = out; acpar.hotdrop = false; acpar.hooknum = hook; read_lock_bh(&table->lock); private = table->private; cb_base = COUNTER_BASE(private->counters, private->nentries, smp_processor_id()); if (private->chainstack) cs = private->chainstack[smp_processor_id()]; else cs = NULL; chaininfo = private->hook_entry[hook]; nentries = private->hook_entry[hook]->nentries; point = (struct ebt_entry *)(private->hook_entry[hook]->data); counter_base = cb_base + private->hook_entry[hook]->counter_offset; /* base for chain jumps */ base = private->entries; i = 0; while (i < nentries) { if (ebt_basic_match(point, skb, in, out)) goto letscontinue; if (EBT_MATCH_ITERATE(point, ebt_do_match, skb, &acpar) != 0) goto letscontinue; if (acpar.hotdrop) { read_unlock_bh(&table->lock); return NF_DROP; } /* increase counter */ (*(counter_base + i)).pcnt++; (*(counter_base + i)).bcnt += skb->len; /* these should only watch: not modify, nor tell us what to do with the packet */ EBT_WATCHER_ITERATE(point, ebt_do_watcher, skb, &acpar); t = (struct ebt_entry_target *) (((char *)point) + point->target_offset); /* standard target */ if (!t->u.target->target) verdict = ((struct ebt_standard_target *)t)->verdict; else { acpar.target = t->u.target; acpar.targinfo = t->data; verdict = t->u.target->target(skb, &acpar); } if (verdict == EBT_ACCEPT) { read_unlock_bh(&table->lock); return NF_ACCEPT; } if (verdict == EBT_DROP) { read_unlock_bh(&table->lock); return NF_DROP; } if (verdict == EBT_RETURN) { letsreturn: #ifdef CONFIG_NETFILTER_DEBUG if (sp == 0) { BUGPRINT("RETURN on base chain"); /* act like this is EBT_CONTINUE */ goto letscontinue; } #endif sp--; /* put all the local variables right */ i = cs[sp].n; chaininfo = cs[sp].chaininfo; nentries = chaininfo->nentries; point = cs[sp].e; counter_base = cb_base + chaininfo->counter_offset; continue; } if (verdict == EBT_CONTINUE) goto letscontinue; #ifdef CONFIG_NETFILTER_DEBUG if (verdict < 0) { BUGPRINT("bogus standard verdict\n"); read_unlock_bh(&table->lock); return NF_DROP; } #endif /* jump to a udc */ cs[sp].n = i + 1; cs[sp].chaininfo = chaininfo; cs[sp].e = ebt_next_entry(point); i = 0; chaininfo = (struct ebt_entries *) (base + verdict); #ifdef CONFIG_NETFILTER_DEBUG if (chaininfo->distinguisher) { BUGPRINT("jump to non-chain\n"); read_unlock_bh(&table->lock); return NF_DROP; } #endif nentries = chaininfo->nentries; point = (struct ebt_entry *)chaininfo->data; counter_base = cb_base + chaininfo->counter_offset; sp++; continue; letscontinue: point = ebt_next_entry(point); i++; } /* I actually like this :) */ if (chaininfo->policy == EBT_RETURN) goto letsreturn; if (chaininfo->policy == EBT_ACCEPT) { read_unlock_bh(&table->lock); return NF_ACCEPT; } read_unlock_bh(&table->lock); return NF_DROP; } /* If it succeeds, returns element and locks mutex */ static inline void * find_inlist_lock_noload(struct list_head *head, const char *name, int *error, struct mutex *mutex) { struct { struct list_head list; char name[EBT_FUNCTION_MAXNAMELEN]; } *e; *error = mutex_lock_interruptible(mutex); if (*error != 0) return NULL; list_for_each_entry(e, head, list) { if (strcmp(e->name, name) == 0) return e; } *error = -ENOENT; mutex_unlock(mutex); return NULL; } static void * find_inlist_lock(struct list_head *head, const char *name, const char *prefix, int *error, struct mutex *mutex) { return try_then_request_module( find_inlist_lock_noload(head, name, error, mutex), "%s%s", prefix, name); } static inline struct ebt_table * find_table_lock(struct net *net, const char *name, int *error, struct mutex *mutex) { return find_inlist_lock(&net->xt.tables[NFPROTO_BRIDGE], name, "ebtable_", error, mutex); } static inline int ebt_check_match(struct ebt_entry_match *m, struct xt_mtchk_param *par, unsigned int *cnt) { const struct ebt_entry *e = par->entryinfo; struct xt_match *match; size_t left = ((char *)e + e->watchers_offset) - (char *)m; int ret; if (left < sizeof(struct ebt_entry_match) || left - sizeof(struct ebt_entry_match) < m->match_size) return -EINVAL; match = xt_request_find_match(NFPROTO_BRIDGE, m->u.name, 0); if (IS_ERR(match)) return PTR_ERR(match); m->u.match = match; par->match = match; par->matchinfo = m->data; ret = xt_check_match(par, m->match_size, e->ethproto, e->invflags & EBT_IPROTO); if (ret < 0) { module_put(match->me); return ret; } (*cnt)++; return 0; } static inline int ebt_check_watcher(struct ebt_entry_watcher *w, struct xt_tgchk_param *par, unsigned int *cnt) { const struct ebt_entry *e = par->entryinfo; struct xt_target *watcher; size_t left = ((char *)e + e->target_offset) - (char *)w; int ret; if (left < sizeof(struct ebt_entry_watcher) || left - sizeof(struct ebt_entry_watcher) < w->watcher_size) return -EINVAL; watcher = xt_request_find_target(NFPROTO_BRIDGE, w->u.name, 0); if (IS_ERR(watcher)) return PTR_ERR(watcher); w->u.watcher = watcher; par->target = watcher; par->targinfo = w->data; ret = xt_check_target(par, w->watcher_size, e->ethproto, e->invflags & EBT_IPROTO); if (ret < 0) { module_put(watcher->me); return ret; } (*cnt)++; return 0; } static int ebt_verify_pointers(const struct ebt_replace *repl, struct ebt_table_info *newinfo) { unsigned int limit = repl->entries_size; unsigned int valid_hooks = repl->valid_hooks; unsigned int offset = 0; int i; for (i = 0; i < NF_BR_NUMHOOKS; i++) newinfo->hook_entry[i] = NULL; newinfo->entries_size = repl->entries_size; newinfo->nentries = repl->nentries; while (offset < limit) { size_t left = limit - offset; struct ebt_entry *e = (void *)newinfo->entries + offset; if (left < sizeof(unsigned int)) break; for (i = 0; i < NF_BR_NUMHOOKS; i++) { if ((valid_hooks & (1 << i)) == 0) continue; if ((char __user *)repl->hook_entry[i] == repl->entries + offset) break; } if (i != NF_BR_NUMHOOKS || !(e->bitmask & EBT_ENTRY_OR_ENTRIES)) { if (e->bitmask != 0) { /* we make userspace set this right, so there is no misunderstanding */ BUGPRINT("EBT_ENTRY_OR_ENTRIES shouldn't be set " "in distinguisher\n"); return -EINVAL; } if (i != NF_BR_NUMHOOKS) newinfo->hook_entry[i] = (struct ebt_entries *)e; if (left < sizeof(struct ebt_entries)) break; offset += sizeof(struct ebt_entries); } else { if (left < sizeof(struct ebt_entry)) break; if (left < e->next_offset) break; if (e->next_offset < sizeof(struct ebt_entry)) return -EINVAL; offset += e->next_offset; } } if (offset != limit) { BUGPRINT("entries_size too small\n"); return -EINVAL; } /* check if all valid hooks have a chain */ for (i = 0; i < NF_BR_NUMHOOKS; i++) { if (!newinfo->hook_entry[i] && (valid_hooks & (1 << i))) { BUGPRINT("Valid hook without chain\n"); return -EINVAL; } } return 0; } /* * this one is very careful, as it is the first function * to parse the userspace data */ static inline int ebt_check_entry_size_and_hooks(const struct ebt_entry *e, const struct ebt_table_info *newinfo, unsigned int *n, unsigned int *cnt, unsigned int *totalcnt, unsigned int *udc_cnt) { int i; for (i = 0; i < NF_BR_NUMHOOKS; i++) { if ((void *)e == (void *)newinfo->hook_entry[i]) break; } /* beginning of a new chain if i == NF_BR_NUMHOOKS it must be a user defined chain */ if (i != NF_BR_NUMHOOKS || !e->bitmask) { /* this checks if the previous chain has as many entries as it said it has */ if (*n != *cnt) { BUGPRINT("nentries does not equal the nr of entries " "in the chain\n"); return -EINVAL; } if (((struct ebt_entries *)e)->policy != EBT_DROP && ((struct ebt_entries *)e)->policy != EBT_ACCEPT) { /* only RETURN from udc */ if (i != NF_BR_NUMHOOKS || ((struct ebt_entries *)e)->policy != EBT_RETURN) { BUGPRINT("bad policy\n"); return -EINVAL; } } if (i == NF_BR_NUMHOOKS) /* it's a user defined chain */ (*udc_cnt)++; if (((struct ebt_entries *)e)->counter_offset != *totalcnt) { BUGPRINT("counter_offset != totalcnt"); return -EINVAL; } *n = ((struct ebt_entries *)e)->nentries; *cnt = 0; return 0; } /* a plain old entry, heh */ if (sizeof(struct ebt_entry) > e->watchers_offset || e->watchers_offset > e->target_offset || e->target_offset >= e->next_offset) { BUGPRINT("entry offsets not in right order\n"); return -EINVAL; } /* this is not checked anywhere else */ if (e->next_offset - e->target_offset < sizeof(struct ebt_entry_target)) { BUGPRINT("target size too small\n"); return -EINVAL; } (*cnt)++; (*totalcnt)++; return 0; } struct ebt_cl_stack { struct ebt_chainstack cs; int from; unsigned int hookmask; }; /* * we need these positions to check that the jumps to a different part of the * entries is a jump to the beginning of a new chain. */ static inline int ebt_get_udc_positions(struct ebt_entry *e, struct ebt_table_info *newinfo, unsigned int *n, struct ebt_cl_stack *udc) { int i; /* we're only interested in chain starts */ if (e->bitmask) return 0; for (i = 0; i < NF_BR_NUMHOOKS; i++) { if (newinfo->hook_entry[i] == (struct ebt_entries *)e) break; } /* only care about udc */ if (i != NF_BR_NUMHOOKS) return 0; udc[*n].cs.chaininfo = (struct ebt_entries *)e; /* these initialisations are depended on later in check_chainloops() */ udc[*n].cs.n = 0; udc[*n].hookmask = 0; (*n)++; return 0; } static inline int ebt_cleanup_match(struct ebt_entry_match *m, struct net *net, unsigned int *i) { struct xt_mtdtor_param par; if (i && (*i)-- == 0) return 1; par.net = net; par.match = m->u.match; par.matchinfo = m->data; par.family = NFPROTO_BRIDGE; if (par.match->destroy != NULL) par.match->destroy(&par); module_put(par.match->me); return 0; } static inline int ebt_cleanup_watcher(struct ebt_entry_watcher *w, struct net *net, unsigned int *i) { struct xt_tgdtor_param par; if (i && (*i)-- == 0) return 1; par.net = net; par.target = w->u.watcher; par.targinfo = w->data; par.family = NFPROTO_BRIDGE; if (par.target->destroy != NULL) par.target->destroy(&par); module_put(par.target->me); return 0; } static inline int ebt_cleanup_entry(struct ebt_entry *e, struct net *net, unsigned int *cnt) { struct xt_tgdtor_param par; struct ebt_entry_target *t; if (e->bitmask == 0) return 0; /* we're done */ if (cnt && (*cnt)-- == 0) return 1; EBT_WATCHER_ITERATE(e, ebt_cleanup_watcher, net, NULL); EBT_MATCH_ITERATE(e, ebt_cleanup_match, net, NULL); t = (struct ebt_entry_target *)(((char *)e) + e->target_offset); par.net = net; par.target = t->u.target; par.targinfo = t->data; par.family = NFPROTO_BRIDGE; if (par.target->destroy != NULL) par.target->destroy(&par); module_put(par.target->me); return 0; } static inline int ebt_check_entry(struct ebt_entry *e, struct net *net, const struct ebt_table_info *newinfo, const char *name, unsigned int *cnt, struct ebt_cl_stack *cl_s, unsigned int udc_cnt) { struct ebt_entry_target *t; struct xt_target *target; unsigned int i, j, hook = 0, hookmask = 0; size_t gap; int ret; struct xt_mtchk_param mtpar; struct xt_tgchk_param tgpar; /* don't mess with the struct ebt_entries */ if (e->bitmask == 0) return 0; if (e->bitmask & ~EBT_F_MASK) { BUGPRINT("Unknown flag for bitmask\n"); return -EINVAL; } if (e->invflags & ~EBT_INV_MASK) { BUGPRINT("Unknown flag for inv bitmask\n"); return -EINVAL; } if ( (e->bitmask & EBT_NOPROTO) && (e->bitmask & EBT_802_3) ) { BUGPRINT("NOPROTO & 802_3 not allowed\n"); return -EINVAL; } /* what hook do we belong to? */ for (i = 0; i < NF_BR_NUMHOOKS; i++) { if (!newinfo->hook_entry[i]) continue; if ((char *)newinfo->hook_entry[i] < (char *)e) hook = i; else break; } /* (1 << NF_BR_NUMHOOKS) tells the check functions the rule is on a base chain */ if (i < NF_BR_NUMHOOKS) hookmask = (1 << hook) | (1 << NF_BR_NUMHOOKS); else { for (i = 0; i < udc_cnt; i++) if ((char *)(cl_s[i].cs.chaininfo) > (char *)e) break; if (i == 0) hookmask = (1 << hook) | (1 << NF_BR_NUMHOOKS); else hookmask = cl_s[i - 1].hookmask; } i = 0; mtpar.net = tgpar.net = net; mtpar.table = tgpar.table = name; mtpar.entryinfo = tgpar.entryinfo = e; mtpar.hook_mask = tgpar.hook_mask = hookmask; mtpar.family = tgpar.family = NFPROTO_BRIDGE; ret = EBT_MATCH_ITERATE(e, ebt_check_match, &mtpar, &i); if (ret != 0) goto cleanup_matches; j = 0; ret = EBT_WATCHER_ITERATE(e, ebt_check_watcher, &tgpar, &j); if (ret != 0) goto cleanup_watchers; t = (struct ebt_entry_target *)(((char *)e) + e->target_offset); gap = e->next_offset - e->target_offset; target = xt_request_find_target(NFPROTO_BRIDGE, t->u.name, 0); if (IS_ERR(target)) { ret = PTR_ERR(target); goto cleanup_watchers; } t->u.target = target; if (t->u.target == &ebt_standard_target) { if (gap < sizeof(struct ebt_standard_target)) { BUGPRINT("Standard target size too big\n"); ret = -EFAULT; goto cleanup_watchers; } if (((struct ebt_standard_target *)t)->verdict < -NUM_STANDARD_TARGETS) { BUGPRINT("Invalid standard target\n"); ret = -EFAULT; goto cleanup_watchers; } } else if (t->target_size > gap - sizeof(struct ebt_entry_target)) { module_put(t->u.target->me); ret = -EFAULT; goto cleanup_watchers; } tgpar.target = target; tgpar.targinfo = t->data; ret = xt_check_target(&tgpar, t->target_size, e->ethproto, e->invflags & EBT_IPROTO); if (ret < 0) { module_put(target->me); goto cleanup_watchers; } (*cnt)++; return 0; cleanup_watchers: EBT_WATCHER_ITERATE(e, ebt_cleanup_watcher, net, &j); cleanup_matches: EBT_MATCH_ITERATE(e, ebt_cleanup_match, net, &i); return ret; } /* * checks for loops and sets the hook mask for udc * the hook mask for udc tells us from which base chains the udc can be * accessed. This mask is a parameter to the check() functions of the extensions */ static int check_chainloops(const struct ebt_entries *chain, struct ebt_cl_stack *cl_s, unsigned int udc_cnt, unsigned int hooknr, char *base) { int i, chain_nr = -1, pos = 0, nentries = chain->nentries, verdict; const struct ebt_entry *e = (struct ebt_entry *)chain->data; const struct ebt_entry_target *t; while (pos < nentries || chain_nr != -1) { /* end of udc, go back one 'recursion' step */ if (pos == nentries) { /* put back values of the time when this chain was called */ e = cl_s[chain_nr].cs.e; if (cl_s[chain_nr].from != -1) nentries = cl_s[cl_s[chain_nr].from].cs.chaininfo->nentries; else nentries = chain->nentries; pos = cl_s[chain_nr].cs.n; /* make sure we won't see a loop that isn't one */ cl_s[chain_nr].cs.n = 0; chain_nr = cl_s[chain_nr].from; if (pos == nentries) continue; } t = (struct ebt_entry_target *) (((char *)e) + e->target_offset); if (strcmp(t->u.name, EBT_STANDARD_TARGET)) goto letscontinue; if (e->target_offset + sizeof(struct ebt_standard_target) > e->next_offset) { BUGPRINT("Standard target size too big\n"); return -1; } verdict = ((struct ebt_standard_target *)t)->verdict; if (verdict >= 0) { /* jump to another chain */ struct ebt_entries *hlp2 = (struct ebt_entries *)(base + verdict); for (i = 0; i < udc_cnt; i++) if (hlp2 == cl_s[i].cs.chaininfo) break; /* bad destination or loop */ if (i == udc_cnt) { BUGPRINT("bad destination\n"); return -1; } if (cl_s[i].cs.n) { BUGPRINT("loop\n"); return -1; } if (cl_s[i].hookmask & (1 << hooknr)) goto letscontinue; /* this can't be 0, so the loop test is correct */ cl_s[i].cs.n = pos + 1; pos = 0; cl_s[i].cs.e = ebt_next_entry(e); e = (struct ebt_entry *)(hlp2->data); nentries = hlp2->nentries; cl_s[i].from = chain_nr; chain_nr = i; /* this udc is accessible from the base chain for hooknr */ cl_s[i].hookmask |= (1 << hooknr); continue; } letscontinue: e = ebt_next_entry(e); pos++; } return 0; } /* do the parsing of the table/chains/entries/matches/watchers/targets, heh */ static int translate_table(struct net *net, const char *name, struct ebt_table_info *newinfo) { unsigned int i, j, k, udc_cnt; int ret; struct ebt_cl_stack *cl_s = NULL; /* used in the checking for chain loops */ i = 0; while (i < NF_BR_NUMHOOKS && !newinfo->hook_entry[i]) i++; if (i == NF_BR_NUMHOOKS) { BUGPRINT("No valid hooks specified\n"); return -EINVAL; } if (newinfo->hook_entry[i] != (struct ebt_entries *)newinfo->entries) { BUGPRINT("Chains don't start at beginning\n"); return -EINVAL; } /* make sure chains are ordered after each other in same order as their corresponding hooks */ for (j = i + 1; j < NF_BR_NUMHOOKS; j++) { if (!newinfo->hook_entry[j]) continue; if (newinfo->hook_entry[j] <= newinfo->hook_entry[i]) { BUGPRINT("Hook order must be followed\n"); return -EINVAL; } i = j; } /* do some early checkings and initialize some things */ i = 0; /* holds the expected nr. of entries for the chain */ j = 0; /* holds the up to now counted entries for the chain */ k = 0; /* holds the total nr. of entries, should equal newinfo->nentries afterwards */ udc_cnt = 0; /* will hold the nr. of user defined chains (udc) */ ret = EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size, ebt_check_entry_size_and_hooks, newinfo, &i, &j, &k, &udc_cnt); if (ret != 0) return ret; if (i != j) { BUGPRINT("nentries does not equal the nr of entries in the " "(last) chain\n"); return -EINVAL; } if (k != newinfo->nentries) { BUGPRINT("Total nentries is wrong\n"); return -EINVAL; } /* get the location of the udc, put them in an array while we're at it, allocate the chainstack */ if (udc_cnt) { /* this will get free'd in do_replace()/ebt_register_table() if an error occurs */ newinfo->chainstack = vmalloc(nr_cpu_ids * sizeof(*(newinfo->chainstack))); if (!newinfo->chainstack) return -ENOMEM; for_each_possible_cpu(i) { newinfo->chainstack[i] = vmalloc(udc_cnt * sizeof(*(newinfo->chainstack[0]))); if (!newinfo->chainstack[i]) { while (i) vfree(newinfo->chainstack[--i]); vfree(newinfo->chainstack); newinfo->chainstack = NULL; return -ENOMEM; } } cl_s = vmalloc(udc_cnt * sizeof(*cl_s)); if (!cl_s) return -ENOMEM; i = 0; /* the i'th udc */ EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size, ebt_get_udc_positions, newinfo, &i, cl_s); /* sanity check */ if (i != udc_cnt) { BUGPRINT("i != udc_cnt\n"); vfree(cl_s); return -EFAULT; } } /* Check for loops */ for (i = 0; i < NF_BR_NUMHOOKS; i++) if (newinfo->hook_entry[i]) if (check_chainloops(newinfo->hook_entry[i], cl_s, udc_cnt, i, newinfo->entries)) { vfree(cl_s); return -EINVAL; } /* we now know the following (along with E=mc²): - the nr of entries in each chain is right - the size of the allocated space is right - all valid hooks have a corresponding chain - there are no loops - wrong data can still be on the level of a single entry - could be there are jumps to places that are not the beginning of a chain. This can only occur in chains that are not accessible from any base chains, so we don't care. */ /* used to know what we need to clean up if something goes wrong */ i = 0; ret = EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size, ebt_check_entry, net, newinfo, name, &i, cl_s, udc_cnt); if (ret != 0) { EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size, ebt_cleanup_entry, net, &i); } vfree(cl_s); return ret; } /* called under write_lock */ static void get_counters(const struct ebt_counter *oldcounters, struct ebt_counter *counters, unsigned int nentries) { int i, cpu; struct ebt_counter *counter_base; /* counters of cpu 0 */ memcpy(counters, oldcounters, sizeof(struct ebt_counter) * nentries); /* add other counters to those of cpu 0 */ for_each_possible_cpu(cpu) { if (cpu == 0) continue; counter_base = COUNTER_BASE(oldcounters, nentries, cpu); for (i = 0; i < nentries; i++) { counters[i].pcnt += counter_base[i].pcnt; counters[i].bcnt += counter_base[i].bcnt; } } } static int do_replace_finish(struct net *net, struct ebt_replace *repl, struct ebt_table_info *newinfo) { int ret, i; struct ebt_counter *counterstmp = NULL; /* used to be able to unlock earlier */ struct ebt_table_info *table; struct ebt_table *t; /* the user wants counters back the check on the size is done later, when we have the lock */ if (repl->num_counters) { unsigned long size = repl->num_counters * sizeof(*counterstmp); counterstmp = vmalloc(size); if (!counterstmp) return -ENOMEM; } newinfo->chainstack = NULL; ret = ebt_verify_pointers(repl, newinfo); if (ret != 0) goto free_counterstmp; ret = translate_table(net, repl->name, newinfo); if (ret != 0) goto free_counterstmp; t = find_table_lock(net, repl->name, &ret, &ebt_mutex); if (!t) { ret = -ENOENT; goto free_iterate; } /* the table doesn't like it */ if (t->check && (ret = t->check(newinfo, repl->valid_hooks))) goto free_unlock; if (repl->num_counters && repl->num_counters != t->private->nentries) { BUGPRINT("Wrong nr. of counters requested\n"); ret = -EINVAL; goto free_unlock; } /* we have the mutex lock, so no danger in reading this pointer */ table = t->private; /* make sure the table can only be rmmod'ed if it contains no rules */ if (!table->nentries && newinfo->nentries && !try_module_get(t->me)) { ret = -ENOENT; goto free_unlock; } else if (table->nentries && !newinfo->nentries) module_put(t->me); /* we need an atomic snapshot of the counters */ write_lock_bh(&t->lock); if (repl->num_counters) get_counters(t->private->counters, counterstmp, t->private->nentries); t->private = newinfo; write_unlock_bh(&t->lock); mutex_unlock(&ebt_mutex); /* so, a user can change the chains while having messed up her counter allocation. Only reason why this is done is because this way the lock is held only once, while this doesn't bring the kernel into a dangerous state. */ if (repl->num_counters && copy_to_user(repl->counters, counterstmp, repl->num_counters * sizeof(struct ebt_counter))) { ret = -EFAULT; } else ret = 0; /* decrease module count and free resources */ EBT_ENTRY_ITERATE(table->entries, table->entries_size, ebt_cleanup_entry, net, NULL); vfree(table->entries); if (table->chainstack) { for_each_possible_cpu(i) vfree(table->chainstack[i]); vfree(table->chainstack); } vfree(table); vfree(counterstmp); return ret; free_unlock: mutex_unlock(&ebt_mutex); free_iterate: EBT_ENTRY_ITERATE(newinfo->entries, newinfo->entries_size, ebt_cleanup_entry, net, NULL); free_counterstmp: vfree(counterstmp); /* can be initialized in translate_table() */ if (newinfo->chainstack) { for_each_possible_cpu(i) vfree(newinfo->chainstack[i]); vfree(newinfo->chainstack); } return ret; } /* replace the table */ static int do_replace(struct net *net, const void __user *user, unsigned int len) { int ret, countersize; struct ebt_table_info *newinfo; struct ebt_replace tmp; if (copy_from_user(&tmp, user, sizeof(tmp)) != 0) return -EFAULT; if (len != sizeof(tmp) + tmp.entries_size) { BUGPRINT("Wrong len argument\n"); return -EINVAL; } if (tmp.entries_size == 0) { BUGPRINT("Entries_size never zero\n"); return -EINVAL; } /* overflow check */ if (tmp.nentries >= ((INT_MAX - sizeof(struct ebt_table_info)) / NR_CPUS - SMP_CACHE_BYTES) / sizeof(struct ebt_counter)) return -ENOMEM; if (tmp.num_counters >= INT_MAX / sizeof(struct ebt_counter)) return -ENOMEM; tmp.name[sizeof(tmp.name) - 1] = 0; countersize = COUNTER_OFFSET(tmp.nentries) * nr_cpu_ids; newinfo = vmalloc(sizeof(*newinfo) + countersize); if (!newinfo) return -ENOMEM; if (countersize) memset(newinfo->counters, 0, countersize); newinfo->entries = vmalloc(tmp.entries_size); if (!newinfo->entries) { ret = -ENOMEM; goto free_newinfo; } if (copy_from_user( newinfo->entries, tmp.entries, tmp.entries_size) != 0) { BUGPRINT("Couldn't copy entries from userspace\n"); ret = -EFAULT; goto free_entries; } ret = do_replace_finish(net, &tmp, newinfo); if (ret == 0) return ret; free_entries: vfree(newinfo->entries); free_newinfo: vfree(newinfo); return ret; } struct ebt_table * ebt_register_table(struct net *net, const struct ebt_table *input_table) { struct ebt_table_info *newinfo; struct ebt_table *t, *table; struct ebt_replace_kernel *repl; int ret, i, countersize; void *p; if (input_table == NULL || (repl = input_table->table) == NULL || repl->entries == NULL || repl->entries_size == 0 || repl->counters != NULL || input_table->private != NULL) { BUGPRINT("Bad table data for ebt_register_table!!!\n"); return ERR_PTR(-EINVAL); } /* Don't add one table to multiple lists. */ table = kmemdup(input_table, sizeof(struct ebt_table), GFP_KERNEL); if (!table) { ret = -ENOMEM; goto out; } countersize = COUNTER_OFFSET(repl->nentries) * nr_cpu_ids; newinfo = vmalloc(sizeof(*newinfo) + countersize); ret = -ENOMEM; if (!newinfo) goto free_table; p = vmalloc(repl->entries_size); if (!p) goto free_newinfo; memcpy(p, repl->entries, repl->entries_size); newinfo->entries = p; newinfo->entries_size = repl->entries_size; newinfo->nentries = repl->nentries; if (countersize) memset(newinfo->counters, 0, countersize); /* fill in newinfo and parse the entries */ newinfo->chainstack = NULL; for (i = 0; i < NF_BR_NUMHOOKS; i++) { if ((repl->valid_hooks & (1 << i)) == 0) newinfo->hook_entry[i] = NULL; else newinfo->hook_entry[i] = p + ((char *)repl->hook_entry[i] - repl->entries); } ret = translate_table(net, repl->name, newinfo); if (ret != 0) { BUGPRINT("Translate_table failed\n"); goto free_chainstack; } if (table->check && table->check(newinfo, table->valid_hooks)) { BUGPRINT("The table doesn't like its own initial data, lol\n"); ret = -EINVAL; goto free_chainstack; } table->private = newinfo; rwlock_init(&table->lock); ret = mutex_lock_interruptible(&ebt_mutex); if (ret != 0) goto free_chainstack; list_for_each_entry(t, &net->xt.tables[NFPROTO_BRIDGE], list) { if (strcmp(t->name, table->name) == 0) { ret = -EEXIST; BUGPRINT("Table name already exists\n"); goto free_unlock; } } /* Hold a reference count if the chains aren't empty */ if (newinfo->nentries && !try_module_get(table->me)) { ret = -ENOENT; goto free_unlock; } list_add(&table->list, &net->xt.tables[NFPROTO_BRIDGE]); mutex_unlock(&ebt_mutex); return table; free_unlock: mutex_unlock(&ebt_mutex); free_chainstack: if (newinfo->chainstack) { for_each_possible_cpu(i) vfree(newinfo->chainstack[i]); vfree(newinfo->chainstack); } vfree(newinfo->entries); free_newinfo: vfree(newinfo); free_table: kfree(table); out: return ERR_PTR(ret); } void ebt_unregister_table(struct net *net, struct ebt_table *table) { int i; if (!table) { BUGPRINT("Request to unregister NULL table!!!\n"); return; } mutex_lock(&ebt_mutex); list_del(&table->list); mutex_unlock(&ebt_mutex); EBT_ENTRY_ITERATE(table->private->entries, table->private->entries_size, ebt_cleanup_entry, net, NULL); if (table->private->nentries) module_put(table->me); vfree(table->private->entries); if (table->private->chainstack) { for_each_possible_cpu(i) vfree(table->private->chainstack[i]); vfree(table->private->chainstack); } vfree(table->private); kfree(table); } /* userspace just supplied us with counters */ static int do_update_counters(struct net *net, const char *name, struct ebt_counter __user *counters, unsigned int num_counters, const void __user *user, unsigned int len) { int i, ret; struct ebt_counter *tmp; struct ebt_table *t; if (num_counters == 0) return -EINVAL; tmp = vmalloc(num_counters * sizeof(*tmp)); if (!tmp) return -ENOMEM; t = find_table_lock(net, name, &ret, &ebt_mutex); if (!t) goto free_tmp; if (num_counters != t->private->nentries) { BUGPRINT("Wrong nr of counters\n"); ret = -EINVAL; goto unlock_mutex; } if (copy_from_user(tmp, counters, num_counters * sizeof(*counters))) { ret = -EFAULT; goto unlock_mutex; } /* we want an atomic add of the counters */ write_lock_bh(&t->lock); /* we add to the counters of the first cpu */ for (i = 0; i < num_counters; i++) { t->private->counters[i].pcnt += tmp[i].pcnt; t->private->counters[i].bcnt += tmp[i].bcnt; } write_unlock_bh(&t->lock); ret = 0; unlock_mutex: mutex_unlock(&ebt_mutex); free_tmp: vfree(tmp); return ret; } static int update_counters(struct net *net, const void __user *user, unsigned int len) { struct ebt_replace hlp; if (copy_from_user(&hlp, user, sizeof(hlp))) return -EFAULT; if (len != sizeof(hlp) + hlp.num_counters * sizeof(struct ebt_counter)) return -EINVAL; return do_update_counters(net, hlp.name, hlp.counters, hlp.num_counters, user, len); } static inline int ebt_make_matchname(const struct ebt_entry_match *m, const char *base, char __user *ubase) { char __user *hlp = ubase + ((char *)m - base); char name[EBT_FUNCTION_MAXNAMELEN] = {}; /* ebtables expects 32 bytes long names but xt_match names are 29 bytes long. Copy 29 bytes and fill remaining bytes with zeroes. */ strncpy(name, m->u.match->name, sizeof(name)); if (copy_to_user(hlp, name, EBT_FUNCTION_MAXNAMELEN)) return -EFAULT; return 0; } static inline int ebt_make_watchername(const struct ebt_entry_watcher *w, const char *base, char __user *ubase) { char __user *hlp = ubase + ((char *)w - base); char name[EBT_FUNCTION_MAXNAMELEN] = {}; strncpy(name, w->u.watcher->name, sizeof(name)); if (copy_to_user(hlp , name, EBT_FUNCTION_MAXNAMELEN)) return -EFAULT; return 0; } static inline int ebt_make_names(struct ebt_entry *e, const char *base, char __user *ubase) { int ret; char __user *hlp; const struct ebt_entry_target *t; char name[EBT_FUNCTION_MAXNAMELEN] = {}; if (e->bitmask == 0) return 0; hlp = ubase + (((char *)e + e->target_offset) - base); t = (struct ebt_entry_target *)(((char *)e) + e->target_offset); ret = EBT_MATCH_ITERATE(e, ebt_make_matchname, base, ubase); if (ret != 0) return ret; ret = EBT_WATCHER_ITERATE(e, ebt_make_watchername, base, ubase); if (ret != 0) return ret; strncpy(name, t->u.target->name, sizeof(name)); if (copy_to_user(hlp, name, EBT_FUNCTION_MAXNAMELEN)) return -EFAULT; return 0; } static int copy_counters_to_user(struct ebt_table *t, const struct ebt_counter *oldcounters, void __user *user, unsigned int num_counters, unsigned int nentries) { struct ebt_counter *counterstmp; int ret = 0; /* userspace might not need the counters */ if (num_counters == 0) return 0; if (num_counters != nentries) { BUGPRINT("Num_counters wrong\n"); return -EINVAL; } counterstmp = vmalloc(nentries * sizeof(*counterstmp)); if (!counterstmp) return -ENOMEM; write_lock_bh(&t->lock); get_counters(oldcounters, counterstmp, nentries); write_unlock_bh(&t->lock); if (copy_to_user(user, counterstmp, nentries * sizeof(struct ebt_counter))) ret = -EFAULT; vfree(counterstmp); return ret; } /* called with ebt_mutex locked */ static int copy_everything_to_user(struct ebt_table *t, void __user *user, const int *len, int cmd) { struct ebt_replace tmp; const struct ebt_counter *oldcounters; unsigned int entries_size, nentries; int ret; char *entries; if (cmd == EBT_SO_GET_ENTRIES) { entries_size = t->private->entries_size; nentries = t->private->nentries; entries = t->private->entries; oldcounters = t->private->counters; } else { entries_size = t->table->entries_size; nentries = t->table->nentries; entries = t->table->entries; oldcounters = t->table->counters; } if (copy_from_user(&tmp, user, sizeof(tmp))) return -EFAULT; if (*len != sizeof(struct ebt_replace) + entries_size + (tmp.num_counters? nentries * sizeof(struct ebt_counter): 0)) return -EINVAL; if (tmp.nentries != nentries) { BUGPRINT("Nentries wrong\n"); return -EINVAL; } if (tmp.entries_size != entries_size) { BUGPRINT("Wrong size\n"); return -EINVAL; } ret = copy_counters_to_user(t, oldcounters, tmp.counters, tmp.num_counters, nentries); if (ret) return ret; if (copy_to_user(tmp.entries, entries, entries_size)) { BUGPRINT("Couldn't copy entries to userspace\n"); return -EFAULT; } /* set the match/watcher/target names right */ return EBT_ENTRY_ITERATE(entries, entries_size, ebt_make_names, entries, tmp.entries); } static int do_ebt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; if (!capable(CAP_NET_ADMIN)) return -EPERM; switch(cmd) { case EBT_SO_SET_ENTRIES: ret = do_replace(sock_net(sk), user, len); break; case EBT_SO_SET_COUNTERS: ret = update_counters(sock_net(sk), user, len); break; default: ret = -EINVAL; } return ret; } static int do_ebt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; struct ebt_replace tmp; struct ebt_table *t; if (!capable(CAP_NET_ADMIN)) return -EPERM; if (copy_from_user(&tmp, user, sizeof(tmp))) return -EFAULT; t = find_table_lock(sock_net(sk), tmp.name, &ret, &ebt_mutex); if (!t) return ret; switch(cmd) { case EBT_SO_GET_INFO: case EBT_SO_GET_INIT_INFO: if (*len != sizeof(struct ebt_replace)){ ret = -EINVAL; mutex_unlock(&ebt_mutex); break; } if (cmd == EBT_SO_GET_INFO) { tmp.nentries = t->private->nentries; tmp.entries_size = t->private->entries_size; tmp.valid_hooks = t->valid_hooks; } else { tmp.nentries = t->table->nentries; tmp.entries_size = t->table->entries_size; tmp.valid_hooks = t->table->valid_hooks; } mutex_unlock(&ebt_mutex); if (copy_to_user(user, &tmp, *len) != 0){ BUGPRINT("c2u Didn't work\n"); ret = -EFAULT; break; } ret = 0; break; case EBT_SO_GET_ENTRIES: case EBT_SO_GET_INIT_ENTRIES: ret = copy_everything_to_user(t, user, len, cmd); mutex_unlock(&ebt_mutex); break; default: mutex_unlock(&ebt_mutex); ret = -EINVAL; } return ret; } #ifdef CONFIG_COMPAT /* 32 bit-userspace compatibility definitions. */ struct compat_ebt_replace { char name[EBT_TABLE_MAXNAMELEN]; compat_uint_t valid_hooks; compat_uint_t nentries; compat_uint_t entries_size; /* start of the chains */ compat_uptr_t hook_entry[NF_BR_NUMHOOKS]; /* nr of counters userspace expects back */ compat_uint_t num_counters; /* where the kernel will put the old counters. */ compat_uptr_t counters; compat_uptr_t entries; }; /* struct ebt_entry_match, _target and _watcher have same layout */ struct compat_ebt_entry_mwt { union { char name[EBT_FUNCTION_MAXNAMELEN]; compat_uptr_t ptr; } u; compat_uint_t match_size; compat_uint_t data[0]; }; /* account for possible padding between match_size and ->data */ static int ebt_compat_entry_padsize(void) { BUILD_BUG_ON(XT_ALIGN(sizeof(struct ebt_entry_match)) < COMPAT_XT_ALIGN(sizeof(struct compat_ebt_entry_mwt))); return (int) XT_ALIGN(sizeof(struct ebt_entry_match)) - COMPAT_XT_ALIGN(sizeof(struct compat_ebt_entry_mwt)); } static int ebt_compat_match_offset(const struct xt_match *match, unsigned int userlen) { /* * ebt_among needs special handling. The kernel .matchsize is * set to -1 at registration time; at runtime an EBT_ALIGN()ed * value is expected. * Example: userspace sends 4500, ebt_among.c wants 4504. */ if (unlikely(match->matchsize == -1)) return XT_ALIGN(userlen) - COMPAT_XT_ALIGN(userlen); return xt_compat_match_offset(match); } static int compat_match_to_user(struct ebt_entry_match *m, void __user **dstptr, unsigned int *size) { const struct xt_match *match = m->u.match; struct compat_ebt_entry_mwt __user *cm = *dstptr; int off = ebt_compat_match_offset(match, m->match_size); compat_uint_t msize = m->match_size - off; BUG_ON(off >= m->match_size); if (copy_to_user(cm->u.name, match->name, strlen(match->name) + 1) || put_user(msize, &cm->match_size)) return -EFAULT; if (match->compat_to_user) { if (match->compat_to_user(cm->data, m->data)) return -EFAULT; } else if (copy_to_user(cm->data, m->data, msize)) return -EFAULT; *size -= ebt_compat_entry_padsize() + off; *dstptr = cm->data; *dstptr += msize; return 0; } static int compat_target_to_user(struct ebt_entry_target *t, void __user **dstptr, unsigned int *size) { const struct xt_target *target = t->u.target; struct compat_ebt_entry_mwt __user *cm = *dstptr; int off = xt_compat_target_offset(target); compat_uint_t tsize = t->target_size - off; BUG_ON(off >= t->target_size); if (copy_to_user(cm->u.name, target->name, strlen(target->name) + 1) || put_user(tsize, &cm->match_size)) return -EFAULT; if (target->compat_to_user) { if (target->compat_to_user(cm->data, t->data)) return -EFAULT; } else if (copy_to_user(cm->data, t->data, tsize)) return -EFAULT; *size -= ebt_compat_entry_padsize() + off; *dstptr = cm->data; *dstptr += tsize; return 0; } static int compat_watcher_to_user(struct ebt_entry_watcher *w, void __user **dstptr, unsigned int *size) { return compat_target_to_user((struct ebt_entry_target *)w, dstptr, size); } static int compat_copy_entry_to_user(struct ebt_entry *e, void __user **dstptr, unsigned int *size) { struct ebt_entry_target *t; struct ebt_entry __user *ce; u32 watchers_offset, target_offset, next_offset; compat_uint_t origsize; int ret; if (e->bitmask == 0) { if (*size < sizeof(struct ebt_entries)) return -EINVAL; if (copy_to_user(*dstptr, e, sizeof(struct ebt_entries))) return -EFAULT; *dstptr += sizeof(struct ebt_entries); *size -= sizeof(struct ebt_entries); return 0; } if (*size < sizeof(*ce)) return -EINVAL; ce = (struct ebt_entry __user *)*dstptr; if (copy_to_user(ce, e, sizeof(*ce))) return -EFAULT; origsize = *size; *dstptr += sizeof(*ce); ret = EBT_MATCH_ITERATE(e, compat_match_to_user, dstptr, size); if (ret) return ret; watchers_offset = e->watchers_offset - (origsize - *size); ret = EBT_WATCHER_ITERATE(e, compat_watcher_to_user, dstptr, size); if (ret) return ret; target_offset = e->target_offset - (origsize - *size); t = (struct ebt_entry_target *) ((char *) e + e->target_offset); ret = compat_target_to_user(t, dstptr, size); if (ret) return ret; next_offset = e->next_offset - (origsize - *size); if (put_user(watchers_offset, &ce->watchers_offset) || put_user(target_offset, &ce->target_offset) || put_user(next_offset, &ce->next_offset)) return -EFAULT; *size -= sizeof(*ce); return 0; } static int compat_calc_match(struct ebt_entry_match *m, int *off) { *off += ebt_compat_match_offset(m->u.match, m->match_size); *off += ebt_compat_entry_padsize(); return 0; } static int compat_calc_watcher(struct ebt_entry_watcher *w, int *off) { *off += xt_compat_target_offset(w->u.watcher); *off += ebt_compat_entry_padsize(); return 0; } static int compat_calc_entry(const struct ebt_entry *e, const struct ebt_table_info *info, const void *base, struct compat_ebt_replace *newinfo) { const struct ebt_entry_target *t; unsigned int entry_offset; int off, ret, i; if (e->bitmask == 0) return 0; off = 0; entry_offset = (void *)e - base; EBT_MATCH_ITERATE(e, compat_calc_match, &off); EBT_WATCHER_ITERATE(e, compat_calc_watcher, &off); t = (const struct ebt_entry_target *) ((char *) e + e->target_offset); off += xt_compat_target_offset(t->u.target); off += ebt_compat_entry_padsize(); newinfo->entries_size -= off; ret = xt_compat_add_offset(NFPROTO_BRIDGE, entry_offset, off); if (ret) return ret; for (i = 0; i < NF_BR_NUMHOOKS; i++) { const void *hookptr = info->hook_entry[i]; if (info->hook_entry[i] && (e < (struct ebt_entry *)(base - hookptr))) { newinfo->hook_entry[i] -= off; pr_debug("0x%08X -> 0x%08X\n", newinfo->hook_entry[i] + off, newinfo->hook_entry[i]); } } return 0; } static int compat_table_info(const struct ebt_table_info *info, struct compat_ebt_replace *newinfo) { unsigned int size = info->entries_size; const void *entries = info->entries; newinfo->entries_size = size; xt_compat_init_offsets(NFPROTO_BRIDGE, info->nentries); return EBT_ENTRY_ITERATE(entries, size, compat_calc_entry, info, entries, newinfo); } static int compat_copy_everything_to_user(struct ebt_table *t, void __user *user, int *len, int cmd) { struct compat_ebt_replace repl, tmp; struct ebt_counter *oldcounters; struct ebt_table_info tinfo; int ret; void __user *pos; memset(&tinfo, 0, sizeof(tinfo)); if (cmd == EBT_SO_GET_ENTRIES) { tinfo.entries_size = t->private->entries_size; tinfo.nentries = t->private->nentries; tinfo.entries = t->private->entries; oldcounters = t->private->counters; } else { tinfo.entries_size = t->table->entries_size; tinfo.nentries = t->table->nentries; tinfo.entries = t->table->entries; oldcounters = t->table->counters; } if (copy_from_user(&tmp, user, sizeof(tmp))) return -EFAULT; if (tmp.nentries != tinfo.nentries || (tmp.num_counters && tmp.num_counters != tinfo.nentries)) return -EINVAL; memcpy(&repl, &tmp, sizeof(repl)); if (cmd == EBT_SO_GET_ENTRIES) ret = compat_table_info(t->private, &repl); else ret = compat_table_info(&tinfo, &repl); if (ret) return ret; if (*len != sizeof(tmp) + repl.entries_size + (tmp.num_counters? tinfo.nentries * sizeof(struct ebt_counter): 0)) { pr_err("wrong size: *len %d, entries_size %u, replsz %d\n", *len, tinfo.entries_size, repl.entries_size); return -EINVAL; } /* userspace might not need the counters */ ret = copy_counters_to_user(t, oldcounters, compat_ptr(tmp.counters), tmp.num_counters, tinfo.nentries); if (ret) return ret; pos = compat_ptr(tmp.entries); return EBT_ENTRY_ITERATE(tinfo.entries, tinfo.entries_size, compat_copy_entry_to_user, &pos, &tmp.entries_size); } struct ebt_entries_buf_state { char *buf_kern_start; /* kernel buffer to copy (translated) data to */ u32 buf_kern_len; /* total size of kernel buffer */ u32 buf_kern_offset; /* amount of data copied so far */ u32 buf_user_offset; /* read position in userspace buffer */ }; static int ebt_buf_count(struct ebt_entries_buf_state *state, unsigned int sz) { state->buf_kern_offset += sz; return state->buf_kern_offset >= sz ? 0 : -EINVAL; } static int ebt_buf_add(struct ebt_entries_buf_state *state, void *data, unsigned int sz) { if (state->buf_kern_start == NULL) goto count_only; BUG_ON(state->buf_kern_offset + sz > state->buf_kern_len); memcpy(state->buf_kern_start + state->buf_kern_offset, data, sz); count_only: state->buf_user_offset += sz; return ebt_buf_count(state, sz); } static int ebt_buf_add_pad(struct ebt_entries_buf_state *state, unsigned int sz) { char *b = state->buf_kern_start; BUG_ON(b && state->buf_kern_offset > state->buf_kern_len); if (b != NULL && sz > 0) memset(b + state->buf_kern_offset, 0, sz); /* do not adjust ->buf_user_offset here, we added kernel-side padding */ return ebt_buf_count(state, sz); } enum compat_mwt { EBT_COMPAT_MATCH, EBT_COMPAT_WATCHER, EBT_COMPAT_TARGET, }; static int compat_mtw_from_user(struct compat_ebt_entry_mwt *mwt, enum compat_mwt compat_mwt, struct ebt_entries_buf_state *state, const unsigned char *base) { char name[EBT_FUNCTION_MAXNAMELEN]; struct xt_match *match; struct xt_target *wt; void *dst = NULL; int off, pad = 0; unsigned int size_kern, match_size = mwt->match_size; strlcpy(name, mwt->u.name, sizeof(name)); if (state->buf_kern_start) dst = state->buf_kern_start + state->buf_kern_offset; switch (compat_mwt) { case EBT_COMPAT_MATCH: match = xt_request_find_match(NFPROTO_BRIDGE, name, 0); if (IS_ERR(match)) return PTR_ERR(match); off = ebt_compat_match_offset(match, match_size); if (dst) { if (match->compat_from_user) match->compat_from_user(dst, mwt->data); else memcpy(dst, mwt->data, match_size); } size_kern = match->matchsize; if (unlikely(size_kern == -1)) size_kern = match_size; module_put(match->me); break; case EBT_COMPAT_WATCHER: /* fallthrough */ case EBT_COMPAT_TARGET: wt = xt_request_find_target(NFPROTO_BRIDGE, name, 0); if (IS_ERR(wt)) return PTR_ERR(wt); off = xt_compat_target_offset(wt); if (dst) { if (wt->compat_from_user) wt->compat_from_user(dst, mwt->data); else memcpy(dst, mwt->data, match_size); } size_kern = wt->targetsize; module_put(wt->me); break; default: return -EINVAL; } state->buf_kern_offset += match_size + off; state->buf_user_offset += match_size; pad = XT_ALIGN(size_kern) - size_kern; if (pad > 0 && dst) { BUG_ON(state->buf_kern_len <= pad); BUG_ON(state->buf_kern_offset - (match_size + off) + size_kern > state->buf_kern_len - pad); memset(dst + size_kern, 0, pad); } return off + match_size; } /* * return size of all matches, watchers or target, including necessary * alignment and padding. */ static int ebt_size_mwt(struct compat_ebt_entry_mwt *match32, unsigned int size_left, enum compat_mwt type, struct ebt_entries_buf_state *state, const void *base) { int growth = 0; char *buf; if (size_left == 0) return 0; buf = (char *) match32; while (size_left >= sizeof(*match32)) { struct ebt_entry_match *match_kern; int ret; match_kern = (struct ebt_entry_match *) state->buf_kern_start; if (match_kern) { char *tmp; tmp = state->buf_kern_start + state->buf_kern_offset; match_kern = (struct ebt_entry_match *) tmp; } ret = ebt_buf_add(state, buf, sizeof(*match32)); if (ret < 0) return ret; size_left -= sizeof(*match32); /* add padding before match->data (if any) */ ret = ebt_buf_add_pad(state, ebt_compat_entry_padsize()); if (ret < 0) return ret; if (match32->match_size > size_left) return -EINVAL; size_left -= match32->match_size; ret = compat_mtw_from_user(match32, type, state, base); if (ret < 0) return ret; BUG_ON(ret < match32->match_size); growth += ret - match32->match_size; growth += ebt_compat_entry_padsize(); buf += sizeof(*match32); buf += match32->match_size; if (match_kern) match_kern->match_size = ret; WARN_ON(type == EBT_COMPAT_TARGET && size_left); match32 = (struct compat_ebt_entry_mwt *) buf; } return growth; } /* called for all ebt_entry structures. */ static int size_entry_mwt(struct ebt_entry *entry, const unsigned char *base, unsigned int *total, struct ebt_entries_buf_state *state) { unsigned int i, j, startoff, new_offset = 0; /* stores match/watchers/targets & offset of next struct ebt_entry: */ unsigned int offsets[4]; unsigned int *offsets_update = NULL; int ret; char *buf_start; if (*total < sizeof(struct ebt_entries)) return -EINVAL; if (!entry->bitmask) { *total -= sizeof(struct ebt_entries); return ebt_buf_add(state, entry, sizeof(struct ebt_entries)); } if (*total < sizeof(*entry) || entry->next_offset < sizeof(*entry)) return -EINVAL; startoff = state->buf_user_offset; /* pull in most part of ebt_entry, it does not need to be changed. */ ret = ebt_buf_add(state, entry, offsetof(struct ebt_entry, watchers_offset)); if (ret < 0) return ret; offsets[0] = sizeof(struct ebt_entry); /* matches come first */ memcpy(&offsets[1], &entry->watchers_offset, sizeof(offsets) - sizeof(offsets[0])); if (state->buf_kern_start) { buf_start = state->buf_kern_start + state->buf_kern_offset; offsets_update = (unsigned int *) buf_start; } ret = ebt_buf_add(state, &offsets[1], sizeof(offsets) - sizeof(offsets[0])); if (ret < 0) return ret; buf_start = (char *) entry; /* * 0: matches offset, always follows ebt_entry. * 1: watchers offset, from ebt_entry structure * 2: target offset, from ebt_entry structure * 3: next ebt_entry offset, from ebt_entry structure * * offsets are relative to beginning of struct ebt_entry (i.e., 0). */ for (i = 0, j = 1 ; j < 4 ; j++, i++) { struct compat_ebt_entry_mwt *match32; unsigned int size; char *buf = buf_start; buf = buf_start + offsets[i]; if (offsets[i] > offsets[j]) return -EINVAL; match32 = (struct compat_ebt_entry_mwt *) buf; size = offsets[j] - offsets[i]; ret = ebt_size_mwt(match32, size, i, state, base); if (ret < 0) return ret; new_offset += ret; if (offsets_update && new_offset) { pr_debug("change offset %d to %d\n", offsets_update[i], offsets[j] + new_offset); offsets_update[i] = offsets[j] + new_offset; } } if (state->buf_kern_start == NULL) { unsigned int offset = buf_start - (char *) base; ret = xt_compat_add_offset(NFPROTO_BRIDGE, offset, new_offset); if (ret < 0) return ret; } startoff = state->buf_user_offset - startoff; BUG_ON(*total < startoff); *total -= startoff; return 0; } /* * repl->entries_size is the size of the ebt_entry blob in userspace. * It might need more memory when copied to a 64 bit kernel in case * userspace is 32-bit. So, first task: find out how much memory is needed. * * Called before validation is performed. */ static int compat_copy_entries(unsigned char *data, unsigned int size_user, struct ebt_entries_buf_state *state) { unsigned int size_remaining = size_user; int ret; ret = EBT_ENTRY_ITERATE(data, size_user, size_entry_mwt, data, &size_remaining, state); if (ret < 0) return ret; WARN_ON(size_remaining); return state->buf_kern_offset; } static int compat_copy_ebt_replace_from_user(struct ebt_replace *repl, void __user *user, unsigned int len) { struct compat_ebt_replace tmp; int i; if (len < sizeof(tmp)) return -EINVAL; if (copy_from_user(&tmp, user, sizeof(tmp))) return -EFAULT; if (len != sizeof(tmp) + tmp.entries_size) return -EINVAL; if (tmp.entries_size == 0) return -EINVAL; if (tmp.nentries >= ((INT_MAX - sizeof(struct ebt_table_info)) / NR_CPUS - SMP_CACHE_BYTES) / sizeof(struct ebt_counter)) return -ENOMEM; if (tmp.num_counters >= INT_MAX / sizeof(struct ebt_counter)) return -ENOMEM; memcpy(repl, &tmp, offsetof(struct ebt_replace, hook_entry)); /* starting with hook_entry, 32 vs. 64 bit structures are different */ for (i = 0; i < NF_BR_NUMHOOKS; i++) repl->hook_entry[i] = compat_ptr(tmp.hook_entry[i]); repl->num_counters = tmp.num_counters; repl->counters = compat_ptr(tmp.counters); repl->entries = compat_ptr(tmp.entries); return 0; } static int compat_do_replace(struct net *net, void __user *user, unsigned int len) { int ret, i, countersize, size64; struct ebt_table_info *newinfo; struct ebt_replace tmp; struct ebt_entries_buf_state state; void *entries_tmp; ret = compat_copy_ebt_replace_from_user(&tmp, user, len); if (ret) { /* try real handler in case userland supplied needed padding */ if (ret == -EINVAL && do_replace(net, user, len) == 0) ret = 0; return ret; } countersize = COUNTER_OFFSET(tmp.nentries) * nr_cpu_ids; newinfo = vmalloc(sizeof(*newinfo) + countersize); if (!newinfo) return -ENOMEM; if (countersize) memset(newinfo->counters, 0, countersize); memset(&state, 0, sizeof(state)); newinfo->entries = vmalloc(tmp.entries_size); if (!newinfo->entries) { ret = -ENOMEM; goto free_newinfo; } if (copy_from_user( newinfo->entries, tmp.entries, tmp.entries_size) != 0) { ret = -EFAULT; goto free_entries; } entries_tmp = newinfo->entries; xt_compat_lock(NFPROTO_BRIDGE); xt_compat_init_offsets(NFPROTO_BRIDGE, tmp.nentries); ret = compat_copy_entries(entries_tmp, tmp.entries_size, &state); if (ret < 0) goto out_unlock; pr_debug("tmp.entries_size %d, kern off %d, user off %d delta %d\n", tmp.entries_size, state.buf_kern_offset, state.buf_user_offset, xt_compat_calc_jump(NFPROTO_BRIDGE, tmp.entries_size)); size64 = ret; newinfo->entries = vmalloc(size64); if (!newinfo->entries) { vfree(entries_tmp); ret = -ENOMEM; goto out_unlock; } memset(&state, 0, sizeof(state)); state.buf_kern_start = newinfo->entries; state.buf_kern_len = size64; ret = compat_copy_entries(entries_tmp, tmp.entries_size, &state); BUG_ON(ret < 0); /* parses same data again */ vfree(entries_tmp); tmp.entries_size = size64; for (i = 0; i < NF_BR_NUMHOOKS; i++) { char __user *usrptr; if (tmp.hook_entry[i]) { unsigned int delta; usrptr = (char __user *) tmp.hook_entry[i]; delta = usrptr - tmp.entries; usrptr += xt_compat_calc_jump(NFPROTO_BRIDGE, delta); tmp.hook_entry[i] = (struct ebt_entries __user *)usrptr; } } xt_compat_flush_offsets(NFPROTO_BRIDGE); xt_compat_unlock(NFPROTO_BRIDGE); ret = do_replace_finish(net, &tmp, newinfo); if (ret == 0) return ret; free_entries: vfree(newinfo->entries); free_newinfo: vfree(newinfo); return ret; out_unlock: xt_compat_flush_offsets(NFPROTO_BRIDGE); xt_compat_unlock(NFPROTO_BRIDGE); goto free_entries; } static int compat_update_counters(struct net *net, void __user *user, unsigned int len) { struct compat_ebt_replace hlp; if (copy_from_user(&hlp, user, sizeof(hlp))) return -EFAULT; /* try real handler in case userland supplied needed padding */ if (len != sizeof(hlp) + hlp.num_counters * sizeof(struct ebt_counter)) return update_counters(net, user, len); return do_update_counters(net, hlp.name, compat_ptr(hlp.counters), hlp.num_counters, user, len); } static int compat_do_ebt_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { int ret; if (!capable(CAP_NET_ADMIN)) return -EPERM; switch (cmd) { case EBT_SO_SET_ENTRIES: ret = compat_do_replace(sock_net(sk), user, len); break; case EBT_SO_SET_COUNTERS: ret = compat_update_counters(sock_net(sk), user, len); break; default: ret = -EINVAL; } return ret; } static int compat_do_ebt_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { int ret; struct compat_ebt_replace tmp; struct ebt_table *t; if (!capable(CAP_NET_ADMIN)) return -EPERM; /* try real handler in case userland supplied needed padding */ if ((cmd == EBT_SO_GET_INFO || cmd == EBT_SO_GET_INIT_INFO) && *len != sizeof(tmp)) return do_ebt_get_ctl(sk, cmd, user, len); if (copy_from_user(&tmp, user, sizeof(tmp))) return -EFAULT; t = find_table_lock(sock_net(sk), tmp.name, &ret, &ebt_mutex); if (!t) return ret; xt_compat_lock(NFPROTO_BRIDGE); switch (cmd) { case EBT_SO_GET_INFO: tmp.nentries = t->private->nentries; ret = compat_table_info(t->private, &tmp); if (ret) goto out; tmp.valid_hooks = t->valid_hooks; if (copy_to_user(user, &tmp, *len) != 0) { ret = -EFAULT; break; } ret = 0; break; case EBT_SO_GET_INIT_INFO: tmp.nentries = t->table->nentries; tmp.entries_size = t->table->entries_size; tmp.valid_hooks = t->table->valid_hooks; if (copy_to_user(user, &tmp, *len) != 0) { ret = -EFAULT; break; } ret = 0; break; case EBT_SO_GET_ENTRIES: case EBT_SO_GET_INIT_ENTRIES: /* * try real handler first in case of userland-side padding. * in case we are dealing with an 'ordinary' 32 bit binary * without 64bit compatibility padding, this will fail right * after copy_from_user when the *len argument is validated. * * the compat_ variant needs to do one pass over the kernel * data set to adjust for size differences before it the check. */ if (copy_everything_to_user(t, user, len, cmd) == 0) ret = 0; else ret = compat_copy_everything_to_user(t, user, len, cmd); break; default: ret = -EINVAL; } out: xt_compat_flush_offsets(NFPROTO_BRIDGE); xt_compat_unlock(NFPROTO_BRIDGE); mutex_unlock(&ebt_mutex); return ret; } #endif static struct nf_sockopt_ops ebt_sockopts = { .pf = PF_INET, .set_optmin = EBT_BASE_CTL, .set_optmax = EBT_SO_SET_MAX + 1, .set = do_ebt_set_ctl, #ifdef CONFIG_COMPAT .compat_set = compat_do_ebt_set_ctl, #endif .get_optmin = EBT_BASE_CTL, .get_optmax = EBT_SO_GET_MAX + 1, .get = do_ebt_get_ctl, #ifdef CONFIG_COMPAT .compat_get = compat_do_ebt_get_ctl, #endif .owner = THIS_MODULE, }; static int __init ebtables_init(void) { int ret; ret = xt_register_target(&ebt_standard_target); if (ret < 0) return ret; ret = nf_register_sockopt(&ebt_sockopts); if (ret < 0) { xt_unregister_target(&ebt_standard_target); return ret; } printk(KERN_INFO "Ebtables v2.0 registered\n"); return 0; } static void __exit ebtables_fini(void) { nf_unregister_sockopt(&ebt_sockopts); xt_unregister_target(&ebt_standard_target); printk(KERN_INFO "Ebtables v2.0 unregistered\n"); } EXPORT_SYMBOL(ebt_register_table); EXPORT_SYMBOL(ebt_unregister_table); EXPORT_SYMBOL(ebt_do_table); module_init(ebtables_init); module_exit(ebtables_fini); MODULE_LICENSE("GPL");
gpl-2.0
Pantech-Discover/android_kernel_pantech_magnus
fs/xfs/xfs_utils.c
4814
8336
/* * Copyright (c) 2000-2002,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_types.h" #include "xfs_bit.h" #include "xfs_log.h" #include "xfs_inum.h" #include "xfs_trans.h" #include "xfs_sb.h" #include "xfs_ag.h" #include "xfs_dir2.h" #include "xfs_mount.h" #include "xfs_bmap_btree.h" #include "xfs_dinode.h" #include "xfs_inode.h" #include "xfs_inode_item.h" #include "xfs_bmap.h" #include "xfs_error.h" #include "xfs_quota.h" #include "xfs_itable.h" #include "xfs_utils.h" /* * Allocates a new inode from disk and return a pointer to the * incore copy. This routine will internally commit the current * transaction and allocate a new one if the Space Manager needed * to do an allocation to replenish the inode free-list. * * This routine is designed to be called from xfs_create and * xfs_create_dir. * */ int xfs_dir_ialloc( xfs_trans_t **tpp, /* input: current transaction; output: may be a new transaction. */ xfs_inode_t *dp, /* directory within whose allocate the inode. */ umode_t mode, xfs_nlink_t nlink, xfs_dev_t rdev, prid_t prid, /* project id */ int okalloc, /* ok to allocate new space */ xfs_inode_t **ipp, /* pointer to inode; it will be locked. */ int *committed) { xfs_trans_t *tp; xfs_trans_t *ntp; xfs_inode_t *ip; xfs_buf_t *ialloc_context = NULL; boolean_t call_again = B_FALSE; int code; uint log_res; uint log_count; void *dqinfo; uint tflags; tp = *tpp; ASSERT(tp->t_flags & XFS_TRANS_PERM_LOG_RES); /* * xfs_ialloc will return a pointer to an incore inode if * the Space Manager has an available inode on the free * list. Otherwise, it will do an allocation and replenish * the freelist. Since we can only do one allocation per * transaction without deadlocks, we will need to commit the * current transaction and start a new one. We will then * need to call xfs_ialloc again to get the inode. * * If xfs_ialloc did an allocation to replenish the freelist, * it returns the bp containing the head of the freelist as * ialloc_context. We will hold a lock on it across the * transaction commit so that no other process can steal * the inode(s) that we've just allocated. */ code = xfs_ialloc(tp, dp, mode, nlink, rdev, prid, okalloc, &ialloc_context, &call_again, &ip); /* * Return an error if we were unable to allocate a new inode. * This should only happen if we run out of space on disk or * encounter a disk error. */ if (code) { *ipp = NULL; return code; } if (!call_again && (ip == NULL)) { *ipp = NULL; return XFS_ERROR(ENOSPC); } /* * If call_again is set, then we were unable to get an * inode in one operation. We need to commit the current * transaction and call xfs_ialloc() again. It is guaranteed * to succeed the second time. */ if (call_again) { /* * Normally, xfs_trans_commit releases all the locks. * We call bhold to hang on to the ialloc_context across * the commit. Holding this buffer prevents any other * processes from doing any allocations in this * allocation group. */ xfs_trans_bhold(tp, ialloc_context); /* * Save the log reservation so we can use * them in the next transaction. */ log_res = xfs_trans_get_log_res(tp); log_count = xfs_trans_get_log_count(tp); /* * We want the quota changes to be associated with the next * transaction, NOT this one. So, detach the dqinfo from this * and attach it to the next transaction. */ dqinfo = NULL; tflags = 0; if (tp->t_dqinfo) { dqinfo = (void *)tp->t_dqinfo; tp->t_dqinfo = NULL; tflags = tp->t_flags & XFS_TRANS_DQ_DIRTY; tp->t_flags &= ~(XFS_TRANS_DQ_DIRTY); } ntp = xfs_trans_dup(tp); code = xfs_trans_commit(tp, 0); tp = ntp; if (committed != NULL) { *committed = 1; } /* * If we get an error during the commit processing, * release the buffer that is still held and return * to the caller. */ if (code) { xfs_buf_relse(ialloc_context); if (dqinfo) { tp->t_dqinfo = dqinfo; xfs_trans_free_dqinfo(tp); } *tpp = ntp; *ipp = NULL; return code; } /* * transaction commit worked ok so we can drop the extra ticket * reference that we gained in xfs_trans_dup() */ xfs_log_ticket_put(tp->t_ticket); code = xfs_trans_reserve(tp, 0, log_res, 0, XFS_TRANS_PERM_LOG_RES, log_count); /* * Re-attach the quota info that we detached from prev trx. */ if (dqinfo) { tp->t_dqinfo = dqinfo; tp->t_flags |= tflags; } if (code) { xfs_buf_relse(ialloc_context); *tpp = ntp; *ipp = NULL; return code; } xfs_trans_bjoin(tp, ialloc_context); /* * Call ialloc again. Since we've locked out all * other allocations in this allocation group, * this call should always succeed. */ code = xfs_ialloc(tp, dp, mode, nlink, rdev, prid, okalloc, &ialloc_context, &call_again, &ip); /* * If we get an error at this point, return to the caller * so that the current transaction can be aborted. */ if (code) { *tpp = tp; *ipp = NULL; return code; } ASSERT ((!call_again) && (ip != NULL)); } else { if (committed != NULL) { *committed = 0; } } *ipp = ip; *tpp = tp; return 0; } /* * Decrement the link count on an inode & log the change. * If this causes the link count to go to zero, initiate the * logging activity required to truncate a file. */ int /* error */ xfs_droplink( xfs_trans_t *tp, xfs_inode_t *ip) { int error; xfs_trans_ichgtime(tp, ip, XFS_ICHGTIME_CHG); ASSERT (ip->i_d.di_nlink > 0); ip->i_d.di_nlink--; drop_nlink(VFS_I(ip)); xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE); error = 0; if (ip->i_d.di_nlink == 0) { /* * We're dropping the last link to this file. * Move the on-disk inode to the AGI unlinked list. * From xfs_inactive() we will pull the inode from * the list and free it. */ error = xfs_iunlink(tp, ip); } return error; } /* * This gets called when the inode's version needs to be changed from 1 to 2. * Currently this happens when the nlink field overflows the old 16-bit value * or when chproj is called to change the project for the first time. * As a side effect the superblock version will also get rev'd * to contain the NLINK bit. */ void xfs_bump_ino_vers2( xfs_trans_t *tp, xfs_inode_t *ip) { xfs_mount_t *mp; ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL)); ASSERT(ip->i_d.di_version == 1); ip->i_d.di_version = 2; ip->i_d.di_onlink = 0; memset(&(ip->i_d.di_pad[0]), 0, sizeof(ip->i_d.di_pad)); mp = tp->t_mountp; if (!xfs_sb_version_hasnlink(&mp->m_sb)) { spin_lock(&mp->m_sb_lock); if (!xfs_sb_version_hasnlink(&mp->m_sb)) { xfs_sb_version_addnlink(&mp->m_sb); spin_unlock(&mp->m_sb_lock); xfs_mod_sb(tp, XFS_SB_VERSIONNUM); } else { spin_unlock(&mp->m_sb_lock); } } /* Caller must log the inode */ } /* * Increment the link count on an inode & log the change. */ int xfs_bumplink( xfs_trans_t *tp, xfs_inode_t *ip) { xfs_trans_ichgtime(tp, ip, XFS_ICHGTIME_CHG); ASSERT(ip->i_d.di_nlink > 0); ip->i_d.di_nlink++; inc_nlink(VFS_I(ip)); if ((ip->i_d.di_version == 1) && (ip->i_d.di_nlink > XFS_MAXLINK_1)) { /* * The inode has increased its number of links beyond * what can fit in an old format inode. It now needs * to be converted to a version 2 inode with a 32 bit * link count. If this is the first inode in the file * system to do this, then we need to bump the superblock * version number as well. */ xfs_bump_ino_vers2(tp, ip); } xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE); return 0; }
gpl-2.0
Pantech-Discover/android_kernel_pantech_magnus
drivers/media/video/s5p-tv/hdmiphy_drv.c
4814
4598
/* * Samsung HDMI Physical interface driver * * Copyright (C) 2010-2011 Samsung Electronics Co.Ltd * Author: Tomasz Stanislawski <t.stanislaws@samsung.com> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. */ #include <linux/module.h> #include <linux/i2c.h> #include <linux/slab.h> #include <linux/clk.h> #include <linux/io.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/err.h> #include <media/v4l2-subdev.h> MODULE_AUTHOR("Tomasz Stanislawski <t.stanislaws@samsung.com>"); MODULE_DESCRIPTION("Samsung HDMI Physical interface driver"); MODULE_LICENSE("GPL"); struct hdmiphy_conf { u32 preset; const u8 *data; }; static const u8 hdmiphy_conf27[32] = { 0x01, 0x05, 0x00, 0xD8, 0x10, 0x1C, 0x30, 0x40, 0x6B, 0x10, 0x02, 0x51, 0xDf, 0xF2, 0x54, 0x87, 0x84, 0x00, 0x30, 0x38, 0x00, 0x08, 0x10, 0xE0, 0x22, 0x40, 0xe3, 0x26, 0x00, 0x00, 0x00, 0x00, }; static const u8 hdmiphy_conf74_175[32] = { 0x01, 0x05, 0x00, 0xD8, 0x10, 0x9C, 0xef, 0x5B, 0x6D, 0x10, 0x01, 0x51, 0xef, 0xF3, 0x54, 0xb9, 0x84, 0x00, 0x30, 0x38, 0x00, 0x08, 0x10, 0xE0, 0x22, 0x40, 0xa5, 0x26, 0x01, 0x00, 0x00, 0x00, }; static const u8 hdmiphy_conf74_25[32] = { 0x01, 0x05, 0x00, 0xd8, 0x10, 0x9c, 0xf8, 0x40, 0x6a, 0x10, 0x01, 0x51, 0xff, 0xf1, 0x54, 0xba, 0x84, 0x00, 0x30, 0x38, 0x00, 0x08, 0x10, 0xe0, 0x22, 0x40, 0xa4, 0x26, 0x01, 0x00, 0x00, 0x00, }; static const u8 hdmiphy_conf148_5[32] = { 0x01, 0x05, 0x00, 0xD8, 0x10, 0x9C, 0xf8, 0x40, 0x6A, 0x18, 0x00, 0x51, 0xff, 0xF1, 0x54, 0xba, 0x84, 0x00, 0x10, 0x38, 0x00, 0x08, 0x10, 0xE0, 0x22, 0x40, 0xa4, 0x26, 0x02, 0x00, 0x00, 0x00, }; static const struct hdmiphy_conf hdmiphy_conf[] = { { V4L2_DV_480P59_94, hdmiphy_conf27 }, { V4L2_DV_1080P30, hdmiphy_conf74_175 }, { V4L2_DV_720P59_94, hdmiphy_conf74_175 }, { V4L2_DV_720P60, hdmiphy_conf74_25 }, { V4L2_DV_1080P50, hdmiphy_conf148_5 }, { V4L2_DV_1080P60, hdmiphy_conf148_5 }, }; const u8 *hdmiphy_preset2conf(u32 preset) { int i; for (i = 0; i < ARRAY_SIZE(hdmiphy_conf); ++i) if (hdmiphy_conf[i].preset == preset) return hdmiphy_conf[i].data; return NULL; } static int hdmiphy_s_power(struct v4l2_subdev *sd, int on) { /* to be implemented */ return 0; } static int hdmiphy_s_dv_preset(struct v4l2_subdev *sd, struct v4l2_dv_preset *preset) { const u8 *data; u8 buffer[32]; int ret; struct i2c_client *client = v4l2_get_subdevdata(sd); struct device *dev = &client->dev; dev_info(dev, "s_dv_preset(preset = %d)\n", preset->preset); data = hdmiphy_preset2conf(preset->preset); if (!data) { dev_err(dev, "format not supported\n"); return -EINVAL; } /* storing configuration to the device */ memcpy(buffer, data, 32); ret = i2c_master_send(client, buffer, 32); if (ret != 32) { dev_err(dev, "failed to configure HDMIPHY via I2C\n"); return -EIO; } return 0; } static int hdmiphy_s_stream(struct v4l2_subdev *sd, int enable) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct device *dev = &client->dev; u8 buffer[2]; int ret; dev_info(dev, "s_stream(%d)\n", enable); /* going to/from configuration from/to operation mode */ buffer[0] = 0x1f; buffer[1] = enable ? 0x80 : 0x00; ret = i2c_master_send(client, buffer, 2); if (ret != 2) { dev_err(dev, "stream (%d) failed\n", enable); return -EIO; } return 0; } static const struct v4l2_subdev_core_ops hdmiphy_core_ops = { .s_power = hdmiphy_s_power, }; static const struct v4l2_subdev_video_ops hdmiphy_video_ops = { .s_dv_preset = hdmiphy_s_dv_preset, .s_stream = hdmiphy_s_stream, }; static const struct v4l2_subdev_ops hdmiphy_ops = { .core = &hdmiphy_core_ops, .video = &hdmiphy_video_ops, }; static int __devinit hdmiphy_probe(struct i2c_client *client, const struct i2c_device_id *id) { static struct v4l2_subdev sd; v4l2_i2c_subdev_init(&sd, client, &hdmiphy_ops); dev_info(&client->dev, "probe successful\n"); return 0; } static int __devexit hdmiphy_remove(struct i2c_client *client) { dev_info(&client->dev, "remove successful\n"); return 0; } static const struct i2c_device_id hdmiphy_id[] = { { "hdmiphy", 0 }, { }, }; MODULE_DEVICE_TABLE(i2c, hdmiphy_id); static struct i2c_driver hdmiphy_driver = { .driver = { .name = "s5p-hdmiphy", .owner = THIS_MODULE, }, .probe = hdmiphy_probe, .remove = __devexit_p(hdmiphy_remove), .id_table = hdmiphy_id, }; module_i2c_driver(hdmiphy_driver);
gpl-2.0
DTse/cm_kernel_lge_d620
drivers/media/video/s5p-tv/hdmiphy_drv.c
4814
4598
/* * Samsung HDMI Physical interface driver * * Copyright (C) 2010-2011 Samsung Electronics Co.Ltd * Author: Tomasz Stanislawski <t.stanislaws@samsung.com> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. */ #include <linux/module.h> #include <linux/i2c.h> #include <linux/slab.h> #include <linux/clk.h> #include <linux/io.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/err.h> #include <media/v4l2-subdev.h> MODULE_AUTHOR("Tomasz Stanislawski <t.stanislaws@samsung.com>"); MODULE_DESCRIPTION("Samsung HDMI Physical interface driver"); MODULE_LICENSE("GPL"); struct hdmiphy_conf { u32 preset; const u8 *data; }; static const u8 hdmiphy_conf27[32] = { 0x01, 0x05, 0x00, 0xD8, 0x10, 0x1C, 0x30, 0x40, 0x6B, 0x10, 0x02, 0x51, 0xDf, 0xF2, 0x54, 0x87, 0x84, 0x00, 0x30, 0x38, 0x00, 0x08, 0x10, 0xE0, 0x22, 0x40, 0xe3, 0x26, 0x00, 0x00, 0x00, 0x00, }; static const u8 hdmiphy_conf74_175[32] = { 0x01, 0x05, 0x00, 0xD8, 0x10, 0x9C, 0xef, 0x5B, 0x6D, 0x10, 0x01, 0x51, 0xef, 0xF3, 0x54, 0xb9, 0x84, 0x00, 0x30, 0x38, 0x00, 0x08, 0x10, 0xE0, 0x22, 0x40, 0xa5, 0x26, 0x01, 0x00, 0x00, 0x00, }; static const u8 hdmiphy_conf74_25[32] = { 0x01, 0x05, 0x00, 0xd8, 0x10, 0x9c, 0xf8, 0x40, 0x6a, 0x10, 0x01, 0x51, 0xff, 0xf1, 0x54, 0xba, 0x84, 0x00, 0x30, 0x38, 0x00, 0x08, 0x10, 0xe0, 0x22, 0x40, 0xa4, 0x26, 0x01, 0x00, 0x00, 0x00, }; static const u8 hdmiphy_conf148_5[32] = { 0x01, 0x05, 0x00, 0xD8, 0x10, 0x9C, 0xf8, 0x40, 0x6A, 0x18, 0x00, 0x51, 0xff, 0xF1, 0x54, 0xba, 0x84, 0x00, 0x10, 0x38, 0x00, 0x08, 0x10, 0xE0, 0x22, 0x40, 0xa4, 0x26, 0x02, 0x00, 0x00, 0x00, }; static const struct hdmiphy_conf hdmiphy_conf[] = { { V4L2_DV_480P59_94, hdmiphy_conf27 }, { V4L2_DV_1080P30, hdmiphy_conf74_175 }, { V4L2_DV_720P59_94, hdmiphy_conf74_175 }, { V4L2_DV_720P60, hdmiphy_conf74_25 }, { V4L2_DV_1080P50, hdmiphy_conf148_5 }, { V4L2_DV_1080P60, hdmiphy_conf148_5 }, }; const u8 *hdmiphy_preset2conf(u32 preset) { int i; for (i = 0; i < ARRAY_SIZE(hdmiphy_conf); ++i) if (hdmiphy_conf[i].preset == preset) return hdmiphy_conf[i].data; return NULL; } static int hdmiphy_s_power(struct v4l2_subdev *sd, int on) { /* to be implemented */ return 0; } static int hdmiphy_s_dv_preset(struct v4l2_subdev *sd, struct v4l2_dv_preset *preset) { const u8 *data; u8 buffer[32]; int ret; struct i2c_client *client = v4l2_get_subdevdata(sd); struct device *dev = &client->dev; dev_info(dev, "s_dv_preset(preset = %d)\n", preset->preset); data = hdmiphy_preset2conf(preset->preset); if (!data) { dev_err(dev, "format not supported\n"); return -EINVAL; } /* storing configuration to the device */ memcpy(buffer, data, 32); ret = i2c_master_send(client, buffer, 32); if (ret != 32) { dev_err(dev, "failed to configure HDMIPHY via I2C\n"); return -EIO; } return 0; } static int hdmiphy_s_stream(struct v4l2_subdev *sd, int enable) { struct i2c_client *client = v4l2_get_subdevdata(sd); struct device *dev = &client->dev; u8 buffer[2]; int ret; dev_info(dev, "s_stream(%d)\n", enable); /* going to/from configuration from/to operation mode */ buffer[0] = 0x1f; buffer[1] = enable ? 0x80 : 0x00; ret = i2c_master_send(client, buffer, 2); if (ret != 2) { dev_err(dev, "stream (%d) failed\n", enable); return -EIO; } return 0; } static const struct v4l2_subdev_core_ops hdmiphy_core_ops = { .s_power = hdmiphy_s_power, }; static const struct v4l2_subdev_video_ops hdmiphy_video_ops = { .s_dv_preset = hdmiphy_s_dv_preset, .s_stream = hdmiphy_s_stream, }; static const struct v4l2_subdev_ops hdmiphy_ops = { .core = &hdmiphy_core_ops, .video = &hdmiphy_video_ops, }; static int __devinit hdmiphy_probe(struct i2c_client *client, const struct i2c_device_id *id) { static struct v4l2_subdev sd; v4l2_i2c_subdev_init(&sd, client, &hdmiphy_ops); dev_info(&client->dev, "probe successful\n"); return 0; } static int __devexit hdmiphy_remove(struct i2c_client *client) { dev_info(&client->dev, "remove successful\n"); return 0; } static const struct i2c_device_id hdmiphy_id[] = { { "hdmiphy", 0 }, { }, }; MODULE_DEVICE_TABLE(i2c, hdmiphy_id); static struct i2c_driver hdmiphy_driver = { .driver = { .name = "s5p-hdmiphy", .owner = THIS_MODULE, }, .probe = hdmiphy_probe, .remove = __devexit_p(hdmiphy_remove), .id_table = hdmiphy_id, }; module_i2c_driver(hdmiphy_driver);
gpl-2.0
Anik1199/Kernel_taoshan
drivers/mtd/maps/sun_uflash.c
5070
3689
/* sun_uflash.c - Driver for user-programmable flash on * Sun Microsystems SME boardsets. * * This driver does NOT provide access to the OBP-flash for * safety reasons-- use <linux>/drivers/sbus/char/flash.c instead. * * Copyright (c) 2001 Eric Brower (ebrower@usa.net) */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/fs.h> #include <linux/errno.h> #include <linux/init.h> #include <linux/ioport.h> #include <linux/of.h> #include <linux/of_device.h> #include <linux/slab.h> #include <asm/prom.h> #include <asm/uaccess.h> #include <asm/io.h> #include <linux/mtd/mtd.h> #include <linux/mtd/map.h> #define UFLASH_OBPNAME "flashprom" #define DRIVER_NAME "sun_uflash" #define PFX DRIVER_NAME ": " #define UFLASH_WINDOW_SIZE 0x200000 #define UFLASH_BUSWIDTH 1 /* EBus is 8-bit */ MODULE_AUTHOR("Eric Brower <ebrower@usa.net>"); MODULE_DESCRIPTION("User-programmable flash device on Sun Microsystems boardsets"); MODULE_SUPPORTED_DEVICE(DRIVER_NAME); MODULE_LICENSE("GPL"); MODULE_VERSION("2.1"); struct uflash_dev { const char *name; /* device name */ struct map_info map; /* mtd map info */ struct mtd_info *mtd; /* mtd info */ }; struct map_info uflash_map_templ = { .name = "SUNW,???-????", .size = UFLASH_WINDOW_SIZE, .bankwidth = UFLASH_BUSWIDTH, }; int uflash_devinit(struct platform_device *op, struct device_node *dp) { struct uflash_dev *up; if (op->resource[1].flags) { /* Non-CFI userflash device-- once I find one we * can work on supporting it. */ printk(KERN_ERR PFX "Unsupported device at %s, 0x%llx\n", dp->full_name, (unsigned long long)op->resource[0].start); return -ENODEV; } up = kzalloc(sizeof(struct uflash_dev), GFP_KERNEL); if (!up) { printk(KERN_ERR PFX "Cannot allocate struct uflash_dev\n"); return -ENOMEM; } /* copy defaults and tweak parameters */ memcpy(&up->map, &uflash_map_templ, sizeof(uflash_map_templ)); up->map.size = resource_size(&op->resource[0]); up->name = of_get_property(dp, "model", NULL); if (up->name && 0 < strlen(up->name)) up->map.name = (char *)up->name; up->map.phys = op->resource[0].start; up->map.virt = of_ioremap(&op->resource[0], 0, up->map.size, DRIVER_NAME); if (!up->map.virt) { printk(KERN_ERR PFX "Failed to map device.\n"); kfree(up); return -EINVAL; } simple_map_init(&up->map); /* MTD registration */ up->mtd = do_map_probe("cfi_probe", &up->map); if (!up->mtd) { of_iounmap(&op->resource[0], up->map.virt, up->map.size); kfree(up); return -ENXIO; } up->mtd->owner = THIS_MODULE; mtd_device_register(up->mtd, NULL, 0); dev_set_drvdata(&op->dev, up); return 0; } static int __devinit uflash_probe(struct platform_device *op) { struct device_node *dp = op->dev.of_node; /* Flashprom must have the "user" property in order to * be used by this driver. */ if (!of_find_property(dp, "user", NULL)) return -ENODEV; return uflash_devinit(op, dp); } static int __devexit uflash_remove(struct platform_device *op) { struct uflash_dev *up = dev_get_drvdata(&op->dev); if (up->mtd) { mtd_device_unregister(up->mtd); map_destroy(up->mtd); } if (up->map.virt) { of_iounmap(&op->resource[0], up->map.virt, up->map.size); up->map.virt = NULL; } kfree(up); return 0; } static const struct of_device_id uflash_match[] = { { .name = UFLASH_OBPNAME, }, {}, }; MODULE_DEVICE_TABLE(of, uflash_match); static struct platform_driver uflash_driver = { .driver = { .name = DRIVER_NAME, .owner = THIS_MODULE, .of_match_table = uflash_match, }, .probe = uflash_probe, .remove = __devexit_p(uflash_remove), }; module_platform_driver(uflash_driver);
gpl-2.0
aniketroxx/Phantocivic_Nicki
drivers/char/hw_random/timeriomem-rng.c
5070
3899
/* * drivers/char/hw_random/timeriomem-rng.c * * Copyright (C) 2009 Alexander Clouter <alex@digriz.org.uk> * * Derived from drivers/char/hw_random/omap-rng.c * Copyright 2005 (c) MontaVista Software, Inc. * Author: Deepak Saxena <dsaxena@plexity.net> * * 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. * * Overview: * This driver is useful for platforms that have an IO range that provides * periodic random data from a single IO memory address. All the platform * has to do is provide the address and 'wait time' that new data becomes * available. * * TODO: add support for reading sizes other than 32bits and masking */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/platform_device.h> #include <linux/hw_random.h> #include <linux/io.h> #include <linux/timeriomem-rng.h> #include <linux/jiffies.h> #include <linux/sched.h> #include <linux/timer.h> #include <linux/completion.h> static struct timeriomem_rng_data *timeriomem_rng_data; static void timeriomem_rng_trigger(unsigned long); static DEFINE_TIMER(timeriomem_rng_timer, timeriomem_rng_trigger, 0, 0); /* * have data return 1, however return 0 if we have nothing */ static int timeriomem_rng_data_present(struct hwrng *rng, int wait) { if (rng->priv == 0) return 1; if (!wait || timeriomem_rng_data->present) return timeriomem_rng_data->present; wait_for_completion(&timeriomem_rng_data->completion); return 1; } static int timeriomem_rng_data_read(struct hwrng *rng, u32 *data) { unsigned long cur; s32 delay; *data = readl(timeriomem_rng_data->address); if (rng->priv != 0) { cur = jiffies; delay = cur - timeriomem_rng_timer.expires; delay = rng->priv - (delay % rng->priv); timeriomem_rng_timer.expires = cur + delay; timeriomem_rng_data->present = 0; init_completion(&timeriomem_rng_data->completion); add_timer(&timeriomem_rng_timer); } return 4; } static void timeriomem_rng_trigger(unsigned long dummy) { timeriomem_rng_data->present = 1; complete(&timeriomem_rng_data->completion); } static struct hwrng timeriomem_rng_ops = { .name = "timeriomem", .data_present = timeriomem_rng_data_present, .data_read = timeriomem_rng_data_read, .priv = 0, }; static int __devinit timeriomem_rng_probe(struct platform_device *pdev) { struct resource *res; int ret; res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) return -ENOENT; timeriomem_rng_data = pdev->dev.platform_data; timeriomem_rng_data->address = ioremap(res->start, resource_size(res)); if (!timeriomem_rng_data->address) return -EIO; if (timeriomem_rng_data->period != 0 && usecs_to_jiffies(timeriomem_rng_data->period) > 0) { timeriomem_rng_timer.expires = jiffies; timeriomem_rng_ops.priv = usecs_to_jiffies( timeriomem_rng_data->period); } timeriomem_rng_data->present = 1; ret = hwrng_register(&timeriomem_rng_ops); if (ret) goto failed; dev_info(&pdev->dev, "32bits from 0x%p @ %dus\n", timeriomem_rng_data->address, timeriomem_rng_data->period); return 0; failed: dev_err(&pdev->dev, "problem registering\n"); iounmap(timeriomem_rng_data->address); return ret; } static int __devexit timeriomem_rng_remove(struct platform_device *pdev) { del_timer_sync(&timeriomem_rng_timer); hwrng_unregister(&timeriomem_rng_ops); iounmap(timeriomem_rng_data->address); return 0; } static struct platform_driver timeriomem_rng_driver = { .driver = { .name = "timeriomem_rng", .owner = THIS_MODULE, }, .probe = timeriomem_rng_probe, .remove = __devexit_p(timeriomem_rng_remove), }; module_platform_driver(timeriomem_rng_driver); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Alexander Clouter <alex@digriz.org.uk>"); MODULE_DESCRIPTION("Timer IOMEM H/W RNG driver");
gpl-2.0
ennarr/linux-kernel
arch/arm/mach-s3c2440/s3c2440-cpufreq.c
5070
7338
/* linux/arch/arm/plat-s3c24xx/s3c2440-cpufreq.c * * Copyright (c) 2006-2009 Simtec Electronics * http://armlinux.simtec.co.uk/ * Ben Dooks <ben@simtec.co.uk> * Vincent Sanders <vince@simtec.co.uk> * * S3C2440/S3C2442 CPU Frequency scaling * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/init.h> #include <linux/module.h> #include <linux/interrupt.h> #include <linux/ioport.h> #include <linux/cpufreq.h> #include <linux/device.h> #include <linux/delay.h> #include <linux/clk.h> #include <linux/err.h> #include <linux/io.h> #include <mach/hardware.h> #include <asm/mach/arch.h> #include <asm/mach/map.h> #include <mach/regs-clock.h> #include <plat/cpu.h> #include <plat/cpu-freq-core.h> #include <plat/clock.h> static struct clk *xtal; static struct clk *fclk; static struct clk *hclk; static struct clk *armclk; /* HDIV: 1, 2, 3, 4, 6, 8 */ static inline int within_khz(unsigned long a, unsigned long b) { long diff = a - b; return (diff >= -1000 && diff <= 1000); } /** * s3c2440_cpufreq_calcdivs - calculate divider settings * @cfg: The cpu frequency settings. * * Calcualte the divider values for the given frequency settings * specified in @cfg. The values are stored in @cfg for later use * by the relevant set routine if the request settings can be reached. */ int s3c2440_cpufreq_calcdivs(struct s3c_cpufreq_config *cfg) { unsigned int hdiv, pdiv; unsigned long hclk, fclk, armclk; unsigned long hclk_max; fclk = cfg->freq.fclk; armclk = cfg->freq.armclk; hclk_max = cfg->max.hclk; s3c_freq_dbg("%s: fclk is %lu, armclk %lu, max hclk %lu\n", __func__, fclk, armclk, hclk_max); if (armclk > fclk) { printk(KERN_WARNING "%s: armclk > fclk\n", __func__); armclk = fclk; } /* if we are in DVS, we need HCLK to be <= ARMCLK */ if (armclk < fclk && armclk < hclk_max) hclk_max = armclk; for (hdiv = 1; hdiv < 9; hdiv++) { if (hdiv == 5 || hdiv == 7) hdiv++; hclk = (fclk / hdiv); if (hclk <= hclk_max || within_khz(hclk, hclk_max)) break; } s3c_freq_dbg("%s: hclk %lu, div %d\n", __func__, hclk, hdiv); if (hdiv > 8) goto invalid; pdiv = (hclk > cfg->max.pclk) ? 2 : 1; if ((hclk / pdiv) > cfg->max.pclk) pdiv++; s3c_freq_dbg("%s: pdiv %d\n", __func__, pdiv); if (pdiv > 2) goto invalid; pdiv *= hdiv; /* calculate a valid armclk */ if (armclk < hclk) armclk = hclk; /* if we're running armclk lower than fclk, this really means * that the system should go into dvs mode, which means that * armclk is connected to hclk. */ if (armclk < fclk) { cfg->divs.dvs = 1; armclk = hclk; } else cfg->divs.dvs = 0; cfg->freq.armclk = armclk; /* store the result, and then return */ cfg->divs.h_divisor = hdiv; cfg->divs.p_divisor = pdiv; return 0; invalid: return -EINVAL; } #define CAMDIVN_HCLK_HALF (S3C2440_CAMDIVN_HCLK3_HALF | \ S3C2440_CAMDIVN_HCLK4_HALF) /** * s3c2440_cpufreq_setdivs - set the cpu frequency divider settings * @cfg: The cpu frequency settings. * * Set the divisors from the settings in @cfg, which where generated * during the calculation phase by s3c2440_cpufreq_calcdivs(). */ static void s3c2440_cpufreq_setdivs(struct s3c_cpufreq_config *cfg) { unsigned long clkdiv, camdiv; s3c_freq_dbg("%s: divsiors: h=%d, p=%d\n", __func__, cfg->divs.h_divisor, cfg->divs.p_divisor); clkdiv = __raw_readl(S3C2410_CLKDIVN); camdiv = __raw_readl(S3C2440_CAMDIVN); clkdiv &= ~(S3C2440_CLKDIVN_HDIVN_MASK | S3C2440_CLKDIVN_PDIVN); camdiv &= ~CAMDIVN_HCLK_HALF; switch (cfg->divs.h_divisor) { case 1: clkdiv |= S3C2440_CLKDIVN_HDIVN_1; break; case 2: clkdiv |= S3C2440_CLKDIVN_HDIVN_2; break; case 6: camdiv |= S3C2440_CAMDIVN_HCLK3_HALF; case 3: clkdiv |= S3C2440_CLKDIVN_HDIVN_3_6; break; case 8: camdiv |= S3C2440_CAMDIVN_HCLK4_HALF; case 4: clkdiv |= S3C2440_CLKDIVN_HDIVN_4_8; break; default: BUG(); /* we don't expect to get here. */ } if (cfg->divs.p_divisor != cfg->divs.h_divisor) clkdiv |= S3C2440_CLKDIVN_PDIVN; /* todo - set pclk. */ /* Write the divisors first with hclk intentionally halved so that * when we write clkdiv we will under-frequency instead of over. We * then make a short delay and remove the hclk halving if necessary. */ __raw_writel(camdiv | CAMDIVN_HCLK_HALF, S3C2440_CAMDIVN); __raw_writel(clkdiv, S3C2410_CLKDIVN); ndelay(20); __raw_writel(camdiv, S3C2440_CAMDIVN); clk_set_parent(armclk, cfg->divs.dvs ? hclk : fclk); } static int run_freq_for(unsigned long max_hclk, unsigned long fclk, int *divs, struct cpufreq_frequency_table *table, size_t table_size) { unsigned long freq; int index = 0; int div; for (div = *divs; div > 0; div = *divs++) { freq = fclk / div; if (freq > max_hclk && div != 1) continue; freq /= 1000; /* table is in kHz */ index = s3c_cpufreq_addfreq(table, index, table_size, freq); if (index < 0) break; } return index; } static int hclk_divs[] = { 1, 2, 3, 4, 6, 8, -1 }; static int s3c2440_cpufreq_calctable(struct s3c_cpufreq_config *cfg, struct cpufreq_frequency_table *table, size_t table_size) { int ret; WARN_ON(cfg->info == NULL); WARN_ON(cfg->board == NULL); ret = run_freq_for(cfg->info->max.hclk, cfg->info->max.fclk, hclk_divs, table, table_size); s3c_freq_dbg("%s: returning %d\n", __func__, ret); return ret; } struct s3c_cpufreq_info s3c2440_cpufreq_info = { .max = { .fclk = 400000000, .hclk = 133333333, .pclk = 66666666, }, .locktime_m = 300, .locktime_u = 300, .locktime_bits = 16, .name = "s3c244x", .calc_iotiming = s3c2410_iotiming_calc, .set_iotiming = s3c2410_iotiming_set, .get_iotiming = s3c2410_iotiming_get, .set_fvco = s3c2410_set_fvco, .set_refresh = s3c2410_cpufreq_setrefresh, .set_divs = s3c2440_cpufreq_setdivs, .calc_divs = s3c2440_cpufreq_calcdivs, .calc_freqtable = s3c2440_cpufreq_calctable, .resume_clocks = s3c244x_setup_clocks, .debug_io_show = s3c_cpufreq_debugfs_call(s3c2410_iotiming_debugfs), }; static int s3c2440_cpufreq_add(struct device *dev, struct subsys_interface *sif) { xtal = s3c_cpufreq_clk_get(NULL, "xtal"); hclk = s3c_cpufreq_clk_get(NULL, "hclk"); fclk = s3c_cpufreq_clk_get(NULL, "fclk"); armclk = s3c_cpufreq_clk_get(NULL, "armclk"); if (IS_ERR(xtal) || IS_ERR(hclk) || IS_ERR(fclk) || IS_ERR(armclk)) { printk(KERN_ERR "%s: failed to get clocks\n", __func__); return -ENOENT; } return s3c_cpufreq_register(&s3c2440_cpufreq_info); } static struct subsys_interface s3c2440_cpufreq_interface = { .name = "s3c2440_cpufreq", .subsys = &s3c2440_subsys, .add_dev = s3c2440_cpufreq_add, }; static int s3c2440_cpufreq_init(void) { return subsys_interface_register(&s3c2440_cpufreq_interface); } /* arch_initcall adds the clocks we need, so use subsys_initcall. */ subsys_initcall(s3c2440_cpufreq_init); static struct subsys_interface s3c2442_cpufreq_interface = { .name = "s3c2442_cpufreq", .subsys = &s3c2442_subsys, .add_dev = s3c2440_cpufreq_add, }; static int s3c2442_cpufreq_init(void) { return subsys_interface_register(&s3c2442_cpufreq_interface); } subsys_initcall(s3c2442_cpufreq_init);
gpl-2.0
yuanguo8/nubiaz5s_kernel
drivers/staging/bcm/InterfaceTx.c
8142
6413
#include "headers.h" /*this is transmit call-back(BULK OUT)*/ static void write_bulk_callback(struct urb *urb/*, struct pt_regs *regs*/) { PUSB_TCB pTcb= (PUSB_TCB)urb->context; PS_INTERFACE_ADAPTER psIntfAdapter = pTcb->psIntfAdapter; CONTROL_MESSAGE *pControlMsg = (CONTROL_MESSAGE *)urb->transfer_buffer; PMINI_ADAPTER psAdapter = psIntfAdapter->psAdapter ; BOOLEAN bpowerDownMsg = FALSE ; PMINI_ADAPTER Adapter = GET_BCM_ADAPTER(gblpnetdev); if (unlikely(netif_msg_tx_done(Adapter))) pr_info(PFX "%s: transmit status %d\n", Adapter->dev->name, urb->status); if(urb->status != STATUS_SUCCESS) { if(urb->status == -EPIPE) { psIntfAdapter->psAdapter->bEndPointHalted = TRUE ; wake_up(&psIntfAdapter->psAdapter->tx_packet_wait_queue); } else { BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL,"Tx URB has got cancelled. status :%d", urb->status); } } pTcb->bUsed = FALSE; atomic_dec(&psIntfAdapter->uNumTcbUsed); if(TRUE == psAdapter->bPreparingForLowPowerMode) { if(((pControlMsg->szData[0] == GO_TO_IDLE_MODE_PAYLOAD) && (pControlMsg->szData[1] == TARGET_CAN_GO_TO_IDLE_MODE))) { bpowerDownMsg = TRUE ; //This covers the bus err while Idle Request msg sent down. if(urb->status != STATUS_SUCCESS) { psAdapter->bPreparingForLowPowerMode = FALSE ; BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL,"Idle Mode Request msg failed to reach to Modem"); //Signalling the cntrl pkt path in Ioctl wake_up(&psAdapter->lowpower_mode_wait_queue); StartInterruptUrb(psIntfAdapter); goto err_exit; } if(psAdapter->bDoSuspend == FALSE) { psAdapter->IdleMode = TRUE; //since going in Idle mode completed hence making this var false; psAdapter->bPreparingForLowPowerMode = FALSE ; BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL, "Host Entered in Idle Mode State..."); //Signalling the cntrl pkt path in Ioctl wake_up(&psAdapter->lowpower_mode_wait_queue); } } else if((pControlMsg->Leader.Status == LINK_UP_CONTROL_REQ) && (pControlMsg->szData[0] == LINK_UP_ACK) && (pControlMsg->szData[1] == LINK_SHUTDOWN_REQ_FROM_FIRMWARE) && (pControlMsg->szData[2] == SHUTDOWN_ACK_FROM_DRIVER)) { //This covers the bus err while shutdown Request msg sent down. if(urb->status != STATUS_SUCCESS) { psAdapter->bPreparingForLowPowerMode = FALSE ; BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL,"Shutdown Request Msg failed to reach to Modem"); //Signalling the cntrl pkt path in Ioctl wake_up(&psAdapter->lowpower_mode_wait_queue); StartInterruptUrb(psIntfAdapter); goto err_exit; } bpowerDownMsg = TRUE ; if(psAdapter->bDoSuspend == FALSE) { psAdapter->bShutStatus = TRUE; //since going in shutdown mode completed hence making this var false; psAdapter->bPreparingForLowPowerMode = FALSE ; BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL,"Host Entered in shutdown Mode State..."); //Signalling the cntrl pkt path in Ioctl wake_up(&psAdapter->lowpower_mode_wait_queue); } } if(psAdapter->bDoSuspend && bpowerDownMsg) { //issuing bus suspend request BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL,"Issuing the Bus suspend request to USB stack"); psIntfAdapter->bPreparingForBusSuspend = TRUE; schedule_work(&psIntfAdapter->usbSuspendWork); } } err_exit : usb_free_coherent(urb->dev, urb->transfer_buffer_length, urb->transfer_buffer, urb->transfer_dma); } static PUSB_TCB GetBulkOutTcb(PS_INTERFACE_ADAPTER psIntfAdapter) { PUSB_TCB pTcb = NULL; UINT index = 0; if((atomic_read(&psIntfAdapter->uNumTcbUsed) < MAXIMUM_USB_TCB) && (psIntfAdapter->psAdapter->StopAllXaction ==FALSE)) { index = atomic_read(&psIntfAdapter->uCurrTcb); pTcb = &psIntfAdapter->asUsbTcb[index]; pTcb->bUsed = TRUE; pTcb->psIntfAdapter= psIntfAdapter; BCM_DEBUG_PRINT(psIntfAdapter->psAdapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL, "Got Tx desc %d used %d", index, atomic_read(&psIntfAdapter->uNumTcbUsed)); index = (index + 1) % MAXIMUM_USB_TCB; atomic_set(&psIntfAdapter->uCurrTcb, index); atomic_inc(&psIntfAdapter->uNumTcbUsed); } return pTcb; } static int TransmitTcb(PS_INTERFACE_ADAPTER psIntfAdapter, PUSB_TCB pTcb, PVOID data, int len) { struct urb *urb = pTcb->urb; int retval = 0; urb->transfer_buffer = usb_alloc_coherent(psIntfAdapter->udev, len, GFP_ATOMIC, &urb->transfer_dma); if (!urb->transfer_buffer) { BCM_DEBUG_PRINT(psIntfAdapter->psAdapter,DBG_TYPE_PRINTK, 0, 0, "Error allocating memory\n"); return -ENOMEM; } memcpy(urb->transfer_buffer, data, len); urb->transfer_buffer_length = len; BCM_DEBUG_PRINT(psIntfAdapter->psAdapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL, "Sending Bulk out packet\n"); //For T3B,INT OUT end point will be used as bulk out end point if((psIntfAdapter->psAdapter->chip_id == T3B) && (psIntfAdapter->bHighSpeedDevice == TRUE)) { usb_fill_int_urb(urb, psIntfAdapter->udev, psIntfAdapter->sBulkOut.bulk_out_pipe, urb->transfer_buffer, len, write_bulk_callback, pTcb, psIntfAdapter->sBulkOut.int_out_interval); } else { usb_fill_bulk_urb(urb, psIntfAdapter->udev, psIntfAdapter->sBulkOut.bulk_out_pipe, urb->transfer_buffer, len, write_bulk_callback, pTcb); } urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; /* For DMA transfer */ if(FALSE == psIntfAdapter->psAdapter->device_removed && FALSE == psIntfAdapter->psAdapter->bEndPointHalted && FALSE == psIntfAdapter->bSuspended && FALSE == psIntfAdapter->bPreparingForBusSuspend) { retval = usb_submit_urb(urb, GFP_ATOMIC); if (retval) { BCM_DEBUG_PRINT(psIntfAdapter->psAdapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL, "failed submitting write urb, error %d", retval); if(retval == -EPIPE) { psIntfAdapter->psAdapter->bEndPointHalted = TRUE ; wake_up(&psIntfAdapter->psAdapter->tx_packet_wait_queue); } } } return retval; } int InterfaceTransmitPacket(PVOID arg, PVOID data, UINT len) { PUSB_TCB pTcb= NULL; PS_INTERFACE_ADAPTER psIntfAdapter = (PS_INTERFACE_ADAPTER)arg; pTcb= GetBulkOutTcb(psIntfAdapter); if(pTcb == NULL) { BCM_DEBUG_PRINT(psIntfAdapter->psAdapter,DBG_TYPE_PRINTK, 0, 0, "No URB to transmit packet, dropping packet"); return -EFAULT; } return TransmitTcb(psIntfAdapter, pTcb, data, len); }
gpl-2.0
markbencze/android_kernel_lge_hammerhead
drivers/staging/bcm/Transmit.c
8142
7437
/** @file Transmit.c @defgroup tx_functions Transmission @section Queueing @dot digraph transmit1 { node[shape=box] edge[weight=5;color=red] bcm_transmit->GetPacketQueueIndex[label="IP Packet"] GetPacketQueueIndex->IpVersion4[label="IPV4"] GetPacketQueueIndex->IpVersion6[label="IPV6"] } @enddot @section De-Queueing @dot digraph transmit2 { node[shape=box] edge[weight=5;color=red] interrupt_service_thread->transmit_packets tx_pkt_hdler->transmit_packets transmit_packets->CheckAndSendPacketFromIndex transmit_packets->UpdateTokenCount CheckAndSendPacketFromIndex->PruneQueue CheckAndSendPacketFromIndex->IsPacketAllowedForFlow CheckAndSendPacketFromIndex->SendControlPacket[label="control pkt"] SendControlPacket->bcm_cmd53 CheckAndSendPacketFromIndex->SendPacketFromQueue[label="data pkt"] SendPacketFromQueue->SetupNextSend->bcm_cmd53 } @enddot */ #include "headers.h" /** @ingroup ctrl_pkt_functions This function dispatches control packet to the h/w interface @return zero(success) or -ve value(failure) */ INT SendControlPacket(PMINI_ADAPTER Adapter, char *pControlPacket) { PLEADER PLeader = (PLEADER)pControlPacket; BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_CONTROL, DBG_LVL_ALL, "Tx"); if(!pControlPacket || !Adapter) { BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_CONTROL, DBG_LVL_ALL, "Got NULL Control Packet or Adapter"); return STATUS_FAILURE; } if((atomic_read( &Adapter->CurrNumFreeTxDesc ) < ((PLeader->PLength-1)/MAX_DEVICE_DESC_SIZE)+1)) { BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_CONTROL, DBG_LVL_ALL, "NO FREE DESCRIPTORS TO SEND CONTROL PACKET"); return STATUS_FAILURE; } /* Update the netdevice statistics */ /* Dump Packet */ BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_CONTROL, DBG_LVL_ALL, "Leader Status: %x", PLeader->Status); BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_CONTROL, DBG_LVL_ALL, "Leader VCID: %x",PLeader->Vcid); BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_CONTROL, DBG_LVL_ALL, "Leader Length: %x",PLeader->PLength); if(Adapter->device_removed) return 0; if (netif_msg_pktdata(Adapter)) print_hex_dump(KERN_DEBUG, PFX "tx control: ", DUMP_PREFIX_NONE, 16, 1, pControlPacket, PLeader->PLength + LEADER_SIZE, 0); Adapter->interface_transmit(Adapter->pvInterfaceAdapter, pControlPacket, (PLeader->PLength + LEADER_SIZE)); atomic_dec(&Adapter->CurrNumFreeTxDesc); BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_CONTROL, DBG_LVL_ALL, "<========="); return STATUS_SUCCESS; } /** @ingroup tx_functions This function despatches the IP packets with the given vcid to the target via the host h/w interface. @return zero(success) or -ve value(failure) */ INT SetupNextSend(PMINI_ADAPTER Adapter, struct sk_buff *Packet, USHORT Vcid) { int status=0; BOOLEAN bHeaderSupressionEnabled = FALSE; B_UINT16 uiClassifierRuleID; u16 QueueIndex = skb_get_queue_mapping(Packet); LEADER Leader={0}; if(Packet->len > MAX_DEVICE_DESC_SIZE) { status = STATUS_FAILURE; goto errExit; } /* Get the Classifier Rule ID */ uiClassifierRuleID = *((UINT32*) (Packet->cb)+SKB_CB_CLASSIFICATION_OFFSET); bHeaderSupressionEnabled = Adapter->PackInfo[QueueIndex].bHeaderSuppressionEnabled & Adapter->bPHSEnabled; if(Adapter->device_removed) { status = STATUS_FAILURE; goto errExit; } status = PHSTransmit(Adapter, &Packet, Vcid, uiClassifierRuleID, bHeaderSupressionEnabled, (UINT *)&Packet->len, Adapter->PackInfo[QueueIndex].bEthCSSupport); if(status != STATUS_SUCCESS) { BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL, "PHS Transmit failed..\n"); goto errExit; } Leader.Vcid = Vcid; if(TCP_ACK == *((UINT32*) (Packet->cb) + SKB_CB_TCPACK_OFFSET )) Leader.Status = LEADER_STATUS_TCP_ACK; else Leader.Status = LEADER_STATUS; if(Adapter->PackInfo[QueueIndex].bEthCSSupport) { Leader.PLength = Packet->len; if(skb_headroom(Packet) < LEADER_SIZE) { if((status = skb_cow(Packet,LEADER_SIZE))) { BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, NEXT_SEND, DBG_LVL_ALL,"bcm_transmit : Failed To Increase headRoom\n"); goto errExit; } } skb_push(Packet, LEADER_SIZE); memcpy(Packet->data, &Leader, LEADER_SIZE); } else { Leader.PLength = Packet->len - ETH_HLEN; memcpy((LEADER*)skb_pull(Packet, (ETH_HLEN - LEADER_SIZE)), &Leader, LEADER_SIZE); } status = Adapter->interface_transmit(Adapter->pvInterfaceAdapter, Packet->data, (Leader.PLength + LEADER_SIZE)); if(status) { ++Adapter->dev->stats.tx_errors; if (netif_msg_tx_err(Adapter)) pr_info(PFX "%s: transmit error %d\n", Adapter->dev->name, status); } else { struct net_device_stats *netstats = &Adapter->dev->stats; Adapter->PackInfo[QueueIndex].uiTotalTxBytes += Leader.PLength; netstats->tx_bytes += Leader.PLength; ++netstats->tx_packets; Adapter->PackInfo[QueueIndex].uiCurrentTokenCount -= Leader.PLength << 3; Adapter->PackInfo[QueueIndex].uiSentBytes += (Packet->len); Adapter->PackInfo[QueueIndex].uiSentPackets++; Adapter->PackInfo[QueueIndex].NumOfPacketsSent++; atomic_dec(&Adapter->PackInfo[QueueIndex].uiPerSFTxResourceCount); Adapter->PackInfo[QueueIndex].uiThisPeriodSentBytes += Leader.PLength; } atomic_dec(&Adapter->CurrNumFreeTxDesc); errExit: dev_kfree_skb(Packet); return status; } static int tx_pending(PMINI_ADAPTER Adapter) { return (atomic_read(&Adapter->TxPktAvail) && MINIMUM_PENDING_DESCRIPTORS < atomic_read(&Adapter->CurrNumFreeTxDesc)) || Adapter->device_removed || (1 == Adapter->downloadDDR); } /** @ingroup tx_functions Transmit thread */ int tx_pkt_handler(PMINI_ADAPTER Adapter /**< pointer to adapter object*/ ) { int status = 0; while(! kthread_should_stop()) { /* FIXME - the timeout looks like workaround for racey usage of TxPktAvail */ if(Adapter->LinkUpStatus) wait_event_timeout(Adapter->tx_packet_wait_queue, tx_pending(Adapter), msecs_to_jiffies(10)); else wait_event_interruptible(Adapter->tx_packet_wait_queue, tx_pending(Adapter)); if (Adapter->device_removed) break; if(Adapter->downloadDDR == 1) { Adapter->downloadDDR +=1; status = download_ddr_settings(Adapter); if(status) pr_err(PFX "DDR DOWNLOAD FAILED! %d\n", status); continue; } //Check end point for halt/stall. if(Adapter->bEndPointHalted == TRUE) { Bcm_clear_halt_of_endpoints(Adapter); Adapter->bEndPointHalted = FALSE; StartInterruptUrb((PS_INTERFACE_ADAPTER)(Adapter->pvInterfaceAdapter)); } if(Adapter->LinkUpStatus && !Adapter->IdleMode) { if(atomic_read(&Adapter->TotalPacketCount)) { update_per_sf_desc_cnts(Adapter); } } if( atomic_read(&Adapter->CurrNumFreeTxDesc) && Adapter->LinkStatus == SYNC_UP_REQUEST && !Adapter->bSyncUpRequestSent) { BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "Calling LinkMessage"); LinkMessage(Adapter); } if((Adapter->IdleMode || Adapter->bShutStatus) && atomic_read(&Adapter->TotalPacketCount)) { BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "Device in Low Power mode...waking up"); Adapter->usIdleModePattern = ABORT_IDLE_MODE; Adapter->bWakeUpDevice = TRUE; wake_up(&Adapter->process_rx_cntrlpkt); } transmit_packets(Adapter); atomic_set(&Adapter->TxPktAvail, 0); } BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, TX_PACKETS, DBG_LVL_ALL, "Exiting the tx thread..\n"); Adapter->transmit_packet_thread = NULL; return 0; }
gpl-2.0
intervigilium/android_kernel_google_msm
arch/arm/plat-s3c24xx/s3c2410-iotiming.c
9166
12013
/* linux/arch/arm/plat-s3c24xx/s3c2410-iotiming.c * * Copyright (c) 2006-2009 Simtec Electronics * http://armlinux.simtec.co.uk/ * Ben Dooks <ben@simtec.co.uk> * * S3C24XX CPU Frequency scaling - IO timing for S3C2410/S3C2440/S3C2442 * * 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/kernel.h> #include <linux/errno.h> #include <linux/cpufreq.h> #include <linux/seq_file.h> #include <linux/io.h> #include <linux/slab.h> #include <mach/map.h> #include <mach/regs-mem.h> #include <mach/regs-clock.h> #include <plat/cpu-freq-core.h> #define print_ns(x) ((x) / 10), ((x) % 10) /** * s3c2410_print_timing - print bank timing data for debug purposes * @pfx: The prefix to put on the output * @timings: The timing inforamtion to print. */ static void s3c2410_print_timing(const char *pfx, struct s3c_iotimings *timings) { struct s3c2410_iobank_timing *bt; int bank; for (bank = 0; bank < MAX_BANKS; bank++) { bt = timings->bank[bank].io_2410; if (!bt) continue; printk(KERN_DEBUG "%s %d: Tacs=%d.%d, Tcos=%d.%d, Tacc=%d.%d, " "Tcoh=%d.%d, Tcah=%d.%d\n", pfx, bank, print_ns(bt->tacs), print_ns(bt->tcos), print_ns(bt->tacc), print_ns(bt->tcoh), print_ns(bt->tcah)); } } /** * bank_reg - convert bank number to pointer to the control register. * @bank: The IO bank number. */ static inline void __iomem *bank_reg(unsigned int bank) { return S3C2410_BANKCON0 + (bank << 2); } /** * bank_is_io - test whether bank is used for IO * @bankcon: The bank control register. * * This is a simplistic test to see if any BANKCON[x] is not an IO * bank. It currently does not take into account whether BWSCON has * an illegal width-setting in it, or if the pin connected to nCS[x] * is actually being handled as a chip-select. */ static inline int bank_is_io(unsigned long bankcon) { return !(bankcon & S3C2410_BANKCON_SDRAM); } /** * to_div - convert cycle time to divisor * @cyc: The cycle time, in 10ths of nanoseconds. * @hclk_tns: The cycle time for HCLK, in 10ths of nanoseconds. * * Convert the given cycle time into the divisor to use to obtain it from * HCLK. */ static inline unsigned int to_div(unsigned int cyc, unsigned int hclk_tns) { if (cyc == 0) return 0; return DIV_ROUND_UP(cyc, hclk_tns); } /** * calc_0124 - calculate divisor control for divisors that do /0, /1. /2 and /4 * @cyc: The cycle time, in 10ths of nanoseconds. * @hclk_tns: The cycle time for HCLK, in 10ths of nanoseconds. * @v: Pointer to register to alter. * @shift: The shift to get to the control bits. * * Calculate the divisor, and turn it into the correct control bits to * set in the result, @v. */ static unsigned int calc_0124(unsigned int cyc, unsigned long hclk_tns, unsigned long *v, int shift) { unsigned int div = to_div(cyc, hclk_tns); unsigned long val; s3c_freq_iodbg("%s: cyc=%d, hclk=%lu, shift=%d => div %d\n", __func__, cyc, hclk_tns, shift, div); switch (div) { case 0: val = 0; break; case 1: val = 1; break; case 2: val = 2; break; case 3: case 4: val = 3; break; default: return -1; } *v |= val << shift; return 0; } int calc_tacp(unsigned int cyc, unsigned long hclk, unsigned long *v) { /* Currently no support for Tacp calculations. */ return 0; } /** * calc_tacc - calculate divisor control for tacc. * @cyc: The cycle time, in 10ths of nanoseconds. * @nwait_en: IS nWAIT enabled for this bank. * @hclk_tns: The cycle time for HCLK, in 10ths of nanoseconds. * @v: Pointer to register to alter. * * Calculate the divisor control for tACC, taking into account whether * the bank has nWAIT enabled. The result is used to modify the value * pointed to by @v. */ static int calc_tacc(unsigned int cyc, int nwait_en, unsigned long hclk_tns, unsigned long *v) { unsigned int div = to_div(cyc, hclk_tns); unsigned long val; s3c_freq_iodbg("%s: cyc=%u, nwait=%d, hclk=%lu => div=%u\n", __func__, cyc, nwait_en, hclk_tns, div); /* if nWait enabled on an bank, Tacc must be at-least 4 cycles. */ if (nwait_en && div < 4) div = 4; switch (div) { case 0: val = 0; break; case 1: case 2: case 3: case 4: val = div - 1; break; case 5: case 6: val = 4; break; case 7: case 8: val = 5; break; case 9: case 10: val = 6; break; case 11: case 12: case 13: case 14: val = 7; break; default: return -1; } *v |= val << 8; return 0; } /** * s3c2410_calc_bank - calculate bank timing infromation * @cfg: The configuration we need to calculate for. * @bt: The bank timing information. * * Given the cycle timine for a bank @bt, calculate the new BANKCON * setting for the @cfg timing. This updates the timing information * ready for the cpu frequency change. */ static int s3c2410_calc_bank(struct s3c_cpufreq_config *cfg, struct s3c2410_iobank_timing *bt) { unsigned long hclk = cfg->freq.hclk_tns; unsigned long res; int ret; res = bt->bankcon; res &= (S3C2410_BANKCON_SDRAM | S3C2410_BANKCON_PMC16); /* tacp: 2,3,4,5 */ /* tcah: 0,1,2,4 */ /* tcoh: 0,1,2,4 */ /* tacc: 1,2,3,4,6,7,10,14 (>4 for nwait) */ /* tcos: 0,1,2,4 */ /* tacs: 0,1,2,4 */ ret = calc_0124(bt->tacs, hclk, &res, S3C2410_BANKCON_Tacs_SHIFT); ret |= calc_0124(bt->tcos, hclk, &res, S3C2410_BANKCON_Tcos_SHIFT); ret |= calc_0124(bt->tcah, hclk, &res, S3C2410_BANKCON_Tcah_SHIFT); ret |= calc_0124(bt->tcoh, hclk, &res, S3C2410_BANKCON_Tcoh_SHIFT); if (ret) return -EINVAL; ret |= calc_tacp(bt->tacp, hclk, &res); ret |= calc_tacc(bt->tacc, bt->nwait_en, hclk, &res); if (ret) return -EINVAL; bt->bankcon = res; return 0; } static unsigned int tacc_tab[] = { [0] = 1, [1] = 2, [2] = 3, [3] = 4, [4] = 6, [5] = 9, [6] = 10, [7] = 14, }; /** * get_tacc - turn tACC value into cycle time * @hclk_tns: The cycle time for HCLK, in 10ths of nanoseconds. * @val: The bank timing register value, shifed down. */ static unsigned int get_tacc(unsigned long hclk_tns, unsigned long val) { val &= 7; return hclk_tns * tacc_tab[val]; } /** * get_0124 - turn 0/1/2/4 divider into cycle time * @hclk_tns: The cycle time for HCLK, in 10ths of nanoseconds. * @val: The bank timing register value, shifed down. */ static unsigned int get_0124(unsigned long hclk_tns, unsigned long val) { val &= 3; return hclk_tns * ((val == 3) ? 4 : val); } /** * s3c2410_iotiming_getbank - turn BANKCON into cycle time information * @cfg: The frequency configuration * @bt: The bank timing to fill in (uses cached BANKCON) * * Given the BANKCON setting in @bt and the current frequency settings * in @cfg, update the cycle timing information. */ void s3c2410_iotiming_getbank(struct s3c_cpufreq_config *cfg, struct s3c2410_iobank_timing *bt) { unsigned long bankcon = bt->bankcon; unsigned long hclk = cfg->freq.hclk_tns; bt->tcah = get_0124(hclk, bankcon >> S3C2410_BANKCON_Tcah_SHIFT); bt->tcoh = get_0124(hclk, bankcon >> S3C2410_BANKCON_Tcoh_SHIFT); bt->tcos = get_0124(hclk, bankcon >> S3C2410_BANKCON_Tcos_SHIFT); bt->tacs = get_0124(hclk, bankcon >> S3C2410_BANKCON_Tacs_SHIFT); bt->tacc = get_tacc(hclk, bankcon >> S3C2410_BANKCON_Tacc_SHIFT); } /** * s3c2410_iotiming_debugfs - debugfs show io bank timing information * @seq: The seq_file to write output to using seq_printf(). * @cfg: The current configuration. * @iob: The IO bank information to decode. */ void s3c2410_iotiming_debugfs(struct seq_file *seq, struct s3c_cpufreq_config *cfg, union s3c_iobank *iob) { struct s3c2410_iobank_timing *bt = iob->io_2410; unsigned long bankcon = bt->bankcon; unsigned long hclk = cfg->freq.hclk_tns; unsigned int tacs; unsigned int tcos; unsigned int tacc; unsigned int tcoh; unsigned int tcah; seq_printf(seq, "BANKCON=0x%08lx\n", bankcon); tcah = get_0124(hclk, bankcon >> S3C2410_BANKCON_Tcah_SHIFT); tcoh = get_0124(hclk, bankcon >> S3C2410_BANKCON_Tcoh_SHIFT); tcos = get_0124(hclk, bankcon >> S3C2410_BANKCON_Tcos_SHIFT); tacs = get_0124(hclk, bankcon >> S3C2410_BANKCON_Tacs_SHIFT); tacc = get_tacc(hclk, bankcon >> S3C2410_BANKCON_Tacc_SHIFT); seq_printf(seq, "\tRead: Tacs=%d.%d, Tcos=%d.%d, Tacc=%d.%d, Tcoh=%d.%d, Tcah=%d.%d\n", print_ns(bt->tacs), print_ns(bt->tcos), print_ns(bt->tacc), print_ns(bt->tcoh), print_ns(bt->tcah)); seq_printf(seq, "\t Set: Tacs=%d.%d, Tcos=%d.%d, Tacc=%d.%d, Tcoh=%d.%d, Tcah=%d.%d\n", print_ns(tacs), print_ns(tcos), print_ns(tacc), print_ns(tcoh), print_ns(tcah)); } /** * s3c2410_iotiming_calc - Calculate bank timing for frequency change. * @cfg: The frequency configuration * @iot: The IO timing information to fill out. * * Calculate the new values for the banks in @iot based on the new * frequency information in @cfg. This is then used by s3c2410_iotiming_set() * to update the timing when necessary. */ int s3c2410_iotiming_calc(struct s3c_cpufreq_config *cfg, struct s3c_iotimings *iot) { struct s3c2410_iobank_timing *bt; unsigned long bankcon; int bank; int ret; for (bank = 0; bank < MAX_BANKS; bank++) { bankcon = __raw_readl(bank_reg(bank)); bt = iot->bank[bank].io_2410; if (!bt) continue; bt->bankcon = bankcon; ret = s3c2410_calc_bank(cfg, bt); if (ret) { printk(KERN_ERR "%s: cannot calculate bank %d io\n", __func__, bank); goto err; } s3c_freq_iodbg("%s: bank %d: con=%08lx\n", __func__, bank, bt->bankcon); } return 0; err: return ret; } /** * s3c2410_iotiming_set - set the IO timings from the given setup. * @cfg: The frequency configuration * @iot: The IO timing information to use. * * Set all the currently used IO bank timing information generated * by s3c2410_iotiming_calc() once the core has validated that all * the new values are within permitted bounds. */ void s3c2410_iotiming_set(struct s3c_cpufreq_config *cfg, struct s3c_iotimings *iot) { struct s3c2410_iobank_timing *bt; int bank; /* set the io timings from the specifier */ for (bank = 0; bank < MAX_BANKS; bank++) { bt = iot->bank[bank].io_2410; if (!bt) continue; __raw_writel(bt->bankcon, bank_reg(bank)); } } /** * s3c2410_iotiming_get - Get the timing information from current registers. * @cfg: The frequency configuration * @timings: The IO timing information to fill out. * * Calculate the @timings timing information from the current frequency * information in @cfg, and the new frequency configur * through all the IO banks, reading the state and then updating @iot * as necessary. * * This is used at the moment on initialisation to get the current * configuration so that boards do not have to carry their own setup * if the timings are correct on initialisation. */ int s3c2410_iotiming_get(struct s3c_cpufreq_config *cfg, struct s3c_iotimings *timings) { struct s3c2410_iobank_timing *bt; unsigned long bankcon; unsigned long bwscon; int bank; bwscon = __raw_readl(S3C2410_BWSCON); /* look through all banks to see what is currently set. */ for (bank = 0; bank < MAX_BANKS; bank++) { bankcon = __raw_readl(bank_reg(bank)); if (!bank_is_io(bankcon)) continue; s3c_freq_iodbg("%s: bank %d: con %08lx\n", __func__, bank, bankcon); bt = kzalloc(sizeof(struct s3c2410_iobank_timing), GFP_KERNEL); if (!bt) { printk(KERN_ERR "%s: no memory for bank\n", __func__); return -ENOMEM; } /* find out in nWait is enabled for bank. */ if (bank != 0) { unsigned long tmp = S3C2410_BWSCON_GET(bwscon, bank); if (tmp & S3C2410_BWSCON_WS) bt->nwait_en = 1; } timings->bank[bank].io_2410 = bt; bt->bankcon = bankcon; s3c2410_iotiming_getbank(cfg, bt); } s3c2410_print_timing("get", timings); return 0; }
gpl-2.0
s05427226/linux
drivers/i2c/muxes/i2c-mux-gpio.c
207
7028
/* * I2C multiplexer using GPIO API * * Peter Korsgaard <peter.korsgaard@barco.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/i2c.h> #include <linux/i2c-mux.h> #include <linux/i2c-mux-gpio.h> #include <linux/platform_device.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/gpio.h> #include <linux/of_gpio.h> struct gpiomux { struct i2c_adapter *parent; struct i2c_adapter **adap; /* child busses */ struct i2c_mux_gpio_platform_data data; unsigned gpio_base; }; static void i2c_mux_gpio_set(const struct gpiomux *mux, unsigned val) { int i; for (i = 0; i < mux->data.n_gpios; i++) gpio_set_value_cansleep(mux->gpio_base + mux->data.gpios[i], val & (1 << i)); } static int i2c_mux_gpio_select(struct i2c_adapter *adap, void *data, u32 chan) { struct gpiomux *mux = data; i2c_mux_gpio_set(mux, chan); return 0; } static int i2c_mux_gpio_deselect(struct i2c_adapter *adap, void *data, u32 chan) { struct gpiomux *mux = data; i2c_mux_gpio_set(mux, mux->data.idle); return 0; } static int match_gpio_chip_by_label(struct gpio_chip *chip, void *data) { return !strcmp(chip->label, data); } #ifdef CONFIG_OF static int i2c_mux_gpio_probe_dt(struct gpiomux *mux, struct platform_device *pdev) { struct device_node *np = pdev->dev.of_node; struct device_node *adapter_np, *child; struct i2c_adapter *adapter; unsigned *values, *gpios; int i = 0, ret; if (!np) return -ENODEV; adapter_np = of_parse_phandle(np, "i2c-parent", 0); if (!adapter_np) { dev_err(&pdev->dev, "Cannot parse i2c-parent\n"); return -ENODEV; } adapter = of_find_i2c_adapter_by_node(adapter_np); if (!adapter) { dev_err(&pdev->dev, "Cannot find parent bus\n"); return -EPROBE_DEFER; } mux->data.parent = i2c_adapter_id(adapter); put_device(&adapter->dev); mux->data.n_values = of_get_child_count(np); values = devm_kzalloc(&pdev->dev, sizeof(*mux->data.values) * mux->data.n_values, GFP_KERNEL); if (!values) { dev_err(&pdev->dev, "Cannot allocate values array"); return -ENOMEM; } for_each_child_of_node(np, child) { of_property_read_u32(child, "reg", values + i); i++; } mux->data.values = values; if (of_property_read_u32(np, "idle-state", &mux->data.idle)) mux->data.idle = I2C_MUX_GPIO_NO_IDLE; mux->data.n_gpios = of_gpio_named_count(np, "mux-gpios"); if (mux->data.n_gpios < 0) { dev_err(&pdev->dev, "Missing mux-gpios property in the DT.\n"); return -EINVAL; } gpios = devm_kzalloc(&pdev->dev, sizeof(*mux->data.gpios) * mux->data.n_gpios, GFP_KERNEL); if (!gpios) { dev_err(&pdev->dev, "Cannot allocate gpios array"); return -ENOMEM; } for (i = 0; i < mux->data.n_gpios; i++) { ret = of_get_named_gpio(np, "mux-gpios", i); if (ret < 0) return ret; gpios[i] = ret; } mux->data.gpios = gpios; return 0; } #else static int i2c_mux_gpio_probe_dt(struct gpiomux *mux, struct platform_device *pdev) { return 0; } #endif static int i2c_mux_gpio_probe(struct platform_device *pdev) { struct gpiomux *mux; struct i2c_adapter *parent; int (*deselect) (struct i2c_adapter *, void *, u32); unsigned initial_state, gpio_base; int i, ret; mux = devm_kzalloc(&pdev->dev, sizeof(*mux), GFP_KERNEL); if (!mux) { dev_err(&pdev->dev, "Cannot allocate gpiomux structure"); return -ENOMEM; } platform_set_drvdata(pdev, mux); if (!dev_get_platdata(&pdev->dev)) { ret = i2c_mux_gpio_probe_dt(mux, pdev); if (ret < 0) return ret; } else { memcpy(&mux->data, dev_get_platdata(&pdev->dev), sizeof(mux->data)); } /* * If a GPIO chip name is provided, the GPIO pin numbers provided are * relative to its base GPIO number. Otherwise they are absolute. */ if (mux->data.gpio_chip) { struct gpio_chip *gpio; gpio = gpiochip_find(mux->data.gpio_chip, match_gpio_chip_by_label); if (!gpio) return -EPROBE_DEFER; gpio_base = gpio->base; } else { gpio_base = 0; } parent = i2c_get_adapter(mux->data.parent); if (!parent) { dev_err(&pdev->dev, "Parent adapter (%d) not found\n", mux->data.parent); return -EPROBE_DEFER; } mux->parent = parent; mux->gpio_base = gpio_base; mux->adap = devm_kzalloc(&pdev->dev, sizeof(*mux->adap) * mux->data.n_values, GFP_KERNEL); if (!mux->adap) { dev_err(&pdev->dev, "Cannot allocate i2c_adapter structure"); ret = -ENOMEM; goto alloc_failed; } if (mux->data.idle != I2C_MUX_GPIO_NO_IDLE) { initial_state = mux->data.idle; deselect = i2c_mux_gpio_deselect; } else { initial_state = mux->data.values[0]; deselect = NULL; } for (i = 0; i < mux->data.n_gpios; i++) { ret = gpio_request(gpio_base + mux->data.gpios[i], "i2c-mux-gpio"); if (ret) { dev_err(&pdev->dev, "Failed to request GPIO %d\n", mux->data.gpios[i]); goto err_request_gpio; } ret = gpio_direction_output(gpio_base + mux->data.gpios[i], initial_state & (1 << i)); if (ret) { dev_err(&pdev->dev, "Failed to set direction of GPIO %d to output\n", mux->data.gpios[i]); i++; /* gpio_request above succeeded, so must free */ goto err_request_gpio; } } for (i = 0; i < mux->data.n_values; i++) { u32 nr = mux->data.base_nr ? (mux->data.base_nr + i) : 0; unsigned int class = mux->data.classes ? mux->data.classes[i] : 0; mux->adap[i] = i2c_add_mux_adapter(parent, &pdev->dev, mux, nr, mux->data.values[i], class, i2c_mux_gpio_select, deselect); if (!mux->adap[i]) { ret = -ENODEV; dev_err(&pdev->dev, "Failed to add adapter %d\n", i); goto add_adapter_failed; } } dev_info(&pdev->dev, "%d port mux on %s adapter\n", mux->data.n_values, parent->name); return 0; add_adapter_failed: for (; i > 0; i--) i2c_del_mux_adapter(mux->adap[i - 1]); i = mux->data.n_gpios; err_request_gpio: for (; i > 0; i--) gpio_free(gpio_base + mux->data.gpios[i - 1]); alloc_failed: i2c_put_adapter(parent); return ret; } static int i2c_mux_gpio_remove(struct platform_device *pdev) { struct gpiomux *mux = platform_get_drvdata(pdev); int i; for (i = 0; i < mux->data.n_values; i++) i2c_del_mux_adapter(mux->adap[i]); for (i = 0; i < mux->data.n_gpios; i++) gpio_free(mux->gpio_base + mux->data.gpios[i]); i2c_put_adapter(mux->parent); return 0; } static const struct of_device_id i2c_mux_gpio_of_match[] = { { .compatible = "i2c-mux-gpio", }, {}, }; MODULE_DEVICE_TABLE(of, i2c_mux_gpio_of_match); static struct platform_driver i2c_mux_gpio_driver = { .probe = i2c_mux_gpio_probe, .remove = i2c_mux_gpio_remove, .driver = { .name = "i2c-mux-gpio", .of_match_table = i2c_mux_gpio_of_match, }, }; module_platform_driver(i2c_mux_gpio_driver); MODULE_DESCRIPTION("GPIO-based I2C multiplexer driver"); MODULE_AUTHOR("Peter Korsgaard <peter.korsgaard@barco.com>"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:i2c-mux-gpio");
gpl-2.0
silver-alx/ac100_kernel
drivers/media/video/cx231xx/cx231xx-video.c
463
58823
/* cx231xx-video.c - driver for Conexant Cx23100/101/102 USB video capture devices Copyright (C) 2008 <srinivasa.deevi at conexant dot com> Based on em28xx driver Based on cx23885 driver Based on cx88 driver This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <linux/init.h> #include <linux/list.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/bitmap.h> #include <linux/usb.h> #include <linux/i2c.h> #include <linux/version.h> #include <linux/mm.h> #include <linux/mutex.h> #include <media/v4l2-common.h> #include <media/v4l2-ioctl.h> #include <media/v4l2-chip-ident.h> #include <media/msp3400.h> #include <media/tuner.h> #include "dvb_frontend.h" #include "cx231xx.h" #include "cx231xx-vbi.h" #define CX231XX_VERSION_CODE KERNEL_VERSION(0, 0, 1) #define DRIVER_AUTHOR "Srinivasa Deevi <srinivasa.deevi@conexant.com>" #define DRIVER_DESC "Conexant cx231xx based USB video device driver" #define cx231xx_videodbg(fmt, arg...) do {\ if (video_debug) \ printk(KERN_INFO "%s %s :"fmt, \ dev->name, __func__ , ##arg); } while (0) static unsigned int isoc_debug; module_param(isoc_debug, int, 0644); MODULE_PARM_DESC(isoc_debug, "enable debug messages [isoc transfers]"); #define cx231xx_isocdbg(fmt, arg...) \ do {\ if (isoc_debug) { \ printk(KERN_INFO "%s %s :"fmt, \ dev->name, __func__ , ##arg); \ } \ } while (0) MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); static unsigned int card[] = {[0 ... (CX231XX_MAXBOARDS - 1)] = UNSET }; static unsigned int video_nr[] = {[0 ... (CX231XX_MAXBOARDS - 1)] = UNSET }; static unsigned int vbi_nr[] = {[0 ... (CX231XX_MAXBOARDS - 1)] = UNSET }; static unsigned int radio_nr[] = {[0 ... (CX231XX_MAXBOARDS - 1)] = UNSET }; module_param_array(card, int, NULL, 0444); module_param_array(video_nr, int, NULL, 0444); module_param_array(vbi_nr, int, NULL, 0444); module_param_array(radio_nr, int, NULL, 0444); MODULE_PARM_DESC(card, "card type"); MODULE_PARM_DESC(video_nr, "video device numbers"); MODULE_PARM_DESC(vbi_nr, "vbi device numbers"); MODULE_PARM_DESC(radio_nr, "radio device numbers"); static unsigned int video_debug; module_param(video_debug, int, 0644); MODULE_PARM_DESC(video_debug, "enable debug messages [video]"); /* supported video standards */ static struct cx231xx_fmt format[] = { { .name = "16bpp YUY2, 4:2:2, packed", .fourcc = V4L2_PIX_FMT_YUYV, .depth = 16, .reg = 0, }, }; /* supported controls */ /* Common to all boards */ /* ------------------------------------------------------------------- */ static const struct v4l2_queryctrl no_ctl = { .name = "42", .flags = V4L2_CTRL_FLAG_DISABLED, }; static struct cx231xx_ctrl cx231xx_ctls[] = { /* --- video --- */ { .v = { .id = V4L2_CID_BRIGHTNESS, .name = "Brightness", .minimum = 0x00, .maximum = 0xff, .step = 1, .default_value = 0x7f, .type = V4L2_CTRL_TYPE_INTEGER, }, .off = 128, .reg = LUMA_CTRL, .mask = 0x00ff, .shift = 0, }, { .v = { .id = V4L2_CID_CONTRAST, .name = "Contrast", .minimum = 0, .maximum = 0xff, .step = 1, .default_value = 0x3f, .type = V4L2_CTRL_TYPE_INTEGER, }, .off = 0, .reg = LUMA_CTRL, .mask = 0xff00, .shift = 8, }, { .v = { .id = V4L2_CID_HUE, .name = "Hue", .minimum = 0, .maximum = 0xff, .step = 1, .default_value = 0x7f, .type = V4L2_CTRL_TYPE_INTEGER, }, .off = 128, .reg = CHROMA_CTRL, .mask = 0xff0000, .shift = 16, }, { /* strictly, this only describes only U saturation. * V saturation is handled specially through code. */ .v = { .id = V4L2_CID_SATURATION, .name = "Saturation", .minimum = 0, .maximum = 0xff, .step = 1, .default_value = 0x7f, .type = V4L2_CTRL_TYPE_INTEGER, }, .off = 0, .reg = CHROMA_CTRL, .mask = 0x00ff, .shift = 0, }, { /* --- audio --- */ .v = { .id = V4L2_CID_AUDIO_MUTE, .name = "Mute", .minimum = 0, .maximum = 1, .default_value = 1, .type = V4L2_CTRL_TYPE_BOOLEAN, }, .reg = PATH1_CTL1, .mask = (0x1f << 24), .shift = 24, }, { .v = { .id = V4L2_CID_AUDIO_VOLUME, .name = "Volume", .minimum = 0, .maximum = 0x3f, .step = 1, .default_value = 0x3f, .type = V4L2_CTRL_TYPE_INTEGER, }, .reg = PATH1_VOL_CTL, .mask = 0xff, .shift = 0, } }; static const int CX231XX_CTLS = ARRAY_SIZE(cx231xx_ctls); static const u32 cx231xx_user_ctrls[] = { V4L2_CID_USER_CLASS, V4L2_CID_BRIGHTNESS, V4L2_CID_CONTRAST, V4L2_CID_SATURATION, V4L2_CID_HUE, V4L2_CID_AUDIO_VOLUME, #if 0 V4L2_CID_AUDIO_BALANCE, #endif V4L2_CID_AUDIO_MUTE, 0 }; static const u32 *ctrl_classes[] = { cx231xx_user_ctrls, NULL }; /* ------------------------------------------------------------------ Video buffer and parser functions ------------------------------------------------------------------*/ /* * Announces that a buffer were filled and request the next */ static inline void buffer_filled(struct cx231xx *dev, struct cx231xx_dmaqueue *dma_q, struct cx231xx_buffer *buf) { /* Advice that buffer was filled */ cx231xx_isocdbg("[%p/%d] wakeup\n", buf, buf->vb.i); buf->vb.state = VIDEOBUF_DONE; buf->vb.field_count++; do_gettimeofday(&buf->vb.ts); dev->video_mode.isoc_ctl.buf = NULL; list_del(&buf->vb.queue); wake_up(&buf->vb.done); } static inline void print_err_status(struct cx231xx *dev, int packet, int status) { char *errmsg = "Unknown"; switch (status) { case -ENOENT: errmsg = "unlinked synchronuously"; break; case -ECONNRESET: errmsg = "unlinked asynchronuously"; break; case -ENOSR: errmsg = "Buffer error (overrun)"; break; case -EPIPE: errmsg = "Stalled (device not responding)"; break; case -EOVERFLOW: errmsg = "Babble (bad cable?)"; break; case -EPROTO: errmsg = "Bit-stuff error (bad cable?)"; break; case -EILSEQ: errmsg = "CRC/Timeout (could be anything)"; break; case -ETIME: errmsg = "Device does not respond"; break; } if (packet < 0) { cx231xx_isocdbg("URB status %d [%s].\n", status, errmsg); } else { cx231xx_isocdbg("URB packet %d, status %d [%s].\n", packet, status, errmsg); } } /* * video-buf generic routine to get the next available buffer */ static inline void get_next_buf(struct cx231xx_dmaqueue *dma_q, struct cx231xx_buffer **buf) { struct cx231xx_video_mode *vmode = container_of(dma_q, struct cx231xx_video_mode, vidq); struct cx231xx *dev = container_of(vmode, struct cx231xx, video_mode); char *outp; if (list_empty(&dma_q->active)) { cx231xx_isocdbg("No active queue to serve\n"); dev->video_mode.isoc_ctl.buf = NULL; *buf = NULL; return; } /* Get the next buffer */ *buf = list_entry(dma_q->active.next, struct cx231xx_buffer, vb.queue); /* Cleans up buffer - Usefull for testing for frame/URB loss */ outp = videobuf_to_vmalloc(&(*buf)->vb); memset(outp, 0, (*buf)->vb.size); dev->video_mode.isoc_ctl.buf = *buf; return; } /* * Controls the isoc copy of each urb packet */ static inline int cx231xx_isoc_copy(struct cx231xx *dev, struct urb *urb) { struct cx231xx_buffer *buf; struct cx231xx_dmaqueue *dma_q = urb->context; unsigned char *outp = NULL; int i, rc = 1; unsigned char *p_buffer; u32 bytes_parsed = 0, buffer_size = 0; u8 sav_eav = 0; if (!dev) return 0; if ((dev->state & DEV_DISCONNECTED) || (dev->state & DEV_MISCONFIGURED)) return 0; if (urb->status < 0) { print_err_status(dev, -1, urb->status); if (urb->status == -ENOENT) return 0; } buf = dev->video_mode.isoc_ctl.buf; if (buf != NULL) outp = videobuf_to_vmalloc(&buf->vb); for (i = 0; i < urb->number_of_packets; i++) { int status = urb->iso_frame_desc[i].status; if (status < 0) { print_err_status(dev, i, status); if (urb->iso_frame_desc[i].status != -EPROTO) continue; } if (urb->iso_frame_desc[i].actual_length <= 0) { /* cx231xx_isocdbg("packet %d is empty",i); - spammy */ continue; } if (urb->iso_frame_desc[i].actual_length > dev->video_mode.max_pkt_size) { cx231xx_isocdbg("packet bigger than packet size"); continue; } /* get buffer pointer and length */ p_buffer = urb->transfer_buffer + urb->iso_frame_desc[i].offset; buffer_size = urb->iso_frame_desc[i].actual_length; bytes_parsed = 0; if (dma_q->is_partial_line) { /* Handle the case of a partial line */ sav_eav = dma_q->last_sav; } else { /* Check for a SAV/EAV overlapping the buffer boundary */ sav_eav = cx231xx_find_boundary_SAV_EAV(p_buffer, dma_q->partial_buf, &bytes_parsed); } sav_eav &= 0xF0; /* Get the first line if we have some portion of an SAV/EAV from the last buffer or a partial line */ if (sav_eav) { bytes_parsed += cx231xx_get_video_line(dev, dma_q, sav_eav, /* SAV/EAV */ p_buffer + bytes_parsed, /* p_buffer */ buffer_size - bytes_parsed);/* buf size */ } /* Now parse data that is completely in this buffer */ /* dma_q->is_partial_line = 0; */ while (bytes_parsed < buffer_size) { u32 bytes_used = 0; sav_eav = cx231xx_find_next_SAV_EAV( p_buffer + bytes_parsed, /* p_buffer */ buffer_size - bytes_parsed, /* buf size */ &bytes_used);/* bytes used to get SAV/EAV */ bytes_parsed += bytes_used; sav_eav &= 0xF0; if (sav_eav && (bytes_parsed < buffer_size)) { bytes_parsed += cx231xx_get_video_line(dev, dma_q, sav_eav, /* SAV/EAV */ p_buffer + bytes_parsed,/* p_buffer */ buffer_size - bytes_parsed);/*buf size*/ } } /* Save the last four bytes of the buffer so we can check the buffer boundary condition next time */ memcpy(dma_q->partial_buf, p_buffer + buffer_size - 4, 4); bytes_parsed = 0; } return rc; } u8 cx231xx_find_boundary_SAV_EAV(u8 *p_buffer, u8 *partial_buf, u32 *p_bytes_used) { u32 bytes_used; u8 boundary_bytes[8]; u8 sav_eav = 0; *p_bytes_used = 0; /* Create an array of the last 4 bytes of the last buffer and the first 4 bytes of the current buffer. */ memcpy(boundary_bytes, partial_buf, 4); memcpy(boundary_bytes + 4, p_buffer, 4); /* Check for the SAV/EAV in the boundary buffer */ sav_eav = cx231xx_find_next_SAV_EAV((u8 *)&boundary_bytes, 8, &bytes_used); if (sav_eav) { /* found a boundary SAV/EAV. Updates the bytes used to reflect only those used in the new buffer */ *p_bytes_used = bytes_used - 4; } return sav_eav; } u8 cx231xx_find_next_SAV_EAV(u8 *p_buffer, u32 buffer_size, u32 *p_bytes_used) { u32 i; u8 sav_eav = 0; /* * Don't search if the buffer size is less than 4. It causes a page * fault since buffer_size - 4 evaluates to a large number in that * case. */ if (buffer_size < 4) { *p_bytes_used = buffer_size; return 0; } for (i = 0; i < (buffer_size - 3); i++) { if ((p_buffer[i] == 0xFF) && (p_buffer[i + 1] == 0x00) && (p_buffer[i + 2] == 0x00)) { *p_bytes_used = i + 4; sav_eav = p_buffer[i + 3]; return sav_eav; } } *p_bytes_used = buffer_size; return 0; } u32 cx231xx_get_video_line(struct cx231xx *dev, struct cx231xx_dmaqueue *dma_q, u8 sav_eav, u8 *p_buffer, u32 buffer_size) { u32 bytes_copied = 0; int current_field = -1; switch (sav_eav) { case SAV_ACTIVE_VIDEO_FIELD1: /* looking for skipped line which occurred in PAL 720x480 mode. In this case, there will be no active data contained between the SAV and EAV */ if ((buffer_size > 3) && (p_buffer[0] == 0xFF) && (p_buffer[1] == 0x00) && (p_buffer[2] == 0x00) && ((p_buffer[3] == EAV_ACTIVE_VIDEO_FIELD1) || (p_buffer[3] == EAV_ACTIVE_VIDEO_FIELD2) || (p_buffer[3] == EAV_VBLANK_FIELD1) || (p_buffer[3] == EAV_VBLANK_FIELD2))) return bytes_copied; current_field = 1; break; case SAV_ACTIVE_VIDEO_FIELD2: /* looking for skipped line which occurred in PAL 720x480 mode. In this case, there will be no active data contained between the SAV and EAV */ if ((buffer_size > 3) && (p_buffer[0] == 0xFF) && (p_buffer[1] == 0x00) && (p_buffer[2] == 0x00) && ((p_buffer[3] == EAV_ACTIVE_VIDEO_FIELD1) || (p_buffer[3] == EAV_ACTIVE_VIDEO_FIELD2) || (p_buffer[3] == EAV_VBLANK_FIELD1) || (p_buffer[3] == EAV_VBLANK_FIELD2))) return bytes_copied; current_field = 2; break; } dma_q->last_sav = sav_eav; bytes_copied = cx231xx_copy_video_line(dev, dma_q, p_buffer, buffer_size, current_field); return bytes_copied; } u32 cx231xx_copy_video_line(struct cx231xx *dev, struct cx231xx_dmaqueue *dma_q, u8 *p_line, u32 length, int field_number) { u32 bytes_to_copy; struct cx231xx_buffer *buf; u32 _line_size = dev->width * 2; if (dma_q->current_field != field_number) cx231xx_reset_video_buffer(dev, dma_q); /* get the buffer pointer */ buf = dev->video_mode.isoc_ctl.buf; /* Remember the field number for next time */ dma_q->current_field = field_number; bytes_to_copy = dma_q->bytes_left_in_line; if (bytes_to_copy > length) bytes_to_copy = length; if (dma_q->lines_completed >= dma_q->lines_per_field) { dma_q->bytes_left_in_line -= bytes_to_copy; dma_q->is_partial_line = (dma_q->bytes_left_in_line == 0) ? 0 : 1; return 0; } dma_q->is_partial_line = 1; /* If we don't have a buffer, just return the number of bytes we would have copied if we had a buffer. */ if (!buf) { dma_q->bytes_left_in_line -= bytes_to_copy; dma_q->is_partial_line = (dma_q->bytes_left_in_line == 0) ? 0 : 1; return bytes_to_copy; } /* copy the data to video buffer */ cx231xx_do_copy(dev, dma_q, p_line, bytes_to_copy); dma_q->pos += bytes_to_copy; dma_q->bytes_left_in_line -= bytes_to_copy; if (dma_q->bytes_left_in_line == 0) { dma_q->bytes_left_in_line = _line_size; dma_q->lines_completed++; dma_q->is_partial_line = 0; if (cx231xx_is_buffer_done(dev, dma_q) && buf) { buffer_filled(dev, dma_q, buf); dma_q->pos = 0; buf = NULL; dma_q->lines_completed = 0; } } return bytes_to_copy; } void cx231xx_reset_video_buffer(struct cx231xx *dev, struct cx231xx_dmaqueue *dma_q) { struct cx231xx_buffer *buf; /* handle the switch from field 1 to field 2 */ if (dma_q->current_field == 1) { if (dma_q->lines_completed >= dma_q->lines_per_field) dma_q->field1_done = 1; else dma_q->field1_done = 0; } buf = dev->video_mode.isoc_ctl.buf; if (buf == NULL) { u8 *outp = NULL; /* first try to get the buffer */ get_next_buf(dma_q, &buf); if (buf) outp = videobuf_to_vmalloc(&buf->vb); dma_q->pos = 0; dma_q->field1_done = 0; dma_q->current_field = -1; } /* reset the counters */ dma_q->bytes_left_in_line = dev->width << 1; dma_q->lines_completed = 0; } int cx231xx_do_copy(struct cx231xx *dev, struct cx231xx_dmaqueue *dma_q, u8 *p_buffer, u32 bytes_to_copy) { u8 *p_out_buffer = NULL; u32 current_line_bytes_copied = 0; struct cx231xx_buffer *buf; u32 _line_size = dev->width << 1; void *startwrite; int offset, lencopy; buf = dev->video_mode.isoc_ctl.buf; if (buf == NULL) return -1; p_out_buffer = videobuf_to_vmalloc(&buf->vb); current_line_bytes_copied = _line_size - dma_q->bytes_left_in_line; /* Offset field 2 one line from the top of the buffer */ offset = (dma_q->current_field == 1) ? 0 : _line_size; /* Offset for field 2 */ startwrite = p_out_buffer + offset; /* lines already completed in the current field */ startwrite += (dma_q->lines_completed * _line_size * 2); /* bytes already completed in the current line */ startwrite += current_line_bytes_copied; lencopy = dma_q->bytes_left_in_line > bytes_to_copy ? bytes_to_copy : dma_q->bytes_left_in_line; if ((u8 *)(startwrite + lencopy) > (u8 *)(p_out_buffer + buf->vb.size)) return 0; /* The below copies the UYVY data straight into video buffer */ cx231xx_swab((u16 *) p_buffer, (u16 *) startwrite, (u16) lencopy); return 0; } void cx231xx_swab(u16 *from, u16 *to, u16 len) { u16 i; if (len <= 0) return; for (i = 0; i < len / 2; i++) to[i] = (from[i] << 8) | (from[i] >> 8); } u8 cx231xx_is_buffer_done(struct cx231xx *dev, struct cx231xx_dmaqueue *dma_q) { u8 buffer_complete = 0; /* Dual field stream */ buffer_complete = ((dma_q->current_field == 2) && (dma_q->lines_completed >= dma_q->lines_per_field) && dma_q->field1_done); return buffer_complete; } /* ------------------------------------------------------------------ Videobuf operations ------------------------------------------------------------------*/ static int buffer_setup(struct videobuf_queue *vq, unsigned int *count, unsigned int *size) { struct cx231xx_fh *fh = vq->priv_data; struct cx231xx *dev = fh->dev; struct v4l2_frequency f; *size = (fh->dev->width * fh->dev->height * dev->format->depth + 7)>>3; if (0 == *count) *count = CX231XX_DEF_BUF; if (*count < CX231XX_MIN_BUF) *count = CX231XX_MIN_BUF; /* Ask tuner to go to analog mode */ memset(&f, 0, sizeof(f)); f.frequency = dev->ctl_freq; f.type = fh->radio ? V4L2_TUNER_RADIO : V4L2_TUNER_ANALOG_TV; call_all(dev, tuner, s_frequency, &f); return 0; } /* This is called *without* dev->slock held; please keep it that way */ static void free_buffer(struct videobuf_queue *vq, struct cx231xx_buffer *buf) { struct cx231xx_fh *fh = vq->priv_data; struct cx231xx *dev = fh->dev; unsigned long flags = 0; if (in_interrupt()) BUG(); /* We used to wait for the buffer to finish here, but this didn't work because, as we were keeping the state as VIDEOBUF_QUEUED, videobuf_queue_cancel marked it as finished for us. (Also, it could wedge forever if the hardware was misconfigured.) This should be safe; by the time we get here, the buffer isn't queued anymore. If we ever start marking the buffers as VIDEOBUF_ACTIVE, it won't be, though. */ spin_lock_irqsave(&dev->video_mode.slock, flags); if (dev->video_mode.isoc_ctl.buf == buf) dev->video_mode.isoc_ctl.buf = NULL; spin_unlock_irqrestore(&dev->video_mode.slock, flags); videobuf_vmalloc_free(&buf->vb); buf->vb.state = VIDEOBUF_NEEDS_INIT; } static int buffer_prepare(struct videobuf_queue *vq, struct videobuf_buffer *vb, enum v4l2_field field) { struct cx231xx_fh *fh = vq->priv_data; struct cx231xx_buffer *buf = container_of(vb, struct cx231xx_buffer, vb); struct cx231xx *dev = fh->dev; int rc = 0, urb_init = 0; /* The only currently supported format is 16 bits/pixel */ buf->vb.size = (fh->dev->width * fh->dev->height * dev->format->depth + 7) >> 3; if (0 != buf->vb.baddr && buf->vb.bsize < buf->vb.size) return -EINVAL; buf->vb.width = dev->width; buf->vb.height = dev->height; buf->vb.field = field; if (VIDEOBUF_NEEDS_INIT == buf->vb.state) { rc = videobuf_iolock(vq, &buf->vb, NULL); if (rc < 0) goto fail; } if (!dev->video_mode.isoc_ctl.num_bufs) urb_init = 1; if (urb_init) { rc = cx231xx_init_isoc(dev, CX231XX_NUM_PACKETS, CX231XX_NUM_BUFS, dev->video_mode.max_pkt_size, cx231xx_isoc_copy); if (rc < 0) goto fail; } buf->vb.state = VIDEOBUF_PREPARED; return 0; fail: free_buffer(vq, buf); return rc; } static void buffer_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb) { struct cx231xx_buffer *buf = container_of(vb, struct cx231xx_buffer, vb); struct cx231xx_fh *fh = vq->priv_data; struct cx231xx *dev = fh->dev; struct cx231xx_dmaqueue *vidq = &dev->video_mode.vidq; buf->vb.state = VIDEOBUF_QUEUED; list_add_tail(&buf->vb.queue, &vidq->active); } static void buffer_release(struct videobuf_queue *vq, struct videobuf_buffer *vb) { struct cx231xx_buffer *buf = container_of(vb, struct cx231xx_buffer, vb); struct cx231xx_fh *fh = vq->priv_data; struct cx231xx *dev = (struct cx231xx *)fh->dev; cx231xx_isocdbg("cx231xx: called buffer_release\n"); free_buffer(vq, buf); } static struct videobuf_queue_ops cx231xx_video_qops = { .buf_setup = buffer_setup, .buf_prepare = buffer_prepare, .buf_queue = buffer_queue, .buf_release = buffer_release, }; /********************* v4l2 interface **************************************/ void video_mux(struct cx231xx *dev, int index) { dev->video_input = index; dev->ctl_ainput = INPUT(index)->amux; cx231xx_set_video_input_mux(dev, index); cx25840_call(dev, video, s_routing, INPUT(index)->vmux, 0, 0); cx231xx_set_audio_input(dev, dev->ctl_ainput); cx231xx_info("video_mux : %d\n", index); /* do mode control overrides if required */ cx231xx_do_mode_ctrl_overrides(dev); } /* Usage lock check functions */ static int res_get(struct cx231xx_fh *fh) { struct cx231xx *dev = fh->dev; int rc = 0; /* This instance already has stream_on */ if (fh->stream_on) return rc; if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) { if (dev->stream_on) return -EBUSY; dev->stream_on = 1; } else if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE) { if (dev->vbi_stream_on) return -EBUSY; dev->vbi_stream_on = 1; } else return -EINVAL; fh->stream_on = 1; return rc; } static int res_check(struct cx231xx_fh *fh) { return fh->stream_on; } static void res_free(struct cx231xx_fh *fh) { struct cx231xx *dev = fh->dev; fh->stream_on = 0; if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) dev->stream_on = 0; if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE) dev->vbi_stream_on = 0; } static int check_dev(struct cx231xx *dev) { if (dev->state & DEV_DISCONNECTED) { cx231xx_errdev("v4l2 ioctl: device not present\n"); return -ENODEV; } if (dev->state & DEV_MISCONFIGURED) { cx231xx_errdev("v4l2 ioctl: device is misconfigured; " "close and open it again\n"); return -EIO; } return 0; } static void get_scale(struct cx231xx *dev, unsigned int width, unsigned int height, unsigned int *hscale, unsigned int *vscale) { unsigned int maxw = norm_maxw(dev); unsigned int maxh = norm_maxh(dev); *hscale = (((unsigned long)maxw) << 12) / width - 4096L; if (*hscale >= 0x4000) *hscale = 0x3fff; *vscale = (((unsigned long)maxh) << 12) / height - 4096L; if (*vscale >= 0x4000) *vscale = 0x3fff; } /* ------------------------------------------------------------------ IOCTL vidioc handling ------------------------------------------------------------------*/ static int vidioc_g_fmt_vid_cap(struct file *file, void *priv, struct v4l2_format *f) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; mutex_lock(&dev->lock); f->fmt.pix.width = dev->width; f->fmt.pix.height = dev->height; f->fmt.pix.pixelformat = dev->format->fourcc; f->fmt.pix.bytesperline = (dev->width * dev->format->depth + 7) >> 3; f->fmt.pix.sizeimage = f->fmt.pix.bytesperline * dev->height; f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M; f->fmt.pix.field = V4L2_FIELD_INTERLACED; mutex_unlock(&dev->lock); return 0; } static struct cx231xx_fmt *format_by_fourcc(unsigned int fourcc) { unsigned int i; for (i = 0; i < ARRAY_SIZE(format); i++) if (format[i].fourcc == fourcc) return &format[i]; return NULL; } static int vidioc_try_fmt_vid_cap(struct file *file, void *priv, struct v4l2_format *f) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; unsigned int width = f->fmt.pix.width; unsigned int height = f->fmt.pix.height; unsigned int maxw = norm_maxw(dev); unsigned int maxh = norm_maxh(dev); unsigned int hscale, vscale; struct cx231xx_fmt *fmt; fmt = format_by_fourcc(f->fmt.pix.pixelformat); if (!fmt) { cx231xx_videodbg("Fourcc format (%08x) invalid.\n", f->fmt.pix.pixelformat); return -EINVAL; } /* width must even because of the YUYV format height must be even because of interlacing */ v4l_bound_align_image(&width, 48, maxw, 1, &height, 32, maxh, 1, 0); get_scale(dev, width, height, &hscale, &vscale); width = (((unsigned long)maxw) << 12) / (hscale + 4096L); height = (((unsigned long)maxh) << 12) / (vscale + 4096L); f->fmt.pix.width = width; f->fmt.pix.height = height; f->fmt.pix.pixelformat = fmt->fourcc; f->fmt.pix.bytesperline = (dev->width * fmt->depth + 7) >> 3; f->fmt.pix.sizeimage = f->fmt.pix.bytesperline * height; f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M; f->fmt.pix.field = V4L2_FIELD_INTERLACED; return 0; } static int vidioc_s_fmt_vid_cap(struct file *file, void *priv, struct v4l2_format *f) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; int rc; struct cx231xx_fmt *fmt; rc = check_dev(dev); if (rc < 0) return rc; mutex_lock(&dev->lock); vidioc_try_fmt_vid_cap(file, priv, f); fmt = format_by_fourcc(f->fmt.pix.pixelformat); if (!fmt) { rc = -EINVAL; goto out; } if (videobuf_queue_is_busy(&fh->vb_vidq)) { cx231xx_errdev("%s queue busy\n", __func__); rc = -EBUSY; goto out; } if (dev->stream_on && !fh->stream_on) { cx231xx_errdev("%s device in use by another fh\n", __func__); rc = -EBUSY; goto out; } /* set new image size */ dev->width = f->fmt.pix.width; dev->height = f->fmt.pix.height; dev->format = fmt; get_scale(dev, dev->width, dev->height, &dev->hscale, &dev->vscale); call_all(dev, video, s_fmt, f); /* Set the correct alternate setting for this resolution */ cx231xx_resolution_set(dev); out: mutex_unlock(&dev->lock); return rc; } static int vidioc_g_std(struct file *file, void *priv, v4l2_std_id * id) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; *id = dev->norm; return 0; } static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id *norm) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; struct v4l2_format f; int rc; rc = check_dev(dev); if (rc < 0) return rc; cx231xx_info("vidioc_s_std : 0x%x\n", (unsigned int)*norm); mutex_lock(&dev->lock); dev->norm = *norm; /* Adjusts width/height, if needed */ f.fmt.pix.width = dev->width; f.fmt.pix.height = dev->height; vidioc_try_fmt_vid_cap(file, priv, &f); /* set new image size */ dev->width = f.fmt.pix.width; dev->height = f.fmt.pix.height; get_scale(dev, dev->width, dev->height, &dev->hscale, &dev->vscale); call_all(dev, core, s_std, dev->norm); mutex_unlock(&dev->lock); cx231xx_resolution_set(dev); /* do mode control overrides */ cx231xx_do_mode_ctrl_overrides(dev); return 0; } static const char *iname[] = { [CX231XX_VMUX_COMPOSITE1] = "Composite1", [CX231XX_VMUX_SVIDEO] = "S-Video", [CX231XX_VMUX_TELEVISION] = "Television", [CX231XX_VMUX_CABLE] = "Cable TV", [CX231XX_VMUX_DVB] = "DVB", [CX231XX_VMUX_DEBUG] = "for debug only", }; static int vidioc_enum_input(struct file *file, void *priv, struct v4l2_input *i) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; unsigned int n; n = i->index; if (n >= MAX_CX231XX_INPUT) return -EINVAL; if (0 == INPUT(n)->type) return -EINVAL; i->index = n; i->type = V4L2_INPUT_TYPE_CAMERA; strcpy(i->name, iname[INPUT(n)->type]); if ((CX231XX_VMUX_TELEVISION == INPUT(n)->type) || (CX231XX_VMUX_CABLE == INPUT(n)->type)) i->type = V4L2_INPUT_TYPE_TUNER; i->std = dev->vdev->tvnorms; return 0; } static int vidioc_g_input(struct file *file, void *priv, unsigned int *i) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; *i = dev->video_input; return 0; } static int vidioc_s_input(struct file *file, void *priv, unsigned int i) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; int rc; rc = check_dev(dev); if (rc < 0) return rc; if (i >= MAX_CX231XX_INPUT) return -EINVAL; if (0 == INPUT(i)->type) return -EINVAL; mutex_lock(&dev->lock); video_mux(dev, i); mutex_unlock(&dev->lock); return 0; } static int vidioc_g_audio(struct file *file, void *priv, struct v4l2_audio *a) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; switch (a->index) { case CX231XX_AMUX_VIDEO: strcpy(a->name, "Television"); break; case CX231XX_AMUX_LINE_IN: strcpy(a->name, "Line In"); break; default: return -EINVAL; } a->index = dev->ctl_ainput; a->capability = V4L2_AUDCAP_STEREO; return 0; } static int vidioc_s_audio(struct file *file, void *priv, struct v4l2_audio *a) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; int status = 0; /* Doesn't allow manual routing */ if (a->index != dev->ctl_ainput) return -EINVAL; dev->ctl_ainput = INPUT(a->index)->amux; status = cx231xx_set_audio_input(dev, dev->ctl_ainput); return status; } static int vidioc_queryctrl(struct file *file, void *priv, struct v4l2_queryctrl *qc) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; int id = qc->id; int i; int rc; rc = check_dev(dev); if (rc < 0) return rc; qc->id = v4l2_ctrl_next(ctrl_classes, qc->id); if (unlikely(qc->id == 0)) return -EINVAL; memset(qc, 0, sizeof(*qc)); qc->id = id; if (qc->id < V4L2_CID_BASE || qc->id >= V4L2_CID_LASTP1) return -EINVAL; for (i = 0; i < CX231XX_CTLS; i++) if (cx231xx_ctls[i].v.id == qc->id) break; if (i == CX231XX_CTLS) { *qc = no_ctl; return 0; } *qc = cx231xx_ctls[i].v; mutex_lock(&dev->lock); call_all(dev, core, queryctrl, qc); mutex_unlock(&dev->lock); if (qc->type) return 0; else return -EINVAL; } static int vidioc_g_ctrl(struct file *file, void *priv, struct v4l2_control *ctrl) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; int rc; rc = check_dev(dev); if (rc < 0) return rc; mutex_lock(&dev->lock); call_all(dev, core, g_ctrl, ctrl); mutex_unlock(&dev->lock); return rc; } static int vidioc_s_ctrl(struct file *file, void *priv, struct v4l2_control *ctrl) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; int rc; rc = check_dev(dev); if (rc < 0) return rc; mutex_lock(&dev->lock); call_all(dev, core, s_ctrl, ctrl); mutex_unlock(&dev->lock); return rc; } static int vidioc_g_tuner(struct file *file, void *priv, struct v4l2_tuner *t) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; int rc; rc = check_dev(dev); if (rc < 0) return rc; if (0 != t->index) return -EINVAL; strcpy(t->name, "Tuner"); t->type = V4L2_TUNER_ANALOG_TV; t->capability = V4L2_TUNER_CAP_NORM; t->rangehigh = 0xffffffffUL; t->signal = 0xffff; /* LOCKED */ return 0; } static int vidioc_s_tuner(struct file *file, void *priv, struct v4l2_tuner *t) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; int rc; rc = check_dev(dev); if (rc < 0) return rc; if (0 != t->index) return -EINVAL; #if 0 mutex_lock(&dev->lock); call_all(dev, tuner, s_tuner, t); mutex_unlock(&dev->lock); #endif return 0; } static int vidioc_g_frequency(struct file *file, void *priv, struct v4l2_frequency *f) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; mutex_lock(&dev->lock); f->type = fh->radio ? V4L2_TUNER_RADIO : V4L2_TUNER_ANALOG_TV; f->frequency = dev->ctl_freq; call_all(dev, tuner, g_frequency, f); mutex_unlock(&dev->lock); return 0; } static int vidioc_s_frequency(struct file *file, void *priv, struct v4l2_frequency *f) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; int rc; rc = check_dev(dev); if (rc < 0) return rc; if (0 != f->tuner) return -EINVAL; if (unlikely(0 == fh->radio && f->type != V4L2_TUNER_ANALOG_TV)) return -EINVAL; if (unlikely(1 == fh->radio && f->type != V4L2_TUNER_RADIO)) return -EINVAL; /* set pre channel change settings in DIF first */ rc = cx231xx_tuner_pre_channel_change(dev); mutex_lock(&dev->lock); dev->ctl_freq = f->frequency; if (dev->tuner_type == TUNER_XC5000) { if (dev->cx231xx_set_analog_freq != NULL) dev->cx231xx_set_analog_freq(dev, f->frequency); } else call_all(dev, tuner, s_frequency, f); mutex_unlock(&dev->lock); /* set post channel change settings in DIF first */ rc = cx231xx_tuner_post_channel_change(dev); cx231xx_info("Set New FREQUENCY to %d\n", f->frequency); return rc; } #ifdef CONFIG_VIDEO_ADV_DEBUG /* -R, --list-registers=type=<host/i2cdrv/i2caddr>, chip=<chip>[,min=<addr>,max=<addr>] dump registers from <min> to <max> [VIDIOC_DBG_G_REGISTER] -r, --set-register=type=<host/i2cdrv/i2caddr>, chip=<chip>,reg=<addr>,val=<val> set the register [VIDIOC_DBG_S_REGISTER] if type == host, then <chip> is the hosts chip ID (default 0) if type == i2cdrv (default), then <chip> is the I2C driver name or ID if type == i2caddr, then <chip> is the 7-bit I2C address */ static int vidioc_g_register(struct file *file, void *priv, struct v4l2_dbg_register *reg) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; int ret = 0; u8 value[4] = { 0, 0, 0, 0 }; u32 data = 0; switch (reg->match.type) { case V4L2_CHIP_MATCH_HOST: switch (reg->match.addr) { case 0: /* Cx231xx - internal registers */ ret = cx231xx_read_ctrl_reg(dev, VRT_GET_REGISTER, (u16)reg->reg, value, 4); reg->val = value[0] | value[1] << 8 | value[2] << 16 | value[3] << 24; break; case 1: /* AFE - read byte */ ret = cx231xx_read_i2c_data(dev, AFE_DEVICE_ADDRESS, (u16)reg->reg, 2, &data, 1); reg->val = le32_to_cpu(data & 0xff); break; case 14: /* AFE - read dword */ ret = cx231xx_read_i2c_data(dev, AFE_DEVICE_ADDRESS, (u16)reg->reg, 2, &data, 4); reg->val = le32_to_cpu(data); break; case 2: /* Video Block - read byte */ ret = cx231xx_read_i2c_data(dev, VID_BLK_I2C_ADDRESS, (u16)reg->reg, 2, &data, 1); reg->val = le32_to_cpu(data & 0xff); break; case 24: /* Video Block - read dword */ ret = cx231xx_read_i2c_data(dev, VID_BLK_I2C_ADDRESS, (u16)reg->reg, 2, &data, 4); reg->val = le32_to_cpu(data); break; case 3: /* I2S block - read byte */ ret = cx231xx_read_i2c_data(dev, I2S_BLK_DEVICE_ADDRESS, (u16)reg->reg, 1, &data, 1); reg->val = le32_to_cpu(data & 0xff); break; case 34: /* I2S Block - read dword */ ret = cx231xx_read_i2c_data(dev, I2S_BLK_DEVICE_ADDRESS, (u16)reg->reg, 1, &data, 4); reg->val = le32_to_cpu(data); break; } return ret < 0 ? ret : 0; case V4L2_CHIP_MATCH_I2C_DRIVER: call_all(dev, core, g_register, reg); return 0; case V4L2_CHIP_MATCH_I2C_ADDR: /* Not supported yet */ return -EINVAL; default: if (!v4l2_chip_match_host(&reg->match)) return -EINVAL; } mutex_lock(&dev->lock); call_all(dev, core, g_register, reg); mutex_unlock(&dev->lock); return ret; } static int vidioc_s_register(struct file *file, void *priv, struct v4l2_dbg_register *reg) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; int ret = 0; __le64 buf; u32 value; u8 data[4] = { 0, 0, 0, 0 }; buf = cpu_to_le64(reg->val); switch (reg->match.type) { case V4L2_CHIP_MATCH_HOST: { value = (u32) buf & 0xffffffff; switch (reg->match.addr) { case 0: /* cx231xx internal registers */ data[0] = (u8) value; data[1] = (u8) (value >> 8); data[2] = (u8) (value >> 16); data[3] = (u8) (value >> 24); ret = cx231xx_write_ctrl_reg(dev, VRT_SET_REGISTER, (u16)reg->reg, data, 4); break; case 1: /* AFE - read byte */ ret = cx231xx_write_i2c_data(dev, AFE_DEVICE_ADDRESS, (u16)reg->reg, 2, value, 1); break; case 14: /* AFE - read dword */ ret = cx231xx_write_i2c_data(dev, AFE_DEVICE_ADDRESS, (u16)reg->reg, 2, value, 4); break; case 2: /* Video Block - read byte */ ret = cx231xx_write_i2c_data(dev, VID_BLK_I2C_ADDRESS, (u16)reg->reg, 2, value, 1); break; case 24: /* Video Block - read dword */ ret = cx231xx_write_i2c_data(dev, VID_BLK_I2C_ADDRESS, (u16)reg->reg, 2, value, 4); break; case 3: /* I2S block - read byte */ ret = cx231xx_write_i2c_data(dev, I2S_BLK_DEVICE_ADDRESS, (u16)reg->reg, 1, value, 1); break; case 34: /* I2S block - read dword */ ret = cx231xx_write_i2c_data(dev, I2S_BLK_DEVICE_ADDRESS, (u16)reg->reg, 1, value, 4); break; } } return ret < 0 ? ret : 0; default: break; } mutex_lock(&dev->lock); call_all(dev, core, s_register, reg); mutex_unlock(&dev->lock); return ret; } #endif static int vidioc_cropcap(struct file *file, void *priv, struct v4l2_cropcap *cc) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; if (cc->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) return -EINVAL; cc->bounds.left = 0; cc->bounds.top = 0; cc->bounds.width = dev->width; cc->bounds.height = dev->height; cc->defrect = cc->bounds; cc->pixelaspect.numerator = 54; /* 4:3 FIXME: remove magic numbers */ cc->pixelaspect.denominator = 59; return 0; } static int vidioc_streamon(struct file *file, void *priv, enum v4l2_buf_type type) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; int rc; rc = check_dev(dev); if (rc < 0) return rc; mutex_lock(&dev->lock); rc = res_get(fh); if (likely(rc >= 0)) rc = videobuf_streamon(&fh->vb_vidq); call_all(dev, video, s_stream, 1); mutex_unlock(&dev->lock); return rc; } static int vidioc_streamoff(struct file *file, void *priv, enum v4l2_buf_type type) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; int rc; rc = check_dev(dev); if (rc < 0) return rc; if ((fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) && (fh->type != V4L2_BUF_TYPE_VBI_CAPTURE)) return -EINVAL; if (type != fh->type) return -EINVAL; mutex_lock(&dev->lock); cx25840_call(dev, video, s_stream, 0); videobuf_streamoff(&fh->vb_vidq); res_free(fh); mutex_unlock(&dev->lock); return 0; } static int vidioc_querycap(struct file *file, void *priv, struct v4l2_capability *cap) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; strlcpy(cap->driver, "cx231xx", sizeof(cap->driver)); strlcpy(cap->card, cx231xx_boards[dev->model].name, sizeof(cap->card)); usb_make_path(dev->udev, cap->bus_info, sizeof(cap->bus_info)); cap->version = CX231XX_VERSION_CODE; cap->capabilities = V4L2_CAP_VBI_CAPTURE | #if 0 V4L2_CAP_SLICED_VBI_CAPTURE | #endif V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_AUDIO | V4L2_CAP_READWRITE | V4L2_CAP_STREAMING; if (dev->tuner_type != TUNER_ABSENT) cap->capabilities |= V4L2_CAP_TUNER; return 0; } static int vidioc_enum_fmt_vid_cap(struct file *file, void *priv, struct v4l2_fmtdesc *f) { if (unlikely(f->index >= ARRAY_SIZE(format))) return -EINVAL; strlcpy(f->description, format[f->index].name, sizeof(f->description)); f->pixelformat = format[f->index].fourcc; return 0; } /* Sliced VBI ioctls */ static int vidioc_g_fmt_sliced_vbi_cap(struct file *file, void *priv, struct v4l2_format *f) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; int rc; rc = check_dev(dev); if (rc < 0) return rc; mutex_lock(&dev->lock); f->fmt.sliced.service_set = 0; call_all(dev, video, g_fmt, f); if (f->fmt.sliced.service_set == 0) rc = -EINVAL; mutex_unlock(&dev->lock); return rc; } static int vidioc_try_set_sliced_vbi_cap(struct file *file, void *priv, struct v4l2_format *f) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; int rc; rc = check_dev(dev); if (rc < 0) return rc; mutex_lock(&dev->lock); call_all(dev, video, g_fmt, f); mutex_unlock(&dev->lock); if (f->fmt.sliced.service_set == 0) return -EINVAL; return 0; } /* RAW VBI ioctls */ static int vidioc_g_fmt_vbi_cap(struct file *file, void *priv, struct v4l2_format *f) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; f->fmt.vbi.sampling_rate = (dev->norm & V4L2_STD_625_50) ? 35468950 : 28636363; f->fmt.vbi.samples_per_line = VBI_LINE_LENGTH; f->fmt.vbi.sample_format = V4L2_PIX_FMT_GREY; f->fmt.vbi.offset = 64 * 4; f->fmt.vbi.start[0] = (dev->norm & V4L2_STD_625_50) ? PAL_VBI_START_LINE : NTSC_VBI_START_LINE; f->fmt.vbi.count[0] = (dev->norm & V4L2_STD_625_50) ? PAL_VBI_LINES : NTSC_VBI_LINES; f->fmt.vbi.start[1] = (dev->norm & V4L2_STD_625_50) ? PAL_VBI_START_LINE + 312 : NTSC_VBI_START_LINE + 263; f->fmt.vbi.count[1] = f->fmt.vbi.count[0]; return 0; } static int vidioc_try_fmt_vbi_cap(struct file *file, void *priv, struct v4l2_format *f) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; if (dev->vbi_stream_on && !fh->stream_on) { cx231xx_errdev("%s device in use by another fh\n", __func__); return -EBUSY; } f->type = V4L2_BUF_TYPE_VBI_CAPTURE; f->fmt.vbi.sampling_rate = (dev->norm & V4L2_STD_625_50) ? 35468950 : 28636363; f->fmt.vbi.samples_per_line = VBI_LINE_LENGTH; f->fmt.vbi.sample_format = V4L2_PIX_FMT_GREY; f->fmt.vbi.offset = 244; f->fmt.vbi.flags = 0; f->fmt.vbi.start[0] = (dev->norm & V4L2_STD_625_50) ? PAL_VBI_START_LINE : NTSC_VBI_START_LINE; f->fmt.vbi.count[0] = (dev->norm & V4L2_STD_625_50) ? PAL_VBI_LINES : NTSC_VBI_LINES; f->fmt.vbi.start[1] = (dev->norm & V4L2_STD_625_50) ? PAL_VBI_START_LINE + 312 : NTSC_VBI_START_LINE + 263; f->fmt.vbi.count[1] = f->fmt.vbi.count[0]; return 0; } static int vidioc_reqbufs(struct file *file, void *priv, struct v4l2_requestbuffers *rb) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; int rc; rc = check_dev(dev); if (rc < 0) return rc; return videobuf_reqbufs(&fh->vb_vidq, rb); } static int vidioc_querybuf(struct file *file, void *priv, struct v4l2_buffer *b) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; int rc; rc = check_dev(dev); if (rc < 0) return rc; return videobuf_querybuf(&fh->vb_vidq, b); } static int vidioc_qbuf(struct file *file, void *priv, struct v4l2_buffer *b) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; int rc; rc = check_dev(dev); if (rc < 0) return rc; return videobuf_qbuf(&fh->vb_vidq, b); } static int vidioc_dqbuf(struct file *file, void *priv, struct v4l2_buffer *b) { struct cx231xx_fh *fh = priv; struct cx231xx *dev = fh->dev; int rc; rc = check_dev(dev); if (rc < 0) return rc; return videobuf_dqbuf(&fh->vb_vidq, b, file->f_flags & O_NONBLOCK); } #ifdef CONFIG_VIDEO_V4L1_COMPAT static int vidiocgmbuf(struct file *file, void *priv, struct video_mbuf *mbuf) { struct cx231xx_fh *fh = priv; return videobuf_cgmbuf(&fh->vb_vidq, mbuf, 8); } #endif /* ----------------------------------------------------------- */ /* RADIO ESPECIFIC IOCTLS */ /* ----------------------------------------------------------- */ static int radio_querycap(struct file *file, void *priv, struct v4l2_capability *cap) { struct cx231xx *dev = ((struct cx231xx_fh *)priv)->dev; strlcpy(cap->driver, "cx231xx", sizeof(cap->driver)); strlcpy(cap->card, cx231xx_boards[dev->model].name, sizeof(cap->card)); usb_make_path(dev->udev, cap->bus_info, sizeof(cap->bus_info)); cap->version = CX231XX_VERSION_CODE; cap->capabilities = V4L2_CAP_TUNER; return 0; } static int radio_g_tuner(struct file *file, void *priv, struct v4l2_tuner *t) { struct cx231xx *dev = ((struct cx231xx_fh *)priv)->dev; if (unlikely(t->index > 0)) return -EINVAL; strcpy(t->name, "Radio"); t->type = V4L2_TUNER_RADIO; mutex_lock(&dev->lock); call_all(dev, tuner, s_tuner, t); mutex_unlock(&dev->lock); return 0; } static int radio_enum_input(struct file *file, void *priv, struct v4l2_input *i) { if (i->index != 0) return -EINVAL; strcpy(i->name, "Radio"); i->type = V4L2_INPUT_TYPE_TUNER; return 0; } static int radio_g_audio(struct file *file, void *priv, struct v4l2_audio *a) { if (unlikely(a->index)) return -EINVAL; strcpy(a->name, "Radio"); return 0; } static int radio_s_tuner(struct file *file, void *priv, struct v4l2_tuner *t) { struct cx231xx *dev = ((struct cx231xx_fh *)priv)->dev; if (0 != t->index) return -EINVAL; mutex_lock(&dev->lock); call_all(dev, tuner, s_tuner, t); mutex_unlock(&dev->lock); return 0; } static int radio_s_audio(struct file *file, void *fh, struct v4l2_audio *a) { return 0; } static int radio_s_input(struct file *file, void *fh, unsigned int i) { return 0; } static int radio_queryctrl(struct file *file, void *priv, struct v4l2_queryctrl *c) { int i; if (c->id < V4L2_CID_BASE || c->id >= V4L2_CID_LASTP1) return -EINVAL; if (c->id == V4L2_CID_AUDIO_MUTE) { for (i = 0; i < CX231XX_CTLS; i++) if (cx231xx_ctls[i].v.id == c->id) break; *c = cx231xx_ctls[i].v; } else *c = no_ctl; return 0; } /* * cx231xx_v4l2_open() * inits the device and starts isoc transfer */ static int cx231xx_v4l2_open(struct file *filp) { int minor = video_devdata(filp)->minor; int errCode = 0, radio = 0; struct cx231xx *dev = NULL; struct cx231xx_fh *fh; enum v4l2_buf_type fh_type = 0; dev = cx231xx_get_device(minor, &fh_type, &radio); if (NULL == dev) return -ENODEV; mutex_lock(&dev->lock); cx231xx_videodbg("open minor=%d type=%s users=%d\n", minor, v4l2_type_names[fh_type], dev->users); #if 0 errCode = cx231xx_set_mode(dev, CX231XX_ANALOG_MODE); if (errCode < 0) { cx231xx_errdev ("Device locked on digital mode. Can't open analog\n"); mutex_unlock(&dev->lock); return -EBUSY; } #endif fh = kzalloc(sizeof(struct cx231xx_fh), GFP_KERNEL); if (!fh) { cx231xx_errdev("cx231xx-video.c: Out of memory?!\n"); mutex_unlock(&dev->lock); return -ENOMEM; } fh->dev = dev; fh->radio = radio; fh->type = fh_type; filp->private_data = fh; if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE && dev->users == 0) { dev->width = norm_maxw(dev); dev->height = norm_maxh(dev); dev->hscale = 0; dev->vscale = 0; /* Power up in Analog TV mode */ cx231xx_set_power_mode(dev, POLARIS_AVMODE_ANALOGT_TV); #if 0 cx231xx_set_mode(dev, CX231XX_ANALOG_MODE); #endif cx231xx_resolution_set(dev); /* set video alternate setting */ cx231xx_set_video_alternate(dev); /* Needed, since GPIO might have disabled power of some i2c device */ cx231xx_config_i2c(dev); /* device needs to be initialized before isoc transfer */ dev->video_input = dev->video_input > 2 ? 2 : dev->video_input; video_mux(dev, dev->video_input); } if (fh->radio) { cx231xx_videodbg("video_open: setting radio device\n"); /* cx231xx_start_radio(dev); */ call_all(dev, tuner, s_radio); } dev->users++; if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) videobuf_queue_vmalloc_init(&fh->vb_vidq, &cx231xx_video_qops, NULL, &dev->video_mode.slock, fh->type, V4L2_FIELD_INTERLACED, sizeof(struct cx231xx_buffer), fh); if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE) { /* Set the required alternate setting VBI interface works in Bulk mode only */ cx231xx_set_alt_setting(dev, INDEX_VANC, 0); videobuf_queue_vmalloc_init(&fh->vb_vidq, &cx231xx_vbi_qops, NULL, &dev->vbi_mode.slock, fh->type, V4L2_FIELD_SEQ_TB, sizeof(struct cx231xx_buffer), fh); } mutex_unlock(&dev->lock); return errCode; } /* * cx231xx_realease_resources() * unregisters the v4l2,i2c and usb devices * called when the device gets disconected or at module unload */ void cx231xx_release_analog_resources(struct cx231xx *dev) { /*FIXME: I2C IR should be disconnected */ if (dev->radio_dev) { if (-1 != dev->radio_dev->minor) video_unregister_device(dev->radio_dev); else video_device_release(dev->radio_dev); dev->radio_dev = NULL; } if (dev->vbi_dev) { cx231xx_info("V4L2 device /dev/vbi%d deregistered\n", dev->vbi_dev->num); if (-1 != dev->vbi_dev->minor) video_unregister_device(dev->vbi_dev); else video_device_release(dev->vbi_dev); dev->vbi_dev = NULL; } if (dev->vdev) { cx231xx_info("V4L2 device /dev/video%d deregistered\n", dev->vdev->num); if (-1 != dev->vdev->minor) video_unregister_device(dev->vdev); else video_device_release(dev->vdev); dev->vdev = NULL; } } /* * cx231xx_v4l2_close() * stops streaming and deallocates all resources allocated by the v4l2 * calls and ioctls */ static int cx231xx_v4l2_close(struct file *filp) { struct cx231xx_fh *fh = filp->private_data; struct cx231xx *dev = fh->dev; cx231xx_videodbg("users=%d\n", dev->users); mutex_lock(&dev->lock); if (res_check(fh)) res_free(fh); if (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE) { videobuf_stop(&fh->vb_vidq); videobuf_mmap_free(&fh->vb_vidq); /* the device is already disconnect, free the remaining resources */ if (dev->state & DEV_DISCONNECTED) { cx231xx_release_resources(dev); mutex_unlock(&dev->lock); kfree(dev); return 0; } /* do this before setting alternate! */ cx231xx_uninit_vbi_isoc(dev); /* set alternate 0 */ if (!dev->vbi_or_sliced_cc_mode) cx231xx_set_alt_setting(dev, INDEX_VANC, 0); else cx231xx_set_alt_setting(dev, INDEX_HANC, 0); kfree(fh); dev->users--; wake_up_interruptible_nr(&dev->open, 1); mutex_unlock(&dev->lock); return 0; } if (dev->users == 1) { videobuf_stop(&fh->vb_vidq); videobuf_mmap_free(&fh->vb_vidq); /* the device is already disconnect, free the remaining resources */ if (dev->state & DEV_DISCONNECTED) { cx231xx_release_resources(dev); mutex_unlock(&dev->lock); kfree(dev); return 0; } /* Save some power by putting tuner to sleep */ call_all(dev, tuner, s_standby); /* do this before setting alternate! */ cx231xx_uninit_isoc(dev); cx231xx_set_mode(dev, CX231XX_SUSPEND); /* set alternate 0 */ cx231xx_set_alt_setting(dev, INDEX_VIDEO, 0); } kfree(fh); dev->users--; wake_up_interruptible_nr(&dev->open, 1); mutex_unlock(&dev->lock); return 0; } /* * cx231xx_v4l2_read() * will allocate buffers when called for the first time */ static ssize_t cx231xx_v4l2_read(struct file *filp, char __user *buf, size_t count, loff_t *pos) { struct cx231xx_fh *fh = filp->private_data; struct cx231xx *dev = fh->dev; int rc; rc = check_dev(dev); if (rc < 0) return rc; if ((fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) || (fh->type == V4L2_BUF_TYPE_VBI_CAPTURE)) { mutex_lock(&dev->lock); rc = res_get(fh); mutex_unlock(&dev->lock); if (unlikely(rc < 0)) return rc; return videobuf_read_stream(&fh->vb_vidq, buf, count, pos, 0, filp->f_flags & O_NONBLOCK); } return 0; } /* * cx231xx_v4l2_poll() * will allocate buffers when called for the first time */ static unsigned int cx231xx_v4l2_poll(struct file *filp, poll_table * wait) { struct cx231xx_fh *fh = filp->private_data; struct cx231xx *dev = fh->dev; int rc; rc = check_dev(dev); if (rc < 0) return rc; mutex_lock(&dev->lock); rc = res_get(fh); mutex_unlock(&dev->lock); if (unlikely(rc < 0)) return POLLERR; if ((V4L2_BUF_TYPE_VIDEO_CAPTURE == fh->type) || (V4L2_BUF_TYPE_VBI_CAPTURE == fh->type)) return videobuf_poll_stream(filp, &fh->vb_vidq, wait); else return POLLERR; } /* * cx231xx_v4l2_mmap() */ static int cx231xx_v4l2_mmap(struct file *filp, struct vm_area_struct *vma) { struct cx231xx_fh *fh = filp->private_data; struct cx231xx *dev = fh->dev; int rc; rc = check_dev(dev); if (rc < 0) return rc; mutex_lock(&dev->lock); rc = res_get(fh); mutex_unlock(&dev->lock); if (unlikely(rc < 0)) return rc; rc = videobuf_mmap_mapper(&fh->vb_vidq, vma); cx231xx_videodbg("vma start=0x%08lx, size=%ld, ret=%d\n", (unsigned long)vma->vm_start, (unsigned long)vma->vm_end - (unsigned long)vma->vm_start, rc); return rc; } static const struct v4l2_file_operations cx231xx_v4l_fops = { .owner = THIS_MODULE, .open = cx231xx_v4l2_open, .release = cx231xx_v4l2_close, .read = cx231xx_v4l2_read, .poll = cx231xx_v4l2_poll, .mmap = cx231xx_v4l2_mmap, .ioctl = video_ioctl2, }; static const struct v4l2_ioctl_ops video_ioctl_ops = { .vidioc_querycap = vidioc_querycap, .vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap, .vidioc_g_fmt_vid_cap = vidioc_g_fmt_vid_cap, .vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap, .vidioc_s_fmt_vid_cap = vidioc_s_fmt_vid_cap, .vidioc_g_fmt_vbi_cap = vidioc_g_fmt_vbi_cap, .vidioc_try_fmt_vbi_cap = vidioc_try_fmt_vbi_cap, .vidioc_s_fmt_vbi_cap = vidioc_try_fmt_vbi_cap, .vidioc_g_audio = vidioc_g_audio, .vidioc_s_audio = vidioc_s_audio, .vidioc_cropcap = vidioc_cropcap, .vidioc_g_fmt_sliced_vbi_cap = vidioc_g_fmt_sliced_vbi_cap, .vidioc_try_fmt_sliced_vbi_cap = vidioc_try_set_sliced_vbi_cap, .vidioc_reqbufs = vidioc_reqbufs, .vidioc_querybuf = vidioc_querybuf, .vidioc_qbuf = vidioc_qbuf, .vidioc_dqbuf = vidioc_dqbuf, .vidioc_s_std = vidioc_s_std, .vidioc_g_std = vidioc_g_std, .vidioc_enum_input = vidioc_enum_input, .vidioc_g_input = vidioc_g_input, .vidioc_s_input = vidioc_s_input, .vidioc_queryctrl = vidioc_queryctrl, .vidioc_g_ctrl = vidioc_g_ctrl, .vidioc_s_ctrl = vidioc_s_ctrl, .vidioc_streamon = vidioc_streamon, .vidioc_streamoff = vidioc_streamoff, .vidioc_g_tuner = vidioc_g_tuner, .vidioc_s_tuner = vidioc_s_tuner, .vidioc_g_frequency = vidioc_g_frequency, .vidioc_s_frequency = vidioc_s_frequency, #ifdef CONFIG_VIDEO_ADV_DEBUG .vidioc_g_register = vidioc_g_register, .vidioc_s_register = vidioc_s_register, #endif #ifdef CONFIG_VIDEO_V4L1_COMPAT .vidiocgmbuf = vidiocgmbuf, #endif }; static struct video_device cx231xx_vbi_template; static const struct video_device cx231xx_video_template = { .fops = &cx231xx_v4l_fops, .release = video_device_release, .ioctl_ops = &video_ioctl_ops, .minor = -1, .tvnorms = V4L2_STD_ALL, .current_norm = V4L2_STD_PAL, }; static const struct v4l2_file_operations radio_fops = { .owner = THIS_MODULE, .open = cx231xx_v4l2_open, .release = cx231xx_v4l2_close, .ioctl = video_ioctl2, }; static const struct v4l2_ioctl_ops radio_ioctl_ops = { .vidioc_querycap = radio_querycap, .vidioc_g_tuner = radio_g_tuner, .vidioc_enum_input = radio_enum_input, .vidioc_g_audio = radio_g_audio, .vidioc_s_tuner = radio_s_tuner, .vidioc_s_audio = radio_s_audio, .vidioc_s_input = radio_s_input, .vidioc_queryctrl = radio_queryctrl, .vidioc_g_ctrl = vidioc_g_ctrl, .vidioc_s_ctrl = vidioc_s_ctrl, .vidioc_g_frequency = vidioc_g_frequency, .vidioc_s_frequency = vidioc_s_frequency, #ifdef CONFIG_VIDEO_ADV_DEBUG .vidioc_g_register = vidioc_g_register, .vidioc_s_register = vidioc_s_register, #endif }; static struct video_device cx231xx_radio_template = { .name = "cx231xx-radio", .fops = &radio_fops, .ioctl_ops = &radio_ioctl_ops, .minor = -1, }; /******************************** usb interface ******************************/ static struct video_device *cx231xx_vdev_init(struct cx231xx *dev, const struct video_device *template, const char *type_name) { struct video_device *vfd; vfd = video_device_alloc(); if (NULL == vfd) return NULL; *vfd = *template; vfd->minor = -1; vfd->v4l2_dev = &dev->v4l2_dev; vfd->release = video_device_release; vfd->debug = video_debug; snprintf(vfd->name, sizeof(vfd->name), "%s %s", dev->name, type_name); return vfd; } int cx231xx_register_analog_devices(struct cx231xx *dev) { int ret; cx231xx_info("%s: v4l2 driver version %d.%d.%d\n", dev->name, (CX231XX_VERSION_CODE >> 16) & 0xff, (CX231XX_VERSION_CODE >> 8) & 0xff, CX231XX_VERSION_CODE & 0xff); /* set default norm */ /*dev->norm = cx231xx_video_template.current_norm; */ dev->width = norm_maxw(dev); dev->height = norm_maxh(dev); dev->interlaced = 0; dev->hscale = 0; dev->vscale = 0; /* Analog specific initialization */ dev->format = &format[0]; /* video_mux(dev, dev->video_input); */ /* Audio defaults */ dev->mute = 1; dev->volume = 0x1f; /* enable vbi capturing */ /* write code here... */ /* allocate and fill video video_device struct */ dev->vdev = cx231xx_vdev_init(dev, &cx231xx_video_template, "video"); if (!dev->vdev) { cx231xx_errdev("cannot allocate video_device.\n"); return -ENODEV; } /* register v4l2 video video_device */ ret = video_register_device(dev->vdev, VFL_TYPE_GRABBER, video_nr[dev->devno]); if (ret) { cx231xx_errdev("unable to register video device (error=%i).\n", ret); return ret; } cx231xx_info("%s/0: registered device video%d [v4l2]\n", dev->name, dev->vdev->num); /* Initialize VBI template */ memcpy(&cx231xx_vbi_template, &cx231xx_video_template, sizeof(cx231xx_vbi_template)); strcpy(cx231xx_vbi_template.name, "cx231xx-vbi"); /* Allocate and fill vbi video_device struct */ dev->vbi_dev = cx231xx_vdev_init(dev, &cx231xx_vbi_template, "vbi"); /* register v4l2 vbi video_device */ ret = video_register_device(dev->vbi_dev, VFL_TYPE_VBI, vbi_nr[dev->devno]); if (ret < 0) { cx231xx_errdev("unable to register vbi device\n"); return ret; } cx231xx_info("%s/0: registered device vbi%d\n", dev->name, dev->vbi_dev->num); if (cx231xx_boards[dev->model].radio.type == CX231XX_RADIO) { dev->radio_dev = cx231xx_vdev_init(dev, &cx231xx_radio_template, "radio"); if (!dev->radio_dev) { cx231xx_errdev("cannot allocate video_device.\n"); return -ENODEV; } ret = video_register_device(dev->radio_dev, VFL_TYPE_RADIO, radio_nr[dev->devno]); if (ret < 0) { cx231xx_errdev("can't register radio device\n"); return ret; } cx231xx_info("Registered radio device as /dev/radio%d\n", dev->radio_dev->num); } cx231xx_info("V4L2 device registered as /dev/video%d and /dev/vbi%d\n", dev->vdev->num, dev->vbi_dev->num); return 0; }
gpl-2.0
Linux-Wii-Mod/linux-wii-2.6.32
drivers/scsi/bfa/bfad.c
463
28330
/* * Copyright (c) 2005-2009 Brocade Communications Systems, Inc. * All rights reserved * www.brocade.com * * Linux driver for Brocade Fibre Channel Host Bus Adapter. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License (GPL) 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. */ /** * bfad.c Linux driver PCI interface module. */ #include <linux/module.h> #include "bfad_drv.h" #include "bfad_im.h" #include "bfad_tm.h" #include "bfad_ipfc.h" #include "bfad_trcmod.h" #include <fcb/bfa_fcb_vf.h> #include <fcb/bfa_fcb_rport.h> #include <fcb/bfa_fcb_port.h> #include <fcb/bfa_fcb.h> BFA_TRC_FILE(LDRV, BFAD); static DEFINE_MUTEX(bfad_mutex); LIST_HEAD(bfad_list); static int bfad_inst; int bfad_supported_fc4s; static char *host_name; static char *os_name; static char *os_patch; static int num_rports; static int num_ios; static int num_tms; static int num_fcxps; static int num_ufbufs; static int reqq_size; static int rspq_size; static int num_sgpgs; static int rport_del_timeout = BFA_FCS_RPORT_DEF_DEL_TIMEOUT; static int bfa_io_max_sge = BFAD_IO_MAX_SGE; static int log_level = BFA_LOG_WARNING; static int ioc_auto_recover = BFA_TRUE; static int ipfc_enable = BFA_FALSE; static int ipfc_mtu = -1; int bfa_lun_queue_depth = BFAD_LUN_QUEUE_DEPTH; int bfa_linkup_delay = -1; module_param(os_name, charp, S_IRUGO | S_IWUSR); module_param(os_patch, charp, S_IRUGO | S_IWUSR); module_param(host_name, charp, S_IRUGO | S_IWUSR); module_param(num_rports, int, S_IRUGO | S_IWUSR); module_param(num_ios, int, S_IRUGO | S_IWUSR); module_param(num_tms, int, S_IRUGO | S_IWUSR); module_param(num_fcxps, int, S_IRUGO | S_IWUSR); module_param(num_ufbufs, int, S_IRUGO | S_IWUSR); module_param(reqq_size, int, S_IRUGO | S_IWUSR); module_param(rspq_size, int, S_IRUGO | S_IWUSR); module_param(num_sgpgs, int, S_IRUGO | S_IWUSR); module_param(rport_del_timeout, int, S_IRUGO | S_IWUSR); module_param(bfa_lun_queue_depth, int, S_IRUGO | S_IWUSR); module_param(bfa_io_max_sge, int, S_IRUGO | S_IWUSR); module_param(log_level, int, S_IRUGO | S_IWUSR); module_param(ioc_auto_recover, int, S_IRUGO | S_IWUSR); module_param(ipfc_enable, int, S_IRUGO | S_IWUSR); module_param(ipfc_mtu, int, S_IRUGO | S_IWUSR); module_param(bfa_linkup_delay, int, S_IRUGO | S_IWUSR); /* * Stores the module parm num_sgpgs value; * used to reset for bfad next instance. */ static int num_sgpgs_parm; static bfa_status_t bfad_fc4_probe(struct bfad_s *bfad) { int rc; rc = bfad_im_probe(bfad); if (rc != BFA_STATUS_OK) goto ext; bfad_tm_probe(bfad); if (ipfc_enable) bfad_ipfc_probe(bfad); ext: return rc; } static void bfad_fc4_probe_undo(struct bfad_s *bfad) { bfad_im_probe_undo(bfad); bfad_tm_probe_undo(bfad); if (ipfc_enable) bfad_ipfc_probe_undo(bfad); } static void bfad_fc4_probe_post(struct bfad_s *bfad) { if (bfad->im) bfad_im_probe_post(bfad->im); bfad_tm_probe_post(bfad); if (ipfc_enable) bfad_ipfc_probe_post(bfad); } static bfa_status_t bfad_fc4_port_new(struct bfad_s *bfad, struct bfad_port_s *port, int roles) { int rc = BFA_STATUS_FAILED; if (roles & BFA_PORT_ROLE_FCP_IM) rc = bfad_im_port_new(bfad, port); if (rc != BFA_STATUS_OK) goto ext; if (roles & BFA_PORT_ROLE_FCP_TM) rc = bfad_tm_port_new(bfad, port); if (rc != BFA_STATUS_OK) goto ext; if ((roles & BFA_PORT_ROLE_FCP_IPFC) && ipfc_enable) rc = bfad_ipfc_port_new(bfad, port, port->pvb_type); ext: return rc; } static void bfad_fc4_port_delete(struct bfad_s *bfad, struct bfad_port_s *port, int roles) { if (roles & BFA_PORT_ROLE_FCP_IM) bfad_im_port_delete(bfad, port); if (roles & BFA_PORT_ROLE_FCP_TM) bfad_tm_port_delete(bfad, port); if ((roles & BFA_PORT_ROLE_FCP_IPFC) && ipfc_enable) bfad_ipfc_port_delete(bfad, port); } /** * BFA callbacks */ void bfad_hcb_comp(void *arg, bfa_status_t status) { struct bfad_hal_comp *fcomp = (struct bfad_hal_comp *)arg; fcomp->status = status; complete(&fcomp->comp); } /** * bfa_init callback */ void bfa_cb_init(void *drv, bfa_status_t init_status) { struct bfad_s *bfad = drv; if (init_status == BFA_STATUS_OK) bfad->bfad_flags |= BFAD_HAL_INIT_DONE; complete(&bfad->comp); } /** * BFA_FCS callbacks */ static struct bfad_port_s * bfad_get_drv_port(struct bfad_s *bfad, struct bfad_vf_s *vf_drv, struct bfad_vport_s *vp_drv) { return ((vp_drv) ? (&(vp_drv)->drv_port) : ((vf_drv) ? (&(vf_drv)->base_port) : (&(bfad)->pport))); } struct bfad_port_s * bfa_fcb_port_new(struct bfad_s *bfad, struct bfa_fcs_port_s *port, enum bfa_port_role roles, struct bfad_vf_s *vf_drv, struct bfad_vport_s *vp_drv) { bfa_status_t rc; struct bfad_port_s *port_drv; if (!vp_drv && !vf_drv) { port_drv = &bfad->pport; port_drv->pvb_type = BFAD_PORT_PHYS_BASE; } else if (!vp_drv && vf_drv) { port_drv = &vf_drv->base_port; port_drv->pvb_type = BFAD_PORT_VF_BASE; } else if (vp_drv && !vf_drv) { port_drv = &vp_drv->drv_port; port_drv->pvb_type = BFAD_PORT_PHYS_VPORT; } else { port_drv = &vp_drv->drv_port; port_drv->pvb_type = BFAD_PORT_VF_VPORT; } port_drv->fcs_port = port; port_drv->roles = roles; rc = bfad_fc4_port_new(bfad, port_drv, roles); if (rc != BFA_STATUS_OK) { bfad_fc4_port_delete(bfad, port_drv, roles); port_drv = NULL; } return port_drv; } void bfa_fcb_port_delete(struct bfad_s *bfad, enum bfa_port_role roles, struct bfad_vf_s *vf_drv, struct bfad_vport_s *vp_drv) { struct bfad_port_s *port_drv; /* * this will be only called from rmmod context */ if (vp_drv && !vp_drv->comp_del) { port_drv = bfad_get_drv_port(bfad, vf_drv, vp_drv); bfa_trc(bfad, roles); bfad_fc4_port_delete(bfad, port_drv, roles); } } void bfa_fcb_port_online(struct bfad_s *bfad, enum bfa_port_role roles, struct bfad_vf_s *vf_drv, struct bfad_vport_s *vp_drv) { struct bfad_port_s *port_drv = bfad_get_drv_port(bfad, vf_drv, vp_drv); if (roles & BFA_PORT_ROLE_FCP_IM) bfad_im_port_online(bfad, port_drv); if (roles & BFA_PORT_ROLE_FCP_TM) bfad_tm_port_online(bfad, port_drv); if ((roles & BFA_PORT_ROLE_FCP_IPFC) && ipfc_enable) bfad_ipfc_port_online(bfad, port_drv); bfad->bfad_flags |= BFAD_PORT_ONLINE; } void bfa_fcb_port_offline(struct bfad_s *bfad, enum bfa_port_role roles, struct bfad_vf_s *vf_drv, struct bfad_vport_s *vp_drv) { struct bfad_port_s *port_drv = bfad_get_drv_port(bfad, vf_drv, vp_drv); if (roles & BFA_PORT_ROLE_FCP_IM) bfad_im_port_offline(bfad, port_drv); if (roles & BFA_PORT_ROLE_FCP_TM) bfad_tm_port_offline(bfad, port_drv); if ((roles & BFA_PORT_ROLE_FCP_IPFC) && ipfc_enable) bfad_ipfc_port_offline(bfad, port_drv); } void bfa_fcb_vport_delete(struct bfad_vport_s *vport_drv) { if (vport_drv->comp_del) { complete(vport_drv->comp_del); return; } kfree(vport_drv); } /** * FCS RPORT alloc callback, after successful PLOGI by FCS */ bfa_status_t bfa_fcb_rport_alloc(struct bfad_s *bfad, struct bfa_fcs_rport_s **rport, struct bfad_rport_s **rport_drv) { bfa_status_t rc = BFA_STATUS_OK; *rport_drv = kzalloc(sizeof(struct bfad_rport_s), GFP_ATOMIC); if (*rport_drv == NULL) { rc = BFA_STATUS_ENOMEM; goto ext; } *rport = &(*rport_drv)->fcs_rport; ext: return rc; } void bfad_hal_mem_release(struct bfad_s *bfad) { int i; struct bfa_meminfo_s *hal_meminfo = &bfad->meminfo; struct bfa_mem_elem_s *meminfo_elem; for (i = 0; i < BFA_MEM_TYPE_MAX; i++) { meminfo_elem = &hal_meminfo->meminfo[i]; if (meminfo_elem->kva != NULL) { switch (meminfo_elem->mem_type) { case BFA_MEM_TYPE_KVA: vfree(meminfo_elem->kva); break; case BFA_MEM_TYPE_DMA: dma_free_coherent(&bfad->pcidev->dev, meminfo_elem->mem_len, meminfo_elem->kva, (dma_addr_t) meminfo_elem->dma); break; default: bfa_assert(0); break; } } } memset(hal_meminfo, 0, sizeof(struct bfa_meminfo_s)); } void bfad_update_hal_cfg(struct bfa_iocfc_cfg_s *bfa_cfg) { if (num_rports > 0) bfa_cfg->fwcfg.num_rports = num_rports; if (num_ios > 0) bfa_cfg->fwcfg.num_ioim_reqs = num_ios; if (num_tms > 0) bfa_cfg->fwcfg.num_tskim_reqs = num_tms; if (num_fcxps > 0) bfa_cfg->fwcfg.num_fcxp_reqs = num_fcxps; if (num_ufbufs > 0) bfa_cfg->fwcfg.num_uf_bufs = num_ufbufs; if (reqq_size > 0) bfa_cfg->drvcfg.num_reqq_elems = reqq_size; if (rspq_size > 0) bfa_cfg->drvcfg.num_rspq_elems = rspq_size; if (num_sgpgs > 0) bfa_cfg->drvcfg.num_sgpgs = num_sgpgs; /* * populate the hal values back to the driver for sysfs use. * otherwise, the default values will be shown as 0 in sysfs */ num_rports = bfa_cfg->fwcfg.num_rports; num_ios = bfa_cfg->fwcfg.num_ioim_reqs; num_tms = bfa_cfg->fwcfg.num_tskim_reqs; num_fcxps = bfa_cfg->fwcfg.num_fcxp_reqs; num_ufbufs = bfa_cfg->fwcfg.num_uf_bufs; reqq_size = bfa_cfg->drvcfg.num_reqq_elems; rspq_size = bfa_cfg->drvcfg.num_rspq_elems; num_sgpgs = bfa_cfg->drvcfg.num_sgpgs; } bfa_status_t bfad_hal_mem_alloc(struct bfad_s *bfad) { struct bfa_meminfo_s *hal_meminfo = &bfad->meminfo; struct bfa_mem_elem_s *meminfo_elem; bfa_status_t rc = BFA_STATUS_OK; dma_addr_t phys_addr; int retry_count = 0; int reset_value = 1; int min_num_sgpgs = 512; void *kva; int i; bfa_cfg_get_default(&bfad->ioc_cfg); retry: bfad_update_hal_cfg(&bfad->ioc_cfg); bfad->cfg_data.ioc_queue_depth = bfad->ioc_cfg.fwcfg.num_ioim_reqs; bfa_cfg_get_meminfo(&bfad->ioc_cfg, hal_meminfo); for (i = 0; i < BFA_MEM_TYPE_MAX; i++) { meminfo_elem = &hal_meminfo->meminfo[i]; switch (meminfo_elem->mem_type) { case BFA_MEM_TYPE_KVA: kva = vmalloc(meminfo_elem->mem_len); if (kva == NULL) { bfad_hal_mem_release(bfad); rc = BFA_STATUS_ENOMEM; goto ext; } memset(kva, 0, meminfo_elem->mem_len); meminfo_elem->kva = kva; break; case BFA_MEM_TYPE_DMA: kva = dma_alloc_coherent(&bfad->pcidev->dev, meminfo_elem->mem_len, &phys_addr, GFP_KERNEL); if (kva == NULL) { bfad_hal_mem_release(bfad); /* * If we cannot allocate with default * num_sgpages try with half the value. */ if (num_sgpgs > min_num_sgpgs) { printk(KERN_INFO "bfad[%d]: memory" " allocation failed with" " num_sgpgs: %d\n", bfad->inst_no, num_sgpgs); nextLowerInt(&num_sgpgs); printk(KERN_INFO "bfad[%d]: trying to" " allocate memory with" " num_sgpgs: %d\n", bfad->inst_no, num_sgpgs); retry_count++; goto retry; } else { if (num_sgpgs_parm > 0) num_sgpgs = num_sgpgs_parm; else { reset_value = (1 << retry_count); num_sgpgs *= reset_value; } rc = BFA_STATUS_ENOMEM; goto ext; } } if (num_sgpgs_parm > 0) num_sgpgs = num_sgpgs_parm; else { reset_value = (1 << retry_count); num_sgpgs *= reset_value; } memset(kva, 0, meminfo_elem->mem_len); meminfo_elem->kva = kva; meminfo_elem->dma = phys_addr; break; default: break; } } ext: return rc; } /** * Create a vport under a vf. */ bfa_status_t bfad_vport_create(struct bfad_s *bfad, u16 vf_id, struct bfa_port_cfg_s *port_cfg) { struct bfad_vport_s *vport; int rc = BFA_STATUS_OK; unsigned long flags; struct completion fcomp; vport = kzalloc(sizeof(struct bfad_vport_s), GFP_KERNEL); if (!vport) { rc = BFA_STATUS_ENOMEM; goto ext; } vport->drv_port.bfad = bfad; spin_lock_irqsave(&bfad->bfad_lock, flags); rc = bfa_fcs_vport_create(&vport->fcs_vport, &bfad->bfa_fcs, vf_id, port_cfg, vport); spin_unlock_irqrestore(&bfad->bfad_lock, flags); if (rc != BFA_STATUS_OK) goto ext_free_vport; if (port_cfg->roles & BFA_PORT_ROLE_FCP_IM) { rc = bfad_im_scsi_host_alloc(bfad, vport->drv_port.im_port); if (rc != BFA_STATUS_OK) goto ext_free_fcs_vport; } spin_lock_irqsave(&bfad->bfad_lock, flags); bfa_fcs_vport_start(&vport->fcs_vport); spin_unlock_irqrestore(&bfad->bfad_lock, flags); return BFA_STATUS_OK; ext_free_fcs_vport: spin_lock_irqsave(&bfad->bfad_lock, flags); vport->comp_del = &fcomp; init_completion(vport->comp_del); bfa_fcs_vport_delete(&vport->fcs_vport); spin_unlock_irqrestore(&bfad->bfad_lock, flags); wait_for_completion(vport->comp_del); ext_free_vport: kfree(vport); ext: return rc; } /** * Create a vf and its base vport implicitely. */ bfa_status_t bfad_vf_create(struct bfad_s *bfad, u16 vf_id, struct bfa_port_cfg_s *port_cfg) { struct bfad_vf_s *vf; int rc = BFA_STATUS_OK; vf = kzalloc(sizeof(struct bfad_vf_s), GFP_KERNEL); if (!vf) { rc = BFA_STATUS_FAILED; goto ext; } rc = bfa_fcs_vf_create(&vf->fcs_vf, &bfad->bfa_fcs, vf_id, port_cfg, vf); if (rc != BFA_STATUS_OK) kfree(vf); ext: return rc; } void bfad_bfa_tmo(unsigned long data) { struct bfad_s *bfad = (struct bfad_s *)data; unsigned long flags; struct list_head doneq; spin_lock_irqsave(&bfad->bfad_lock, flags); bfa_timer_tick(&bfad->bfa); bfa_comp_deq(&bfad->bfa, &doneq); spin_unlock_irqrestore(&bfad->bfad_lock, flags); if (!list_empty(&doneq)) { bfa_comp_process(&bfad->bfa, &doneq); spin_lock_irqsave(&bfad->bfad_lock, flags); bfa_comp_free(&bfad->bfa, &doneq); spin_unlock_irqrestore(&bfad->bfad_lock, flags); } mod_timer(&bfad->hal_tmo, jiffies + msecs_to_jiffies(BFA_TIMER_FREQ)); } void bfad_init_timer(struct bfad_s *bfad) { init_timer(&bfad->hal_tmo); bfad->hal_tmo.function = bfad_bfa_tmo; bfad->hal_tmo.data = (unsigned long)bfad; mod_timer(&bfad->hal_tmo, jiffies + msecs_to_jiffies(BFA_TIMER_FREQ)); } int bfad_pci_init(struct pci_dev *pdev, struct bfad_s *bfad) { unsigned long bar0_len; int rc = -ENODEV; if (pci_enable_device(pdev)) { BFA_PRINTF(BFA_ERR, "pci_enable_device fail %p\n", pdev); goto out; } if (pci_request_regions(pdev, BFAD_DRIVER_NAME)) goto out_disable_device; pci_set_master(pdev); if (pci_set_dma_mask(pdev, DMA_BIT_MASK(64)) != 0) if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) != 0) { BFA_PRINTF(BFA_ERR, "pci_set_dma_mask fail %p\n", pdev); goto out_release_region; } bfad->pci_bar0_map = pci_resource_start(pdev, 0); bar0_len = pci_resource_len(pdev, 0); bfad->pci_bar0_kva = ioremap(bfad->pci_bar0_map, bar0_len); if (bfad->pci_bar0_kva == NULL) { BFA_PRINTF(BFA_ERR, "Fail to map bar0\n"); goto out_release_region; } bfad->hal_pcidev.pci_slot = PCI_SLOT(pdev->devfn); bfad->hal_pcidev.pci_func = PCI_FUNC(pdev->devfn); bfad->hal_pcidev.pci_bar_kva = bfad->pci_bar0_kva; bfad->hal_pcidev.device_id = pdev->device; bfad->pci_name = pci_name(pdev); bfad->pci_attr.vendor_id = pdev->vendor; bfad->pci_attr.device_id = pdev->device; bfad->pci_attr.ssid = pdev->subsystem_device; bfad->pci_attr.ssvid = pdev->subsystem_vendor; bfad->pci_attr.pcifn = PCI_FUNC(pdev->devfn); bfad->pcidev = pdev; return 0; out_release_region: pci_release_regions(pdev); out_disable_device: pci_disable_device(pdev); out: return rc; } void bfad_pci_uninit(struct pci_dev *pdev, struct bfad_s *bfad) { #if defined(__ia64__) pci_iounmap(pdev, bfad->pci_bar0_kva); #else iounmap(bfad->pci_bar0_kva); #endif pci_release_regions(pdev); pci_disable_device(pdev); pci_set_drvdata(pdev, NULL); } void bfad_fcs_port_cfg(struct bfad_s *bfad) { struct bfa_port_cfg_s port_cfg; struct bfa_pport_attr_s attr; char symname[BFA_SYMNAME_MAXLEN]; sprintf(symname, "%s-%d", BFAD_DRIVER_NAME, bfad->inst_no); memcpy(port_cfg.sym_name.symname, symname, strlen(symname)); bfa_pport_get_attr(&bfad->bfa, &attr); port_cfg.nwwn = attr.nwwn; port_cfg.pwwn = attr.pwwn; bfa_fcs_cfg_base_port(&bfad->bfa_fcs, &port_cfg); } bfa_status_t bfad_drv_init(struct bfad_s *bfad) { bfa_status_t rc; unsigned long flags; struct bfa_fcs_driver_info_s driver_info; int i; bfad->cfg_data.rport_del_timeout = rport_del_timeout; bfad->cfg_data.lun_queue_depth = bfa_lun_queue_depth; bfad->cfg_data.io_max_sge = bfa_io_max_sge; bfad->cfg_data.binding_method = FCP_PWWN_BINDING; rc = bfad_hal_mem_alloc(bfad); if (rc != BFA_STATUS_OK) { printk(KERN_WARNING "bfad%d bfad_hal_mem_alloc failure\n", bfad->inst_no); printk(KERN_WARNING "Not enough memory to attach all Brocade HBA ports," " System may need more memory.\n"); goto out_hal_mem_alloc_failure; } bfa_init_log(&bfad->bfa, bfad->logmod); bfa_init_trc(&bfad->bfa, bfad->trcmod); bfa_init_aen(&bfad->bfa, bfad->aen); INIT_LIST_HEAD(&bfad->file_q); INIT_LIST_HEAD(&bfad->file_free_q); for (i = 0; i < BFAD_AEN_MAX_APPS; i++) { bfa_q_qe_init(&bfad->file_buf[i].qe); list_add_tail(&bfad->file_buf[i].qe, &bfad->file_free_q); } bfa_init_plog(&bfad->bfa, &bfad->plog_buf); bfa_plog_init(&bfad->plog_buf); bfa_plog_str(&bfad->plog_buf, BFA_PL_MID_DRVR, BFA_PL_EID_DRIVER_START, 0, "Driver Attach"); bfa_attach(&bfad->bfa, bfad, &bfad->ioc_cfg, &bfad->meminfo, &bfad->hal_pcidev); init_completion(&bfad->comp); /* * Enable Interrupt and wait bfa_init completion */ if (bfad_setup_intr(bfad)) { printk(KERN_WARNING "bfad%d: bfad_setup_intr failed\n", bfad->inst_no); goto out_setup_intr_failure; } spin_lock_irqsave(&bfad->bfad_lock, flags); bfa_init(&bfad->bfa); spin_unlock_irqrestore(&bfad->bfad_lock, flags); /* * Set up interrupt handler for each vectors */ if ((bfad->bfad_flags & BFAD_MSIX_ON) && bfad_install_msix_handler(bfad)) { printk(KERN_WARNING "%s: install_msix failed, bfad%d\n", __FUNCTION__, bfad->inst_no); } bfad_init_timer(bfad); wait_for_completion(&bfad->comp); memset(&driver_info, 0, sizeof(driver_info)); strncpy(driver_info.version, BFAD_DRIVER_VERSION, sizeof(driver_info.version) - 1); if (host_name) strncpy(driver_info.host_machine_name, host_name, sizeof(driver_info.host_machine_name) - 1); if (os_name) strncpy(driver_info.host_os_name, os_name, sizeof(driver_info.host_os_name) - 1); if (os_patch) strncpy(driver_info.host_os_patch, os_patch, sizeof(driver_info.host_os_patch) - 1); strncpy(driver_info.os_device_name, bfad->pci_name, sizeof(driver_info.os_device_name - 1)); /* * FCS INIT */ spin_lock_irqsave(&bfad->bfad_lock, flags); bfa_fcs_log_init(&bfad->bfa_fcs, bfad->logmod); bfa_fcs_trc_init(&bfad->bfa_fcs, bfad->trcmod); bfa_fcs_aen_init(&bfad->bfa_fcs, bfad->aen); bfa_fcs_init(&bfad->bfa_fcs, &bfad->bfa, bfad, BFA_FALSE); bfa_fcs_driver_info_init(&bfad->bfa_fcs, &driver_info); spin_unlock_irqrestore(&bfad->bfad_lock, flags); bfad->bfad_flags |= BFAD_DRV_INIT_DONE; return BFA_STATUS_OK; out_setup_intr_failure: bfa_detach(&bfad->bfa); bfad_hal_mem_release(bfad); out_hal_mem_alloc_failure: return BFA_STATUS_FAILED; } void bfad_drv_uninit(struct bfad_s *bfad) { del_timer_sync(&bfad->hal_tmo); bfa_isr_disable(&bfad->bfa); bfa_detach(&bfad->bfa); bfad_remove_intr(bfad); bfa_assert(list_empty(&bfad->file_q)); bfad_hal_mem_release(bfad); } void bfad_drv_start(struct bfad_s *bfad) { unsigned long flags; spin_lock_irqsave(&bfad->bfad_lock, flags); bfa_start(&bfad->bfa); bfa_fcs_start(&bfad->bfa_fcs); bfad->bfad_flags |= BFAD_HAL_START_DONE; spin_unlock_irqrestore(&bfad->bfad_lock, flags); bfad_fc4_probe_post(bfad); } void bfad_drv_stop(struct bfad_s *bfad) { unsigned long flags; spin_lock_irqsave(&bfad->bfad_lock, flags); init_completion(&bfad->comp); bfad->pport.flags |= BFAD_PORT_DELETE; bfa_fcs_exit(&bfad->bfa_fcs); spin_unlock_irqrestore(&bfad->bfad_lock, flags); wait_for_completion(&bfad->comp); spin_lock_irqsave(&bfad->bfad_lock, flags); init_completion(&bfad->comp); bfa_stop(&bfad->bfa); bfad->bfad_flags &= ~BFAD_HAL_START_DONE; spin_unlock_irqrestore(&bfad->bfad_lock, flags); wait_for_completion(&bfad->comp); } bfa_status_t bfad_cfg_pport(struct bfad_s *bfad, enum bfa_port_role role) { int rc = BFA_STATUS_OK; /* * Allocate scsi_host for the physical port */ if ((bfad_supported_fc4s & BFA_PORT_ROLE_FCP_IM) && (role & BFA_PORT_ROLE_FCP_IM)) { if (bfad->pport.im_port == NULL) { rc = BFA_STATUS_FAILED; goto out; } rc = bfad_im_scsi_host_alloc(bfad, bfad->pport.im_port); if (rc != BFA_STATUS_OK) goto out; bfad->pport.roles |= BFA_PORT_ROLE_FCP_IM; } bfad->bfad_flags |= BFAD_CFG_PPORT_DONE; out: return rc; } void bfad_uncfg_pport(struct bfad_s *bfad) { if ((bfad->pport.roles & BFA_PORT_ROLE_FCP_IPFC) && ipfc_enable) { bfad_ipfc_port_delete(bfad, &bfad->pport); bfad->pport.roles &= ~BFA_PORT_ROLE_FCP_IPFC; } if ((bfad_supported_fc4s & BFA_PORT_ROLE_FCP_IM) && (bfad->pport.roles & BFA_PORT_ROLE_FCP_IM)) { bfad_im_scsi_host_free(bfad, bfad->pport.im_port); bfad_im_port_clean(bfad->pport.im_port); kfree(bfad->pport.im_port); bfad->pport.roles &= ~BFA_PORT_ROLE_FCP_IM; } bfad->bfad_flags &= ~BFAD_CFG_PPORT_DONE; } void bfad_drv_log_level_set(struct bfad_s *bfad) { if (log_level > BFA_LOG_INVALID && log_level <= BFA_LOG_LEVEL_MAX) bfa_log_set_level_all(&bfad->log_data, log_level); } /* * PCI_entry PCI driver entries * { */ /** * PCI probe entry. */ int bfad_pci_probe(struct pci_dev *pdev, const struct pci_device_id *pid) { struct bfad_s *bfad; int error = -ENODEV, retval; char buf[16]; /* * For single port cards - only claim function 0 */ if ((pdev->device == BFA_PCI_DEVICE_ID_FC_8G1P) && (PCI_FUNC(pdev->devfn) != 0)) return -ENODEV; BFA_TRACE(BFA_INFO, "bfad_pci_probe entry"); bfad = kzalloc(sizeof(struct bfad_s), GFP_KERNEL); if (!bfad) { error = -ENOMEM; goto out; } bfad->trcmod = kzalloc(sizeof(struct bfa_trc_mod_s), GFP_KERNEL); if (!bfad->trcmod) { printk(KERN_WARNING "Error alloc trace buffer!\n"); error = -ENOMEM; goto out_alloc_trace_failure; } /* * LOG/TRACE INIT */ bfa_trc_init(bfad->trcmod); bfa_trc(bfad, bfad_inst); bfad->logmod = &bfad->log_data; sprintf(buf, "%d", bfad_inst); bfa_log_init(bfad->logmod, buf, bfa_os_printf); bfad_drv_log_level_set(bfad); bfad->aen = &bfad->aen_buf; if (!(bfad_load_fwimg(pdev))) { printk(KERN_WARNING "bfad_load_fwimg failure!\n"); kfree(bfad->trcmod); goto out_alloc_trace_failure; } retval = bfad_pci_init(pdev, bfad); if (retval) { printk(KERN_WARNING "bfad_pci_init failure!\n"); error = retval; goto out_pci_init_failure; } mutex_lock(&bfad_mutex); bfad->inst_no = bfad_inst++; list_add_tail(&bfad->list_entry, &bfad_list); mutex_unlock(&bfad_mutex); spin_lock_init(&bfad->bfad_lock); pci_set_drvdata(pdev, bfad); bfad->ref_count = 0; bfad->pport.bfad = bfad; retval = bfad_drv_init(bfad); if (retval != BFA_STATUS_OK) goto out_drv_init_failure; if (!(bfad->bfad_flags & BFAD_HAL_INIT_DONE)) { printk(KERN_WARNING "bfad%d: hal init failed\n", bfad->inst_no); goto ok; } /* * PPORT FCS config */ bfad_fcs_port_cfg(bfad); retval = bfad_cfg_pport(bfad, BFA_PORT_ROLE_FCP_IM); if (retval != BFA_STATUS_OK) goto out_cfg_pport_failure; /* * BFAD level FC4 (IM/TM/IPFC) specific resource allocation */ retval = bfad_fc4_probe(bfad); if (retval != BFA_STATUS_OK) { printk(KERN_WARNING "bfad_fc4_probe failed\n"); goto out_fc4_probe_failure; } bfad_drv_start(bfad); /* * If bfa_linkup_delay is set to -1 default; try to retrive the * value using the bfad_os_get_linkup_delay(); else use the * passed in module param value as the bfa_linkup_delay. */ if (bfa_linkup_delay < 0) { bfa_linkup_delay = bfad_os_get_linkup_delay(bfad); bfad_os_rport_online_wait(bfad); bfa_linkup_delay = -1; } else { bfad_os_rport_online_wait(bfad); } bfa_log(bfad->logmod, BFA_LOG_LINUX_DEVICE_CLAIMED, bfad->pci_name); ok: return 0; out_fc4_probe_failure: bfad_fc4_probe_undo(bfad); bfad_uncfg_pport(bfad); out_cfg_pport_failure: bfad_drv_uninit(bfad); out_drv_init_failure: mutex_lock(&bfad_mutex); bfad_inst--; list_del(&bfad->list_entry); mutex_unlock(&bfad_mutex); bfad_pci_uninit(pdev, bfad); out_pci_init_failure: kfree(bfad->trcmod); out_alloc_trace_failure: kfree(bfad); out: return error; } /** * PCI remove entry. */ void bfad_pci_remove(struct pci_dev *pdev) { struct bfad_s *bfad = pci_get_drvdata(pdev); unsigned long flags; bfa_trc(bfad, bfad->inst_no); if ((bfad->bfad_flags & BFAD_DRV_INIT_DONE) && !(bfad->bfad_flags & BFAD_HAL_INIT_DONE)) { spin_lock_irqsave(&bfad->bfad_lock, flags); init_completion(&bfad->comp); bfa_stop(&bfad->bfa); spin_unlock_irqrestore(&bfad->bfad_lock, flags); wait_for_completion(&bfad->comp); bfad_remove_intr(bfad); del_timer_sync(&bfad->hal_tmo); goto hal_detach; } else if (!(bfad->bfad_flags & BFAD_DRV_INIT_DONE)) { goto remove_sysfs; } if (bfad->bfad_flags & BFAD_HAL_START_DONE) bfad_drv_stop(bfad); bfad_remove_intr(bfad); del_timer_sync(&bfad->hal_tmo); bfad_fc4_probe_undo(bfad); if (bfad->bfad_flags & BFAD_CFG_PPORT_DONE) bfad_uncfg_pport(bfad); hal_detach: spin_lock_irqsave(&bfad->bfad_lock, flags); bfa_detach(&bfad->bfa); spin_unlock_irqrestore(&bfad->bfad_lock, flags); bfad_hal_mem_release(bfad); remove_sysfs: mutex_lock(&bfad_mutex); bfad_inst--; list_del(&bfad->list_entry); mutex_unlock(&bfad_mutex); bfad_pci_uninit(pdev, bfad); kfree(bfad->trcmod); kfree(bfad); } static struct pci_device_id bfad_id_table[] = { { .vendor = BFA_PCI_VENDOR_ID_BROCADE, .device = BFA_PCI_DEVICE_ID_FC_8G2P, .subvendor = PCI_ANY_ID, .subdevice = PCI_ANY_ID, }, { .vendor = BFA_PCI_VENDOR_ID_BROCADE, .device = BFA_PCI_DEVICE_ID_FC_8G1P, .subvendor = PCI_ANY_ID, .subdevice = PCI_ANY_ID, }, { .vendor = BFA_PCI_VENDOR_ID_BROCADE, .device = BFA_PCI_DEVICE_ID_CT, .subvendor = PCI_ANY_ID, .subdevice = PCI_ANY_ID, .class = (PCI_CLASS_SERIAL_FIBER << 8), .class_mask = ~0, }, {0, 0}, }; MODULE_DEVICE_TABLE(pci, bfad_id_table); static struct pci_driver bfad_pci_driver = { .name = BFAD_DRIVER_NAME, .id_table = bfad_id_table, .probe = bfad_pci_probe, .remove = __devexit_p(bfad_pci_remove), }; /** * Linux driver module functions */ bfa_status_t bfad_fc4_module_init(void) { int rc; rc = bfad_im_module_init(); if (rc != BFA_STATUS_OK) goto ext; bfad_tm_module_init(); if (ipfc_enable) bfad_ipfc_module_init(); ext: return rc; } void bfad_fc4_module_exit(void) { if (ipfc_enable) bfad_ipfc_module_exit(); bfad_tm_module_exit(); bfad_im_module_exit(); } /** * Driver module init. */ static int __init bfad_init(void) { int error = 0; printk(KERN_INFO "Brocade BFA FC/FCOE SCSI driver - version: %s\n", BFAD_DRIVER_VERSION); if (num_sgpgs > 0) num_sgpgs_parm = num_sgpgs; error = bfad_fc4_module_init(); if (error) { error = -ENOMEM; printk(KERN_WARNING "bfad_fc4_module_init failure\n"); goto ext; } if (!strcmp(FCPI_NAME, " fcpim")) bfad_supported_fc4s |= BFA_PORT_ROLE_FCP_IM; if (!strcmp(FCPT_NAME, " fcptm")) bfad_supported_fc4s |= BFA_PORT_ROLE_FCP_TM; if (!strcmp(IPFC_NAME, " ipfc")) bfad_supported_fc4s |= BFA_PORT_ROLE_FCP_IPFC; bfa_ioc_auto_recover(ioc_auto_recover); bfa_fcs_rport_set_del_timeout(rport_del_timeout); error = pci_register_driver(&bfad_pci_driver); if (error) { printk(KERN_WARNING "bfad pci_register_driver failure\n"); goto ext; } return 0; ext: bfad_fc4_module_exit(); return error; } /** * Driver module exit. */ static void __exit bfad_exit(void) { pci_unregister_driver(&bfad_pci_driver); bfad_fc4_module_exit(); bfad_free_fwimg(); } #define BFAD_PROTO_NAME FCPI_NAME FCPT_NAME IPFC_NAME module_init(bfad_init); module_exit(bfad_exit); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Brocade Fibre Channel HBA Driver" BFAD_PROTO_NAME); MODULE_AUTHOR("Brocade Communications Systems, Inc."); MODULE_VERSION(BFAD_DRIVER_VERSION);
gpl-2.0
okrt/note8-jb-kernel
drivers/media/video/exynos/tv/hdmiphy_conf_4210.c
719
1787
/* * Samsung HDMI Physical interface driver * * Copyright (C) 2010-2011 Samsung Electronics Co.Ltd * Author: Jiun Yu <jiun.yu@samsung.com> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. */ #include "hdmi.h" static const u8 hdmiphy_conf27[32] = { 0x01, 0x05, 0x00, 0xD8, 0x10, 0x1C, 0x30, 0x40, 0x6B, 0x10, 0x02, 0x51, 0xDf, 0xF2, 0x54, 0x87, 0x84, 0x00, 0x30, 0x38, 0x00, 0x08, 0x10, 0xE0, 0x22, 0x40, 0xe3, 0x26, 0x00, 0x00, 0x00, 0x80, }; static const u8 hdmiphy_conf74_175[32] = { 0x01, 0x05, 0x00, 0xD8, 0x10, 0x9C, 0xef, 0x5B, 0x6D, 0x10, 0x01, 0x51, 0xef, 0xF3, 0x54, 0xb9, 0x84, 0x00, 0x30, 0x38, 0x00, 0x08, 0x10, 0xE0, 0x22, 0x40, 0xa5, 0x26, 0x01, 0x00, 0x00, 0x80, }; static const u8 hdmiphy_conf74_25[32] = { 0x01, 0x05, 0x00, 0xd8, 0x10, 0x9c, 0xf8, 0x40, 0x6a, 0x10, 0x01, 0x51, 0xff, 0xf1, 0x54, 0xba, 0x84, 0x00, 0x10, 0x38, 0x00, 0x08, 0x10, 0xe0, 0x22, 0x40, 0xa4, 0x26, 0x01, 0x00, 0x00, 0x80, }; static const u8 hdmiphy_conf148_5[32] = { 0x01, 0x05, 0x00, 0xD8, 0x10, 0x9C, 0xf8, 0x40, 0x6A, 0x18, 0x00, 0x51, 0xff, 0xF1, 0x54, 0xba, 0x84, 0x00, 0x10, 0x38, 0x00, 0x08, 0x10, 0xE0, 0x22, 0x40, 0xa4, 0x26, 0x02, 0x00, 0x00, 0x80, }; const struct hdmiphy_conf hdmiphy_conf[] = { { V4L2_DV_480P59_94, hdmiphy_conf27 }, { V4L2_DV_1080P30, hdmiphy_conf74_175 }, { V4L2_DV_720P59_94, hdmiphy_conf74_175 }, { V4L2_DV_720P60, hdmiphy_conf74_25 }, { V4L2_DV_1080P50, hdmiphy_conf148_5 }, { V4L2_DV_1080P60, hdmiphy_conf148_5 }, { V4L2_DV_1080I60, hdmiphy_conf74_25 }, }; const int hdmiphy_conf_cnt = ARRAY_SIZE(hdmiphy_conf);
gpl-2.0
lab11/bluetooth-next
drivers/misc/sgi-gru/gruhandles.c
719
5428
/* * GRU KERNEL MCS INSTRUCTIONS * * Copyright (c) 2008 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; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/kernel.h> #include "gru.h" #include "grulib.h" #include "grutables.h" /* 10 sec */ #ifdef CONFIG_IA64 #include <asm/processor.h> #define GRU_OPERATION_TIMEOUT (((cycles_t) local_cpu_data->itc_freq)*10) #define CLKS2NSEC(c) ((c) *1000000000 / local_cpu_data->itc_freq) #else #include <asm/tsc.h> #define GRU_OPERATION_TIMEOUT ((cycles_t) tsc_khz*10*1000) #define CLKS2NSEC(c) ((c) * 1000000 / tsc_khz) #endif /* Extract the status field from a kernel handle */ #define GET_MSEG_HANDLE_STATUS(h) (((*(unsigned long *)(h)) >> 16) & 3) struct mcs_op_statistic mcs_op_statistics[mcsop_last]; static void update_mcs_stats(enum mcs_op op, unsigned long clks) { unsigned long nsec; nsec = CLKS2NSEC(clks); atomic_long_inc(&mcs_op_statistics[op].count); atomic_long_add(nsec, &mcs_op_statistics[op].total); if (mcs_op_statistics[op].max < nsec) mcs_op_statistics[op].max = nsec; } static void start_instruction(void *h) { unsigned long *w0 = h; wmb(); /* setting CMD/STATUS bits must be last */ *w0 = *w0 | 0x20001; gru_flush_cache(h); } static void report_instruction_timeout(void *h) { unsigned long goff = GSEGPOFF((unsigned long)h); char *id = "???"; if (TYPE_IS(CCH, goff)) id = "CCH"; else if (TYPE_IS(TGH, goff)) id = "TGH"; else if (TYPE_IS(TFH, goff)) id = "TFH"; panic(KERN_ALERT "GRU %p (%s) is malfunctioning\n", h, id); } static int wait_instruction_complete(void *h, enum mcs_op opc) { int status; unsigned long start_time = get_cycles(); while (1) { cpu_relax(); status = GET_MSEG_HANDLE_STATUS(h); if (status != CCHSTATUS_ACTIVE) break; if (GRU_OPERATION_TIMEOUT < (get_cycles() - start_time)) { report_instruction_timeout(h); start_time = get_cycles(); } } if (gru_options & OPT_STATS) update_mcs_stats(opc, get_cycles() - start_time); return status; } int cch_allocate(struct gru_context_configuration_handle *cch) { int ret; cch->opc = CCHOP_ALLOCATE; start_instruction(cch); ret = wait_instruction_complete(cch, cchop_allocate); /* * Stop speculation into the GSEG being mapped by the previous ALLOCATE. * The GSEG memory does not exist until the ALLOCATE completes. */ sync_core(); return ret; } int cch_start(struct gru_context_configuration_handle *cch) { cch->opc = CCHOP_START; start_instruction(cch); return wait_instruction_complete(cch, cchop_start); } int cch_interrupt(struct gru_context_configuration_handle *cch) { cch->opc = CCHOP_INTERRUPT; start_instruction(cch); return wait_instruction_complete(cch, cchop_interrupt); } int cch_deallocate(struct gru_context_configuration_handle *cch) { int ret; cch->opc = CCHOP_DEALLOCATE; start_instruction(cch); ret = wait_instruction_complete(cch, cchop_deallocate); /* * Stop speculation into the GSEG being unmapped by the previous * DEALLOCATE. */ sync_core(); return ret; } int cch_interrupt_sync(struct gru_context_configuration_handle *cch) { cch->opc = CCHOP_INTERRUPT_SYNC; start_instruction(cch); return wait_instruction_complete(cch, cchop_interrupt_sync); } int tgh_invalidate(struct gru_tlb_global_handle *tgh, unsigned long vaddr, unsigned long vaddrmask, int asid, int pagesize, int global, int n, unsigned short ctxbitmap) { tgh->vaddr = vaddr; tgh->asid = asid; tgh->pagesize = pagesize; tgh->n = n; tgh->global = global; tgh->vaddrmask = vaddrmask; tgh->ctxbitmap = ctxbitmap; tgh->opc = TGHOP_TLBINV; start_instruction(tgh); return wait_instruction_complete(tgh, tghop_invalidate); } int tfh_write_only(struct gru_tlb_fault_handle *tfh, unsigned long paddr, int gaa, unsigned long vaddr, int asid, int dirty, int pagesize) { tfh->fillasid = asid; tfh->fillvaddr = vaddr; tfh->pfn = paddr >> GRU_PADDR_SHIFT; tfh->gaa = gaa; tfh->dirty = dirty; tfh->pagesize = pagesize; tfh->opc = TFHOP_WRITE_ONLY; start_instruction(tfh); return wait_instruction_complete(tfh, tfhop_write_only); } void tfh_write_restart(struct gru_tlb_fault_handle *tfh, unsigned long paddr, int gaa, unsigned long vaddr, int asid, int dirty, int pagesize) { tfh->fillasid = asid; tfh->fillvaddr = vaddr; tfh->pfn = paddr >> GRU_PADDR_SHIFT; tfh->gaa = gaa; tfh->dirty = dirty; tfh->pagesize = pagesize; tfh->opc = TFHOP_WRITE_RESTART; start_instruction(tfh); } void tfh_user_polling_mode(struct gru_tlb_fault_handle *tfh) { tfh->opc = TFHOP_USER_POLLING_MODE; start_instruction(tfh); } void tfh_exception(struct gru_tlb_fault_handle *tfh) { tfh->opc = TFHOP_EXCEPTION; start_instruction(tfh); }
gpl-2.0
NathanAtSamraksh/dart-linux
drivers/net/wireless/hostap/hostap_cs.c
975
18166
#define PRISM2_PCCARD #include <linux/module.h> #include <linux/if.h> #include <linux/slab.h> #include <linux/wait.h> #include <linux/timer.h> #include <linux/skbuff.h> #include <linux/netdevice.h> #include <linux/workqueue.h> #include <linux/wireless.h> #include <net/iw_handler.h> #include <pcmcia/cistpl.h> #include <pcmcia/cisreg.h> #include <pcmcia/ds.h> #include <asm/io.h> #include "hostap_wlan.h" static char *dev_info = "hostap_cs"; MODULE_AUTHOR("Jouni Malinen"); MODULE_DESCRIPTION("Support for Intersil Prism2-based 802.11 wireless LAN " "cards (PC Card)."); MODULE_SUPPORTED_DEVICE("Intersil Prism2-based WLAN cards (PC Card)"); MODULE_LICENSE("GPL"); static int ignore_cis_vcc; module_param(ignore_cis_vcc, int, 0444); MODULE_PARM_DESC(ignore_cis_vcc, "Ignore broken CIS VCC entry"); /* struct local_info::hw_priv */ struct hostap_cs_priv { struct pcmcia_device *link; int sandisk_connectplus; }; #ifdef PRISM2_IO_DEBUG static inline void hfa384x_outb_debug(struct net_device *dev, int a, u8 v) { struct hostap_interface *iface; local_info_t *local; unsigned long flags; iface = netdev_priv(dev); local = iface->local; spin_lock_irqsave(&local->lock, flags); prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_OUTB, a, v); outb(v, dev->base_addr + a); spin_unlock_irqrestore(&local->lock, flags); } static inline u8 hfa384x_inb_debug(struct net_device *dev, int a) { struct hostap_interface *iface; local_info_t *local; unsigned long flags; u8 v; iface = netdev_priv(dev); local = iface->local; spin_lock_irqsave(&local->lock, flags); v = inb(dev->base_addr + a); prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_INB, a, v); spin_unlock_irqrestore(&local->lock, flags); return v; } static inline void hfa384x_outw_debug(struct net_device *dev, int a, u16 v) { struct hostap_interface *iface; local_info_t *local; unsigned long flags; iface = netdev_priv(dev); local = iface->local; spin_lock_irqsave(&local->lock, flags); prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_OUTW, a, v); outw(v, dev->base_addr + a); spin_unlock_irqrestore(&local->lock, flags); } static inline u16 hfa384x_inw_debug(struct net_device *dev, int a) { struct hostap_interface *iface; local_info_t *local; unsigned long flags; u16 v; iface = netdev_priv(dev); local = iface->local; spin_lock_irqsave(&local->lock, flags); v = inw(dev->base_addr + a); prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_INW, a, v); spin_unlock_irqrestore(&local->lock, flags); return v; } static inline void hfa384x_outsw_debug(struct net_device *dev, int a, u8 *buf, int wc) { struct hostap_interface *iface; local_info_t *local; unsigned long flags; iface = netdev_priv(dev); local = iface->local; spin_lock_irqsave(&local->lock, flags); prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_OUTSW, a, wc); outsw(dev->base_addr + a, buf, wc); spin_unlock_irqrestore(&local->lock, flags); } static inline void hfa384x_insw_debug(struct net_device *dev, int a, u8 *buf, int wc) { struct hostap_interface *iface; local_info_t *local; unsigned long flags; iface = netdev_priv(dev); local = iface->local; spin_lock_irqsave(&local->lock, flags); prism2_io_debug_add(dev, PRISM2_IO_DEBUG_CMD_INSW, a, wc); insw(dev->base_addr + a, buf, wc); spin_unlock_irqrestore(&local->lock, flags); } #define HFA384X_OUTB(v,a) hfa384x_outb_debug(dev, (a), (v)) #define HFA384X_INB(a) hfa384x_inb_debug(dev, (a)) #define HFA384X_OUTW(v,a) hfa384x_outw_debug(dev, (a), (v)) #define HFA384X_INW(a) hfa384x_inw_debug(dev, (a)) #define HFA384X_OUTSW(a, buf, wc) hfa384x_outsw_debug(dev, (a), (buf), (wc)) #define HFA384X_INSW(a, buf, wc) hfa384x_insw_debug(dev, (a), (buf), (wc)) #else /* PRISM2_IO_DEBUG */ #define HFA384X_OUTB(v,a) outb((v), dev->base_addr + (a)) #define HFA384X_INB(a) inb(dev->base_addr + (a)) #define HFA384X_OUTW(v,a) outw((v), dev->base_addr + (a)) #define HFA384X_INW(a) inw(dev->base_addr + (a)) #define HFA384X_INSW(a, buf, wc) insw(dev->base_addr + (a), buf, wc) #define HFA384X_OUTSW(a, buf, wc) outsw(dev->base_addr + (a), buf, wc) #endif /* PRISM2_IO_DEBUG */ static int hfa384x_from_bap(struct net_device *dev, u16 bap, void *buf, int len) { u16 d_off; u16 *pos; d_off = (bap == 1) ? HFA384X_DATA1_OFF : HFA384X_DATA0_OFF; pos = (u16 *) buf; if (len / 2) HFA384X_INSW(d_off, buf, len / 2); pos += len / 2; if (len & 1) *((char *) pos) = HFA384X_INB(d_off); return 0; } static int hfa384x_to_bap(struct net_device *dev, u16 bap, void *buf, int len) { u16 d_off; u16 *pos; d_off = (bap == 1) ? HFA384X_DATA1_OFF : HFA384X_DATA0_OFF; pos = (u16 *) buf; if (len / 2) HFA384X_OUTSW(d_off, buf, len / 2); pos += len / 2; if (len & 1) HFA384X_OUTB(*((char *) pos), d_off); return 0; } /* FIX: This might change at some point.. */ #include "hostap_hw.c" static void prism2_detach(struct pcmcia_device *p_dev); static void prism2_release(u_long arg); static int prism2_config(struct pcmcia_device *link); static int prism2_pccard_card_present(local_info_t *local) { struct hostap_cs_priv *hw_priv = local->hw_priv; if (hw_priv != NULL && hw_priv->link != NULL && pcmcia_dev_present(hw_priv->link)) return 1; return 0; } /* * SanDisk CompactFlash WLAN Flashcard - Product Manual v1.0 * Document No. 20-10-00058, January 2004 * http://www.sandisk.com/pdf/industrial/ProdManualCFWLANv1.0.pdf */ #define SANDISK_WLAN_ACTIVATION_OFF 0x40 #define SANDISK_HCR_OFF 0x42 static void sandisk_set_iobase(local_info_t *local) { int res; struct hostap_cs_priv *hw_priv = local->hw_priv; res = pcmcia_write_config_byte(hw_priv->link, 0x10, hw_priv->link->resource[0]->start & 0x00ff); if (res != 0) { printk(KERN_DEBUG "Prism3 SanDisk - failed to set I/O base 0 -" " res=%d\n", res); } udelay(10); res = pcmcia_write_config_byte(hw_priv->link, 0x12, (hw_priv->link->resource[0]->start >> 8) & 0x00ff); if (res != 0) { printk(KERN_DEBUG "Prism3 SanDisk - failed to set I/O base 1 -" " res=%d\n", res); } } static void sandisk_write_hcr(local_info_t *local, int hcr) { struct net_device *dev = local->dev; int i; HFA384X_OUTB(0x80, SANDISK_WLAN_ACTIVATION_OFF); udelay(50); for (i = 0; i < 10; i++) { HFA384X_OUTB(hcr, SANDISK_HCR_OFF); } udelay(55); HFA384X_OUTB(0x45, SANDISK_WLAN_ACTIVATION_OFF); } static int sandisk_enable_wireless(struct net_device *dev) { int res, ret = 0; struct hostap_interface *iface = netdev_priv(dev); local_info_t *local = iface->local; struct hostap_cs_priv *hw_priv = local->hw_priv; if (resource_size(hw_priv->link->resource[0]) < 0x42) { /* Not enough ports to be SanDisk multi-function card */ ret = -ENODEV; goto done; } if (hw_priv->link->manf_id != 0xd601 || hw_priv->link->card_id != 0x0101) { /* No SanDisk manfid found */ ret = -ENODEV; goto done; } if (hw_priv->link->socket->functions < 2) { /* No multi-function links found */ ret = -ENODEV; goto done; } printk(KERN_DEBUG "%s: Multi-function SanDisk ConnectPlus detected" " - using vendor-specific initialization\n", dev->name); hw_priv->sandisk_connectplus = 1; res = pcmcia_write_config_byte(hw_priv->link, CISREG_COR, COR_SOFT_RESET); if (res != 0) { printk(KERN_DEBUG "%s: SanDisk - COR sreset failed (%d)\n", dev->name, res); goto done; } mdelay(5); /* * Do not enable interrupts here to avoid some bogus events. Interrupts * will be enabled during the first cor_sreset call. */ res = pcmcia_write_config_byte(hw_priv->link, CISREG_COR, (COR_LEVEL_REQ | 0x8 | COR_ADDR_DECODE | COR_FUNC_ENA)); if (res != 0) { printk(KERN_DEBUG "%s: SanDisk - COR sreset failed (%d)\n", dev->name, res); goto done; } mdelay(5); sandisk_set_iobase(local); HFA384X_OUTB(0xc5, SANDISK_WLAN_ACTIVATION_OFF); udelay(10); HFA384X_OUTB(0x4b, SANDISK_WLAN_ACTIVATION_OFF); udelay(10); done: return ret; } static void prism2_pccard_cor_sreset(local_info_t *local) { int res; u8 val; struct hostap_cs_priv *hw_priv = local->hw_priv; if (!prism2_pccard_card_present(local)) return; res = pcmcia_read_config_byte(hw_priv->link, CISREG_COR, &val); if (res != 0) { printk(KERN_DEBUG "prism2_pccard_cor_sreset failed 1 (%d)\n", res); return; } printk(KERN_DEBUG "prism2_pccard_cor_sreset: original COR %02x\n", val); val |= COR_SOFT_RESET; res = pcmcia_write_config_byte(hw_priv->link, CISREG_COR, val); if (res != 0) { printk(KERN_DEBUG "prism2_pccard_cor_sreset failed 2 (%d)\n", res); return; } mdelay(hw_priv->sandisk_connectplus ? 5 : 2); val &= ~COR_SOFT_RESET; if (hw_priv->sandisk_connectplus) val |= COR_IREQ_ENA; res = pcmcia_write_config_byte(hw_priv->link, CISREG_COR, val); if (res != 0) { printk(KERN_DEBUG "prism2_pccard_cor_sreset failed 3 (%d)\n", res); return; } mdelay(hw_priv->sandisk_connectplus ? 5 : 2); if (hw_priv->sandisk_connectplus) sandisk_set_iobase(local); } static void prism2_pccard_genesis_reset(local_info_t *local, int hcr) { int res; u8 old_cor; struct hostap_cs_priv *hw_priv = local->hw_priv; if (!prism2_pccard_card_present(local)) return; if (hw_priv->sandisk_connectplus) { sandisk_write_hcr(local, hcr); return; } res = pcmcia_read_config_byte(hw_priv->link, CISREG_COR, &old_cor); if (res != 0) { printk(KERN_DEBUG "%s failed 1 (%d)\n", __func__, res); return; } printk(KERN_DEBUG "%s: original COR %02x\n", __func__, old_cor); res = pcmcia_write_config_byte(hw_priv->link, CISREG_COR, old_cor | COR_SOFT_RESET); if (res != 0) { printk(KERN_DEBUG "%s failed 2 (%d)\n", __func__, res); return; } mdelay(10); /* Setup Genesis mode */ res = pcmcia_write_config_byte(hw_priv->link, CISREG_CCSR, hcr); if (res != 0) { printk(KERN_DEBUG "%s failed 3 (%d)\n", __func__, res); return; } mdelay(10); res = pcmcia_write_config_byte(hw_priv->link, CISREG_COR, old_cor & ~COR_SOFT_RESET); if (res != 0) { printk(KERN_DEBUG "%s failed 4 (%d)\n", __func__, res); return; } mdelay(10); } static struct prism2_helper_functions prism2_pccard_funcs = { .card_present = prism2_pccard_card_present, .cor_sreset = prism2_pccard_cor_sreset, .genesis_reset = prism2_pccard_genesis_reset, .hw_type = HOSTAP_HW_PCCARD, }; /* allocate local data and register with CardServices * initialize dev_link structure, but do not configure the card yet */ static int hostap_cs_probe(struct pcmcia_device *p_dev) { int ret; PDEBUG(DEBUG_HW, "%s: setting Vcc=33 (constant)\n", dev_info); ret = prism2_config(p_dev); if (ret) { PDEBUG(DEBUG_EXTRA, "prism2_config() failed\n"); } return ret; } static void prism2_detach(struct pcmcia_device *link) { PDEBUG(DEBUG_FLOW, "prism2_detach\n"); prism2_release((u_long)link); /* release net devices */ if (link->priv) { struct hostap_cs_priv *hw_priv; struct net_device *dev; struct hostap_interface *iface; dev = link->priv; iface = netdev_priv(dev); hw_priv = iface->local->hw_priv; prism2_free_local_data(dev); kfree(hw_priv); } } static int prism2_config_check(struct pcmcia_device *p_dev, void *priv_data) { if (p_dev->config_index == 0) return -EINVAL; return pcmcia_request_io(p_dev); } static int prism2_config(struct pcmcia_device *link) { struct net_device *dev; struct hostap_interface *iface; local_info_t *local; int ret = 1; struct hostap_cs_priv *hw_priv; unsigned long flags; PDEBUG(DEBUG_FLOW, "prism2_config()\n"); hw_priv = kzalloc(sizeof(*hw_priv), GFP_KERNEL); if (hw_priv == NULL) { ret = -ENOMEM; goto failed; } /* Look for an appropriate configuration table entry in the CIS */ link->config_flags |= CONF_AUTO_SET_VPP | CONF_AUTO_AUDIO | CONF_AUTO_CHECK_VCC | CONF_AUTO_SET_IO | CONF_ENABLE_IRQ; if (ignore_cis_vcc) link->config_flags &= ~CONF_AUTO_CHECK_VCC; ret = pcmcia_loop_config(link, prism2_config_check, NULL); if (ret) { if (!ignore_cis_vcc) printk(KERN_ERR "GetNextTuple(): No matching " "CIS configuration. Maybe you need the " "ignore_cis_vcc=1 parameter.\n"); goto failed; } /* Need to allocate net_device before requesting IRQ handler */ dev = prism2_init_local_data(&prism2_pccard_funcs, 0, &link->dev); if (dev == NULL) goto failed; link->priv = dev; iface = netdev_priv(dev); local = iface->local; local->hw_priv = hw_priv; hw_priv->link = link; /* * We enable IRQ here, but IRQ handler will not proceed * until dev->base_addr is set below. This protect us from * receive interrupts when driver is not initialized. */ ret = pcmcia_request_irq(link, prism2_interrupt); if (ret) goto failed; ret = pcmcia_enable_device(link); if (ret) goto failed; spin_lock_irqsave(&local->irq_init_lock, flags); dev->irq = link->irq; dev->base_addr = link->resource[0]->start; spin_unlock_irqrestore(&local->irq_init_lock, flags); local->shutdown = 0; sandisk_enable_wireless(dev); ret = prism2_hw_config(dev, 1); if (!ret) ret = hostap_hw_ready(dev); return ret; failed: kfree(hw_priv); prism2_release((u_long)link); return ret; } static void prism2_release(u_long arg) { struct pcmcia_device *link = (struct pcmcia_device *)arg; PDEBUG(DEBUG_FLOW, "prism2_release\n"); if (link->priv) { struct net_device *dev = link->priv; struct hostap_interface *iface; iface = netdev_priv(dev); prism2_hw_shutdown(dev, 0); iface->local->shutdown = 1; } pcmcia_disable_device(link); PDEBUG(DEBUG_FLOW, "release - done\n"); } static int hostap_cs_suspend(struct pcmcia_device *link) { struct net_device *dev = (struct net_device *) link->priv; int dev_open = 0; struct hostap_interface *iface = NULL; if (!dev) return -ENODEV; iface = netdev_priv(dev); PDEBUG(DEBUG_EXTRA, "%s: CS_EVENT_PM_SUSPEND\n", dev_info); if (iface && iface->local) dev_open = iface->local->num_dev_open > 0; if (dev_open) { netif_stop_queue(dev); netif_device_detach(dev); } prism2_suspend(dev); return 0; } static int hostap_cs_resume(struct pcmcia_device *link) { struct net_device *dev = (struct net_device *) link->priv; int dev_open = 0; struct hostap_interface *iface = NULL; if (!dev) return -ENODEV; iface = netdev_priv(dev); PDEBUG(DEBUG_EXTRA, "%s: CS_EVENT_PM_RESUME\n", dev_info); if (iface && iface->local) dev_open = iface->local->num_dev_open > 0; prism2_hw_shutdown(dev, 1); prism2_hw_config(dev, dev_open ? 0 : 1); if (dev_open) { netif_device_attach(dev); netif_start_queue(dev); } return 0; } static const struct pcmcia_device_id hostap_cs_ids[] = { PCMCIA_DEVICE_MANF_CARD(0x000b, 0x7100), PCMCIA_DEVICE_MANF_CARD(0x000b, 0x7300), PCMCIA_DEVICE_MANF_CARD(0x0101, 0x0777), PCMCIA_DEVICE_MANF_CARD(0x0126, 0x8000), PCMCIA_DEVICE_MANF_CARD(0x0138, 0x0002), PCMCIA_DEVICE_MANF_CARD(0x01bf, 0x3301), PCMCIA_DEVICE_MANF_CARD(0x0250, 0x0002), PCMCIA_DEVICE_MANF_CARD(0x026f, 0x030b), PCMCIA_DEVICE_MANF_CARD(0x0274, 0x1612), PCMCIA_DEVICE_MANF_CARD(0x0274, 0x1613), PCMCIA_DEVICE_MANF_CARD(0x028a, 0x0002), PCMCIA_DEVICE_MANF_CARD(0x02aa, 0x0002), PCMCIA_DEVICE_MANF_CARD(0x02d2, 0x0001), PCMCIA_DEVICE_MANF_CARD(0x50c2, 0x0001), PCMCIA_DEVICE_MANF_CARD(0x50c2, 0x7300), /* PCMCIA_DEVICE_MANF_CARD(0xc00f, 0x0000), conflict with pcnet_cs */ PCMCIA_DEVICE_MANF_CARD(0xc250, 0x0002), PCMCIA_DEVICE_MANF_CARD(0xd601, 0x0002), PCMCIA_DEVICE_MANF_CARD(0xd601, 0x0005), PCMCIA_DEVICE_MANF_CARD(0xd601, 0x0010), PCMCIA_DEVICE_MANF_CARD(0x0126, 0x0002), PCMCIA_DEVICE_MANF_CARD_PROD_ID1(0xd601, 0x0005, "ADLINK 345 CF", 0x2d858104), PCMCIA_DEVICE_MANF_CARD_PROD_ID1(0x0156, 0x0002, "INTERSIL", 0x74c5e40d), PCMCIA_DEVICE_MANF_CARD_PROD_ID1(0x0156, 0x0002, "Intersil", 0x4b801a17), PCMCIA_DEVICE_MANF_CARD_PROD_ID3(0x0156, 0x0002, "Version 01.02", 0x4b74baa0), PCMCIA_MFC_DEVICE_PROD_ID12(0, "SanDisk", "ConnectPlus", 0x7a954bd9, 0x74be00c6), PCMCIA_DEVICE_PROD_ID123( "Addtron", "AWP-100 Wireless PCMCIA", "Version 01.02", 0xe6ec52ce, 0x08649af2, 0x4b74baa0), PCMCIA_DEVICE_PROD_ID123( "Canon", "Wireless LAN CF Card K30225", "Version 01.00", 0x96ef6fe2, 0x263fcbab, 0xa57adb8c), PCMCIA_DEVICE_PROD_ID123( "D", "Link DWL-650 11Mbps WLAN Card", "Version 01.02", 0x71b18589, 0xb6f1b0ab, 0x4b74baa0), PCMCIA_DEVICE_PROD_ID123( "Instant Wireless ", " Network PC CARD", "Version 01.02", 0x11d901af, 0x6e9bd926, 0x4b74baa0), PCMCIA_DEVICE_PROD_ID123( "SMC", "SMC2632W", "Version 01.02", 0xc4f8b18b, 0x474a1f2a, 0x4b74baa0), PCMCIA_DEVICE_PROD_ID12("BUFFALO", "WLI-CF-S11G", 0x2decece3, 0x82067c18), PCMCIA_DEVICE_PROD_ID12("Compaq", "WL200_11Mbps_Wireless_PCI_Card", 0x54f7c49c, 0x15a75e5b), PCMCIA_DEVICE_PROD_ID12("INTERSIL", "HFA384x/IEEE", 0x74c5e40d, 0xdb472a18), PCMCIA_DEVICE_PROD_ID12("Linksys", "Wireless CompactFlash Card", 0x0733cc81, 0x0c52f395), PCMCIA_DEVICE_PROD_ID12( "ZoomAir 11Mbps High", "Rate wireless Networking", 0x273fe3db, 0x32a1eaee), PCMCIA_DEVICE_PROD_ID12("NETGEAR MA401 Wireless PC", "Card", 0xa37434e9, 0x9762e8f1), PCMCIA_DEVICE_PROD_ID123( "Pretec", "CompactWLAN Card 802.11b", "2.5", 0x1cadd3e5, 0xe697636c, 0x7a5bfcf1), PCMCIA_DEVICE_PROD_ID123( "U.S. Robotics", "IEEE 802.11b PC-CARD", "Version 01.02", 0xc7b8df9d, 0x1700d087, 0x4b74baa0), PCMCIA_DEVICE_PROD_ID123( "Allied Telesyn", "AT-WCL452 Wireless PCMCIA Radio", "Ver. 1.00", 0x5cd01705, 0x4271660f, 0x9d08ee12), PCMCIA_DEVICE_PROD_ID123( "Wireless LAN" , "11Mbps PC Card", "Version 01.02", 0x4b8870ff, 0x70e946d1, 0x4b74baa0), PCMCIA_DEVICE_PROD_ID3("HFA3863", 0x355cb092), PCMCIA_DEVICE_PROD_ID3("ISL37100P", 0x630d52b2), PCMCIA_DEVICE_PROD_ID3("ISL37101P-10", 0xdd97a26b), PCMCIA_DEVICE_PROD_ID3("ISL37300P", 0xc9049a39), PCMCIA_DEVICE_NULL }; MODULE_DEVICE_TABLE(pcmcia, hostap_cs_ids); static struct pcmcia_driver hostap_driver = { .name = "hostap_cs", .probe = hostap_cs_probe, .remove = prism2_detach, .owner = THIS_MODULE, .id_table = hostap_cs_ids, .suspend = hostap_cs_suspend, .resume = hostap_cs_resume, }; module_pcmcia_driver(hostap_driver);
gpl-2.0
nadanomics/linux
drivers/gpio/gpio-xtensa.c
975
4807
/* * Copyright (C) 2013 TangoTec Ltd. * Author: Baruch Siach <baruch@tkos.co.il> * * 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. * * Driver for the Xtensa LX4 GPIO32 Option * * Documentation: Xtensa LX4 Microprocessor Data Book, Section 2.22 * * GPIO32 is a standard optional extension to the Xtensa architecture core that * provides preconfigured output and input ports for intra SoC signaling. The * GPIO32 option is implemented as 32bit Tensilica Instruction Extension (TIE) * output state called EXPSTATE, and 32bit input wire called IMPWIRE. This * driver treats input and output states as two distinct devices. * * Access to GPIO32 specific instructions is controlled by the CPENABLE * (Coprocessor Enable Bits) register. By default Xtensa Linux startup code * disables access to all coprocessors. This driver sets the CPENABLE bit * corresponding to GPIO32 before any GPIO32 specific instruction, and restores * CPENABLE state after that. * * This driver is currently incompatible with SMP. The GPIO32 extension is not * guaranteed to be available in all cores. Moreover, each core controls a * different set of IO wires. A theoretical SMP aware version of this driver * would need to have a per core workqueue to do the actual GPIO manipulation. */ #include <linux/err.h> #include <linux/module.h> #include <linux/gpio.h> #include <linux/bitops.h> #include <linux/platform_device.h> #include <asm/coprocessor.h> /* CPENABLE read/write macros */ #ifndef XCHAL_CP_ID_XTIOP #error GPIO32 option is not enabled for your xtensa core variant #endif #if XCHAL_HAVE_CP static inline unsigned long enable_cp(unsigned long *cpenable) { unsigned long flags; local_irq_save(flags); RSR_CPENABLE(*cpenable); WSR_CPENABLE(*cpenable | BIT(XCHAL_CP_ID_XTIOP)); return flags; } static inline void disable_cp(unsigned long flags, unsigned long cpenable) { WSR_CPENABLE(cpenable); local_irq_restore(flags); } #else static inline unsigned long enable_cp(unsigned long *cpenable) { *cpenable = 0; /* avoid uninitialized value warning */ return 0; } static inline void disable_cp(unsigned long flags, unsigned long cpenable) { } #endif /* XCHAL_HAVE_CP */ static int xtensa_impwire_get_direction(struct gpio_chip *gc, unsigned offset) { return 1; /* input only */ } static int xtensa_impwire_get_value(struct gpio_chip *gc, unsigned offset) { unsigned long flags, saved_cpenable; u32 impwire; flags = enable_cp(&saved_cpenable); __asm__ __volatile__("read_impwire %0" : "=a" (impwire)); disable_cp(flags, saved_cpenable); return !!(impwire & BIT(offset)); } static void xtensa_impwire_set_value(struct gpio_chip *gc, unsigned offset, int value) { BUG(); /* output only; should never be called */ } static int xtensa_expstate_get_direction(struct gpio_chip *gc, unsigned offset) { return 0; /* output only */ } static int xtensa_expstate_get_value(struct gpio_chip *gc, unsigned offset) { unsigned long flags, saved_cpenable; u32 expstate; flags = enable_cp(&saved_cpenable); __asm__ __volatile__("rur.expstate %0" : "=a" (expstate)); disable_cp(flags, saved_cpenable); return !!(expstate & BIT(offset)); } static void xtensa_expstate_set_value(struct gpio_chip *gc, unsigned offset, int value) { unsigned long flags, saved_cpenable; u32 mask = BIT(offset); u32 val = value ? BIT(offset) : 0; flags = enable_cp(&saved_cpenable); __asm__ __volatile__("wrmsk_expstate %0, %1" :: "a" (val), "a" (mask)); disable_cp(flags, saved_cpenable); } static struct gpio_chip impwire_chip = { .label = "impwire", .base = -1, .ngpio = 32, .get_direction = xtensa_impwire_get_direction, .get = xtensa_impwire_get_value, .set = xtensa_impwire_set_value, }; static struct gpio_chip expstate_chip = { .label = "expstate", .base = -1, .ngpio = 32, .get_direction = xtensa_expstate_get_direction, .get = xtensa_expstate_get_value, .set = xtensa_expstate_set_value, }; static int xtensa_gpio_probe(struct platform_device *pdev) { int ret; ret = gpiochip_add(&impwire_chip); if (ret) return ret; return gpiochip_add(&expstate_chip); } static struct platform_driver xtensa_gpio_driver = { .driver = { .name = "xtensa-gpio", }, .probe = xtensa_gpio_probe, }; static int __init xtensa_gpio_init(void) { struct platform_device *pdev; pdev = platform_device_register_simple("xtensa-gpio", 0, NULL, 0); if (IS_ERR(pdev)) return PTR_ERR(pdev); return platform_driver_register(&xtensa_gpio_driver); } device_initcall(xtensa_gpio_init); MODULE_AUTHOR("Baruch Siach <baruch@tkos.co.il>"); MODULE_DESCRIPTION("Xtensa LX4 GPIO32 driver"); MODULE_LICENSE("GPL");
gpl-2.0
dianlujitao/CAF_kernel_msm-3.10
arch/mips/netlogic/xlp/wakeup.c
1999
4323
/* * Copyright 2003-2011 NetLogic Microsystems, Inc. (NetLogic). 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 NetLogic * license below: * * 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. * * THIS SOFTWARE IS PROVIDED BY NETLOGIC ``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 NETLOGIC OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <linux/init.h> #include <linux/kernel.h> #include <linux/threads.h> #include <asm/asm.h> #include <asm/asm-offsets.h> #include <asm/mipsregs.h> #include <asm/addrspace.h> #include <asm/string.h> #include <asm/netlogic/haldefs.h> #include <asm/netlogic/common.h> #include <asm/netlogic/mips-extns.h> #include <asm/netlogic/xlp-hal/iomap.h> #include <asm/netlogic/xlp-hal/pic.h> #include <asm/netlogic/xlp-hal/xlp.h> #include <asm/netlogic/xlp-hal/sys.h> static int xlp_wakeup_core(uint64_t sysbase, int node, int core) { uint32_t coremask, value; int count; coremask = (1 << core); /* Enable CPU clock */ value = nlm_read_sys_reg(sysbase, SYS_CORE_DFS_DIS_CTRL); value &= ~coremask; nlm_write_sys_reg(sysbase, SYS_CORE_DFS_DIS_CTRL, value); /* Remove CPU Reset */ value = nlm_read_sys_reg(sysbase, SYS_CPU_RESET); value &= ~coremask; nlm_write_sys_reg(sysbase, SYS_CPU_RESET, value); /* Poll for CPU to mark itself coherent */ count = 100000; do { value = nlm_read_sys_reg(sysbase, SYS_CPU_NONCOHERENT_MODE); } while ((value & coremask) != 0 && --count > 0); return count != 0; } static void xlp_enable_secondary_cores(const cpumask_t *wakeup_mask) { struct nlm_soc_info *nodep; uint64_t syspcibase; uint32_t syscoremask; int core, n, cpu, count, val; for (n = 0; n < NLM_NR_NODES; n++) { syspcibase = nlm_get_sys_pcibase(n); if (nlm_read_reg(syspcibase, 0) == 0xffffffff) break; /* read cores in reset from SYS */ if (n != 0) nlm_node_init(n); nodep = nlm_get_node(n); syscoremask = nlm_read_sys_reg(nodep->sysbase, SYS_CPU_RESET); /* The boot cpu */ if (n == 0) { syscoremask |= 1; nodep->coremask = 1; } for (core = 0; core < NLM_CORES_PER_NODE; core++) { /* we will be on node 0 core 0 */ if (n == 0 && core == 0) continue; /* see if the core exists */ if ((syscoremask & (1 << core)) == 0) continue; /* see if at least the first hw thread is enabled */ cpu = (n * NLM_CORES_PER_NODE + core) * NLM_THREADS_PER_CORE; if (!cpumask_test_cpu(cpu, wakeup_mask)) continue; /* wake up the core */ if (!xlp_wakeup_core(nodep->sysbase, n, core)) continue; /* core is up */ nodep->coremask |= 1u << core; /* spin until the first hw thread sets its ready */ count = 0x20000000; do { val = *(volatile int *)&nlm_cpu_ready[cpu]; } while (val == 0 && --count > 0); } } } void xlp_wakeup_secondary_cpus() { /* * In case of u-boot, the secondaries are in reset * first wakeup core 0 threads */ xlp_boot_core0_siblings(); /* now get other cores out of reset */ xlp_enable_secondary_cores(&nlm_cpumask); }
gpl-2.0
Stane1983/amlogic-m6_m8
sound/soc/codecs/max98088.c
1999
76796
/* * max98088.c -- MAX98088 ALSA SoC Audio driver * * Copyright 2010 Maxim Integrated Products * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/pm.h> #include <linux/i2c.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/soc.h> #include <sound/initval.h> #include <sound/tlv.h> #include <linux/slab.h> #include <asm/div64.h> #include <sound/max98088.h> #include "max98088.h" enum max98088_type { MAX98088, MAX98089, }; struct max98088_cdata { unsigned int rate; unsigned int fmt; int eq_sel; }; struct max98088_priv { enum max98088_type devtype; struct max98088_pdata *pdata; unsigned int sysclk; struct max98088_cdata dai[2]; int eq_textcnt; const char **eq_texts; struct soc_enum eq_enum; u8 ina_state; u8 inb_state; unsigned int ex_mode; unsigned int digmic; unsigned int mic1pre; unsigned int mic2pre; unsigned int extmic_mode; }; static const u8 max98088_reg[M98088_REG_CNT] = { 0x00, /* 00 IRQ status */ 0x00, /* 01 MIC status */ 0x00, /* 02 jack status */ 0x00, /* 03 battery voltage */ 0x00, /* 04 */ 0x00, /* 05 */ 0x00, /* 06 */ 0x00, /* 07 */ 0x00, /* 08 */ 0x00, /* 09 */ 0x00, /* 0A */ 0x00, /* 0B */ 0x00, /* 0C */ 0x00, /* 0D */ 0x00, /* 0E */ 0x00, /* 0F interrupt enable */ 0x00, /* 10 master clock */ 0x00, /* 11 DAI1 clock mode */ 0x00, /* 12 DAI1 clock control */ 0x00, /* 13 DAI1 clock control */ 0x00, /* 14 DAI1 format */ 0x00, /* 15 DAI1 clock */ 0x00, /* 16 DAI1 config */ 0x00, /* 17 DAI1 TDM */ 0x00, /* 18 DAI1 filters */ 0x00, /* 19 DAI2 clock mode */ 0x00, /* 1A DAI2 clock control */ 0x00, /* 1B DAI2 clock control */ 0x00, /* 1C DAI2 format */ 0x00, /* 1D DAI2 clock */ 0x00, /* 1E DAI2 config */ 0x00, /* 1F DAI2 TDM */ 0x00, /* 20 DAI2 filters */ 0x00, /* 21 data config */ 0x00, /* 22 DAC mixer */ 0x00, /* 23 left ADC mixer */ 0x00, /* 24 right ADC mixer */ 0x00, /* 25 left HP mixer */ 0x00, /* 26 right HP mixer */ 0x00, /* 27 HP control */ 0x00, /* 28 left REC mixer */ 0x00, /* 29 right REC mixer */ 0x00, /* 2A REC control */ 0x00, /* 2B left SPK mixer */ 0x00, /* 2C right SPK mixer */ 0x00, /* 2D SPK control */ 0x00, /* 2E sidetone */ 0x00, /* 2F DAI1 playback level */ 0x00, /* 30 DAI1 playback level */ 0x00, /* 31 DAI2 playback level */ 0x00, /* 32 DAI2 playbakc level */ 0x00, /* 33 left ADC level */ 0x00, /* 34 right ADC level */ 0x00, /* 35 MIC1 level */ 0x00, /* 36 MIC2 level */ 0x00, /* 37 INA level */ 0x00, /* 38 INB level */ 0x00, /* 39 left HP volume */ 0x00, /* 3A right HP volume */ 0x00, /* 3B left REC volume */ 0x00, /* 3C right REC volume */ 0x00, /* 3D left SPK volume */ 0x00, /* 3E right SPK volume */ 0x00, /* 3F MIC config */ 0x00, /* 40 MIC threshold */ 0x00, /* 41 excursion limiter filter */ 0x00, /* 42 excursion limiter threshold */ 0x00, /* 43 ALC */ 0x00, /* 44 power limiter threshold */ 0x00, /* 45 power limiter config */ 0x00, /* 46 distortion limiter config */ 0x00, /* 47 audio input */ 0x00, /* 48 microphone */ 0x00, /* 49 level control */ 0x00, /* 4A bypass switches */ 0x00, /* 4B jack detect */ 0x00, /* 4C input enable */ 0x00, /* 4D output enable */ 0xF0, /* 4E bias control */ 0x00, /* 4F DAC power */ 0x0F, /* 50 DAC power */ 0x00, /* 51 system */ 0x00, /* 52 DAI1 EQ1 */ 0x00, /* 53 DAI1 EQ1 */ 0x00, /* 54 DAI1 EQ1 */ 0x00, /* 55 DAI1 EQ1 */ 0x00, /* 56 DAI1 EQ1 */ 0x00, /* 57 DAI1 EQ1 */ 0x00, /* 58 DAI1 EQ1 */ 0x00, /* 59 DAI1 EQ1 */ 0x00, /* 5A DAI1 EQ1 */ 0x00, /* 5B DAI1 EQ1 */ 0x00, /* 5C DAI1 EQ2 */ 0x00, /* 5D DAI1 EQ2 */ 0x00, /* 5E DAI1 EQ2 */ 0x00, /* 5F DAI1 EQ2 */ 0x00, /* 60 DAI1 EQ2 */ 0x00, /* 61 DAI1 EQ2 */ 0x00, /* 62 DAI1 EQ2 */ 0x00, /* 63 DAI1 EQ2 */ 0x00, /* 64 DAI1 EQ2 */ 0x00, /* 65 DAI1 EQ2 */ 0x00, /* 66 DAI1 EQ3 */ 0x00, /* 67 DAI1 EQ3 */ 0x00, /* 68 DAI1 EQ3 */ 0x00, /* 69 DAI1 EQ3 */ 0x00, /* 6A DAI1 EQ3 */ 0x00, /* 6B DAI1 EQ3 */ 0x00, /* 6C DAI1 EQ3 */ 0x00, /* 6D DAI1 EQ3 */ 0x00, /* 6E DAI1 EQ3 */ 0x00, /* 6F DAI1 EQ3 */ 0x00, /* 70 DAI1 EQ4 */ 0x00, /* 71 DAI1 EQ4 */ 0x00, /* 72 DAI1 EQ4 */ 0x00, /* 73 DAI1 EQ4 */ 0x00, /* 74 DAI1 EQ4 */ 0x00, /* 75 DAI1 EQ4 */ 0x00, /* 76 DAI1 EQ4 */ 0x00, /* 77 DAI1 EQ4 */ 0x00, /* 78 DAI1 EQ4 */ 0x00, /* 79 DAI1 EQ4 */ 0x00, /* 7A DAI1 EQ5 */ 0x00, /* 7B DAI1 EQ5 */ 0x00, /* 7C DAI1 EQ5 */ 0x00, /* 7D DAI1 EQ5 */ 0x00, /* 7E DAI1 EQ5 */ 0x00, /* 7F DAI1 EQ5 */ 0x00, /* 80 DAI1 EQ5 */ 0x00, /* 81 DAI1 EQ5 */ 0x00, /* 82 DAI1 EQ5 */ 0x00, /* 83 DAI1 EQ5 */ 0x00, /* 84 DAI2 EQ1 */ 0x00, /* 85 DAI2 EQ1 */ 0x00, /* 86 DAI2 EQ1 */ 0x00, /* 87 DAI2 EQ1 */ 0x00, /* 88 DAI2 EQ1 */ 0x00, /* 89 DAI2 EQ1 */ 0x00, /* 8A DAI2 EQ1 */ 0x00, /* 8B DAI2 EQ1 */ 0x00, /* 8C DAI2 EQ1 */ 0x00, /* 8D DAI2 EQ1 */ 0x00, /* 8E DAI2 EQ2 */ 0x00, /* 8F DAI2 EQ2 */ 0x00, /* 90 DAI2 EQ2 */ 0x00, /* 91 DAI2 EQ2 */ 0x00, /* 92 DAI2 EQ2 */ 0x00, /* 93 DAI2 EQ2 */ 0x00, /* 94 DAI2 EQ2 */ 0x00, /* 95 DAI2 EQ2 */ 0x00, /* 96 DAI2 EQ2 */ 0x00, /* 97 DAI2 EQ2 */ 0x00, /* 98 DAI2 EQ3 */ 0x00, /* 99 DAI2 EQ3 */ 0x00, /* 9A DAI2 EQ3 */ 0x00, /* 9B DAI2 EQ3 */ 0x00, /* 9C DAI2 EQ3 */ 0x00, /* 9D DAI2 EQ3 */ 0x00, /* 9E DAI2 EQ3 */ 0x00, /* 9F DAI2 EQ3 */ 0x00, /* A0 DAI2 EQ3 */ 0x00, /* A1 DAI2 EQ3 */ 0x00, /* A2 DAI2 EQ4 */ 0x00, /* A3 DAI2 EQ4 */ 0x00, /* A4 DAI2 EQ4 */ 0x00, /* A5 DAI2 EQ4 */ 0x00, /* A6 DAI2 EQ4 */ 0x00, /* A7 DAI2 EQ4 */ 0x00, /* A8 DAI2 EQ4 */ 0x00, /* A9 DAI2 EQ4 */ 0x00, /* AA DAI2 EQ4 */ 0x00, /* AB DAI2 EQ4 */ 0x00, /* AC DAI2 EQ5 */ 0x00, /* AD DAI2 EQ5 */ 0x00, /* AE DAI2 EQ5 */ 0x00, /* AF DAI2 EQ5 */ 0x00, /* B0 DAI2 EQ5 */ 0x00, /* B1 DAI2 EQ5 */ 0x00, /* B2 DAI2 EQ5 */ 0x00, /* B3 DAI2 EQ5 */ 0x00, /* B4 DAI2 EQ5 */ 0x00, /* B5 DAI2 EQ5 */ 0x00, /* B6 DAI1 biquad */ 0x00, /* B7 DAI1 biquad */ 0x00, /* B8 DAI1 biquad */ 0x00, /* B9 DAI1 biquad */ 0x00, /* BA DAI1 biquad */ 0x00, /* BB DAI1 biquad */ 0x00, /* BC DAI1 biquad */ 0x00, /* BD DAI1 biquad */ 0x00, /* BE DAI1 biquad */ 0x00, /* BF DAI1 biquad */ 0x00, /* C0 DAI2 biquad */ 0x00, /* C1 DAI2 biquad */ 0x00, /* C2 DAI2 biquad */ 0x00, /* C3 DAI2 biquad */ 0x00, /* C4 DAI2 biquad */ 0x00, /* C5 DAI2 biquad */ 0x00, /* C6 DAI2 biquad */ 0x00, /* C7 DAI2 biquad */ 0x00, /* C8 DAI2 biquad */ 0x00, /* C9 DAI2 biquad */ 0x00, /* CA */ 0x00, /* CB */ 0x00, /* CC */ 0x00, /* CD */ 0x00, /* CE */ 0x00, /* CF */ 0x00, /* D0 */ 0x00, /* D1 */ 0x00, /* D2 */ 0x00, /* D3 */ 0x00, /* D4 */ 0x00, /* D5 */ 0x00, /* D6 */ 0x00, /* D7 */ 0x00, /* D8 */ 0x00, /* D9 */ 0x00, /* DA */ 0x70, /* DB */ 0x00, /* DC */ 0x00, /* DD */ 0x00, /* DE */ 0x00, /* DF */ 0x00, /* E0 */ 0x00, /* E1 */ 0x00, /* E2 */ 0x00, /* E3 */ 0x00, /* E4 */ 0x00, /* E5 */ 0x00, /* E6 */ 0x00, /* E7 */ 0x00, /* E8 */ 0x00, /* E9 */ 0x00, /* EA */ 0x00, /* EB */ 0x00, /* EC */ 0x00, /* ED */ 0x00, /* EE */ 0x00, /* EF */ 0x00, /* F0 */ 0x00, /* F1 */ 0x00, /* F2 */ 0x00, /* F3 */ 0x00, /* F4 */ 0x00, /* F5 */ 0x00, /* F6 */ 0x00, /* F7 */ 0x00, /* F8 */ 0x00, /* F9 */ 0x00, /* FA */ 0x00, /* FB */ 0x00, /* FC */ 0x00, /* FD */ 0x00, /* FE */ 0x00, /* FF */ }; static struct { int readable; int writable; int vol; } max98088_access[M98088_REG_CNT] = { { 0xFF, 0xFF, 1 }, /* 00 IRQ status */ { 0xFF, 0x00, 1 }, /* 01 MIC status */ { 0xFF, 0x00, 1 }, /* 02 jack status */ { 0x1F, 0x1F, 1 }, /* 03 battery voltage */ { 0xFF, 0xFF, 0 }, /* 04 */ { 0xFF, 0xFF, 0 }, /* 05 */ { 0xFF, 0xFF, 0 }, /* 06 */ { 0xFF, 0xFF, 0 }, /* 07 */ { 0xFF, 0xFF, 0 }, /* 08 */ { 0xFF, 0xFF, 0 }, /* 09 */ { 0xFF, 0xFF, 0 }, /* 0A */ { 0xFF, 0xFF, 0 }, /* 0B */ { 0xFF, 0xFF, 0 }, /* 0C */ { 0xFF, 0xFF, 0 }, /* 0D */ { 0xFF, 0xFF, 0 }, /* 0E */ { 0xFF, 0xFF, 0 }, /* 0F interrupt enable */ { 0xFF, 0xFF, 0 }, /* 10 master clock */ { 0xFF, 0xFF, 0 }, /* 11 DAI1 clock mode */ { 0xFF, 0xFF, 0 }, /* 12 DAI1 clock control */ { 0xFF, 0xFF, 0 }, /* 13 DAI1 clock control */ { 0xFF, 0xFF, 0 }, /* 14 DAI1 format */ { 0xFF, 0xFF, 0 }, /* 15 DAI1 clock */ { 0xFF, 0xFF, 0 }, /* 16 DAI1 config */ { 0xFF, 0xFF, 0 }, /* 17 DAI1 TDM */ { 0xFF, 0xFF, 0 }, /* 18 DAI1 filters */ { 0xFF, 0xFF, 0 }, /* 19 DAI2 clock mode */ { 0xFF, 0xFF, 0 }, /* 1A DAI2 clock control */ { 0xFF, 0xFF, 0 }, /* 1B DAI2 clock control */ { 0xFF, 0xFF, 0 }, /* 1C DAI2 format */ { 0xFF, 0xFF, 0 }, /* 1D DAI2 clock */ { 0xFF, 0xFF, 0 }, /* 1E DAI2 config */ { 0xFF, 0xFF, 0 }, /* 1F DAI2 TDM */ { 0xFF, 0xFF, 0 }, /* 20 DAI2 filters */ { 0xFF, 0xFF, 0 }, /* 21 data config */ { 0xFF, 0xFF, 0 }, /* 22 DAC mixer */ { 0xFF, 0xFF, 0 }, /* 23 left ADC mixer */ { 0xFF, 0xFF, 0 }, /* 24 right ADC mixer */ { 0xFF, 0xFF, 0 }, /* 25 left HP mixer */ { 0xFF, 0xFF, 0 }, /* 26 right HP mixer */ { 0xFF, 0xFF, 0 }, /* 27 HP control */ { 0xFF, 0xFF, 0 }, /* 28 left REC mixer */ { 0xFF, 0xFF, 0 }, /* 29 right REC mixer */ { 0xFF, 0xFF, 0 }, /* 2A REC control */ { 0xFF, 0xFF, 0 }, /* 2B left SPK mixer */ { 0xFF, 0xFF, 0 }, /* 2C right SPK mixer */ { 0xFF, 0xFF, 0 }, /* 2D SPK control */ { 0xFF, 0xFF, 0 }, /* 2E sidetone */ { 0xFF, 0xFF, 0 }, /* 2F DAI1 playback level */ { 0xFF, 0xFF, 0 }, /* 30 DAI1 playback level */ { 0xFF, 0xFF, 0 }, /* 31 DAI2 playback level */ { 0xFF, 0xFF, 0 }, /* 32 DAI2 playbakc level */ { 0xFF, 0xFF, 0 }, /* 33 left ADC level */ { 0xFF, 0xFF, 0 }, /* 34 right ADC level */ { 0xFF, 0xFF, 0 }, /* 35 MIC1 level */ { 0xFF, 0xFF, 0 }, /* 36 MIC2 level */ { 0xFF, 0xFF, 0 }, /* 37 INA level */ { 0xFF, 0xFF, 0 }, /* 38 INB level */ { 0xFF, 0xFF, 0 }, /* 39 left HP volume */ { 0xFF, 0xFF, 0 }, /* 3A right HP volume */ { 0xFF, 0xFF, 0 }, /* 3B left REC volume */ { 0xFF, 0xFF, 0 }, /* 3C right REC volume */ { 0xFF, 0xFF, 0 }, /* 3D left SPK volume */ { 0xFF, 0xFF, 0 }, /* 3E right SPK volume */ { 0xFF, 0xFF, 0 }, /* 3F MIC config */ { 0xFF, 0xFF, 0 }, /* 40 MIC threshold */ { 0xFF, 0xFF, 0 }, /* 41 excursion limiter filter */ { 0xFF, 0xFF, 0 }, /* 42 excursion limiter threshold */ { 0xFF, 0xFF, 0 }, /* 43 ALC */ { 0xFF, 0xFF, 0 }, /* 44 power limiter threshold */ { 0xFF, 0xFF, 0 }, /* 45 power limiter config */ { 0xFF, 0xFF, 0 }, /* 46 distortion limiter config */ { 0xFF, 0xFF, 0 }, /* 47 audio input */ { 0xFF, 0xFF, 0 }, /* 48 microphone */ { 0xFF, 0xFF, 0 }, /* 49 level control */ { 0xFF, 0xFF, 0 }, /* 4A bypass switches */ { 0xFF, 0xFF, 0 }, /* 4B jack detect */ { 0xFF, 0xFF, 0 }, /* 4C input enable */ { 0xFF, 0xFF, 0 }, /* 4D output enable */ { 0xFF, 0xFF, 0 }, /* 4E bias control */ { 0xFF, 0xFF, 0 }, /* 4F DAC power */ { 0xFF, 0xFF, 0 }, /* 50 DAC power */ { 0xFF, 0xFF, 0 }, /* 51 system */ { 0xFF, 0xFF, 0 }, /* 52 DAI1 EQ1 */ { 0xFF, 0xFF, 0 }, /* 53 DAI1 EQ1 */ { 0xFF, 0xFF, 0 }, /* 54 DAI1 EQ1 */ { 0xFF, 0xFF, 0 }, /* 55 DAI1 EQ1 */ { 0xFF, 0xFF, 0 }, /* 56 DAI1 EQ1 */ { 0xFF, 0xFF, 0 }, /* 57 DAI1 EQ1 */ { 0xFF, 0xFF, 0 }, /* 58 DAI1 EQ1 */ { 0xFF, 0xFF, 0 }, /* 59 DAI1 EQ1 */ { 0xFF, 0xFF, 0 }, /* 5A DAI1 EQ1 */ { 0xFF, 0xFF, 0 }, /* 5B DAI1 EQ1 */ { 0xFF, 0xFF, 0 }, /* 5C DAI1 EQ2 */ { 0xFF, 0xFF, 0 }, /* 5D DAI1 EQ2 */ { 0xFF, 0xFF, 0 }, /* 5E DAI1 EQ2 */ { 0xFF, 0xFF, 0 }, /* 5F DAI1 EQ2 */ { 0xFF, 0xFF, 0 }, /* 60 DAI1 EQ2 */ { 0xFF, 0xFF, 0 }, /* 61 DAI1 EQ2 */ { 0xFF, 0xFF, 0 }, /* 62 DAI1 EQ2 */ { 0xFF, 0xFF, 0 }, /* 63 DAI1 EQ2 */ { 0xFF, 0xFF, 0 }, /* 64 DAI1 EQ2 */ { 0xFF, 0xFF, 0 }, /* 65 DAI1 EQ2 */ { 0xFF, 0xFF, 0 }, /* 66 DAI1 EQ3 */ { 0xFF, 0xFF, 0 }, /* 67 DAI1 EQ3 */ { 0xFF, 0xFF, 0 }, /* 68 DAI1 EQ3 */ { 0xFF, 0xFF, 0 }, /* 69 DAI1 EQ3 */ { 0xFF, 0xFF, 0 }, /* 6A DAI1 EQ3 */ { 0xFF, 0xFF, 0 }, /* 6B DAI1 EQ3 */ { 0xFF, 0xFF, 0 }, /* 6C DAI1 EQ3 */ { 0xFF, 0xFF, 0 }, /* 6D DAI1 EQ3 */ { 0xFF, 0xFF, 0 }, /* 6E DAI1 EQ3 */ { 0xFF, 0xFF, 0 }, /* 6F DAI1 EQ3 */ { 0xFF, 0xFF, 0 }, /* 70 DAI1 EQ4 */ { 0xFF, 0xFF, 0 }, /* 71 DAI1 EQ4 */ { 0xFF, 0xFF, 0 }, /* 72 DAI1 EQ4 */ { 0xFF, 0xFF, 0 }, /* 73 DAI1 EQ4 */ { 0xFF, 0xFF, 0 }, /* 74 DAI1 EQ4 */ { 0xFF, 0xFF, 0 }, /* 75 DAI1 EQ4 */ { 0xFF, 0xFF, 0 }, /* 76 DAI1 EQ4 */ { 0xFF, 0xFF, 0 }, /* 77 DAI1 EQ4 */ { 0xFF, 0xFF, 0 }, /* 78 DAI1 EQ4 */ { 0xFF, 0xFF, 0 }, /* 79 DAI1 EQ4 */ { 0xFF, 0xFF, 0 }, /* 7A DAI1 EQ5 */ { 0xFF, 0xFF, 0 }, /* 7B DAI1 EQ5 */ { 0xFF, 0xFF, 0 }, /* 7C DAI1 EQ5 */ { 0xFF, 0xFF, 0 }, /* 7D DAI1 EQ5 */ { 0xFF, 0xFF, 0 }, /* 7E DAI1 EQ5 */ { 0xFF, 0xFF, 0 }, /* 7F DAI1 EQ5 */ { 0xFF, 0xFF, 0 }, /* 80 DAI1 EQ5 */ { 0xFF, 0xFF, 0 }, /* 81 DAI1 EQ5 */ { 0xFF, 0xFF, 0 }, /* 82 DAI1 EQ5 */ { 0xFF, 0xFF, 0 }, /* 83 DAI1 EQ5 */ { 0xFF, 0xFF, 0 }, /* 84 DAI2 EQ1 */ { 0xFF, 0xFF, 0 }, /* 85 DAI2 EQ1 */ { 0xFF, 0xFF, 0 }, /* 86 DAI2 EQ1 */ { 0xFF, 0xFF, 0 }, /* 87 DAI2 EQ1 */ { 0xFF, 0xFF, 0 }, /* 88 DAI2 EQ1 */ { 0xFF, 0xFF, 0 }, /* 89 DAI2 EQ1 */ { 0xFF, 0xFF, 0 }, /* 8A DAI2 EQ1 */ { 0xFF, 0xFF, 0 }, /* 8B DAI2 EQ1 */ { 0xFF, 0xFF, 0 }, /* 8C DAI2 EQ1 */ { 0xFF, 0xFF, 0 }, /* 8D DAI2 EQ1 */ { 0xFF, 0xFF, 0 }, /* 8E DAI2 EQ2 */ { 0xFF, 0xFF, 0 }, /* 8F DAI2 EQ2 */ { 0xFF, 0xFF, 0 }, /* 90 DAI2 EQ2 */ { 0xFF, 0xFF, 0 }, /* 91 DAI2 EQ2 */ { 0xFF, 0xFF, 0 }, /* 92 DAI2 EQ2 */ { 0xFF, 0xFF, 0 }, /* 93 DAI2 EQ2 */ { 0xFF, 0xFF, 0 }, /* 94 DAI2 EQ2 */ { 0xFF, 0xFF, 0 }, /* 95 DAI2 EQ2 */ { 0xFF, 0xFF, 0 }, /* 96 DAI2 EQ2 */ { 0xFF, 0xFF, 0 }, /* 97 DAI2 EQ2 */ { 0xFF, 0xFF, 0 }, /* 98 DAI2 EQ3 */ { 0xFF, 0xFF, 0 }, /* 99 DAI2 EQ3 */ { 0xFF, 0xFF, 0 }, /* 9A DAI2 EQ3 */ { 0xFF, 0xFF, 0 }, /* 9B DAI2 EQ3 */ { 0xFF, 0xFF, 0 }, /* 9C DAI2 EQ3 */ { 0xFF, 0xFF, 0 }, /* 9D DAI2 EQ3 */ { 0xFF, 0xFF, 0 }, /* 9E DAI2 EQ3 */ { 0xFF, 0xFF, 0 }, /* 9F DAI2 EQ3 */ { 0xFF, 0xFF, 0 }, /* A0 DAI2 EQ3 */ { 0xFF, 0xFF, 0 }, /* A1 DAI2 EQ3 */ { 0xFF, 0xFF, 0 }, /* A2 DAI2 EQ4 */ { 0xFF, 0xFF, 0 }, /* A3 DAI2 EQ4 */ { 0xFF, 0xFF, 0 }, /* A4 DAI2 EQ4 */ { 0xFF, 0xFF, 0 }, /* A5 DAI2 EQ4 */ { 0xFF, 0xFF, 0 }, /* A6 DAI2 EQ4 */ { 0xFF, 0xFF, 0 }, /* A7 DAI2 EQ4 */ { 0xFF, 0xFF, 0 }, /* A8 DAI2 EQ4 */ { 0xFF, 0xFF, 0 }, /* A9 DAI2 EQ4 */ { 0xFF, 0xFF, 0 }, /* AA DAI2 EQ4 */ { 0xFF, 0xFF, 0 }, /* AB DAI2 EQ4 */ { 0xFF, 0xFF, 0 }, /* AC DAI2 EQ5 */ { 0xFF, 0xFF, 0 }, /* AD DAI2 EQ5 */ { 0xFF, 0xFF, 0 }, /* AE DAI2 EQ5 */ { 0xFF, 0xFF, 0 }, /* AF DAI2 EQ5 */ { 0xFF, 0xFF, 0 }, /* B0 DAI2 EQ5 */ { 0xFF, 0xFF, 0 }, /* B1 DAI2 EQ5 */ { 0xFF, 0xFF, 0 }, /* B2 DAI2 EQ5 */ { 0xFF, 0xFF, 0 }, /* B3 DAI2 EQ5 */ { 0xFF, 0xFF, 0 }, /* B4 DAI2 EQ5 */ { 0xFF, 0xFF, 0 }, /* B5 DAI2 EQ5 */ { 0xFF, 0xFF, 0 }, /* B6 DAI1 biquad */ { 0xFF, 0xFF, 0 }, /* B7 DAI1 biquad */ { 0xFF, 0xFF, 0 }, /* B8 DAI1 biquad */ { 0xFF, 0xFF, 0 }, /* B9 DAI1 biquad */ { 0xFF, 0xFF, 0 }, /* BA DAI1 biquad */ { 0xFF, 0xFF, 0 }, /* BB DAI1 biquad */ { 0xFF, 0xFF, 0 }, /* BC DAI1 biquad */ { 0xFF, 0xFF, 0 }, /* BD DAI1 biquad */ { 0xFF, 0xFF, 0 }, /* BE DAI1 biquad */ { 0xFF, 0xFF, 0 }, /* BF DAI1 biquad */ { 0xFF, 0xFF, 0 }, /* C0 DAI2 biquad */ { 0xFF, 0xFF, 0 }, /* C1 DAI2 biquad */ { 0xFF, 0xFF, 0 }, /* C2 DAI2 biquad */ { 0xFF, 0xFF, 0 }, /* C3 DAI2 biquad */ { 0xFF, 0xFF, 0 }, /* C4 DAI2 biquad */ { 0xFF, 0xFF, 0 }, /* C5 DAI2 biquad */ { 0xFF, 0xFF, 0 }, /* C6 DAI2 biquad */ { 0xFF, 0xFF, 0 }, /* C7 DAI2 biquad */ { 0xFF, 0xFF, 0 }, /* C8 DAI2 biquad */ { 0xFF, 0xFF, 0 }, /* C9 DAI2 biquad */ { 0x00, 0x00, 0 }, /* CA */ { 0x00, 0x00, 0 }, /* CB */ { 0x00, 0x00, 0 }, /* CC */ { 0x00, 0x00, 0 }, /* CD */ { 0x00, 0x00, 0 }, /* CE */ { 0x00, 0x00, 0 }, /* CF */ { 0x00, 0x00, 0 }, /* D0 */ { 0x00, 0x00, 0 }, /* D1 */ { 0x00, 0x00, 0 }, /* D2 */ { 0x00, 0x00, 0 }, /* D3 */ { 0x00, 0x00, 0 }, /* D4 */ { 0x00, 0x00, 0 }, /* D5 */ { 0x00, 0x00, 0 }, /* D6 */ { 0x00, 0x00, 0 }, /* D7 */ { 0x00, 0x00, 0 }, /* D8 */ { 0x00, 0x00, 0 }, /* D9 */ { 0x00, 0x00, 0 }, /* DA */ { 0x00, 0x00, 0 }, /* DB */ { 0x00, 0x00, 0 }, /* DC */ { 0x00, 0x00, 0 }, /* DD */ { 0x00, 0x00, 0 }, /* DE */ { 0x00, 0x00, 0 }, /* DF */ { 0x00, 0x00, 0 }, /* E0 */ { 0x00, 0x00, 0 }, /* E1 */ { 0x00, 0x00, 0 }, /* E2 */ { 0x00, 0x00, 0 }, /* E3 */ { 0x00, 0x00, 0 }, /* E4 */ { 0x00, 0x00, 0 }, /* E5 */ { 0x00, 0x00, 0 }, /* E6 */ { 0x00, 0x00, 0 }, /* E7 */ { 0x00, 0x00, 0 }, /* E8 */ { 0x00, 0x00, 0 }, /* E9 */ { 0x00, 0x00, 0 }, /* EA */ { 0x00, 0x00, 0 }, /* EB */ { 0x00, 0x00, 0 }, /* EC */ { 0x00, 0x00, 0 }, /* ED */ { 0x00, 0x00, 0 }, /* EE */ { 0x00, 0x00, 0 }, /* EF */ { 0x00, 0x00, 0 }, /* F0 */ { 0x00, 0x00, 0 }, /* F1 */ { 0x00, 0x00, 0 }, /* F2 */ { 0x00, 0x00, 0 }, /* F3 */ { 0x00, 0x00, 0 }, /* F4 */ { 0x00, 0x00, 0 }, /* F5 */ { 0x00, 0x00, 0 }, /* F6 */ { 0x00, 0x00, 0 }, /* F7 */ { 0x00, 0x00, 0 }, /* F8 */ { 0x00, 0x00, 0 }, /* F9 */ { 0x00, 0x00, 0 }, /* FA */ { 0x00, 0x00, 0 }, /* FB */ { 0x00, 0x00, 0 }, /* FC */ { 0x00, 0x00, 0 }, /* FD */ { 0x00, 0x00, 0 }, /* FE */ { 0xFF, 0x00, 1 }, /* FF */ }; static int max98088_volatile_register(struct snd_soc_codec *codec, unsigned int reg) { return max98088_access[reg].vol; } /* * Load equalizer DSP coefficient configurations registers */ static void m98088_eq_band(struct snd_soc_codec *codec, unsigned int dai, unsigned int band, u16 *coefs) { unsigned int eq_reg; unsigned int i; BUG_ON(band > 4); BUG_ON(dai > 1); /* Load the base register address */ eq_reg = dai ? M98088_REG_84_DAI2_EQ_BASE : M98088_REG_52_DAI1_EQ_BASE; /* Add the band address offset, note adjustment for word address */ eq_reg += band * (M98088_COEFS_PER_BAND << 1); /* Step through the registers and coefs */ for (i = 0; i < M98088_COEFS_PER_BAND; i++) { snd_soc_write(codec, eq_reg++, M98088_BYTE1(coefs[i])); snd_soc_write(codec, eq_reg++, M98088_BYTE0(coefs[i])); } } /* * Excursion limiter modes */ static const char *max98088_exmode_texts[] = { "Off", "100Hz", "400Hz", "600Hz", "800Hz", "1000Hz", "200-400Hz", "400-600Hz", "400-800Hz", }; static const unsigned int max98088_exmode_values[] = { 0x00, 0x43, 0x10, 0x20, 0x30, 0x40, 0x11, 0x22, 0x32 }; static const struct soc_enum max98088_exmode_enum = SOC_VALUE_ENUM_SINGLE(M98088_REG_41_SPKDHP, 0, 127, ARRAY_SIZE(max98088_exmode_texts), max98088_exmode_texts, max98088_exmode_values); static const char *max98088_ex_thresh[] = { /* volts PP */ "0.6", "1.2", "1.8", "2.4", "3.0", "3.6", "4.2", "4.8"}; static const struct soc_enum max98088_ex_thresh_enum[] = { SOC_ENUM_SINGLE(M98088_REG_42_SPKDHP_THRESH, 0, 8, max98088_ex_thresh), }; static const char *max98088_fltr_mode[] = {"Voice", "Music" }; static const struct soc_enum max98088_filter_mode_enum[] = { SOC_ENUM_SINGLE(M98088_REG_18_DAI1_FILTERS, 7, 2, max98088_fltr_mode), }; static const char *max98088_extmic_text[] = { "None", "MIC1", "MIC2" }; static const struct soc_enum max98088_extmic_enum = SOC_ENUM_SINGLE(M98088_REG_48_CFG_MIC, 0, 3, max98088_extmic_text); static const struct snd_kcontrol_new max98088_extmic_mux = SOC_DAPM_ENUM("External MIC Mux", max98088_extmic_enum); static const char *max98088_dai1_fltr[] = { "Off", "fc=258/fs=16k", "fc=500/fs=16k", "fc=258/fs=8k", "fc=500/fs=8k", "fc=200"}; static const struct soc_enum max98088_dai1_dac_filter_enum[] = { SOC_ENUM_SINGLE(M98088_REG_18_DAI1_FILTERS, 0, 6, max98088_dai1_fltr), }; static const struct soc_enum max98088_dai1_adc_filter_enum[] = { SOC_ENUM_SINGLE(M98088_REG_18_DAI1_FILTERS, 4, 6, max98088_dai1_fltr), }; static int max98088_mic1pre_set(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec); unsigned int sel = ucontrol->value.integer.value[0]; max98088->mic1pre = sel; snd_soc_update_bits(codec, M98088_REG_35_LVL_MIC1, M98088_MICPRE_MASK, (1+sel)<<M98088_MICPRE_SHIFT); return 0; } static int max98088_mic1pre_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec); ucontrol->value.integer.value[0] = max98088->mic1pre; return 0; } static int max98088_mic2pre_set(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec); unsigned int sel = ucontrol->value.integer.value[0]; max98088->mic2pre = sel; snd_soc_update_bits(codec, M98088_REG_36_LVL_MIC2, M98088_MICPRE_MASK, (1+sel)<<M98088_MICPRE_SHIFT); return 0; } static int max98088_mic2pre_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec); ucontrol->value.integer.value[0] = max98088->mic2pre; return 0; } static const unsigned int max98088_micboost_tlv[] = { TLV_DB_RANGE_HEAD(2), 0, 1, TLV_DB_SCALE_ITEM(0, 2000, 0), 2, 2, TLV_DB_SCALE_ITEM(3000, 0, 0), }; static const unsigned int max98088_hp_tlv[] = { TLV_DB_RANGE_HEAD(5), 0, 6, TLV_DB_SCALE_ITEM(-6700, 400, 0), 7, 14, TLV_DB_SCALE_ITEM(-4000, 300, 0), 15, 21, TLV_DB_SCALE_ITEM(-1700, 200, 0), 22, 27, TLV_DB_SCALE_ITEM(-400, 100, 0), 28, 31, TLV_DB_SCALE_ITEM(150, 50, 0), }; static const unsigned int max98088_spk_tlv[] = { TLV_DB_RANGE_HEAD(5), 0, 6, TLV_DB_SCALE_ITEM(-6200, 400, 0), 7, 14, TLV_DB_SCALE_ITEM(-3500, 300, 0), 15, 21, TLV_DB_SCALE_ITEM(-1200, 200, 0), 22, 27, TLV_DB_SCALE_ITEM(100, 100, 0), 28, 31, TLV_DB_SCALE_ITEM(650, 50, 0), }; static const struct snd_kcontrol_new max98088_snd_controls[] = { SOC_DOUBLE_R_TLV("Headphone Volume", M98088_REG_39_LVL_HP_L, M98088_REG_3A_LVL_HP_R, 0, 31, 0, max98088_hp_tlv), SOC_DOUBLE_R_TLV("Speaker Volume", M98088_REG_3D_LVL_SPK_L, M98088_REG_3E_LVL_SPK_R, 0, 31, 0, max98088_spk_tlv), SOC_DOUBLE_R_TLV("Receiver Volume", M98088_REG_3B_LVL_REC_L, M98088_REG_3C_LVL_REC_R, 0, 31, 0, max98088_spk_tlv), SOC_DOUBLE_R("Headphone Switch", M98088_REG_39_LVL_HP_L, M98088_REG_3A_LVL_HP_R, 7, 1, 1), SOC_DOUBLE_R("Speaker Switch", M98088_REG_3D_LVL_SPK_L, M98088_REG_3E_LVL_SPK_R, 7, 1, 1), SOC_DOUBLE_R("Receiver Switch", M98088_REG_3B_LVL_REC_L, M98088_REG_3C_LVL_REC_R, 7, 1, 1), SOC_SINGLE("MIC1 Volume", M98088_REG_35_LVL_MIC1, 0, 31, 1), SOC_SINGLE("MIC2 Volume", M98088_REG_36_LVL_MIC2, 0, 31, 1), SOC_SINGLE_EXT_TLV("MIC1 Boost Volume", M98088_REG_35_LVL_MIC1, 5, 2, 0, max98088_mic1pre_get, max98088_mic1pre_set, max98088_micboost_tlv), SOC_SINGLE_EXT_TLV("MIC2 Boost Volume", M98088_REG_36_LVL_MIC2, 5, 2, 0, max98088_mic2pre_get, max98088_mic2pre_set, max98088_micboost_tlv), SOC_SINGLE("INA Volume", M98088_REG_37_LVL_INA, 0, 7, 1), SOC_SINGLE("INB Volume", M98088_REG_38_LVL_INB, 0, 7, 1), SOC_SINGLE("ADCL Volume", M98088_REG_33_LVL_ADC_L, 0, 15, 0), SOC_SINGLE("ADCR Volume", M98088_REG_34_LVL_ADC_R, 0, 15, 0), SOC_SINGLE("ADCL Boost Volume", M98088_REG_33_LVL_ADC_L, 4, 3, 0), SOC_SINGLE("ADCR Boost Volume", M98088_REG_34_LVL_ADC_R, 4, 3, 0), SOC_SINGLE("EQ1 Switch", M98088_REG_49_CFG_LEVEL, 0, 1, 0), SOC_SINGLE("EQ2 Switch", M98088_REG_49_CFG_LEVEL, 1, 1, 0), SOC_ENUM("EX Limiter Mode", max98088_exmode_enum), SOC_ENUM("EX Limiter Threshold", max98088_ex_thresh_enum), SOC_ENUM("DAI1 Filter Mode", max98088_filter_mode_enum), SOC_ENUM("DAI1 DAC Filter", max98088_dai1_dac_filter_enum), SOC_ENUM("DAI1 ADC Filter", max98088_dai1_adc_filter_enum), SOC_SINGLE("DAI2 DC Block Switch", M98088_REG_20_DAI2_FILTERS, 0, 1, 0), SOC_SINGLE("ALC Switch", M98088_REG_43_SPKALC_COMP, 7, 1, 0), SOC_SINGLE("ALC Threshold", M98088_REG_43_SPKALC_COMP, 0, 7, 0), SOC_SINGLE("ALC Multiband", M98088_REG_43_SPKALC_COMP, 3, 1, 0), SOC_SINGLE("ALC Release Time", M98088_REG_43_SPKALC_COMP, 4, 7, 0), SOC_SINGLE("PWR Limiter Threshold", M98088_REG_44_PWRLMT_CFG, 4, 15, 0), SOC_SINGLE("PWR Limiter Weight", M98088_REG_44_PWRLMT_CFG, 0, 7, 0), SOC_SINGLE("PWR Limiter Time1", M98088_REG_45_PWRLMT_TIME, 0, 15, 0), SOC_SINGLE("PWR Limiter Time2", M98088_REG_45_PWRLMT_TIME, 4, 15, 0), SOC_SINGLE("THD Limiter Threshold", M98088_REG_46_THDLMT_CFG, 4, 15, 0), SOC_SINGLE("THD Limiter Time", M98088_REG_46_THDLMT_CFG, 0, 7, 0), }; /* Left speaker mixer switch */ static const struct snd_kcontrol_new max98088_left_speaker_mixer_controls[] = { SOC_DAPM_SINGLE("Left DAC1 Switch", M98088_REG_2B_MIX_SPK_LEFT, 0, 1, 0), SOC_DAPM_SINGLE("Right DAC1 Switch", M98088_REG_2B_MIX_SPK_LEFT, 7, 1, 0), SOC_DAPM_SINGLE("Left DAC2 Switch", M98088_REG_2B_MIX_SPK_LEFT, 0, 1, 0), SOC_DAPM_SINGLE("Right DAC2 Switch", M98088_REG_2B_MIX_SPK_LEFT, 7, 1, 0), SOC_DAPM_SINGLE("MIC1 Switch", M98088_REG_2B_MIX_SPK_LEFT, 5, 1, 0), SOC_DAPM_SINGLE("MIC2 Switch", M98088_REG_2B_MIX_SPK_LEFT, 6, 1, 0), SOC_DAPM_SINGLE("INA1 Switch", M98088_REG_2B_MIX_SPK_LEFT, 1, 1, 0), SOC_DAPM_SINGLE("INA2 Switch", M98088_REG_2B_MIX_SPK_LEFT, 2, 1, 0), SOC_DAPM_SINGLE("INB1 Switch", M98088_REG_2B_MIX_SPK_LEFT, 3, 1, 0), SOC_DAPM_SINGLE("INB2 Switch", M98088_REG_2B_MIX_SPK_LEFT, 4, 1, 0), }; /* Right speaker mixer switch */ static const struct snd_kcontrol_new max98088_right_speaker_mixer_controls[] = { SOC_DAPM_SINGLE("Left DAC1 Switch", M98088_REG_2C_MIX_SPK_RIGHT, 7, 1, 0), SOC_DAPM_SINGLE("Right DAC1 Switch", M98088_REG_2C_MIX_SPK_RIGHT, 0, 1, 0), SOC_DAPM_SINGLE("Left DAC2 Switch", M98088_REG_2C_MIX_SPK_RIGHT, 7, 1, 0), SOC_DAPM_SINGLE("Right DAC2 Switch", M98088_REG_2C_MIX_SPK_RIGHT, 0, 1, 0), SOC_DAPM_SINGLE("MIC1 Switch", M98088_REG_2C_MIX_SPK_RIGHT, 5, 1, 0), SOC_DAPM_SINGLE("MIC2 Switch", M98088_REG_2C_MIX_SPK_RIGHT, 6, 1, 0), SOC_DAPM_SINGLE("INA1 Switch", M98088_REG_2C_MIX_SPK_RIGHT, 1, 1, 0), SOC_DAPM_SINGLE("INA2 Switch", M98088_REG_2C_MIX_SPK_RIGHT, 2, 1, 0), SOC_DAPM_SINGLE("INB1 Switch", M98088_REG_2C_MIX_SPK_RIGHT, 3, 1, 0), SOC_DAPM_SINGLE("INB2 Switch", M98088_REG_2C_MIX_SPK_RIGHT, 4, 1, 0), }; /* Left headphone mixer switch */ static const struct snd_kcontrol_new max98088_left_hp_mixer_controls[] = { SOC_DAPM_SINGLE("Left DAC1 Switch", M98088_REG_25_MIX_HP_LEFT, 0, 1, 0), SOC_DAPM_SINGLE("Right DAC1 Switch", M98088_REG_25_MIX_HP_LEFT, 7, 1, 0), SOC_DAPM_SINGLE("Left DAC2 Switch", M98088_REG_25_MIX_HP_LEFT, 0, 1, 0), SOC_DAPM_SINGLE("Right DAC2 Switch", M98088_REG_25_MIX_HP_LEFT, 7, 1, 0), SOC_DAPM_SINGLE("MIC1 Switch", M98088_REG_25_MIX_HP_LEFT, 5, 1, 0), SOC_DAPM_SINGLE("MIC2 Switch", M98088_REG_25_MIX_HP_LEFT, 6, 1, 0), SOC_DAPM_SINGLE("INA1 Switch", M98088_REG_25_MIX_HP_LEFT, 1, 1, 0), SOC_DAPM_SINGLE("INA2 Switch", M98088_REG_25_MIX_HP_LEFT, 2, 1, 0), SOC_DAPM_SINGLE("INB1 Switch", M98088_REG_25_MIX_HP_LEFT, 3, 1, 0), SOC_DAPM_SINGLE("INB2 Switch", M98088_REG_25_MIX_HP_LEFT, 4, 1, 0), }; /* Right headphone mixer switch */ static const struct snd_kcontrol_new max98088_right_hp_mixer_controls[] = { SOC_DAPM_SINGLE("Left DAC1 Switch", M98088_REG_26_MIX_HP_RIGHT, 7, 1, 0), SOC_DAPM_SINGLE("Right DAC1 Switch", M98088_REG_26_MIX_HP_RIGHT, 0, 1, 0), SOC_DAPM_SINGLE("Left DAC2 Switch", M98088_REG_26_MIX_HP_RIGHT, 7, 1, 0), SOC_DAPM_SINGLE("Right DAC2 Switch", M98088_REG_26_MIX_HP_RIGHT, 0, 1, 0), SOC_DAPM_SINGLE("MIC1 Switch", M98088_REG_26_MIX_HP_RIGHT, 5, 1, 0), SOC_DAPM_SINGLE("MIC2 Switch", M98088_REG_26_MIX_HP_RIGHT, 6, 1, 0), SOC_DAPM_SINGLE("INA1 Switch", M98088_REG_26_MIX_HP_RIGHT, 1, 1, 0), SOC_DAPM_SINGLE("INA2 Switch", M98088_REG_26_MIX_HP_RIGHT, 2, 1, 0), SOC_DAPM_SINGLE("INB1 Switch", M98088_REG_26_MIX_HP_RIGHT, 3, 1, 0), SOC_DAPM_SINGLE("INB2 Switch", M98088_REG_26_MIX_HP_RIGHT, 4, 1, 0), }; /* Left earpiece/receiver mixer switch */ static const struct snd_kcontrol_new max98088_left_rec_mixer_controls[] = { SOC_DAPM_SINGLE("Left DAC1 Switch", M98088_REG_28_MIX_REC_LEFT, 0, 1, 0), SOC_DAPM_SINGLE("Right DAC1 Switch", M98088_REG_28_MIX_REC_LEFT, 7, 1, 0), SOC_DAPM_SINGLE("Left DAC2 Switch", M98088_REG_28_MIX_REC_LEFT, 0, 1, 0), SOC_DAPM_SINGLE("Right DAC2 Switch", M98088_REG_28_MIX_REC_LEFT, 7, 1, 0), SOC_DAPM_SINGLE("MIC1 Switch", M98088_REG_28_MIX_REC_LEFT, 5, 1, 0), SOC_DAPM_SINGLE("MIC2 Switch", M98088_REG_28_MIX_REC_LEFT, 6, 1, 0), SOC_DAPM_SINGLE("INA1 Switch", M98088_REG_28_MIX_REC_LEFT, 1, 1, 0), SOC_DAPM_SINGLE("INA2 Switch", M98088_REG_28_MIX_REC_LEFT, 2, 1, 0), SOC_DAPM_SINGLE("INB1 Switch", M98088_REG_28_MIX_REC_LEFT, 3, 1, 0), SOC_DAPM_SINGLE("INB2 Switch", M98088_REG_28_MIX_REC_LEFT, 4, 1, 0), }; /* Right earpiece/receiver mixer switch */ static const struct snd_kcontrol_new max98088_right_rec_mixer_controls[] = { SOC_DAPM_SINGLE("Left DAC1 Switch", M98088_REG_29_MIX_REC_RIGHT, 7, 1, 0), SOC_DAPM_SINGLE("Right DAC1 Switch", M98088_REG_29_MIX_REC_RIGHT, 0, 1, 0), SOC_DAPM_SINGLE("Left DAC2 Switch", M98088_REG_29_MIX_REC_RIGHT, 7, 1, 0), SOC_DAPM_SINGLE("Right DAC2 Switch", M98088_REG_29_MIX_REC_RIGHT, 0, 1, 0), SOC_DAPM_SINGLE("MIC1 Switch", M98088_REG_29_MIX_REC_RIGHT, 5, 1, 0), SOC_DAPM_SINGLE("MIC2 Switch", M98088_REG_29_MIX_REC_RIGHT, 6, 1, 0), SOC_DAPM_SINGLE("INA1 Switch", M98088_REG_29_MIX_REC_RIGHT, 1, 1, 0), SOC_DAPM_SINGLE("INA2 Switch", M98088_REG_29_MIX_REC_RIGHT, 2, 1, 0), SOC_DAPM_SINGLE("INB1 Switch", M98088_REG_29_MIX_REC_RIGHT, 3, 1, 0), SOC_DAPM_SINGLE("INB2 Switch", M98088_REG_29_MIX_REC_RIGHT, 4, 1, 0), }; /* Left ADC mixer switch */ static const struct snd_kcontrol_new max98088_left_ADC_mixer_controls[] = { SOC_DAPM_SINGLE("MIC1 Switch", M98088_REG_23_MIX_ADC_LEFT, 7, 1, 0), SOC_DAPM_SINGLE("MIC2 Switch", M98088_REG_23_MIX_ADC_LEFT, 6, 1, 0), SOC_DAPM_SINGLE("INA1 Switch", M98088_REG_23_MIX_ADC_LEFT, 3, 1, 0), SOC_DAPM_SINGLE("INA2 Switch", M98088_REG_23_MIX_ADC_LEFT, 2, 1, 0), SOC_DAPM_SINGLE("INB1 Switch", M98088_REG_23_MIX_ADC_LEFT, 1, 1, 0), SOC_DAPM_SINGLE("INB2 Switch", M98088_REG_23_MIX_ADC_LEFT, 0, 1, 0), }; /* Right ADC mixer switch */ static const struct snd_kcontrol_new max98088_right_ADC_mixer_controls[] = { SOC_DAPM_SINGLE("MIC1 Switch", M98088_REG_24_MIX_ADC_RIGHT, 7, 1, 0), SOC_DAPM_SINGLE("MIC2 Switch", M98088_REG_24_MIX_ADC_RIGHT, 6, 1, 0), SOC_DAPM_SINGLE("INA1 Switch", M98088_REG_24_MIX_ADC_RIGHT, 3, 1, 0), SOC_DAPM_SINGLE("INA2 Switch", M98088_REG_24_MIX_ADC_RIGHT, 2, 1, 0), SOC_DAPM_SINGLE("INB1 Switch", M98088_REG_24_MIX_ADC_RIGHT, 1, 1, 0), SOC_DAPM_SINGLE("INB2 Switch", M98088_REG_24_MIX_ADC_RIGHT, 0, 1, 0), }; static int max98088_mic_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_codec *codec = w->codec; struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec); switch (event) { case SND_SOC_DAPM_POST_PMU: if (w->reg == M98088_REG_35_LVL_MIC1) { snd_soc_update_bits(codec, w->reg, M98088_MICPRE_MASK, (1+max98088->mic1pre)<<M98088_MICPRE_SHIFT); } else { snd_soc_update_bits(codec, w->reg, M98088_MICPRE_MASK, (1+max98088->mic2pre)<<M98088_MICPRE_SHIFT); } break; case SND_SOC_DAPM_POST_PMD: snd_soc_update_bits(codec, w->reg, M98088_MICPRE_MASK, 0); break; default: return -EINVAL; } return 0; } /* * The line inputs are 2-channel stereo inputs with the left * and right channels sharing a common PGA power control signal. */ static int max98088_line_pga(struct snd_soc_dapm_widget *w, int event, int line, u8 channel) { struct snd_soc_codec *codec = w->codec; struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec); u8 *state; BUG_ON(!((channel == 1) || (channel == 2))); switch (line) { case LINE_INA: state = &max98088->ina_state; break; case LINE_INB: state = &max98088->inb_state; break; default: return -EINVAL; } switch (event) { case SND_SOC_DAPM_POST_PMU: *state |= channel; snd_soc_update_bits(codec, w->reg, (1 << w->shift), (1 << w->shift)); break; case SND_SOC_DAPM_POST_PMD: *state &= ~channel; if (*state == 0) { snd_soc_update_bits(codec, w->reg, (1 << w->shift), 0); } break; default: return -EINVAL; } return 0; } static int max98088_pga_ina1_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *k, int event) { return max98088_line_pga(w, event, LINE_INA, 1); } static int max98088_pga_ina2_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *k, int event) { return max98088_line_pga(w, event, LINE_INA, 2); } static int max98088_pga_inb1_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *k, int event) { return max98088_line_pga(w, event, LINE_INB, 1); } static int max98088_pga_inb2_event(struct snd_soc_dapm_widget *w, struct snd_kcontrol *k, int event) { return max98088_line_pga(w, event, LINE_INB, 2); } static const struct snd_soc_dapm_widget max98088_dapm_widgets[] = { SND_SOC_DAPM_ADC("ADCL", "HiFi Capture", M98088_REG_4C_PWR_EN_IN, 1, 0), SND_SOC_DAPM_ADC("ADCR", "HiFi Capture", M98088_REG_4C_PWR_EN_IN, 0, 0), SND_SOC_DAPM_DAC("DACL1", "HiFi Playback", M98088_REG_4D_PWR_EN_OUT, 1, 0), SND_SOC_DAPM_DAC("DACR1", "HiFi Playback", M98088_REG_4D_PWR_EN_OUT, 0, 0), SND_SOC_DAPM_DAC("DACL2", "Aux Playback", M98088_REG_4D_PWR_EN_OUT, 1, 0), SND_SOC_DAPM_DAC("DACR2", "Aux Playback", M98088_REG_4D_PWR_EN_OUT, 0, 0), SND_SOC_DAPM_PGA("HP Left Out", M98088_REG_4D_PWR_EN_OUT, 7, 0, NULL, 0), SND_SOC_DAPM_PGA("HP Right Out", M98088_REG_4D_PWR_EN_OUT, 6, 0, NULL, 0), SND_SOC_DAPM_PGA("SPK Left Out", M98088_REG_4D_PWR_EN_OUT, 5, 0, NULL, 0), SND_SOC_DAPM_PGA("SPK Right Out", M98088_REG_4D_PWR_EN_OUT, 4, 0, NULL, 0), SND_SOC_DAPM_PGA("REC Left Out", M98088_REG_4D_PWR_EN_OUT, 3, 0, NULL, 0), SND_SOC_DAPM_PGA("REC Right Out", M98088_REG_4D_PWR_EN_OUT, 2, 0, NULL, 0), SND_SOC_DAPM_MUX("External MIC", SND_SOC_NOPM, 0, 0, &max98088_extmic_mux), SND_SOC_DAPM_MIXER("Left HP Mixer", SND_SOC_NOPM, 0, 0, &max98088_left_hp_mixer_controls[0], ARRAY_SIZE(max98088_left_hp_mixer_controls)), SND_SOC_DAPM_MIXER("Right HP Mixer", SND_SOC_NOPM, 0, 0, &max98088_right_hp_mixer_controls[0], ARRAY_SIZE(max98088_right_hp_mixer_controls)), SND_SOC_DAPM_MIXER("Left SPK Mixer", SND_SOC_NOPM, 0, 0, &max98088_left_speaker_mixer_controls[0], ARRAY_SIZE(max98088_left_speaker_mixer_controls)), SND_SOC_DAPM_MIXER("Right SPK Mixer", SND_SOC_NOPM, 0, 0, &max98088_right_speaker_mixer_controls[0], ARRAY_SIZE(max98088_right_speaker_mixer_controls)), SND_SOC_DAPM_MIXER("Left REC Mixer", SND_SOC_NOPM, 0, 0, &max98088_left_rec_mixer_controls[0], ARRAY_SIZE(max98088_left_rec_mixer_controls)), SND_SOC_DAPM_MIXER("Right REC Mixer", SND_SOC_NOPM, 0, 0, &max98088_right_rec_mixer_controls[0], ARRAY_SIZE(max98088_right_rec_mixer_controls)), SND_SOC_DAPM_MIXER("Left ADC Mixer", SND_SOC_NOPM, 0, 0, &max98088_left_ADC_mixer_controls[0], ARRAY_SIZE(max98088_left_ADC_mixer_controls)), SND_SOC_DAPM_MIXER("Right ADC Mixer", SND_SOC_NOPM, 0, 0, &max98088_right_ADC_mixer_controls[0], ARRAY_SIZE(max98088_right_ADC_mixer_controls)), SND_SOC_DAPM_PGA_E("MIC1 Input", M98088_REG_35_LVL_MIC1, 5, 0, NULL, 0, max98088_mic_event, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_PGA_E("MIC2 Input", M98088_REG_36_LVL_MIC2, 5, 0, NULL, 0, max98088_mic_event, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_PGA_E("INA1 Input", M98088_REG_4C_PWR_EN_IN, 7, 0, NULL, 0, max98088_pga_ina1_event, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_PGA_E("INA2 Input", M98088_REG_4C_PWR_EN_IN, 7, 0, NULL, 0, max98088_pga_ina2_event, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_PGA_E("INB1 Input", M98088_REG_4C_PWR_EN_IN, 6, 0, NULL, 0, max98088_pga_inb1_event, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_PGA_E("INB2 Input", M98088_REG_4C_PWR_EN_IN, 6, 0, NULL, 0, max98088_pga_inb2_event, SND_SOC_DAPM_POST_PMU | SND_SOC_DAPM_POST_PMD), SND_SOC_DAPM_MICBIAS("MICBIAS", M98088_REG_4C_PWR_EN_IN, 3, 0), SND_SOC_DAPM_OUTPUT("HPL"), SND_SOC_DAPM_OUTPUT("HPR"), SND_SOC_DAPM_OUTPUT("SPKL"), SND_SOC_DAPM_OUTPUT("SPKR"), SND_SOC_DAPM_OUTPUT("RECL"), SND_SOC_DAPM_OUTPUT("RECR"), SND_SOC_DAPM_INPUT("MIC1"), SND_SOC_DAPM_INPUT("MIC2"), SND_SOC_DAPM_INPUT("INA1"), SND_SOC_DAPM_INPUT("INA2"), SND_SOC_DAPM_INPUT("INB1"), SND_SOC_DAPM_INPUT("INB2"), }; static const struct snd_soc_dapm_route max98088_audio_map[] = { /* Left headphone output mixer */ {"Left HP Mixer", "Left DAC1 Switch", "DACL1"}, {"Left HP Mixer", "Left DAC2 Switch", "DACL2"}, {"Left HP Mixer", "Right DAC1 Switch", "DACR1"}, {"Left HP Mixer", "Right DAC2 Switch", "DACR2"}, {"Left HP Mixer", "MIC1 Switch", "MIC1 Input"}, {"Left HP Mixer", "MIC2 Switch", "MIC2 Input"}, {"Left HP Mixer", "INA1 Switch", "INA1 Input"}, {"Left HP Mixer", "INA2 Switch", "INA2 Input"}, {"Left HP Mixer", "INB1 Switch", "INB1 Input"}, {"Left HP Mixer", "INB2 Switch", "INB2 Input"}, /* Right headphone output mixer */ {"Right HP Mixer", "Left DAC1 Switch", "DACL1"}, {"Right HP Mixer", "Left DAC2 Switch", "DACL2" }, {"Right HP Mixer", "Right DAC1 Switch", "DACR1"}, {"Right HP Mixer", "Right DAC2 Switch", "DACR2"}, {"Right HP Mixer", "MIC1 Switch", "MIC1 Input"}, {"Right HP Mixer", "MIC2 Switch", "MIC2 Input"}, {"Right HP Mixer", "INA1 Switch", "INA1 Input"}, {"Right HP Mixer", "INA2 Switch", "INA2 Input"}, {"Right HP Mixer", "INB1 Switch", "INB1 Input"}, {"Right HP Mixer", "INB2 Switch", "INB2 Input"}, /* Left speaker output mixer */ {"Left SPK Mixer", "Left DAC1 Switch", "DACL1"}, {"Left SPK Mixer", "Left DAC2 Switch", "DACL2"}, {"Left SPK Mixer", "Right DAC1 Switch", "DACR1"}, {"Left SPK Mixer", "Right DAC2 Switch", "DACR2"}, {"Left SPK Mixer", "MIC1 Switch", "MIC1 Input"}, {"Left SPK Mixer", "MIC2 Switch", "MIC2 Input"}, {"Left SPK Mixer", "INA1 Switch", "INA1 Input"}, {"Left SPK Mixer", "INA2 Switch", "INA2 Input"}, {"Left SPK Mixer", "INB1 Switch", "INB1 Input"}, {"Left SPK Mixer", "INB2 Switch", "INB2 Input"}, /* Right speaker output mixer */ {"Right SPK Mixer", "Left DAC1 Switch", "DACL1"}, {"Right SPK Mixer", "Left DAC2 Switch", "DACL2"}, {"Right SPK Mixer", "Right DAC1 Switch", "DACR1"}, {"Right SPK Mixer", "Right DAC2 Switch", "DACR2"}, {"Right SPK Mixer", "MIC1 Switch", "MIC1 Input"}, {"Right SPK Mixer", "MIC2 Switch", "MIC2 Input"}, {"Right SPK Mixer", "INA1 Switch", "INA1 Input"}, {"Right SPK Mixer", "INA2 Switch", "INA2 Input"}, {"Right SPK Mixer", "INB1 Switch", "INB1 Input"}, {"Right SPK Mixer", "INB2 Switch", "INB2 Input"}, /* Earpiece/Receiver output mixer */ {"Left REC Mixer", "Left DAC1 Switch", "DACL1"}, {"Left REC Mixer", "Left DAC2 Switch", "DACL2"}, {"Left REC Mixer", "Right DAC1 Switch", "DACR1"}, {"Left REC Mixer", "Right DAC2 Switch", "DACR2"}, {"Left REC Mixer", "MIC1 Switch", "MIC1 Input"}, {"Left REC Mixer", "MIC2 Switch", "MIC2 Input"}, {"Left REC Mixer", "INA1 Switch", "INA1 Input"}, {"Left REC Mixer", "INA2 Switch", "INA2 Input"}, {"Left REC Mixer", "INB1 Switch", "INB1 Input"}, {"Left REC Mixer", "INB2 Switch", "INB2 Input"}, /* Earpiece/Receiver output mixer */ {"Right REC Mixer", "Left DAC1 Switch", "DACL1"}, {"Right REC Mixer", "Left DAC2 Switch", "DACL2"}, {"Right REC Mixer", "Right DAC1 Switch", "DACR1"}, {"Right REC Mixer", "Right DAC2 Switch", "DACR2"}, {"Right REC Mixer", "MIC1 Switch", "MIC1 Input"}, {"Right REC Mixer", "MIC2 Switch", "MIC2 Input"}, {"Right REC Mixer", "INA1 Switch", "INA1 Input"}, {"Right REC Mixer", "INA2 Switch", "INA2 Input"}, {"Right REC Mixer", "INB1 Switch", "INB1 Input"}, {"Right REC Mixer", "INB2 Switch", "INB2 Input"}, {"HP Left Out", NULL, "Left HP Mixer"}, {"HP Right Out", NULL, "Right HP Mixer"}, {"SPK Left Out", NULL, "Left SPK Mixer"}, {"SPK Right Out", NULL, "Right SPK Mixer"}, {"REC Left Out", NULL, "Left REC Mixer"}, {"REC Right Out", NULL, "Right REC Mixer"}, {"HPL", NULL, "HP Left Out"}, {"HPR", NULL, "HP Right Out"}, {"SPKL", NULL, "SPK Left Out"}, {"SPKR", NULL, "SPK Right Out"}, {"RECL", NULL, "REC Left Out"}, {"RECR", NULL, "REC Right Out"}, /* Left ADC input mixer */ {"Left ADC Mixer", "MIC1 Switch", "MIC1 Input"}, {"Left ADC Mixer", "MIC2 Switch", "MIC2 Input"}, {"Left ADC Mixer", "INA1 Switch", "INA1 Input"}, {"Left ADC Mixer", "INA2 Switch", "INA2 Input"}, {"Left ADC Mixer", "INB1 Switch", "INB1 Input"}, {"Left ADC Mixer", "INB2 Switch", "INB2 Input"}, /* Right ADC input mixer */ {"Right ADC Mixer", "MIC1 Switch", "MIC1 Input"}, {"Right ADC Mixer", "MIC2 Switch", "MIC2 Input"}, {"Right ADC Mixer", "INA1 Switch", "INA1 Input"}, {"Right ADC Mixer", "INA2 Switch", "INA2 Input"}, {"Right ADC Mixer", "INB1 Switch", "INB1 Input"}, {"Right ADC Mixer", "INB2 Switch", "INB2 Input"}, /* Inputs */ {"ADCL", NULL, "Left ADC Mixer"}, {"ADCR", NULL, "Right ADC Mixer"}, {"INA1 Input", NULL, "INA1"}, {"INA2 Input", NULL, "INA2"}, {"INB1 Input", NULL, "INB1"}, {"INB2 Input", NULL, "INB2"}, {"MIC1 Input", NULL, "MIC1"}, {"MIC2 Input", NULL, "MIC2"}, }; /* codec mclk clock divider coefficients */ static const struct { u32 rate; u8 sr; } rate_table[] = { {8000, 0x10}, {11025, 0x20}, {16000, 0x30}, {22050, 0x40}, {24000, 0x50}, {32000, 0x60}, {44100, 0x70}, {48000, 0x80}, {88200, 0x90}, {96000, 0xA0}, }; static inline int rate_value(int rate, u8 *value) { int i; for (i = 0; i < ARRAY_SIZE(rate_table); i++) { if (rate_table[i].rate >= rate) { *value = rate_table[i].sr; return 0; } } *value = rate_table[0].sr; return -EINVAL; } static int max98088_dai1_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { struct snd_soc_codec *codec = dai->codec; struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec); struct max98088_cdata *cdata; unsigned long long ni; unsigned int rate; u8 regval; cdata = &max98088->dai[0]; rate = params_rate(params); switch (params_format(params)) { case SNDRV_PCM_FORMAT_S16_LE: snd_soc_update_bits(codec, M98088_REG_14_DAI1_FORMAT, M98088_DAI_WS, 0); break; case SNDRV_PCM_FORMAT_S24_LE: snd_soc_update_bits(codec, M98088_REG_14_DAI1_FORMAT, M98088_DAI_WS, M98088_DAI_WS); break; default: return -EINVAL; } snd_soc_update_bits(codec, M98088_REG_51_PWR_SYS, M98088_SHDNRUN, 0); if (rate_value(rate, &regval)) return -EINVAL; snd_soc_update_bits(codec, M98088_REG_11_DAI1_CLKMODE, M98088_CLKMODE_MASK, regval); cdata->rate = rate; /* Configure NI when operating as master */ if (snd_soc_read(codec, M98088_REG_14_DAI1_FORMAT) & M98088_DAI_MAS) { if (max98088->sysclk == 0) { dev_err(codec->dev, "Invalid system clock frequency\n"); return -EINVAL; } ni = 65536ULL * (rate < 50000 ? 96ULL : 48ULL) * (unsigned long long int)rate; do_div(ni, (unsigned long long int)max98088->sysclk); snd_soc_write(codec, M98088_REG_12_DAI1_CLKCFG_HI, (ni >> 8) & 0x7F); snd_soc_write(codec, M98088_REG_13_DAI1_CLKCFG_LO, ni & 0xFF); } /* Update sample rate mode */ if (rate < 50000) snd_soc_update_bits(codec, M98088_REG_18_DAI1_FILTERS, M98088_DAI_DHF, 0); else snd_soc_update_bits(codec, M98088_REG_18_DAI1_FILTERS, M98088_DAI_DHF, M98088_DAI_DHF); snd_soc_update_bits(codec, M98088_REG_51_PWR_SYS, M98088_SHDNRUN, M98088_SHDNRUN); return 0; } static int max98088_dai2_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { struct snd_soc_codec *codec = dai->codec; struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec); struct max98088_cdata *cdata; unsigned long long ni; unsigned int rate; u8 regval; cdata = &max98088->dai[1]; rate = params_rate(params); switch (params_format(params)) { case SNDRV_PCM_FORMAT_S16_LE: snd_soc_update_bits(codec, M98088_REG_1C_DAI2_FORMAT, M98088_DAI_WS, 0); break; case SNDRV_PCM_FORMAT_S24_LE: snd_soc_update_bits(codec, M98088_REG_1C_DAI2_FORMAT, M98088_DAI_WS, M98088_DAI_WS); break; default: return -EINVAL; } snd_soc_update_bits(codec, M98088_REG_51_PWR_SYS, M98088_SHDNRUN, 0); if (rate_value(rate, &regval)) return -EINVAL; snd_soc_update_bits(codec, M98088_REG_19_DAI2_CLKMODE, M98088_CLKMODE_MASK, regval); cdata->rate = rate; /* Configure NI when operating as master */ if (snd_soc_read(codec, M98088_REG_1C_DAI2_FORMAT) & M98088_DAI_MAS) { if (max98088->sysclk == 0) { dev_err(codec->dev, "Invalid system clock frequency\n"); return -EINVAL; } ni = 65536ULL * (rate < 50000 ? 96ULL : 48ULL) * (unsigned long long int)rate; do_div(ni, (unsigned long long int)max98088->sysclk); snd_soc_write(codec, M98088_REG_1A_DAI2_CLKCFG_HI, (ni >> 8) & 0x7F); snd_soc_write(codec, M98088_REG_1B_DAI2_CLKCFG_LO, ni & 0xFF); } /* Update sample rate mode */ if (rate < 50000) snd_soc_update_bits(codec, M98088_REG_20_DAI2_FILTERS, M98088_DAI_DHF, 0); else snd_soc_update_bits(codec, M98088_REG_20_DAI2_FILTERS, M98088_DAI_DHF, M98088_DAI_DHF); snd_soc_update_bits(codec, M98088_REG_51_PWR_SYS, M98088_SHDNRUN, M98088_SHDNRUN); return 0; } static int max98088_dai_set_sysclk(struct snd_soc_dai *dai, int clk_id, unsigned int freq, int dir) { struct snd_soc_codec *codec = dai->codec; struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec); /* Requested clock frequency is already setup */ if (freq == max98088->sysclk) return 0; /* Setup clocks for slave mode, and using the PLL * PSCLK = 0x01 (when master clk is 10MHz to 20MHz) * 0x02 (when master clk is 20MHz to 30MHz).. */ if ((freq >= 10000000) && (freq < 20000000)) { snd_soc_write(codec, M98088_REG_10_SYS_CLK, 0x10); } else if ((freq >= 20000000) && (freq < 30000000)) { snd_soc_write(codec, M98088_REG_10_SYS_CLK, 0x20); } else { dev_err(codec->dev, "Invalid master clock frequency\n"); return -EINVAL; } if (snd_soc_read(codec, M98088_REG_51_PWR_SYS) & M98088_SHDNRUN) { snd_soc_update_bits(codec, M98088_REG_51_PWR_SYS, M98088_SHDNRUN, 0); snd_soc_update_bits(codec, M98088_REG_51_PWR_SYS, M98088_SHDNRUN, M98088_SHDNRUN); } dev_dbg(dai->dev, "Clock source is %d at %uHz\n", clk_id, freq); max98088->sysclk = freq; return 0; } static int max98088_dai1_set_fmt(struct snd_soc_dai *codec_dai, unsigned int fmt) { struct snd_soc_codec *codec = codec_dai->codec; struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec); struct max98088_cdata *cdata; u8 reg15val; u8 reg14val = 0; cdata = &max98088->dai[0]; if (fmt != cdata->fmt) { cdata->fmt = fmt; switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) { case SND_SOC_DAIFMT_CBS_CFS: /* Slave mode PLL */ snd_soc_write(codec, M98088_REG_12_DAI1_CLKCFG_HI, 0x80); snd_soc_write(codec, M98088_REG_13_DAI1_CLKCFG_LO, 0x00); break; case SND_SOC_DAIFMT_CBM_CFM: /* Set to master mode */ reg14val |= M98088_DAI_MAS; break; case SND_SOC_DAIFMT_CBS_CFM: case SND_SOC_DAIFMT_CBM_CFS: default: dev_err(codec->dev, "Clock mode unsupported"); return -EINVAL; } switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { case SND_SOC_DAIFMT_I2S: reg14val |= M98088_DAI_DLY; break; case SND_SOC_DAIFMT_LEFT_J: break; default: return -EINVAL; } switch (fmt & SND_SOC_DAIFMT_INV_MASK) { case SND_SOC_DAIFMT_NB_NF: break; case SND_SOC_DAIFMT_NB_IF: reg14val |= M98088_DAI_WCI; break; case SND_SOC_DAIFMT_IB_NF: reg14val |= M98088_DAI_BCI; break; case SND_SOC_DAIFMT_IB_IF: reg14val |= M98088_DAI_BCI|M98088_DAI_WCI; break; default: return -EINVAL; } snd_soc_update_bits(codec, M98088_REG_14_DAI1_FORMAT, M98088_DAI_MAS | M98088_DAI_DLY | M98088_DAI_BCI | M98088_DAI_WCI, reg14val); reg15val = M98088_DAI_BSEL64; if (max98088->digmic) reg15val |= M98088_DAI_OSR64; snd_soc_write(codec, M98088_REG_15_DAI1_CLOCK, reg15val); } return 0; } static int max98088_dai2_set_fmt(struct snd_soc_dai *codec_dai, unsigned int fmt) { struct snd_soc_codec *codec = codec_dai->codec; struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec); struct max98088_cdata *cdata; u8 reg1Cval = 0; cdata = &max98088->dai[1]; if (fmt != cdata->fmt) { cdata->fmt = fmt; switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) { case SND_SOC_DAIFMT_CBS_CFS: /* Slave mode PLL */ snd_soc_write(codec, M98088_REG_1A_DAI2_CLKCFG_HI, 0x80); snd_soc_write(codec, M98088_REG_1B_DAI2_CLKCFG_LO, 0x00); break; case SND_SOC_DAIFMT_CBM_CFM: /* Set to master mode */ reg1Cval |= M98088_DAI_MAS; break; case SND_SOC_DAIFMT_CBS_CFM: case SND_SOC_DAIFMT_CBM_CFS: default: dev_err(codec->dev, "Clock mode unsupported"); return -EINVAL; } switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { case SND_SOC_DAIFMT_I2S: reg1Cval |= M98088_DAI_DLY; break; case SND_SOC_DAIFMT_LEFT_J: break; default: return -EINVAL; } switch (fmt & SND_SOC_DAIFMT_INV_MASK) { case SND_SOC_DAIFMT_NB_NF: break; case SND_SOC_DAIFMT_NB_IF: reg1Cval |= M98088_DAI_WCI; break; case SND_SOC_DAIFMT_IB_NF: reg1Cval |= M98088_DAI_BCI; break; case SND_SOC_DAIFMT_IB_IF: reg1Cval |= M98088_DAI_BCI|M98088_DAI_WCI; break; default: return -EINVAL; } snd_soc_update_bits(codec, M98088_REG_1C_DAI2_FORMAT, M98088_DAI_MAS | M98088_DAI_DLY | M98088_DAI_BCI | M98088_DAI_WCI, reg1Cval); snd_soc_write(codec, M98088_REG_1D_DAI2_CLOCK, M98088_DAI_BSEL64); } return 0; } static int max98088_dai1_digital_mute(struct snd_soc_dai *codec_dai, int mute) { struct snd_soc_codec *codec = codec_dai->codec; int reg; if (mute) reg = M98088_DAI_MUTE; else reg = 0; snd_soc_update_bits(codec, M98088_REG_2F_LVL_DAI1_PLAY, M98088_DAI_MUTE_MASK, reg); return 0; } static int max98088_dai2_digital_mute(struct snd_soc_dai *codec_dai, int mute) { struct snd_soc_codec *codec = codec_dai->codec; int reg; if (mute) reg = M98088_DAI_MUTE; else reg = 0; snd_soc_update_bits(codec, M98088_REG_31_LVL_DAI2_PLAY, M98088_DAI_MUTE_MASK, reg); return 0; } static void max98088_sync_cache(struct snd_soc_codec *codec) { u8 *reg_cache = codec->reg_cache; int i; if (!codec->cache_sync) return; codec->cache_only = 0; /* write back cached values if they're writeable and * different from the hardware default. */ for (i = 1; i < codec->driver->reg_cache_size; i++) { if (!max98088_access[i].writable) continue; if (reg_cache[i] == max98088_reg[i]) continue; snd_soc_write(codec, i, reg_cache[i]); } codec->cache_sync = 0; } static int max98088_set_bias_level(struct snd_soc_codec *codec, enum snd_soc_bias_level level) { switch (level) { case SND_SOC_BIAS_ON: break; case SND_SOC_BIAS_PREPARE: break; case SND_SOC_BIAS_STANDBY: if (codec->dapm.bias_level == SND_SOC_BIAS_OFF) max98088_sync_cache(codec); snd_soc_update_bits(codec, M98088_REG_4C_PWR_EN_IN, M98088_MBEN, M98088_MBEN); break; case SND_SOC_BIAS_OFF: snd_soc_update_bits(codec, M98088_REG_4C_PWR_EN_IN, M98088_MBEN, 0); codec->cache_sync = 1; break; } codec->dapm.bias_level = level; return 0; } #define MAX98088_RATES SNDRV_PCM_RATE_8000_96000 #define MAX98088_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S24_LE) static const struct snd_soc_dai_ops max98088_dai1_ops = { .set_sysclk = max98088_dai_set_sysclk, .set_fmt = max98088_dai1_set_fmt, .hw_params = max98088_dai1_hw_params, .digital_mute = max98088_dai1_digital_mute, }; static const struct snd_soc_dai_ops max98088_dai2_ops = { .set_sysclk = max98088_dai_set_sysclk, .set_fmt = max98088_dai2_set_fmt, .hw_params = max98088_dai2_hw_params, .digital_mute = max98088_dai2_digital_mute, }; static struct snd_soc_dai_driver max98088_dai[] = { { .name = "HiFi", .playback = { .stream_name = "HiFi Playback", .channels_min = 1, .channels_max = 2, .rates = MAX98088_RATES, .formats = MAX98088_FORMATS, }, .capture = { .stream_name = "HiFi Capture", .channels_min = 1, .channels_max = 2, .rates = MAX98088_RATES, .formats = MAX98088_FORMATS, }, .ops = &max98088_dai1_ops, }, { .name = "Aux", .playback = { .stream_name = "Aux Playback", .channels_min = 1, .channels_max = 2, .rates = MAX98088_RATES, .formats = MAX98088_FORMATS, }, .ops = &max98088_dai2_ops, } }; static const char *eq_mode_name[] = {"EQ1 Mode", "EQ2 Mode"}; static int max98088_get_channel(struct snd_soc_codec *codec, const char *name) { int i; for (i = 0; i < ARRAY_SIZE(eq_mode_name); i++) if (strcmp(name, eq_mode_name[i]) == 0) return i; /* Shouldn't happen */ dev_err(codec->dev, "Bad EQ channel name '%s'\n", name); return -EINVAL; } static void max98088_setup_eq1(struct snd_soc_codec *codec) { struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec); struct max98088_pdata *pdata = max98088->pdata; struct max98088_eq_cfg *coef_set; int best, best_val, save, i, sel, fs; struct max98088_cdata *cdata; cdata = &max98088->dai[0]; if (!pdata || !max98088->eq_textcnt) return; /* Find the selected configuration with nearest sample rate */ fs = cdata->rate; sel = cdata->eq_sel; best = 0; best_val = INT_MAX; for (i = 0; i < pdata->eq_cfgcnt; i++) { if (strcmp(pdata->eq_cfg[i].name, max98088->eq_texts[sel]) == 0 && abs(pdata->eq_cfg[i].rate - fs) < best_val) { best = i; best_val = abs(pdata->eq_cfg[i].rate - fs); } } dev_dbg(codec->dev, "Selected %s/%dHz for %dHz sample rate\n", pdata->eq_cfg[best].name, pdata->eq_cfg[best].rate, fs); /* Disable EQ while configuring, and save current on/off state */ save = snd_soc_read(codec, M98088_REG_49_CFG_LEVEL); snd_soc_update_bits(codec, M98088_REG_49_CFG_LEVEL, M98088_EQ1EN, 0); coef_set = &pdata->eq_cfg[sel]; m98088_eq_band(codec, 0, 0, coef_set->band1); m98088_eq_band(codec, 0, 1, coef_set->band2); m98088_eq_band(codec, 0, 2, coef_set->band3); m98088_eq_band(codec, 0, 3, coef_set->band4); m98088_eq_band(codec, 0, 4, coef_set->band5); /* Restore the original on/off state */ snd_soc_update_bits(codec, M98088_REG_49_CFG_LEVEL, M98088_EQ1EN, save); } static void max98088_setup_eq2(struct snd_soc_codec *codec) { struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec); struct max98088_pdata *pdata = max98088->pdata; struct max98088_eq_cfg *coef_set; int best, best_val, save, i, sel, fs; struct max98088_cdata *cdata; cdata = &max98088->dai[1]; if (!pdata || !max98088->eq_textcnt) return; /* Find the selected configuration with nearest sample rate */ fs = cdata->rate; sel = cdata->eq_sel; best = 0; best_val = INT_MAX; for (i = 0; i < pdata->eq_cfgcnt; i++) { if (strcmp(pdata->eq_cfg[i].name, max98088->eq_texts[sel]) == 0 && abs(pdata->eq_cfg[i].rate - fs) < best_val) { best = i; best_val = abs(pdata->eq_cfg[i].rate - fs); } } dev_dbg(codec->dev, "Selected %s/%dHz for %dHz sample rate\n", pdata->eq_cfg[best].name, pdata->eq_cfg[best].rate, fs); /* Disable EQ while configuring, and save current on/off state */ save = snd_soc_read(codec, M98088_REG_49_CFG_LEVEL); snd_soc_update_bits(codec, M98088_REG_49_CFG_LEVEL, M98088_EQ2EN, 0); coef_set = &pdata->eq_cfg[sel]; m98088_eq_band(codec, 1, 0, coef_set->band1); m98088_eq_band(codec, 1, 1, coef_set->band2); m98088_eq_band(codec, 1, 2, coef_set->band3); m98088_eq_band(codec, 1, 3, coef_set->band4); m98088_eq_band(codec, 1, 4, coef_set->band5); /* Restore the original on/off state */ snd_soc_update_bits(codec, M98088_REG_49_CFG_LEVEL, M98088_EQ2EN, save); } static int max98088_put_eq_enum(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec); struct max98088_pdata *pdata = max98088->pdata; int channel = max98088_get_channel(codec, kcontrol->id.name); struct max98088_cdata *cdata; int sel = ucontrol->value.integer.value[0]; if (channel < 0) return channel; cdata = &max98088->dai[channel]; if (sel >= pdata->eq_cfgcnt) return -EINVAL; cdata->eq_sel = sel; switch (channel) { case 0: max98088_setup_eq1(codec); break; case 1: max98088_setup_eq2(codec); break; } return 0; } static int max98088_get_eq_enum(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) { struct snd_soc_codec *codec = snd_kcontrol_chip(kcontrol); struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec); int channel = max98088_get_channel(codec, kcontrol->id.name); struct max98088_cdata *cdata; if (channel < 0) return channel; cdata = &max98088->dai[channel]; ucontrol->value.enumerated.item[0] = cdata->eq_sel; return 0; } static void max98088_handle_eq_pdata(struct snd_soc_codec *codec) { struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec); struct max98088_pdata *pdata = max98088->pdata; struct max98088_eq_cfg *cfg; unsigned int cfgcnt; int i, j; const char **t; int ret; struct snd_kcontrol_new controls[] = { SOC_ENUM_EXT((char *)eq_mode_name[0], max98088->eq_enum, max98088_get_eq_enum, max98088_put_eq_enum), SOC_ENUM_EXT((char *)eq_mode_name[1], max98088->eq_enum, max98088_get_eq_enum, max98088_put_eq_enum), }; BUILD_BUG_ON(ARRAY_SIZE(controls) != ARRAY_SIZE(eq_mode_name)); cfg = pdata->eq_cfg; cfgcnt = pdata->eq_cfgcnt; /* Setup an array of texts for the equalizer enum. * This is based on Mark Brown's equalizer driver code. */ max98088->eq_textcnt = 0; max98088->eq_texts = NULL; for (i = 0; i < cfgcnt; i++) { for (j = 0; j < max98088->eq_textcnt; j++) { if (strcmp(cfg[i].name, max98088->eq_texts[j]) == 0) break; } if (j != max98088->eq_textcnt) continue; /* Expand the array */ t = krealloc(max98088->eq_texts, sizeof(char *) * (max98088->eq_textcnt + 1), GFP_KERNEL); if (t == NULL) continue; /* Store the new entry */ t[max98088->eq_textcnt] = cfg[i].name; max98088->eq_textcnt++; max98088->eq_texts = t; } /* Now point the soc_enum to .texts array items */ max98088->eq_enum.texts = max98088->eq_texts; max98088->eq_enum.max = max98088->eq_textcnt; ret = snd_soc_add_codec_controls(codec, controls, ARRAY_SIZE(controls)); if (ret != 0) dev_err(codec->dev, "Failed to add EQ control: %d\n", ret); } static void max98088_handle_pdata(struct snd_soc_codec *codec) { struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec); struct max98088_pdata *pdata = max98088->pdata; u8 regval = 0; if (!pdata) { dev_dbg(codec->dev, "No platform data\n"); return; } /* Configure mic for analog/digital mic mode */ if (pdata->digmic_left_mode) regval |= M98088_DIGMIC_L; if (pdata->digmic_right_mode) regval |= M98088_DIGMIC_R; max98088->digmic = (regval ? 1 : 0); snd_soc_write(codec, M98088_REG_48_CFG_MIC, regval); /* Configure receiver output */ regval = ((pdata->receiver_mode) ? M98088_REC_LINEMODE : 0); snd_soc_update_bits(codec, M98088_REG_2A_MIC_REC_CNTL, M98088_REC_LINEMODE_MASK, regval); /* Configure equalizers */ if (pdata->eq_cfgcnt) max98088_handle_eq_pdata(codec); } #ifdef CONFIG_PM static int max98088_suspend(struct snd_soc_codec *codec) { max98088_set_bias_level(codec, SND_SOC_BIAS_OFF); return 0; } static int max98088_resume(struct snd_soc_codec *codec) { max98088_set_bias_level(codec, SND_SOC_BIAS_STANDBY); return 0; } #else #define max98088_suspend NULL #define max98088_resume NULL #endif static int max98088_probe(struct snd_soc_codec *codec) { struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec); struct max98088_cdata *cdata; int ret = 0; codec->cache_sync = 1; ret = snd_soc_codec_set_cache_io(codec, 8, 8, SND_SOC_I2C); if (ret != 0) { dev_err(codec->dev, "Failed to set cache I/O: %d\n", ret); return ret; } /* initialize private data */ max98088->sysclk = (unsigned)-1; max98088->eq_textcnt = 0; cdata = &max98088->dai[0]; cdata->rate = (unsigned)-1; cdata->fmt = (unsigned)-1; cdata->eq_sel = 0; cdata = &max98088->dai[1]; cdata->rate = (unsigned)-1; cdata->fmt = (unsigned)-1; cdata->eq_sel = 0; max98088->ina_state = 0; max98088->inb_state = 0; max98088->ex_mode = 0; max98088->digmic = 0; max98088->mic1pre = 0; max98088->mic2pre = 0; ret = snd_soc_read(codec, M98088_REG_FF_REV_ID); if (ret < 0) { dev_err(codec->dev, "Failed to read device revision: %d\n", ret); goto err_access; } dev_info(codec->dev, "revision %c\n", ret - 0x40 + 'A'); snd_soc_write(codec, M98088_REG_51_PWR_SYS, M98088_PWRSV); /* initialize registers cache to hardware default */ max98088_set_bias_level(codec, SND_SOC_BIAS_STANDBY); snd_soc_write(codec, M98088_REG_0F_IRQ_ENABLE, 0x00); snd_soc_write(codec, M98088_REG_22_MIX_DAC, M98088_DAI1L_TO_DACL|M98088_DAI2L_TO_DACL| M98088_DAI1R_TO_DACR|M98088_DAI2R_TO_DACR); snd_soc_write(codec, M98088_REG_4E_BIAS_CNTL, 0xF0); snd_soc_write(codec, M98088_REG_50_DAC_BIAS2, 0x0F); snd_soc_write(codec, M98088_REG_16_DAI1_IOCFG, M98088_S1NORMAL|M98088_SDATA); snd_soc_write(codec, M98088_REG_1E_DAI2_IOCFG, M98088_S2NORMAL|M98088_SDATA); max98088_handle_pdata(codec); snd_soc_add_codec_controls(codec, max98088_snd_controls, ARRAY_SIZE(max98088_snd_controls)); err_access: return ret; } static int max98088_remove(struct snd_soc_codec *codec) { struct max98088_priv *max98088 = snd_soc_codec_get_drvdata(codec); max98088_set_bias_level(codec, SND_SOC_BIAS_OFF); kfree(max98088->eq_texts); return 0; } static struct snd_soc_codec_driver soc_codec_dev_max98088 = { .probe = max98088_probe, .remove = max98088_remove, .suspend = max98088_suspend, .resume = max98088_resume, .set_bias_level = max98088_set_bias_level, .reg_cache_size = ARRAY_SIZE(max98088_reg), .reg_word_size = sizeof(u8), .reg_cache_default = max98088_reg, .volatile_register = max98088_volatile_register, .dapm_widgets = max98088_dapm_widgets, .num_dapm_widgets = ARRAY_SIZE(max98088_dapm_widgets), .dapm_routes = max98088_audio_map, .num_dapm_routes = ARRAY_SIZE(max98088_audio_map), }; static int max98088_i2c_probe(struct i2c_client *i2c, const struct i2c_device_id *id) { struct max98088_priv *max98088; int ret; max98088 = devm_kzalloc(&i2c->dev, sizeof(struct max98088_priv), GFP_KERNEL); if (max98088 == NULL) return -ENOMEM; max98088->devtype = id->driver_data; i2c_set_clientdata(i2c, max98088); max98088->pdata = i2c->dev.platform_data; ret = snd_soc_register_codec(&i2c->dev, &soc_codec_dev_max98088, &max98088_dai[0], 2); return ret; } static int max98088_i2c_remove(struct i2c_client *client) { snd_soc_unregister_codec(&client->dev); return 0; } static const struct i2c_device_id max98088_i2c_id[] = { { "max98088", MAX98088 }, { "max98089", MAX98089 }, { } }; MODULE_DEVICE_TABLE(i2c, max98088_i2c_id); static struct i2c_driver max98088_i2c_driver = { .driver = { .name = "max98088", .owner = THIS_MODULE, }, .probe = max98088_i2c_probe, .remove = max98088_i2c_remove, .id_table = max98088_i2c_id, }; module_i2c_driver(max98088_i2c_driver); MODULE_DESCRIPTION("ALSA SoC MAX98088 driver"); MODULE_AUTHOR("Peter Hsiang, Jesse Marroquin"); MODULE_LICENSE("GPL");
gpl-2.0
Jetson-TK1-AndroidTV/android_kernel_tegra_hdmi_prime
arch/mips/txx9/generic/setup_tx4939.c
1999
16955
/* * TX4939 setup routines * Based on linux/arch/mips/txx9/generic/setup_tx4938.c, * and RBTX49xx patch from CELF patch archive. * * 2003-2005 (c) MontaVista Software, Inc. * (C) Copyright TOSHIBA CORPORATION 2000-2001, 2004-2007 * * 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/ioport.h> #include <linux/delay.h> #include <linux/netdevice.h> #include <linux/notifier.h> #include <linux/device.h> #include <linux/ethtool.h> #include <linux/param.h> #include <linux/ptrace.h> #include <linux/mtd/physmap.h> #include <linux/platform_device.h> #include <asm/bootinfo.h> #include <asm/reboot.h> #include <asm/traps.h> #include <asm/txx9irq.h> #include <asm/txx9tmr.h> #include <asm/txx9/generic.h> #include <asm/txx9/ndfmc.h> #include <asm/txx9/dmac.h> #include <asm/txx9/tx4939.h> static void __init tx4939_wdr_init(void) { /* report watchdog reset status */ if (____raw_readq(&tx4939_ccfgptr->ccfg) & TX4939_CCFG_WDRST) pr_warning("Watchdog reset detected at 0x%lx\n", read_c0_errorepc()); /* clear WatchDogReset (W1C) */ tx4939_ccfg_set(TX4939_CCFG_WDRST); /* do reset on watchdog */ tx4939_ccfg_set(TX4939_CCFG_WR); } void __init tx4939_wdt_init(void) { txx9_wdt_init(TX4939_TMR_REG(2) & 0xfffffffffULL); } static void tx4939_machine_restart(char *command) { local_irq_disable(); pr_emerg("Rebooting (with %s watchdog reset)...\n", (____raw_readq(&tx4939_ccfgptr->ccfg) & TX4939_CCFG_WDREXEN) ? "external" : "internal"); /* clear watchdog status */ tx4939_ccfg_set(TX4939_CCFG_WDRST); /* W1C */ txx9_wdt_now(TX4939_TMR_REG(2) & 0xfffffffffULL); while (!(____raw_readq(&tx4939_ccfgptr->ccfg) & TX4939_CCFG_WDRST)) ; mdelay(10); if (____raw_readq(&tx4939_ccfgptr->ccfg) & TX4939_CCFG_WDREXEN) { pr_emerg("Rebooting (with internal watchdog reset)...\n"); /* External WDRST failed. Do internal watchdog reset */ tx4939_ccfg_clear(TX4939_CCFG_WDREXEN); } /* fallback */ (*_machine_halt)(); } void show_registers(struct pt_regs *regs); static int tx4939_be_handler(struct pt_regs *regs, int is_fixup) { int data = regs->cp0_cause & 4; console_verbose(); pr_err("%cBE exception at %#lx\n", data ? 'D' : 'I', regs->cp0_epc); pr_err("ccfg:%llx, toea:%llx\n", (unsigned long long)____raw_readq(&tx4939_ccfgptr->ccfg), (unsigned long long)____raw_readq(&tx4939_ccfgptr->toea)); #ifdef CONFIG_PCI tx4927_report_pcic_status(); #endif show_registers(regs); panic("BusError!"); } static void __init tx4939_be_init(void) { board_be_handler = tx4939_be_handler; } static struct resource tx4939_sdram_resource[4]; static struct resource tx4939_sram_resource; #define TX4939_SRAM_SIZE 0x800 void __init tx4939_add_memory_regions(void) { int i; unsigned long start, size; u64 win; for (i = 0; i < 4; i++) { if (!((__u32)____raw_readq(&tx4939_ddrcptr->winen) & (1 << i))) continue; win = ____raw_readq(&tx4939_ddrcptr->win[i]); start = (unsigned long)(win >> 48); size = (((unsigned long)(win >> 32) & 0xffff) + 1) - start; add_memory_region(start << 20, size << 20, BOOT_MEM_RAM); } } void __init tx4939_setup(void) { int i; __u32 divmode; __u64 pcfg; unsigned int cpuclk = 0; txx9_reg_res_init(TX4939_REV_PCODE(), TX4939_REG_BASE, TX4939_REG_SIZE); set_c0_config(TX49_CONF_CWFON); /* SDRAMC,EBUSC are configured by PROM */ for (i = 0; i < 4; i++) { if (!(TX4939_EBUSC_CR(i) & 0x8)) continue; /* disabled */ txx9_ce_res[i].start = (unsigned long)TX4939_EBUSC_BA(i); txx9_ce_res[i].end = txx9_ce_res[i].start + TX4939_EBUSC_SIZE(i) - 1; request_resource(&iomem_resource, &txx9_ce_res[i]); } /* clocks */ if (txx9_master_clock) { /* calculate cpu_clock from master_clock */ divmode = (__u32)____raw_readq(&tx4939_ccfgptr->ccfg) & TX4939_CCFG_MULCLK_MASK; cpuclk = txx9_master_clock * 20 / 2; switch (divmode) { case TX4939_CCFG_MULCLK_8: cpuclk = cpuclk / 3 * 4 /* / 6 * 8 */; break; case TX4939_CCFG_MULCLK_9: cpuclk = cpuclk / 2 * 3 /* / 6 * 9 */; break; case TX4939_CCFG_MULCLK_10: cpuclk = cpuclk / 3 * 5 /* / 6 * 10 */; break; case TX4939_CCFG_MULCLK_11: cpuclk = cpuclk / 6 * 11; break; case TX4939_CCFG_MULCLK_12: cpuclk = cpuclk * 2 /* / 6 * 12 */; break; case TX4939_CCFG_MULCLK_13: cpuclk = cpuclk / 6 * 13; break; case TX4939_CCFG_MULCLK_14: cpuclk = cpuclk / 3 * 7 /* / 6 * 14 */; break; case TX4939_CCFG_MULCLK_15: cpuclk = cpuclk / 2 * 5 /* / 6 * 15 */; break; } txx9_cpu_clock = cpuclk; } else { if (txx9_cpu_clock == 0) txx9_cpu_clock = 400000000; /* 400MHz */ /* calculate master_clock from cpu_clock */ cpuclk = txx9_cpu_clock; divmode = (__u32)____raw_readq(&tx4939_ccfgptr->ccfg) & TX4939_CCFG_MULCLK_MASK; switch (divmode) { case TX4939_CCFG_MULCLK_8: txx9_master_clock = cpuclk * 6 / 8; break; case TX4939_CCFG_MULCLK_9: txx9_master_clock = cpuclk * 6 / 9; break; case TX4939_CCFG_MULCLK_10: txx9_master_clock = cpuclk * 6 / 10; break; case TX4939_CCFG_MULCLK_11: txx9_master_clock = cpuclk * 6 / 11; break; case TX4939_CCFG_MULCLK_12: txx9_master_clock = cpuclk * 6 / 12; break; case TX4939_CCFG_MULCLK_13: txx9_master_clock = cpuclk * 6 / 13; break; case TX4939_CCFG_MULCLK_14: txx9_master_clock = cpuclk * 6 / 14; break; case TX4939_CCFG_MULCLK_15: txx9_master_clock = cpuclk * 6 / 15; break; } txx9_master_clock /= 10; /* * 2 / 20 */ } /* calculate gbus_clock from cpu_clock */ divmode = (__u32)____raw_readq(&tx4939_ccfgptr->ccfg) & TX4939_CCFG_YDIVMODE_MASK; txx9_gbus_clock = txx9_cpu_clock; switch (divmode) { case TX4939_CCFG_YDIVMODE_2: txx9_gbus_clock /= 2; break; case TX4939_CCFG_YDIVMODE_3: txx9_gbus_clock /= 3; break; case TX4939_CCFG_YDIVMODE_5: txx9_gbus_clock /= 5; break; case TX4939_CCFG_YDIVMODE_6: txx9_gbus_clock /= 6; break; } /* change default value to udelay/mdelay take reasonable time */ loops_per_jiffy = txx9_cpu_clock / HZ / 2; /* CCFG */ tx4939_wdr_init(); /* clear BusErrorOnWrite flag (W1C) */ tx4939_ccfg_set(TX4939_CCFG_WDRST | TX4939_CCFG_BEOW); /* enable Timeout BusError */ if (txx9_ccfg_toeon) tx4939_ccfg_set(TX4939_CCFG_TOE); /* DMA selection */ txx9_clear64(&tx4939_ccfgptr->pcfg, TX4939_PCFG_DMASEL_ALL); /* Use external clock for external arbiter */ if (!(____raw_readq(&tx4939_ccfgptr->ccfg) & TX4939_CCFG_PCIARB)) txx9_clear64(&tx4939_ccfgptr->pcfg, TX4939_PCFG_PCICLKEN_ALL); pr_info("%s -- %dMHz(M%dMHz,G%dMHz) CRIR:%08x CCFG:%llx PCFG:%llx\n", txx9_pcode_str, (cpuclk + 500000) / 1000000, (txx9_master_clock + 500000) / 1000000, (txx9_gbus_clock + 500000) / 1000000, (__u32)____raw_readq(&tx4939_ccfgptr->crir), (unsigned long long)____raw_readq(&tx4939_ccfgptr->ccfg), (unsigned long long)____raw_readq(&tx4939_ccfgptr->pcfg)); pr_info("%s DDRC -- EN:%08x", txx9_pcode_str, (__u32)____raw_readq(&tx4939_ddrcptr->winen)); for (i = 0; i < 4; i++) { __u64 win = ____raw_readq(&tx4939_ddrcptr->win[i]); if (!((__u32)____raw_readq(&tx4939_ddrcptr->winen) & (1 << i))) continue; /* disabled */ printk(KERN_CONT " #%d:%016llx", i, (unsigned long long)win); tx4939_sdram_resource[i].name = "DDR SDRAM"; tx4939_sdram_resource[i].start = (unsigned long)(win >> 48) << 20; tx4939_sdram_resource[i].end = ((((unsigned long)(win >> 32) & 0xffff) + 1) << 20) - 1; tx4939_sdram_resource[i].flags = IORESOURCE_MEM; request_resource(&iomem_resource, &tx4939_sdram_resource[i]); } printk(KERN_CONT "\n"); /* SRAM */ if (____raw_readq(&tx4939_sramcptr->cr) & 1) { unsigned int size = TX4939_SRAM_SIZE; tx4939_sram_resource.name = "SRAM"; tx4939_sram_resource.start = (____raw_readq(&tx4939_sramcptr->cr) >> (39-11)) & ~(size - 1); tx4939_sram_resource.end = tx4939_sram_resource.start + TX4939_SRAM_SIZE - 1; tx4939_sram_resource.flags = IORESOURCE_MEM; request_resource(&iomem_resource, &tx4939_sram_resource); } /* TMR */ /* disable all timers */ for (i = 0; i < TX4939_NR_TMR; i++) txx9_tmr_init(TX4939_TMR_REG(i) & 0xfffffffffULL); /* set PCIC1 reset (required to prevent hangup on BIST) */ txx9_set64(&tx4939_ccfgptr->clkctr, TX4939_CLKCTR_PCI1RST); pcfg = ____raw_readq(&tx4939_ccfgptr->pcfg); if (pcfg & (TX4939_PCFG_ET0MODE | TX4939_PCFG_ET1MODE)) { mdelay(1); /* at least 128 cpu clock */ /* clear PCIC1 reset */ txx9_clear64(&tx4939_ccfgptr->clkctr, TX4939_CLKCTR_PCI1RST); } else { pr_info("%s: stop PCIC1\n", txx9_pcode_str); /* stop PCIC1 */ txx9_set64(&tx4939_ccfgptr->clkctr, TX4939_CLKCTR_PCI1CKD); } if (!(pcfg & TX4939_PCFG_ET0MODE)) { pr_info("%s: stop ETH0\n", txx9_pcode_str); txx9_set64(&tx4939_ccfgptr->clkctr, TX4939_CLKCTR_ETH0RST); txx9_set64(&tx4939_ccfgptr->clkctr, TX4939_CLKCTR_ETH0CKD); } if (!(pcfg & TX4939_PCFG_ET1MODE)) { pr_info("%s: stop ETH1\n", txx9_pcode_str); txx9_set64(&tx4939_ccfgptr->clkctr, TX4939_CLKCTR_ETH1RST); txx9_set64(&tx4939_ccfgptr->clkctr, TX4939_CLKCTR_ETH1CKD); } _machine_restart = tx4939_machine_restart; board_be_init = tx4939_be_init; } void __init tx4939_time_init(unsigned int tmrnr) { if (____raw_readq(&tx4939_ccfgptr->ccfg) & TX4939_CCFG_TINTDIS) txx9_clockevent_init(TX4939_TMR_REG(tmrnr) & 0xfffffffffULL, TXX9_IRQ_BASE + TX4939_IR_TMR(tmrnr), TXX9_IMCLK); } void __init tx4939_sio_init(unsigned int sclk, unsigned int cts_mask) { int i; unsigned int ch_mask = 0; __u64 pcfg = __raw_readq(&tx4939_ccfgptr->pcfg); cts_mask |= ~1; /* only SIO0 have RTS/CTS */ if ((pcfg & TX4939_PCFG_SIO2MODE_MASK) != TX4939_PCFG_SIO2MODE_SIO0) cts_mask |= 1 << 0; /* disable SIO0 RTS/CTS by PCFG setting */ if ((pcfg & TX4939_PCFG_SIO2MODE_MASK) != TX4939_PCFG_SIO2MODE_SIO2) ch_mask |= 1 << 2; /* disable SIO2 by PCFG setting */ if (pcfg & TX4939_PCFG_SIO3MODE) ch_mask |= 1 << 3; /* disable SIO3 by PCFG setting */ for (i = 0; i < 4; i++) { if ((1 << i) & ch_mask) continue; txx9_sio_init(TX4939_SIO_REG(i) & 0xfffffffffULL, TXX9_IRQ_BASE + TX4939_IR_SIO(i), i, sclk, (1 << i) & cts_mask); } } #if IS_ENABLED(CONFIG_TC35815) static u32 tx4939_get_eth_speed(struct net_device *dev) { struct ethtool_cmd cmd; if (__ethtool_get_settings(dev, &cmd)) return 100; /* default 100Mbps */ return ethtool_cmd_speed(&cmd); } static int tx4939_netdev_event(struct notifier_block *this, unsigned long event, void *ptr) { struct net_device *dev = ptr; if (event == NETDEV_CHANGE && netif_carrier_ok(dev)) { __u64 bit = 0; if (dev->irq == TXX9_IRQ_BASE + TX4939_IR_ETH(0)) bit = TX4939_PCFG_SPEED0; else if (dev->irq == TXX9_IRQ_BASE + TX4939_IR_ETH(1)) bit = TX4939_PCFG_SPEED1; if (bit) { if (tx4939_get_eth_speed(dev) == 100) txx9_set64(&tx4939_ccfgptr->pcfg, bit); else txx9_clear64(&tx4939_ccfgptr->pcfg, bit); } } return NOTIFY_DONE; } static struct notifier_block tx4939_netdev_notifier = { .notifier_call = tx4939_netdev_event, .priority = 1, }; void __init tx4939_ethaddr_init(unsigned char *addr0, unsigned char *addr1) { u64 pcfg = __raw_readq(&tx4939_ccfgptr->pcfg); if (addr0 && (pcfg & TX4939_PCFG_ET0MODE)) txx9_ethaddr_init(TXX9_IRQ_BASE + TX4939_IR_ETH(0), addr0); if (addr1 && (pcfg & TX4939_PCFG_ET1MODE)) txx9_ethaddr_init(TXX9_IRQ_BASE + TX4939_IR_ETH(1), addr1); register_netdevice_notifier(&tx4939_netdev_notifier); } #else void __init tx4939_ethaddr_init(unsigned char *addr0, unsigned char *addr1) { } #endif void __init tx4939_mtd_init(int ch) { struct physmap_flash_data pdata = { .width = TX4939_EBUSC_WIDTH(ch) / 8, }; unsigned long start = txx9_ce_res[ch].start; unsigned long size = txx9_ce_res[ch].end - start + 1; if (!(TX4939_EBUSC_CR(ch) & 0x8)) return; /* disabled */ txx9_physmap_flash_init(ch, start, size, &pdata); } #define TX4939_ATA_REG_PHYS(ch) (TX4939_ATA_REG(ch) & 0xfffffffffULL) void __init tx4939_ata_init(void) { static struct resource ata0_res[] = { { .start = TX4939_ATA_REG_PHYS(0), .end = TX4939_ATA_REG_PHYS(0) + 0x1000 - 1, .flags = IORESOURCE_MEM, }, { .start = TXX9_IRQ_BASE + TX4939_IR_ATA(0), .flags = IORESOURCE_IRQ, }, }; static struct resource ata1_res[] = { { .start = TX4939_ATA_REG_PHYS(1), .end = TX4939_ATA_REG_PHYS(1) + 0x1000 - 1, .flags = IORESOURCE_MEM, }, { .start = TXX9_IRQ_BASE + TX4939_IR_ATA(1), .flags = IORESOURCE_IRQ, }, }; static struct platform_device ata0_dev = { .name = "tx4939ide", .id = 0, .num_resources = ARRAY_SIZE(ata0_res), .resource = ata0_res, }; static struct platform_device ata1_dev = { .name = "tx4939ide", .id = 1, .num_resources = ARRAY_SIZE(ata1_res), .resource = ata1_res, }; __u64 pcfg = __raw_readq(&tx4939_ccfgptr->pcfg); if (pcfg & TX4939_PCFG_ATA0MODE) platform_device_register(&ata0_dev); if ((pcfg & (TX4939_PCFG_ATA1MODE | TX4939_PCFG_ET1MODE | TX4939_PCFG_ET0MODE)) == TX4939_PCFG_ATA1MODE) platform_device_register(&ata1_dev); } void __init tx4939_rtc_init(void) { static struct resource res[] = { { .start = TX4939_RTC_REG & 0xfffffffffULL, .end = (TX4939_RTC_REG & 0xfffffffffULL) + 0x100 - 1, .flags = IORESOURCE_MEM, }, { .start = TXX9_IRQ_BASE + TX4939_IR_RTC, .flags = IORESOURCE_IRQ, }, }; static struct platform_device rtc_dev = { .name = "tx4939rtc", .id = -1, .num_resources = ARRAY_SIZE(res), .resource = res, }; platform_device_register(&rtc_dev); } void __init tx4939_ndfmc_init(unsigned int hold, unsigned int spw, unsigned char ch_mask, unsigned char wide_mask) { struct txx9ndfmc_platform_data plat_data = { .shift = 1, .gbus_clock = txx9_gbus_clock, .hold = hold, .spw = spw, .flags = NDFMC_PLAT_FLAG_NO_RSTR | NDFMC_PLAT_FLAG_HOLDADD | NDFMC_PLAT_FLAG_DUMMYWRITE, .ch_mask = ch_mask, .wide_mask = wide_mask, }; txx9_ndfmc_init(TX4939_NDFMC_REG & 0xfffffffffULL, &plat_data); } void __init tx4939_dmac_init(int memcpy_chan0, int memcpy_chan1) { struct txx9dmac_platform_data plat_data = { .have_64bit_regs = true, }; int i; for (i = 0; i < 2; i++) { plat_data.memcpy_chan = i ? memcpy_chan1 : memcpy_chan0; txx9_dmac_init(i, TX4939_DMA_REG(i) & 0xfffffffffULL, TXX9_IRQ_BASE + TX4939_IR_DMA(i, 0), &plat_data); } } void __init tx4939_aclc_init(void) { u64 pcfg = __raw_readq(&tx4939_ccfgptr->pcfg); if ((pcfg & TX4939_PCFG_I2SMODE_MASK) == TX4939_PCFG_I2SMODE_ACLC) txx9_aclc_init(TX4939_ACLC_REG & 0xfffffffffULL, TXX9_IRQ_BASE + TX4939_IR_ACLC, 1, 0, 1); } void __init tx4939_sramc_init(void) { if (tx4939_sram_resource.start) txx9_sramc_init(&tx4939_sram_resource); } void __init tx4939_rng_init(void) { static struct resource res = { .start = TX4939_RNG_REG & 0xfffffffffULL, .end = (TX4939_RNG_REG & 0xfffffffffULL) + 0x30 - 1, .flags = IORESOURCE_MEM, }; static struct platform_device pdev = { .name = "tx4939-rng", .id = -1, .num_resources = 1, .resource = &res, }; platform_device_register(&pdev); } static void __init tx4939_stop_unused_modules(void) { __u64 pcfg, rst = 0, ckd = 0; char buf[128]; buf[0] = '\0'; local_irq_disable(); pcfg = ____raw_readq(&tx4939_ccfgptr->pcfg); if ((pcfg & TX4939_PCFG_I2SMODE_MASK) != TX4939_PCFG_I2SMODE_ACLC) { rst |= TX4939_CLKCTR_ACLRST; ckd |= TX4939_CLKCTR_ACLCKD; strcat(buf, " ACLC"); } if ((pcfg & TX4939_PCFG_I2SMODE_MASK) != TX4939_PCFG_I2SMODE_I2S && (pcfg & TX4939_PCFG_I2SMODE_MASK) != TX4939_PCFG_I2SMODE_I2S_ALT) { rst |= TX4939_CLKCTR_I2SRST; ckd |= TX4939_CLKCTR_I2SCKD; strcat(buf, " I2S"); } if (!(pcfg & TX4939_PCFG_ATA0MODE)) { rst |= TX4939_CLKCTR_ATA0RST; ckd |= TX4939_CLKCTR_ATA0CKD; strcat(buf, " ATA0"); } if (!(pcfg & TX4939_PCFG_ATA1MODE)) { rst |= TX4939_CLKCTR_ATA1RST; ckd |= TX4939_CLKCTR_ATA1CKD; strcat(buf, " ATA1"); } if (pcfg & TX4939_PCFG_SPIMODE) { rst |= TX4939_CLKCTR_SPIRST; ckd |= TX4939_CLKCTR_SPICKD; strcat(buf, " SPI"); } if (!(pcfg & (TX4939_PCFG_VSSMODE | TX4939_PCFG_VPSMODE))) { rst |= TX4939_CLKCTR_VPCRST; ckd |= TX4939_CLKCTR_VPCCKD; strcat(buf, " VPC"); } if ((pcfg & TX4939_PCFG_SIO2MODE_MASK) != TX4939_PCFG_SIO2MODE_SIO2) { rst |= TX4939_CLKCTR_SIO2RST; ckd |= TX4939_CLKCTR_SIO2CKD; strcat(buf, " SIO2"); } if (pcfg & TX4939_PCFG_SIO3MODE) { rst |= TX4939_CLKCTR_SIO3RST; ckd |= TX4939_CLKCTR_SIO3CKD; strcat(buf, " SIO3"); } if (rst | ckd) { txx9_set64(&tx4939_ccfgptr->clkctr, rst); txx9_set64(&tx4939_ccfgptr->clkctr, ckd); } local_irq_enable(); if (buf[0]) pr_info("%s: stop%s\n", txx9_pcode_str, buf); } static int __init tx4939_late_init(void) { if (txx9_pcode != 0x4939) return -ENODEV; tx4939_stop_unused_modules(); return 0; } late_initcall(tx4939_late_init);
gpl-2.0
DienoX/NightSimple-5.0.2_BOK2_G901F
drivers/regulator/wm831x-isink.c
2255
6520
/* * wm831x-isink.c -- Current sink driver for the WM831x series * * Copyright 2009 Wolfson Microelectronics PLC. * * Author: Mark Brown <broonie@opensource.wolfsonmicro.com> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/init.h> #include <linux/bitops.h> #include <linux/err.h> #include <linux/i2c.h> #include <linux/platform_device.h> #include <linux/regulator/driver.h> #include <linux/slab.h> #include <linux/mfd/wm831x/core.h> #include <linux/mfd/wm831x/regulator.h> #include <linux/mfd/wm831x/pdata.h> #define WM831X_ISINK_MAX_NAME 7 struct wm831x_isink { char name[WM831X_ISINK_MAX_NAME]; struct regulator_desc desc; int reg; struct wm831x *wm831x; struct regulator_dev *regulator; }; static int wm831x_isink_enable(struct regulator_dev *rdev) { struct wm831x_isink *isink = rdev_get_drvdata(rdev); struct wm831x *wm831x = isink->wm831x; int ret; /* We have a two stage enable: first start the ISINK... */ ret = wm831x_set_bits(wm831x, isink->reg, WM831X_CS1_ENA, WM831X_CS1_ENA); if (ret != 0) return ret; /* ...then enable drive */ ret = wm831x_set_bits(wm831x, isink->reg, WM831X_CS1_DRIVE, WM831X_CS1_DRIVE); if (ret != 0) wm831x_set_bits(wm831x, isink->reg, WM831X_CS1_ENA, 0); return ret; } static int wm831x_isink_disable(struct regulator_dev *rdev) { struct wm831x_isink *isink = rdev_get_drvdata(rdev); struct wm831x *wm831x = isink->wm831x; int ret; ret = wm831x_set_bits(wm831x, isink->reg, WM831X_CS1_DRIVE, 0); if (ret < 0) return ret; ret = wm831x_set_bits(wm831x, isink->reg, WM831X_CS1_ENA, 0); if (ret < 0) return ret; return ret; } static int wm831x_isink_is_enabled(struct regulator_dev *rdev) { struct wm831x_isink *isink = rdev_get_drvdata(rdev); struct wm831x *wm831x = isink->wm831x; int ret; ret = wm831x_reg_read(wm831x, isink->reg); if (ret < 0) return ret; if ((ret & (WM831X_CS1_ENA | WM831X_CS1_DRIVE)) == (WM831X_CS1_ENA | WM831X_CS1_DRIVE)) return 1; else return 0; } static int wm831x_isink_set_current(struct regulator_dev *rdev, int min_uA, int max_uA) { struct wm831x_isink *isink = rdev_get_drvdata(rdev); struct wm831x *wm831x = isink->wm831x; int ret, i; for (i = 0; i < ARRAY_SIZE(wm831x_isinkv_values); i++) { int val = wm831x_isinkv_values[i]; if (min_uA <= val && val <= max_uA) { ret = wm831x_set_bits(wm831x, isink->reg, WM831X_CS1_ISEL_MASK, i); return ret; } } return -EINVAL; } static int wm831x_isink_get_current(struct regulator_dev *rdev) { struct wm831x_isink *isink = rdev_get_drvdata(rdev); struct wm831x *wm831x = isink->wm831x; int ret; ret = wm831x_reg_read(wm831x, isink->reg); if (ret < 0) return ret; ret &= WM831X_CS1_ISEL_MASK; if (ret > WM831X_ISINK_MAX_ISEL) ret = WM831X_ISINK_MAX_ISEL; return wm831x_isinkv_values[ret]; } static struct regulator_ops wm831x_isink_ops = { .is_enabled = wm831x_isink_is_enabled, .enable = wm831x_isink_enable, .disable = wm831x_isink_disable, .set_current_limit = wm831x_isink_set_current, .get_current_limit = wm831x_isink_get_current, }; static irqreturn_t wm831x_isink_irq(int irq, void *data) { struct wm831x_isink *isink = data; regulator_notifier_call_chain(isink->regulator, REGULATOR_EVENT_OVER_CURRENT, NULL); return IRQ_HANDLED; } static int wm831x_isink_probe(struct platform_device *pdev) { struct wm831x *wm831x = dev_get_drvdata(pdev->dev.parent); struct wm831x_pdata *pdata = wm831x->dev->platform_data; struct wm831x_isink *isink; int id = pdev->id % ARRAY_SIZE(pdata->isink); struct regulator_config config = { }; struct resource *res; int ret, irq; dev_dbg(&pdev->dev, "Probing ISINK%d\n", id + 1); if (pdata == NULL || pdata->isink[id] == NULL) return -ENODEV; isink = devm_kzalloc(&pdev->dev, sizeof(struct wm831x_isink), GFP_KERNEL); if (isink == NULL) { dev_err(&pdev->dev, "Unable to allocate private data\n"); return -ENOMEM; } isink->wm831x = wm831x; res = platform_get_resource(pdev, IORESOURCE_REG, 0); if (res == NULL) { dev_err(&pdev->dev, "No REG resource\n"); ret = -EINVAL; goto err; } isink->reg = res->start; /* For current parts this is correct; probably need to revisit * in future. */ snprintf(isink->name, sizeof(isink->name), "ISINK%d", id + 1); isink->desc.name = isink->name; isink->desc.id = id; isink->desc.ops = &wm831x_isink_ops; isink->desc.type = REGULATOR_CURRENT; isink->desc.owner = THIS_MODULE; config.dev = pdev->dev.parent; config.init_data = pdata->isink[id]; config.driver_data = isink; isink->regulator = regulator_register(&isink->desc, &config); if (IS_ERR(isink->regulator)) { ret = PTR_ERR(isink->regulator); dev_err(wm831x->dev, "Failed to register ISINK%d: %d\n", id + 1, ret); goto err; } irq = wm831x_irq(wm831x, platform_get_irq(pdev, 0)); ret = request_threaded_irq(irq, NULL, wm831x_isink_irq, IRQF_TRIGGER_RISING, isink->name, isink); if (ret != 0) { dev_err(&pdev->dev, "Failed to request ISINK IRQ %d: %d\n", irq, ret); goto err_regulator; } platform_set_drvdata(pdev, isink); return 0; err_regulator: regulator_unregister(isink->regulator); err: return ret; } static int wm831x_isink_remove(struct platform_device *pdev) { struct wm831x_isink *isink = platform_get_drvdata(pdev); platform_set_drvdata(pdev, NULL); free_irq(wm831x_irq(isink->wm831x, platform_get_irq(pdev, 0)), isink); regulator_unregister(isink->regulator); return 0; } static struct platform_driver wm831x_isink_driver = { .probe = wm831x_isink_probe, .remove = wm831x_isink_remove, .driver = { .name = "wm831x-isink", .owner = THIS_MODULE, }, }; static int __init wm831x_isink_init(void) { int ret; ret = platform_driver_register(&wm831x_isink_driver); if (ret != 0) pr_err("Failed to register WM831x ISINK driver: %d\n", ret); return ret; } subsys_initcall(wm831x_isink_init); static void __exit wm831x_isink_exit(void) { platform_driver_unregister(&wm831x_isink_driver); } module_exit(wm831x_isink_exit); /* Module information */ MODULE_AUTHOR("Mark Brown"); MODULE_DESCRIPTION("WM831x current sink driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:wm831x-isink");
gpl-2.0
supersonicninja/android_kernel_huawei_msm8960
crypto/shash.c
2511
16620
/* * Synchronous Cryptographic Hash operations. * * Copyright (c) 2008 Herbert Xu <herbert@gondor.apana.org.au> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * */ #include <crypto/scatterwalk.h> #include <crypto/internal/hash.h> #include <linux/err.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/seq_file.h> #include "internal.h" static const struct crypto_type crypto_shash_type; static int shash_no_setkey(struct crypto_shash *tfm, const u8 *key, unsigned int keylen) { return -ENOSYS; } static int shash_setkey_unaligned(struct crypto_shash *tfm, const u8 *key, unsigned int keylen) { struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); unsigned long absize; u8 *buffer, *alignbuffer; int err; absize = keylen + (alignmask & ~(crypto_tfm_ctx_alignment() - 1)); buffer = kmalloc(absize, GFP_KERNEL); if (!buffer) return -ENOMEM; alignbuffer = (u8 *)ALIGN((unsigned long)buffer, alignmask + 1); memcpy(alignbuffer, key, keylen); err = shash->setkey(tfm, alignbuffer, keylen); kzfree(buffer); return err; } int crypto_shash_setkey(struct crypto_shash *tfm, const u8 *key, unsigned int keylen) { struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); if ((unsigned long)key & alignmask) return shash_setkey_unaligned(tfm, key, keylen); return shash->setkey(tfm, key, keylen); } EXPORT_SYMBOL_GPL(crypto_shash_setkey); static inline unsigned int shash_align_buffer_size(unsigned len, unsigned long mask) { return len + (mask & ~(__alignof__(u8 __attribute__ ((aligned))) - 1)); } static int shash_update_unaligned(struct shash_desc *desc, const u8 *data, unsigned int len) { struct crypto_shash *tfm = desc->tfm; struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); unsigned int unaligned_len = alignmask + 1 - ((unsigned long)data & alignmask); u8 ubuf[shash_align_buffer_size(unaligned_len, alignmask)] __attribute__ ((aligned)); u8 *buf = PTR_ALIGN(&ubuf[0], alignmask + 1); int err; if (unaligned_len > len) unaligned_len = len; memcpy(buf, data, unaligned_len); err = shash->update(desc, buf, unaligned_len); memset(buf, 0, unaligned_len); return err ?: shash->update(desc, data + unaligned_len, len - unaligned_len); } int crypto_shash_update(struct shash_desc *desc, const u8 *data, unsigned int len) { struct crypto_shash *tfm = desc->tfm; struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); if ((unsigned long)data & alignmask) return shash_update_unaligned(desc, data, len); return shash->update(desc, data, len); } EXPORT_SYMBOL_GPL(crypto_shash_update); static int shash_final_unaligned(struct shash_desc *desc, u8 *out) { struct crypto_shash *tfm = desc->tfm; unsigned long alignmask = crypto_shash_alignmask(tfm); struct shash_alg *shash = crypto_shash_alg(tfm); unsigned int ds = crypto_shash_digestsize(tfm); u8 ubuf[shash_align_buffer_size(ds, alignmask)] __attribute__ ((aligned)); u8 *buf = PTR_ALIGN(&ubuf[0], alignmask + 1); int err; err = shash->final(desc, buf); if (err) goto out; memcpy(out, buf, ds); out: memset(buf, 0, ds); return err; } int crypto_shash_final(struct shash_desc *desc, u8 *out) { struct crypto_shash *tfm = desc->tfm; struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); if ((unsigned long)out & alignmask) return shash_final_unaligned(desc, out); return shash->final(desc, out); } EXPORT_SYMBOL_GPL(crypto_shash_final); static int shash_finup_unaligned(struct shash_desc *desc, const u8 *data, unsigned int len, u8 *out) { return crypto_shash_update(desc, data, len) ?: crypto_shash_final(desc, out); } int crypto_shash_finup(struct shash_desc *desc, const u8 *data, unsigned int len, u8 *out) { struct crypto_shash *tfm = desc->tfm; struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); if (((unsigned long)data | (unsigned long)out) & alignmask) return shash_finup_unaligned(desc, data, len, out); return shash->finup(desc, data, len, out); } EXPORT_SYMBOL_GPL(crypto_shash_finup); static int shash_digest_unaligned(struct shash_desc *desc, const u8 *data, unsigned int len, u8 *out) { return crypto_shash_init(desc) ?: crypto_shash_finup(desc, data, len, out); } int crypto_shash_digest(struct shash_desc *desc, const u8 *data, unsigned int len, u8 *out) { struct crypto_shash *tfm = desc->tfm; struct shash_alg *shash = crypto_shash_alg(tfm); unsigned long alignmask = crypto_shash_alignmask(tfm); if (((unsigned long)data | (unsigned long)out) & alignmask) return shash_digest_unaligned(desc, data, len, out); return shash->digest(desc, data, len, out); } EXPORT_SYMBOL_GPL(crypto_shash_digest); static int shash_default_export(struct shash_desc *desc, void *out) { memcpy(out, shash_desc_ctx(desc), crypto_shash_descsize(desc->tfm)); return 0; } static int shash_default_import(struct shash_desc *desc, const void *in) { memcpy(shash_desc_ctx(desc), in, crypto_shash_descsize(desc->tfm)); return 0; } static int shash_async_setkey(struct crypto_ahash *tfm, const u8 *key, unsigned int keylen) { struct crypto_shash **ctx = crypto_ahash_ctx(tfm); return crypto_shash_setkey(*ctx, key, keylen); } static int shash_async_init(struct ahash_request *req) { struct crypto_shash **ctx = crypto_ahash_ctx(crypto_ahash_reqtfm(req)); struct shash_desc *desc = ahash_request_ctx(req); desc->tfm = *ctx; desc->flags = req->base.flags; return crypto_shash_init(desc); } int shash_ahash_update(struct ahash_request *req, struct shash_desc *desc) { struct crypto_hash_walk walk; int nbytes; for (nbytes = crypto_hash_walk_first(req, &walk); nbytes > 0; nbytes = crypto_hash_walk_done(&walk, nbytes)) nbytes = crypto_shash_update(desc, walk.data, nbytes); return nbytes; } EXPORT_SYMBOL_GPL(shash_ahash_update); static int shash_async_update(struct ahash_request *req) { return shash_ahash_update(req, ahash_request_ctx(req)); } static int shash_async_final(struct ahash_request *req) { return crypto_shash_final(ahash_request_ctx(req), req->result); } int shash_ahash_finup(struct ahash_request *req, struct shash_desc *desc) { struct crypto_hash_walk walk; int nbytes; nbytes = crypto_hash_walk_first(req, &walk); if (!nbytes) return crypto_shash_final(desc, req->result); do { nbytes = crypto_hash_walk_last(&walk) ? crypto_shash_finup(desc, walk.data, nbytes, req->result) : crypto_shash_update(desc, walk.data, nbytes); nbytes = crypto_hash_walk_done(&walk, nbytes); } while (nbytes > 0); return nbytes; } EXPORT_SYMBOL_GPL(shash_ahash_finup); static int shash_async_finup(struct ahash_request *req) { struct crypto_shash **ctx = crypto_ahash_ctx(crypto_ahash_reqtfm(req)); struct shash_desc *desc = ahash_request_ctx(req); desc->tfm = *ctx; desc->flags = req->base.flags; return shash_ahash_finup(req, desc); } int shash_ahash_digest(struct ahash_request *req, struct shash_desc *desc) { struct scatterlist *sg = req->src; unsigned int offset = sg->offset; unsigned int nbytes = req->nbytes; int err; if (nbytes < min(sg->length, ((unsigned int)(PAGE_SIZE)) - offset)) { void *data; data = crypto_kmap(sg_page(sg), 0); err = crypto_shash_digest(desc, data + offset, nbytes, req->result); crypto_kunmap(data, 0); crypto_yield(desc->flags); } else err = crypto_shash_init(desc) ?: shash_ahash_finup(req, desc); return err; } EXPORT_SYMBOL_GPL(shash_ahash_digest); static int shash_async_digest(struct ahash_request *req) { struct crypto_shash **ctx = crypto_ahash_ctx(crypto_ahash_reqtfm(req)); struct shash_desc *desc = ahash_request_ctx(req); desc->tfm = *ctx; desc->flags = req->base.flags; return shash_ahash_digest(req, desc); } static int shash_async_export(struct ahash_request *req, void *out) { return crypto_shash_export(ahash_request_ctx(req), out); } static int shash_async_import(struct ahash_request *req, const void *in) { struct crypto_shash **ctx = crypto_ahash_ctx(crypto_ahash_reqtfm(req)); struct shash_desc *desc = ahash_request_ctx(req); desc->tfm = *ctx; desc->flags = req->base.flags; return crypto_shash_import(desc, in); } static void crypto_exit_shash_ops_async(struct crypto_tfm *tfm) { struct crypto_shash **ctx = crypto_tfm_ctx(tfm); crypto_free_shash(*ctx); } int crypto_init_shash_ops_async(struct crypto_tfm *tfm) { struct crypto_alg *calg = tfm->__crt_alg; struct shash_alg *alg = __crypto_shash_alg(calg); struct crypto_ahash *crt = __crypto_ahash_cast(tfm); struct crypto_shash **ctx = crypto_tfm_ctx(tfm); struct crypto_shash *shash; if (!crypto_mod_get(calg)) return -EAGAIN; shash = crypto_create_tfm(calg, &crypto_shash_type); if (IS_ERR(shash)) { crypto_mod_put(calg); return PTR_ERR(shash); } *ctx = shash; tfm->exit = crypto_exit_shash_ops_async; crt->init = shash_async_init; crt->update = shash_async_update; crt->final = shash_async_final; crt->finup = shash_async_finup; crt->digest = shash_async_digest; if (alg->setkey) crt->setkey = shash_async_setkey; if (alg->export) crt->export = shash_async_export; if (alg->import) crt->import = shash_async_import; crt->reqsize = sizeof(struct shash_desc) + crypto_shash_descsize(shash); return 0; } static int shash_compat_setkey(struct crypto_hash *tfm, const u8 *key, unsigned int keylen) { struct shash_desc **descp = crypto_hash_ctx(tfm); struct shash_desc *desc = *descp; return crypto_shash_setkey(desc->tfm, key, keylen); } static int shash_compat_init(struct hash_desc *hdesc) { struct shash_desc **descp = crypto_hash_ctx(hdesc->tfm); struct shash_desc *desc = *descp; desc->flags = hdesc->flags; return crypto_shash_init(desc); } static int shash_compat_update(struct hash_desc *hdesc, struct scatterlist *sg, unsigned int len) { struct shash_desc **descp = crypto_hash_ctx(hdesc->tfm); struct shash_desc *desc = *descp; struct crypto_hash_walk walk; int nbytes; for (nbytes = crypto_hash_walk_first_compat(hdesc, &walk, sg, len); nbytes > 0; nbytes = crypto_hash_walk_done(&walk, nbytes)) nbytes = crypto_shash_update(desc, walk.data, nbytes); return nbytes; } static int shash_compat_final(struct hash_desc *hdesc, u8 *out) { struct shash_desc **descp = crypto_hash_ctx(hdesc->tfm); return crypto_shash_final(*descp, out); } static int shash_compat_digest(struct hash_desc *hdesc, struct scatterlist *sg, unsigned int nbytes, u8 *out) { unsigned int offset = sg->offset; int err; if (nbytes < min(sg->length, ((unsigned int)(PAGE_SIZE)) - offset)) { struct shash_desc **descp = crypto_hash_ctx(hdesc->tfm); struct shash_desc *desc = *descp; void *data; desc->flags = hdesc->flags; data = crypto_kmap(sg_page(sg), 0); err = crypto_shash_digest(desc, data + offset, nbytes, out); crypto_kunmap(data, 0); crypto_yield(desc->flags); goto out; } err = shash_compat_init(hdesc); if (err) goto out; err = shash_compat_update(hdesc, sg, nbytes); if (err) goto out; err = shash_compat_final(hdesc, out); out: return err; } static void crypto_exit_shash_ops_compat(struct crypto_tfm *tfm) { struct shash_desc **descp = crypto_tfm_ctx(tfm); struct shash_desc *desc = *descp; crypto_free_shash(desc->tfm); kzfree(desc); } static int crypto_init_shash_ops_compat(struct crypto_tfm *tfm) { struct hash_tfm *crt = &tfm->crt_hash; struct crypto_alg *calg = tfm->__crt_alg; struct shash_alg *alg = __crypto_shash_alg(calg); struct shash_desc **descp = crypto_tfm_ctx(tfm); struct crypto_shash *shash; struct shash_desc *desc; if (!crypto_mod_get(calg)) return -EAGAIN; shash = crypto_create_tfm(calg, &crypto_shash_type); if (IS_ERR(shash)) { crypto_mod_put(calg); return PTR_ERR(shash); } desc = kmalloc(sizeof(*desc) + crypto_shash_descsize(shash), GFP_KERNEL); if (!desc) { crypto_free_shash(shash); return -ENOMEM; } *descp = desc; desc->tfm = shash; tfm->exit = crypto_exit_shash_ops_compat; crt->init = shash_compat_init; crt->update = shash_compat_update; crt->final = shash_compat_final; crt->digest = shash_compat_digest; crt->setkey = shash_compat_setkey; crt->digestsize = alg->digestsize; return 0; } static int crypto_init_shash_ops(struct crypto_tfm *tfm, u32 type, u32 mask) { switch (mask & CRYPTO_ALG_TYPE_MASK) { case CRYPTO_ALG_TYPE_HASH_MASK: return crypto_init_shash_ops_compat(tfm); } return -EINVAL; } static unsigned int crypto_shash_ctxsize(struct crypto_alg *alg, u32 type, u32 mask) { switch (mask & CRYPTO_ALG_TYPE_MASK) { case CRYPTO_ALG_TYPE_HASH_MASK: return sizeof(struct shash_desc *); } return 0; } static int crypto_shash_init_tfm(struct crypto_tfm *tfm) { struct crypto_shash *hash = __crypto_shash_cast(tfm); hash->descsize = crypto_shash_alg(hash)->descsize; return 0; } static unsigned int crypto_shash_extsize(struct crypto_alg *alg) { return alg->cra_ctxsize; } static void crypto_shash_show(struct seq_file *m, struct crypto_alg *alg) __attribute__ ((unused)); static void crypto_shash_show(struct seq_file *m, struct crypto_alg *alg) { struct shash_alg *salg = __crypto_shash_alg(alg); seq_printf(m, "type : shash\n"); seq_printf(m, "blocksize : %u\n", alg->cra_blocksize); seq_printf(m, "digestsize : %u\n", salg->digestsize); } static const struct crypto_type crypto_shash_type = { .ctxsize = crypto_shash_ctxsize, .extsize = crypto_shash_extsize, .init = crypto_init_shash_ops, .init_tfm = crypto_shash_init_tfm, #ifdef CONFIG_PROC_FS .show = crypto_shash_show, #endif .maskclear = ~CRYPTO_ALG_TYPE_MASK, .maskset = CRYPTO_ALG_TYPE_MASK, .type = CRYPTO_ALG_TYPE_SHASH, .tfmsize = offsetof(struct crypto_shash, base), }; struct crypto_shash *crypto_alloc_shash(const char *alg_name, u32 type, u32 mask) { return crypto_alloc_tfm(alg_name, &crypto_shash_type, type, mask); } EXPORT_SYMBOL_GPL(crypto_alloc_shash); static int shash_prepare_alg(struct shash_alg *alg) { struct crypto_alg *base = &alg->base; if (alg->digestsize > PAGE_SIZE / 8 || alg->descsize > PAGE_SIZE / 8 || alg->statesize > PAGE_SIZE / 8) return -EINVAL; base->cra_type = &crypto_shash_type; base->cra_flags &= ~CRYPTO_ALG_TYPE_MASK; base->cra_flags |= CRYPTO_ALG_TYPE_SHASH; if (!alg->finup) alg->finup = shash_finup_unaligned; if (!alg->digest) alg->digest = shash_digest_unaligned; if (!alg->export) { alg->export = shash_default_export; alg->import = shash_default_import; alg->statesize = alg->descsize; } if (!alg->setkey) alg->setkey = shash_no_setkey; return 0; } int crypto_register_shash(struct shash_alg *alg) { struct crypto_alg *base = &alg->base; int err; err = shash_prepare_alg(alg); if (err) return err; return crypto_register_alg(base); } EXPORT_SYMBOL_GPL(crypto_register_shash); int crypto_unregister_shash(struct shash_alg *alg) { return crypto_unregister_alg(&alg->base); } EXPORT_SYMBOL_GPL(crypto_unregister_shash); int shash_register_instance(struct crypto_template *tmpl, struct shash_instance *inst) { int err; err = shash_prepare_alg(&inst->alg); if (err) return err; return crypto_register_instance(tmpl, shash_crypto_instance(inst)); } EXPORT_SYMBOL_GPL(shash_register_instance); void shash_free_instance(struct crypto_instance *inst) { crypto_drop_spawn(crypto_instance_ctx(inst)); kfree(shash_instance(inst)); } EXPORT_SYMBOL_GPL(shash_free_instance); int crypto_init_shash_spawn(struct crypto_shash_spawn *spawn, struct shash_alg *alg, struct crypto_instance *inst) { return crypto_init_spawn2(&spawn->base, &alg->base, inst, &crypto_shash_type); } EXPORT_SYMBOL_GPL(crypto_init_shash_spawn); struct shash_alg *shash_attr_alg(struct rtattr *rta, u32 type, u32 mask) { struct crypto_alg *alg; alg = crypto_attr_alg2(rta, &crypto_shash_type, type, mask); return IS_ERR(alg) ? ERR_CAST(alg) : container_of(alg, struct shash_alg, base); } EXPORT_SYMBOL_GPL(shash_attr_alg); MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("Synchronous cryptographic hash type");
gpl-2.0
KangBangKreations/KangBanged-Kernel
sound/soc/samsung/goni_wm8994.c
2767
7561
/* * goni_wm8994.c * * Copyright (C) 2010 Samsung Electronics Co.Ltd * Author: Chanwoo Choi <cw00.choi@samsung.com> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * */ #include <sound/soc.h> #include <sound/jack.h> #include <asm/mach-types.h> #include <mach/gpio.h> #include "../codecs/wm8994.h" #define MACHINE_NAME 0 #define CPU_VOICE_DAI 1 static const char *aquila_str[] = { [MACHINE_NAME] = "aquila", [CPU_VOICE_DAI] = "aquila-voice-dai", }; static struct snd_soc_card goni; static struct platform_device *goni_snd_device; /* 3.5 pie jack */ static struct snd_soc_jack jack; /* 3.5 pie jack detection DAPM pins */ static struct snd_soc_jack_pin jack_pins[] = { { .pin = "Headset Mic", .mask = SND_JACK_MICROPHONE, }, { .pin = "Headset Stereophone", .mask = SND_JACK_HEADPHONE | SND_JACK_MECHANICAL | SND_JACK_AVOUT, }, }; /* 3.5 pie jack detection gpios */ static struct snd_soc_jack_gpio jack_gpios[] = { { .gpio = S5PV210_GPH0(6), .name = "DET_3.5", .report = SND_JACK_HEADSET | SND_JACK_MECHANICAL | SND_JACK_AVOUT, .debounce_time = 200, }, }; static const struct snd_soc_dapm_widget goni_dapm_widgets[] = { SND_SOC_DAPM_SPK("Ext Left Spk", NULL), SND_SOC_DAPM_SPK("Ext Right Spk", NULL), SND_SOC_DAPM_SPK("Ext Rcv", NULL), SND_SOC_DAPM_HP("Headset Stereophone", NULL), SND_SOC_DAPM_MIC("Headset Mic", NULL), SND_SOC_DAPM_MIC("Main Mic", NULL), SND_SOC_DAPM_MIC("2nd Mic", NULL), SND_SOC_DAPM_LINE("Radio In", NULL), }; static const struct snd_soc_dapm_route goni_dapm_routes[] = { {"Ext Left Spk", NULL, "SPKOUTLP"}, {"Ext Left Spk", NULL, "SPKOUTLN"}, {"Ext Right Spk", NULL, "SPKOUTRP"}, {"Ext Right Spk", NULL, "SPKOUTRN"}, {"Ext Rcv", NULL, "HPOUT2N"}, {"Ext Rcv", NULL, "HPOUT2P"}, {"Headset Stereophone", NULL, "HPOUT1L"}, {"Headset Stereophone", NULL, "HPOUT1R"}, {"IN1RN", NULL, "Headset Mic"}, {"IN1RP", NULL, "Headset Mic"}, {"IN1RN", NULL, "2nd Mic"}, {"IN1RP", NULL, "2nd Mic"}, {"IN1LN", NULL, "Main Mic"}, {"IN1LP", NULL, "Main Mic"}, {"IN2LN", NULL, "Radio In"}, {"IN2RN", NULL, "Radio In"}, }; static int goni_wm8994_init(struct snd_soc_pcm_runtime *rtd) { struct snd_soc_codec *codec = rtd->codec; struct snd_soc_dapm_context *dapm = &codec->dapm; int ret; /* add goni specific widgets */ snd_soc_dapm_new_controls(dapm, goni_dapm_widgets, ARRAY_SIZE(goni_dapm_widgets)); /* set up goni specific audio routes */ snd_soc_dapm_add_routes(dapm, goni_dapm_routes, ARRAY_SIZE(goni_dapm_routes)); /* set endpoints to not connected */ snd_soc_dapm_nc_pin(dapm, "IN2LP:VXRN"); snd_soc_dapm_nc_pin(dapm, "IN2RP:VXRP"); snd_soc_dapm_nc_pin(dapm, "LINEOUT1N"); snd_soc_dapm_nc_pin(dapm, "LINEOUT1P"); snd_soc_dapm_nc_pin(dapm, "LINEOUT2N"); snd_soc_dapm_nc_pin(dapm, "LINEOUT2P"); if (machine_is_aquila()) { snd_soc_dapm_nc_pin(dapm, "SPKOUTRN"); snd_soc_dapm_nc_pin(dapm, "SPKOUTRP"); } snd_soc_dapm_sync(dapm); /* Headset jack detection */ ret = snd_soc_jack_new(codec, "Headset Jack", SND_JACK_HEADSET | SND_JACK_MECHANICAL | SND_JACK_AVOUT, &jack); if (ret) return ret; ret = snd_soc_jack_add_pins(&jack, ARRAY_SIZE(jack_pins), jack_pins); if (ret) return ret; ret = snd_soc_jack_add_gpios(&jack, ARRAY_SIZE(jack_gpios), jack_gpios); if (ret) return ret; return 0; } static int goni_hifi_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_dai *codec_dai = rtd->codec_dai; struct snd_soc_dai *cpu_dai = rtd->cpu_dai; unsigned int pll_out = 24000000; int ret = 0; /* set the cpu DAI configuration */ ret = snd_soc_dai_set_fmt(cpu_dai, SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_CBM_CFM); if (ret < 0) return ret; /* set codec DAI configuration */ ret = snd_soc_dai_set_fmt(codec_dai, SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_CBM_CFM); if (ret < 0) return ret; /* set the codec FLL */ ret = snd_soc_dai_set_pll(codec_dai, WM8994_FLL1, 0, pll_out, params_rate(params) * 256); if (ret < 0) return ret; /* set the codec system clock */ ret = snd_soc_dai_set_sysclk(codec_dai, WM8994_SYSCLK_FLL1, params_rate(params) * 256, SND_SOC_CLOCK_IN); if (ret < 0) return ret; return 0; } static struct snd_soc_ops goni_hifi_ops = { .hw_params = goni_hifi_hw_params, }; static int goni_voice_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_dai *codec_dai = rtd->codec_dai; unsigned int pll_out = 24000000; int ret = 0; if (params_rate(params) != 8000) return -EINVAL; /* set codec DAI configuration */ ret = snd_soc_dai_set_fmt(codec_dai, SND_SOC_DAIFMT_LEFT_J | SND_SOC_DAIFMT_IB_IF | SND_SOC_DAIFMT_CBM_CFM); if (ret < 0) return ret; /* set the codec FLL */ ret = snd_soc_dai_set_pll(codec_dai, WM8994_FLL2, 0, pll_out, params_rate(params) * 256); if (ret < 0) return ret; /* set the codec system clock */ ret = snd_soc_dai_set_sysclk(codec_dai, WM8994_SYSCLK_FLL2, params_rate(params) * 256, SND_SOC_CLOCK_IN); if (ret < 0) return ret; return 0; } static struct snd_soc_dai_driver voice_dai = { .name = "goni-voice-dai", .id = 0, .playback = { .channels_min = 1, .channels_max = 2, .rates = SNDRV_PCM_RATE_8000, .formats = SNDRV_PCM_FMTBIT_S16_LE,}, .capture = { .channels_min = 1, .channels_max = 2, .rates = SNDRV_PCM_RATE_8000, .formats = SNDRV_PCM_FMTBIT_S16_LE,}, }; static struct snd_soc_ops goni_voice_ops = { .hw_params = goni_voice_hw_params, }; static struct snd_soc_dai_link goni_dai[] = { { .name = "WM8994", .stream_name = "WM8994 HiFi", .cpu_dai_name = "samsung-i2s.0", .codec_dai_name = "wm8994-aif1", .platform_name = "samsung-audio", .codec_name = "wm8994-codec.0-001a", .init = goni_wm8994_init, .ops = &goni_hifi_ops, }, { .name = "WM8994 Voice", .stream_name = "Voice", .cpu_dai_name = "goni-voice-dai", .codec_dai_name = "wm8994-aif2", .codec_name = "wm8994-codec.0-001a", .ops = &goni_voice_ops, }, }; static struct snd_soc_card goni = { .name = "goni", .dai_link = goni_dai, .num_links = ARRAY_SIZE(goni_dai), }; static int __init goni_init(void) { int ret; if (machine_is_aquila()) { voice_dai.name = aquila_str[CPU_VOICE_DAI]; goni_dai[1].cpu_dai_name = aquila_str[CPU_VOICE_DAI]; goni.name = aquila_str[MACHINE_NAME]; } else if (!machine_is_goni()) return -ENODEV; goni_snd_device = platform_device_alloc("soc-audio", -1); if (!goni_snd_device) return -ENOMEM; /* register voice DAI here */ ret = snd_soc_register_dai(&goni_snd_device->dev, &voice_dai); if (ret) { platform_device_put(goni_snd_device); return ret; } platform_set_drvdata(goni_snd_device, &goni); ret = platform_device_add(goni_snd_device); if (ret) { snd_soc_unregister_dai(&goni_snd_device->dev); platform_device_put(goni_snd_device); } return ret; } static void __exit goni_exit(void) { snd_soc_unregister_dai(&goni_snd_device->dev); platform_device_unregister(goni_snd_device); } module_init(goni_init); module_exit(goni_exit); /* Module information */ MODULE_DESCRIPTION("ALSA SoC WM8994 GONI(S5PV210)"); MODULE_AUTHOR("Chanwoo Choi <cw00.choi@samsung.com>"); MODULE_LICENSE("GPL");
gpl-2.0
bigsupersquid/android_kernel_lge_msm7x27-3.0.x
fs/btrfs/super.c
2767
33286
/* * Copyright (C) 2007 Oracle. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public * License v2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 021110-1307, USA. */ #include <linux/blkdev.h> #include <linux/module.h> #include <linux/buffer_head.h> #include <linux/fs.h> #include <linux/pagemap.h> #include <linux/highmem.h> #include <linux/time.h> #include <linux/init.h> #include <linux/seq_file.h> #include <linux/string.h> #include <linux/backing-dev.h> #include <linux/mount.h> #include <linux/mpage.h> #include <linux/swap.h> #include <linux/writeback.h> #include <linux/statfs.h> #include <linux/compat.h> #include <linux/parser.h> #include <linux/ctype.h> #include <linux/namei.h> #include <linux/miscdevice.h> #include <linux/magic.h> #include <linux/slab.h> #include <linux/cleancache.h> #include "compat.h" #include "delayed-inode.h" #include "ctree.h" #include "disk-io.h" #include "transaction.h" #include "btrfs_inode.h" #include "ioctl.h" #include "print-tree.h" #include "xattr.h" #include "volumes.h" #include "version.h" #include "export.h" #include "compression.h" #define CREATE_TRACE_POINTS #include <trace/events/btrfs.h> static const struct super_operations btrfs_super_ops; static const char *btrfs_decode_error(struct btrfs_fs_info *fs_info, int errno, char nbuf[16]) { char *errstr = NULL; switch (errno) { case -EIO: errstr = "IO failure"; break; case -ENOMEM: errstr = "Out of memory"; break; case -EROFS: errstr = "Readonly filesystem"; break; default: if (nbuf) { if (snprintf(nbuf, 16, "error %d", -errno) >= 0) errstr = nbuf; } break; } return errstr; } static void __save_error_info(struct btrfs_fs_info *fs_info) { /* * today we only save the error info into ram. Long term we'll * also send it down to the disk */ fs_info->fs_state = BTRFS_SUPER_FLAG_ERROR; } /* NOTE: * We move write_super stuff at umount in order to avoid deadlock * for umount hold all lock. */ static void save_error_info(struct btrfs_fs_info *fs_info) { __save_error_info(fs_info); } /* btrfs handle error by forcing the filesystem readonly */ static void btrfs_handle_error(struct btrfs_fs_info *fs_info) { struct super_block *sb = fs_info->sb; if (sb->s_flags & MS_RDONLY) return; if (fs_info->fs_state & BTRFS_SUPER_FLAG_ERROR) { sb->s_flags |= MS_RDONLY; printk(KERN_INFO "btrfs is forced readonly\n"); } } /* * __btrfs_std_error decodes expected errors from the caller and * invokes the approciate error response. */ void __btrfs_std_error(struct btrfs_fs_info *fs_info, const char *function, unsigned int line, int errno) { struct super_block *sb = fs_info->sb; char nbuf[16]; const char *errstr; /* * Special case: if the error is EROFS, and we're already * under MS_RDONLY, then it is safe here. */ if (errno == -EROFS && (sb->s_flags & MS_RDONLY)) return; errstr = btrfs_decode_error(fs_info, errno, nbuf); printk(KERN_CRIT "BTRFS error (device %s) in %s:%d: %s\n", sb->s_id, function, line, errstr); save_error_info(fs_info); btrfs_handle_error(fs_info); } static void btrfs_put_super(struct super_block *sb) { struct btrfs_root *root = btrfs_sb(sb); int ret; ret = close_ctree(root); sb->s_fs_info = NULL; (void)ret; /* FIXME: need to fix VFS to return error? */ } enum { Opt_degraded, Opt_subvol, Opt_subvolid, Opt_device, Opt_nodatasum, Opt_nodatacow, Opt_max_inline, Opt_alloc_start, Opt_nobarrier, Opt_ssd, Opt_nossd, Opt_ssd_spread, Opt_thread_pool, Opt_noacl, Opt_compress, Opt_compress_type, Opt_compress_force, Opt_compress_force_type, Opt_notreelog, Opt_ratio, Opt_flushoncommit, Opt_discard, Opt_space_cache, Opt_clear_cache, Opt_user_subvol_rm_allowed, Opt_enospc_debug, Opt_subvolrootid, Opt_defrag, Opt_inode_cache, Opt_err, }; static match_table_t tokens = { {Opt_degraded, "degraded"}, {Opt_subvol, "subvol=%s"}, {Opt_subvolid, "subvolid=%d"}, {Opt_device, "device=%s"}, {Opt_nodatasum, "nodatasum"}, {Opt_nodatacow, "nodatacow"}, {Opt_nobarrier, "nobarrier"}, {Opt_max_inline, "max_inline=%s"}, {Opt_alloc_start, "alloc_start=%s"}, {Opt_thread_pool, "thread_pool=%d"}, {Opt_compress, "compress"}, {Opt_compress_type, "compress=%s"}, {Opt_compress_force, "compress-force"}, {Opt_compress_force_type, "compress-force=%s"}, {Opt_ssd, "ssd"}, {Opt_ssd_spread, "ssd_spread"}, {Opt_nossd, "nossd"}, {Opt_noacl, "noacl"}, {Opt_notreelog, "notreelog"}, {Opt_flushoncommit, "flushoncommit"}, {Opt_ratio, "metadata_ratio=%d"}, {Opt_discard, "discard"}, {Opt_space_cache, "space_cache"}, {Opt_clear_cache, "clear_cache"}, {Opt_user_subvol_rm_allowed, "user_subvol_rm_allowed"}, {Opt_enospc_debug, "enospc_debug"}, {Opt_subvolrootid, "subvolrootid=%d"}, {Opt_defrag, "autodefrag"}, {Opt_inode_cache, "inode_cache"}, {Opt_err, NULL}, }; /* * Regular mount options parser. Everything that is needed only when * reading in a new superblock is parsed here. */ int btrfs_parse_options(struct btrfs_root *root, char *options) { struct btrfs_fs_info *info = root->fs_info; substring_t args[MAX_OPT_ARGS]; char *p, *num, *orig; int intarg; int ret = 0; char *compress_type; bool compress_force = false; if (!options) return 0; /* * strsep changes the string, duplicate it because parse_options * gets called twice */ options = kstrdup(options, GFP_NOFS); if (!options) return -ENOMEM; orig = options; while ((p = strsep(&options, ",")) != NULL) { int token; if (!*p) continue; token = match_token(p, tokens, args); switch (token) { case Opt_degraded: printk(KERN_INFO "btrfs: allowing degraded mounts\n"); btrfs_set_opt(info->mount_opt, DEGRADED); break; case Opt_subvol: case Opt_subvolid: case Opt_subvolrootid: case Opt_device: /* * These are parsed by btrfs_parse_early_options * and can be happily ignored here. */ break; case Opt_nodatasum: printk(KERN_INFO "btrfs: setting nodatasum\n"); btrfs_set_opt(info->mount_opt, NODATASUM); break; case Opt_nodatacow: printk(KERN_INFO "btrfs: setting nodatacow\n"); btrfs_set_opt(info->mount_opt, NODATACOW); btrfs_set_opt(info->mount_opt, NODATASUM); break; case Opt_compress_force: case Opt_compress_force_type: compress_force = true; case Opt_compress: case Opt_compress_type: if (token == Opt_compress || token == Opt_compress_force || strcmp(args[0].from, "zlib") == 0) { compress_type = "zlib"; info->compress_type = BTRFS_COMPRESS_ZLIB; } else if (strcmp(args[0].from, "lzo") == 0) { compress_type = "lzo"; info->compress_type = BTRFS_COMPRESS_LZO; } else { ret = -EINVAL; goto out; } btrfs_set_opt(info->mount_opt, COMPRESS); if (compress_force) { btrfs_set_opt(info->mount_opt, FORCE_COMPRESS); pr_info("btrfs: force %s compression\n", compress_type); } else pr_info("btrfs: use %s compression\n", compress_type); break; case Opt_ssd: printk(KERN_INFO "btrfs: use ssd allocation scheme\n"); btrfs_set_opt(info->mount_opt, SSD); break; case Opt_ssd_spread: printk(KERN_INFO "btrfs: use spread ssd " "allocation scheme\n"); btrfs_set_opt(info->mount_opt, SSD); btrfs_set_opt(info->mount_opt, SSD_SPREAD); break; case Opt_nossd: printk(KERN_INFO "btrfs: not using ssd allocation " "scheme\n"); btrfs_set_opt(info->mount_opt, NOSSD); btrfs_clear_opt(info->mount_opt, SSD); btrfs_clear_opt(info->mount_opt, SSD_SPREAD); break; case Opt_nobarrier: printk(KERN_INFO "btrfs: turning off barriers\n"); btrfs_set_opt(info->mount_opt, NOBARRIER); break; case Opt_thread_pool: intarg = 0; match_int(&args[0], &intarg); if (intarg) { info->thread_pool_size = intarg; printk(KERN_INFO "btrfs: thread pool %d\n", info->thread_pool_size); } break; case Opt_max_inline: num = match_strdup(&args[0]); if (num) { info->max_inline = memparse(num, NULL); kfree(num); if (info->max_inline) { info->max_inline = max_t(u64, info->max_inline, root->sectorsize); } printk(KERN_INFO "btrfs: max_inline at %llu\n", (unsigned long long)info->max_inline); } break; case Opt_alloc_start: num = match_strdup(&args[0]); if (num) { info->alloc_start = memparse(num, NULL); kfree(num); printk(KERN_INFO "btrfs: allocations start at %llu\n", (unsigned long long)info->alloc_start); } break; case Opt_noacl: root->fs_info->sb->s_flags &= ~MS_POSIXACL; break; case Opt_notreelog: printk(KERN_INFO "btrfs: disabling tree log\n"); btrfs_set_opt(info->mount_opt, NOTREELOG); break; case Opt_flushoncommit: printk(KERN_INFO "btrfs: turning on flush-on-commit\n"); btrfs_set_opt(info->mount_opt, FLUSHONCOMMIT); break; case Opt_ratio: intarg = 0; match_int(&args[0], &intarg); if (intarg) { info->metadata_ratio = intarg; printk(KERN_INFO "btrfs: metadata ratio %d\n", info->metadata_ratio); } break; case Opt_discard: btrfs_set_opt(info->mount_opt, DISCARD); break; case Opt_space_cache: printk(KERN_INFO "btrfs: enabling disk space caching\n"); btrfs_set_opt(info->mount_opt, SPACE_CACHE); break; case Opt_inode_cache: printk(KERN_INFO "btrfs: enabling inode map caching\n"); btrfs_set_opt(info->mount_opt, INODE_MAP_CACHE); break; case Opt_clear_cache: printk(KERN_INFO "btrfs: force clearing of disk cache\n"); btrfs_set_opt(info->mount_opt, CLEAR_CACHE); break; case Opt_user_subvol_rm_allowed: btrfs_set_opt(info->mount_opt, USER_SUBVOL_RM_ALLOWED); break; case Opt_enospc_debug: btrfs_set_opt(info->mount_opt, ENOSPC_DEBUG); break; case Opt_defrag: printk(KERN_INFO "btrfs: enabling auto defrag"); btrfs_set_opt(info->mount_opt, AUTO_DEFRAG); break; case Opt_err: printk(KERN_INFO "btrfs: unrecognized mount option " "'%s'\n", p); ret = -EINVAL; goto out; default: break; } } out: kfree(orig); return ret; } /* * Parse mount options that are required early in the mount process. * * All other options will be parsed on much later in the mount process and * only when we need to allocate a new super block. */ static int btrfs_parse_early_options(const char *options, fmode_t flags, void *holder, char **subvol_name, u64 *subvol_objectid, u64 *subvol_rootid, struct btrfs_fs_devices **fs_devices) { substring_t args[MAX_OPT_ARGS]; char *opts, *orig, *p; int error = 0; int intarg; if (!options) goto out; /* * strsep changes the string, duplicate it because parse_options * gets called twice */ opts = kstrdup(options, GFP_KERNEL); if (!opts) return -ENOMEM; orig = opts; while ((p = strsep(&opts, ",")) != NULL) { int token; if (!*p) continue; token = match_token(p, tokens, args); switch (token) { case Opt_subvol: *subvol_name = match_strdup(&args[0]); break; case Opt_subvolid: intarg = 0; error = match_int(&args[0], &intarg); if (!error) { /* we want the original fs_tree */ if (!intarg) *subvol_objectid = BTRFS_FS_TREE_OBJECTID; else *subvol_objectid = intarg; } break; case Opt_subvolrootid: intarg = 0; error = match_int(&args[0], &intarg); if (!error) { /* we want the original fs_tree */ if (!intarg) *subvol_rootid = BTRFS_FS_TREE_OBJECTID; else *subvol_rootid = intarg; } break; case Opt_device: error = btrfs_scan_one_device(match_strdup(&args[0]), flags, holder, fs_devices); if (error) goto out_free_opts; break; default: break; } } out_free_opts: kfree(orig); out: /* * If no subvolume name is specified we use the default one. Allocate * a copy of the string "." here so that code later in the * mount path doesn't care if it's the default volume or another one. */ if (!*subvol_name) { *subvol_name = kstrdup(".", GFP_KERNEL); if (!*subvol_name) return -ENOMEM; } return error; } static struct dentry *get_default_root(struct super_block *sb, u64 subvol_objectid) { struct btrfs_root *root = sb->s_fs_info; struct btrfs_root *new_root; struct btrfs_dir_item *di; struct btrfs_path *path; struct btrfs_key location; struct inode *inode; struct dentry *dentry; u64 dir_id; int new = 0; /* * We have a specific subvol we want to mount, just setup location and * go look up the root. */ if (subvol_objectid) { location.objectid = subvol_objectid; location.type = BTRFS_ROOT_ITEM_KEY; location.offset = (u64)-1; goto find_root; } path = btrfs_alloc_path(); if (!path) return ERR_PTR(-ENOMEM); path->leave_spinning = 1; /* * Find the "default" dir item which points to the root item that we * will mount by default if we haven't been given a specific subvolume * to mount. */ dir_id = btrfs_super_root_dir(&root->fs_info->super_copy); di = btrfs_lookup_dir_item(NULL, root, path, dir_id, "default", 7, 0); if (IS_ERR(di)) { btrfs_free_path(path); return ERR_CAST(di); } if (!di) { /* * Ok the default dir item isn't there. This is weird since * it's always been there, but don't freak out, just try and * mount to root most subvolume. */ btrfs_free_path(path); dir_id = BTRFS_FIRST_FREE_OBJECTID; new_root = root->fs_info->fs_root; goto setup_root; } btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location); btrfs_free_path(path); find_root: new_root = btrfs_read_fs_root_no_name(root->fs_info, &location); if (IS_ERR(new_root)) return ERR_CAST(new_root); if (btrfs_root_refs(&new_root->root_item) == 0) return ERR_PTR(-ENOENT); dir_id = btrfs_root_dirid(&new_root->root_item); setup_root: location.objectid = dir_id; location.type = BTRFS_INODE_ITEM_KEY; location.offset = 0; inode = btrfs_iget(sb, &location, new_root, &new); if (IS_ERR(inode)) return ERR_CAST(inode); /* * If we're just mounting the root most subvol put the inode and return * a reference to the dentry. We will have already gotten a reference * to the inode in btrfs_fill_super so we're good to go. */ if (!new && sb->s_root->d_inode == inode) { iput(inode); return dget(sb->s_root); } if (new) { const struct qstr name = { .name = "/", .len = 1 }; /* * New inode, we need to make the dentry a sibling of s_root so * everything gets cleaned up properly on unmount. */ dentry = d_alloc(sb->s_root, &name); if (!dentry) { iput(inode); return ERR_PTR(-ENOMEM); } d_splice_alias(inode, dentry); } else { /* * We found the inode in cache, just find a dentry for it and * put the reference to the inode we just got. */ dentry = d_find_alias(inode); iput(inode); } return dentry; } static int btrfs_fill_super(struct super_block *sb, struct btrfs_fs_devices *fs_devices, void *data, int silent) { struct inode *inode; struct dentry *root_dentry; struct btrfs_root *tree_root; struct btrfs_key key; int err; sb->s_maxbytes = MAX_LFS_FILESIZE; sb->s_magic = BTRFS_SUPER_MAGIC; sb->s_op = &btrfs_super_ops; sb->s_d_op = &btrfs_dentry_operations; sb->s_export_op = &btrfs_export_ops; sb->s_xattr = btrfs_xattr_handlers; sb->s_time_gran = 1; #ifdef CONFIG_BTRFS_FS_POSIX_ACL sb->s_flags |= MS_POSIXACL; #endif tree_root = open_ctree(sb, fs_devices, (char *)data); if (IS_ERR(tree_root)) { printk("btrfs: open_ctree failed\n"); return PTR_ERR(tree_root); } sb->s_fs_info = tree_root; key.objectid = BTRFS_FIRST_FREE_OBJECTID; key.type = BTRFS_INODE_ITEM_KEY; key.offset = 0; inode = btrfs_iget(sb, &key, tree_root->fs_info->fs_root, NULL); if (IS_ERR(inode)) { err = PTR_ERR(inode); goto fail_close; } root_dentry = d_alloc_root(inode); if (!root_dentry) { iput(inode); err = -ENOMEM; goto fail_close; } sb->s_root = root_dentry; save_mount_options(sb, data); cleancache_init_fs(sb); return 0; fail_close: close_ctree(tree_root); return err; } int btrfs_sync_fs(struct super_block *sb, int wait) { struct btrfs_trans_handle *trans; struct btrfs_root *root = btrfs_sb(sb); int ret; trace_btrfs_sync_fs(wait); if (!wait) { filemap_flush(root->fs_info->btree_inode->i_mapping); return 0; } btrfs_start_delalloc_inodes(root, 0); btrfs_wait_ordered_extents(root, 0, 0); trans = btrfs_start_transaction(root, 0); if (IS_ERR(trans)) return PTR_ERR(trans); ret = btrfs_commit_transaction(trans, root); return ret; } static int btrfs_show_options(struct seq_file *seq, struct vfsmount *vfs) { struct btrfs_root *root = btrfs_sb(vfs->mnt_sb); struct btrfs_fs_info *info = root->fs_info; char *compress_type; if (btrfs_test_opt(root, DEGRADED)) seq_puts(seq, ",degraded"); if (btrfs_test_opt(root, NODATASUM)) seq_puts(seq, ",nodatasum"); if (btrfs_test_opt(root, NODATACOW)) seq_puts(seq, ",nodatacow"); if (btrfs_test_opt(root, NOBARRIER)) seq_puts(seq, ",nobarrier"); if (info->max_inline != 8192 * 1024) seq_printf(seq, ",max_inline=%llu", (unsigned long long)info->max_inline); if (info->alloc_start != 0) seq_printf(seq, ",alloc_start=%llu", (unsigned long long)info->alloc_start); if (info->thread_pool_size != min_t(unsigned long, num_online_cpus() + 2, 8)) seq_printf(seq, ",thread_pool=%d", info->thread_pool_size); if (btrfs_test_opt(root, COMPRESS)) { if (info->compress_type == BTRFS_COMPRESS_ZLIB) compress_type = "zlib"; else compress_type = "lzo"; if (btrfs_test_opt(root, FORCE_COMPRESS)) seq_printf(seq, ",compress-force=%s", compress_type); else seq_printf(seq, ",compress=%s", compress_type); } if (btrfs_test_opt(root, NOSSD)) seq_puts(seq, ",nossd"); if (btrfs_test_opt(root, SSD_SPREAD)) seq_puts(seq, ",ssd_spread"); else if (btrfs_test_opt(root, SSD)) seq_puts(seq, ",ssd"); if (btrfs_test_opt(root, NOTREELOG)) seq_puts(seq, ",notreelog"); if (btrfs_test_opt(root, FLUSHONCOMMIT)) seq_puts(seq, ",flushoncommit"); if (btrfs_test_opt(root, DISCARD)) seq_puts(seq, ",discard"); if (!(root->fs_info->sb->s_flags & MS_POSIXACL)) seq_puts(seq, ",noacl"); if (btrfs_test_opt(root, SPACE_CACHE)) seq_puts(seq, ",space_cache"); if (btrfs_test_opt(root, CLEAR_CACHE)) seq_puts(seq, ",clear_cache"); if (btrfs_test_opt(root, USER_SUBVOL_RM_ALLOWED)) seq_puts(seq, ",user_subvol_rm_allowed"); if (btrfs_test_opt(root, ENOSPC_DEBUG)) seq_puts(seq, ",enospc_debug"); if (btrfs_test_opt(root, AUTO_DEFRAG)) seq_puts(seq, ",autodefrag"); if (btrfs_test_opt(root, INODE_MAP_CACHE)) seq_puts(seq, ",inode_cache"); return 0; } static int btrfs_test_super(struct super_block *s, void *data) { struct btrfs_root *test_root = data; struct btrfs_root *root = btrfs_sb(s); /* * If this super block is going away, return false as it * can't match as an existing super block. */ if (!atomic_read(&s->s_active)) return 0; return root->fs_info->fs_devices == test_root->fs_info->fs_devices; } static int btrfs_set_super(struct super_block *s, void *data) { s->s_fs_info = data; return set_anon_super(s, data); } /* * Find a superblock for the given device / mount point. * * Note: This is based on get_sb_bdev from fs/super.c with a few additions * for multiple device setup. Make sure to keep it in sync. */ static struct dentry *btrfs_mount(struct file_system_type *fs_type, int flags, const char *device_name, void *data) { struct block_device *bdev = NULL; struct super_block *s; struct dentry *root; struct btrfs_fs_devices *fs_devices = NULL; struct btrfs_root *tree_root = NULL; struct btrfs_fs_info *fs_info = NULL; fmode_t mode = FMODE_READ; char *subvol_name = NULL; u64 subvol_objectid = 0; u64 subvol_rootid = 0; int error = 0; if (!(flags & MS_RDONLY)) mode |= FMODE_WRITE; error = btrfs_parse_early_options(data, mode, fs_type, &subvol_name, &subvol_objectid, &subvol_rootid, &fs_devices); if (error) return ERR_PTR(error); error = btrfs_scan_one_device(device_name, mode, fs_type, &fs_devices); if (error) goto error_free_subvol_name; error = btrfs_open_devices(fs_devices, mode, fs_type); if (error) goto error_free_subvol_name; if (!(flags & MS_RDONLY) && fs_devices->rw_devices == 0) { error = -EACCES; goto error_close_devices; } /* * Setup a dummy root and fs_info for test/set super. This is because * we don't actually fill this stuff out until open_ctree, but we need * it for searching for existing supers, so this lets us do that and * then open_ctree will properly initialize everything later. */ fs_info = kzalloc(sizeof(struct btrfs_fs_info), GFP_NOFS); tree_root = kzalloc(sizeof(struct btrfs_root), GFP_NOFS); if (!fs_info || !tree_root) { error = -ENOMEM; goto error_close_devices; } fs_info->tree_root = tree_root; fs_info->fs_devices = fs_devices; tree_root->fs_info = fs_info; bdev = fs_devices->latest_bdev; s = sget(fs_type, btrfs_test_super, btrfs_set_super, tree_root); if (IS_ERR(s)) goto error_s; if (s->s_root) { if ((flags ^ s->s_flags) & MS_RDONLY) { deactivate_locked_super(s); error = -EBUSY; goto error_close_devices; } btrfs_close_devices(fs_devices); kfree(fs_info); kfree(tree_root); } else { char b[BDEVNAME_SIZE]; s->s_flags = flags | MS_NOSEC; strlcpy(s->s_id, bdevname(bdev, b), sizeof(s->s_id)); error = btrfs_fill_super(s, fs_devices, data, flags & MS_SILENT ? 1 : 0); if (error) { deactivate_locked_super(s); goto error_free_subvol_name; } btrfs_sb(s)->fs_info->bdev_holder = fs_type; s->s_flags |= MS_ACTIVE; } /* if they gave us a subvolume name bind mount into that */ if (strcmp(subvol_name, ".")) { struct dentry *new_root; root = get_default_root(s, subvol_rootid); if (IS_ERR(root)) { error = PTR_ERR(root); deactivate_locked_super(s); goto error_free_subvol_name; } mutex_lock(&root->d_inode->i_mutex); new_root = lookup_one_len(subvol_name, root, strlen(subvol_name)); mutex_unlock(&root->d_inode->i_mutex); if (IS_ERR(new_root)) { dput(root); deactivate_locked_super(s); error = PTR_ERR(new_root); goto error_free_subvol_name; } if (!new_root->d_inode) { dput(root); dput(new_root); deactivate_locked_super(s); error = -ENXIO; goto error_free_subvol_name; } dput(root); root = new_root; } else { root = get_default_root(s, subvol_objectid); if (IS_ERR(root)) { error = PTR_ERR(root); deactivate_locked_super(s); goto error_free_subvol_name; } } kfree(subvol_name); return root; error_s: error = PTR_ERR(s); error_close_devices: btrfs_close_devices(fs_devices); kfree(fs_info); kfree(tree_root); error_free_subvol_name: kfree(subvol_name); return ERR_PTR(error); } static int btrfs_remount(struct super_block *sb, int *flags, char *data) { struct btrfs_root *root = btrfs_sb(sb); int ret; ret = btrfs_parse_options(root, data); if (ret) return -EINVAL; if ((*flags & MS_RDONLY) == (sb->s_flags & MS_RDONLY)) return 0; if (*flags & MS_RDONLY) { sb->s_flags |= MS_RDONLY; ret = btrfs_commit_super(root); WARN_ON(ret); } else { if (root->fs_info->fs_devices->rw_devices == 0) return -EACCES; if (btrfs_super_log_root(&root->fs_info->super_copy) != 0) return -EINVAL; ret = btrfs_cleanup_fs_roots(root->fs_info); WARN_ON(ret); /* recover relocation */ ret = btrfs_recover_relocation(root); WARN_ON(ret); sb->s_flags &= ~MS_RDONLY; } return 0; } /* Used to sort the devices by max_avail(descending sort) */ static int btrfs_cmp_device_free_bytes(const void *dev_info1, const void *dev_info2) { if (((struct btrfs_device_info *)dev_info1)->max_avail > ((struct btrfs_device_info *)dev_info2)->max_avail) return -1; else if (((struct btrfs_device_info *)dev_info1)->max_avail < ((struct btrfs_device_info *)dev_info2)->max_avail) return 1; else return 0; } /* * sort the devices by max_avail, in which max free extent size of each device * is stored.(Descending Sort) */ static inline void btrfs_descending_sort_devices( struct btrfs_device_info *devices, size_t nr_devices) { sort(devices, nr_devices, sizeof(struct btrfs_device_info), btrfs_cmp_device_free_bytes, NULL); } /* * The helper to calc the free space on the devices that can be used to store * file data. */ static int btrfs_calc_avail_data_space(struct btrfs_root *root, u64 *free_bytes) { struct btrfs_fs_info *fs_info = root->fs_info; struct btrfs_device_info *devices_info; struct btrfs_fs_devices *fs_devices = fs_info->fs_devices; struct btrfs_device *device; u64 skip_space; u64 type; u64 avail_space; u64 used_space; u64 min_stripe_size; int min_stripes = 1; int i = 0, nr_devices; int ret; nr_devices = fs_info->fs_devices->rw_devices; BUG_ON(!nr_devices); devices_info = kmalloc(sizeof(*devices_info) * nr_devices, GFP_NOFS); if (!devices_info) return -ENOMEM; /* calc min stripe number for data space alloction */ type = btrfs_get_alloc_profile(root, 1); if (type & BTRFS_BLOCK_GROUP_RAID0) min_stripes = 2; else if (type & BTRFS_BLOCK_GROUP_RAID1) min_stripes = 2; else if (type & BTRFS_BLOCK_GROUP_RAID10) min_stripes = 4; if (type & BTRFS_BLOCK_GROUP_DUP) min_stripe_size = 2 * BTRFS_STRIPE_LEN; else min_stripe_size = BTRFS_STRIPE_LEN; list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) { if (!device->in_fs_metadata) continue; avail_space = device->total_bytes - device->bytes_used; /* align with stripe_len */ do_div(avail_space, BTRFS_STRIPE_LEN); avail_space *= BTRFS_STRIPE_LEN; /* * In order to avoid overwritting the superblock on the drive, * btrfs starts at an offset of at least 1MB when doing chunk * allocation. */ skip_space = 1024 * 1024; /* user can set the offset in fs_info->alloc_start. */ if (fs_info->alloc_start + BTRFS_STRIPE_LEN <= device->total_bytes) skip_space = max(fs_info->alloc_start, skip_space); /* * btrfs can not use the free space in [0, skip_space - 1], * we must subtract it from the total. In order to implement * it, we account the used space in this range first. */ ret = btrfs_account_dev_extents_size(device, 0, skip_space - 1, &used_space); if (ret) { kfree(devices_info); return ret; } /* calc the free space in [0, skip_space - 1] */ skip_space -= used_space; /* * we can use the free space in [0, skip_space - 1], subtract * it from the total. */ if (avail_space && avail_space >= skip_space) avail_space -= skip_space; else avail_space = 0; if (avail_space < min_stripe_size) continue; devices_info[i].dev = device; devices_info[i].max_avail = avail_space; i++; } nr_devices = i; btrfs_descending_sort_devices(devices_info, nr_devices); i = nr_devices - 1; avail_space = 0; while (nr_devices >= min_stripes) { if (devices_info[i].max_avail >= min_stripe_size) { int j; u64 alloc_size; avail_space += devices_info[i].max_avail * min_stripes; alloc_size = devices_info[i].max_avail; for (j = i + 1 - min_stripes; j <= i; j++) devices_info[j].max_avail -= alloc_size; } i--; nr_devices--; } kfree(devices_info); *free_bytes = avail_space; return 0; } static int btrfs_statfs(struct dentry *dentry, struct kstatfs *buf) { struct btrfs_root *root = btrfs_sb(dentry->d_sb); struct btrfs_super_block *disk_super = &root->fs_info->super_copy; struct list_head *head = &root->fs_info->space_info; struct btrfs_space_info *found; u64 total_used = 0; u64 total_free_data = 0; int bits = dentry->d_sb->s_blocksize_bits; __be32 *fsid = (__be32 *)root->fs_info->fsid; int ret; /* holding chunk_muext to avoid allocating new chunks */ mutex_lock(&root->fs_info->chunk_mutex); rcu_read_lock(); list_for_each_entry_rcu(found, head, list) { if (found->flags & BTRFS_BLOCK_GROUP_DATA) { total_free_data += found->disk_total - found->disk_used; total_free_data -= btrfs_account_ro_block_groups_free_space(found); } total_used += found->disk_used; } rcu_read_unlock(); buf->f_namelen = BTRFS_NAME_LEN; buf->f_blocks = btrfs_super_total_bytes(disk_super) >> bits; buf->f_bfree = buf->f_blocks - (total_used >> bits); buf->f_bsize = dentry->d_sb->s_blocksize; buf->f_type = BTRFS_SUPER_MAGIC; buf->f_bavail = total_free_data; ret = btrfs_calc_avail_data_space(root, &total_free_data); if (ret) { mutex_unlock(&root->fs_info->chunk_mutex); return ret; } buf->f_bavail += total_free_data; buf->f_bavail = buf->f_bavail >> bits; mutex_unlock(&root->fs_info->chunk_mutex); /* We treat it as constant endianness (it doesn't matter _which_) because we want the fsid to come out the same whether mounted on a big-endian or little-endian host */ buf->f_fsid.val[0] = be32_to_cpu(fsid[0]) ^ be32_to_cpu(fsid[2]); buf->f_fsid.val[1] = be32_to_cpu(fsid[1]) ^ be32_to_cpu(fsid[3]); /* Mask in the root object ID too, to disambiguate subvols */ buf->f_fsid.val[0] ^= BTRFS_I(dentry->d_inode)->root->objectid >> 32; buf->f_fsid.val[1] ^= BTRFS_I(dentry->d_inode)->root->objectid; return 0; } static struct file_system_type btrfs_fs_type = { .owner = THIS_MODULE, .name = "btrfs", .mount = btrfs_mount, .kill_sb = kill_anon_super, .fs_flags = FS_REQUIRES_DEV, }; /* * used by btrfsctl to scan devices when no FS is mounted */ static long btrfs_control_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct btrfs_ioctl_vol_args *vol; struct btrfs_fs_devices *fs_devices; int ret = -ENOTTY; if (!capable(CAP_SYS_ADMIN)) return -EPERM; vol = memdup_user((void __user *)arg, sizeof(*vol)); if (IS_ERR(vol)) return PTR_ERR(vol); switch (cmd) { case BTRFS_IOC_SCAN_DEV: ret = btrfs_scan_one_device(vol->name, FMODE_READ, &btrfs_fs_type, &fs_devices); break; } kfree(vol); return ret; } static int btrfs_freeze(struct super_block *sb) { struct btrfs_root *root = btrfs_sb(sb); mutex_lock(&root->fs_info->transaction_kthread_mutex); mutex_lock(&root->fs_info->cleaner_mutex); return 0; } static int btrfs_unfreeze(struct super_block *sb) { struct btrfs_root *root = btrfs_sb(sb); mutex_unlock(&root->fs_info->cleaner_mutex); mutex_unlock(&root->fs_info->transaction_kthread_mutex); return 0; } static const struct super_operations btrfs_super_ops = { .drop_inode = btrfs_drop_inode, .evict_inode = btrfs_evict_inode, .put_super = btrfs_put_super, .sync_fs = btrfs_sync_fs, .show_options = btrfs_show_options, .write_inode = btrfs_write_inode, .dirty_inode = btrfs_dirty_inode, .alloc_inode = btrfs_alloc_inode, .destroy_inode = btrfs_destroy_inode, .statfs = btrfs_statfs, .remount_fs = btrfs_remount, .freeze_fs = btrfs_freeze, .unfreeze_fs = btrfs_unfreeze, }; static const struct file_operations btrfs_ctl_fops = { .unlocked_ioctl = btrfs_control_ioctl, .compat_ioctl = btrfs_control_ioctl, .owner = THIS_MODULE, .llseek = noop_llseek, }; static struct miscdevice btrfs_misc = { .minor = BTRFS_MINOR, .name = "btrfs-control", .fops = &btrfs_ctl_fops }; MODULE_ALIAS_MISCDEV(BTRFS_MINOR); MODULE_ALIAS("devname:btrfs-control"); static int btrfs_interface_init(void) { return misc_register(&btrfs_misc); } static void btrfs_interface_exit(void) { if (misc_deregister(&btrfs_misc) < 0) printk(KERN_INFO "misc_deregister failed for control device"); } static int __init init_btrfs_fs(void) { int err; err = btrfs_init_sysfs(); if (err) return err; err = btrfs_init_compress(); if (err) goto free_sysfs; err = btrfs_init_cachep(); if (err) goto free_compress; err = extent_io_init(); if (err) goto free_cachep; err = extent_map_init(); if (err) goto free_extent_io; err = btrfs_delayed_inode_init(); if (err) goto free_extent_map; err = btrfs_interface_init(); if (err) goto free_delayed_inode; err = register_filesystem(&btrfs_fs_type); if (err) goto unregister_ioctl; printk(KERN_INFO "%s loaded\n", BTRFS_BUILD_VERSION); return 0; unregister_ioctl: btrfs_interface_exit(); free_delayed_inode: btrfs_delayed_inode_exit(); free_extent_map: extent_map_exit(); free_extent_io: extent_io_exit(); free_cachep: btrfs_destroy_cachep(); free_compress: btrfs_exit_compress(); free_sysfs: btrfs_exit_sysfs(); return err; } static void __exit exit_btrfs_fs(void) { btrfs_destroy_cachep(); btrfs_delayed_inode_exit(); extent_map_exit(); extent_io_exit(); btrfs_interface_exit(); unregister_filesystem(&btrfs_fs_type); btrfs_exit_sysfs(); btrfs_cleanup_fs_uuids(); btrfs_exit_compress(); } module_init(init_btrfs_fs) module_exit(exit_btrfs_fs) MODULE_LICENSE("GPL");
gpl-2.0
vm03/android_kernel_lge_msm8610
fs/nfs/mount_clnt.c
3279
11964
/* * In-kernel MOUNT protocol client * * Copyright (C) 1997, Olaf Kirch <okir@monad.swb.de> */ #include <linux/types.h> #include <linux/socket.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/uio.h> #include <linux/net.h> #include <linux/in.h> #include <linux/sunrpc/clnt.h> #include <linux/sunrpc/sched.h> #include <linux/nfs_fs.h> #include "internal.h" #ifdef NFS_DEBUG # define NFSDBG_FACILITY NFSDBG_MOUNT #endif /* * Defined by RFC 1094, section A.3; and RFC 1813, section 5.1.4 */ #define MNTPATHLEN (1024) /* * XDR data type sizes */ #define encode_dirpath_sz (1 + XDR_QUADLEN(MNTPATHLEN)) #define MNT_status_sz (1) #define MNT_fhs_status_sz (1) #define MNT_fhandle_sz XDR_QUADLEN(NFS2_FHSIZE) #define MNT_fhandle3_sz (1 + XDR_QUADLEN(NFS3_FHSIZE)) #define MNT_authflav3_sz (1 + NFS_MAX_SECFLAVORS) /* * XDR argument and result sizes */ #define MNT_enc_dirpath_sz encode_dirpath_sz #define MNT_dec_mountres_sz (MNT_status_sz + MNT_fhandle_sz) #define MNT_dec_mountres3_sz (MNT_status_sz + MNT_fhandle_sz + \ MNT_authflav3_sz) /* * Defined by RFC 1094, section A.5 */ enum { MOUNTPROC_NULL = 0, MOUNTPROC_MNT = 1, MOUNTPROC_DUMP = 2, MOUNTPROC_UMNT = 3, MOUNTPROC_UMNTALL = 4, MOUNTPROC_EXPORT = 5, }; /* * Defined by RFC 1813, section 5.2 */ enum { MOUNTPROC3_NULL = 0, MOUNTPROC3_MNT = 1, MOUNTPROC3_DUMP = 2, MOUNTPROC3_UMNT = 3, MOUNTPROC3_UMNTALL = 4, MOUNTPROC3_EXPORT = 5, }; static const struct rpc_program mnt_program; /* * Defined by OpenGroup XNFS Version 3W, chapter 8 */ enum mountstat { MNT_OK = 0, MNT_EPERM = 1, MNT_ENOENT = 2, MNT_EACCES = 13, MNT_EINVAL = 22, }; static struct { u32 status; int errno; } mnt_errtbl[] = { { .status = MNT_OK, .errno = 0, }, { .status = MNT_EPERM, .errno = -EPERM, }, { .status = MNT_ENOENT, .errno = -ENOENT, }, { .status = MNT_EACCES, .errno = -EACCES, }, { .status = MNT_EINVAL, .errno = -EINVAL, }, }; /* * Defined by RFC 1813, section 5.1.5 */ enum mountstat3 { MNT3_OK = 0, /* no error */ MNT3ERR_PERM = 1, /* Not owner */ MNT3ERR_NOENT = 2, /* No such file or directory */ MNT3ERR_IO = 5, /* I/O error */ MNT3ERR_ACCES = 13, /* Permission denied */ MNT3ERR_NOTDIR = 20, /* Not a directory */ MNT3ERR_INVAL = 22, /* Invalid argument */ MNT3ERR_NAMETOOLONG = 63, /* Filename too long */ MNT3ERR_NOTSUPP = 10004, /* Operation not supported */ MNT3ERR_SERVERFAULT = 10006, /* A failure on the server */ }; static struct { u32 status; int errno; } mnt3_errtbl[] = { { .status = MNT3_OK, .errno = 0, }, { .status = MNT3ERR_PERM, .errno = -EPERM, }, { .status = MNT3ERR_NOENT, .errno = -ENOENT, }, { .status = MNT3ERR_IO, .errno = -EIO, }, { .status = MNT3ERR_ACCES, .errno = -EACCES, }, { .status = MNT3ERR_NOTDIR, .errno = -ENOTDIR, }, { .status = MNT3ERR_INVAL, .errno = -EINVAL, }, { .status = MNT3ERR_NAMETOOLONG, .errno = -ENAMETOOLONG, }, { .status = MNT3ERR_NOTSUPP, .errno = -ENOTSUPP, }, { .status = MNT3ERR_SERVERFAULT, .errno = -EREMOTEIO, }, }; struct mountres { int errno; struct nfs_fh *fh; unsigned int *auth_count; rpc_authflavor_t *auth_flavors; }; struct mnt_fhstatus { u32 status; struct nfs_fh *fh; }; /** * nfs_mount - Obtain an NFS file handle for the given host and path * @info: pointer to mount request arguments * * Uses default timeout parameters specified by underlying transport. */ int nfs_mount(struct nfs_mount_request *info) { struct mountres result = { .fh = info->fh, .auth_count = info->auth_flav_len, .auth_flavors = info->auth_flavs, }; struct rpc_message msg = { .rpc_argp = info->dirpath, .rpc_resp = &result, }; struct rpc_create_args args = { .net = info->net, .protocol = info->protocol, .address = info->sap, .addrsize = info->salen, .servername = info->hostname, .program = &mnt_program, .version = info->version, .authflavor = RPC_AUTH_UNIX, }; struct rpc_clnt *mnt_clnt; int status; dprintk("NFS: sending MNT request for %s:%s\n", (info->hostname ? info->hostname : "server"), info->dirpath); if (info->noresvport) args.flags |= RPC_CLNT_CREATE_NONPRIVPORT; mnt_clnt = rpc_create(&args); if (IS_ERR(mnt_clnt)) goto out_clnt_err; if (info->version == NFS_MNT3_VERSION) msg.rpc_proc = &mnt_clnt->cl_procinfo[MOUNTPROC3_MNT]; else msg.rpc_proc = &mnt_clnt->cl_procinfo[MOUNTPROC_MNT]; status = rpc_call_sync(mnt_clnt, &msg, 0); rpc_shutdown_client(mnt_clnt); if (status < 0) goto out_call_err; if (result.errno != 0) goto out_mnt_err; dprintk("NFS: MNT request succeeded\n"); status = 0; out: return status; out_clnt_err: status = PTR_ERR(mnt_clnt); dprintk("NFS: failed to create MNT RPC client, status=%d\n", status); goto out; out_call_err: dprintk("NFS: MNT request failed, status=%d\n", status); goto out; out_mnt_err: dprintk("NFS: MNT server returned result %d\n", result.errno); status = result.errno; goto out; } /** * nfs_umount - Notify a server that we have unmounted this export * @info: pointer to umount request arguments * * MOUNTPROC_UMNT is advisory, so we set a short timeout, and always * use UDP. */ void nfs_umount(const struct nfs_mount_request *info) { static const struct rpc_timeout nfs_umnt_timeout = { .to_initval = 1 * HZ, .to_maxval = 3 * HZ, .to_retries = 2, }; struct rpc_create_args args = { .net = info->net, .protocol = IPPROTO_UDP, .address = info->sap, .addrsize = info->salen, .timeout = &nfs_umnt_timeout, .servername = info->hostname, .program = &mnt_program, .version = info->version, .authflavor = RPC_AUTH_UNIX, .flags = RPC_CLNT_CREATE_NOPING, }; struct rpc_message msg = { .rpc_argp = info->dirpath, }; struct rpc_clnt *clnt; int status; if (info->noresvport) args.flags |= RPC_CLNT_CREATE_NONPRIVPORT; clnt = rpc_create(&args); if (IS_ERR(clnt)) goto out_clnt_err; dprintk("NFS: sending UMNT request for %s:%s\n", (info->hostname ? info->hostname : "server"), info->dirpath); if (info->version == NFS_MNT3_VERSION) msg.rpc_proc = &clnt->cl_procinfo[MOUNTPROC3_UMNT]; else msg.rpc_proc = &clnt->cl_procinfo[MOUNTPROC_UMNT]; status = rpc_call_sync(clnt, &msg, 0); rpc_shutdown_client(clnt); if (unlikely(status < 0)) goto out_call_err; return; out_clnt_err: dprintk("NFS: failed to create UMNT RPC client, status=%ld\n", PTR_ERR(clnt)); return; out_call_err: dprintk("NFS: UMNT request failed, status=%d\n", status); } /* * XDR encode/decode functions for MOUNT */ static void encode_mntdirpath(struct xdr_stream *xdr, const char *pathname) { const u32 pathname_len = strlen(pathname); __be32 *p; BUG_ON(pathname_len > MNTPATHLEN); p = xdr_reserve_space(xdr, 4 + pathname_len); xdr_encode_opaque(p, pathname, pathname_len); } static void mnt_xdr_enc_dirpath(struct rpc_rqst *req, struct xdr_stream *xdr, const char *dirpath) { encode_mntdirpath(xdr, dirpath); } /* * RFC 1094: "A non-zero status indicates some sort of error. In this * case, the status is a UNIX error number." This can be problematic * if the server and client use different errno values for the same * error. * * However, the OpenGroup XNFS spec provides a simple mapping that is * independent of local errno values on the server and the client. */ static int decode_status(struct xdr_stream *xdr, struct mountres *res) { unsigned int i; u32 status; __be32 *p; p = xdr_inline_decode(xdr, 4); if (unlikely(p == NULL)) return -EIO; status = be32_to_cpup(p); for (i = 0; i < ARRAY_SIZE(mnt_errtbl); i++) { if (mnt_errtbl[i].status == status) { res->errno = mnt_errtbl[i].errno; return 0; } } dprintk("NFS: unrecognized MNT status code: %u\n", status); res->errno = -EACCES; return 0; } static int decode_fhandle(struct xdr_stream *xdr, struct mountres *res) { struct nfs_fh *fh = res->fh; __be32 *p; p = xdr_inline_decode(xdr, NFS2_FHSIZE); if (unlikely(p == NULL)) return -EIO; fh->size = NFS2_FHSIZE; memcpy(fh->data, p, NFS2_FHSIZE); return 0; } static int mnt_xdr_dec_mountres(struct rpc_rqst *req, struct xdr_stream *xdr, struct mountres *res) { int status; status = decode_status(xdr, res); if (unlikely(status != 0 || res->errno != 0)) return status; return decode_fhandle(xdr, res); } static int decode_fhs_status(struct xdr_stream *xdr, struct mountres *res) { unsigned int i; u32 status; __be32 *p; p = xdr_inline_decode(xdr, 4); if (unlikely(p == NULL)) return -EIO; status = be32_to_cpup(p); for (i = 0; i < ARRAY_SIZE(mnt3_errtbl); i++) { if (mnt3_errtbl[i].status == status) { res->errno = mnt3_errtbl[i].errno; return 0; } } dprintk("NFS: unrecognized MNT3 status code: %u\n", status); res->errno = -EACCES; return 0; } static int decode_fhandle3(struct xdr_stream *xdr, struct mountres *res) { struct nfs_fh *fh = res->fh; u32 size; __be32 *p; p = xdr_inline_decode(xdr, 4); if (unlikely(p == NULL)) return -EIO; size = be32_to_cpup(p); if (size > NFS3_FHSIZE || size == 0) return -EIO; p = xdr_inline_decode(xdr, size); if (unlikely(p == NULL)) return -EIO; fh->size = size; memcpy(fh->data, p, size); return 0; } static int decode_auth_flavors(struct xdr_stream *xdr, struct mountres *res) { rpc_authflavor_t *flavors = res->auth_flavors; unsigned int *count = res->auth_count; u32 entries, i; __be32 *p; if (*count == 0) return 0; p = xdr_inline_decode(xdr, 4); if (unlikely(p == NULL)) return -EIO; entries = be32_to_cpup(p); dprintk("NFS: received %u auth flavors\n", entries); if (entries > NFS_MAX_SECFLAVORS) entries = NFS_MAX_SECFLAVORS; p = xdr_inline_decode(xdr, 4 * entries); if (unlikely(p == NULL)) return -EIO; if (entries > *count) entries = *count; for (i = 0; i < entries; i++) { flavors[i] = be32_to_cpup(p++); dprintk("NFS: auth flavor[%u]: %d\n", i, flavors[i]); } *count = i; return 0; } static int mnt_xdr_dec_mountres3(struct rpc_rqst *req, struct xdr_stream *xdr, struct mountres *res) { int status; status = decode_fhs_status(xdr, res); if (unlikely(status != 0 || res->errno != 0)) return status; status = decode_fhandle3(xdr, res); if (unlikely(status != 0)) { res->errno = -EBADHANDLE; return 0; } return decode_auth_flavors(xdr, res); } static struct rpc_procinfo mnt_procedures[] = { [MOUNTPROC_MNT] = { .p_proc = MOUNTPROC_MNT, .p_encode = (kxdreproc_t)mnt_xdr_enc_dirpath, .p_decode = (kxdrdproc_t)mnt_xdr_dec_mountres, .p_arglen = MNT_enc_dirpath_sz, .p_replen = MNT_dec_mountres_sz, .p_statidx = MOUNTPROC_MNT, .p_name = "MOUNT", }, [MOUNTPROC_UMNT] = { .p_proc = MOUNTPROC_UMNT, .p_encode = (kxdreproc_t)mnt_xdr_enc_dirpath, .p_arglen = MNT_enc_dirpath_sz, .p_statidx = MOUNTPROC_UMNT, .p_name = "UMOUNT", }, }; static struct rpc_procinfo mnt3_procedures[] = { [MOUNTPROC3_MNT] = { .p_proc = MOUNTPROC3_MNT, .p_encode = (kxdreproc_t)mnt_xdr_enc_dirpath, .p_decode = (kxdrdproc_t)mnt_xdr_dec_mountres3, .p_arglen = MNT_enc_dirpath_sz, .p_replen = MNT_dec_mountres3_sz, .p_statidx = MOUNTPROC3_MNT, .p_name = "MOUNT", }, [MOUNTPROC3_UMNT] = { .p_proc = MOUNTPROC3_UMNT, .p_encode = (kxdreproc_t)mnt_xdr_enc_dirpath, .p_arglen = MNT_enc_dirpath_sz, .p_statidx = MOUNTPROC3_UMNT, .p_name = "UMOUNT", }, }; static const struct rpc_version mnt_version1 = { .number = 1, .nrprocs = ARRAY_SIZE(mnt_procedures), .procs = mnt_procedures, }; static const struct rpc_version mnt_version3 = { .number = 3, .nrprocs = ARRAY_SIZE(mnt3_procedures), .procs = mnt3_procedures, }; static const struct rpc_version *mnt_version[] = { NULL, &mnt_version1, NULL, &mnt_version3, }; static struct rpc_stat mnt_stats; static const struct rpc_program mnt_program = { .name = "mount", .number = NFS_MNT_PROGRAM, .nrvers = ARRAY_SIZE(mnt_version), .version = mnt_version, .stats = &mnt_stats, };
gpl-2.0
SlimRoms/kernel_lge_mako
fs/nfs/mount_clnt.c
3279
11964
/* * In-kernel MOUNT protocol client * * Copyright (C) 1997, Olaf Kirch <okir@monad.swb.de> */ #include <linux/types.h> #include <linux/socket.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/uio.h> #include <linux/net.h> #include <linux/in.h> #include <linux/sunrpc/clnt.h> #include <linux/sunrpc/sched.h> #include <linux/nfs_fs.h> #include "internal.h" #ifdef NFS_DEBUG # define NFSDBG_FACILITY NFSDBG_MOUNT #endif /* * Defined by RFC 1094, section A.3; and RFC 1813, section 5.1.4 */ #define MNTPATHLEN (1024) /* * XDR data type sizes */ #define encode_dirpath_sz (1 + XDR_QUADLEN(MNTPATHLEN)) #define MNT_status_sz (1) #define MNT_fhs_status_sz (1) #define MNT_fhandle_sz XDR_QUADLEN(NFS2_FHSIZE) #define MNT_fhandle3_sz (1 + XDR_QUADLEN(NFS3_FHSIZE)) #define MNT_authflav3_sz (1 + NFS_MAX_SECFLAVORS) /* * XDR argument and result sizes */ #define MNT_enc_dirpath_sz encode_dirpath_sz #define MNT_dec_mountres_sz (MNT_status_sz + MNT_fhandle_sz) #define MNT_dec_mountres3_sz (MNT_status_sz + MNT_fhandle_sz + \ MNT_authflav3_sz) /* * Defined by RFC 1094, section A.5 */ enum { MOUNTPROC_NULL = 0, MOUNTPROC_MNT = 1, MOUNTPROC_DUMP = 2, MOUNTPROC_UMNT = 3, MOUNTPROC_UMNTALL = 4, MOUNTPROC_EXPORT = 5, }; /* * Defined by RFC 1813, section 5.2 */ enum { MOUNTPROC3_NULL = 0, MOUNTPROC3_MNT = 1, MOUNTPROC3_DUMP = 2, MOUNTPROC3_UMNT = 3, MOUNTPROC3_UMNTALL = 4, MOUNTPROC3_EXPORT = 5, }; static const struct rpc_program mnt_program; /* * Defined by OpenGroup XNFS Version 3W, chapter 8 */ enum mountstat { MNT_OK = 0, MNT_EPERM = 1, MNT_ENOENT = 2, MNT_EACCES = 13, MNT_EINVAL = 22, }; static struct { u32 status; int errno; } mnt_errtbl[] = { { .status = MNT_OK, .errno = 0, }, { .status = MNT_EPERM, .errno = -EPERM, }, { .status = MNT_ENOENT, .errno = -ENOENT, }, { .status = MNT_EACCES, .errno = -EACCES, }, { .status = MNT_EINVAL, .errno = -EINVAL, }, }; /* * Defined by RFC 1813, section 5.1.5 */ enum mountstat3 { MNT3_OK = 0, /* no error */ MNT3ERR_PERM = 1, /* Not owner */ MNT3ERR_NOENT = 2, /* No such file or directory */ MNT3ERR_IO = 5, /* I/O error */ MNT3ERR_ACCES = 13, /* Permission denied */ MNT3ERR_NOTDIR = 20, /* Not a directory */ MNT3ERR_INVAL = 22, /* Invalid argument */ MNT3ERR_NAMETOOLONG = 63, /* Filename too long */ MNT3ERR_NOTSUPP = 10004, /* Operation not supported */ MNT3ERR_SERVERFAULT = 10006, /* A failure on the server */ }; static struct { u32 status; int errno; } mnt3_errtbl[] = { { .status = MNT3_OK, .errno = 0, }, { .status = MNT3ERR_PERM, .errno = -EPERM, }, { .status = MNT3ERR_NOENT, .errno = -ENOENT, }, { .status = MNT3ERR_IO, .errno = -EIO, }, { .status = MNT3ERR_ACCES, .errno = -EACCES, }, { .status = MNT3ERR_NOTDIR, .errno = -ENOTDIR, }, { .status = MNT3ERR_INVAL, .errno = -EINVAL, }, { .status = MNT3ERR_NAMETOOLONG, .errno = -ENAMETOOLONG, }, { .status = MNT3ERR_NOTSUPP, .errno = -ENOTSUPP, }, { .status = MNT3ERR_SERVERFAULT, .errno = -EREMOTEIO, }, }; struct mountres { int errno; struct nfs_fh *fh; unsigned int *auth_count; rpc_authflavor_t *auth_flavors; }; struct mnt_fhstatus { u32 status; struct nfs_fh *fh; }; /** * nfs_mount - Obtain an NFS file handle for the given host and path * @info: pointer to mount request arguments * * Uses default timeout parameters specified by underlying transport. */ int nfs_mount(struct nfs_mount_request *info) { struct mountres result = { .fh = info->fh, .auth_count = info->auth_flav_len, .auth_flavors = info->auth_flavs, }; struct rpc_message msg = { .rpc_argp = info->dirpath, .rpc_resp = &result, }; struct rpc_create_args args = { .net = info->net, .protocol = info->protocol, .address = info->sap, .addrsize = info->salen, .servername = info->hostname, .program = &mnt_program, .version = info->version, .authflavor = RPC_AUTH_UNIX, }; struct rpc_clnt *mnt_clnt; int status; dprintk("NFS: sending MNT request for %s:%s\n", (info->hostname ? info->hostname : "server"), info->dirpath); if (info->noresvport) args.flags |= RPC_CLNT_CREATE_NONPRIVPORT; mnt_clnt = rpc_create(&args); if (IS_ERR(mnt_clnt)) goto out_clnt_err; if (info->version == NFS_MNT3_VERSION) msg.rpc_proc = &mnt_clnt->cl_procinfo[MOUNTPROC3_MNT]; else msg.rpc_proc = &mnt_clnt->cl_procinfo[MOUNTPROC_MNT]; status = rpc_call_sync(mnt_clnt, &msg, 0); rpc_shutdown_client(mnt_clnt); if (status < 0) goto out_call_err; if (result.errno != 0) goto out_mnt_err; dprintk("NFS: MNT request succeeded\n"); status = 0; out: return status; out_clnt_err: status = PTR_ERR(mnt_clnt); dprintk("NFS: failed to create MNT RPC client, status=%d\n", status); goto out; out_call_err: dprintk("NFS: MNT request failed, status=%d\n", status); goto out; out_mnt_err: dprintk("NFS: MNT server returned result %d\n", result.errno); status = result.errno; goto out; } /** * nfs_umount - Notify a server that we have unmounted this export * @info: pointer to umount request arguments * * MOUNTPROC_UMNT is advisory, so we set a short timeout, and always * use UDP. */ void nfs_umount(const struct nfs_mount_request *info) { static const struct rpc_timeout nfs_umnt_timeout = { .to_initval = 1 * HZ, .to_maxval = 3 * HZ, .to_retries = 2, }; struct rpc_create_args args = { .net = info->net, .protocol = IPPROTO_UDP, .address = info->sap, .addrsize = info->salen, .timeout = &nfs_umnt_timeout, .servername = info->hostname, .program = &mnt_program, .version = info->version, .authflavor = RPC_AUTH_UNIX, .flags = RPC_CLNT_CREATE_NOPING, }; struct rpc_message msg = { .rpc_argp = info->dirpath, }; struct rpc_clnt *clnt; int status; if (info->noresvport) args.flags |= RPC_CLNT_CREATE_NONPRIVPORT; clnt = rpc_create(&args); if (IS_ERR(clnt)) goto out_clnt_err; dprintk("NFS: sending UMNT request for %s:%s\n", (info->hostname ? info->hostname : "server"), info->dirpath); if (info->version == NFS_MNT3_VERSION) msg.rpc_proc = &clnt->cl_procinfo[MOUNTPROC3_UMNT]; else msg.rpc_proc = &clnt->cl_procinfo[MOUNTPROC_UMNT]; status = rpc_call_sync(clnt, &msg, 0); rpc_shutdown_client(clnt); if (unlikely(status < 0)) goto out_call_err; return; out_clnt_err: dprintk("NFS: failed to create UMNT RPC client, status=%ld\n", PTR_ERR(clnt)); return; out_call_err: dprintk("NFS: UMNT request failed, status=%d\n", status); } /* * XDR encode/decode functions for MOUNT */ static void encode_mntdirpath(struct xdr_stream *xdr, const char *pathname) { const u32 pathname_len = strlen(pathname); __be32 *p; BUG_ON(pathname_len > MNTPATHLEN); p = xdr_reserve_space(xdr, 4 + pathname_len); xdr_encode_opaque(p, pathname, pathname_len); } static void mnt_xdr_enc_dirpath(struct rpc_rqst *req, struct xdr_stream *xdr, const char *dirpath) { encode_mntdirpath(xdr, dirpath); } /* * RFC 1094: "A non-zero status indicates some sort of error. In this * case, the status is a UNIX error number." This can be problematic * if the server and client use different errno values for the same * error. * * However, the OpenGroup XNFS spec provides a simple mapping that is * independent of local errno values on the server and the client. */ static int decode_status(struct xdr_stream *xdr, struct mountres *res) { unsigned int i; u32 status; __be32 *p; p = xdr_inline_decode(xdr, 4); if (unlikely(p == NULL)) return -EIO; status = be32_to_cpup(p); for (i = 0; i < ARRAY_SIZE(mnt_errtbl); i++) { if (mnt_errtbl[i].status == status) { res->errno = mnt_errtbl[i].errno; return 0; } } dprintk("NFS: unrecognized MNT status code: %u\n", status); res->errno = -EACCES; return 0; } static int decode_fhandle(struct xdr_stream *xdr, struct mountres *res) { struct nfs_fh *fh = res->fh; __be32 *p; p = xdr_inline_decode(xdr, NFS2_FHSIZE); if (unlikely(p == NULL)) return -EIO; fh->size = NFS2_FHSIZE; memcpy(fh->data, p, NFS2_FHSIZE); return 0; } static int mnt_xdr_dec_mountres(struct rpc_rqst *req, struct xdr_stream *xdr, struct mountres *res) { int status; status = decode_status(xdr, res); if (unlikely(status != 0 || res->errno != 0)) return status; return decode_fhandle(xdr, res); } static int decode_fhs_status(struct xdr_stream *xdr, struct mountres *res) { unsigned int i; u32 status; __be32 *p; p = xdr_inline_decode(xdr, 4); if (unlikely(p == NULL)) return -EIO; status = be32_to_cpup(p); for (i = 0; i < ARRAY_SIZE(mnt3_errtbl); i++) { if (mnt3_errtbl[i].status == status) { res->errno = mnt3_errtbl[i].errno; return 0; } } dprintk("NFS: unrecognized MNT3 status code: %u\n", status); res->errno = -EACCES; return 0; } static int decode_fhandle3(struct xdr_stream *xdr, struct mountres *res) { struct nfs_fh *fh = res->fh; u32 size; __be32 *p; p = xdr_inline_decode(xdr, 4); if (unlikely(p == NULL)) return -EIO; size = be32_to_cpup(p); if (size > NFS3_FHSIZE || size == 0) return -EIO; p = xdr_inline_decode(xdr, size); if (unlikely(p == NULL)) return -EIO; fh->size = size; memcpy(fh->data, p, size); return 0; } static int decode_auth_flavors(struct xdr_stream *xdr, struct mountres *res) { rpc_authflavor_t *flavors = res->auth_flavors; unsigned int *count = res->auth_count; u32 entries, i; __be32 *p; if (*count == 0) return 0; p = xdr_inline_decode(xdr, 4); if (unlikely(p == NULL)) return -EIO; entries = be32_to_cpup(p); dprintk("NFS: received %u auth flavors\n", entries); if (entries > NFS_MAX_SECFLAVORS) entries = NFS_MAX_SECFLAVORS; p = xdr_inline_decode(xdr, 4 * entries); if (unlikely(p == NULL)) return -EIO; if (entries > *count) entries = *count; for (i = 0; i < entries; i++) { flavors[i] = be32_to_cpup(p++); dprintk("NFS: auth flavor[%u]: %d\n", i, flavors[i]); } *count = i; return 0; } static int mnt_xdr_dec_mountres3(struct rpc_rqst *req, struct xdr_stream *xdr, struct mountres *res) { int status; status = decode_fhs_status(xdr, res); if (unlikely(status != 0 || res->errno != 0)) return status; status = decode_fhandle3(xdr, res); if (unlikely(status != 0)) { res->errno = -EBADHANDLE; return 0; } return decode_auth_flavors(xdr, res); } static struct rpc_procinfo mnt_procedures[] = { [MOUNTPROC_MNT] = { .p_proc = MOUNTPROC_MNT, .p_encode = (kxdreproc_t)mnt_xdr_enc_dirpath, .p_decode = (kxdrdproc_t)mnt_xdr_dec_mountres, .p_arglen = MNT_enc_dirpath_sz, .p_replen = MNT_dec_mountres_sz, .p_statidx = MOUNTPROC_MNT, .p_name = "MOUNT", }, [MOUNTPROC_UMNT] = { .p_proc = MOUNTPROC_UMNT, .p_encode = (kxdreproc_t)mnt_xdr_enc_dirpath, .p_arglen = MNT_enc_dirpath_sz, .p_statidx = MOUNTPROC_UMNT, .p_name = "UMOUNT", }, }; static struct rpc_procinfo mnt3_procedures[] = { [MOUNTPROC3_MNT] = { .p_proc = MOUNTPROC3_MNT, .p_encode = (kxdreproc_t)mnt_xdr_enc_dirpath, .p_decode = (kxdrdproc_t)mnt_xdr_dec_mountres3, .p_arglen = MNT_enc_dirpath_sz, .p_replen = MNT_dec_mountres3_sz, .p_statidx = MOUNTPROC3_MNT, .p_name = "MOUNT", }, [MOUNTPROC3_UMNT] = { .p_proc = MOUNTPROC3_UMNT, .p_encode = (kxdreproc_t)mnt_xdr_enc_dirpath, .p_arglen = MNT_enc_dirpath_sz, .p_statidx = MOUNTPROC3_UMNT, .p_name = "UMOUNT", }, }; static const struct rpc_version mnt_version1 = { .number = 1, .nrprocs = ARRAY_SIZE(mnt_procedures), .procs = mnt_procedures, }; static const struct rpc_version mnt_version3 = { .number = 3, .nrprocs = ARRAY_SIZE(mnt3_procedures), .procs = mnt3_procedures, }; static const struct rpc_version *mnt_version[] = { NULL, &mnt_version1, NULL, &mnt_version3, }; static struct rpc_stat mnt_stats; static const struct rpc_program mnt_program = { .name = "mount", .number = NFS_MNT_PROGRAM, .nrvers = ARRAY_SIZE(mnt_version), .version = mnt_version, .stats = &mnt_stats, };
gpl-2.0
maniacx/android_kernel_htcleo-3.0
drivers/media/dvb/frontends/s5h1409.c
4303
23559
/* Samsung S5H1409 VSB/QAM demodulator driver Copyright (C) 2006 Steven Toth <stoth@linuxtv.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. */ #include <linux/kernel.h> #include <linux/init.h> #include <linux/module.h> #include <linux/string.h> #include <linux/slab.h> #include <linux/delay.h> #include "dvb_frontend.h" #include "s5h1409.h" struct s5h1409_state { struct i2c_adapter *i2c; /* configuration settings */ const struct s5h1409_config *config; struct dvb_frontend frontend; /* previous uncorrected block counter */ fe_modulation_t current_modulation; u32 current_frequency; int if_freq; u32 is_qam_locked; /* QAM tuning state goes through the following state transitions */ #define QAM_STATE_UNTUNED 0 #define QAM_STATE_TUNING_STARTED 1 #define QAM_STATE_INTERLEAVE_SET 2 #define QAM_STATE_QAM_OPTIMIZED_L1 3 #define QAM_STATE_QAM_OPTIMIZED_L2 4 #define QAM_STATE_QAM_OPTIMIZED_L3 5 u8 qam_state; }; static int debug; module_param(debug, int, 0644); MODULE_PARM_DESC(debug, "Enable verbose debug messages"); #define dprintk if (debug) printk /* Register values to initialise the demod, this will set VSB by default */ static struct init_tab { u8 reg; u16 data; } init_tab[] = { { 0x00, 0x0071, }, { 0x01, 0x3213, }, { 0x09, 0x0025, }, { 0x1c, 0x001d, }, { 0x1f, 0x002d, }, { 0x20, 0x001d, }, { 0x22, 0x0022, }, { 0x23, 0x0020, }, { 0x29, 0x110f, }, { 0x2a, 0x10b4, }, { 0x2b, 0x10ae, }, { 0x2c, 0x0031, }, { 0x31, 0x010d, }, { 0x32, 0x0100, }, { 0x44, 0x0510, }, { 0x54, 0x0104, }, { 0x58, 0x2222, }, { 0x59, 0x1162, }, { 0x5a, 0x3211, }, { 0x5d, 0x0370, }, { 0x5e, 0x0296, }, { 0x61, 0x0010, }, { 0x63, 0x4a00, }, { 0x65, 0x0800, }, { 0x71, 0x0003, }, { 0x72, 0x0470, }, { 0x81, 0x0002, }, { 0x82, 0x0600, }, { 0x86, 0x0002, }, { 0x8a, 0x2c38, }, { 0x8b, 0x2a37, }, { 0x92, 0x302f, }, { 0x93, 0x3332, }, { 0x96, 0x000c, }, { 0x99, 0x0101, }, { 0x9c, 0x2e37, }, { 0x9d, 0x2c37, }, { 0x9e, 0x2c37, }, { 0xab, 0x0100, }, { 0xac, 0x1003, }, { 0xad, 0x103f, }, { 0xe2, 0x0100, }, { 0xe3, 0x1000, }, { 0x28, 0x1010, }, { 0xb1, 0x000e, }, }; /* VSB SNR lookup table */ static struct vsb_snr_tab { u16 val; u16 data; } vsb_snr_tab[] = { { 924, 300, }, { 923, 300, }, { 918, 295, }, { 915, 290, }, { 911, 285, }, { 906, 280, }, { 901, 275, }, { 896, 270, }, { 891, 265, }, { 885, 260, }, { 879, 255, }, { 873, 250, }, { 864, 245, }, { 858, 240, }, { 850, 235, }, { 841, 230, }, { 832, 225, }, { 823, 220, }, { 812, 215, }, { 802, 210, }, { 788, 205, }, { 778, 200, }, { 767, 195, }, { 753, 190, }, { 740, 185, }, { 725, 180, }, { 707, 175, }, { 689, 170, }, { 671, 165, }, { 656, 160, }, { 637, 155, }, { 616, 150, }, { 542, 145, }, { 519, 140, }, { 507, 135, }, { 497, 130, }, { 492, 125, }, { 474, 120, }, { 300, 111, }, { 0, 0, }, }; /* QAM64 SNR lookup table */ static struct qam64_snr_tab { u16 val; u16 data; } qam64_snr_tab[] = { { 1, 0, }, { 12, 300, }, { 15, 290, }, { 18, 280, }, { 22, 270, }, { 23, 268, }, { 24, 266, }, { 25, 264, }, { 27, 262, }, { 28, 260, }, { 29, 258, }, { 30, 256, }, { 32, 254, }, { 33, 252, }, { 34, 250, }, { 35, 249, }, { 36, 248, }, { 37, 247, }, { 38, 246, }, { 39, 245, }, { 40, 244, }, { 41, 243, }, { 42, 241, }, { 43, 240, }, { 44, 239, }, { 45, 238, }, { 46, 237, }, { 47, 236, }, { 48, 235, }, { 49, 234, }, { 50, 233, }, { 51, 232, }, { 52, 231, }, { 53, 230, }, { 55, 229, }, { 56, 228, }, { 57, 227, }, { 58, 226, }, { 59, 225, }, { 60, 224, }, { 62, 223, }, { 63, 222, }, { 65, 221, }, { 66, 220, }, { 68, 219, }, { 69, 218, }, { 70, 217, }, { 72, 216, }, { 73, 215, }, { 75, 214, }, { 76, 213, }, { 78, 212, }, { 80, 211, }, { 81, 210, }, { 83, 209, }, { 84, 208, }, { 85, 207, }, { 87, 206, }, { 89, 205, }, { 91, 204, }, { 93, 203, }, { 95, 202, }, { 96, 201, }, { 104, 200, }, { 255, 0, }, }; /* QAM256 SNR lookup table */ static struct qam256_snr_tab { u16 val; u16 data; } qam256_snr_tab[] = { { 1, 0, }, { 12, 400, }, { 13, 390, }, { 15, 380, }, { 17, 360, }, { 19, 350, }, { 22, 348, }, { 23, 346, }, { 24, 344, }, { 25, 342, }, { 26, 340, }, { 27, 336, }, { 28, 334, }, { 29, 332, }, { 30, 330, }, { 31, 328, }, { 32, 326, }, { 33, 325, }, { 34, 322, }, { 35, 320, }, { 37, 318, }, { 39, 316, }, { 40, 314, }, { 41, 312, }, { 42, 310, }, { 43, 308, }, { 46, 306, }, { 47, 304, }, { 49, 302, }, { 51, 300, }, { 53, 298, }, { 54, 297, }, { 55, 296, }, { 56, 295, }, { 57, 294, }, { 59, 293, }, { 60, 292, }, { 61, 291, }, { 63, 290, }, { 64, 289, }, { 65, 288, }, { 66, 287, }, { 68, 286, }, { 69, 285, }, { 71, 284, }, { 72, 283, }, { 74, 282, }, { 75, 281, }, { 76, 280, }, { 77, 279, }, { 78, 278, }, { 81, 277, }, { 83, 276, }, { 84, 275, }, { 86, 274, }, { 87, 273, }, { 89, 272, }, { 90, 271, }, { 92, 270, }, { 93, 269, }, { 95, 268, }, { 96, 267, }, { 98, 266, }, { 100, 265, }, { 102, 264, }, { 104, 263, }, { 105, 262, }, { 106, 261, }, { 110, 260, }, { 255, 0, }, }; /* 8 bit registers, 16 bit values */ static int s5h1409_writereg(struct s5h1409_state *state, u8 reg, u16 data) { int ret; u8 buf[] = { reg, data >> 8, data & 0xff }; struct i2c_msg msg = { .addr = state->config->demod_address, .flags = 0, .buf = buf, .len = 3 }; ret = i2c_transfer(state->i2c, &msg, 1); if (ret != 1) printk(KERN_ERR "%s: error (reg == 0x%02x, val == 0x%04x, " "ret == %i)\n", __func__, reg, data, ret); return (ret != 1) ? -1 : 0; } static u16 s5h1409_readreg(struct s5h1409_state *state, u8 reg) { int ret; u8 b0[] = { reg }; u8 b1[] = { 0, 0 }; struct i2c_msg msg[] = { { .addr = state->config->demod_address, .flags = 0, .buf = b0, .len = 1 }, { .addr = state->config->demod_address, .flags = I2C_M_RD, .buf = b1, .len = 2 } }; ret = i2c_transfer(state->i2c, msg, 2); if (ret != 2) printk("%s: readreg error (ret == %i)\n", __func__, ret); return (b1[0] << 8) | b1[1]; } static int s5h1409_softreset(struct dvb_frontend *fe) { struct s5h1409_state *state = fe->demodulator_priv; dprintk("%s()\n", __func__); s5h1409_writereg(state, 0xf5, 0); s5h1409_writereg(state, 0xf5, 1); state->is_qam_locked = 0; state->qam_state = QAM_STATE_UNTUNED; return 0; } #define S5H1409_VSB_IF_FREQ 5380 #define S5H1409_QAM_IF_FREQ (state->config->qam_if) static int s5h1409_set_if_freq(struct dvb_frontend *fe, int KHz) { struct s5h1409_state *state = fe->demodulator_priv; dprintk("%s(%d KHz)\n", __func__, KHz); switch (KHz) { case 4000: s5h1409_writereg(state, 0x87, 0x014b); s5h1409_writereg(state, 0x88, 0x0cb5); s5h1409_writereg(state, 0x89, 0x03e2); break; case 5380: case 44000: default: s5h1409_writereg(state, 0x87, 0x01be); s5h1409_writereg(state, 0x88, 0x0436); s5h1409_writereg(state, 0x89, 0x054d); break; } state->if_freq = KHz; return 0; } static int s5h1409_set_spectralinversion(struct dvb_frontend *fe, int inverted) { struct s5h1409_state *state = fe->demodulator_priv; dprintk("%s(%d)\n", __func__, inverted); if (inverted == 1) return s5h1409_writereg(state, 0x1b, 0x1101); /* Inverted */ else return s5h1409_writereg(state, 0x1b, 0x0110); /* Normal */ } static int s5h1409_enable_modulation(struct dvb_frontend *fe, fe_modulation_t m) { struct s5h1409_state *state = fe->demodulator_priv; dprintk("%s(0x%08x)\n", __func__, m); switch (m) { case VSB_8: dprintk("%s() VSB_8\n", __func__); if (state->if_freq != S5H1409_VSB_IF_FREQ) s5h1409_set_if_freq(fe, S5H1409_VSB_IF_FREQ); s5h1409_writereg(state, 0xf4, 0); break; case QAM_64: case QAM_256: case QAM_AUTO: dprintk("%s() QAM_AUTO (64/256)\n", __func__); if (state->if_freq != S5H1409_QAM_IF_FREQ) s5h1409_set_if_freq(fe, S5H1409_QAM_IF_FREQ); s5h1409_writereg(state, 0xf4, 1); s5h1409_writereg(state, 0x85, 0x110); break; default: dprintk("%s() Invalid modulation\n", __func__); return -EINVAL; } state->current_modulation = m; s5h1409_softreset(fe); return 0; } static int s5h1409_i2c_gate_ctrl(struct dvb_frontend *fe, int enable) { struct s5h1409_state *state = fe->demodulator_priv; dprintk("%s(%d)\n", __func__, enable); if (enable) return s5h1409_writereg(state, 0xf3, 1); else return s5h1409_writereg(state, 0xf3, 0); } static int s5h1409_set_gpio(struct dvb_frontend *fe, int enable) { struct s5h1409_state *state = fe->demodulator_priv; dprintk("%s(%d)\n", __func__, enable); if (enable) return s5h1409_writereg(state, 0xe3, s5h1409_readreg(state, 0xe3) | 0x1100); else return s5h1409_writereg(state, 0xe3, s5h1409_readreg(state, 0xe3) & 0xfeff); } static int s5h1409_sleep(struct dvb_frontend *fe, int enable) { struct s5h1409_state *state = fe->demodulator_priv; dprintk("%s(%d)\n", __func__, enable); return s5h1409_writereg(state, 0xf2, enable); } static int s5h1409_register_reset(struct dvb_frontend *fe) { struct s5h1409_state *state = fe->demodulator_priv; dprintk("%s()\n", __func__); return s5h1409_writereg(state, 0xfa, 0); } static void s5h1409_set_qam_amhum_mode(struct dvb_frontend *fe) { struct s5h1409_state *state = fe->demodulator_priv; u16 reg; if (state->qam_state < QAM_STATE_INTERLEAVE_SET) { /* We should not perform amhum optimization until the interleave mode has been configured */ return; } if (state->qam_state == QAM_STATE_QAM_OPTIMIZED_L3) { /* We've already reached the maximum optimization level, so dont bother banging on the status registers */ return; } /* QAM EQ lock check */ reg = s5h1409_readreg(state, 0xf0); if ((reg >> 13) & 0x1) { reg &= 0xff; s5h1409_writereg(state, 0x96, 0x000c); if (reg < 0x68) { if (state->qam_state < QAM_STATE_QAM_OPTIMIZED_L3) { dprintk("%s() setting QAM state to OPT_L3\n", __func__); s5h1409_writereg(state, 0x93, 0x3130); s5h1409_writereg(state, 0x9e, 0x2836); state->qam_state = QAM_STATE_QAM_OPTIMIZED_L3; } } else { if (state->qam_state < QAM_STATE_QAM_OPTIMIZED_L2) { dprintk("%s() setting QAM state to OPT_L2\n", __func__); s5h1409_writereg(state, 0x93, 0x3332); s5h1409_writereg(state, 0x9e, 0x2c37); state->qam_state = QAM_STATE_QAM_OPTIMIZED_L2; } } } else { if (state->qam_state < QAM_STATE_QAM_OPTIMIZED_L1) { dprintk("%s() setting QAM state to OPT_L1\n", __func__); s5h1409_writereg(state, 0x96, 0x0008); s5h1409_writereg(state, 0x93, 0x3332); s5h1409_writereg(state, 0x9e, 0x2c37); state->qam_state = QAM_STATE_QAM_OPTIMIZED_L1; } } } static void s5h1409_set_qam_amhum_mode_legacy(struct dvb_frontend *fe) { struct s5h1409_state *state = fe->demodulator_priv; u16 reg; if (state->is_qam_locked) return; /* QAM EQ lock check */ reg = s5h1409_readreg(state, 0xf0); if ((reg >> 13) & 0x1) { state->is_qam_locked = 1; reg &= 0xff; s5h1409_writereg(state, 0x96, 0x00c); if ((reg < 0x38) || (reg > 0x68)) { s5h1409_writereg(state, 0x93, 0x3332); s5h1409_writereg(state, 0x9e, 0x2c37); } else { s5h1409_writereg(state, 0x93, 0x3130); s5h1409_writereg(state, 0x9e, 0x2836); } } else { s5h1409_writereg(state, 0x96, 0x0008); s5h1409_writereg(state, 0x93, 0x3332); s5h1409_writereg(state, 0x9e, 0x2c37); } } static void s5h1409_set_qam_interleave_mode(struct dvb_frontend *fe) { struct s5h1409_state *state = fe->demodulator_priv; u16 reg, reg1, reg2; if (state->qam_state >= QAM_STATE_INTERLEAVE_SET) { /* We've done the optimization already */ return; } reg = s5h1409_readreg(state, 0xf1); /* Master lock */ if ((reg >> 15) & 0x1) { if (state->qam_state == QAM_STATE_UNTUNED || state->qam_state == QAM_STATE_TUNING_STARTED) { dprintk("%s() setting QAM state to INTERLEAVE_SET\n", __func__); reg1 = s5h1409_readreg(state, 0xb2); reg2 = s5h1409_readreg(state, 0xad); s5h1409_writereg(state, 0x96, 0x0020); s5h1409_writereg(state, 0xad, (((reg1 & 0xf000) >> 4) | (reg2 & 0xf0ff))); state->qam_state = QAM_STATE_INTERLEAVE_SET; } } else { if (state->qam_state == QAM_STATE_UNTUNED) { dprintk("%s() setting QAM state to TUNING_STARTED\n", __func__); s5h1409_writereg(state, 0x96, 0x08); s5h1409_writereg(state, 0xab, s5h1409_readreg(state, 0xab) | 0x1001); state->qam_state = QAM_STATE_TUNING_STARTED; } } } static void s5h1409_set_qam_interleave_mode_legacy(struct dvb_frontend *fe) { struct s5h1409_state *state = fe->demodulator_priv; u16 reg, reg1, reg2; reg = s5h1409_readreg(state, 0xf1); /* Master lock */ if ((reg >> 15) & 0x1) { if (state->qam_state != 2) { state->qam_state = 2; reg1 = s5h1409_readreg(state, 0xb2); reg2 = s5h1409_readreg(state, 0xad); s5h1409_writereg(state, 0x96, 0x20); s5h1409_writereg(state, 0xad, (((reg1 & 0xf000) >> 4) | (reg2 & 0xf0ff))); s5h1409_writereg(state, 0xab, s5h1409_readreg(state, 0xab) & 0xeffe); } } else { if (state->qam_state != 1) { state->qam_state = 1; s5h1409_writereg(state, 0x96, 0x08); s5h1409_writereg(state, 0xab, s5h1409_readreg(state, 0xab) | 0x1001); } } } /* Talk to the demod, set the FEC, GUARD, QAM settings etc */ static int s5h1409_set_frontend(struct dvb_frontend *fe, struct dvb_frontend_parameters *p) { struct s5h1409_state *state = fe->demodulator_priv; dprintk("%s(frequency=%d)\n", __func__, p->frequency); s5h1409_softreset(fe); state->current_frequency = p->frequency; s5h1409_enable_modulation(fe, p->u.vsb.modulation); if (fe->ops.tuner_ops.set_params) { if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 1); fe->ops.tuner_ops.set_params(fe, p); if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 0); } /* Issue a reset to the demod so it knows to resync against the newly tuned frequency */ s5h1409_softreset(fe); /* Optimize the demod for QAM */ if (state->current_modulation != VSB_8) { /* This almost certainly applies to all boards, but for now only do it for the HVR-1600. Once the other boards are tested, the "legacy" versions can just go away */ if (state->config->hvr1600_opt == S5H1409_HVR1600_OPTIMIZE) { s5h1409_set_qam_interleave_mode(fe); s5h1409_set_qam_amhum_mode(fe); } else { s5h1409_set_qam_amhum_mode_legacy(fe); s5h1409_set_qam_interleave_mode_legacy(fe); } } return 0; } static int s5h1409_set_mpeg_timing(struct dvb_frontend *fe, int mode) { struct s5h1409_state *state = fe->demodulator_priv; u16 val; dprintk("%s(%d)\n", __func__, mode); val = s5h1409_readreg(state, 0xac) & 0xcfff; switch (mode) { case S5H1409_MPEGTIMING_CONTINOUS_INVERTING_CLOCK: val |= 0x0000; break; case S5H1409_MPEGTIMING_CONTINOUS_NONINVERTING_CLOCK: dprintk("%s(%d) Mode1 or Defaulting\n", __func__, mode); val |= 0x1000; break; case S5H1409_MPEGTIMING_NONCONTINOUS_INVERTING_CLOCK: val |= 0x2000; break; case S5H1409_MPEGTIMING_NONCONTINOUS_NONINVERTING_CLOCK: val |= 0x3000; break; default: return -EINVAL; } /* Configure MPEG Signal Timing charactistics */ return s5h1409_writereg(state, 0xac, val); } /* Reset the demod hardware and reset all of the configuration registers to a default state. */ static int s5h1409_init(struct dvb_frontend *fe) { int i; struct s5h1409_state *state = fe->demodulator_priv; dprintk("%s()\n", __func__); s5h1409_sleep(fe, 0); s5h1409_register_reset(fe); for (i = 0; i < ARRAY_SIZE(init_tab); i++) s5h1409_writereg(state, init_tab[i].reg, init_tab[i].data); /* The datasheet says that after initialisation, VSB is default */ state->current_modulation = VSB_8; /* Optimize for the HVR-1600 if appropriate. Note that some of these may get folded into the generic case after testing with other devices */ if (state->config->hvr1600_opt == S5H1409_HVR1600_OPTIMIZE) { /* VSB AGC REF */ s5h1409_writereg(state, 0x09, 0x0050); /* Unknown but Windows driver does it... */ s5h1409_writereg(state, 0x21, 0x0001); s5h1409_writereg(state, 0x50, 0x030e); /* QAM AGC REF */ s5h1409_writereg(state, 0x82, 0x0800); } if (state->config->output_mode == S5H1409_SERIAL_OUTPUT) s5h1409_writereg(state, 0xab, s5h1409_readreg(state, 0xab) | 0x100); /* Serial */ else s5h1409_writereg(state, 0xab, s5h1409_readreg(state, 0xab) & 0xfeff); /* Parallel */ s5h1409_set_spectralinversion(fe, state->config->inversion); s5h1409_set_if_freq(fe, state->if_freq); s5h1409_set_gpio(fe, state->config->gpio); s5h1409_set_mpeg_timing(fe, state->config->mpeg_timing); s5h1409_softreset(fe); /* Note: Leaving the I2C gate closed. */ s5h1409_i2c_gate_ctrl(fe, 0); return 0; } static int s5h1409_read_status(struct dvb_frontend *fe, fe_status_t *status) { struct s5h1409_state *state = fe->demodulator_priv; u16 reg; u32 tuner_status = 0; *status = 0; /* Optimize the demod for QAM */ if (state->current_modulation != VSB_8) { /* This almost certainly applies to all boards, but for now only do it for the HVR-1600. Once the other boards are tested, the "legacy" versions can just go away */ if (state->config->hvr1600_opt == S5H1409_HVR1600_OPTIMIZE) { s5h1409_set_qam_interleave_mode(fe); s5h1409_set_qam_amhum_mode(fe); } } /* Get the demodulator status */ reg = s5h1409_readreg(state, 0xf1); if (reg & 0x1000) *status |= FE_HAS_VITERBI; if (reg & 0x8000) *status |= FE_HAS_LOCK | FE_HAS_SYNC; switch (state->config->status_mode) { case S5H1409_DEMODLOCKING: if (*status & FE_HAS_VITERBI) *status |= FE_HAS_CARRIER | FE_HAS_SIGNAL; break; case S5H1409_TUNERLOCKING: /* Get the tuner status */ if (fe->ops.tuner_ops.get_status) { if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 1); fe->ops.tuner_ops.get_status(fe, &tuner_status); if (fe->ops.i2c_gate_ctrl) fe->ops.i2c_gate_ctrl(fe, 0); } if (tuner_status) *status |= FE_HAS_CARRIER | FE_HAS_SIGNAL; break; } dprintk("%s() status 0x%08x\n", __func__, *status); return 0; } static int s5h1409_qam256_lookup_snr(struct dvb_frontend *fe, u16 *snr, u16 v) { int i, ret = -EINVAL; dprintk("%s()\n", __func__); for (i = 0; i < ARRAY_SIZE(qam256_snr_tab); i++) { if (v < qam256_snr_tab[i].val) { *snr = qam256_snr_tab[i].data; ret = 0; break; } } return ret; } static int s5h1409_qam64_lookup_snr(struct dvb_frontend *fe, u16 *snr, u16 v) { int i, ret = -EINVAL; dprintk("%s()\n", __func__); for (i = 0; i < ARRAY_SIZE(qam64_snr_tab); i++) { if (v < qam64_snr_tab[i].val) { *snr = qam64_snr_tab[i].data; ret = 0; break; } } return ret; } static int s5h1409_vsb_lookup_snr(struct dvb_frontend *fe, u16 *snr, u16 v) { int i, ret = -EINVAL; dprintk("%s()\n", __func__); for (i = 0; i < ARRAY_SIZE(vsb_snr_tab); i++) { if (v > vsb_snr_tab[i].val) { *snr = vsb_snr_tab[i].data; ret = 0; break; } } dprintk("%s() snr=%d\n", __func__, *snr); return ret; } static int s5h1409_read_snr(struct dvb_frontend *fe, u16 *snr) { struct s5h1409_state *state = fe->demodulator_priv; u16 reg; dprintk("%s()\n", __func__); switch (state->current_modulation) { case QAM_64: reg = s5h1409_readreg(state, 0xf0) & 0xff; return s5h1409_qam64_lookup_snr(fe, snr, reg); case QAM_256: reg = s5h1409_readreg(state, 0xf0) & 0xff; return s5h1409_qam256_lookup_snr(fe, snr, reg); case VSB_8: reg = s5h1409_readreg(state, 0xf1) & 0x3ff; return s5h1409_vsb_lookup_snr(fe, snr, reg); default: break; } return -EINVAL; } static int s5h1409_read_signal_strength(struct dvb_frontend *fe, u16 *signal_strength) { return s5h1409_read_snr(fe, signal_strength); } static int s5h1409_read_ucblocks(struct dvb_frontend *fe, u32 *ucblocks) { struct s5h1409_state *state = fe->demodulator_priv; *ucblocks = s5h1409_readreg(state, 0xb5); return 0; } static int s5h1409_read_ber(struct dvb_frontend *fe, u32 *ber) { return s5h1409_read_ucblocks(fe, ber); } static int s5h1409_get_frontend(struct dvb_frontend *fe, struct dvb_frontend_parameters *p) { struct s5h1409_state *state = fe->demodulator_priv; p->frequency = state->current_frequency; p->u.vsb.modulation = state->current_modulation; return 0; } static int s5h1409_get_tune_settings(struct dvb_frontend *fe, struct dvb_frontend_tune_settings *tune) { tune->min_delay_ms = 1000; return 0; } static void s5h1409_release(struct dvb_frontend *fe) { struct s5h1409_state *state = fe->demodulator_priv; kfree(state); } static struct dvb_frontend_ops s5h1409_ops; struct dvb_frontend *s5h1409_attach(const struct s5h1409_config *config, struct i2c_adapter *i2c) { struct s5h1409_state *state = NULL; u16 reg; /* allocate memory for the internal state */ state = kzalloc(sizeof(struct s5h1409_state), GFP_KERNEL); if (state == NULL) goto error; /* setup the state */ state->config = config; state->i2c = i2c; state->current_modulation = 0; state->if_freq = S5H1409_VSB_IF_FREQ; /* check if the demod exists */ reg = s5h1409_readreg(state, 0x04); if ((reg != 0x0066) && (reg != 0x007f)) goto error; /* create dvb_frontend */ memcpy(&state->frontend.ops, &s5h1409_ops, sizeof(struct dvb_frontend_ops)); state->frontend.demodulator_priv = state; if (s5h1409_init(&state->frontend) != 0) { printk(KERN_ERR "%s: Failed to initialize correctly\n", __func__); goto error; } /* Note: Leaving the I2C gate open here. */ s5h1409_i2c_gate_ctrl(&state->frontend, 1); return &state->frontend; error: kfree(state); return NULL; } EXPORT_SYMBOL(s5h1409_attach); static struct dvb_frontend_ops s5h1409_ops = { .info = { .name = "Samsung S5H1409 QAM/8VSB Frontend", .type = FE_ATSC, .frequency_min = 54000000, .frequency_max = 858000000, .frequency_stepsize = 62500, .caps = FE_CAN_QAM_64 | FE_CAN_QAM_256 | FE_CAN_8VSB }, .init = s5h1409_init, .i2c_gate_ctrl = s5h1409_i2c_gate_ctrl, .set_frontend = s5h1409_set_frontend, .get_frontend = s5h1409_get_frontend, .get_tune_settings = s5h1409_get_tune_settings, .read_status = s5h1409_read_status, .read_ber = s5h1409_read_ber, .read_signal_strength = s5h1409_read_signal_strength, .read_snr = s5h1409_read_snr, .read_ucblocks = s5h1409_read_ucblocks, .release = s5h1409_release, }; MODULE_DESCRIPTION("Samsung S5H1409 QAM-B/ATSC Demodulator driver"); MODULE_AUTHOR("Steven Toth"); MODULE_LICENSE("GPL"); /* * Local variables: * c-basic-offset: 8 */
gpl-2.0
cristianomatos/android_kernel_motorola_msm8226
drivers/ata/pata_palmld.c
5071
3259
/* * drivers/ata/pata_palmld.c * * Driver for IDE channel in Palm LifeDrive * * Based on research of: * Alex Osborne <ato@meshy.org> * * Rewrite for mainline: * Marek Vasut <marek.vasut@gmail.com> * * Rewritten version based on pata_ixp4xx_cf.c: * ixp4xx PATA/Compact Flash driver * Copyright (C) 2006-07 Tower Technologies * Author: Alessandro Zummo <a.zummo@towertech.it> * * 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/libata.h> #include <linux/irq.h> #include <linux/platform_device.h> #include <linux/delay.h> #include <linux/gpio.h> #include <scsi/scsi_host.h> #include <mach/palmld.h> #define DRV_NAME "pata_palmld" static struct gpio palmld_hdd_gpios[] = { { GPIO_NR_PALMLD_IDE_PWEN, GPIOF_INIT_HIGH, "HDD Power" }, { GPIO_NR_PALMLD_IDE_RESET, GPIOF_INIT_LOW, "HDD Reset" }, }; static struct scsi_host_template palmld_sht = { ATA_PIO_SHT(DRV_NAME), }; static struct ata_port_operations palmld_port_ops = { .inherits = &ata_sff_port_ops, .sff_data_xfer = ata_sff_data_xfer_noirq, .cable_detect = ata_cable_40wire, }; static __devinit int palmld_pata_probe(struct platform_device *pdev) { struct ata_host *host; struct ata_port *ap; void __iomem *mem; int ret; /* allocate host */ host = ata_host_alloc(&pdev->dev, 1); if (!host) { ret = -ENOMEM; goto err1; } /* remap drive's physical memory address */ mem = devm_ioremap(&pdev->dev, PALMLD_IDE_PHYS, 0x1000); if (!mem) { ret = -ENOMEM; goto err1; } /* request and activate power GPIO, IRQ GPIO */ ret = gpio_request_array(palmld_hdd_gpios, ARRAY_SIZE(palmld_hdd_gpios)); if (ret) goto err1; /* reset the drive */ gpio_set_value(GPIO_NR_PALMLD_IDE_RESET, 0); msleep(30); gpio_set_value(GPIO_NR_PALMLD_IDE_RESET, 1); msleep(30); /* setup the ata port */ ap = host->ports[0]; ap->ops = &palmld_port_ops; ap->pio_mask = ATA_PIO4; ap->flags |= ATA_FLAG_PIO_POLLING; /* memory mapping voodoo */ ap->ioaddr.cmd_addr = mem + 0x10; ap->ioaddr.altstatus_addr = mem + 0xe; ap->ioaddr.ctl_addr = mem + 0xe; /* start the port */ ata_sff_std_ports(&ap->ioaddr); /* activate host */ ret = ata_host_activate(host, 0, NULL, IRQF_TRIGGER_RISING, &palmld_sht); if (ret) goto err2; return ret; err2: gpio_free_array(palmld_hdd_gpios, ARRAY_SIZE(palmld_hdd_gpios)); err1: return ret; } static __devexit int palmld_pata_remove(struct platform_device *dev) { struct ata_host *host = platform_get_drvdata(dev); ata_host_detach(host); /* power down the HDD */ gpio_set_value(GPIO_NR_PALMLD_IDE_PWEN, 0); gpio_free_array(palmld_hdd_gpios, ARRAY_SIZE(palmld_hdd_gpios)); return 0; } static struct platform_driver palmld_pata_platform_driver = { .driver = { .name = DRV_NAME, .owner = THIS_MODULE, }, .probe = palmld_pata_probe, .remove = __devexit_p(palmld_pata_remove), }; module_platform_driver(palmld_pata_platform_driver); MODULE_AUTHOR("Marek Vasut <marek.vasut@gmail.com>"); MODULE_DESCRIPTION("PalmLD PATA driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:" DRV_NAME);
gpl-2.0
FEDEVEL/openrex-linux-3.14
arch/powerpc/platforms/embedded6xx/usbgecko_udbg.c
11727
6864
/* * arch/powerpc/platforms/embedded6xx/usbgecko_udbg.c * * udbg serial input/output routines for the USB Gecko adapter. * Copyright (C) 2008-2009 The GameCube Linux Team * Copyright (C) 2008,2009 Albert Herranz * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * */ #include <mm/mmu_decl.h> #include <asm/io.h> #include <asm/prom.h> #include <asm/udbg.h> #include <asm/fixmap.h> #include "usbgecko_udbg.h" #define EXI_CLK_32MHZ 5 #define EXI_CSR 0x00 #define EXI_CSR_CLKMASK (0x7<<4) #define EXI_CSR_CLK_32MHZ (EXI_CLK_32MHZ<<4) #define EXI_CSR_CSMASK (0x7<<7) #define EXI_CSR_CS_0 (0x1<<7) /* Chip Select 001 */ #define EXI_CR 0x0c #define EXI_CR_TSTART (1<<0) #define EXI_CR_WRITE (1<<2) #define EXI_CR_READ_WRITE (2<<2) #define EXI_CR_TLEN(len) (((len)-1)<<4) #define EXI_DATA 0x10 #define UG_READ_ATTEMPTS 100 #define UG_WRITE_ATTEMPTS 100 static void __iomem *ug_io_base; /* * Performs one input/output transaction between the exi host and the usbgecko. */ static u32 ug_io_transaction(u32 in) { u32 __iomem *csr_reg = ug_io_base + EXI_CSR; u32 __iomem *data_reg = ug_io_base + EXI_DATA; u32 __iomem *cr_reg = ug_io_base + EXI_CR; u32 csr, data, cr; /* select */ csr = EXI_CSR_CLK_32MHZ | EXI_CSR_CS_0; out_be32(csr_reg, csr); /* read/write */ data = in; out_be32(data_reg, data); cr = EXI_CR_TLEN(2) | EXI_CR_READ_WRITE | EXI_CR_TSTART; out_be32(cr_reg, cr); while (in_be32(cr_reg) & EXI_CR_TSTART) barrier(); /* deselect */ out_be32(csr_reg, 0); /* result */ data = in_be32(data_reg); return data; } /* * Returns true if an usbgecko adapter is found. */ static int ug_is_adapter_present(void) { if (!ug_io_base) return 0; return ug_io_transaction(0x90000000) == 0x04700000; } /* * Returns true if the TX fifo is ready for transmission. */ static int ug_is_txfifo_ready(void) { return ug_io_transaction(0xc0000000) & 0x04000000; } /* * Tries to transmit a character. * If the TX fifo is not ready the result is undefined. */ static void ug_raw_putc(char ch) { ug_io_transaction(0xb0000000 | (ch << 20)); } /* * Transmits a character. * It silently fails if the TX fifo is not ready after a number of retries. */ static void ug_putc(char ch) { int count = UG_WRITE_ATTEMPTS; if (!ug_io_base) return; if (ch == '\n') ug_putc('\r'); while (!ug_is_txfifo_ready() && count--) barrier(); if (count >= 0) ug_raw_putc(ch); } /* * Returns true if the RX fifo is ready for transmission. */ static int ug_is_rxfifo_ready(void) { return ug_io_transaction(0xd0000000) & 0x04000000; } /* * Tries to receive a character. * If a character is unavailable the function returns -1. */ static int ug_raw_getc(void) { u32 data = ug_io_transaction(0xa0000000); if (data & 0x08000000) return (data >> 16) & 0xff; else return -1; } /* * Receives a character. * It fails if the RX fifo is not ready after a number of retries. */ static int ug_getc(void) { int count = UG_READ_ATTEMPTS; if (!ug_io_base) return -1; while (!ug_is_rxfifo_ready() && count--) barrier(); return ug_raw_getc(); } /* * udbg functions. * */ /* * Transmits a character. */ void ug_udbg_putc(char ch) { ug_putc(ch); } /* * Receives a character. Waits until a character is available. */ static int ug_udbg_getc(void) { int ch; while ((ch = ug_getc()) == -1) barrier(); return ch; } /* * Receives a character. If a character is not available, returns -1. */ static int ug_udbg_getc_poll(void) { if (!ug_is_rxfifo_ready()) return -1; return ug_getc(); } /* * Retrieves and prepares the virtual address needed to access the hardware. */ static void __iomem *ug_udbg_setup_exi_io_base(struct device_node *np) { void __iomem *exi_io_base = NULL; phys_addr_t paddr; const unsigned int *reg; reg = of_get_property(np, "reg", NULL); if (reg) { paddr = of_translate_address(np, reg); if (paddr) exi_io_base = ioremap(paddr, reg[1]); } return exi_io_base; } /* * Checks if a USB Gecko adapter is inserted in any memory card slot. */ static void __iomem *ug_udbg_probe(void __iomem *exi_io_base) { int i; /* look for a usbgecko on memcard slots A and B */ for (i = 0; i < 2; i++) { ug_io_base = exi_io_base + 0x14 * i; if (ug_is_adapter_present()) break; } if (i == 2) ug_io_base = NULL; return ug_io_base; } /* * USB Gecko udbg support initialization. */ void __init ug_udbg_init(void) { struct device_node *np; void __iomem *exi_io_base; if (ug_io_base) udbg_printf("%s: early -> final\n", __func__); np = of_find_compatible_node(NULL, NULL, "nintendo,flipper-exi"); if (!np) { udbg_printf("%s: EXI node not found\n", __func__); goto done; } exi_io_base = ug_udbg_setup_exi_io_base(np); if (!exi_io_base) { udbg_printf("%s: failed to setup EXI io base\n", __func__); goto done; } if (!ug_udbg_probe(exi_io_base)) { udbg_printf("usbgecko_udbg: not found\n"); iounmap(exi_io_base); } else { udbg_putc = ug_udbg_putc; udbg_getc = ug_udbg_getc; udbg_getc_poll = ug_udbg_getc_poll; udbg_printf("usbgecko_udbg: ready\n"); } done: if (np) of_node_put(np); return; } #ifdef CONFIG_PPC_EARLY_DEBUG_USBGECKO static phys_addr_t __init ug_early_grab_io_addr(void) { #if defined(CONFIG_GAMECUBE) return 0x0c000000; #elif defined(CONFIG_WII) return 0x0d000000; #else #error Invalid platform for USB Gecko based early debugging. #endif } /* * USB Gecko early debug support initialization for udbg. */ void __init udbg_init_usbgecko(void) { void __iomem *early_debug_area; void __iomem *exi_io_base; /* * At this point we have a BAT already setup that enables I/O * to the EXI hardware. * * The BAT uses a virtual address range reserved at the fixmap. * This must match the virtual address configured in * head_32.S:setup_usbgecko_bat(). */ early_debug_area = (void __iomem *)__fix_to_virt(FIX_EARLY_DEBUG_BASE); exi_io_base = early_debug_area + 0x00006800; /* try to detect a USB Gecko */ if (!ug_udbg_probe(exi_io_base)) return; /* we found a USB Gecko, load udbg hooks */ udbg_putc = ug_udbg_putc; udbg_getc = ug_udbg_getc; udbg_getc_poll = ug_udbg_getc_poll; /* * Prepare again the same BAT for MMU_init. * This allows udbg I/O to continue working after the MMU is * turned on for real. * It is safe to continue using the same virtual address as it is * a reserved fixmap area. */ setbat(1, (unsigned long)early_debug_area, ug_early_grab_io_addr(), 128*1024, PAGE_KERNEL_NCG); } #endif /* CONFIG_PPC_EARLY_DEBUG_USBGECKO */
gpl-2.0
DZB-Team/kernel_torino_cm11
net/rxrpc/ar-proc.c
14287
5159
/* /proc/net/ support for AF_RXRPC * * Copyright (C) 2007 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/module.h> #include <net/sock.h> #include <net/af_rxrpc.h> #include "ar-internal.h" static const char *const rxrpc_conn_states[] = { [RXRPC_CONN_UNUSED] = "Unused ", [RXRPC_CONN_CLIENT] = "Client ", [RXRPC_CONN_SERVER_UNSECURED] = "SvUnsec ", [RXRPC_CONN_SERVER_CHALLENGING] = "SvChall ", [RXRPC_CONN_SERVER] = "SvSecure", [RXRPC_CONN_REMOTELY_ABORTED] = "RmtAbort", [RXRPC_CONN_LOCALLY_ABORTED] = "LocAbort", [RXRPC_CONN_NETWORK_ERROR] = "NetError", }; /* * generate a list of extant and dead calls in /proc/net/rxrpc_calls */ static void *rxrpc_call_seq_start(struct seq_file *seq, loff_t *_pos) { read_lock(&rxrpc_call_lock); return seq_list_start_head(&rxrpc_calls, *_pos); } static void *rxrpc_call_seq_next(struct seq_file *seq, void *v, loff_t *pos) { return seq_list_next(v, &rxrpc_calls, pos); } static void rxrpc_call_seq_stop(struct seq_file *seq, void *v) { read_unlock(&rxrpc_call_lock); } static int rxrpc_call_seq_show(struct seq_file *seq, void *v) { struct rxrpc_transport *trans; struct rxrpc_call *call; char lbuff[4 + 4 + 4 + 4 + 5 + 1], rbuff[4 + 4 + 4 + 4 + 5 + 1]; if (v == &rxrpc_calls) { seq_puts(seq, "Proto Local Remote " " SvID ConnID CallID End Use State Abort " " UserID\n"); return 0; } call = list_entry(v, struct rxrpc_call, link); trans = call->conn->trans; sprintf(lbuff, "%pI4:%u", &trans->local->srx.transport.sin.sin_addr, ntohs(trans->local->srx.transport.sin.sin_port)); sprintf(rbuff, "%pI4:%u", &trans->peer->srx.transport.sin.sin_addr, ntohs(trans->peer->srx.transport.sin.sin_port)); seq_printf(seq, "UDP %-22.22s %-22.22s %4x %08x %08x %s %3u" " %-8.8s %08x %lx\n", lbuff, rbuff, ntohs(call->conn->service_id), ntohl(call->conn->cid), ntohl(call->call_id), call->conn->in_clientflag ? "Svc" : "Clt", atomic_read(&call->usage), rxrpc_call_states[call->state], call->abort_code, call->user_call_ID); return 0; } static const struct seq_operations rxrpc_call_seq_ops = { .start = rxrpc_call_seq_start, .next = rxrpc_call_seq_next, .stop = rxrpc_call_seq_stop, .show = rxrpc_call_seq_show, }; static int rxrpc_call_seq_open(struct inode *inode, struct file *file) { return seq_open(file, &rxrpc_call_seq_ops); } const struct file_operations rxrpc_call_seq_fops = { .owner = THIS_MODULE, .open = rxrpc_call_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; /* * generate a list of extant virtual connections in /proc/net/rxrpc_conns */ static void *rxrpc_connection_seq_start(struct seq_file *seq, loff_t *_pos) { read_lock(&rxrpc_connection_lock); return seq_list_start_head(&rxrpc_connections, *_pos); } static void *rxrpc_connection_seq_next(struct seq_file *seq, void *v, loff_t *pos) { return seq_list_next(v, &rxrpc_connections, pos); } static void rxrpc_connection_seq_stop(struct seq_file *seq, void *v) { read_unlock(&rxrpc_connection_lock); } static int rxrpc_connection_seq_show(struct seq_file *seq, void *v) { struct rxrpc_connection *conn; struct rxrpc_transport *trans; char lbuff[4 + 4 + 4 + 4 + 5 + 1], rbuff[4 + 4 + 4 + 4 + 5 + 1]; if (v == &rxrpc_connections) { seq_puts(seq, "Proto Local Remote " " SvID ConnID Calls End Use State Key " " Serial ISerial\n" ); return 0; } conn = list_entry(v, struct rxrpc_connection, link); trans = conn->trans; sprintf(lbuff, "%pI4:%u", &trans->local->srx.transport.sin.sin_addr, ntohs(trans->local->srx.transport.sin.sin_port)); sprintf(rbuff, "%pI4:%u", &trans->peer->srx.transport.sin.sin_addr, ntohs(trans->peer->srx.transport.sin.sin_port)); seq_printf(seq, "UDP %-22.22s %-22.22s %4x %08x %08x %s %3u" " %s %08x %08x %08x\n", lbuff, rbuff, ntohs(conn->service_id), ntohl(conn->cid), conn->call_counter, conn->in_clientflag ? "Svc" : "Clt", atomic_read(&conn->usage), rxrpc_conn_states[conn->state], key_serial(conn->key), atomic_read(&conn->serial), atomic_read(&conn->hi_serial)); return 0; } static const struct seq_operations rxrpc_connection_seq_ops = { .start = rxrpc_connection_seq_start, .next = rxrpc_connection_seq_next, .stop = rxrpc_connection_seq_stop, .show = rxrpc_connection_seq_show, }; static int rxrpc_connection_seq_open(struct inode *inode, struct file *file) { return seq_open(file, &rxrpc_connection_seq_ops); } const struct file_operations rxrpc_connection_seq_fops = { .owner = THIS_MODULE, .open = rxrpc_connection_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, };
gpl-2.0
jyunyen/Nexus7_Kernal
net/rxrpc/ar-proc.c
14287
5159
/* /proc/net/ support for AF_RXRPC * * Copyright (C) 2007 Red Hat, Inc. All Rights Reserved. * Written by David Howells (dhowells@redhat.com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/module.h> #include <net/sock.h> #include <net/af_rxrpc.h> #include "ar-internal.h" static const char *const rxrpc_conn_states[] = { [RXRPC_CONN_UNUSED] = "Unused ", [RXRPC_CONN_CLIENT] = "Client ", [RXRPC_CONN_SERVER_UNSECURED] = "SvUnsec ", [RXRPC_CONN_SERVER_CHALLENGING] = "SvChall ", [RXRPC_CONN_SERVER] = "SvSecure", [RXRPC_CONN_REMOTELY_ABORTED] = "RmtAbort", [RXRPC_CONN_LOCALLY_ABORTED] = "LocAbort", [RXRPC_CONN_NETWORK_ERROR] = "NetError", }; /* * generate a list of extant and dead calls in /proc/net/rxrpc_calls */ static void *rxrpc_call_seq_start(struct seq_file *seq, loff_t *_pos) { read_lock(&rxrpc_call_lock); return seq_list_start_head(&rxrpc_calls, *_pos); } static void *rxrpc_call_seq_next(struct seq_file *seq, void *v, loff_t *pos) { return seq_list_next(v, &rxrpc_calls, pos); } static void rxrpc_call_seq_stop(struct seq_file *seq, void *v) { read_unlock(&rxrpc_call_lock); } static int rxrpc_call_seq_show(struct seq_file *seq, void *v) { struct rxrpc_transport *trans; struct rxrpc_call *call; char lbuff[4 + 4 + 4 + 4 + 5 + 1], rbuff[4 + 4 + 4 + 4 + 5 + 1]; if (v == &rxrpc_calls) { seq_puts(seq, "Proto Local Remote " " SvID ConnID CallID End Use State Abort " " UserID\n"); return 0; } call = list_entry(v, struct rxrpc_call, link); trans = call->conn->trans; sprintf(lbuff, "%pI4:%u", &trans->local->srx.transport.sin.sin_addr, ntohs(trans->local->srx.transport.sin.sin_port)); sprintf(rbuff, "%pI4:%u", &trans->peer->srx.transport.sin.sin_addr, ntohs(trans->peer->srx.transport.sin.sin_port)); seq_printf(seq, "UDP %-22.22s %-22.22s %4x %08x %08x %s %3u" " %-8.8s %08x %lx\n", lbuff, rbuff, ntohs(call->conn->service_id), ntohl(call->conn->cid), ntohl(call->call_id), call->conn->in_clientflag ? "Svc" : "Clt", atomic_read(&call->usage), rxrpc_call_states[call->state], call->abort_code, call->user_call_ID); return 0; } static const struct seq_operations rxrpc_call_seq_ops = { .start = rxrpc_call_seq_start, .next = rxrpc_call_seq_next, .stop = rxrpc_call_seq_stop, .show = rxrpc_call_seq_show, }; static int rxrpc_call_seq_open(struct inode *inode, struct file *file) { return seq_open(file, &rxrpc_call_seq_ops); } const struct file_operations rxrpc_call_seq_fops = { .owner = THIS_MODULE, .open = rxrpc_call_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; /* * generate a list of extant virtual connections in /proc/net/rxrpc_conns */ static void *rxrpc_connection_seq_start(struct seq_file *seq, loff_t *_pos) { read_lock(&rxrpc_connection_lock); return seq_list_start_head(&rxrpc_connections, *_pos); } static void *rxrpc_connection_seq_next(struct seq_file *seq, void *v, loff_t *pos) { return seq_list_next(v, &rxrpc_connections, pos); } static void rxrpc_connection_seq_stop(struct seq_file *seq, void *v) { read_unlock(&rxrpc_connection_lock); } static int rxrpc_connection_seq_show(struct seq_file *seq, void *v) { struct rxrpc_connection *conn; struct rxrpc_transport *trans; char lbuff[4 + 4 + 4 + 4 + 5 + 1], rbuff[4 + 4 + 4 + 4 + 5 + 1]; if (v == &rxrpc_connections) { seq_puts(seq, "Proto Local Remote " " SvID ConnID Calls End Use State Key " " Serial ISerial\n" ); return 0; } conn = list_entry(v, struct rxrpc_connection, link); trans = conn->trans; sprintf(lbuff, "%pI4:%u", &trans->local->srx.transport.sin.sin_addr, ntohs(trans->local->srx.transport.sin.sin_port)); sprintf(rbuff, "%pI4:%u", &trans->peer->srx.transport.sin.sin_addr, ntohs(trans->peer->srx.transport.sin.sin_port)); seq_printf(seq, "UDP %-22.22s %-22.22s %4x %08x %08x %s %3u" " %s %08x %08x %08x\n", lbuff, rbuff, ntohs(conn->service_id), ntohl(conn->cid), conn->call_counter, conn->in_clientflag ? "Svc" : "Clt", atomic_read(&conn->usage), rxrpc_conn_states[conn->state], key_serial(conn->key), atomic_read(&conn->serial), atomic_read(&conn->hi_serial)); return 0; } static const struct seq_operations rxrpc_connection_seq_ops = { .start = rxrpc_connection_seq_start, .next = rxrpc_connection_seq_next, .stop = rxrpc_connection_seq_stop, .show = rxrpc_connection_seq_show, }; static int rxrpc_connection_seq_open(struct inode *inode, struct file *file) { return seq_open(file, &rxrpc_connection_seq_ops); } const struct file_operations rxrpc_connection_seq_fops = { .owner = THIS_MODULE, .open = rxrpc_connection_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, };
gpl-2.0
longqiany/linux
drivers/net/wireless/iwlwifi/mvm/nvm.c
208
24099
/****************************************************************************** * * This file is provided under a dual BSD/GPLv2 license. When using or * redistributing this file, you may do so under either license. * * GPL LICENSE SUMMARY * * Copyright(c) 2012 - 2014 Intel Corporation. All rights reserved. * Copyright(c) 2013 - 2015 Intel Mobile Communications GmbH * * This program is free software; you can redistribute it and/or modify * it under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, * USA * * The full GNU General Public License is included in this distribution * in the file called COPYING. * * Contact Information: * Intel Linux Wireless <ilw@linux.intel.com> * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497 * * BSD LICENSE * * Copyright(c) 2012 - 2014 Intel Corporation. All rights reserved. * Copyright(c) 2013 - 2015 Intel Mobile Communications GmbH * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *****************************************************************************/ #include <linux/firmware.h> #include <linux/rtnetlink.h> #include <linux/pci.h> #include <linux/acpi.h> #include "iwl-trans.h" #include "iwl-csr.h" #include "mvm.h" #include "iwl-eeprom-parse.h" #include "iwl-eeprom-read.h" #include "iwl-nvm-parse.h" #include "iwl-prph.h" /* Default NVM size to read */ #define IWL_NVM_DEFAULT_CHUNK_SIZE (2*1024) #define IWL_MAX_NVM_SECTION_SIZE 0x1b58 #define IWL_MAX_NVM_8000_SECTION_SIZE 0x1ffc #define NVM_WRITE_OPCODE 1 #define NVM_READ_OPCODE 0 /* load nvm chunk response */ enum { READ_NVM_CHUNK_SUCCEED = 0, READ_NVM_CHUNK_NOT_VALID_ADDRESS = 1 }; /* * prepare the NVM host command w/ the pointers to the nvm buffer * and send it to fw */ static int iwl_nvm_write_chunk(struct iwl_mvm *mvm, u16 section, u16 offset, u16 length, const u8 *data) { struct iwl_nvm_access_cmd nvm_access_cmd = { .offset = cpu_to_le16(offset), .length = cpu_to_le16(length), .type = cpu_to_le16(section), .op_code = NVM_WRITE_OPCODE, }; struct iwl_host_cmd cmd = { .id = NVM_ACCESS_CMD, .len = { sizeof(struct iwl_nvm_access_cmd), length }, .flags = CMD_SEND_IN_RFKILL, .data = { &nvm_access_cmd, data }, /* data may come from vmalloc, so use _DUP */ .dataflags = { 0, IWL_HCMD_DFL_DUP }, }; return iwl_mvm_send_cmd(mvm, &cmd); } static int iwl_nvm_read_chunk(struct iwl_mvm *mvm, u16 section, u16 offset, u16 length, u8 *data) { struct iwl_nvm_access_cmd nvm_access_cmd = { .offset = cpu_to_le16(offset), .length = cpu_to_le16(length), .type = cpu_to_le16(section), .op_code = NVM_READ_OPCODE, }; struct iwl_nvm_access_resp *nvm_resp; struct iwl_rx_packet *pkt; struct iwl_host_cmd cmd = { .id = NVM_ACCESS_CMD, .flags = CMD_WANT_SKB | CMD_SEND_IN_RFKILL, .data = { &nvm_access_cmd, }, }; int ret, bytes_read, offset_read; u8 *resp_data; cmd.len[0] = sizeof(struct iwl_nvm_access_cmd); ret = iwl_mvm_send_cmd(mvm, &cmd); if (ret) return ret; pkt = cmd.resp_pkt; /* Extract NVM response */ nvm_resp = (void *)pkt->data; ret = le16_to_cpu(nvm_resp->status); bytes_read = le16_to_cpu(nvm_resp->length); offset_read = le16_to_cpu(nvm_resp->offset); resp_data = nvm_resp->data; if (ret) { if ((offset != 0) && (ret == READ_NVM_CHUNK_NOT_VALID_ADDRESS)) { /* * meaning of NOT_VALID_ADDRESS: * driver try to read chunk from address that is * multiple of 2K and got an error since addr is empty. * meaning of (offset != 0): driver already * read valid data from another chunk so this case * is not an error. */ IWL_DEBUG_EEPROM(mvm->trans->dev, "NVM access command failed on offset 0x%x since that section size is multiple 2K\n", offset); ret = 0; } else { IWL_DEBUG_EEPROM(mvm->trans->dev, "NVM access command failed with status %d (device: %s)\n", ret, mvm->cfg->name); ret = -EIO; } goto exit; } if (offset_read != offset) { IWL_ERR(mvm, "NVM ACCESS response with invalid offset %d\n", offset_read); ret = -EINVAL; goto exit; } /* Write data to NVM */ memcpy(data + offset, resp_data, bytes_read); ret = bytes_read; exit: iwl_free_resp(&cmd); return ret; } static int iwl_nvm_write_section(struct iwl_mvm *mvm, u16 section, const u8 *data, u16 length) { int offset = 0; /* copy data in chunks of 2k (and remainder if any) */ while (offset < length) { int chunk_size, ret; chunk_size = min(IWL_NVM_DEFAULT_CHUNK_SIZE, length - offset); ret = iwl_nvm_write_chunk(mvm, section, offset, chunk_size, data + offset); if (ret < 0) return ret; offset += chunk_size; } return 0; } /* * Reads an NVM section completely. * NICs prior to 7000 family doesn't have a real NVM, but just read * section 0 which is the EEPROM. Because the EEPROM reading is unlimited * by uCode, we need to manually check in this case that we don't * overflow and try to read more than the EEPROM size. * For 7000 family NICs, we supply the maximal size we can read, and * the uCode fills the response with as much data as we can, * without overflowing, so no check is needed. */ static int iwl_nvm_read_section(struct iwl_mvm *mvm, u16 section, u8 *data, u32 size_read) { u16 length, offset = 0; int ret; /* Set nvm section read length */ length = IWL_NVM_DEFAULT_CHUNK_SIZE; ret = length; /* Read the NVM until exhausted (reading less than requested) */ while (ret == length) { /* Check no memory assumptions fail and cause an overflow */ if ((size_read + offset + length) > mvm->cfg->base_params->eeprom_size) { IWL_ERR(mvm, "EEPROM size is too small for NVM\n"); return -ENOBUFS; } ret = iwl_nvm_read_chunk(mvm, section, offset, length, data); if (ret < 0) { IWL_DEBUG_EEPROM(mvm->trans->dev, "Cannot read NVM from section %d offset %d, length %d\n", section, offset, length); return ret; } offset += ret; } IWL_DEBUG_EEPROM(mvm->trans->dev, "NVM section %d read completed\n", section); return offset; } static struct iwl_nvm_data * iwl_parse_nvm_sections(struct iwl_mvm *mvm) { struct iwl_nvm_section *sections = mvm->nvm_sections; const __le16 *hw, *sw, *calib, *regulatory, *mac_override, *phy_sku; bool lar_enabled; u32 mac_addr0, mac_addr1; /* Checking for required sections */ if (mvm->trans->cfg->device_family != IWL_DEVICE_FAMILY_8000) { if (!mvm->nvm_sections[NVM_SECTION_TYPE_SW].data || !mvm->nvm_sections[mvm->cfg->nvm_hw_section_num].data) { IWL_ERR(mvm, "Can't parse empty OTP/NVM sections\n"); return NULL; } } else { /* SW and REGULATORY sections are mandatory */ if (!mvm->nvm_sections[NVM_SECTION_TYPE_SW].data || !mvm->nvm_sections[NVM_SECTION_TYPE_REGULATORY].data) { IWL_ERR(mvm, "Can't parse empty family 8000 OTP/NVM sections\n"); return NULL; } /* MAC_OVERRIDE or at least HW section must exist */ if (!mvm->nvm_sections[mvm->cfg->nvm_hw_section_num].data && !mvm->nvm_sections[NVM_SECTION_TYPE_MAC_OVERRIDE].data) { IWL_ERR(mvm, "Can't parse mac_address, empty sections\n"); return NULL; } /* PHY_SKU section is mandatory in B0 */ if (!mvm->nvm_sections[NVM_SECTION_TYPE_PHY_SKU].data) { IWL_ERR(mvm, "Can't parse phy_sku in B0, empty sections\n"); return NULL; } } if (WARN_ON(!mvm->cfg)) return NULL; /* read the mac address from WFMP registers */ mac_addr0 = iwl_trans_read_prph(mvm->trans, WFMP_MAC_ADDR_0); mac_addr1 = iwl_trans_read_prph(mvm->trans, WFMP_MAC_ADDR_1); hw = (const __le16 *)sections[mvm->cfg->nvm_hw_section_num].data; sw = (const __le16 *)sections[NVM_SECTION_TYPE_SW].data; calib = (const __le16 *)sections[NVM_SECTION_TYPE_CALIBRATION].data; regulatory = (const __le16 *)sections[NVM_SECTION_TYPE_REGULATORY].data; mac_override = (const __le16 *)sections[NVM_SECTION_TYPE_MAC_OVERRIDE].data; phy_sku = (const __le16 *)sections[NVM_SECTION_TYPE_PHY_SKU].data; lar_enabled = !iwlwifi_mod_params.lar_disable && fw_has_capa(&mvm->fw->ucode_capa, IWL_UCODE_TLV_CAPA_LAR_SUPPORT); return iwl_parse_nvm_data(mvm->trans->dev, mvm->cfg, hw, sw, calib, regulatory, mac_override, phy_sku, mvm->fw->valid_tx_ant, mvm->fw->valid_rx_ant, lar_enabled, mac_addr0, mac_addr1); } #define MAX_NVM_FILE_LEN 16384 /* * Reads external NVM from a file into mvm->nvm_sections * * HOW TO CREATE THE NVM FILE FORMAT: * ------------------------------ * 1. create hex file, format: * 3800 -> header * 0000 -> header * 5a40 -> data * * rev - 6 bit (word1) * len - 10 bit (word1) * id - 4 bit (word2) * rsv - 12 bit (word2) * * 2. flip 8bits with 8 bits per line to get the right NVM file format * * 3. create binary file from the hex file * * 4. save as "iNVM_xxx.bin" under /lib/firmware */ static int iwl_mvm_read_external_nvm(struct iwl_mvm *mvm) { int ret, section_size; u16 section_id; const struct firmware *fw_entry; const struct { __le16 word1; __le16 word2; u8 data[]; } *file_sec; const u8 *eof, *temp; int max_section_size; const __le32 *dword_buff; #define NVM_WORD1_LEN(x) (8 * (x & 0x03FF)) #define NVM_WORD2_ID(x) (x >> 12) #define NVM_WORD2_LEN_FAMILY_8000(x) (2 * ((x & 0xFF) << 8 | x >> 8)) #define NVM_WORD1_ID_FAMILY_8000(x) (x >> 4) #define NVM_HEADER_0 (0x2A504C54) #define NVM_HEADER_1 (0x4E564D2A) #define NVM_HEADER_SIZE (4 * sizeof(u32)) IWL_DEBUG_EEPROM(mvm->trans->dev, "Read from external NVM\n"); /* Maximal size depends on HW family and step */ if (mvm->trans->cfg->device_family != IWL_DEVICE_FAMILY_8000) max_section_size = IWL_MAX_NVM_SECTION_SIZE; else max_section_size = IWL_MAX_NVM_8000_SECTION_SIZE; /* * Obtain NVM image via request_firmware. Since we already used * request_firmware_nowait() for the firmware binary load and only * get here after that we assume the NVM request can be satisfied * synchronously. */ ret = request_firmware(&fw_entry, mvm->nvm_file_name, mvm->trans->dev); if (ret) { IWL_ERR(mvm, "ERROR: %s isn't available %d\n", mvm->nvm_file_name, ret); return ret; } IWL_INFO(mvm, "Loaded NVM file %s (%zu bytes)\n", mvm->nvm_file_name, fw_entry->size); if (fw_entry->size > MAX_NVM_FILE_LEN) { IWL_ERR(mvm, "NVM file too large\n"); ret = -EINVAL; goto out; } eof = fw_entry->data + fw_entry->size; dword_buff = (__le32 *)fw_entry->data; /* some NVM file will contain a header. * The header is identified by 2 dwords header as follow: * dword[0] = 0x2A504C54 * dword[1] = 0x4E564D2A * * This header must be skipped when providing the NVM data to the FW. */ if (fw_entry->size > NVM_HEADER_SIZE && dword_buff[0] == cpu_to_le32(NVM_HEADER_0) && dword_buff[1] == cpu_to_le32(NVM_HEADER_1)) { file_sec = (void *)(fw_entry->data + NVM_HEADER_SIZE); IWL_INFO(mvm, "NVM Version %08X\n", le32_to_cpu(dword_buff[2])); IWL_INFO(mvm, "NVM Manufacturing date %08X\n", le32_to_cpu(dword_buff[3])); /* nvm file validation, dword_buff[2] holds the file version */ if ((CSR_HW_REV_STEP(mvm->trans->hw_rev) == SILICON_C_STEP && le32_to_cpu(dword_buff[2]) < 0xE4A) || (CSR_HW_REV_STEP(mvm->trans->hw_rev) == SILICON_B_STEP && le32_to_cpu(dword_buff[2]) >= 0xE4A)) { ret = -EFAULT; goto out; } } else { file_sec = (void *)fw_entry->data; } while (true) { if (file_sec->data > eof) { IWL_ERR(mvm, "ERROR - NVM file too short for section header\n"); ret = -EINVAL; break; } /* check for EOF marker */ if (!file_sec->word1 && !file_sec->word2) { ret = 0; break; } if (mvm->trans->cfg->device_family != IWL_DEVICE_FAMILY_8000) { section_size = 2 * NVM_WORD1_LEN(le16_to_cpu(file_sec->word1)); section_id = NVM_WORD2_ID(le16_to_cpu(file_sec->word2)); } else { section_size = 2 * NVM_WORD2_LEN_FAMILY_8000( le16_to_cpu(file_sec->word2)); section_id = NVM_WORD1_ID_FAMILY_8000( le16_to_cpu(file_sec->word1)); } if (section_size > max_section_size) { IWL_ERR(mvm, "ERROR - section too large (%d)\n", section_size); ret = -EINVAL; break; } if (!section_size) { IWL_ERR(mvm, "ERROR - section empty\n"); ret = -EINVAL; break; } if (file_sec->data + section_size > eof) { IWL_ERR(mvm, "ERROR - NVM file too short for section (%d bytes)\n", section_size); ret = -EINVAL; break; } if (WARN(section_id >= NVM_MAX_NUM_SECTIONS, "Invalid NVM section ID %d\n", section_id)) { ret = -EINVAL; break; } temp = kmemdup(file_sec->data, section_size, GFP_KERNEL); if (!temp) { ret = -ENOMEM; break; } mvm->nvm_sections[section_id].data = temp; mvm->nvm_sections[section_id].length = section_size; /* advance to the next section */ file_sec = (void *)(file_sec->data + section_size); } out: release_firmware(fw_entry); return ret; } /* Loads the NVM data stored in mvm->nvm_sections into the NIC */ int iwl_mvm_load_nvm_to_nic(struct iwl_mvm *mvm) { int i, ret = 0; struct iwl_nvm_section *sections = mvm->nvm_sections; IWL_DEBUG_EEPROM(mvm->trans->dev, "'Write to NVM\n"); for (i = 0; i < ARRAY_SIZE(mvm->nvm_sections); i++) { if (!mvm->nvm_sections[i].data || !mvm->nvm_sections[i].length) continue; ret = iwl_nvm_write_section(mvm, i, sections[i].data, sections[i].length); if (ret < 0) { IWL_ERR(mvm, "iwl_mvm_send_cmd failed: %d\n", ret); break; } } return ret; } int iwl_nvm_init(struct iwl_mvm *mvm, bool read_nvm_from_nic) { int ret, section; u32 size_read = 0; u8 *nvm_buffer, *temp; const char *nvm_file_B = mvm->cfg->default_nvm_file_B_step; const char *nvm_file_C = mvm->cfg->default_nvm_file_C_step; if (WARN_ON_ONCE(mvm->cfg->nvm_hw_section_num >= NVM_MAX_NUM_SECTIONS)) return -EINVAL; /* load NVM values from nic */ if (read_nvm_from_nic) { /* Read From FW NVM */ IWL_DEBUG_EEPROM(mvm->trans->dev, "Read from NVM\n"); nvm_buffer = kmalloc(mvm->cfg->base_params->eeprom_size, GFP_KERNEL); if (!nvm_buffer) return -ENOMEM; for (section = 0; section < NVM_MAX_NUM_SECTIONS; section++) { /* we override the constness for initial read */ ret = iwl_nvm_read_section(mvm, section, nvm_buffer, size_read); if (ret < 0) continue; size_read += ret; temp = kmemdup(nvm_buffer, ret, GFP_KERNEL); if (!temp) { ret = -ENOMEM; break; } mvm->nvm_sections[section].data = temp; mvm->nvm_sections[section].length = ret; #ifdef CONFIG_IWLWIFI_DEBUGFS switch (section) { case NVM_SECTION_TYPE_SW: mvm->nvm_sw_blob.data = temp; mvm->nvm_sw_blob.size = ret; break; case NVM_SECTION_TYPE_CALIBRATION: mvm->nvm_calib_blob.data = temp; mvm->nvm_calib_blob.size = ret; break; case NVM_SECTION_TYPE_PRODUCTION: mvm->nvm_prod_blob.data = temp; mvm->nvm_prod_blob.size = ret; break; default: if (section == mvm->cfg->nvm_hw_section_num) { mvm->nvm_hw_blob.data = temp; mvm->nvm_hw_blob.size = ret; break; } } #endif } if (!size_read) IWL_ERR(mvm, "OTP is blank\n"); kfree(nvm_buffer); } /* Only if PNVM selected in the mod param - load external NVM */ if (mvm->nvm_file_name) { /* read External NVM file from the mod param */ ret = iwl_mvm_read_external_nvm(mvm); if (ret) { /* choose the nvm_file name according to the * HW step */ if (CSR_HW_REV_STEP(mvm->trans->hw_rev) == SILICON_B_STEP) mvm->nvm_file_name = nvm_file_B; else mvm->nvm_file_name = nvm_file_C; if (ret == -EFAULT && mvm->nvm_file_name) { /* in case nvm file was failed try again */ ret = iwl_mvm_read_external_nvm(mvm); if (ret) return ret; } else { return ret; } } } /* parse the relevant nvm sections */ mvm->nvm_data = iwl_parse_nvm_sections(mvm); if (!mvm->nvm_data) return -ENODATA; IWL_DEBUG_EEPROM(mvm->trans->dev, "nvm version = %x\n", mvm->nvm_data->nvm_version); return 0; } struct iwl_mcc_update_resp * iwl_mvm_update_mcc(struct iwl_mvm *mvm, const char *alpha2, enum iwl_mcc_source src_id) { struct iwl_mcc_update_cmd mcc_update_cmd = { .mcc = cpu_to_le16(alpha2[0] << 8 | alpha2[1]), .source_id = (u8)src_id, }; struct iwl_mcc_update_resp *mcc_resp, *resp_cp = NULL; struct iwl_rx_packet *pkt; struct iwl_host_cmd cmd = { .id = MCC_UPDATE_CMD, .flags = CMD_WANT_SKB, .data = { &mcc_update_cmd }, }; int ret; u32 status; int resp_len, n_channels; u16 mcc; if (WARN_ON_ONCE(!iwl_mvm_is_lar_supported(mvm))) return ERR_PTR(-EOPNOTSUPP); cmd.len[0] = sizeof(struct iwl_mcc_update_cmd); IWL_DEBUG_LAR(mvm, "send MCC update to FW with '%c%c' src = %d\n", alpha2[0], alpha2[1], src_id); ret = iwl_mvm_send_cmd(mvm, &cmd); if (ret) return ERR_PTR(ret); pkt = cmd.resp_pkt; /* Extract MCC response */ mcc_resp = (void *)pkt->data; status = le32_to_cpu(mcc_resp->status); mcc = le16_to_cpu(mcc_resp->mcc); /* W/A for a FW/NVM issue - returns 0x00 for the world domain */ if (mcc == 0) { mcc = 0x3030; /* "00" - world */ mcc_resp->mcc = cpu_to_le16(mcc); } n_channels = __le32_to_cpu(mcc_resp->n_channels); IWL_DEBUG_LAR(mvm, "MCC response status: 0x%x. new MCC: 0x%x ('%c%c') change: %d n_chans: %d\n", status, mcc, mcc >> 8, mcc & 0xff, !!(status == MCC_RESP_NEW_CHAN_PROFILE), n_channels); resp_len = sizeof(*mcc_resp) + n_channels * sizeof(__le32); resp_cp = kmemdup(mcc_resp, resp_len, GFP_KERNEL); if (!resp_cp) { ret = -ENOMEM; goto exit; } ret = 0; exit: iwl_free_resp(&cmd); if (ret) return ERR_PTR(ret); return resp_cp; } #ifdef CONFIG_ACPI #define WRD_METHOD "WRDD" #define WRDD_WIFI (0x07) #define WRDD_WIGIG (0x10) static u32 iwl_mvm_wrdd_get_mcc(struct iwl_mvm *mvm, union acpi_object *wrdd) { union acpi_object *mcc_pkg, *domain_type, *mcc_value; u32 i; if (wrdd->type != ACPI_TYPE_PACKAGE || wrdd->package.count < 2 || wrdd->package.elements[0].type != ACPI_TYPE_INTEGER || wrdd->package.elements[0].integer.value != 0) { IWL_DEBUG_LAR(mvm, "Unsupported wrdd structure\n"); return 0; } for (i = 1 ; i < wrdd->package.count ; ++i) { mcc_pkg = &wrdd->package.elements[i]; if (mcc_pkg->type != ACPI_TYPE_PACKAGE || mcc_pkg->package.count < 2 || mcc_pkg->package.elements[0].type != ACPI_TYPE_INTEGER || mcc_pkg->package.elements[1].type != ACPI_TYPE_INTEGER) { mcc_pkg = NULL; continue; } domain_type = &mcc_pkg->package.elements[0]; if (domain_type->integer.value == WRDD_WIFI) break; mcc_pkg = NULL; } if (mcc_pkg) { mcc_value = &mcc_pkg->package.elements[1]; return mcc_value->integer.value; } return 0; } static int iwl_mvm_get_bios_mcc(struct iwl_mvm *mvm, char *mcc) { acpi_handle root_handle; acpi_handle handle; struct acpi_buffer wrdd = {ACPI_ALLOCATE_BUFFER, NULL}; acpi_status status; u32 mcc_val; struct pci_dev *pdev = to_pci_dev(mvm->dev); root_handle = ACPI_HANDLE(&pdev->dev); if (!root_handle) { IWL_DEBUG_LAR(mvm, "Could not retrieve root port ACPI handle\n"); return -ENOENT; } /* Get the method's handle */ status = acpi_get_handle(root_handle, (acpi_string)WRD_METHOD, &handle); if (ACPI_FAILURE(status)) { IWL_DEBUG_LAR(mvm, "WRD method not found\n"); return -ENOENT; } /* Call WRDD with no arguments */ status = acpi_evaluate_object(handle, NULL, NULL, &wrdd); if (ACPI_FAILURE(status)) { IWL_DEBUG_LAR(mvm, "WRDC invocation failed (0x%x)\n", status); return -ENOENT; } mcc_val = iwl_mvm_wrdd_get_mcc(mvm, wrdd.pointer); kfree(wrdd.pointer); if (!mcc_val) return -ENOENT; mcc[0] = (mcc_val >> 8) & 0xff; mcc[1] = mcc_val & 0xff; mcc[2] = '\0'; return 0; } #else /* CONFIG_ACPI */ static int iwl_mvm_get_bios_mcc(struct iwl_mvm *mvm, char *mcc) { return -ENOENT; } #endif int iwl_mvm_init_mcc(struct iwl_mvm *mvm) { bool tlv_lar; bool nvm_lar; int retval; struct ieee80211_regdomain *regd; char mcc[3]; if (mvm->cfg->device_family == IWL_DEVICE_FAMILY_8000) { tlv_lar = fw_has_capa(&mvm->fw->ucode_capa, IWL_UCODE_TLV_CAPA_LAR_SUPPORT); nvm_lar = mvm->nvm_data->lar_enabled; if (tlv_lar != nvm_lar) IWL_INFO(mvm, "Conflict between TLV & NVM regarding enabling LAR (TLV = %s NVM =%s)\n", tlv_lar ? "enabled" : "disabled", nvm_lar ? "enabled" : "disabled"); } if (!iwl_mvm_is_lar_supported(mvm)) return 0; /* * try to replay the last set MCC to FW. If it doesn't exist, * queue an update to cfg80211 to retrieve the default alpha2 from FW. */ retval = iwl_mvm_init_fw_regd(mvm); if (retval != -ENOENT) return retval; /* * Driver regulatory hint for initial update, this also informs the * firmware we support wifi location updates. * Disallow scans that might crash the FW while the LAR regdomain * is not set. */ mvm->lar_regdom_set = false; regd = iwl_mvm_get_current_regdomain(mvm, NULL); if (IS_ERR_OR_NULL(regd)) return -EIO; if (iwl_mvm_is_wifi_mcc_supported(mvm) && !iwl_mvm_get_bios_mcc(mvm, mcc)) { kfree(regd); regd = iwl_mvm_get_regdomain(mvm->hw->wiphy, mcc, MCC_SOURCE_BIOS, NULL); if (IS_ERR_OR_NULL(regd)) return -EIO; } retval = regulatory_set_wiphy_regd_sync_rtnl(mvm->hw->wiphy, regd); kfree(regd); return retval; } void iwl_mvm_rx_chub_update_mcc(struct iwl_mvm *mvm, struct iwl_rx_cmd_buffer *rxb) { struct iwl_rx_packet *pkt = rxb_addr(rxb); struct iwl_mcc_chub_notif *notif = (void *)pkt->data; enum iwl_mcc_source src; char mcc[3]; struct ieee80211_regdomain *regd; lockdep_assert_held(&mvm->mutex); if (WARN_ON_ONCE(!iwl_mvm_is_lar_supported(mvm))) return; mcc[0] = notif->mcc >> 8; mcc[1] = notif->mcc & 0xff; mcc[2] = '\0'; src = notif->source_id; IWL_DEBUG_LAR(mvm, "RX: received chub update mcc cmd (mcc '%s' src %d)\n", mcc, src); regd = iwl_mvm_get_regdomain(mvm->hw->wiphy, mcc, src, NULL); if (IS_ERR_OR_NULL(regd)) return; regulatory_set_wiphy_regd(mvm->hw->wiphy, regd); kfree(regd); }
gpl-2.0
JonnyXDA/android_kernel_ulefone_metal
sound/pci/emu10k1/emu10k1.c
208
9025
/* * The driver for the EMU10K1 (SB Live!) based soundcards * Copyright (c) by Jaroslav Kysela <perex@perex.cz> * * Copyright (c) by James Courtier-Dutton <James@superbug.demon.co.uk> * Added support for Audigy 2 Value. * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * */ #include <linux/init.h> #include <linux/pci.h> #include <linux/time.h> #include <linux/module.h> #include <sound/core.h> #include <sound/emu10k1.h> #include <sound/initval.h> MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>"); MODULE_DESCRIPTION("EMU10K1"); MODULE_LICENSE("GPL"); MODULE_SUPPORTED_DEVICE("{{Creative Labs,SB Live!/PCI512/E-mu APS}," "{Creative Labs,SB Audigy}}"); #if defined(CONFIG_SND_SEQUENCER) || (defined(MODULE) && defined(CONFIG_SND_SEQUENCER_MODULE)) #define ENABLE_SYNTH #include <sound/emu10k1_synth.h> #endif static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */ static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */ static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP; /* Enable this card */ static int extin[SNDRV_CARDS]; static int extout[SNDRV_CARDS]; static int seq_ports[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 4}; static int max_synth_voices[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 64}; static int max_buffer_size[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 128}; static bool enable_ir[SNDRV_CARDS]; static uint subsystem[SNDRV_CARDS]; /* Force card subsystem model */ static uint delay_pcm_irq[SNDRV_CARDS] = {[0 ... (SNDRV_CARDS - 1)] = 2}; module_param_array(index, int, NULL, 0444); MODULE_PARM_DESC(index, "Index value for the EMU10K1 soundcard."); module_param_array(id, charp, NULL, 0444); MODULE_PARM_DESC(id, "ID string for the EMU10K1 soundcard."); module_param_array(enable, bool, NULL, 0444); MODULE_PARM_DESC(enable, "Enable the EMU10K1 soundcard."); module_param_array(extin, int, NULL, 0444); MODULE_PARM_DESC(extin, "Available external inputs for FX8010. Zero=default."); module_param_array(extout, int, NULL, 0444); MODULE_PARM_DESC(extout, "Available external outputs for FX8010. Zero=default."); module_param_array(seq_ports, int, NULL, 0444); MODULE_PARM_DESC(seq_ports, "Allocated sequencer ports for internal synthesizer."); module_param_array(max_synth_voices, int, NULL, 0444); MODULE_PARM_DESC(max_synth_voices, "Maximum number of voices for WaveTable."); module_param_array(max_buffer_size, int, NULL, 0444); MODULE_PARM_DESC(max_buffer_size, "Maximum sample buffer size in MB."); module_param_array(enable_ir, bool, NULL, 0444); MODULE_PARM_DESC(enable_ir, "Enable IR."); module_param_array(subsystem, uint, NULL, 0444); MODULE_PARM_DESC(subsystem, "Force card subsystem model."); module_param_array(delay_pcm_irq, uint, NULL, 0444); MODULE_PARM_DESC(delay_pcm_irq, "Delay PCM interrupt by specified number of samples (default 0)."); /* * Class 0401: 1102:0008 (rev 00) Subsystem: 1102:1001 -> Audigy2 Value Model:SB0400 */ static const struct pci_device_id snd_emu10k1_ids[] = { { PCI_VDEVICE(CREATIVE, 0x0002), 0 }, /* EMU10K1 */ { PCI_VDEVICE(CREATIVE, 0x0004), 1 }, /* Audigy */ { PCI_VDEVICE(CREATIVE, 0x0008), 1 }, /* Audigy 2 Value SB0400 */ { 0, } }; /* * Audigy 2 Value notes: * A_IOCFG Input (GPIO) * 0x400 = Front analog jack plugged in. (Green socket) * 0x1000 = Read analog jack plugged in. (Black socket) * 0x2000 = Center/LFE analog jack plugged in. (Orange socket) * A_IOCFG Output (GPIO) * 0x60 = Sound out of front Left. * Win sets it to 0xXX61 */ MODULE_DEVICE_TABLE(pci, snd_emu10k1_ids); static int snd_card_emu10k1_probe(struct pci_dev *pci, const struct pci_device_id *pci_id) { static int dev; struct snd_card *card; struct snd_emu10k1 *emu; #ifdef ENABLE_SYNTH struct snd_seq_device *wave = NULL; #endif int err; if (dev >= SNDRV_CARDS) return -ENODEV; if (!enable[dev]) { dev++; return -ENOENT; } err = snd_card_new(&pci->dev, index[dev], id[dev], THIS_MODULE, 0, &card); if (err < 0) return err; if (max_buffer_size[dev] < 32) max_buffer_size[dev] = 32; else if (max_buffer_size[dev] > 1024) max_buffer_size[dev] = 1024; if ((err = snd_emu10k1_create(card, pci, extin[dev], extout[dev], (long)max_buffer_size[dev] * 1024 * 1024, enable_ir[dev], subsystem[dev], &emu)) < 0) goto error; card->private_data = emu; emu->delay_pcm_irq = delay_pcm_irq[dev] & 0x1f; if ((err = snd_emu10k1_pcm(emu, 0, NULL)) < 0) goto error; if ((err = snd_emu10k1_pcm_mic(emu, 1, NULL)) < 0) goto error; if ((err = snd_emu10k1_pcm_efx(emu, 2, NULL)) < 0) goto error; /* This stores the periods table. */ if (emu->card_capabilities->ca0151_chip) { /* P16V */ if ((err = snd_dma_alloc_pages(SNDRV_DMA_TYPE_DEV, snd_dma_pci_data(pci), 1024, &emu->p16v_buffer)) < 0) goto error; } if ((err = snd_emu10k1_mixer(emu, 0, 3)) < 0) goto error; if ((err = snd_emu10k1_timer(emu, 0)) < 0) goto error; if ((err = snd_emu10k1_pcm_multi(emu, 3, NULL)) < 0) goto error; if (emu->card_capabilities->ca0151_chip) { /* P16V */ if ((err = snd_p16v_pcm(emu, 4, NULL)) < 0) goto error; } if (emu->audigy) { if ((err = snd_emu10k1_audigy_midi(emu)) < 0) goto error; } else { if ((err = snd_emu10k1_midi(emu)) < 0) goto error; } if ((err = snd_emu10k1_fx8010_new(emu, 0, NULL)) < 0) goto error; #ifdef ENABLE_SYNTH if (snd_seq_device_new(card, 1, SNDRV_SEQ_DEV_ID_EMU10K1_SYNTH, sizeof(struct snd_emu10k1_synth_arg), &wave) < 0 || wave == NULL) { dev_warn(emu->card->dev, "can't initialize Emu10k1 wavetable synth\n"); } else { struct snd_emu10k1_synth_arg *arg; arg = SNDRV_SEQ_DEVICE_ARGPTR(wave); strcpy(wave->name, "Emu-10k1 Synth"); arg->hwptr = emu; arg->index = 1; arg->seq_ports = seq_ports[dev]; arg->max_voices = max_synth_voices[dev]; } #endif strlcpy(card->driver, emu->card_capabilities->driver, sizeof(card->driver)); strlcpy(card->shortname, emu->card_capabilities->name, sizeof(card->shortname)); snprintf(card->longname, sizeof(card->longname), "%s (rev.%d, serial:0x%x) at 0x%lx, irq %i", card->shortname, emu->revision, emu->serial, emu->port, emu->irq); if ((err = snd_card_register(card)) < 0) goto error; pci_set_drvdata(pci, card); dev++; return 0; error: snd_card_free(card); return err; } static void snd_card_emu10k1_remove(struct pci_dev *pci) { snd_card_free(pci_get_drvdata(pci)); } #ifdef CONFIG_PM_SLEEP static int snd_emu10k1_suspend(struct device *dev) { struct pci_dev *pci = to_pci_dev(dev); struct snd_card *card = dev_get_drvdata(dev); struct snd_emu10k1 *emu = card->private_data; snd_power_change_state(card, SNDRV_CTL_POWER_D3hot); emu->suspend = 1; snd_pcm_suspend_all(emu->pcm); snd_pcm_suspend_all(emu->pcm_mic); snd_pcm_suspend_all(emu->pcm_efx); snd_pcm_suspend_all(emu->pcm_multi); snd_pcm_suspend_all(emu->pcm_p16v); snd_ac97_suspend(emu->ac97); snd_emu10k1_efx_suspend(emu); snd_emu10k1_suspend_regs(emu); if (emu->card_capabilities->ca0151_chip) snd_p16v_suspend(emu); snd_emu10k1_done(emu); pci_disable_device(pci); pci_save_state(pci); pci_set_power_state(pci, PCI_D3hot); return 0; } static int snd_emu10k1_resume(struct device *dev) { struct pci_dev *pci = to_pci_dev(dev); struct snd_card *card = dev_get_drvdata(dev); struct snd_emu10k1 *emu = card->private_data; pci_set_power_state(pci, PCI_D0); pci_restore_state(pci); if (pci_enable_device(pci) < 0) { dev_err(dev, "pci_enable_device failed, disabling device\n"); snd_card_disconnect(card); return -EIO; } pci_set_master(pci); snd_emu10k1_resume_init(emu); snd_emu10k1_efx_resume(emu); snd_ac97_resume(emu->ac97); snd_emu10k1_resume_regs(emu); if (emu->card_capabilities->ca0151_chip) snd_p16v_resume(emu); emu->suspend = 0; snd_power_change_state(card, SNDRV_CTL_POWER_D0); return 0; } static SIMPLE_DEV_PM_OPS(snd_emu10k1_pm, snd_emu10k1_suspend, snd_emu10k1_resume); #define SND_EMU10K1_PM_OPS &snd_emu10k1_pm #else #define SND_EMU10K1_PM_OPS NULL #endif /* CONFIG_PM_SLEEP */ static struct pci_driver emu10k1_driver = { .name = KBUILD_MODNAME, .id_table = snd_emu10k1_ids, .probe = snd_card_emu10k1_probe, .remove = snd_card_emu10k1_remove, .driver = { .pm = SND_EMU10K1_PM_OPS, }, }; module_pci_driver(emu10k1_driver);
gpl-2.0
noonien-d/linux-Digilent-Dev
sound/soc/dwc/designware_i2s.c
464
11283
/* * ALSA SoC Synopsys I2S Audio Layer * * sound/soc/dwc/designware_i2s.c * * Copyright (C) 2010 ST Microelectronics * Rajeev Kumar <rajeev-dlh.kumar@st.com> * * This file is licensed under the terms of the GNU General Public * License version 2. This program is licensed "as is" without any * warranty of any kind, whether express or implied. */ #include <linux/clk.h> #include <linux/device.h> #include <linux/init.h> #include <linux/io.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/slab.h> #include <sound/designware_i2s.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/soc.h> /* common register for all channel */ #define IER 0x000 #define IRER 0x004 #define ITER 0x008 #define CER 0x00C #define CCR 0x010 #define RXFFR 0x014 #define TXFFR 0x018 /* I2STxRxRegisters for all channels */ #define LRBR_LTHR(x) (0x40 * x + 0x020) #define RRBR_RTHR(x) (0x40 * x + 0x024) #define RER(x) (0x40 * x + 0x028) #define TER(x) (0x40 * x + 0x02C) #define RCR(x) (0x40 * x + 0x030) #define TCR(x) (0x40 * x + 0x034) #define ISR(x) (0x40 * x + 0x038) #define IMR(x) (0x40 * x + 0x03C) #define ROR(x) (0x40 * x + 0x040) #define TOR(x) (0x40 * x + 0x044) #define RFCR(x) (0x40 * x + 0x048) #define TFCR(x) (0x40 * x + 0x04C) #define RFF(x) (0x40 * x + 0x050) #define TFF(x) (0x40 * x + 0x054) /* I2SCOMPRegisters */ #define I2S_COMP_PARAM_2 0x01F0 #define I2S_COMP_PARAM_1 0x01F4 #define I2S_COMP_VERSION 0x01F8 #define I2S_COMP_TYPE 0x01FC #define MAX_CHANNEL_NUM 8 #define MIN_CHANNEL_NUM 2 struct dw_i2s_dev { void __iomem *i2s_base; struct clk *clk; int active; unsigned int capability; struct device *dev; /* data related to DMA transfers b/w i2s and DMAC */ struct i2s_dma_data play_dma_data; struct i2s_dma_data capture_dma_data; struct i2s_clk_config_data config; int (*i2s_clk_cfg)(struct i2s_clk_config_data *config); }; static inline void i2s_write_reg(void __iomem *io_base, int reg, u32 val) { writel(val, io_base + reg); } static inline u32 i2s_read_reg(void __iomem *io_base, int reg) { return readl(io_base + reg); } static inline void i2s_disable_channels(struct dw_i2s_dev *dev, u32 stream) { u32 i = 0; if (stream == SNDRV_PCM_STREAM_PLAYBACK) { for (i = 0; i < 4; i++) i2s_write_reg(dev->i2s_base, TER(i), 0); } else { for (i = 0; i < 4; i++) i2s_write_reg(dev->i2s_base, RER(i), 0); } } static inline void i2s_clear_irqs(struct dw_i2s_dev *dev, u32 stream) { u32 i = 0; if (stream == SNDRV_PCM_STREAM_PLAYBACK) { for (i = 0; i < 4; i++) i2s_write_reg(dev->i2s_base, TOR(i), 0); } else { for (i = 0; i < 4; i++) i2s_write_reg(dev->i2s_base, ROR(i), 0); } } static void i2s_start(struct dw_i2s_dev *dev, struct snd_pcm_substream *substream) { i2s_write_reg(dev->i2s_base, IER, 1); if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) i2s_write_reg(dev->i2s_base, ITER, 1); else i2s_write_reg(dev->i2s_base, IRER, 1); i2s_write_reg(dev->i2s_base, CER, 1); } static void i2s_stop(struct dw_i2s_dev *dev, struct snd_pcm_substream *substream) { u32 i = 0, irq; i2s_clear_irqs(dev, substream->stream); if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { i2s_write_reg(dev->i2s_base, ITER, 0); for (i = 0; i < 4; i++) { irq = i2s_read_reg(dev->i2s_base, IMR(i)); i2s_write_reg(dev->i2s_base, IMR(i), irq | 0x30); } } else { i2s_write_reg(dev->i2s_base, IRER, 0); for (i = 0; i < 4; i++) { irq = i2s_read_reg(dev->i2s_base, IMR(i)); i2s_write_reg(dev->i2s_base, IMR(i), irq | 0x03); } } if (!dev->active) { i2s_write_reg(dev->i2s_base, CER, 0); i2s_write_reg(dev->i2s_base, IER, 0); } } static int dw_i2s_startup(struct snd_pcm_substream *substream, struct snd_soc_dai *cpu_dai) { struct dw_i2s_dev *dev = snd_soc_dai_get_drvdata(cpu_dai); struct i2s_dma_data *dma_data = NULL; if (!(dev->capability & DWC_I2S_RECORD) && (substream->stream == SNDRV_PCM_STREAM_CAPTURE)) return -EINVAL; if (!(dev->capability & DWC_I2S_PLAY) && (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)) return -EINVAL; if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) dma_data = &dev->play_dma_data; else if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) dma_data = &dev->capture_dma_data; snd_soc_dai_set_dma_data(cpu_dai, substream, (void *)dma_data); return 0; } static int dw_i2s_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { struct dw_i2s_dev *dev = snd_soc_dai_get_drvdata(dai); struct i2s_clk_config_data *config = &dev->config; u32 ccr, xfer_resolution, ch_reg, irq; int ret; switch (params_format(params)) { case SNDRV_PCM_FORMAT_S16_LE: config->data_width = 16; ccr = 0x00; xfer_resolution = 0x02; break; case SNDRV_PCM_FORMAT_S24_LE: config->data_width = 24; ccr = 0x08; xfer_resolution = 0x04; break; case SNDRV_PCM_FORMAT_S32_LE: config->data_width = 32; ccr = 0x10; xfer_resolution = 0x05; break; default: dev_err(dev->dev, "designware-i2s: unsuppted PCM fmt"); return -EINVAL; } config->chan_nr = params_channels(params); switch (config->chan_nr) { case EIGHT_CHANNEL_SUPPORT: ch_reg = 3; break; case SIX_CHANNEL_SUPPORT: ch_reg = 2; break; case FOUR_CHANNEL_SUPPORT: ch_reg = 1; break; case TWO_CHANNEL_SUPPORT: ch_reg = 0; break; default: dev_err(dev->dev, "channel not supported\n"); return -EINVAL; } i2s_disable_channels(dev, substream->stream); if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { i2s_write_reg(dev->i2s_base, TCR(ch_reg), xfer_resolution); i2s_write_reg(dev->i2s_base, TFCR(ch_reg), 0x02); irq = i2s_read_reg(dev->i2s_base, IMR(ch_reg)); i2s_write_reg(dev->i2s_base, IMR(ch_reg), irq & ~0x30); i2s_write_reg(dev->i2s_base, TER(ch_reg), 1); } else { i2s_write_reg(dev->i2s_base, RCR(ch_reg), xfer_resolution); i2s_write_reg(dev->i2s_base, RFCR(ch_reg), 0x07); irq = i2s_read_reg(dev->i2s_base, IMR(ch_reg)); i2s_write_reg(dev->i2s_base, IMR(ch_reg), irq & ~0x03); i2s_write_reg(dev->i2s_base, RER(ch_reg), 1); } i2s_write_reg(dev->i2s_base, CCR, ccr); config->sample_rate = params_rate(params); if (!dev->i2s_clk_cfg) return -EINVAL; ret = dev->i2s_clk_cfg(config); if (ret < 0) { dev_err(dev->dev, "runtime audio clk config fail\n"); return ret; } return 0; } static void dw_i2s_shutdown(struct snd_pcm_substream *substream, struct snd_soc_dai *dai) { snd_soc_dai_set_dma_data(dai, substream, NULL); } static int dw_i2s_trigger(struct snd_pcm_substream *substream, int cmd, struct snd_soc_dai *dai) { struct dw_i2s_dev *dev = snd_soc_dai_get_drvdata(dai); int ret = 0; switch (cmd) { case SNDRV_PCM_TRIGGER_START: case SNDRV_PCM_TRIGGER_RESUME: case SNDRV_PCM_TRIGGER_PAUSE_RELEASE: dev->active++; i2s_start(dev, substream); break; case SNDRV_PCM_TRIGGER_STOP: case SNDRV_PCM_TRIGGER_SUSPEND: case SNDRV_PCM_TRIGGER_PAUSE_PUSH: dev->active--; i2s_stop(dev, substream); break; default: ret = -EINVAL; break; } return ret; } static struct snd_soc_dai_ops dw_i2s_dai_ops = { .startup = dw_i2s_startup, .shutdown = dw_i2s_shutdown, .hw_params = dw_i2s_hw_params, .trigger = dw_i2s_trigger, }; static const struct snd_soc_component_driver dw_i2s_component = { .name = "dw-i2s", }; #ifdef CONFIG_PM static int dw_i2s_suspend(struct snd_soc_dai *dai) { struct dw_i2s_dev *dev = snd_soc_dai_get_drvdata(dai); clk_disable(dev->clk); return 0; } static int dw_i2s_resume(struct snd_soc_dai *dai) { struct dw_i2s_dev *dev = snd_soc_dai_get_drvdata(dai); clk_enable(dev->clk); return 0; } #else #define dw_i2s_suspend NULL #define dw_i2s_resume NULL #endif static int dw_i2s_probe(struct platform_device *pdev) { const struct i2s_platform_data *pdata = pdev->dev.platform_data; struct dw_i2s_dev *dev; struct resource *res; int ret; unsigned int cap; struct snd_soc_dai_driver *dw_i2s_dai; if (!pdata) { dev_err(&pdev->dev, "Invalid platform data\n"); return -EINVAL; } res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) { dev_err(&pdev->dev, "no i2s resource defined\n"); return -ENODEV; } if (!devm_request_mem_region(&pdev->dev, res->start, resource_size(res), pdev->name)) { dev_err(&pdev->dev, "i2s region already claimed\n"); return -EBUSY; } dev = devm_kzalloc(&pdev->dev, sizeof(*dev), GFP_KERNEL); if (!dev) { dev_warn(&pdev->dev, "kzalloc fail\n"); return -ENOMEM; } dev->i2s_base = devm_ioremap(&pdev->dev, res->start, resource_size(res)); if (!dev->i2s_base) { dev_err(&pdev->dev, "ioremap fail for i2s_region\n"); return -ENOMEM; } cap = pdata->cap; dev->capability = cap; dev->i2s_clk_cfg = pdata->i2s_clk_cfg; /* Set DMA slaves info */ dev->play_dma_data.data = pdata->play_dma_data; dev->capture_dma_data.data = pdata->capture_dma_data; dev->play_dma_data.addr = res->start + I2S_TXDMA; dev->capture_dma_data.addr = res->start + I2S_RXDMA; dev->play_dma_data.max_burst = 16; dev->capture_dma_data.max_burst = 16; dev->play_dma_data.addr_width = DMA_SLAVE_BUSWIDTH_2_BYTES; dev->capture_dma_data.addr_width = DMA_SLAVE_BUSWIDTH_2_BYTES; dev->play_dma_data.filter = pdata->filter; dev->capture_dma_data.filter = pdata->filter; dev->clk = clk_get(&pdev->dev, NULL); if (IS_ERR(dev->clk)) return PTR_ERR(dev->clk); ret = clk_enable(dev->clk); if (ret < 0) goto err_clk_put; dw_i2s_dai = devm_kzalloc(&pdev->dev, sizeof(*dw_i2s_dai), GFP_KERNEL); if (!dw_i2s_dai) { dev_err(&pdev->dev, "mem allocation failed for dai driver\n"); ret = -ENOMEM; goto err_clk_disable; } if (cap & DWC_I2S_PLAY) { dev_dbg(&pdev->dev, " designware: play supported\n"); dw_i2s_dai->playback.channels_min = MIN_CHANNEL_NUM; dw_i2s_dai->playback.channels_max = pdata->channel; dw_i2s_dai->playback.formats = pdata->snd_fmts; dw_i2s_dai->playback.rates = pdata->snd_rates; } if (cap & DWC_I2S_RECORD) { dev_dbg(&pdev->dev, "designware: record supported\n"); dw_i2s_dai->capture.channels_min = MIN_CHANNEL_NUM; dw_i2s_dai->capture.channels_max = pdata->channel; dw_i2s_dai->capture.formats = pdata->snd_fmts; dw_i2s_dai->capture.rates = pdata->snd_rates; } dw_i2s_dai->ops = &dw_i2s_dai_ops; dw_i2s_dai->suspend = dw_i2s_suspend; dw_i2s_dai->resume = dw_i2s_resume; dev->dev = &pdev->dev; dev_set_drvdata(&pdev->dev, dev); ret = snd_soc_register_component(&pdev->dev, &dw_i2s_component, dw_i2s_dai, 1); if (ret != 0) { dev_err(&pdev->dev, "not able to register dai\n"); goto err_clk_disable; } return 0; err_clk_disable: clk_disable(dev->clk); err_clk_put: clk_put(dev->clk); return ret; } static int dw_i2s_remove(struct platform_device *pdev) { struct dw_i2s_dev *dev = dev_get_drvdata(&pdev->dev); snd_soc_unregister_component(&pdev->dev); clk_put(dev->clk); return 0; } static struct platform_driver dw_i2s_driver = { .probe = dw_i2s_probe, .remove = dw_i2s_remove, .driver = { .name = "designware-i2s", .owner = THIS_MODULE, }, }; module_platform_driver(dw_i2s_driver); MODULE_AUTHOR("Rajeev Kumar <rajeev-dlh.kumar@st.com>"); MODULE_DESCRIPTION("DESIGNWARE I2S SoC Interface"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:designware_i2s");
gpl-2.0
psyke83/codeaurora-kernel_samsung_europa
drivers/scsi/bfa/bfa_rport.c
464
21136
/* * Copyright (c) 2005-2009 Brocade Communications Systems, Inc. * All rights reserved * www.brocade.com * * Linux driver for Brocade Fibre Channel Host Bus Adapter. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License (GPL) Version 2 as * published by the Free Software Foundation * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. */ #include <bfa.h> #include <bfa_svc.h> #include <cs/bfa_debug.h> #include <bfi/bfi_rport.h> #include "bfa_intr_priv.h" BFA_TRC_FILE(HAL, RPORT); BFA_MODULE(rport); #define bfa_rport_offline_cb(__rp) do { \ if ((__rp)->bfa->fcs) \ bfa_cb_rport_offline((__rp)->rport_drv); \ else { \ bfa_cb_queue((__rp)->bfa, &(__rp)->hcb_qe, \ __bfa_cb_rport_offline, (__rp)); \ } \ } while (0) #define bfa_rport_online_cb(__rp) do { \ if ((__rp)->bfa->fcs) \ bfa_cb_rport_online((__rp)->rport_drv); \ else { \ bfa_cb_queue((__rp)->bfa, &(__rp)->hcb_qe, \ __bfa_cb_rport_online, (__rp)); \ } \ } while (0) /* * forward declarations */ static struct bfa_rport_s *bfa_rport_alloc(struct bfa_rport_mod_s *rp_mod); static void bfa_rport_free(struct bfa_rport_s *rport); static bfa_boolean_t bfa_rport_send_fwcreate(struct bfa_rport_s *rp); static bfa_boolean_t bfa_rport_send_fwdelete(struct bfa_rport_s *rp); static bfa_boolean_t bfa_rport_send_fwspeed(struct bfa_rport_s *rp); static void __bfa_cb_rport_online(void *cbarg, bfa_boolean_t complete); static void __bfa_cb_rport_offline(void *cbarg, bfa_boolean_t complete); /** * bfa_rport_sm BFA rport state machine */ enum bfa_rport_event { BFA_RPORT_SM_CREATE = 1, /* rport create event */ BFA_RPORT_SM_DELETE = 2, /* deleting an existing rport */ BFA_RPORT_SM_ONLINE = 3, /* rport is online */ BFA_RPORT_SM_OFFLINE = 4, /* rport is offline */ BFA_RPORT_SM_FWRSP = 5, /* firmware response */ BFA_RPORT_SM_HWFAIL = 6, /* IOC h/w failure */ BFA_RPORT_SM_QOS_SCN = 7, /* QoS SCN from firmware */ BFA_RPORT_SM_SET_SPEED = 8, /* Set Rport Speed */ BFA_RPORT_SM_QRESUME = 9, /* space in requeue queue */ }; static void bfa_rport_sm_uninit(struct bfa_rport_s *rp, enum bfa_rport_event event); static void bfa_rport_sm_created(struct bfa_rport_s *rp, enum bfa_rport_event event); static void bfa_rport_sm_fwcreate(struct bfa_rport_s *rp, enum bfa_rport_event event); static void bfa_rport_sm_online(struct bfa_rport_s *rp, enum bfa_rport_event event); static void bfa_rport_sm_fwdelete(struct bfa_rport_s *rp, enum bfa_rport_event event); static void bfa_rport_sm_offline(struct bfa_rport_s *rp, enum bfa_rport_event event); static void bfa_rport_sm_deleting(struct bfa_rport_s *rp, enum bfa_rport_event event); static void bfa_rport_sm_offline_pending(struct bfa_rport_s *rp, enum bfa_rport_event event); static void bfa_rport_sm_delete_pending(struct bfa_rport_s *rp, enum bfa_rport_event event); static void bfa_rport_sm_iocdisable(struct bfa_rport_s *rp, enum bfa_rport_event event); static void bfa_rport_sm_fwcreate_qfull(struct bfa_rport_s *rp, enum bfa_rport_event event); static void bfa_rport_sm_fwdelete_qfull(struct bfa_rport_s *rp, enum bfa_rport_event event); static void bfa_rport_sm_deleting_qfull(struct bfa_rport_s *rp, enum bfa_rport_event event); /** * Beginning state, only online event expected. */ static void bfa_rport_sm_uninit(struct bfa_rport_s *rp, enum bfa_rport_event event) { bfa_trc(rp->bfa, rp->rport_tag); bfa_trc(rp->bfa, event); switch (event) { case BFA_RPORT_SM_CREATE: bfa_stats(rp, sm_un_cr); bfa_sm_set_state(rp, bfa_rport_sm_created); break; default: bfa_stats(rp, sm_un_unexp); bfa_assert(0); } } static void bfa_rport_sm_created(struct bfa_rport_s *rp, enum bfa_rport_event event) { bfa_trc(rp->bfa, rp->rport_tag); bfa_trc(rp->bfa, event); switch (event) { case BFA_RPORT_SM_ONLINE: bfa_stats(rp, sm_cr_on); if (bfa_rport_send_fwcreate(rp)) bfa_sm_set_state(rp, bfa_rport_sm_fwcreate); else bfa_sm_set_state(rp, bfa_rport_sm_fwcreate_qfull); break; case BFA_RPORT_SM_DELETE: bfa_stats(rp, sm_cr_del); bfa_sm_set_state(rp, bfa_rport_sm_uninit); bfa_rport_free(rp); break; case BFA_RPORT_SM_HWFAIL: bfa_stats(rp, sm_cr_hwf); bfa_sm_set_state(rp, bfa_rport_sm_iocdisable); break; default: bfa_stats(rp, sm_cr_unexp); bfa_assert(0); } } /** * Waiting for rport create response from firmware. */ static void bfa_rport_sm_fwcreate(struct bfa_rport_s *rp, enum bfa_rport_event event) { bfa_trc(rp->bfa, rp->rport_tag); bfa_trc(rp->bfa, event); switch (event) { case BFA_RPORT_SM_FWRSP: bfa_stats(rp, sm_fwc_rsp); bfa_sm_set_state(rp, bfa_rport_sm_online); bfa_rport_online_cb(rp); break; case BFA_RPORT_SM_DELETE: bfa_stats(rp, sm_fwc_del); bfa_sm_set_state(rp, bfa_rport_sm_delete_pending); break; case BFA_RPORT_SM_OFFLINE: bfa_stats(rp, sm_fwc_off); bfa_sm_set_state(rp, bfa_rport_sm_offline_pending); break; case BFA_RPORT_SM_HWFAIL: bfa_stats(rp, sm_fwc_hwf); bfa_sm_set_state(rp, bfa_rport_sm_iocdisable); break; default: bfa_stats(rp, sm_fwc_unexp); bfa_assert(0); } } /** * Request queue is full, awaiting queue resume to send create request. */ static void bfa_rport_sm_fwcreate_qfull(struct bfa_rport_s *rp, enum bfa_rport_event event) { bfa_trc(rp->bfa, rp->rport_tag); bfa_trc(rp->bfa, event); switch (event) { case BFA_RPORT_SM_QRESUME: bfa_sm_set_state(rp, bfa_rport_sm_fwcreate); bfa_rport_send_fwcreate(rp); break; case BFA_RPORT_SM_DELETE: bfa_stats(rp, sm_fwc_del); bfa_sm_set_state(rp, bfa_rport_sm_uninit); bfa_reqq_wcancel(&rp->reqq_wait); bfa_rport_free(rp); break; case BFA_RPORT_SM_OFFLINE: bfa_stats(rp, sm_fwc_off); bfa_sm_set_state(rp, bfa_rport_sm_offline); bfa_reqq_wcancel(&rp->reqq_wait); bfa_rport_offline_cb(rp); break; case BFA_RPORT_SM_HWFAIL: bfa_stats(rp, sm_fwc_hwf); bfa_sm_set_state(rp, bfa_rport_sm_iocdisable); bfa_reqq_wcancel(&rp->reqq_wait); break; default: bfa_stats(rp, sm_fwc_unexp); bfa_assert(0); } } /** * Online state - normal parking state. */ static void bfa_rport_sm_online(struct bfa_rport_s *rp, enum bfa_rport_event event) { struct bfi_rport_qos_scn_s *qos_scn; bfa_trc(rp->bfa, rp->rport_tag); bfa_trc(rp->bfa, event); switch (event) { case BFA_RPORT_SM_OFFLINE: bfa_stats(rp, sm_on_off); if (bfa_rport_send_fwdelete(rp)) bfa_sm_set_state(rp, bfa_rport_sm_fwdelete); else bfa_sm_set_state(rp, bfa_rport_sm_fwdelete_qfull); break; case BFA_RPORT_SM_DELETE: bfa_stats(rp, sm_on_del); if (bfa_rport_send_fwdelete(rp)) bfa_sm_set_state(rp, bfa_rport_sm_deleting); else bfa_sm_set_state(rp, bfa_rport_sm_deleting_qfull); break; case BFA_RPORT_SM_HWFAIL: bfa_stats(rp, sm_on_hwf); bfa_sm_set_state(rp, bfa_rport_sm_iocdisable); break; case BFA_RPORT_SM_SET_SPEED: bfa_rport_send_fwspeed(rp); break; case BFA_RPORT_SM_QOS_SCN: qos_scn = (struct bfi_rport_qos_scn_s *) rp->event_arg.fw_msg; rp->qos_attr = qos_scn->new_qos_attr; bfa_trc(rp->bfa, qos_scn->old_qos_attr.qos_flow_id); bfa_trc(rp->bfa, qos_scn->new_qos_attr.qos_flow_id); bfa_trc(rp->bfa, qos_scn->old_qos_attr.qos_priority); bfa_trc(rp->bfa, qos_scn->new_qos_attr.qos_priority); qos_scn->old_qos_attr.qos_flow_id = bfa_os_ntohl(qos_scn->old_qos_attr.qos_flow_id); qos_scn->new_qos_attr.qos_flow_id = bfa_os_ntohl(qos_scn->new_qos_attr.qos_flow_id); qos_scn->old_qos_attr.qos_priority = bfa_os_ntohl(qos_scn->old_qos_attr.qos_priority); qos_scn->new_qos_attr.qos_priority = bfa_os_ntohl(qos_scn->new_qos_attr.qos_priority); if (qos_scn->old_qos_attr.qos_flow_id != qos_scn->new_qos_attr.qos_flow_id) bfa_cb_rport_qos_scn_flowid(rp->rport_drv, qos_scn->old_qos_attr, qos_scn->new_qos_attr); if (qos_scn->old_qos_attr.qos_priority != qos_scn->new_qos_attr.qos_priority) bfa_cb_rport_qos_scn_prio(rp->rport_drv, qos_scn->old_qos_attr, qos_scn->new_qos_attr); break; default: bfa_stats(rp, sm_on_unexp); bfa_assert(0); } } /** * Firmware rport is being deleted - awaiting f/w response. */ static void bfa_rport_sm_fwdelete(struct bfa_rport_s *rp, enum bfa_rport_event event) { bfa_trc(rp->bfa, rp->rport_tag); bfa_trc(rp->bfa, event); switch (event) { case BFA_RPORT_SM_FWRSP: bfa_stats(rp, sm_fwd_rsp); bfa_sm_set_state(rp, bfa_rport_sm_offline); bfa_rport_offline_cb(rp); break; case BFA_RPORT_SM_DELETE: bfa_stats(rp, sm_fwd_del); bfa_sm_set_state(rp, bfa_rport_sm_deleting); break; case BFA_RPORT_SM_HWFAIL: bfa_stats(rp, sm_fwd_hwf); bfa_sm_set_state(rp, bfa_rport_sm_iocdisable); bfa_rport_offline_cb(rp); break; default: bfa_stats(rp, sm_fwd_unexp); bfa_assert(0); } } static void bfa_rport_sm_fwdelete_qfull(struct bfa_rport_s *rp, enum bfa_rport_event event) { bfa_trc(rp->bfa, rp->rport_tag); bfa_trc(rp->bfa, event); switch (event) { case BFA_RPORT_SM_QRESUME: bfa_sm_set_state(rp, bfa_rport_sm_fwdelete); bfa_rport_send_fwdelete(rp); break; case BFA_RPORT_SM_DELETE: bfa_stats(rp, sm_fwd_del); bfa_sm_set_state(rp, bfa_rport_sm_deleting_qfull); break; case BFA_RPORT_SM_HWFAIL: bfa_stats(rp, sm_fwd_hwf); bfa_sm_set_state(rp, bfa_rport_sm_iocdisable); bfa_reqq_wcancel(&rp->reqq_wait); bfa_rport_offline_cb(rp); break; default: bfa_stats(rp, sm_fwd_unexp); bfa_assert(0); } } /** * Offline state. */ static void bfa_rport_sm_offline(struct bfa_rport_s *rp, enum bfa_rport_event event) { bfa_trc(rp->bfa, rp->rport_tag); bfa_trc(rp->bfa, event); switch (event) { case BFA_RPORT_SM_DELETE: bfa_stats(rp, sm_off_del); bfa_sm_set_state(rp, bfa_rport_sm_uninit); bfa_rport_free(rp); break; case BFA_RPORT_SM_ONLINE: bfa_stats(rp, sm_off_on); if (bfa_rport_send_fwcreate(rp)) bfa_sm_set_state(rp, bfa_rport_sm_fwcreate); else bfa_sm_set_state(rp, bfa_rport_sm_fwcreate_qfull); break; case BFA_RPORT_SM_HWFAIL: bfa_stats(rp, sm_off_hwf); bfa_sm_set_state(rp, bfa_rport_sm_iocdisable); break; default: bfa_stats(rp, sm_off_unexp); bfa_assert(0); } } /** * Rport is deleted, waiting for firmware response to delete. */ static void bfa_rport_sm_deleting(struct bfa_rport_s *rp, enum bfa_rport_event event) { bfa_trc(rp->bfa, rp->rport_tag); bfa_trc(rp->bfa, event); switch (event) { case BFA_RPORT_SM_FWRSP: bfa_stats(rp, sm_del_fwrsp); bfa_sm_set_state(rp, bfa_rport_sm_uninit); bfa_rport_free(rp); break; case BFA_RPORT_SM_HWFAIL: bfa_stats(rp, sm_del_hwf); bfa_sm_set_state(rp, bfa_rport_sm_uninit); bfa_rport_free(rp); break; default: bfa_assert(0); } } static void bfa_rport_sm_deleting_qfull(struct bfa_rport_s *rp, enum bfa_rport_event event) { bfa_trc(rp->bfa, rp->rport_tag); bfa_trc(rp->bfa, event); switch (event) { case BFA_RPORT_SM_QRESUME: bfa_stats(rp, sm_del_fwrsp); bfa_sm_set_state(rp, bfa_rport_sm_deleting); bfa_rport_send_fwdelete(rp); break; case BFA_RPORT_SM_HWFAIL: bfa_stats(rp, sm_del_hwf); bfa_sm_set_state(rp, bfa_rport_sm_uninit); bfa_reqq_wcancel(&rp->reqq_wait); bfa_rport_free(rp); break; default: bfa_assert(0); } } /** * Waiting for rport create response from firmware. A delete is pending. */ static void bfa_rport_sm_delete_pending(struct bfa_rport_s *rp, enum bfa_rport_event event) { bfa_trc(rp->bfa, rp->rport_tag); bfa_trc(rp->bfa, event); switch (event) { case BFA_RPORT_SM_FWRSP: bfa_stats(rp, sm_delp_fwrsp); if (bfa_rport_send_fwdelete(rp)) bfa_sm_set_state(rp, bfa_rport_sm_deleting); else bfa_sm_set_state(rp, bfa_rport_sm_deleting_qfull); break; case BFA_RPORT_SM_HWFAIL: bfa_stats(rp, sm_delp_hwf); bfa_sm_set_state(rp, bfa_rport_sm_uninit); bfa_rport_free(rp); break; default: bfa_stats(rp, sm_delp_unexp); bfa_assert(0); } } /** * Waiting for rport create response from firmware. Rport offline is pending. */ static void bfa_rport_sm_offline_pending(struct bfa_rport_s *rp, enum bfa_rport_event event) { bfa_trc(rp->bfa, rp->rport_tag); bfa_trc(rp->bfa, event); switch (event) { case BFA_RPORT_SM_FWRSP: bfa_stats(rp, sm_offp_fwrsp); if (bfa_rport_send_fwdelete(rp)) bfa_sm_set_state(rp, bfa_rport_sm_fwdelete); else bfa_sm_set_state(rp, bfa_rport_sm_fwdelete_qfull); break; case BFA_RPORT_SM_DELETE: bfa_stats(rp, sm_offp_del); bfa_sm_set_state(rp, bfa_rport_sm_delete_pending); break; case BFA_RPORT_SM_HWFAIL: bfa_stats(rp, sm_offp_hwf); bfa_sm_set_state(rp, bfa_rport_sm_iocdisable); break; default: bfa_stats(rp, sm_offp_unexp); bfa_assert(0); } } /** * IOC h/w failed. */ static void bfa_rport_sm_iocdisable(struct bfa_rport_s *rp, enum bfa_rport_event event) { bfa_trc(rp->bfa, rp->rport_tag); bfa_trc(rp->bfa, event); switch (event) { case BFA_RPORT_SM_OFFLINE: bfa_stats(rp, sm_iocd_off); bfa_rport_offline_cb(rp); break; case BFA_RPORT_SM_DELETE: bfa_stats(rp, sm_iocd_del); bfa_sm_set_state(rp, bfa_rport_sm_uninit); bfa_rport_free(rp); break; case BFA_RPORT_SM_ONLINE: bfa_stats(rp, sm_iocd_on); if (bfa_rport_send_fwcreate(rp)) bfa_sm_set_state(rp, bfa_rport_sm_fwcreate); else bfa_sm_set_state(rp, bfa_rport_sm_fwcreate_qfull); break; case BFA_RPORT_SM_HWFAIL: break; default: bfa_stats(rp, sm_iocd_unexp); bfa_assert(0); } } /** * bfa_rport_private BFA rport private functions */ static void __bfa_cb_rport_online(void *cbarg, bfa_boolean_t complete) { struct bfa_rport_s *rp = cbarg; if (complete) bfa_cb_rport_online(rp->rport_drv); } static void __bfa_cb_rport_offline(void *cbarg, bfa_boolean_t complete) { struct bfa_rport_s *rp = cbarg; if (complete) bfa_cb_rport_offline(rp->rport_drv); } static void bfa_rport_qresume(void *cbarg) { struct bfa_rport_s *rp = cbarg; bfa_sm_send_event(rp, BFA_RPORT_SM_QRESUME); } static void bfa_rport_meminfo(struct bfa_iocfc_cfg_s *cfg, u32 *km_len, u32 *dm_len) { if (cfg->fwcfg.num_rports < BFA_RPORT_MIN) cfg->fwcfg.num_rports = BFA_RPORT_MIN; *km_len += cfg->fwcfg.num_rports * sizeof(struct bfa_rport_s); } static void bfa_rport_attach(struct bfa_s *bfa, void *bfad, struct bfa_iocfc_cfg_s *cfg, struct bfa_meminfo_s *meminfo, struct bfa_pcidev_s *pcidev) { struct bfa_rport_mod_s *mod = BFA_RPORT_MOD(bfa); struct bfa_rport_s *rp; u16 i; INIT_LIST_HEAD(&mod->rp_free_q); INIT_LIST_HEAD(&mod->rp_active_q); rp = (struct bfa_rport_s *) bfa_meminfo_kva(meminfo); mod->rps_list = rp; mod->num_rports = cfg->fwcfg.num_rports; bfa_assert(mod->num_rports && !(mod->num_rports & (mod->num_rports - 1))); for (i = 0; i < mod->num_rports; i++, rp++) { bfa_os_memset(rp, 0, sizeof(struct bfa_rport_s)); rp->bfa = bfa; rp->rport_tag = i; bfa_sm_set_state(rp, bfa_rport_sm_uninit); /** * - is unused */ if (i) list_add_tail(&rp->qe, &mod->rp_free_q); bfa_reqq_winit(&rp->reqq_wait, bfa_rport_qresume, rp); } /** * consume memory */ bfa_meminfo_kva(meminfo) = (u8 *) rp; } static void bfa_rport_initdone(struct bfa_s *bfa) { } static void bfa_rport_detach(struct bfa_s *bfa) { } static void bfa_rport_start(struct bfa_s *bfa) { } static void bfa_rport_stop(struct bfa_s *bfa) { } static void bfa_rport_iocdisable(struct bfa_s *bfa) { struct bfa_rport_mod_s *mod = BFA_RPORT_MOD(bfa); struct bfa_rport_s *rport; struct list_head *qe, *qen; list_for_each_safe(qe, qen, &mod->rp_active_q) { rport = (struct bfa_rport_s *) qe; bfa_sm_send_event(rport, BFA_RPORT_SM_HWFAIL); } } static struct bfa_rport_s * bfa_rport_alloc(struct bfa_rport_mod_s *mod) { struct bfa_rport_s *rport; bfa_q_deq(&mod->rp_free_q, &rport); if (rport) list_add_tail(&rport->qe, &mod->rp_active_q); return (rport); } static void bfa_rport_free(struct bfa_rport_s *rport) { struct bfa_rport_mod_s *mod = BFA_RPORT_MOD(rport->bfa); bfa_assert(bfa_q_is_on_q(&mod->rp_active_q, rport)); list_del(&rport->qe); list_add_tail(&rport->qe, &mod->rp_free_q); } static bfa_boolean_t bfa_rport_send_fwcreate(struct bfa_rport_s *rp) { struct bfi_rport_create_req_s *m; /** * check for room in queue to send request now */ m = bfa_reqq_next(rp->bfa, BFA_REQQ_RPORT); if (!m) { bfa_reqq_wait(rp->bfa, BFA_REQQ_RPORT, &rp->reqq_wait); return BFA_FALSE; } bfi_h2i_set(m->mh, BFI_MC_RPORT, BFI_RPORT_H2I_CREATE_REQ, bfa_lpuid(rp->bfa)); m->bfa_handle = rp->rport_tag; m->max_frmsz = bfa_os_htons(rp->rport_info.max_frmsz); m->pid = rp->rport_info.pid; m->lp_tag = rp->rport_info.lp_tag; m->local_pid = rp->rport_info.local_pid; m->fc_class = rp->rport_info.fc_class; m->vf_en = rp->rport_info.vf_en; m->vf_id = rp->rport_info.vf_id; m->cisc = rp->rport_info.cisc; /** * queue I/O message to firmware */ bfa_reqq_produce(rp->bfa, BFA_REQQ_RPORT); return BFA_TRUE; } static bfa_boolean_t bfa_rport_send_fwdelete(struct bfa_rport_s *rp) { struct bfi_rport_delete_req_s *m; /** * check for room in queue to send request now */ m = bfa_reqq_next(rp->bfa, BFA_REQQ_RPORT); if (!m) { bfa_reqq_wait(rp->bfa, BFA_REQQ_RPORT, &rp->reqq_wait); return BFA_FALSE; } bfi_h2i_set(m->mh, BFI_MC_RPORT, BFI_RPORT_H2I_DELETE_REQ, bfa_lpuid(rp->bfa)); m->fw_handle = rp->fw_handle; /** * queue I/O message to firmware */ bfa_reqq_produce(rp->bfa, BFA_REQQ_RPORT); return BFA_TRUE; } static bfa_boolean_t bfa_rport_send_fwspeed(struct bfa_rport_s *rp) { struct bfa_rport_speed_req_s *m; /** * check for room in queue to send request now */ m = bfa_reqq_next(rp->bfa, BFA_REQQ_RPORT); if (!m) { bfa_trc(rp->bfa, rp->rport_info.speed); return BFA_FALSE; } bfi_h2i_set(m->mh, BFI_MC_RPORT, BFI_RPORT_H2I_SET_SPEED_REQ, bfa_lpuid(rp->bfa)); m->fw_handle = rp->fw_handle; m->speed = (u8)rp->rport_info.speed; /** * queue I/O message to firmware */ bfa_reqq_produce(rp->bfa, BFA_REQQ_RPORT); return BFA_TRUE; } /** * bfa_rport_public */ /** * Rport interrupt processing. */ void bfa_rport_isr(struct bfa_s *bfa, struct bfi_msg_s *m) { union bfi_rport_i2h_msg_u msg; struct bfa_rport_s *rp; bfa_trc(bfa, m->mhdr.msg_id); msg.msg = m; switch (m->mhdr.msg_id) { case BFI_RPORT_I2H_CREATE_RSP: rp = BFA_RPORT_FROM_TAG(bfa, msg.create_rsp->bfa_handle); rp->fw_handle = msg.create_rsp->fw_handle; rp->qos_attr = msg.create_rsp->qos_attr; bfa_assert(msg.create_rsp->status == BFA_STATUS_OK); bfa_sm_send_event(rp, BFA_RPORT_SM_FWRSP); break; case BFI_RPORT_I2H_DELETE_RSP: rp = BFA_RPORT_FROM_TAG(bfa, msg.delete_rsp->bfa_handle); bfa_assert(msg.delete_rsp->status == BFA_STATUS_OK); bfa_sm_send_event(rp, BFA_RPORT_SM_FWRSP); break; case BFI_RPORT_I2H_QOS_SCN: rp = BFA_RPORT_FROM_TAG(bfa, msg.qos_scn_evt->bfa_handle); rp->event_arg.fw_msg = msg.qos_scn_evt; bfa_sm_send_event(rp, BFA_RPORT_SM_QOS_SCN); break; default: bfa_trc(bfa, m->mhdr.msg_id); bfa_assert(0); } } /** * bfa_rport_api */ struct bfa_rport_s * bfa_rport_create(struct bfa_s *bfa, void *rport_drv) { struct bfa_rport_s *rp; rp = bfa_rport_alloc(BFA_RPORT_MOD(bfa)); if (rp == NULL) return (NULL); rp->bfa = bfa; rp->rport_drv = rport_drv; bfa_rport_clear_stats(rp); bfa_assert(bfa_sm_cmp_state(rp, bfa_rport_sm_uninit)); bfa_sm_send_event(rp, BFA_RPORT_SM_CREATE); return (rp); } void bfa_rport_delete(struct bfa_rport_s *rport) { bfa_sm_send_event(rport, BFA_RPORT_SM_DELETE); } void bfa_rport_online(struct bfa_rport_s *rport, struct bfa_rport_info_s *rport_info) { bfa_assert(rport_info->max_frmsz != 0); /** * Some JBODs are seen to be not setting PDU size correctly in PLOGI * responses. Default to minimum size. */ if (rport_info->max_frmsz == 0) { bfa_trc(rport->bfa, rport->rport_tag); rport_info->max_frmsz = FC_MIN_PDUSZ; } bfa_os_assign(rport->rport_info, *rport_info); bfa_sm_send_event(rport, BFA_RPORT_SM_ONLINE); } void bfa_rport_offline(struct bfa_rport_s *rport) { bfa_sm_send_event(rport, BFA_RPORT_SM_OFFLINE); } void bfa_rport_speed(struct bfa_rport_s *rport, enum bfa_pport_speed speed) { bfa_assert(speed != 0); bfa_assert(speed != BFA_PPORT_SPEED_AUTO); rport->rport_info.speed = speed; bfa_sm_send_event(rport, BFA_RPORT_SM_SET_SPEED); } void bfa_rport_get_stats(struct bfa_rport_s *rport, struct bfa_rport_hal_stats_s *stats) { *stats = rport->stats; } void bfa_rport_get_qos_attr(struct bfa_rport_s *rport, struct bfa_rport_qos_attr_s *qos_attr) { qos_attr->qos_priority = bfa_os_ntohl(rport->qos_attr.qos_priority); qos_attr->qos_flow_id = bfa_os_ntohl(rport->qos_attr.qos_flow_id); } void bfa_rport_clear_stats(struct bfa_rport_s *rport) { bfa_os_memset(&rport->stats, 0, sizeof(rport->stats)); }
gpl-2.0
pchri03/net-next
drivers/gpio/gpio-adp5520.c
976
4318
/* * GPIO driver for Analog Devices ADP5520 MFD PMICs * * Copyright 2009 Analog Devices Inc. * * Licensed under the GPL-2 or later. */ #include <linux/module.h> #include <linux/slab.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/mfd/adp5520.h> #include <linux/gpio.h> struct adp5520_gpio { struct device *master; struct gpio_chip gpio_chip; unsigned char lut[ADP5520_MAXGPIOS]; unsigned long output; }; static int adp5520_gpio_get_value(struct gpio_chip *chip, unsigned off) { struct adp5520_gpio *dev; uint8_t reg_val; dev = container_of(chip, struct adp5520_gpio, gpio_chip); /* * There are dedicated registers for GPIO IN/OUT. * Make sure we return the right value, even when configured as output */ if (test_bit(off, &dev->output)) adp5520_read(dev->master, ADP5520_GPIO_OUT, &reg_val); else adp5520_read(dev->master, ADP5520_GPIO_IN, &reg_val); return !!(reg_val & dev->lut[off]); } static void adp5520_gpio_set_value(struct gpio_chip *chip, unsigned off, int val) { struct adp5520_gpio *dev; dev = container_of(chip, struct adp5520_gpio, gpio_chip); if (val) adp5520_set_bits(dev->master, ADP5520_GPIO_OUT, dev->lut[off]); else adp5520_clr_bits(dev->master, ADP5520_GPIO_OUT, dev->lut[off]); } static int adp5520_gpio_direction_input(struct gpio_chip *chip, unsigned off) { struct adp5520_gpio *dev; dev = container_of(chip, struct adp5520_gpio, gpio_chip); clear_bit(off, &dev->output); return adp5520_clr_bits(dev->master, ADP5520_GPIO_CFG_2, dev->lut[off]); } static int adp5520_gpio_direction_output(struct gpio_chip *chip, unsigned off, int val) { struct adp5520_gpio *dev; int ret = 0; dev = container_of(chip, struct adp5520_gpio, gpio_chip); set_bit(off, &dev->output); if (val) ret |= adp5520_set_bits(dev->master, ADP5520_GPIO_OUT, dev->lut[off]); else ret |= adp5520_clr_bits(dev->master, ADP5520_GPIO_OUT, dev->lut[off]); ret |= adp5520_set_bits(dev->master, ADP5520_GPIO_CFG_2, dev->lut[off]); return ret; } static int adp5520_gpio_probe(struct platform_device *pdev) { struct adp5520_gpio_platform_data *pdata = dev_get_platdata(&pdev->dev); struct adp5520_gpio *dev; struct gpio_chip *gc; int ret, i, gpios; unsigned char ctl_mask = 0; if (pdata == NULL) { dev_err(&pdev->dev, "missing platform data\n"); return -ENODEV; } if (pdev->id != ID_ADP5520) { dev_err(&pdev->dev, "only ADP5520 supports GPIO\n"); return -ENODEV; } dev = devm_kzalloc(&pdev->dev, sizeof(*dev), GFP_KERNEL); if (dev == NULL) return -ENOMEM; dev->master = pdev->dev.parent; for (gpios = 0, i = 0; i < ADP5520_MAXGPIOS; i++) if (pdata->gpio_en_mask & (1 << i)) dev->lut[gpios++] = 1 << i; if (gpios < 1) { ret = -EINVAL; goto err; } gc = &dev->gpio_chip; gc->direction_input = adp5520_gpio_direction_input; gc->direction_output = adp5520_gpio_direction_output; gc->get = adp5520_gpio_get_value; gc->set = adp5520_gpio_set_value; gc->can_sleep = true; gc->base = pdata->gpio_start; gc->ngpio = gpios; gc->label = pdev->name; gc->owner = THIS_MODULE; ret = adp5520_clr_bits(dev->master, ADP5520_GPIO_CFG_1, pdata->gpio_en_mask); if (pdata->gpio_en_mask & ADP5520_GPIO_C3) ctl_mask |= ADP5520_C3_MODE; if (pdata->gpio_en_mask & ADP5520_GPIO_R3) ctl_mask |= ADP5520_R3_MODE; if (ctl_mask) ret = adp5520_set_bits(dev->master, ADP5520_LED_CONTROL, ctl_mask); ret |= adp5520_set_bits(dev->master, ADP5520_GPIO_PULLUP, pdata->gpio_pullup_mask); if (ret) { dev_err(&pdev->dev, "failed to write\n"); goto err; } ret = gpiochip_add(&dev->gpio_chip); if (ret) goto err; platform_set_drvdata(pdev, dev); return 0; err: return ret; } static int adp5520_gpio_remove(struct platform_device *pdev) { struct adp5520_gpio *dev; dev = platform_get_drvdata(pdev); gpiochip_remove(&dev->gpio_chip); return 0; } static struct platform_driver adp5520_gpio_driver = { .driver = { .name = "adp5520-gpio", }, .probe = adp5520_gpio_probe, .remove = adp5520_gpio_remove, }; module_platform_driver(adp5520_gpio_driver); MODULE_AUTHOR("Michael Hennerich <hennerich@blackfin.uclinux.org>"); MODULE_DESCRIPTION("GPIO ADP5520 Driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:adp5520-gpio");
gpl-2.0
s-class/Kona_01
fs/fuse/dir.c
1232
40788
/* FUSE: Filesystem in Userspace Copyright (C) 2001-2008 Miklos Szeredi <miklos@szeredi.hu> This program can be distributed under the terms of the GNU GPL. See the file COPYING. */ #include "fuse_i.h" #include <linux/pagemap.h> #include <linux/file.h> #include <linux/sched.h> #include <linux/namei.h> #include <linux/slab.h> #if BITS_PER_LONG >= 64 static inline void fuse_dentry_settime(struct dentry *entry, u64 time) { entry->d_time = time; } static inline u64 fuse_dentry_time(struct dentry *entry) { return entry->d_time; } #else /* * On 32 bit archs store the high 32 bits of time in d_fsdata */ static void fuse_dentry_settime(struct dentry *entry, u64 time) { entry->d_time = time; entry->d_fsdata = (void *) (unsigned long) (time >> 32); } static u64 fuse_dentry_time(struct dentry *entry) { return (u64) entry->d_time + ((u64) (unsigned long) entry->d_fsdata << 32); } #endif /* * FUSE caches dentries and attributes with separate timeout. The * time in jiffies until the dentry/attributes are valid is stored in * dentry->d_time and fuse_inode->i_time respectively. */ /* * Calculate the time in jiffies until a dentry/attributes are valid */ static u64 time_to_jiffies(unsigned long sec, unsigned long nsec) { if (sec || nsec) { struct timespec ts = {sec, nsec}; return get_jiffies_64() + timespec_to_jiffies(&ts); } else return 0; } /* * Set dentry and possibly attribute timeouts from the lookup/mk* * replies */ static void fuse_change_entry_timeout(struct dentry *entry, struct fuse_entry_out *o) { fuse_dentry_settime(entry, time_to_jiffies(o->entry_valid, o->entry_valid_nsec)); } static u64 attr_timeout(struct fuse_attr_out *o) { return time_to_jiffies(o->attr_valid, o->attr_valid_nsec); } static u64 entry_attr_timeout(struct fuse_entry_out *o) { return time_to_jiffies(o->attr_valid, o->attr_valid_nsec); } /* * Mark the attributes as stale, so that at the next call to * ->getattr() they will be fetched from userspace */ void fuse_invalidate_attr(struct inode *inode) { get_fuse_inode(inode)->i_time = 0; } /* * Just mark the entry as stale, so that a next attempt to look it up * will result in a new lookup call to userspace * * This is called when a dentry is about to become negative and the * timeout is unknown (unlink, rmdir, rename and in some cases * lookup) */ void fuse_invalidate_entry_cache(struct dentry *entry) { fuse_dentry_settime(entry, 0); } /* * Same as fuse_invalidate_entry_cache(), but also try to remove the * dentry from the hash */ static void fuse_invalidate_entry(struct dentry *entry) { d_invalidate(entry); fuse_invalidate_entry_cache(entry); } static void fuse_lookup_init(struct fuse_conn *fc, struct fuse_req *req, u64 nodeid, struct qstr *name, struct fuse_entry_out *outarg) { memset(outarg, 0, sizeof(struct fuse_entry_out)); req->in.h.opcode = FUSE_LOOKUP; req->in.h.nodeid = nodeid; req->in.numargs = 1; req->in.args[0].size = name->len + 1; req->in.args[0].value = name->name; req->out.numargs = 1; if (fc->minor < 9) req->out.args[0].size = FUSE_COMPAT_ENTRY_OUT_SIZE; else req->out.args[0].size = sizeof(struct fuse_entry_out); req->out.args[0].value = outarg; } u64 fuse_get_attr_version(struct fuse_conn *fc) { u64 curr_version; /* * The spin lock isn't actually needed on 64bit archs, but we * don't yet care too much about such optimizations. */ spin_lock(&fc->lock); curr_version = fc->attr_version; spin_unlock(&fc->lock); return curr_version; } /* * Check whether the dentry is still valid * * If the entry validity timeout has expired and the dentry is * positive, try to redo the lookup. If the lookup results in a * different inode, then let the VFS invalidate the dentry and redo * the lookup once more. If the lookup results in the same inode, * then refresh the attributes, timeouts and mark the dentry valid. */ static int fuse_dentry_revalidate(struct dentry *entry, struct nameidata *nd) { struct inode *inode; inode = ACCESS_ONCE(entry->d_inode); if (inode && is_bad_inode(inode)) return 0; else if (fuse_dentry_time(entry) < get_jiffies_64()) { int err; struct fuse_entry_out outarg; struct fuse_conn *fc; struct fuse_req *req; struct fuse_forget_link *forget; struct dentry *parent; u64 attr_version; /* For negative dentries, always do a fresh lookup */ if (!inode) return 0; if (nd && (nd->flags & LOOKUP_RCU)) return -ECHILD; fc = get_fuse_conn(inode); req = fuse_get_req(fc); if (IS_ERR(req)) return 0; forget = fuse_alloc_forget(); if (!forget) { fuse_put_request(fc, req); return 0; } attr_version = fuse_get_attr_version(fc); parent = dget_parent(entry); fuse_lookup_init(fc, req, get_node_id(parent->d_inode), &entry->d_name, &outarg); fuse_request_send(fc, req); dput(parent); err = req->out.h.error; fuse_put_request(fc, req); /* Zero nodeid is same as -ENOENT */ if (!err && !outarg.nodeid) err = -ENOENT; if (!err) { struct fuse_inode *fi = get_fuse_inode(inode); if (outarg.nodeid != get_node_id(inode)) { fuse_queue_forget(fc, forget, outarg.nodeid, 1); return 0; } spin_lock(&fc->lock); fi->nlookup++; spin_unlock(&fc->lock); } kfree(forget); if (err || (outarg.attr.mode ^ inode->i_mode) & S_IFMT) return 0; fuse_change_attributes(inode, &outarg.attr, entry_attr_timeout(&outarg), attr_version); fuse_change_entry_timeout(entry, &outarg); } return 1; } static int invalid_nodeid(u64 nodeid) { return !nodeid || nodeid == FUSE_ROOT_ID; } const struct dentry_operations fuse_dentry_operations = { .d_revalidate = fuse_dentry_revalidate, }; int fuse_valid_type(int m) { return S_ISREG(m) || S_ISDIR(m) || S_ISLNK(m) || S_ISCHR(m) || S_ISBLK(m) || S_ISFIFO(m) || S_ISSOCK(m); } /* * Add a directory inode to a dentry, ensuring that no other dentry * refers to this inode. Called with fc->inst_mutex. */ static struct dentry *fuse_d_add_directory(struct dentry *entry, struct inode *inode) { struct dentry *alias = d_find_alias(inode); if (alias && !(alias->d_flags & DCACHE_DISCONNECTED)) { /* This tries to shrink the subtree below alias */ fuse_invalidate_entry(alias); dput(alias); if (!list_empty(&inode->i_dentry)) return ERR_PTR(-EBUSY); } else { dput(alias); } return d_splice_alias(inode, entry); } int fuse_lookup_name(struct super_block *sb, u64 nodeid, struct qstr *name, struct fuse_entry_out *outarg, struct inode **inode) { struct fuse_conn *fc = get_fuse_conn_super(sb); struct fuse_req *req; struct fuse_forget_link *forget; u64 attr_version; int err; *inode = NULL; err = -ENAMETOOLONG; if (name->len > FUSE_NAME_MAX) goto out; req = fuse_get_req(fc); err = PTR_ERR(req); if (IS_ERR(req)) goto out; forget = fuse_alloc_forget(); err = -ENOMEM; if (!forget) { fuse_put_request(fc, req); goto out; } attr_version = fuse_get_attr_version(fc); fuse_lookup_init(fc, req, nodeid, name, outarg); fuse_request_send(fc, req); err = req->out.h.error; fuse_put_request(fc, req); /* Zero nodeid is same as -ENOENT, but with valid timeout */ if (err || !outarg->nodeid) goto out_put_forget; err = -EIO; if (!outarg->nodeid) goto out_put_forget; if (!fuse_valid_type(outarg->attr.mode)) goto out_put_forget; *inode = fuse_iget(sb, outarg->nodeid, outarg->generation, &outarg->attr, entry_attr_timeout(outarg), attr_version); err = -ENOMEM; if (!*inode) { fuse_queue_forget(fc, forget, outarg->nodeid, 1); goto out; } err = 0; out_put_forget: kfree(forget); out: return err; } static struct dentry *fuse_lookup(struct inode *dir, struct dentry *entry, struct nameidata *nd) { int err; struct fuse_entry_out outarg; struct inode *inode; struct dentry *newent; struct fuse_conn *fc = get_fuse_conn(dir); bool outarg_valid = true; err = fuse_lookup_name(dir->i_sb, get_node_id(dir), &entry->d_name, &outarg, &inode); if (err == -ENOENT) { outarg_valid = false; err = 0; } if (err) goto out_err; err = -EIO; if (inode && get_node_id(inode) == FUSE_ROOT_ID) goto out_iput; if (inode && S_ISDIR(inode->i_mode)) { mutex_lock(&fc->inst_mutex); newent = fuse_d_add_directory(entry, inode); mutex_unlock(&fc->inst_mutex); err = PTR_ERR(newent); if (IS_ERR(newent)) goto out_iput; } else { newent = d_splice_alias(inode, entry); } entry = newent ? newent : entry; if (outarg_valid) fuse_change_entry_timeout(entry, &outarg); else fuse_invalidate_entry_cache(entry); return newent; out_iput: iput(inode); out_err: return ERR_PTR(err); } /* * Atomic create+open operation * * If the filesystem doesn't support this, then fall back to separate * 'mknod' + 'open' requests. */ static int fuse_create_open(struct inode *dir, struct dentry *entry, int mode, struct nameidata *nd) { int err; struct inode *inode; struct fuse_conn *fc = get_fuse_conn(dir); struct fuse_req *req; struct fuse_forget_link *forget; struct fuse_create_in inarg; struct fuse_open_out outopen; struct fuse_entry_out outentry; struct fuse_file *ff; struct file *file; int flags = nd->intent.open.flags - 1; if (fc->no_create) return -ENOSYS; if (flags & O_DIRECT) return -EINVAL; forget = fuse_alloc_forget(); if (!forget) return -ENOMEM; req = fuse_get_req(fc); err = PTR_ERR(req); if (IS_ERR(req)) goto out_put_forget_req; err = -ENOMEM; ff = fuse_file_alloc(fc); if (!ff) goto out_put_request; if (!fc->dont_mask) mode &= ~current_umask(); flags &= ~O_NOCTTY; memset(&inarg, 0, sizeof(inarg)); memset(&outentry, 0, sizeof(outentry)); inarg.flags = flags; inarg.mode = mode; inarg.umask = current_umask(); req->in.h.opcode = FUSE_CREATE; req->in.h.nodeid = get_node_id(dir); req->in.numargs = 2; req->in.args[0].size = fc->minor < 12 ? sizeof(struct fuse_open_in) : sizeof(inarg); req->in.args[0].value = &inarg; req->in.args[1].size = entry->d_name.len + 1; req->in.args[1].value = entry->d_name.name; req->out.numargs = 2; if (fc->minor < 9) req->out.args[0].size = FUSE_COMPAT_ENTRY_OUT_SIZE; else req->out.args[0].size = sizeof(outentry); req->out.args[0].value = &outentry; req->out.args[1].size = sizeof(outopen); req->out.args[1].value = &outopen; fuse_request_send(fc, req); err = req->out.h.error; if (err) { if (err == -ENOSYS) fc->no_create = 1; goto out_free_ff; } err = -EIO; if (!S_ISREG(outentry.attr.mode) || invalid_nodeid(outentry.nodeid)) goto out_free_ff; fuse_put_request(fc, req); ff->fh = outopen.fh; ff->nodeid = outentry.nodeid; ff->open_flags = outopen.open_flags; inode = fuse_iget(dir->i_sb, outentry.nodeid, outentry.generation, &outentry.attr, entry_attr_timeout(&outentry), 0); if (!inode) { flags &= ~(O_CREAT | O_EXCL | O_TRUNC); fuse_sync_release(ff, flags); fuse_queue_forget(fc, forget, outentry.nodeid, 1); return -ENOMEM; } kfree(forget); d_instantiate(entry, inode); fuse_change_entry_timeout(entry, &outentry); fuse_invalidate_attr(dir); file = lookup_instantiate_filp(nd, entry, generic_file_open); if (IS_ERR(file)) { fuse_sync_release(ff, flags); return PTR_ERR(file); } file->private_data = fuse_file_get(ff); fuse_finish_open(inode, file); return 0; out_free_ff: fuse_file_free(ff); out_put_request: fuse_put_request(fc, req); out_put_forget_req: kfree(forget); return err; } /* * Code shared between mknod, mkdir, symlink and link */ static int create_new_entry(struct fuse_conn *fc, struct fuse_req *req, struct inode *dir, struct dentry *entry, int mode) { struct fuse_entry_out outarg; struct inode *inode; int err; struct fuse_forget_link *forget; forget = fuse_alloc_forget(); if (!forget) { fuse_put_request(fc, req); return -ENOMEM; } memset(&outarg, 0, sizeof(outarg)); req->in.h.nodeid = get_node_id(dir); req->out.numargs = 1; if (fc->minor < 9) req->out.args[0].size = FUSE_COMPAT_ENTRY_OUT_SIZE; else req->out.args[0].size = sizeof(outarg); req->out.args[0].value = &outarg; fuse_request_send(fc, req); err = req->out.h.error; fuse_put_request(fc, req); if (err) goto out_put_forget_req; err = -EIO; if (invalid_nodeid(outarg.nodeid)) goto out_put_forget_req; if ((outarg.attr.mode ^ mode) & S_IFMT) goto out_put_forget_req; inode = fuse_iget(dir->i_sb, outarg.nodeid, outarg.generation, &outarg.attr, entry_attr_timeout(&outarg), 0); if (!inode) { fuse_queue_forget(fc, forget, outarg.nodeid, 1); return -ENOMEM; } kfree(forget); if (S_ISDIR(inode->i_mode)) { struct dentry *alias; mutex_lock(&fc->inst_mutex); alias = d_find_alias(inode); if (alias) { /* New directory must have moved since mkdir */ mutex_unlock(&fc->inst_mutex); dput(alias); iput(inode); return -EBUSY; } d_instantiate(entry, inode); mutex_unlock(&fc->inst_mutex); } else d_instantiate(entry, inode); fuse_change_entry_timeout(entry, &outarg); fuse_invalidate_attr(dir); return 0; out_put_forget_req: kfree(forget); return err; } static int fuse_mknod(struct inode *dir, struct dentry *entry, int mode, dev_t rdev) { struct fuse_mknod_in inarg; struct fuse_conn *fc = get_fuse_conn(dir); struct fuse_req *req = fuse_get_req(fc); if (IS_ERR(req)) return PTR_ERR(req); if (!fc->dont_mask) mode &= ~current_umask(); memset(&inarg, 0, sizeof(inarg)); inarg.mode = mode; inarg.rdev = new_encode_dev(rdev); inarg.umask = current_umask(); req->in.h.opcode = FUSE_MKNOD; req->in.numargs = 2; req->in.args[0].size = fc->minor < 12 ? FUSE_COMPAT_MKNOD_IN_SIZE : sizeof(inarg); req->in.args[0].value = &inarg; req->in.args[1].size = entry->d_name.len + 1; req->in.args[1].value = entry->d_name.name; return create_new_entry(fc, req, dir, entry, mode); } static int fuse_create(struct inode *dir, struct dentry *entry, int mode, struct nameidata *nd) { if (nd && (nd->flags & LOOKUP_OPEN)) { int err = fuse_create_open(dir, entry, mode, nd); if (err != -ENOSYS) return err; /* Fall back on mknod */ } return fuse_mknod(dir, entry, mode, 0); } static int fuse_mkdir(struct inode *dir, struct dentry *entry, int mode) { struct fuse_mkdir_in inarg; struct fuse_conn *fc = get_fuse_conn(dir); struct fuse_req *req = fuse_get_req(fc); if (IS_ERR(req)) return PTR_ERR(req); if (!fc->dont_mask) mode &= ~current_umask(); memset(&inarg, 0, sizeof(inarg)); inarg.mode = mode; inarg.umask = current_umask(); req->in.h.opcode = FUSE_MKDIR; req->in.numargs = 2; req->in.args[0].size = sizeof(inarg); req->in.args[0].value = &inarg; req->in.args[1].size = entry->d_name.len + 1; req->in.args[1].value = entry->d_name.name; return create_new_entry(fc, req, dir, entry, S_IFDIR); } static int fuse_symlink(struct inode *dir, struct dentry *entry, const char *link) { struct fuse_conn *fc = get_fuse_conn(dir); unsigned len = strlen(link) + 1; struct fuse_req *req = fuse_get_req(fc); if (IS_ERR(req)) return PTR_ERR(req); req->in.h.opcode = FUSE_SYMLINK; req->in.numargs = 2; req->in.args[0].size = entry->d_name.len + 1; req->in.args[0].value = entry->d_name.name; req->in.args[1].size = len; req->in.args[1].value = link; return create_new_entry(fc, req, dir, entry, S_IFLNK); } static int fuse_unlink(struct inode *dir, struct dentry *entry) { int err; struct fuse_conn *fc = get_fuse_conn(dir); struct fuse_req *req = fuse_get_req(fc); if (IS_ERR(req)) return PTR_ERR(req); req->in.h.opcode = FUSE_UNLINK; req->in.h.nodeid = get_node_id(dir); req->in.numargs = 1; req->in.args[0].size = entry->d_name.len + 1; req->in.args[0].value = entry->d_name.name; fuse_request_send(fc, req); err = req->out.h.error; fuse_put_request(fc, req); if (!err) { struct inode *inode = entry->d_inode; /* * Set nlink to zero so the inode can be cleared, if the inode * does have more links this will be discovered at the next * lookup/getattr. */ clear_nlink(inode); fuse_invalidate_attr(inode); fuse_invalidate_attr(dir); fuse_invalidate_entry_cache(entry); } else if (err == -EINTR) fuse_invalidate_entry(entry); return err; } static int fuse_rmdir(struct inode *dir, struct dentry *entry) { int err; struct fuse_conn *fc = get_fuse_conn(dir); struct fuse_req *req = fuse_get_req(fc); if (IS_ERR(req)) return PTR_ERR(req); req->in.h.opcode = FUSE_RMDIR; req->in.h.nodeid = get_node_id(dir); req->in.numargs = 1; req->in.args[0].size = entry->d_name.len + 1; req->in.args[0].value = entry->d_name.name; fuse_request_send(fc, req); err = req->out.h.error; fuse_put_request(fc, req); if (!err) { clear_nlink(entry->d_inode); fuse_invalidate_attr(dir); fuse_invalidate_entry_cache(entry); } else if (err == -EINTR) fuse_invalidate_entry(entry); return err; } static int fuse_rename(struct inode *olddir, struct dentry *oldent, struct inode *newdir, struct dentry *newent) { int err; struct fuse_rename_in inarg; struct fuse_conn *fc = get_fuse_conn(olddir); struct fuse_req *req = fuse_get_req(fc); if (IS_ERR(req)) return PTR_ERR(req); memset(&inarg, 0, sizeof(inarg)); inarg.newdir = get_node_id(newdir); req->in.h.opcode = FUSE_RENAME; req->in.h.nodeid = get_node_id(olddir); req->in.numargs = 3; req->in.args[0].size = sizeof(inarg); req->in.args[0].value = &inarg; req->in.args[1].size = oldent->d_name.len + 1; req->in.args[1].value = oldent->d_name.name; req->in.args[2].size = newent->d_name.len + 1; req->in.args[2].value = newent->d_name.name; fuse_request_send(fc, req); err = req->out.h.error; fuse_put_request(fc, req); if (!err) { /* ctime changes */ fuse_invalidate_attr(oldent->d_inode); fuse_invalidate_attr(olddir); if (olddir != newdir) fuse_invalidate_attr(newdir); /* newent will end up negative */ if (newent->d_inode) { fuse_invalidate_attr(newent->d_inode); fuse_invalidate_entry_cache(newent); } } else if (err == -EINTR) { /* If request was interrupted, DEITY only knows if the rename actually took place. If the invalidation fails (e.g. some process has CWD under the renamed directory), then there can be inconsistency between the dcache and the real filesystem. Tough luck. */ fuse_invalidate_entry(oldent); if (newent->d_inode) fuse_invalidate_entry(newent); } return err; } static int fuse_link(struct dentry *entry, struct inode *newdir, struct dentry *newent) { int err; struct fuse_link_in inarg; struct inode *inode = entry->d_inode; struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_req *req = fuse_get_req(fc); if (IS_ERR(req)) return PTR_ERR(req); memset(&inarg, 0, sizeof(inarg)); inarg.oldnodeid = get_node_id(inode); req->in.h.opcode = FUSE_LINK; req->in.numargs = 2; req->in.args[0].size = sizeof(inarg); req->in.args[0].value = &inarg; req->in.args[1].size = newent->d_name.len + 1; req->in.args[1].value = newent->d_name.name; err = create_new_entry(fc, req, newdir, newent, inode->i_mode); /* Contrary to "normal" filesystems it can happen that link makes two "logical" inodes point to the same "physical" inode. We invalidate the attributes of the old one, so it will reflect changes in the backing inode (link count, etc.) */ if (!err || err == -EINTR) fuse_invalidate_attr(inode); return err; } static void fuse_fillattr(struct inode *inode, struct fuse_attr *attr, struct kstat *stat) { stat->dev = inode->i_sb->s_dev; stat->ino = attr->ino; stat->mode = (inode->i_mode & S_IFMT) | (attr->mode & 07777); stat->nlink = attr->nlink; stat->uid = attr->uid; stat->gid = attr->gid; stat->rdev = inode->i_rdev; stat->atime.tv_sec = attr->atime; stat->atime.tv_nsec = attr->atimensec; stat->mtime.tv_sec = attr->mtime; stat->mtime.tv_nsec = attr->mtimensec; stat->ctime.tv_sec = attr->ctime; stat->ctime.tv_nsec = attr->ctimensec; stat->size = attr->size; stat->blocks = attr->blocks; stat->blksize = (1 << inode->i_blkbits); } static int fuse_do_getattr(struct inode *inode, struct kstat *stat, struct file *file) { int err; struct fuse_getattr_in inarg; struct fuse_attr_out outarg; struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_req *req; u64 attr_version; req = fuse_get_req(fc); if (IS_ERR(req)) return PTR_ERR(req); attr_version = fuse_get_attr_version(fc); memset(&inarg, 0, sizeof(inarg)); memset(&outarg, 0, sizeof(outarg)); /* Directories have separate file-handle space */ if (file && S_ISREG(inode->i_mode)) { struct fuse_file *ff = file->private_data; inarg.getattr_flags |= FUSE_GETATTR_FH; inarg.fh = ff->fh; } req->in.h.opcode = FUSE_GETATTR; req->in.h.nodeid = get_node_id(inode); req->in.numargs = 1; req->in.args[0].size = sizeof(inarg); req->in.args[0].value = &inarg; req->out.numargs = 1; if (fc->minor < 9) req->out.args[0].size = FUSE_COMPAT_ATTR_OUT_SIZE; else req->out.args[0].size = sizeof(outarg); req->out.args[0].value = &outarg; fuse_request_send(fc, req); err = req->out.h.error; fuse_put_request(fc, req); if (!err) { if ((inode->i_mode ^ outarg.attr.mode) & S_IFMT) { make_bad_inode(inode); err = -EIO; } else { fuse_change_attributes(inode, &outarg.attr, attr_timeout(&outarg), attr_version); if (stat) fuse_fillattr(inode, &outarg.attr, stat); } } return err; } int fuse_update_attributes(struct inode *inode, struct kstat *stat, struct file *file, bool *refreshed) { struct fuse_inode *fi = get_fuse_inode(inode); int err; bool r; if (fi->i_time < get_jiffies_64()) { r = true; err = fuse_do_getattr(inode, stat, file); } else { r = false; err = 0; if (stat) { generic_fillattr(inode, stat); stat->mode = fi->orig_i_mode; } } if (refreshed != NULL) *refreshed = r; return err; } int fuse_reverse_inval_entry(struct super_block *sb, u64 parent_nodeid, struct qstr *name) { int err = -ENOTDIR; struct inode *parent; struct dentry *dir; struct dentry *entry; parent = ilookup5(sb, parent_nodeid, fuse_inode_eq, &parent_nodeid); if (!parent) return -ENOENT; mutex_lock(&parent->i_mutex); if (!S_ISDIR(parent->i_mode)) goto unlock; err = -ENOENT; dir = d_find_alias(parent); if (!dir) goto unlock; entry = d_lookup(dir, name); dput(dir); if (!entry) goto unlock; fuse_invalidate_attr(parent); fuse_invalidate_entry(entry); dput(entry); err = 0; unlock: mutex_unlock(&parent->i_mutex); iput(parent); return err; } /* * Calling into a user-controlled filesystem gives the filesystem * daemon ptrace-like capabilities over the requester process. This * means, that the filesystem daemon is able to record the exact * filesystem operations performed, and can also control the behavior * of the requester process in otherwise impossible ways. For example * it can delay the operation for arbitrary length of time allowing * DoS against the requester. * * For this reason only those processes can call into the filesystem, * for which the owner of the mount has ptrace privilege. This * excludes processes started by other users, suid or sgid processes. */ int fuse_allow_task(struct fuse_conn *fc, struct task_struct *task) { const struct cred *cred; int ret; if (fc->flags & FUSE_ALLOW_OTHER) return 1; rcu_read_lock(); ret = 0; cred = __task_cred(task); if (cred->euid == fc->user_id && cred->suid == fc->user_id && cred->uid == fc->user_id && cred->egid == fc->group_id && cred->sgid == fc->group_id && cred->gid == fc->group_id) ret = 1; rcu_read_unlock(); return ret; } static int fuse_access(struct inode *inode, int mask) { struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_req *req; struct fuse_access_in inarg; int err; if (fc->no_access) return 0; req = fuse_get_req(fc); if (IS_ERR(req)) return PTR_ERR(req); memset(&inarg, 0, sizeof(inarg)); inarg.mask = mask & (MAY_READ | MAY_WRITE | MAY_EXEC); req->in.h.opcode = FUSE_ACCESS; req->in.h.nodeid = get_node_id(inode); req->in.numargs = 1; req->in.args[0].size = sizeof(inarg); req->in.args[0].value = &inarg; fuse_request_send(fc, req); err = req->out.h.error; fuse_put_request(fc, req); if (err == -ENOSYS) { fc->no_access = 1; err = 0; } return err; } static int fuse_perm_getattr(struct inode *inode, int flags) { if (flags & IPERM_FLAG_RCU) return -ECHILD; return fuse_do_getattr(inode, NULL, NULL); } /* * Check permission. The two basic access models of FUSE are: * * 1) Local access checking ('default_permissions' mount option) based * on file mode. This is the plain old disk filesystem permission * modell. * * 2) "Remote" access checking, where server is responsible for * checking permission in each inode operation. An exception to this * is if ->permission() was invoked from sys_access() in which case an * access request is sent. Execute permission is still checked * locally based on file mode. */ static int fuse_permission(struct inode *inode, int mask, unsigned int flags) { struct fuse_conn *fc = get_fuse_conn(inode); bool refreshed = false; int err = 0; if (!fuse_allow_task(fc, current)) return -EACCES; /* * If attributes are needed, refresh them before proceeding */ if ((fc->flags & FUSE_DEFAULT_PERMISSIONS) || ((mask & MAY_EXEC) && S_ISREG(inode->i_mode))) { struct fuse_inode *fi = get_fuse_inode(inode); if (fi->i_time < get_jiffies_64()) { refreshed = true; err = fuse_perm_getattr(inode, flags); if (err) return err; } } if (fc->flags & FUSE_DEFAULT_PERMISSIONS) { err = generic_permission(inode, mask, flags, NULL); /* If permission is denied, try to refresh file attributes. This is also needed, because the root node will at first have no permissions */ if (err == -EACCES && !refreshed) { err = fuse_perm_getattr(inode, flags); if (!err) err = generic_permission(inode, mask, flags, NULL); } /* Note: the opposite of the above test does not exist. So if permissions are revoked this won't be noticed immediately, only after the attribute timeout has expired */ } else if (mask & (MAY_ACCESS | MAY_CHDIR)) { if (flags & IPERM_FLAG_RCU) return -ECHILD; err = fuse_access(inode, mask); } else if ((mask & MAY_EXEC) && S_ISREG(inode->i_mode)) { if (!(inode->i_mode & S_IXUGO)) { if (refreshed) return -EACCES; err = fuse_perm_getattr(inode, flags); if (!err && !(inode->i_mode & S_IXUGO)) return -EACCES; } } return err; } static int parse_dirfile(char *buf, size_t nbytes, struct file *file, void *dstbuf, filldir_t filldir) { while (nbytes >= FUSE_NAME_OFFSET) { struct fuse_dirent *dirent = (struct fuse_dirent *) buf; size_t reclen = FUSE_DIRENT_SIZE(dirent); int over; if (!dirent->namelen || dirent->namelen > FUSE_NAME_MAX) return -EIO; if (reclen > nbytes) break; over = filldir(dstbuf, dirent->name, dirent->namelen, file->f_pos, dirent->ino, dirent->type); if (over) break; buf += reclen; nbytes -= reclen; file->f_pos = dirent->off; } return 0; } static int fuse_readdir(struct file *file, void *dstbuf, filldir_t filldir) { int err; size_t nbytes; struct page *page; struct inode *inode = file->f_path.dentry->d_inode; struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_req *req; if (is_bad_inode(inode)) return -EIO; req = fuse_get_req(fc); if (IS_ERR(req)) return PTR_ERR(req); page = alloc_page(GFP_KERNEL); if (!page) { fuse_put_request(fc, req); return -ENOMEM; } req->out.argpages = 1; req->num_pages = 1; req->pages[0] = page; fuse_read_fill(req, file, file->f_pos, PAGE_SIZE, FUSE_READDIR); fuse_request_send(fc, req); nbytes = req->out.args[0].size; err = req->out.h.error; fuse_put_request(fc, req); if (!err) err = parse_dirfile(page_address(page), nbytes, file, dstbuf, filldir); __free_page(page); fuse_invalidate_attr(inode); /* atime changed */ return err; } static char *read_link(struct dentry *dentry) { struct inode *inode = dentry->d_inode; struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_req *req = fuse_get_req(fc); char *link; if (IS_ERR(req)) return ERR_CAST(req); link = (char *) __get_free_page(GFP_KERNEL); if (!link) { link = ERR_PTR(-ENOMEM); goto out; } req->in.h.opcode = FUSE_READLINK; req->in.h.nodeid = get_node_id(inode); req->out.argvar = 1; req->out.numargs = 1; req->out.args[0].size = PAGE_SIZE - 1; req->out.args[0].value = link; fuse_request_send(fc, req); if (req->out.h.error) { free_page((unsigned long) link); link = ERR_PTR(req->out.h.error); } else link[req->out.args[0].size] = '\0'; out: fuse_put_request(fc, req); fuse_invalidate_attr(inode); /* atime changed */ return link; } static void free_link(char *link) { if (!IS_ERR(link)) free_page((unsigned long) link); } static void *fuse_follow_link(struct dentry *dentry, struct nameidata *nd) { nd_set_link(nd, read_link(dentry)); return NULL; } static void fuse_put_link(struct dentry *dentry, struct nameidata *nd, void *c) { free_link(nd_get_link(nd)); } static int fuse_dir_open(struct inode *inode, struct file *file) { return fuse_open_common(inode, file, true); } static int fuse_dir_release(struct inode *inode, struct file *file) { fuse_release_common(file, FUSE_RELEASEDIR); return 0; } static int fuse_dir_fsync(struct file *file, int datasync) { return fuse_fsync_common(file, datasync, 1); } static bool update_mtime(unsigned ivalid) { /* Always update if mtime is explicitly set */ if (ivalid & ATTR_MTIME_SET) return true; /* If it's an open(O_TRUNC) or an ftruncate(), don't update */ if ((ivalid & ATTR_SIZE) && (ivalid & (ATTR_OPEN | ATTR_FILE))) return false; /* In all other cases update */ return true; } static void iattr_to_fattr(struct iattr *iattr, struct fuse_setattr_in *arg) { unsigned ivalid = iattr->ia_valid; if (ivalid & ATTR_MODE) arg->valid |= FATTR_MODE, arg->mode = iattr->ia_mode; if (ivalid & ATTR_UID) arg->valid |= FATTR_UID, arg->uid = iattr->ia_uid; if (ivalid & ATTR_GID) arg->valid |= FATTR_GID, arg->gid = iattr->ia_gid; if (ivalid & ATTR_SIZE) arg->valid |= FATTR_SIZE, arg->size = iattr->ia_size; if (ivalid & ATTR_ATIME) { arg->valid |= FATTR_ATIME; arg->atime = iattr->ia_atime.tv_sec; arg->atimensec = iattr->ia_atime.tv_nsec; if (!(ivalid & ATTR_ATIME_SET)) arg->valid |= FATTR_ATIME_NOW; } if ((ivalid & ATTR_MTIME) && update_mtime(ivalid)) { arg->valid |= FATTR_MTIME; arg->mtime = iattr->ia_mtime.tv_sec; arg->mtimensec = iattr->ia_mtime.tv_nsec; if (!(ivalid & ATTR_MTIME_SET)) arg->valid |= FATTR_MTIME_NOW; } } /* * Prevent concurrent writepages on inode * * This is done by adding a negative bias to the inode write counter * and waiting for all pending writes to finish. */ void fuse_set_nowrite(struct inode *inode) { struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_inode *fi = get_fuse_inode(inode); BUG_ON(!mutex_is_locked(&inode->i_mutex)); spin_lock(&fc->lock); BUG_ON(fi->writectr < 0); fi->writectr += FUSE_NOWRITE; spin_unlock(&fc->lock); wait_event(fi->page_waitq, fi->writectr == FUSE_NOWRITE); } /* * Allow writepages on inode * * Remove the bias from the writecounter and send any queued * writepages. */ static void __fuse_release_nowrite(struct inode *inode) { struct fuse_inode *fi = get_fuse_inode(inode); BUG_ON(fi->writectr != FUSE_NOWRITE); fi->writectr = 0; fuse_flush_writepages(inode); } void fuse_release_nowrite(struct inode *inode) { struct fuse_conn *fc = get_fuse_conn(inode); spin_lock(&fc->lock); __fuse_release_nowrite(inode); spin_unlock(&fc->lock); } /* * Set attributes, and at the same time refresh them. * * Truncation is slightly complicated, because the 'truncate' request * may fail, in which case we don't want to touch the mapping. * vmtruncate() doesn't allow for this case, so do the rlimit checking * and the actual truncation by hand. */ static int fuse_do_setattr(struct dentry *entry, struct iattr *attr, struct file *file) { struct inode *inode = entry->d_inode; struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_req *req; struct fuse_setattr_in inarg; struct fuse_attr_out outarg; bool is_truncate = false; loff_t oldsize; int err; if (!fuse_allow_task(fc, current)) return -EACCES; if (!(fc->flags & FUSE_DEFAULT_PERMISSIONS)) attr->ia_valid |= ATTR_FORCE; err = inode_change_ok(inode, attr); if (err) return err; if (attr->ia_valid & ATTR_OPEN) { if (fc->atomic_o_trunc) return 0; file = NULL; } if (attr->ia_valid & ATTR_SIZE) is_truncate = true; req = fuse_get_req(fc); if (IS_ERR(req)) return PTR_ERR(req); if (is_truncate) fuse_set_nowrite(inode); memset(&inarg, 0, sizeof(inarg)); memset(&outarg, 0, sizeof(outarg)); iattr_to_fattr(attr, &inarg); if (file) { struct fuse_file *ff = file->private_data; inarg.valid |= FATTR_FH; inarg.fh = ff->fh; } if (attr->ia_valid & ATTR_SIZE) { /* For mandatory locking in truncate */ inarg.valid |= FATTR_LOCKOWNER; inarg.lock_owner = fuse_lock_owner_id(fc, current->files); } req->in.h.opcode = FUSE_SETATTR; req->in.h.nodeid = get_node_id(inode); req->in.numargs = 1; req->in.args[0].size = sizeof(inarg); req->in.args[0].value = &inarg; req->out.numargs = 1; if (fc->minor < 9) req->out.args[0].size = FUSE_COMPAT_ATTR_OUT_SIZE; else req->out.args[0].size = sizeof(outarg); req->out.args[0].value = &outarg; fuse_request_send(fc, req); err = req->out.h.error; fuse_put_request(fc, req); if (err) { if (err == -EINTR) fuse_invalidate_attr(inode); goto error; } if ((inode->i_mode ^ outarg.attr.mode) & S_IFMT) { make_bad_inode(inode); err = -EIO; goto error; } spin_lock(&fc->lock); fuse_change_attributes_common(inode, &outarg.attr, attr_timeout(&outarg)); oldsize = inode->i_size; i_size_write(inode, outarg.attr.size); if (is_truncate) { /* NOTE: this may release/reacquire fc->lock */ __fuse_release_nowrite(inode); } spin_unlock(&fc->lock); /* * Only call invalidate_inode_pages2() after removing * FUSE_NOWRITE, otherwise fuse_launder_page() would deadlock. */ if (S_ISREG(inode->i_mode) && oldsize != outarg.attr.size) { truncate_pagecache(inode, oldsize, outarg.attr.size); invalidate_inode_pages2(inode->i_mapping); } return 0; error: if (is_truncate) fuse_release_nowrite(inode); return err; } static int fuse_setattr(struct dentry *entry, struct iattr *attr) { if (attr->ia_valid & ATTR_FILE) return fuse_do_setattr(entry, attr, attr->ia_file); else return fuse_do_setattr(entry, attr, NULL); } static int fuse_getattr(struct vfsmount *mnt, struct dentry *entry, struct kstat *stat) { struct inode *inode = entry->d_inode; struct fuse_conn *fc = get_fuse_conn(inode); if (!fuse_allow_task(fc, current)) return -EACCES; return fuse_update_attributes(inode, stat, NULL, NULL); } static int fuse_setxattr(struct dentry *entry, const char *name, const void *value, size_t size, int flags) { struct inode *inode = entry->d_inode; struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_req *req; struct fuse_setxattr_in inarg; int err; if (fc->no_setxattr) return -EOPNOTSUPP; req = fuse_get_req(fc); if (IS_ERR(req)) return PTR_ERR(req); memset(&inarg, 0, sizeof(inarg)); inarg.size = size; inarg.flags = flags; req->in.h.opcode = FUSE_SETXATTR; req->in.h.nodeid = get_node_id(inode); req->in.numargs = 3; req->in.args[0].size = sizeof(inarg); req->in.args[0].value = &inarg; req->in.args[1].size = strlen(name) + 1; req->in.args[1].value = name; req->in.args[2].size = size; req->in.args[2].value = value; fuse_request_send(fc, req); err = req->out.h.error; fuse_put_request(fc, req); if (err == -ENOSYS) { fc->no_setxattr = 1; err = -EOPNOTSUPP; } return err; } static ssize_t fuse_getxattr(struct dentry *entry, const char *name, void *value, size_t size) { struct inode *inode = entry->d_inode; struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_req *req; struct fuse_getxattr_in inarg; struct fuse_getxattr_out outarg; ssize_t ret; if (fc->no_getxattr) return -EOPNOTSUPP; req = fuse_get_req(fc); if (IS_ERR(req)) return PTR_ERR(req); memset(&inarg, 0, sizeof(inarg)); inarg.size = size; req->in.h.opcode = FUSE_GETXATTR; req->in.h.nodeid = get_node_id(inode); req->in.numargs = 2; req->in.args[0].size = sizeof(inarg); req->in.args[0].value = &inarg; req->in.args[1].size = strlen(name) + 1; req->in.args[1].value = name; /* This is really two different operations rolled into one */ req->out.numargs = 1; if (size) { req->out.argvar = 1; req->out.args[0].size = size; req->out.args[0].value = value; } else { req->out.args[0].size = sizeof(outarg); req->out.args[0].value = &outarg; } fuse_request_send(fc, req); ret = req->out.h.error; if (!ret) ret = size ? req->out.args[0].size : outarg.size; else { if (ret == -ENOSYS) { fc->no_getxattr = 1; ret = -EOPNOTSUPP; } } fuse_put_request(fc, req); return ret; } static ssize_t fuse_listxattr(struct dentry *entry, char *list, size_t size) { struct inode *inode = entry->d_inode; struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_req *req; struct fuse_getxattr_in inarg; struct fuse_getxattr_out outarg; ssize_t ret; if (!fuse_allow_task(fc, current)) return -EACCES; if (fc->no_listxattr) return -EOPNOTSUPP; req = fuse_get_req(fc); if (IS_ERR(req)) return PTR_ERR(req); memset(&inarg, 0, sizeof(inarg)); inarg.size = size; req->in.h.opcode = FUSE_LISTXATTR; req->in.h.nodeid = get_node_id(inode); req->in.numargs = 1; req->in.args[0].size = sizeof(inarg); req->in.args[0].value = &inarg; /* This is really two different operations rolled into one */ req->out.numargs = 1; if (size) { req->out.argvar = 1; req->out.args[0].size = size; req->out.args[0].value = list; } else { req->out.args[0].size = sizeof(outarg); req->out.args[0].value = &outarg; } fuse_request_send(fc, req); ret = req->out.h.error; if (!ret) ret = size ? req->out.args[0].size : outarg.size; else { if (ret == -ENOSYS) { fc->no_listxattr = 1; ret = -EOPNOTSUPP; } } fuse_put_request(fc, req); return ret; } static int fuse_removexattr(struct dentry *entry, const char *name) { struct inode *inode = entry->d_inode; struct fuse_conn *fc = get_fuse_conn(inode); struct fuse_req *req; int err; if (fc->no_removexattr) return -EOPNOTSUPP; req = fuse_get_req(fc); if (IS_ERR(req)) return PTR_ERR(req); req->in.h.opcode = FUSE_REMOVEXATTR; req->in.h.nodeid = get_node_id(inode); req->in.numargs = 1; req->in.args[0].size = strlen(name) + 1; req->in.args[0].value = name; fuse_request_send(fc, req); err = req->out.h.error; fuse_put_request(fc, req); if (err == -ENOSYS) { fc->no_removexattr = 1; err = -EOPNOTSUPP; } return err; } static const struct inode_operations fuse_dir_inode_operations = { .lookup = fuse_lookup, .mkdir = fuse_mkdir, .symlink = fuse_symlink, .unlink = fuse_unlink, .rmdir = fuse_rmdir, .rename = fuse_rename, .link = fuse_link, .setattr = fuse_setattr, .create = fuse_create, .mknod = fuse_mknod, .permission = fuse_permission, .getattr = fuse_getattr, .setxattr = fuse_setxattr, .getxattr = fuse_getxattr, .listxattr = fuse_listxattr, .removexattr = fuse_removexattr, }; static const struct file_operations fuse_dir_operations = { .llseek = generic_file_llseek, .read = generic_read_dir, .readdir = fuse_readdir, .open = fuse_dir_open, .release = fuse_dir_release, .fsync = fuse_dir_fsync, }; static const struct inode_operations fuse_common_inode_operations = { .setattr = fuse_setattr, .permission = fuse_permission, .getattr = fuse_getattr, .setxattr = fuse_setxattr, .getxattr = fuse_getxattr, .listxattr = fuse_listxattr, .removexattr = fuse_removexattr, }; static const struct inode_operations fuse_symlink_inode_operations = { .setattr = fuse_setattr, .follow_link = fuse_follow_link, .put_link = fuse_put_link, .readlink = generic_readlink, .getattr = fuse_getattr, .setxattr = fuse_setxattr, .getxattr = fuse_getxattr, .listxattr = fuse_listxattr, .removexattr = fuse_removexattr, }; void fuse_init_common(struct inode *inode) { inode->i_op = &fuse_common_inode_operations; } void fuse_init_dir(struct inode *inode) { inode->i_op = &fuse_dir_inode_operations; inode->i_fop = &fuse_dir_operations; } void fuse_init_symlink(struct inode *inode) { inode->i_op = &fuse_symlink_inode_operations; }
gpl-2.0
nuvotonmcu/linux-3.10.y
arch/mips/lasat/sysctl.c
2000
6085
/* * Thomas Horsten <thh@lasat.com> * Copyright (C) 2000 LASAT Networks A/S. * * This program is free software; you can distribute it and/or modify it * under the terms of the GNU General Public License (Version 2) as * published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston MA 02111-1307, USA. * * Routines specific to the LASAT boards */ #include <linux/types.h> #include <asm/lasat/lasat.h> #include <linux/module.h> #include <linux/sysctl.h> #include <linux/stddef.h> #include <linux/init.h> #include <linux/fs.h> #include <linux/ctype.h> #include <linux/string.h> #include <linux/net.h> #include <linux/inet.h> #include <linux/uaccess.h> #include <asm/time.h> #ifdef CONFIG_DS1603 #include "ds1603.h" #endif /* And the same for proc */ int proc_dolasatstring(ctl_table *table, int write, void *buffer, size_t *lenp, loff_t *ppos) { int r; r = proc_dostring(table, write, buffer, lenp, ppos); if ((!write) || r) return r; lasat_write_eeprom_info(); return 0; } /* proc function to write EEPROM after changing int entry */ int proc_dolasatint(ctl_table *table, int write, void *buffer, size_t *lenp, loff_t *ppos) { int r; r = proc_dointvec(table, write, buffer, lenp, ppos); if ((!write) || r) return r; lasat_write_eeprom_info(); return 0; } #ifdef CONFIG_DS1603 static int rtctmp; /* proc function to read/write RealTime Clock */ int proc_dolasatrtc(ctl_table *table, int write, void *buffer, size_t *lenp, loff_t *ppos) { struct timespec ts; int r; if (!write) { read_persistent_clock(&ts); rtctmp = ts.tv_sec; /* check for time < 0 and set to 0 */ if (rtctmp < 0) rtctmp = 0; } r = proc_dointvec(table, write, buffer, lenp, ppos); if (r) return r; if (write) rtc_mips_set_mmss(rtctmp); return 0; } #endif #ifdef CONFIG_INET int proc_lasat_ip(ctl_table *table, int write, void *buffer, size_t *lenp, loff_t *ppos) { unsigned int ip; char *p, c; int len; char ipbuf[32]; if (!table->data || !table->maxlen || !*lenp || (*ppos && !write)) { *lenp = 0; return 0; } if (write) { len = 0; p = buffer; while (len < *lenp) { if (get_user(c, p++)) return -EFAULT; if (c == 0 || c == '\n') break; len++; } if (len >= sizeof(ipbuf)-1) len = sizeof(ipbuf) - 1; if (copy_from_user(ipbuf, buffer, len)) return -EFAULT; ipbuf[len] = 0; *ppos += *lenp; /* Now see if we can convert it to a valid IP */ ip = in_aton(ipbuf); *(unsigned int *)(table->data) = ip; lasat_write_eeprom_info(); } else { ip = *(unsigned int *)(table->data); sprintf(ipbuf, "%d.%d.%d.%d", (ip) & 0xff, (ip >> 8) & 0xff, (ip >> 16) & 0xff, (ip >> 24) & 0xff); len = strlen(ipbuf); if (len > *lenp) len = *lenp; if (len) if (copy_to_user(buffer, ipbuf, len)) return -EFAULT; if (len < *lenp) { if (put_user('\n', ((char *) buffer) + len)) return -EFAULT; len++; } *lenp = len; *ppos += len; } return 0; } #endif int proc_lasat_prid(ctl_table *table, int write, void *buffer, size_t *lenp, loff_t *ppos) { int r; r = proc_dointvec(table, write, buffer, lenp, ppos); if (r < 0) return r; if (write) { lasat_board_info.li_eeprom_info.prid = lasat_board_info.li_prid; lasat_write_eeprom_info(); lasat_init_board_info(); } return 0; } extern int lasat_boot_to_service; static ctl_table lasat_table[] = { { .procname = "cpu-hz", .data = &lasat_board_info.li_cpu_hz, .maxlen = sizeof(int), .mode = 0444, .proc_handler = proc_dointvec, }, { .procname = "bus-hz", .data = &lasat_board_info.li_bus_hz, .maxlen = sizeof(int), .mode = 0444, .proc_handler = proc_dointvec, }, { .procname = "bmid", .data = &lasat_board_info.li_bmid, .maxlen = sizeof(int), .mode = 0444, .proc_handler = proc_dointvec, }, { .procname = "prid", .data = &lasat_board_info.li_prid, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_lasat_prid, }, #ifdef CONFIG_INET { .procname = "ipaddr", .data = &lasat_board_info.li_eeprom_info.ipaddr, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_lasat_ip, }, { .procname = "netmask", .data = &lasat_board_info.li_eeprom_info.netmask, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_lasat_ip, }, #endif { .procname = "passwd_hash", .data = &lasat_board_info.li_eeprom_info.passwd_hash, .maxlen = sizeof(lasat_board_info.li_eeprom_info.passwd_hash), .mode = 0600, .proc_handler = proc_dolasatstring, }, { .procname = "boot-service", .data = &lasat_boot_to_service, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, #ifdef CONFIG_DS1603 { .procname = "rtc", .data = &rtctmp, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dolasatrtc, }, #endif { .procname = "namestr", .data = &lasat_board_info.li_namestr, .maxlen = sizeof(lasat_board_info.li_namestr), .mode = 0444, .proc_handler = proc_dostring, }, { .procname = "typestr", .data = &lasat_board_info.li_typestr, .maxlen = sizeof(lasat_board_info.li_typestr), .mode = 0444, .proc_handler = proc_dostring, }, {} }; static ctl_table lasat_root_table[] = { { .procname = "lasat", .mode = 0555, .child = lasat_table }, {} }; static int __init lasat_register_sysctl(void) { struct ctl_table_header *lasat_table_header; lasat_table_header = register_sysctl_table(lasat_root_table); if (!lasat_table_header) { printk(KERN_ERR "Unable to register LASAT sysctl\n"); return -ENOMEM; } return 0; } __initcall(lasat_register_sysctl);
gpl-2.0
AlmightyMegadeth00/kernel_tegra
sound/soc/samsung/littlemill.c
2768
8114
/* * Littlemill audio support * * Copyright 2011 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; either version 2 of the License, or (at your * option) any later version. */ #include <sound/soc.h> #include <sound/soc-dapm.h> #include <sound/jack.h> #include <linux/gpio.h> #include <linux/module.h> #include "../codecs/wm8994.h" static int sample_rate = 44100; static int littlemill_set_bias_level(struct snd_soc_card *card, struct snd_soc_dapm_context *dapm, enum snd_soc_bias_level level) { struct snd_soc_dai *aif1_dai = card->rtd[0].codec_dai; int ret; if (dapm->dev != aif1_dai->dev) return 0; switch (level) { case SND_SOC_BIAS_PREPARE: /* * If we've not already clocked things via hw_params() * then do so now, otherwise these are noops. */ if (dapm->bias_level == SND_SOC_BIAS_STANDBY) { ret = snd_soc_dai_set_pll(aif1_dai, WM8994_FLL1, WM8994_FLL_SRC_MCLK2, 32768, sample_rate * 512); if (ret < 0) { pr_err("Failed to start FLL: %d\n", ret); return ret; } ret = snd_soc_dai_set_sysclk(aif1_dai, WM8994_SYSCLK_FLL1, sample_rate * 512, SND_SOC_CLOCK_IN); if (ret < 0) { pr_err("Failed to set SYSCLK: %d\n", ret); return ret; } } break; default: break; } return 0; } static int littlemill_set_bias_level_post(struct snd_soc_card *card, struct snd_soc_dapm_context *dapm, enum snd_soc_bias_level level) { struct snd_soc_dai *aif1_dai = card->rtd[0].codec_dai; int ret; if (dapm->dev != aif1_dai->dev) return 0; switch (level) { case SND_SOC_BIAS_STANDBY: ret = snd_soc_dai_set_sysclk(aif1_dai, WM8994_SYSCLK_MCLK2, 32768, SND_SOC_CLOCK_IN); if (ret < 0) { pr_err("Failed to switch away from FLL1: %d\n", ret); return ret; } ret = snd_soc_dai_set_pll(aif1_dai, WM8994_FLL1, 0, 0, 0); if (ret < 0) { pr_err("Failed to stop FLL1: %d\n", ret); return ret; } break; default: break; } dapm->bias_level = level; return 0; } static int littlemill_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_dai *codec_dai = rtd->codec_dai; int ret; sample_rate = params_rate(params); ret = snd_soc_dai_set_pll(codec_dai, WM8994_FLL1, WM8994_FLL_SRC_MCLK2, 32768, sample_rate * 512); if (ret < 0) { pr_err("Failed to start FLL: %d\n", ret); return ret; } ret = snd_soc_dai_set_sysclk(codec_dai, WM8994_SYSCLK_FLL1, sample_rate * 512, SND_SOC_CLOCK_IN); if (ret < 0) { pr_err("Failed to set SYSCLK: %d\n", ret); return ret; } return 0; } static struct snd_soc_ops littlemill_ops = { .hw_params = littlemill_hw_params, }; static const struct snd_soc_pcm_stream baseband_params = { .formats = SNDRV_PCM_FMTBIT_S32_LE, .rate_min = 8000, .rate_max = 8000, .channels_min = 2, .channels_max = 2, }; static struct snd_soc_dai_link littlemill_dai[] = { { .name = "CPU", .stream_name = "CPU", .cpu_dai_name = "samsung-i2s.0", .codec_dai_name = "wm8994-aif1", .platform_name = "samsung-i2s.0", .codec_name = "wm8994-codec", .dai_fmt = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_CBM_CFM, .ops = &littlemill_ops, }, { .name = "Baseband", .stream_name = "Baseband", .cpu_dai_name = "wm8994-aif2", .codec_dai_name = "wm1250-ev1", .codec_name = "wm1250-ev1.1-0027", .dai_fmt = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_CBM_CFM, .ignore_suspend = 1, .params = &baseband_params, }, }; static int bbclk_ev(struct snd_soc_dapm_widget *w, struct snd_kcontrol *kcontrol, int event) { struct snd_soc_card *card = w->dapm->card; struct snd_soc_dai *aif2_dai = card->rtd[1].cpu_dai; int ret; switch (event) { case SND_SOC_DAPM_PRE_PMU: ret = snd_soc_dai_set_pll(aif2_dai, WM8994_FLL2, WM8994_FLL_SRC_BCLK, 64 * 8000, 8000 * 256); if (ret < 0) { pr_err("Failed to start FLL: %d\n", ret); return ret; } ret = snd_soc_dai_set_sysclk(aif2_dai, WM8994_SYSCLK_FLL2, 8000 * 256, SND_SOC_CLOCK_IN); if (ret < 0) { pr_err("Failed to set SYSCLK: %d\n", ret); return ret; } break; case SND_SOC_DAPM_POST_PMD: ret = snd_soc_dai_set_sysclk(aif2_dai, WM8994_SYSCLK_MCLK2, 32768, SND_SOC_CLOCK_IN); if (ret < 0) { pr_err("Failed to switch away from FLL2: %d\n", ret); return ret; } ret = snd_soc_dai_set_pll(aif2_dai, WM8994_FLL2, 0, 0, 0); if (ret < 0) { pr_err("Failed to stop FLL2: %d\n", ret); return ret; } break; default: return -EINVAL; } return 0; } static const struct snd_kcontrol_new controls[] = { SOC_DAPM_PIN_SWITCH("WM1250 Input"), SOC_DAPM_PIN_SWITCH("WM1250 Output"), }; static struct snd_soc_dapm_widget widgets[] = { SND_SOC_DAPM_HP("Headphone", NULL), SND_SOC_DAPM_MIC("AMIC", NULL), SND_SOC_DAPM_MIC("DMIC", NULL), SND_SOC_DAPM_SUPPLY_S("Baseband Clock", -1, SND_SOC_NOPM, 0, 0, bbclk_ev, SND_SOC_DAPM_PRE_PMU | SND_SOC_DAPM_POST_PMD), }; static struct snd_soc_dapm_route audio_paths[] = { { "Headphone", NULL, "HPOUT1L" }, { "Headphone", NULL, "HPOUT1R" }, { "AMIC", NULL, "MICBIAS1" }, /* Default for AMICBIAS jumper */ { "IN1LN", NULL, "AMIC" }, { "DMIC", NULL, "MICBIAS2" }, /* Default for DMICBIAS jumper */ { "DMIC1DAT", NULL, "DMIC" }, { "DMIC2DAT", NULL, "DMIC" }, { "AIF2CLK", NULL, "Baseband Clock" }, }; static struct snd_soc_jack littlemill_headset; static int littlemill_late_probe(struct snd_soc_card *card) { struct snd_soc_codec *codec = card->rtd[0].codec; struct snd_soc_dai *aif1_dai = card->rtd[0].codec_dai; struct snd_soc_dai *aif2_dai = card->rtd[1].cpu_dai; int ret; ret = snd_soc_dai_set_sysclk(aif1_dai, WM8994_SYSCLK_MCLK2, 32768, SND_SOC_CLOCK_IN); if (ret < 0) return ret; ret = snd_soc_dai_set_sysclk(aif2_dai, WM8994_SYSCLK_MCLK2, 32768, SND_SOC_CLOCK_IN); if (ret < 0) return ret; ret = snd_soc_jack_new(codec, "Headset", SND_JACK_HEADSET | SND_JACK_MECHANICAL | SND_JACK_BTN_0 | SND_JACK_BTN_1 | SND_JACK_BTN_2 | SND_JACK_BTN_3 | SND_JACK_BTN_4 | SND_JACK_BTN_5, &littlemill_headset); if (ret) return ret; /* This will check device compatibility itself */ wm8958_mic_detect(codec, &littlemill_headset, NULL, NULL, NULL, NULL); /* As will this */ wm8994_mic_detect(codec, &littlemill_headset, 1); return 0; } static struct snd_soc_card littlemill = { .name = "Littlemill", .owner = THIS_MODULE, .dai_link = littlemill_dai, .num_links = ARRAY_SIZE(littlemill_dai), .set_bias_level = littlemill_set_bias_level, .set_bias_level_post = littlemill_set_bias_level_post, .controls = controls, .num_controls = ARRAY_SIZE(controls), .dapm_widgets = widgets, .num_dapm_widgets = ARRAY_SIZE(widgets), .dapm_routes = audio_paths, .num_dapm_routes = ARRAY_SIZE(audio_paths), .late_probe = littlemill_late_probe, }; static int littlemill_probe(struct platform_device *pdev) { struct snd_soc_card *card = &littlemill; int ret; card->dev = &pdev->dev; ret = snd_soc_register_card(card); if (ret) { dev_err(&pdev->dev, "snd_soc_register_card() failed: %d\n", ret); return ret; } return 0; } static int littlemill_remove(struct platform_device *pdev) { struct snd_soc_card *card = platform_get_drvdata(pdev); snd_soc_unregister_card(card); return 0; } static struct platform_driver littlemill_driver = { .driver = { .name = "littlemill", .owner = THIS_MODULE, .pm = &snd_soc_pm_ops, }, .probe = littlemill_probe, .remove = littlemill_remove, }; module_platform_driver(littlemill_driver); MODULE_DESCRIPTION("Littlemill audio support"); MODULE_AUTHOR("Mark Brown <broonie@opensource.wolfsonmicro.com>"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:littlemill");
gpl-2.0
hallovveen31/smooth
sound/soc/codecs/wm8971.c
3024
22907
/* * wm8971.c -- WM8971 ALSA SoC Audio driver * * Copyright 2005 Lab126, Inc. * * Author: Kenneth Kiraly <kiraly@lab126.com> * * Based on wm8753.c by Liam Girdwood * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/init.h> #include <linux/delay.h> #include <linux/pm.h> #include <linux/i2c.h> #include <linux/platform_device.h> #include <linux/slab.h> #include <sound/core.h> #include <sound/pcm.h> #include <sound/pcm_params.h> #include <sound/soc.h> #include <sound/initval.h> #include "wm8971.h" #define WM8971_REG_COUNT 43 static struct workqueue_struct *wm8971_workq = NULL; /* codec private data */ struct wm8971_priv { enum snd_soc_control_type control_type; unsigned int sysclk; }; /* * wm8971 register cache * We can't read the WM8971 register space when we * are using 2 wire for device control, so we cache them instead. */ static const u16 wm8971_reg[] = { 0x0097, 0x0097, 0x0079, 0x0079, /* 0 */ 0x0000, 0x0008, 0x0000, 0x000a, /* 4 */ 0x0000, 0x0000, 0x00ff, 0x00ff, /* 8 */ 0x000f, 0x000f, 0x0000, 0x0000, /* 12 */ 0x0000, 0x007b, 0x0000, 0x0032, /* 16 */ 0x0000, 0x00c3, 0x00c3, 0x00c0, /* 20 */ 0x0000, 0x0000, 0x0000, 0x0000, /* 24 */ 0x0000, 0x0000, 0x0000, 0x0000, /* 28 */ 0x0000, 0x0000, 0x0050, 0x0050, /* 32 */ 0x0050, 0x0050, 0x0050, 0x0050, /* 36 */ 0x0079, 0x0079, 0x0079, /* 40 */ }; #define wm8971_reset(c) snd_soc_write(c, WM8971_RESET, 0) /* WM8971 Controls */ static const char *wm8971_bass[] = { "Linear Control", "Adaptive Boost" }; static const char *wm8971_bass_filter[] = { "130Hz @ 48kHz", "200Hz @ 48kHz" }; static const char *wm8971_treble[] = { "8kHz", "4kHz" }; static const char *wm8971_alc_func[] = { "Off", "Right", "Left", "Stereo" }; static const char *wm8971_ng_type[] = { "Constant PGA Gain", "Mute ADC Output" }; static const char *wm8971_deemp[] = { "None", "32kHz", "44.1kHz", "48kHz" }; static const char *wm8971_mono_mux[] = {"Stereo", "Mono (Left)", "Mono (Right)", "Digital Mono"}; static const char *wm8971_dac_phase[] = { "Non Inverted", "Inverted" }; static const char *wm8971_lline_mux[] = {"Line", "NC", "NC", "PGA", "Differential"}; static const char *wm8971_rline_mux[] = {"Line", "Mic", "NC", "PGA", "Differential"}; static const char *wm8971_lpga_sel[] = {"Line", "NC", "NC", "Differential"}; static const char *wm8971_rpga_sel[] = {"Line", "Mic", "NC", "Differential"}; static const char *wm8971_adcpol[] = {"Normal", "L Invert", "R Invert", "L + R Invert"}; static const struct soc_enum wm8971_enum[] = { SOC_ENUM_SINGLE(WM8971_BASS, 7, 2, wm8971_bass), /* 0 */ SOC_ENUM_SINGLE(WM8971_BASS, 6, 2, wm8971_bass_filter), SOC_ENUM_SINGLE(WM8971_TREBLE, 6, 2, wm8971_treble), SOC_ENUM_SINGLE(WM8971_ALC1, 7, 4, wm8971_alc_func), SOC_ENUM_SINGLE(WM8971_NGATE, 1, 2, wm8971_ng_type), /* 4 */ SOC_ENUM_SINGLE(WM8971_ADCDAC, 1, 4, wm8971_deemp), SOC_ENUM_SINGLE(WM8971_ADCTL1, 4, 4, wm8971_mono_mux), SOC_ENUM_SINGLE(WM8971_ADCTL1, 1, 2, wm8971_dac_phase), SOC_ENUM_SINGLE(WM8971_LOUTM1, 0, 5, wm8971_lline_mux), /* 8 */ SOC_ENUM_SINGLE(WM8971_ROUTM1, 0, 5, wm8971_rline_mux), SOC_ENUM_SINGLE(WM8971_LADCIN, 6, 4, wm8971_lpga_sel), SOC_ENUM_SINGLE(WM8971_RADCIN, 6, 4, wm8971_rpga_sel), SOC_ENUM_SINGLE(WM8971_ADCDAC, 5, 4, wm8971_adcpol), /* 12 */ SOC_ENUM_SINGLE(WM8971_ADCIN, 6, 4, wm8971_mono_mux), }; static const struct snd_kcontrol_new wm8971_snd_controls[] = { SOC_DOUBLE_R("Capture Volume", WM8971_LINVOL, WM8971_RINVOL, 0, 63, 0), SOC_DOUBLE_R("Capture ZC Switch", WM8971_LINVOL, WM8971_RINVOL, 6, 1, 0), SOC_DOUBLE_R("Capture Switch", WM8971_LINVOL, WM8971_RINVOL, 7, 1, 1), SOC_DOUBLE_R("Headphone Playback ZC Switch", WM8971_LOUT1V, WM8971_ROUT1V, 7, 1, 0), SOC_DOUBLE_R("Speaker Playback ZC Switch", WM8971_LOUT2V, WM8971_ROUT2V, 7, 1, 0), SOC_SINGLE("Mono Playback ZC Switch", WM8971_MOUTV, 7, 1, 0), SOC_DOUBLE_R("PCM Volume", WM8971_LDAC, WM8971_RDAC, 0, 255, 0), SOC_DOUBLE_R("Bypass Left Playback Volume", WM8971_LOUTM1, WM8971_LOUTM2, 4, 7, 1), SOC_DOUBLE_R("Bypass Right Playback Volume", WM8971_ROUTM1, WM8971_ROUTM2, 4, 7, 1), SOC_DOUBLE_R("Bypass Mono Playback Volume", WM8971_MOUTM1, WM8971_MOUTM2, 4, 7, 1), SOC_DOUBLE_R("Headphone Playback Volume", WM8971_LOUT1V, WM8971_ROUT1V, 0, 127, 0), SOC_DOUBLE_R("Speaker Playback Volume", WM8971_LOUT2V, WM8971_ROUT2V, 0, 127, 0), SOC_ENUM("Bass Boost", wm8971_enum[0]), SOC_ENUM("Bass Filter", wm8971_enum[1]), SOC_SINGLE("Bass Volume", WM8971_BASS, 0, 7, 1), SOC_SINGLE("Treble Volume", WM8971_TREBLE, 0, 7, 0), SOC_ENUM("Treble Cut-off", wm8971_enum[2]), SOC_SINGLE("Capture Filter Switch", WM8971_ADCDAC, 0, 1, 1), SOC_SINGLE("ALC Target Volume", WM8971_ALC1, 0, 7, 0), SOC_SINGLE("ALC Max Volume", WM8971_ALC1, 4, 7, 0), SOC_SINGLE("ALC Capture Target Volume", WM8971_ALC1, 0, 7, 0), SOC_SINGLE("ALC Capture Max Volume", WM8971_ALC1, 4, 7, 0), SOC_ENUM("ALC Capture Function", wm8971_enum[3]), SOC_SINGLE("ALC Capture ZC Switch", WM8971_ALC2, 7, 1, 0), SOC_SINGLE("ALC Capture Hold Time", WM8971_ALC2, 0, 15, 0), SOC_SINGLE("ALC Capture Decay Time", WM8971_ALC3, 4, 15, 0), SOC_SINGLE("ALC Capture Attack Time", WM8971_ALC3, 0, 15, 0), SOC_SINGLE("ALC Capture NG Threshold", WM8971_NGATE, 3, 31, 0), SOC_ENUM("ALC Capture NG Type", wm8971_enum[4]), SOC_SINGLE("ALC Capture NG Switch", WM8971_NGATE, 0, 1, 0), SOC_SINGLE("Capture 6dB Attenuate", WM8971_ADCDAC, 8, 1, 0), SOC_SINGLE("Playback 6dB Attenuate", WM8971_ADCDAC, 7, 1, 0), SOC_ENUM("Playback De-emphasis", wm8971_enum[5]), SOC_ENUM("Playback Function", wm8971_enum[6]), SOC_ENUM("Playback Phase", wm8971_enum[7]), SOC_DOUBLE_R("Mic Boost", WM8971_LADCIN, WM8971_RADCIN, 4, 3, 0), }; /* * DAPM Controls */ /* Left Mixer */ static const struct snd_kcontrol_new wm8971_left_mixer_controls[] = { SOC_DAPM_SINGLE("Playback Switch", WM8971_LOUTM1, 8, 1, 0), SOC_DAPM_SINGLE("Left Bypass Switch", WM8971_LOUTM1, 7, 1, 0), SOC_DAPM_SINGLE("Right Playback Switch", WM8971_LOUTM2, 8, 1, 0), SOC_DAPM_SINGLE("Right Bypass Switch", WM8971_LOUTM2, 7, 1, 0), }; /* Right Mixer */ static const struct snd_kcontrol_new wm8971_right_mixer_controls[] = { SOC_DAPM_SINGLE("Left Playback Switch", WM8971_ROUTM1, 8, 1, 0), SOC_DAPM_SINGLE("Left Bypass Switch", WM8971_ROUTM1, 7, 1, 0), SOC_DAPM_SINGLE("Playback Switch", WM8971_ROUTM2, 8, 1, 0), SOC_DAPM_SINGLE("Right Bypass Switch", WM8971_ROUTM2, 7, 1, 0), }; /* Mono Mixer */ static const struct snd_kcontrol_new wm8971_mono_mixer_controls[] = { SOC_DAPM_SINGLE("Left Playback Switch", WM8971_MOUTM1, 8, 1, 0), SOC_DAPM_SINGLE("Left Bypass Switch", WM8971_MOUTM1, 7, 1, 0), SOC_DAPM_SINGLE("Right Playback Switch", WM8971_MOUTM2, 8, 1, 0), SOC_DAPM_SINGLE("Right Bypass Switch", WM8971_MOUTM2, 7, 1, 0), }; /* Left Line Mux */ static const struct snd_kcontrol_new wm8971_left_line_controls = SOC_DAPM_ENUM("Route", wm8971_enum[8]); /* Right Line Mux */ static const struct snd_kcontrol_new wm8971_right_line_controls = SOC_DAPM_ENUM("Route", wm8971_enum[9]); /* Left PGA Mux */ static const struct snd_kcontrol_new wm8971_left_pga_controls = SOC_DAPM_ENUM("Route", wm8971_enum[10]); /* Right PGA Mux */ static const struct snd_kcontrol_new wm8971_right_pga_controls = SOC_DAPM_ENUM("Route", wm8971_enum[11]); /* Mono ADC Mux */ static const struct snd_kcontrol_new wm8971_monomux_controls = SOC_DAPM_ENUM("Route", wm8971_enum[13]); static const struct snd_soc_dapm_widget wm8971_dapm_widgets[] = { SND_SOC_DAPM_MIXER("Left Mixer", SND_SOC_NOPM, 0, 0, &wm8971_left_mixer_controls[0], ARRAY_SIZE(wm8971_left_mixer_controls)), SND_SOC_DAPM_MIXER("Right Mixer", SND_SOC_NOPM, 0, 0, &wm8971_right_mixer_controls[0], ARRAY_SIZE(wm8971_right_mixer_controls)), SND_SOC_DAPM_MIXER("Mono Mixer", WM8971_PWR2, 2, 0, &wm8971_mono_mixer_controls[0], ARRAY_SIZE(wm8971_mono_mixer_controls)), SND_SOC_DAPM_PGA("Right Out 2", WM8971_PWR2, 3, 0, NULL, 0), SND_SOC_DAPM_PGA("Left Out 2", WM8971_PWR2, 4, 0, NULL, 0), SND_SOC_DAPM_PGA("Right Out 1", WM8971_PWR2, 5, 0, NULL, 0), SND_SOC_DAPM_PGA("Left Out 1", WM8971_PWR2, 6, 0, NULL, 0), SND_SOC_DAPM_DAC("Right DAC", "Right Playback", WM8971_PWR2, 7, 0), SND_SOC_DAPM_DAC("Left DAC", "Left Playback", WM8971_PWR2, 8, 0), SND_SOC_DAPM_PGA("Mono Out 1", WM8971_PWR2, 2, 0, NULL, 0), SND_SOC_DAPM_MICBIAS("Mic Bias", WM8971_PWR1, 1, 0), SND_SOC_DAPM_ADC("Right ADC", "Right Capture", WM8971_PWR1, 2, 0), SND_SOC_DAPM_ADC("Left ADC", "Left Capture", WM8971_PWR1, 3, 0), SND_SOC_DAPM_MUX("Left PGA Mux", WM8971_PWR1, 5, 0, &wm8971_left_pga_controls), SND_SOC_DAPM_MUX("Right PGA Mux", WM8971_PWR1, 4, 0, &wm8971_right_pga_controls), SND_SOC_DAPM_MUX("Left Line Mux", SND_SOC_NOPM, 0, 0, &wm8971_left_line_controls), SND_SOC_DAPM_MUX("Right Line Mux", SND_SOC_NOPM, 0, 0, &wm8971_right_line_controls), SND_SOC_DAPM_MUX("Left ADC Mux", SND_SOC_NOPM, 0, 0, &wm8971_monomux_controls), SND_SOC_DAPM_MUX("Right ADC Mux", SND_SOC_NOPM, 0, 0, &wm8971_monomux_controls), SND_SOC_DAPM_OUTPUT("LOUT1"), SND_SOC_DAPM_OUTPUT("ROUT1"), SND_SOC_DAPM_OUTPUT("LOUT2"), SND_SOC_DAPM_OUTPUT("ROUT2"), SND_SOC_DAPM_OUTPUT("MONO"), SND_SOC_DAPM_INPUT("LINPUT1"), SND_SOC_DAPM_INPUT("RINPUT1"), SND_SOC_DAPM_INPUT("MIC"), }; static const struct snd_soc_dapm_route audio_map[] = { /* left mixer */ {"Left Mixer", "Playback Switch", "Left DAC"}, {"Left Mixer", "Left Bypass Switch", "Left Line Mux"}, {"Left Mixer", "Right Playback Switch", "Right DAC"}, {"Left Mixer", "Right Bypass Switch", "Right Line Mux"}, /* right mixer */ {"Right Mixer", "Left Playback Switch", "Left DAC"}, {"Right Mixer", "Left Bypass Switch", "Left Line Mux"}, {"Right Mixer", "Playback Switch", "Right DAC"}, {"Right Mixer", "Right Bypass Switch", "Right Line Mux"}, /* left out 1 */ {"Left Out 1", NULL, "Left Mixer"}, {"LOUT1", NULL, "Left Out 1"}, /* left out 2 */ {"Left Out 2", NULL, "Left Mixer"}, {"LOUT2", NULL, "Left Out 2"}, /* right out 1 */ {"Right Out 1", NULL, "Right Mixer"}, {"ROUT1", NULL, "Right Out 1"}, /* right out 2 */ {"Right Out 2", NULL, "Right Mixer"}, {"ROUT2", NULL, "Right Out 2"}, /* mono mixer */ {"Mono Mixer", "Left Playback Switch", "Left DAC"}, {"Mono Mixer", "Left Bypass Switch", "Left Line Mux"}, {"Mono Mixer", "Right Playback Switch", "Right DAC"}, {"Mono Mixer", "Right Bypass Switch", "Right Line Mux"}, /* mono out */ {"Mono Out", NULL, "Mono Mixer"}, {"MONO1", NULL, "Mono Out"}, /* Left Line Mux */ {"Left Line Mux", "Line", "LINPUT1"}, {"Left Line Mux", "PGA", "Left PGA Mux"}, {"Left Line Mux", "Differential", "Differential Mux"}, /* Right Line Mux */ {"Right Line Mux", "Line", "RINPUT1"}, {"Right Line Mux", "Mic", "MIC"}, {"Right Line Mux", "PGA", "Right PGA Mux"}, {"Right Line Mux", "Differential", "Differential Mux"}, /* Left PGA Mux */ {"Left PGA Mux", "Line", "LINPUT1"}, {"Left PGA Mux", "Differential", "Differential Mux"}, /* Right PGA Mux */ {"Right PGA Mux", "Line", "RINPUT1"}, {"Right PGA Mux", "Differential", "Differential Mux"}, /* Differential Mux */ {"Differential Mux", "Line", "LINPUT1"}, {"Differential Mux", "Line", "RINPUT1"}, /* Left ADC Mux */ {"Left ADC Mux", "Stereo", "Left PGA Mux"}, {"Left ADC Mux", "Mono (Left)", "Left PGA Mux"}, {"Left ADC Mux", "Digital Mono", "Left PGA Mux"}, /* Right ADC Mux */ {"Right ADC Mux", "Stereo", "Right PGA Mux"}, {"Right ADC Mux", "Mono (Right)", "Right PGA Mux"}, {"Right ADC Mux", "Digital Mono", "Right PGA Mux"}, /* ADC */ {"Left ADC", NULL, "Left ADC Mux"}, {"Right ADC", NULL, "Right ADC Mux"}, }; static int wm8971_add_widgets(struct snd_soc_codec *codec) { struct snd_soc_dapm_context *dapm = &codec->dapm; snd_soc_dapm_new_controls(dapm, wm8971_dapm_widgets, ARRAY_SIZE(wm8971_dapm_widgets)); snd_soc_dapm_add_routes(dapm, audio_map, ARRAY_SIZE(audio_map)); return 0; } struct _coeff_div { u32 mclk; u32 rate; u16 fs; u8 sr:5; u8 usb:1; }; /* codec hifi mclk clock divider coefficients */ static const struct _coeff_div coeff_div[] = { /* 8k */ {12288000, 8000, 1536, 0x6, 0x0}, {11289600, 8000, 1408, 0x16, 0x0}, {18432000, 8000, 2304, 0x7, 0x0}, {16934400, 8000, 2112, 0x17, 0x0}, {12000000, 8000, 1500, 0x6, 0x1}, /* 11.025k */ {11289600, 11025, 1024, 0x18, 0x0}, {16934400, 11025, 1536, 0x19, 0x0}, {12000000, 11025, 1088, 0x19, 0x1}, /* 16k */ {12288000, 16000, 768, 0xa, 0x0}, {18432000, 16000, 1152, 0xb, 0x0}, {12000000, 16000, 750, 0xa, 0x1}, /* 22.05k */ {11289600, 22050, 512, 0x1a, 0x0}, {16934400, 22050, 768, 0x1b, 0x0}, {12000000, 22050, 544, 0x1b, 0x1}, /* 32k */ {12288000, 32000, 384, 0xc, 0x0}, {18432000, 32000, 576, 0xd, 0x0}, {12000000, 32000, 375, 0xa, 0x1}, /* 44.1k */ {11289600, 44100, 256, 0x10, 0x0}, {16934400, 44100, 384, 0x11, 0x0}, {12000000, 44100, 272, 0x11, 0x1}, /* 48k */ {12288000, 48000, 256, 0x0, 0x0}, {18432000, 48000, 384, 0x1, 0x0}, {12000000, 48000, 250, 0x0, 0x1}, /* 88.2k */ {11289600, 88200, 128, 0x1e, 0x0}, {16934400, 88200, 192, 0x1f, 0x0}, {12000000, 88200, 136, 0x1f, 0x1}, /* 96k */ {12288000, 96000, 128, 0xe, 0x0}, {18432000, 96000, 192, 0xf, 0x0}, {12000000, 96000, 125, 0xe, 0x1}, }; static int get_coeff(int mclk, int rate) { int i; for (i = 0; i < ARRAY_SIZE(coeff_div); i++) { if (coeff_div[i].rate == rate && coeff_div[i].mclk == mclk) return i; } return -EINVAL; } static int wm8971_set_dai_sysclk(struct snd_soc_dai *codec_dai, int clk_id, unsigned int freq, int dir) { struct snd_soc_codec *codec = codec_dai->codec; struct wm8971_priv *wm8971 = snd_soc_codec_get_drvdata(codec); switch (freq) { case 11289600: case 12000000: case 12288000: case 16934400: case 18432000: wm8971->sysclk = freq; return 0; } return -EINVAL; } static int wm8971_set_dai_fmt(struct snd_soc_dai *codec_dai, unsigned int fmt) { struct snd_soc_codec *codec = codec_dai->codec; u16 iface = 0; /* set master/slave audio interface */ switch (fmt & SND_SOC_DAIFMT_MASTER_MASK) { case SND_SOC_DAIFMT_CBM_CFM: iface = 0x0040; break; case SND_SOC_DAIFMT_CBS_CFS: break; default: return -EINVAL; } /* interface format */ switch (fmt & SND_SOC_DAIFMT_FORMAT_MASK) { case SND_SOC_DAIFMT_I2S: iface |= 0x0002; break; case SND_SOC_DAIFMT_RIGHT_J: break; case SND_SOC_DAIFMT_LEFT_J: iface |= 0x0001; break; case SND_SOC_DAIFMT_DSP_A: iface |= 0x0003; break; case SND_SOC_DAIFMT_DSP_B: iface |= 0x0013; break; default: return -EINVAL; } /* clock inversion */ switch (fmt & SND_SOC_DAIFMT_INV_MASK) { case SND_SOC_DAIFMT_NB_NF: break; case SND_SOC_DAIFMT_IB_IF: iface |= 0x0090; break; case SND_SOC_DAIFMT_IB_NF: iface |= 0x0080; break; case SND_SOC_DAIFMT_NB_IF: iface |= 0x0010; break; default: return -EINVAL; } snd_soc_write(codec, WM8971_IFACE, iface); return 0; } static int wm8971_pcm_hw_params(struct snd_pcm_substream *substream, struct snd_pcm_hw_params *params, struct snd_soc_dai *dai) { struct snd_soc_pcm_runtime *rtd = substream->private_data; struct snd_soc_codec *codec = rtd->codec; struct wm8971_priv *wm8971 = snd_soc_codec_get_drvdata(codec); u16 iface = snd_soc_read(codec, WM8971_IFACE) & 0x1f3; u16 srate = snd_soc_read(codec, WM8971_SRATE) & 0x1c0; int coeff = get_coeff(wm8971->sysclk, params_rate(params)); /* bit size */ switch (params_format(params)) { case SNDRV_PCM_FORMAT_S16_LE: break; case SNDRV_PCM_FORMAT_S20_3LE: iface |= 0x0004; break; case SNDRV_PCM_FORMAT_S24_LE: iface |= 0x0008; break; case SNDRV_PCM_FORMAT_S32_LE: iface |= 0x000c; break; } /* set iface & srate */ snd_soc_write(codec, WM8971_IFACE, iface); if (coeff >= 0) snd_soc_write(codec, WM8971_SRATE, srate | (coeff_div[coeff].sr << 1) | coeff_div[coeff].usb); return 0; } static int wm8971_mute(struct snd_soc_dai *dai, int mute) { struct snd_soc_codec *codec = dai->codec; u16 mute_reg = snd_soc_read(codec, WM8971_ADCDAC) & 0xfff7; if (mute) snd_soc_write(codec, WM8971_ADCDAC, mute_reg | 0x8); else snd_soc_write(codec, WM8971_ADCDAC, mute_reg); return 0; } static int wm8971_set_bias_level(struct snd_soc_codec *codec, enum snd_soc_bias_level level) { u16 pwr_reg = snd_soc_read(codec, WM8971_PWR1) & 0xfe3e; switch (level) { case SND_SOC_BIAS_ON: /* set vmid to 50k and unmute dac */ snd_soc_write(codec, WM8971_PWR1, pwr_reg | 0x00c1); break; case SND_SOC_BIAS_PREPARE: break; case SND_SOC_BIAS_STANDBY: /* mute dac and set vmid to 500k, enable VREF */ snd_soc_write(codec, WM8971_PWR1, pwr_reg | 0x0140); break; case SND_SOC_BIAS_OFF: snd_soc_write(codec, WM8971_PWR1, 0x0001); break; } codec->dapm.bias_level = level; return 0; } #define WM8971_RATES (SNDRV_PCM_RATE_8000 | SNDRV_PCM_RATE_11025 |\ SNDRV_PCM_RATE_16000 | SNDRV_PCM_RATE_22050 | SNDRV_PCM_RATE_44100 | \ SNDRV_PCM_RATE_48000 | SNDRV_PCM_RATE_88200 | SNDRV_PCM_RATE_96000) #define WM8971_FORMATS (SNDRV_PCM_FMTBIT_S16_LE | SNDRV_PCM_FMTBIT_S20_3LE |\ SNDRV_PCM_FMTBIT_S24_LE) static struct snd_soc_dai_ops wm8971_dai_ops = { .hw_params = wm8971_pcm_hw_params, .digital_mute = wm8971_mute, .set_fmt = wm8971_set_dai_fmt, .set_sysclk = wm8971_set_dai_sysclk, }; static struct snd_soc_dai_driver wm8971_dai = { .name = "wm8971-hifi", .playback = { .stream_name = "Playback", .channels_min = 1, .channels_max = 2, .rates = WM8971_RATES, .formats = WM8971_FORMATS,}, .capture = { .stream_name = "Capture", .channels_min = 1, .channels_max = 2, .rates = WM8971_RATES, .formats = WM8971_FORMATS,}, .ops = &wm8971_dai_ops, }; static void wm8971_work(struct work_struct *work) { struct snd_soc_dapm_context *dapm = container_of(work, struct snd_soc_dapm_context, delayed_work.work); struct snd_soc_codec *codec = dapm->codec; wm8971_set_bias_level(codec, codec->dapm.bias_level); } static int wm8971_suspend(struct snd_soc_codec *codec, pm_message_t state) { wm8971_set_bias_level(codec, SND_SOC_BIAS_OFF); return 0; } static int wm8971_resume(struct snd_soc_codec *codec) { int i; u8 data[2]; u16 *cache = codec->reg_cache; u16 reg; /* Sync reg_cache with the hardware */ for (i = 0; i < ARRAY_SIZE(wm8971_reg); i++) { if (i + 1 == WM8971_RESET) continue; data[0] = (i << 1) | ((cache[i] >> 8) & 0x0001); data[1] = cache[i] & 0x00ff; codec->hw_write(codec->control_data, data, 2); } wm8971_set_bias_level(codec, SND_SOC_BIAS_STANDBY); /* charge wm8971 caps */ if (codec->dapm.suspend_bias_level == SND_SOC_BIAS_ON) { reg = snd_soc_read(codec, WM8971_PWR1) & 0xfe3e; snd_soc_write(codec, WM8971_PWR1, reg | 0x01c0); codec->dapm.bias_level = SND_SOC_BIAS_ON; queue_delayed_work(wm8971_workq, &codec->dapm.delayed_work, msecs_to_jiffies(1000)); } return 0; } static int wm8971_probe(struct snd_soc_codec *codec) { struct wm8971_priv *wm8971 = snd_soc_codec_get_drvdata(codec); int ret = 0; u16 reg; ret = snd_soc_codec_set_cache_io(codec, 7, 9, wm8971->control_type); if (ret < 0) { printk(KERN_ERR "wm8971: failed to set cache I/O: %d\n", ret); return ret; } INIT_DELAYED_WORK(&codec->dapm.delayed_work, wm8971_work); wm8971_workq = create_workqueue("wm8971"); if (wm8971_workq == NULL) return -ENOMEM; wm8971_reset(codec); /* charge output caps - set vmid to 5k for quick power up */ reg = snd_soc_read(codec, WM8971_PWR1) & 0xfe3e; snd_soc_write(codec, WM8971_PWR1, reg | 0x01c0); codec->dapm.bias_level = SND_SOC_BIAS_STANDBY; queue_delayed_work(wm8971_workq, &codec->dapm.delayed_work, msecs_to_jiffies(1000)); /* set the update bits */ reg = snd_soc_read(codec, WM8971_LDAC); snd_soc_write(codec, WM8971_LDAC, reg | 0x0100); reg = snd_soc_read(codec, WM8971_RDAC); snd_soc_write(codec, WM8971_RDAC, reg | 0x0100); reg = snd_soc_read(codec, WM8971_LOUT1V); snd_soc_write(codec, WM8971_LOUT1V, reg | 0x0100); reg = snd_soc_read(codec, WM8971_ROUT1V); snd_soc_write(codec, WM8971_ROUT1V, reg | 0x0100); reg = snd_soc_read(codec, WM8971_LOUT2V); snd_soc_write(codec, WM8971_LOUT2V, reg | 0x0100); reg = snd_soc_read(codec, WM8971_ROUT2V); snd_soc_write(codec, WM8971_ROUT2V, reg | 0x0100); reg = snd_soc_read(codec, WM8971_LINVOL); snd_soc_write(codec, WM8971_LINVOL, reg | 0x0100); reg = snd_soc_read(codec, WM8971_RINVOL); snd_soc_write(codec, WM8971_RINVOL, reg | 0x0100); snd_soc_add_controls(codec, wm8971_snd_controls, ARRAY_SIZE(wm8971_snd_controls)); wm8971_add_widgets(codec); return ret; } /* power down chip */ static int wm8971_remove(struct snd_soc_codec *codec) { wm8971_set_bias_level(codec, SND_SOC_BIAS_OFF); if (wm8971_workq) destroy_workqueue(wm8971_workq); return 0; } static struct snd_soc_codec_driver soc_codec_dev_wm8971 = { .probe = wm8971_probe, .remove = wm8971_remove, .suspend = wm8971_suspend, .resume = wm8971_resume, .set_bias_level = wm8971_set_bias_level, .reg_cache_size = ARRAY_SIZE(wm8971_reg), .reg_word_size = sizeof(u16), .reg_cache_default = wm8971_reg, }; #if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE) static __devinit int wm8971_i2c_probe(struct i2c_client *i2c, const struct i2c_device_id *id) { struct wm8971_priv *wm8971; int ret; wm8971 = kzalloc(sizeof(struct wm8971_priv), GFP_KERNEL); if (wm8971 == NULL) return -ENOMEM; wm8971->control_type = SND_SOC_I2C; i2c_set_clientdata(i2c, wm8971); ret = snd_soc_register_codec(&i2c->dev, &soc_codec_dev_wm8971, &wm8971_dai, 1); if (ret < 0) kfree(wm8971); return ret; } static __devexit int wm8971_i2c_remove(struct i2c_client *client) { snd_soc_unregister_codec(&client->dev); kfree(i2c_get_clientdata(client)); return 0; } static const struct i2c_device_id wm8971_i2c_id[] = { { "wm8971", 0 }, { } }; MODULE_DEVICE_TABLE(i2c, wm8971_i2c_id); static struct i2c_driver wm8971_i2c_driver = { .driver = { .name = "wm8971-codec", .owner = THIS_MODULE, }, .probe = wm8971_i2c_probe, .remove = __devexit_p(wm8971_i2c_remove), .id_table = wm8971_i2c_id, }; #endif static int __init wm8971_modinit(void) { int ret = 0; #if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE) ret = i2c_add_driver(&wm8971_i2c_driver); if (ret != 0) { printk(KERN_ERR "Failed to register WM8971 I2C driver: %d\n", ret); } #endif return ret; } module_init(wm8971_modinit); static void __exit wm8971_exit(void) { #if defined(CONFIG_I2C) || defined(CONFIG_I2C_MODULE) i2c_del_driver(&wm8971_i2c_driver); #endif } module_exit(wm8971_exit); MODULE_DESCRIPTION("ASoC WM8971 driver"); MODULE_AUTHOR("Lab126"); MODULE_LICENSE("GPL");
gpl-2.0
Smartandroidtech/platform_kernel_lge_hammerhead
drivers/usb/serial/ssu100.c
3280
16925
/* * usb-serial driver for Quatech SSU-100 * * based on ftdi_sio.c and the original serqt_usb.c from Quatech * */ #include <linux/errno.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/tty.h> #include <linux/tty_driver.h> #include <linux/tty_flip.h> #include <linux/module.h> #include <linux/serial.h> #include <linux/usb.h> #include <linux/usb/serial.h> #include <linux/serial_reg.h> #include <linux/uaccess.h> #define QT_OPEN_CLOSE_CHANNEL 0xca #define QT_SET_GET_DEVICE 0xc2 #define QT_SET_GET_REGISTER 0xc0 #define QT_GET_SET_PREBUF_TRIG_LVL 0xcc #define QT_SET_ATF 0xcd #define QT_GET_SET_UART 0xc1 #define QT_TRANSFER_IN 0xc0 #define QT_HW_FLOW_CONTROL_MASK 0xc5 #define QT_SW_FLOW_CONTROL_MASK 0xc6 #define SERIAL_MSR_MASK 0xf0 #define SERIAL_CRTSCTS ((UART_MCR_RTS << 8) | UART_MSR_CTS) #define SERIAL_EVEN_PARITY (UART_LCR_PARITY | UART_LCR_EPAR) #define MAX_BAUD_RATE 460800 #define ATC_DISABLED 0x00 #define DUPMODE_BITS 0xc0 #define RR_BITS 0x03 #define LOOPMODE_BITS 0x41 #define RS232_MODE 0x00 #define RTSCTS_TO_CONNECTOR 0x40 #define CLKS_X4 0x02 #define FULLPWRBIT 0x00000080 #define NEXT_BOARD_POWER_BIT 0x00000004 static bool debug; /* Version Information */ #define DRIVER_VERSION "v0.1" #define DRIVER_DESC "Quatech SSU-100 USB to Serial Driver" #define USB_VENDOR_ID_QUATECH 0x061d /* Quatech VID */ #define QUATECH_SSU100 0xC020 /* SSU100 */ static const struct usb_device_id id_table[] = { {USB_DEVICE(USB_VENDOR_ID_QUATECH, QUATECH_SSU100)}, {} /* Terminating entry */ }; MODULE_DEVICE_TABLE(usb, id_table); static struct usb_driver ssu100_driver = { .name = "ssu100", .probe = usb_serial_probe, .disconnect = usb_serial_disconnect, .id_table = id_table, .suspend = usb_serial_suspend, .resume = usb_serial_resume, .supports_autosuspend = 1, }; struct ssu100_port_private { spinlock_t status_lock; u8 shadowLSR; u8 shadowMSR; wait_queue_head_t delta_msr_wait; /* Used for TIOCMIWAIT */ struct async_icount icount; }; static void ssu100_release(struct usb_serial *serial) { struct ssu100_port_private *priv = usb_get_serial_port_data(*serial->port); dbg("%s", __func__); kfree(priv); } static inline int ssu100_control_msg(struct usb_device *dev, u8 request, u16 data, u16 index) { return usb_control_msg(dev, usb_sndctrlpipe(dev, 0), request, 0x40, data, index, NULL, 0, 300); } static inline int ssu100_setdevice(struct usb_device *dev, u8 *data) { u16 x = ((u16)(data[1] << 8) | (u16)(data[0])); return ssu100_control_msg(dev, QT_SET_GET_DEVICE, x, 0); } static inline int ssu100_getdevice(struct usb_device *dev, u8 *data) { return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0), QT_SET_GET_DEVICE, 0xc0, 0, 0, data, 3, 300); } static inline int ssu100_getregister(struct usb_device *dev, unsigned short uart, unsigned short reg, u8 *data) { return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0), QT_SET_GET_REGISTER, 0xc0, reg, uart, data, sizeof(*data), 300); } static inline int ssu100_setregister(struct usb_device *dev, unsigned short uart, unsigned short reg, u16 data) { u16 value = (data << 8) | reg; return usb_control_msg(dev, usb_sndctrlpipe(dev, 0), QT_SET_GET_REGISTER, 0x40, value, uart, NULL, 0, 300); } #define set_mctrl(dev, set) update_mctrl((dev), (set), 0) #define clear_mctrl(dev, clear) update_mctrl((dev), 0, (clear)) /* these do not deal with device that have more than 1 port */ static inline int update_mctrl(struct usb_device *dev, unsigned int set, unsigned int clear) { unsigned urb_value; int result; if (((set | clear) & (TIOCM_DTR | TIOCM_RTS)) == 0) { dbg("%s - DTR|RTS not being set|cleared", __func__); return 0; /* no change */ } clear &= ~set; /* 'set' takes precedence over 'clear' */ urb_value = 0; if (set & TIOCM_DTR) urb_value |= UART_MCR_DTR; if (set & TIOCM_RTS) urb_value |= UART_MCR_RTS; result = ssu100_setregister(dev, 0, UART_MCR, urb_value); if (result < 0) dbg("%s Error from MODEM_CTRL urb", __func__); return result; } static int ssu100_initdevice(struct usb_device *dev) { u8 *data; int result = 0; dbg("%s", __func__); data = kzalloc(3, GFP_KERNEL); if (!data) return -ENOMEM; result = ssu100_getdevice(dev, data); if (result < 0) { dbg("%s - get_device failed %i", __func__, result); goto out; } data[1] &= ~FULLPWRBIT; result = ssu100_setdevice(dev, data); if (result < 0) { dbg("%s - setdevice failed %i", __func__, result); goto out; } result = ssu100_control_msg(dev, QT_GET_SET_PREBUF_TRIG_LVL, 128, 0); if (result < 0) { dbg("%s - set prebuffer level failed %i", __func__, result); goto out; } result = ssu100_control_msg(dev, QT_SET_ATF, ATC_DISABLED, 0); if (result < 0) { dbg("%s - set ATFprebuffer level failed %i", __func__, result); goto out; } result = ssu100_getdevice(dev, data); if (result < 0) { dbg("%s - get_device failed %i", __func__, result); goto out; } data[0] &= ~(RR_BITS | DUPMODE_BITS); data[0] |= CLKS_X4; data[1] &= ~(LOOPMODE_BITS); data[1] |= RS232_MODE; result = ssu100_setdevice(dev, data); if (result < 0) { dbg("%s - setdevice failed %i", __func__, result); goto out; } out: kfree(data); return result; } static void ssu100_set_termios(struct tty_struct *tty, struct usb_serial_port *port, struct ktermios *old_termios) { struct usb_device *dev = port->serial->dev; struct ktermios *termios = tty->termios; u16 baud, divisor, remainder; unsigned int cflag = termios->c_cflag; u16 urb_value = 0; /* will hold the new flags */ int result; dbg("%s", __func__); if (cflag & PARENB) { if (cflag & PARODD) urb_value |= UART_LCR_PARITY; else urb_value |= SERIAL_EVEN_PARITY; } switch (cflag & CSIZE) { case CS5: urb_value |= UART_LCR_WLEN5; break; case CS6: urb_value |= UART_LCR_WLEN6; break; case CS7: urb_value |= UART_LCR_WLEN7; break; default: case CS8: urb_value |= UART_LCR_WLEN8; break; } baud = tty_get_baud_rate(tty); if (!baud) baud = 9600; dbg("%s - got baud = %d\n", __func__, baud); divisor = MAX_BAUD_RATE / baud; remainder = MAX_BAUD_RATE % baud; if (((remainder * 2) >= baud) && (baud != 110)) divisor++; urb_value = urb_value << 8; result = ssu100_control_msg(dev, QT_GET_SET_UART, divisor, urb_value); if (result < 0) dbg("%s - set uart failed", __func__); if (cflag & CRTSCTS) result = ssu100_control_msg(dev, QT_HW_FLOW_CONTROL_MASK, SERIAL_CRTSCTS, 0); else result = ssu100_control_msg(dev, QT_HW_FLOW_CONTROL_MASK, 0, 0); if (result < 0) dbg("%s - set HW flow control failed", __func__); if (I_IXOFF(tty) || I_IXON(tty)) { u16 x = ((u16)(START_CHAR(tty) << 8) | (u16)(STOP_CHAR(tty))); result = ssu100_control_msg(dev, QT_SW_FLOW_CONTROL_MASK, x, 0); } else result = ssu100_control_msg(dev, QT_SW_FLOW_CONTROL_MASK, 0, 0); if (result < 0) dbg("%s - set SW flow control failed", __func__); } static int ssu100_open(struct tty_struct *tty, struct usb_serial_port *port) { struct usb_device *dev = port->serial->dev; struct ssu100_port_private *priv = usb_get_serial_port_data(port); u8 *data; int result; unsigned long flags; dbg("%s - port %d", __func__, port->number); data = kzalloc(2, GFP_KERNEL); if (!data) return -ENOMEM; result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0), QT_OPEN_CLOSE_CHANNEL, QT_TRANSFER_IN, 0x01, 0, data, 2, 300); if (result < 0) { dbg("%s - open failed %i", __func__, result); kfree(data); return result; } spin_lock_irqsave(&priv->status_lock, flags); priv->shadowLSR = data[0]; priv->shadowMSR = data[1]; spin_unlock_irqrestore(&priv->status_lock, flags); kfree(data); /* set to 9600 */ result = ssu100_control_msg(dev, QT_GET_SET_UART, 0x30, 0x0300); if (result < 0) dbg("%s - set uart failed", __func__); if (tty) ssu100_set_termios(tty, port, tty->termios); return usb_serial_generic_open(tty, port); } static void ssu100_close(struct usb_serial_port *port) { dbg("%s", __func__); usb_serial_generic_close(port); } static int get_serial_info(struct usb_serial_port *port, struct serial_struct __user *retinfo) { struct serial_struct tmp; if (!retinfo) return -EFAULT; memset(&tmp, 0, sizeof(tmp)); tmp.line = port->serial->minor; tmp.port = 0; tmp.irq = 0; tmp.flags = ASYNC_SKIP_TEST | ASYNC_AUTO_IRQ; tmp.xmit_fifo_size = port->bulk_out_size; tmp.baud_base = 9600; tmp.close_delay = 5*HZ; tmp.closing_wait = 30*HZ; if (copy_to_user(retinfo, &tmp, sizeof(*retinfo))) return -EFAULT; return 0; } static int wait_modem_info(struct usb_serial_port *port, unsigned int arg) { struct ssu100_port_private *priv = usb_get_serial_port_data(port); struct async_icount prev, cur; unsigned long flags; spin_lock_irqsave(&priv->status_lock, flags); prev = priv->icount; spin_unlock_irqrestore(&priv->status_lock, flags); while (1) { wait_event_interruptible(priv->delta_msr_wait, ((priv->icount.rng != prev.rng) || (priv->icount.dsr != prev.dsr) || (priv->icount.dcd != prev.dcd) || (priv->icount.cts != prev.cts))); if (signal_pending(current)) return -ERESTARTSYS; spin_lock_irqsave(&priv->status_lock, flags); cur = priv->icount; spin_unlock_irqrestore(&priv->status_lock, flags); if ((prev.rng == cur.rng) && (prev.dsr == cur.dsr) && (prev.dcd == cur.dcd) && (prev.cts == cur.cts)) return -EIO; if ((arg & TIOCM_RNG && (prev.rng != cur.rng)) || (arg & TIOCM_DSR && (prev.dsr != cur.dsr)) || (arg & TIOCM_CD && (prev.dcd != cur.dcd)) || (arg & TIOCM_CTS && (prev.cts != cur.cts))) return 0; } return 0; } static int ssu100_get_icount(struct tty_struct *tty, struct serial_icounter_struct *icount) { struct usb_serial_port *port = tty->driver_data; struct ssu100_port_private *priv = usb_get_serial_port_data(port); struct async_icount cnow = priv->icount; icount->cts = cnow.cts; icount->dsr = cnow.dsr; icount->rng = cnow.rng; icount->dcd = cnow.dcd; icount->rx = cnow.rx; icount->tx = cnow.tx; icount->frame = cnow.frame; icount->overrun = cnow.overrun; icount->parity = cnow.parity; icount->brk = cnow.brk; icount->buf_overrun = cnow.buf_overrun; return 0; } static int ssu100_ioctl(struct tty_struct *tty, unsigned int cmd, unsigned long arg) { struct usb_serial_port *port = tty->driver_data; dbg("%s cmd 0x%04x", __func__, cmd); switch (cmd) { case TIOCGSERIAL: return get_serial_info(port, (struct serial_struct __user *) arg); case TIOCMIWAIT: return wait_modem_info(port, arg); default: break; } dbg("%s arg not supported", __func__); return -ENOIOCTLCMD; } static int ssu100_attach(struct usb_serial *serial) { struct ssu100_port_private *priv; struct usb_serial_port *port = *serial->port; dbg("%s", __func__); priv = kzalloc(sizeof(*priv), GFP_KERNEL); if (!priv) { dev_err(&port->dev, "%s- kmalloc(%Zd) failed.\n", __func__, sizeof(*priv)); return -ENOMEM; } spin_lock_init(&priv->status_lock); init_waitqueue_head(&priv->delta_msr_wait); usb_set_serial_port_data(port, priv); return ssu100_initdevice(serial->dev); } static int ssu100_tiocmget(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; struct usb_device *dev = port->serial->dev; u8 *d; int r; dbg("%s\n", __func__); d = kzalloc(2, GFP_KERNEL); if (!d) return -ENOMEM; r = ssu100_getregister(dev, 0, UART_MCR, d); if (r < 0) goto mget_out; r = ssu100_getregister(dev, 0, UART_MSR, d+1); if (r < 0) goto mget_out; r = (d[0] & UART_MCR_DTR ? TIOCM_DTR : 0) | (d[0] & UART_MCR_RTS ? TIOCM_RTS : 0) | (d[1] & UART_MSR_CTS ? TIOCM_CTS : 0) | (d[1] & UART_MSR_DCD ? TIOCM_CAR : 0) | (d[1] & UART_MSR_RI ? TIOCM_RI : 0) | (d[1] & UART_MSR_DSR ? TIOCM_DSR : 0); mget_out: kfree(d); return r; } static int ssu100_tiocmset(struct tty_struct *tty, unsigned int set, unsigned int clear) { struct usb_serial_port *port = tty->driver_data; struct usb_device *dev = port->serial->dev; dbg("%s\n", __func__); return update_mctrl(dev, set, clear); } static void ssu100_dtr_rts(struct usb_serial_port *port, int on) { struct usb_device *dev = port->serial->dev; dbg("%s\n", __func__); mutex_lock(&port->serial->disc_mutex); if (!port->serial->disconnected) { /* Disable flow control */ if (!on && ssu100_setregister(dev, 0, UART_MCR, 0) < 0) dev_err(&port->dev, "error from flowcontrol urb\n"); /* drop RTS and DTR */ if (on) set_mctrl(dev, TIOCM_DTR | TIOCM_RTS); else clear_mctrl(dev, TIOCM_DTR | TIOCM_RTS); } mutex_unlock(&port->serial->disc_mutex); } static void ssu100_update_msr(struct usb_serial_port *port, u8 msr) { struct ssu100_port_private *priv = usb_get_serial_port_data(port); unsigned long flags; spin_lock_irqsave(&priv->status_lock, flags); priv->shadowMSR = msr; spin_unlock_irqrestore(&priv->status_lock, flags); if (msr & UART_MSR_ANY_DELTA) { /* update input line counters */ if (msr & UART_MSR_DCTS) priv->icount.cts++; if (msr & UART_MSR_DDSR) priv->icount.dsr++; if (msr & UART_MSR_DDCD) priv->icount.dcd++; if (msr & UART_MSR_TERI) priv->icount.rng++; wake_up_interruptible(&priv->delta_msr_wait); } } static void ssu100_update_lsr(struct usb_serial_port *port, u8 lsr, char *tty_flag) { struct ssu100_port_private *priv = usb_get_serial_port_data(port); unsigned long flags; spin_lock_irqsave(&priv->status_lock, flags); priv->shadowLSR = lsr; spin_unlock_irqrestore(&priv->status_lock, flags); *tty_flag = TTY_NORMAL; if (lsr & UART_LSR_BRK_ERROR_BITS) { /* we always want to update icount, but we only want to * update tty_flag for one case */ if (lsr & UART_LSR_BI) { priv->icount.brk++; *tty_flag = TTY_BREAK; usb_serial_handle_break(port); } if (lsr & UART_LSR_PE) { priv->icount.parity++; if (*tty_flag == TTY_NORMAL) *tty_flag = TTY_PARITY; } if (lsr & UART_LSR_FE) { priv->icount.frame++; if (*tty_flag == TTY_NORMAL) *tty_flag = TTY_FRAME; } if (lsr & UART_LSR_OE){ priv->icount.overrun++; if (*tty_flag == TTY_NORMAL) *tty_flag = TTY_OVERRUN; } } } static int ssu100_process_packet(struct urb *urb, struct tty_struct *tty) { struct usb_serial_port *port = urb->context; char *packet = (char *)urb->transfer_buffer; char flag = TTY_NORMAL; u32 len = urb->actual_length; int i; char *ch; dbg("%s - port %d", __func__, port->number); if ((len >= 4) && (packet[0] == 0x1b) && (packet[1] == 0x1b) && ((packet[2] == 0x00) || (packet[2] == 0x01))) { if (packet[2] == 0x00) { ssu100_update_lsr(port, packet[3], &flag); if (flag == TTY_OVERRUN) tty_insert_flip_char(tty, 0, TTY_OVERRUN); } if (packet[2] == 0x01) ssu100_update_msr(port, packet[3]); len -= 4; ch = packet + 4; } else ch = packet; if (!len) return 0; /* status only */ if (port->port.console && port->sysrq) { for (i = 0; i < len; i++, ch++) { if (!usb_serial_handle_sysrq_char(port, *ch)) tty_insert_flip_char(tty, *ch, flag); } } else tty_insert_flip_string_fixed_flag(tty, ch, flag, len); return len; } static void ssu100_process_read_urb(struct urb *urb) { struct usb_serial_port *port = urb->context; struct tty_struct *tty; int count; dbg("%s", __func__); tty = tty_port_tty_get(&port->port); if (!tty) return; count = ssu100_process_packet(urb, tty); if (count) tty_flip_buffer_push(tty); tty_kref_put(tty); } static struct usb_serial_driver ssu100_device = { .driver = { .owner = THIS_MODULE, .name = "ssu100", }, .description = DRIVER_DESC, .id_table = id_table, .num_ports = 1, .open = ssu100_open, .close = ssu100_close, .attach = ssu100_attach, .release = ssu100_release, .dtr_rts = ssu100_dtr_rts, .process_read_urb = ssu100_process_read_urb, .tiocmget = ssu100_tiocmget, .tiocmset = ssu100_tiocmset, .get_icount = ssu100_get_icount, .ioctl = ssu100_ioctl, .set_termios = ssu100_set_termios, .disconnect = usb_serial_generic_disconnect, }; static struct usb_serial_driver * const serial_drivers[] = { &ssu100_device, NULL }; module_usb_serial_driver(ssu100_driver, serial_drivers); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); module_param(debug, bool, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(debug, "Debug enabled or not");
gpl-2.0
CyanogenMod/android_kernel_samsung_espresso10
drivers/net/arm/at91_ether.c
3536
37546
/* * Ethernet driver for the Atmel AT91RM9200 (Thunder) * * Copyright (C) 2003 SAN People (Pty) Ltd * * Based on an earlier Atmel EMAC macrocell driver by Atmel and Lineo Inc. * Initial version by Rick Bronson 01/11/2003 * * Intel LXT971A PHY support by Christopher Bahns & David Knickerbocker * (Polaroid Corporation) * * Realtek RTL8201(B)L PHY support by Roman Avramenko <roman@imsystems.ru> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/module.h> #include <linux/init.h> #include <linux/mii.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/skbuff.h> #include <linux/dma-mapping.h> #include <linux/ethtool.h> #include <linux/platform_device.h> #include <linux/clk.h> #include <linux/gfp.h> #include <asm/io.h> #include <asm/uaccess.h> #include <asm/mach-types.h> #include <mach/at91rm9200_emac.h> #include <mach/gpio.h> #include <mach/board.h> #include "at91_ether.h" #define DRV_NAME "at91_ether" #define DRV_VERSION "1.0" #define LINK_POLL_INTERVAL (HZ) /* ..................................................................... */ /* * Read from a EMAC register. */ static inline unsigned long at91_emac_read(unsigned int reg) { void __iomem *emac_base = (void __iomem *)AT91_VA_BASE_EMAC; return __raw_readl(emac_base + reg); } /* * Write to a EMAC register. */ static inline void at91_emac_write(unsigned int reg, unsigned long value) { void __iomem *emac_base = (void __iomem *)AT91_VA_BASE_EMAC; __raw_writel(value, emac_base + reg); } /* ........................... PHY INTERFACE ........................... */ /* * Enable the MDIO bit in MAC control register * When not called from an interrupt-handler, access to the PHY must be * protected by a spinlock. */ static void enable_mdi(void) { unsigned long ctl; ctl = at91_emac_read(AT91_EMAC_CTL); at91_emac_write(AT91_EMAC_CTL, ctl | AT91_EMAC_MPE); /* enable management port */ } /* * Disable the MDIO bit in the MAC control register */ static void disable_mdi(void) { unsigned long ctl; ctl = at91_emac_read(AT91_EMAC_CTL); at91_emac_write(AT91_EMAC_CTL, ctl & ~AT91_EMAC_MPE); /* disable management port */ } /* * Wait until the PHY operation is complete. */ static inline void at91_phy_wait(void) { unsigned long timeout = jiffies + 2; while (!(at91_emac_read(AT91_EMAC_SR) & AT91_EMAC_SR_IDLE)) { if (time_after(jiffies, timeout)) { printk("at91_ether: MIO timeout\n"); break; } cpu_relax(); } } /* * Write value to the a PHY register * Note: MDI interface is assumed to already have been enabled. */ static void write_phy(unsigned char phy_addr, unsigned char address, unsigned int value) { at91_emac_write(AT91_EMAC_MAN, AT91_EMAC_MAN_802_3 | AT91_EMAC_RW_W | ((phy_addr & 0x1f) << 23) | (address << 18) | (value & AT91_EMAC_DATA)); /* Wait until IDLE bit in Network Status register is cleared */ at91_phy_wait(); } /* * Read value stored in a PHY register. * Note: MDI interface is assumed to already have been enabled. */ static void read_phy(unsigned char phy_addr, unsigned char address, unsigned int *value) { at91_emac_write(AT91_EMAC_MAN, AT91_EMAC_MAN_802_3 | AT91_EMAC_RW_R | ((phy_addr & 0x1f) << 23) | (address << 18)); /* Wait until IDLE bit in Network Status register is cleared */ at91_phy_wait(); *value = at91_emac_read(AT91_EMAC_MAN) & AT91_EMAC_DATA; } /* ........................... PHY MANAGEMENT .......................... */ /* * Access the PHY to determine the current link speed and mode, and update the * MAC accordingly. * If no link or auto-negotiation is busy, then no changes are made. */ static void update_linkspeed(struct net_device *dev, int silent) { struct at91_private *lp = netdev_priv(dev); unsigned int bmsr, bmcr, lpa, mac_cfg; unsigned int speed, duplex; if (!mii_link_ok(&lp->mii)) { /* no link */ netif_carrier_off(dev); if (!silent) printk(KERN_INFO "%s: Link down.\n", dev->name); return; } /* Link up, or auto-negotiation still in progress */ read_phy(lp->phy_address, MII_BMSR, &bmsr); read_phy(lp->phy_address, MII_BMCR, &bmcr); if (bmcr & BMCR_ANENABLE) { /* AutoNegotiation is enabled */ if (!(bmsr & BMSR_ANEGCOMPLETE)) return; /* Do nothing - another interrupt generated when negotiation complete */ read_phy(lp->phy_address, MII_LPA, &lpa); if ((lpa & LPA_100FULL) || (lpa & LPA_100HALF)) speed = SPEED_100; else speed = SPEED_10; if ((lpa & LPA_100FULL) || (lpa & LPA_10FULL)) duplex = DUPLEX_FULL; else duplex = DUPLEX_HALF; } else { speed = (bmcr & BMCR_SPEED100) ? SPEED_100 : SPEED_10; duplex = (bmcr & BMCR_FULLDPLX) ? DUPLEX_FULL : DUPLEX_HALF; } /* Update the MAC */ mac_cfg = at91_emac_read(AT91_EMAC_CFG) & ~(AT91_EMAC_SPD | AT91_EMAC_FD); if (speed == SPEED_100) { if (duplex == DUPLEX_FULL) /* 100 Full Duplex */ mac_cfg |= AT91_EMAC_SPD | AT91_EMAC_FD; else /* 100 Half Duplex */ mac_cfg |= AT91_EMAC_SPD; } else { if (duplex == DUPLEX_FULL) /* 10 Full Duplex */ mac_cfg |= AT91_EMAC_FD; else {} /* 10 Half Duplex */ } at91_emac_write(AT91_EMAC_CFG, mac_cfg); if (!silent) printk(KERN_INFO "%s: Link now %i-%s\n", dev->name, speed, (duplex == DUPLEX_FULL) ? "FullDuplex" : "HalfDuplex"); netif_carrier_on(dev); } /* * Handle interrupts from the PHY */ static irqreturn_t at91ether_phy_interrupt(int irq, void *dev_id) { struct net_device *dev = (struct net_device *) dev_id; struct at91_private *lp = netdev_priv(dev); unsigned int phy; /* * This hander is triggered on both edges, but the PHY chips expect * level-triggering. We therefore have to check if the PHY actually has * an IRQ pending. */ enable_mdi(); if ((lp->phy_type == MII_DM9161_ID) || (lp->phy_type == MII_DM9161A_ID)) { read_phy(lp->phy_address, MII_DSINTR_REG, &phy); /* ack interrupt in Davicom PHY */ if (!(phy & (1 << 0))) goto done; } else if (lp->phy_type == MII_LXT971A_ID) { read_phy(lp->phy_address, MII_ISINTS_REG, &phy); /* ack interrupt in Intel PHY */ if (!(phy & (1 << 2))) goto done; } else if (lp->phy_type == MII_BCM5221_ID) { read_phy(lp->phy_address, MII_BCMINTR_REG, &phy); /* ack interrupt in Broadcom PHY */ if (!(phy & (1 << 0))) goto done; } else if (lp->phy_type == MII_KS8721_ID) { read_phy(lp->phy_address, MII_TPISTATUS, &phy); /* ack interrupt in Micrel PHY */ if (!(phy & ((1 << 2) | 1))) goto done; } else if (lp->phy_type == MII_T78Q21x3_ID) { /* ack interrupt in Teridian PHY */ read_phy(lp->phy_address, MII_T78Q21INT_REG, &phy); if (!(phy & ((1 << 2) | 1))) goto done; } else if (lp->phy_type == MII_DP83848_ID) { read_phy(lp->phy_address, MII_DPPHYSTS_REG, &phy); /* ack interrupt in DP83848 PHY */ if (!(phy & (1 << 7))) goto done; } update_linkspeed(dev, 0); done: disable_mdi(); return IRQ_HANDLED; } /* * Initialize and enable the PHY interrupt for link-state changes */ static void enable_phyirq(struct net_device *dev) { struct at91_private *lp = netdev_priv(dev); unsigned int dsintr, irq_number; int status; irq_number = lp->board_data.phy_irq_pin; if (!irq_number) { /* * PHY doesn't have an IRQ pin (RTL8201, DP83847, AC101L), * or board does not have it connected. */ mod_timer(&lp->check_timer, jiffies + LINK_POLL_INTERVAL); return; } status = request_irq(irq_number, at91ether_phy_interrupt, 0, dev->name, dev); if (status) { printk(KERN_ERR "at91_ether: PHY IRQ %d request failed - status %d!\n", irq_number, status); return; } spin_lock_irq(&lp->lock); enable_mdi(); if ((lp->phy_type == MII_DM9161_ID) || (lp->phy_type == MII_DM9161A_ID)) { /* for Davicom PHY */ read_phy(lp->phy_address, MII_DSINTR_REG, &dsintr); dsintr = dsintr & ~0xf00; /* clear bits 8..11 */ write_phy(lp->phy_address, MII_DSINTR_REG, dsintr); } else if (lp->phy_type == MII_LXT971A_ID) { /* for Intel PHY */ read_phy(lp->phy_address, MII_ISINTE_REG, &dsintr); dsintr = dsintr | 0xf2; /* set bits 1, 4..7 */ write_phy(lp->phy_address, MII_ISINTE_REG, dsintr); } else if (lp->phy_type == MII_BCM5221_ID) { /* for Broadcom PHY */ dsintr = (1 << 15) | ( 1 << 14); write_phy(lp->phy_address, MII_BCMINTR_REG, dsintr); } else if (lp->phy_type == MII_KS8721_ID) { /* for Micrel PHY */ dsintr = (1 << 10) | ( 1 << 8); write_phy(lp->phy_address, MII_TPISTATUS, dsintr); } else if (lp->phy_type == MII_T78Q21x3_ID) { /* for Teridian PHY */ read_phy(lp->phy_address, MII_T78Q21INT_REG, &dsintr); dsintr = dsintr | 0x500; /* set bits 8, 10 */ write_phy(lp->phy_address, MII_T78Q21INT_REG, dsintr); } else if (lp->phy_type == MII_DP83848_ID) { /* National Semiconductor DP83848 PHY */ read_phy(lp->phy_address, MII_DPMISR_REG, &dsintr); dsintr = dsintr | 0x3c; /* set bits 2..5 */ write_phy(lp->phy_address, MII_DPMISR_REG, dsintr); read_phy(lp->phy_address, MII_DPMICR_REG, &dsintr); dsintr = dsintr | 0x3; /* set bits 0,1 */ write_phy(lp->phy_address, MII_DPMICR_REG, dsintr); } disable_mdi(); spin_unlock_irq(&lp->lock); } /* * Disable the PHY interrupt */ static void disable_phyirq(struct net_device *dev) { struct at91_private *lp = netdev_priv(dev); unsigned int dsintr; unsigned int irq_number; irq_number = lp->board_data.phy_irq_pin; if (!irq_number) { del_timer_sync(&lp->check_timer); return; } spin_lock_irq(&lp->lock); enable_mdi(); if ((lp->phy_type == MII_DM9161_ID) || (lp->phy_type == MII_DM9161A_ID)) { /* for Davicom PHY */ read_phy(lp->phy_address, MII_DSINTR_REG, &dsintr); dsintr = dsintr | 0xf00; /* set bits 8..11 */ write_phy(lp->phy_address, MII_DSINTR_REG, dsintr); } else if (lp->phy_type == MII_LXT971A_ID) { /* for Intel PHY */ read_phy(lp->phy_address, MII_ISINTE_REG, &dsintr); dsintr = dsintr & ~0xf2; /* clear bits 1, 4..7 */ write_phy(lp->phy_address, MII_ISINTE_REG, dsintr); } else if (lp->phy_type == MII_BCM5221_ID) { /* for Broadcom PHY */ read_phy(lp->phy_address, MII_BCMINTR_REG, &dsintr); dsintr = ~(1 << 14); write_phy(lp->phy_address, MII_BCMINTR_REG, dsintr); } else if (lp->phy_type == MII_KS8721_ID) { /* for Micrel PHY */ read_phy(lp->phy_address, MII_TPISTATUS, &dsintr); dsintr = ~((1 << 10) | (1 << 8)); write_phy(lp->phy_address, MII_TPISTATUS, dsintr); } else if (lp->phy_type == MII_T78Q21x3_ID) { /* for Teridian PHY */ read_phy(lp->phy_address, MII_T78Q21INT_REG, &dsintr); dsintr = dsintr & ~0x500; /* clear bits 8, 10 */ write_phy(lp->phy_address, MII_T78Q21INT_REG, dsintr); } else if (lp->phy_type == MII_DP83848_ID) { /* National Semiconductor DP83848 PHY */ read_phy(lp->phy_address, MII_DPMICR_REG, &dsintr); dsintr = dsintr & ~0x3; /* clear bits 0, 1 */ write_phy(lp->phy_address, MII_DPMICR_REG, dsintr); read_phy(lp->phy_address, MII_DPMISR_REG, &dsintr); dsintr = dsintr & ~0x3c; /* clear bits 2..5 */ write_phy(lp->phy_address, MII_DPMISR_REG, dsintr); } disable_mdi(); spin_unlock_irq(&lp->lock); free_irq(irq_number, dev); /* Free interrupt handler */ } /* * Perform a software reset of the PHY. */ #if 0 static void reset_phy(struct net_device *dev) { struct at91_private *lp = netdev_priv(dev); unsigned int bmcr; spin_lock_irq(&lp->lock); enable_mdi(); /* Perform PHY reset */ write_phy(lp->phy_address, MII_BMCR, BMCR_RESET); /* Wait until PHY reset is complete */ do { read_phy(lp->phy_address, MII_BMCR, &bmcr); } while (!(bmcr & BMCR_RESET)); disable_mdi(); spin_unlock_irq(&lp->lock); } #endif static void at91ether_check_link(unsigned long dev_id) { struct net_device *dev = (struct net_device *) dev_id; struct at91_private *lp = netdev_priv(dev); enable_mdi(); update_linkspeed(dev, 1); disable_mdi(); mod_timer(&lp->check_timer, jiffies + LINK_POLL_INTERVAL); } /* ......................... ADDRESS MANAGEMENT ........................ */ /* * NOTE: Your bootloader must always set the MAC address correctly before * booting into Linux. * * - It must always set the MAC address after reset, even if it doesn't * happen to access the Ethernet while it's booting. Some versions of * U-Boot on the AT91RM9200-DK do not do this. * * - Likewise it must store the addresses in the correct byte order. * MicroMonitor (uMon) on the CSB337 does this incorrectly (and * continues to do so, for bug-compatibility). */ static short __init unpack_mac_address(struct net_device *dev, unsigned int hi, unsigned int lo) { char addr[6]; if (machine_is_csb337()) { addr[5] = (lo & 0xff); /* The CSB337 bootloader stores the MAC the wrong-way around */ addr[4] = (lo & 0xff00) >> 8; addr[3] = (lo & 0xff0000) >> 16; addr[2] = (lo & 0xff000000) >> 24; addr[1] = (hi & 0xff); addr[0] = (hi & 0xff00) >> 8; } else { addr[0] = (lo & 0xff); addr[1] = (lo & 0xff00) >> 8; addr[2] = (lo & 0xff0000) >> 16; addr[3] = (lo & 0xff000000) >> 24; addr[4] = (hi & 0xff); addr[5] = (hi & 0xff00) >> 8; } if (is_valid_ether_addr(addr)) { memcpy(dev->dev_addr, &addr, 6); return 1; } return 0; } /* * Set the ethernet MAC address in dev->dev_addr */ static void __init get_mac_address(struct net_device *dev) { /* Check Specific-Address 1 */ if (unpack_mac_address(dev, at91_emac_read(AT91_EMAC_SA1H), at91_emac_read(AT91_EMAC_SA1L))) return; /* Check Specific-Address 2 */ if (unpack_mac_address(dev, at91_emac_read(AT91_EMAC_SA2H), at91_emac_read(AT91_EMAC_SA2L))) return; /* Check Specific-Address 3 */ if (unpack_mac_address(dev, at91_emac_read(AT91_EMAC_SA3H), at91_emac_read(AT91_EMAC_SA3L))) return; /* Check Specific-Address 4 */ if (unpack_mac_address(dev, at91_emac_read(AT91_EMAC_SA4H), at91_emac_read(AT91_EMAC_SA4L))) return; printk(KERN_ERR "at91_ether: Your bootloader did not configure a MAC address.\n"); } /* * Program the hardware MAC address from dev->dev_addr. */ static void update_mac_address(struct net_device *dev) { at91_emac_write(AT91_EMAC_SA1L, (dev->dev_addr[3] << 24) | (dev->dev_addr[2] << 16) | (dev->dev_addr[1] << 8) | (dev->dev_addr[0])); at91_emac_write(AT91_EMAC_SA1H, (dev->dev_addr[5] << 8) | (dev->dev_addr[4])); at91_emac_write(AT91_EMAC_SA2L, 0); at91_emac_write(AT91_EMAC_SA2H, 0); } /* * Store the new hardware address in dev->dev_addr, and update the MAC. */ static int set_mac_address(struct net_device *dev, void* addr) { struct sockaddr *address = addr; if (!is_valid_ether_addr(address->sa_data)) return -EADDRNOTAVAIL; memcpy(dev->dev_addr, address->sa_data, dev->addr_len); update_mac_address(dev); printk("%s: Setting MAC address to %pM\n", dev->name, dev->dev_addr); return 0; } static int inline hash_bit_value(int bitnr, __u8 *addr) { if (addr[bitnr / 8] & (1 << (bitnr % 8))) return 1; return 0; } /* * The hash address register is 64 bits long and takes up two locations in the memory map. * The least significant bits are stored in EMAC_HSL and the most significant * bits in EMAC_HSH. * * The unicast hash enable and the multicast hash enable bits in the network configuration * register enable the reception of hash matched frames. The destination address is * reduced to a 6 bit index into the 64 bit hash register using the following hash function. * The hash function is an exclusive or of every sixth bit of the destination address. * hash_index[5] = da[5] ^ da[11] ^ da[17] ^ da[23] ^ da[29] ^ da[35] ^ da[41] ^ da[47] * hash_index[4] = da[4] ^ da[10] ^ da[16] ^ da[22] ^ da[28] ^ da[34] ^ da[40] ^ da[46] * hash_index[3] = da[3] ^ da[09] ^ da[15] ^ da[21] ^ da[27] ^ da[33] ^ da[39] ^ da[45] * hash_index[2] = da[2] ^ da[08] ^ da[14] ^ da[20] ^ da[26] ^ da[32] ^ da[38] ^ da[44] * hash_index[1] = da[1] ^ da[07] ^ da[13] ^ da[19] ^ da[25] ^ da[31] ^ da[37] ^ da[43] * hash_index[0] = da[0] ^ da[06] ^ da[12] ^ da[18] ^ da[24] ^ da[30] ^ da[36] ^ da[42] * da[0] represents the least significant bit of the first byte received, that is, the multicast/ * unicast indicator, and da[47] represents the most significant bit of the last byte * received. * If the hash index points to a bit that is set in the hash register then the frame will be * matched according to whether the frame is multicast or unicast. * A multicast match will be signalled if the multicast hash enable bit is set, da[0] is 1 and * the hash index points to a bit set in the hash register. * A unicast match will be signalled if the unicast hash enable bit is set, da[0] is 0 and the * hash index points to a bit set in the hash register. * To receive all multicast frames, the hash register should be set with all ones and the * multicast hash enable bit should be set in the network configuration register. */ /* * Return the hash index value for the specified address. */ static int hash_get_index(__u8 *addr) { int i, j, bitval; int hash_index = 0; for (j = 0; j < 6; j++) { for (i = 0, bitval = 0; i < 8; i++) bitval ^= hash_bit_value(i*6 + j, addr); hash_index |= (bitval << j); } return hash_index; } /* * Add multicast addresses to the internal multicast-hash table. */ static void at91ether_sethashtable(struct net_device *dev) { struct netdev_hw_addr *ha; unsigned long mc_filter[2]; unsigned int bitnr; mc_filter[0] = mc_filter[1] = 0; netdev_for_each_mc_addr(ha, dev) { bitnr = hash_get_index(ha->addr); mc_filter[bitnr >> 5] |= 1 << (bitnr & 31); } at91_emac_write(AT91_EMAC_HSL, mc_filter[0]); at91_emac_write(AT91_EMAC_HSH, mc_filter[1]); } /* * Enable/Disable promiscuous and multicast modes. */ static void at91ether_set_multicast_list(struct net_device *dev) { unsigned long cfg; cfg = at91_emac_read(AT91_EMAC_CFG); if (dev->flags & IFF_PROMISC) /* Enable promiscuous mode */ cfg |= AT91_EMAC_CAF; else if (dev->flags & (~IFF_PROMISC)) /* Disable promiscuous mode */ cfg &= ~AT91_EMAC_CAF; if (dev->flags & IFF_ALLMULTI) { /* Enable all multicast mode */ at91_emac_write(AT91_EMAC_HSH, -1); at91_emac_write(AT91_EMAC_HSL, -1); cfg |= AT91_EMAC_MTI; } else if (!netdev_mc_empty(dev)) { /* Enable specific multicasts */ at91ether_sethashtable(dev); cfg |= AT91_EMAC_MTI; } else if (dev->flags & (~IFF_ALLMULTI)) { /* Disable all multicast mode */ at91_emac_write(AT91_EMAC_HSH, 0); at91_emac_write(AT91_EMAC_HSL, 0); cfg &= ~AT91_EMAC_MTI; } at91_emac_write(AT91_EMAC_CFG, cfg); } /* ......................... ETHTOOL SUPPORT ........................... */ static int mdio_read(struct net_device *dev, int phy_id, int location) { unsigned int value; read_phy(phy_id, location, &value); return value; } static void mdio_write(struct net_device *dev, int phy_id, int location, int value) { write_phy(phy_id, location, value); } static int at91ether_get_settings(struct net_device *dev, struct ethtool_cmd *cmd) { struct at91_private *lp = netdev_priv(dev); int ret; spin_lock_irq(&lp->lock); enable_mdi(); ret = mii_ethtool_gset(&lp->mii, cmd); disable_mdi(); spin_unlock_irq(&lp->lock); if (lp->phy_media == PORT_FIBRE) { /* override media type since mii.c doesn't know */ cmd->supported = SUPPORTED_FIBRE; cmd->port = PORT_FIBRE; } return ret; } static int at91ether_set_settings(struct net_device *dev, struct ethtool_cmd *cmd) { struct at91_private *lp = netdev_priv(dev); int ret; spin_lock_irq(&lp->lock); enable_mdi(); ret = mii_ethtool_sset(&lp->mii, cmd); disable_mdi(); spin_unlock_irq(&lp->lock); return ret; } static int at91ether_nwayreset(struct net_device *dev) { struct at91_private *lp = netdev_priv(dev); int ret; spin_lock_irq(&lp->lock); enable_mdi(); ret = mii_nway_restart(&lp->mii); disable_mdi(); spin_unlock_irq(&lp->lock); return ret; } static void at91ether_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { strlcpy(info->driver, DRV_NAME, sizeof(info->driver)); strlcpy(info->version, DRV_VERSION, sizeof(info->version)); strlcpy(info->bus_info, dev_name(dev->dev.parent), sizeof(info->bus_info)); } static const struct ethtool_ops at91ether_ethtool_ops = { .get_settings = at91ether_get_settings, .set_settings = at91ether_set_settings, .get_drvinfo = at91ether_get_drvinfo, .nway_reset = at91ether_nwayreset, .get_link = ethtool_op_get_link, }; static int at91ether_ioctl(struct net_device *dev, struct ifreq *rq, int cmd) { struct at91_private *lp = netdev_priv(dev); int res; if (!netif_running(dev)) return -EINVAL; spin_lock_irq(&lp->lock); enable_mdi(); res = generic_mii_ioctl(&lp->mii, if_mii(rq), cmd, NULL); disable_mdi(); spin_unlock_irq(&lp->lock); return res; } /* ................................ MAC ................................ */ /* * Initialize and start the Receiver and Transmit subsystems */ static void at91ether_start(struct net_device *dev) { struct at91_private *lp = netdev_priv(dev); struct recv_desc_bufs *dlist, *dlist_phys; int i; unsigned long ctl; dlist = lp->dlist; dlist_phys = lp->dlist_phys; for (i = 0; i < MAX_RX_DESCR; i++) { dlist->descriptors[i].addr = (unsigned int) &dlist_phys->recv_buf[i][0]; dlist->descriptors[i].size = 0; } /* Set the Wrap bit on the last descriptor */ dlist->descriptors[i-1].addr |= EMAC_DESC_WRAP; /* Reset buffer index */ lp->rxBuffIndex = 0; /* Program address of descriptor list in Rx Buffer Queue register */ at91_emac_write(AT91_EMAC_RBQP, (unsigned long) dlist_phys); /* Enable Receive and Transmit */ ctl = at91_emac_read(AT91_EMAC_CTL); at91_emac_write(AT91_EMAC_CTL, ctl | AT91_EMAC_RE | AT91_EMAC_TE); } /* * Open the ethernet interface */ static int at91ether_open(struct net_device *dev) { struct at91_private *lp = netdev_priv(dev); unsigned long ctl; if (!is_valid_ether_addr(dev->dev_addr)) return -EADDRNOTAVAIL; clk_enable(lp->ether_clk); /* Re-enable Peripheral clock */ /* Clear internal statistics */ ctl = at91_emac_read(AT91_EMAC_CTL); at91_emac_write(AT91_EMAC_CTL, ctl | AT91_EMAC_CSR); /* Update the MAC address (incase user has changed it) */ update_mac_address(dev); /* Enable PHY interrupt */ enable_phyirq(dev); /* Enable MAC interrupts */ at91_emac_write(AT91_EMAC_IER, AT91_EMAC_RCOM | AT91_EMAC_RBNA | AT91_EMAC_TUND | AT91_EMAC_RTRY | AT91_EMAC_TCOM | AT91_EMAC_ROVR | AT91_EMAC_ABT); /* Determine current link speed */ spin_lock_irq(&lp->lock); enable_mdi(); update_linkspeed(dev, 0); disable_mdi(); spin_unlock_irq(&lp->lock); at91ether_start(dev); netif_start_queue(dev); return 0; } /* * Close the interface */ static int at91ether_close(struct net_device *dev) { struct at91_private *lp = netdev_priv(dev); unsigned long ctl; /* Disable Receiver and Transmitter */ ctl = at91_emac_read(AT91_EMAC_CTL); at91_emac_write(AT91_EMAC_CTL, ctl & ~(AT91_EMAC_TE | AT91_EMAC_RE)); /* Disable PHY interrupt */ disable_phyirq(dev); /* Disable MAC interrupts */ at91_emac_write(AT91_EMAC_IDR, AT91_EMAC_RCOM | AT91_EMAC_RBNA | AT91_EMAC_TUND | AT91_EMAC_RTRY | AT91_EMAC_TCOM | AT91_EMAC_ROVR | AT91_EMAC_ABT); netif_stop_queue(dev); clk_disable(lp->ether_clk); /* Disable Peripheral clock */ return 0; } /* * Transmit packet. */ static int at91ether_start_xmit(struct sk_buff *skb, struct net_device *dev) { struct at91_private *lp = netdev_priv(dev); if (at91_emac_read(AT91_EMAC_TSR) & AT91_EMAC_TSR_BNQ) { netif_stop_queue(dev); /* Store packet information (to free when Tx completed) */ lp->skb = skb; lp->skb_length = skb->len; lp->skb_physaddr = dma_map_single(NULL, skb->data, skb->len, DMA_TO_DEVICE); dev->stats.tx_bytes += skb->len; /* Set address of the data in the Transmit Address register */ at91_emac_write(AT91_EMAC_TAR, lp->skb_physaddr); /* Set length of the packet in the Transmit Control register */ at91_emac_write(AT91_EMAC_TCR, skb->len); } else { printk(KERN_ERR "at91_ether.c: at91ether_start_xmit() called, but device is busy!\n"); return NETDEV_TX_BUSY; /* if we return anything but zero, dev.c:1055 calls kfree_skb(skb) on this skb, he also reports -ENETDOWN and printk's, so either we free and return(0) or don't free and return 1 */ } return NETDEV_TX_OK; } /* * Update the current statistics from the internal statistics registers. */ static struct net_device_stats *at91ether_stats(struct net_device *dev) { int ale, lenerr, seqe, lcol, ecol; if (netif_running(dev)) { dev->stats.rx_packets += at91_emac_read(AT91_EMAC_OK); /* Good frames received */ ale = at91_emac_read(AT91_EMAC_ALE); dev->stats.rx_frame_errors += ale; /* Alignment errors */ lenerr = at91_emac_read(AT91_EMAC_ELR) + at91_emac_read(AT91_EMAC_USF); dev->stats.rx_length_errors += lenerr; /* Excessive Length or Undersize Frame error */ seqe = at91_emac_read(AT91_EMAC_SEQE); dev->stats.rx_crc_errors += seqe; /* CRC error */ dev->stats.rx_fifo_errors += at91_emac_read(AT91_EMAC_DRFC); /* Receive buffer not available */ dev->stats.rx_errors += (ale + lenerr + seqe + at91_emac_read(AT91_EMAC_CDE) + at91_emac_read(AT91_EMAC_RJB)); dev->stats.tx_packets += at91_emac_read(AT91_EMAC_FRA); /* Frames successfully transmitted */ dev->stats.tx_fifo_errors += at91_emac_read(AT91_EMAC_TUE); /* Transmit FIFO underruns */ dev->stats.tx_carrier_errors += at91_emac_read(AT91_EMAC_CSE); /* Carrier Sense errors */ dev->stats.tx_heartbeat_errors += at91_emac_read(AT91_EMAC_SQEE);/* Heartbeat error */ lcol = at91_emac_read(AT91_EMAC_LCOL); ecol = at91_emac_read(AT91_EMAC_ECOL); dev->stats.tx_window_errors += lcol; /* Late collisions */ dev->stats.tx_aborted_errors += ecol; /* 16 collisions */ dev->stats.collisions += (at91_emac_read(AT91_EMAC_SCOL) + at91_emac_read(AT91_EMAC_MCOL) + lcol + ecol); } return &dev->stats; } /* * Extract received frame from buffer descriptors and sent to upper layers. * (Called from interrupt context) */ static void at91ether_rx(struct net_device *dev) { struct at91_private *lp = netdev_priv(dev); struct recv_desc_bufs *dlist; unsigned char *p_recv; struct sk_buff *skb; unsigned int pktlen; dlist = lp->dlist; while (dlist->descriptors[lp->rxBuffIndex].addr & EMAC_DESC_DONE) { p_recv = dlist->recv_buf[lp->rxBuffIndex]; pktlen = dlist->descriptors[lp->rxBuffIndex].size & 0x7ff; /* Length of frame including FCS */ skb = dev_alloc_skb(pktlen + 2); if (skb != NULL) { skb_reserve(skb, 2); memcpy(skb_put(skb, pktlen), p_recv, pktlen); skb->protocol = eth_type_trans(skb, dev); dev->stats.rx_bytes += pktlen; netif_rx(skb); } else { dev->stats.rx_dropped += 1; printk(KERN_NOTICE "%s: Memory squeeze, dropping packet.\n", dev->name); } if (dlist->descriptors[lp->rxBuffIndex].size & EMAC_MULTICAST) dev->stats.multicast++; dlist->descriptors[lp->rxBuffIndex].addr &= ~EMAC_DESC_DONE; /* reset ownership bit */ if (lp->rxBuffIndex == MAX_RX_DESCR-1) /* wrap after last buffer */ lp->rxBuffIndex = 0; else lp->rxBuffIndex++; } } /* * MAC interrupt handler */ static irqreturn_t at91ether_interrupt(int irq, void *dev_id) { struct net_device *dev = (struct net_device *) dev_id; struct at91_private *lp = netdev_priv(dev); unsigned long intstatus, ctl; /* MAC Interrupt Status register indicates what interrupts are pending. It is automatically cleared once read. */ intstatus = at91_emac_read(AT91_EMAC_ISR); if (intstatus & AT91_EMAC_RCOM) /* Receive complete */ at91ether_rx(dev); if (intstatus & AT91_EMAC_TCOM) { /* Transmit complete */ /* The TCOM bit is set even if the transmission failed. */ if (intstatus & (AT91_EMAC_TUND | AT91_EMAC_RTRY)) dev->stats.tx_errors += 1; if (lp->skb) { dev_kfree_skb_irq(lp->skb); lp->skb = NULL; dma_unmap_single(NULL, lp->skb_physaddr, lp->skb_length, DMA_TO_DEVICE); } netif_wake_queue(dev); } /* Work-around for Errata #11 */ if (intstatus & AT91_EMAC_RBNA) { ctl = at91_emac_read(AT91_EMAC_CTL); at91_emac_write(AT91_EMAC_CTL, ctl & ~AT91_EMAC_RE); at91_emac_write(AT91_EMAC_CTL, ctl | AT91_EMAC_RE); } if (intstatus & AT91_EMAC_ROVR) printk("%s: ROVR error\n", dev->name); return IRQ_HANDLED; } #ifdef CONFIG_NET_POLL_CONTROLLER static void at91ether_poll_controller(struct net_device *dev) { unsigned long flags; local_irq_save(flags); at91ether_interrupt(dev->irq, dev); local_irq_restore(flags); } #endif static const struct net_device_ops at91ether_netdev_ops = { .ndo_open = at91ether_open, .ndo_stop = at91ether_close, .ndo_start_xmit = at91ether_start_xmit, .ndo_get_stats = at91ether_stats, .ndo_set_multicast_list = at91ether_set_multicast_list, .ndo_set_mac_address = set_mac_address, .ndo_do_ioctl = at91ether_ioctl, .ndo_validate_addr = eth_validate_addr, .ndo_change_mtu = eth_change_mtu, #ifdef CONFIG_NET_POLL_CONTROLLER .ndo_poll_controller = at91ether_poll_controller, #endif }; /* * Initialize the ethernet interface */ static int __init at91ether_setup(unsigned long phy_type, unsigned short phy_address, struct platform_device *pdev, struct clk *ether_clk) { struct at91_eth_data *board_data = pdev->dev.platform_data; struct net_device *dev; struct at91_private *lp; unsigned int val; int res; dev = alloc_etherdev(sizeof(struct at91_private)); if (!dev) return -ENOMEM; dev->base_addr = AT91_VA_BASE_EMAC; dev->irq = AT91RM9200_ID_EMAC; /* Install the interrupt handler */ if (request_irq(dev->irq, at91ether_interrupt, 0, dev->name, dev)) { free_netdev(dev); return -EBUSY; } /* Allocate memory for DMA Receive descriptors */ lp = netdev_priv(dev); lp->dlist = (struct recv_desc_bufs *) dma_alloc_coherent(NULL, sizeof(struct recv_desc_bufs), (dma_addr_t *) &lp->dlist_phys, GFP_KERNEL); if (lp->dlist == NULL) { free_irq(dev->irq, dev); free_netdev(dev); return -ENOMEM; } lp->board_data = *board_data; lp->ether_clk = ether_clk; platform_set_drvdata(pdev, dev); spin_lock_init(&lp->lock); ether_setup(dev); dev->netdev_ops = &at91ether_netdev_ops; dev->ethtool_ops = &at91ether_ethtool_ops; SET_NETDEV_DEV(dev, &pdev->dev); get_mac_address(dev); /* Get ethernet address and store it in dev->dev_addr */ update_mac_address(dev); /* Program ethernet address into MAC */ at91_emac_write(AT91_EMAC_CTL, 0); if (lp->board_data.is_rmii) at91_emac_write(AT91_EMAC_CFG, AT91_EMAC_CLK_DIV32 | AT91_EMAC_BIG | AT91_EMAC_RMII); else at91_emac_write(AT91_EMAC_CFG, AT91_EMAC_CLK_DIV32 | AT91_EMAC_BIG); /* Perform PHY-specific initialization */ spin_lock_irq(&lp->lock); enable_mdi(); if ((phy_type == MII_DM9161_ID) || (lp->phy_type == MII_DM9161A_ID)) { read_phy(phy_address, MII_DSCR_REG, &val); if ((val & (1 << 10)) == 0) /* DSCR bit 10 is 0 -- fiber mode */ lp->phy_media = PORT_FIBRE; } else if (machine_is_csb337()) { /* mix link activity status into LED2 link state */ write_phy(phy_address, MII_LEDCTRL_REG, 0x0d22); } else if (machine_is_ecbat91()) write_phy(phy_address, MII_LEDCTRL_REG, 0x156A); disable_mdi(); spin_unlock_irq(&lp->lock); lp->mii.dev = dev; /* Support for ethtool */ lp->mii.mdio_read = mdio_read; lp->mii.mdio_write = mdio_write; lp->mii.phy_id = phy_address; lp->mii.phy_id_mask = 0x1f; lp->mii.reg_num_mask = 0x1f; lp->phy_type = phy_type; /* Type of PHY connected */ lp->phy_address = phy_address; /* MDI address of PHY */ /* Register the network interface */ res = register_netdev(dev); if (res) { free_irq(dev->irq, dev); free_netdev(dev); dma_free_coherent(NULL, sizeof(struct recv_desc_bufs), lp->dlist, (dma_addr_t)lp->dlist_phys); return res; } /* Determine current link speed */ spin_lock_irq(&lp->lock); enable_mdi(); update_linkspeed(dev, 0); disable_mdi(); spin_unlock_irq(&lp->lock); netif_carrier_off(dev); /* will be enabled in open() */ /* If board has no PHY IRQ, use a timer to poll the PHY */ if (!lp->board_data.phy_irq_pin) { init_timer(&lp->check_timer); lp->check_timer.data = (unsigned long)dev; lp->check_timer.function = at91ether_check_link; } else if (lp->board_data.phy_irq_pin >= 32) gpio_request(lp->board_data.phy_irq_pin, "ethernet_phy"); /* Display ethernet banner */ printk(KERN_INFO "%s: AT91 ethernet at 0x%08x int=%d %s%s (%pM)\n", dev->name, (uint) dev->base_addr, dev->irq, at91_emac_read(AT91_EMAC_CFG) & AT91_EMAC_SPD ? "100-" : "10-", at91_emac_read(AT91_EMAC_CFG) & AT91_EMAC_FD ? "FullDuplex" : "HalfDuplex", dev->dev_addr); if ((phy_type == MII_DM9161_ID) || (lp->phy_type == MII_DM9161A_ID)) printk(KERN_INFO "%s: Davicom 9161 PHY %s\n", dev->name, (lp->phy_media == PORT_FIBRE) ? "(Fiber)" : "(Copper)"); else if (phy_type == MII_LXT971A_ID) printk(KERN_INFO "%s: Intel LXT971A PHY\n", dev->name); else if (phy_type == MII_RTL8201_ID) printk(KERN_INFO "%s: Realtek RTL8201(B)L PHY\n", dev->name); else if (phy_type == MII_BCM5221_ID) printk(KERN_INFO "%s: Broadcom BCM5221 PHY\n", dev->name); else if (phy_type == MII_DP83847_ID) printk(KERN_INFO "%s: National Semiconductor DP83847 PHY\n", dev->name); else if (phy_type == MII_DP83848_ID) printk(KERN_INFO "%s: National Semiconductor DP83848 PHY\n", dev->name); else if (phy_type == MII_AC101L_ID) printk(KERN_INFO "%s: Altima AC101L PHY\n", dev->name); else if (phy_type == MII_KS8721_ID) printk(KERN_INFO "%s: Micrel KS8721 PHY\n", dev->name); else if (phy_type == MII_T78Q21x3_ID) printk(KERN_INFO "%s: Teridian 78Q21x3 PHY\n", dev->name); else if (phy_type == MII_LAN83C185_ID) printk(KERN_INFO "%s: SMSC LAN83C185 PHY\n", dev->name); return 0; } /* * Detect MAC and PHY and perform initialization */ static int __init at91ether_probe(struct platform_device *pdev) { unsigned int phyid1, phyid2; int detected = -1; unsigned long phy_id; unsigned short phy_address = 0; struct clk *ether_clk; ether_clk = clk_get(&pdev->dev, "ether_clk"); if (IS_ERR(ether_clk)) { printk(KERN_ERR "at91_ether: no clock defined\n"); return -ENODEV; } clk_enable(ether_clk); /* Enable Peripheral clock */ while ((detected != 0) && (phy_address < 32)) { /* Read the PHY ID registers */ enable_mdi(); read_phy(phy_address, MII_PHYSID1, &phyid1); read_phy(phy_address, MII_PHYSID2, &phyid2); disable_mdi(); phy_id = (phyid1 << 16) | (phyid2 & 0xfff0); switch (phy_id) { case MII_DM9161_ID: /* Davicom 9161: PHY_ID1 = 0x181, PHY_ID2 = B881 */ case MII_DM9161A_ID: /* Davicom 9161A: PHY_ID1 = 0x181, PHY_ID2 = B8A0 */ case MII_LXT971A_ID: /* Intel LXT971A: PHY_ID1 = 0x13, PHY_ID2 = 78E0 */ case MII_RTL8201_ID: /* Realtek RTL8201: PHY_ID1 = 0, PHY_ID2 = 0x8201 */ case MII_BCM5221_ID: /* Broadcom BCM5221: PHY_ID1 = 0x40, PHY_ID2 = 0x61e0 */ case MII_DP83847_ID: /* National Semiconductor DP83847: */ case MII_DP83848_ID: /* National Semiconductor DP83848: */ case MII_AC101L_ID: /* Altima AC101L: PHY_ID1 = 0x22, PHY_ID2 = 0x5520 */ case MII_KS8721_ID: /* Micrel KS8721: PHY_ID1 = 0x22, PHY_ID2 = 0x1610 */ case MII_T78Q21x3_ID: /* Teridian 78Q21x3: PHY_ID1 = 0x0E, PHY_ID2 = 7237 */ case MII_LAN83C185_ID: /* SMSC LAN83C185: PHY_ID1 = 0x0007, PHY_ID2 = 0xC0A1 */ detected = at91ether_setup(phy_id, phy_address, pdev, ether_clk); break; } phy_address++; } clk_disable(ether_clk); /* Disable Peripheral clock */ return detected; } static int __devexit at91ether_remove(struct platform_device *pdev) { struct net_device *dev = platform_get_drvdata(pdev); struct at91_private *lp = netdev_priv(dev); if (lp->board_data.phy_irq_pin >= 32) gpio_free(lp->board_data.phy_irq_pin); unregister_netdev(dev); free_irq(dev->irq, dev); dma_free_coherent(NULL, sizeof(struct recv_desc_bufs), lp->dlist, (dma_addr_t)lp->dlist_phys); clk_put(lp->ether_clk); platform_set_drvdata(pdev, NULL); free_netdev(dev); return 0; } #ifdef CONFIG_PM static int at91ether_suspend(struct platform_device *pdev, pm_message_t mesg) { struct net_device *net_dev = platform_get_drvdata(pdev); struct at91_private *lp = netdev_priv(net_dev); int phy_irq = lp->board_data.phy_irq_pin; if (netif_running(net_dev)) { if (phy_irq) disable_irq(phy_irq); netif_stop_queue(net_dev); netif_device_detach(net_dev); clk_disable(lp->ether_clk); } return 0; } static int at91ether_resume(struct platform_device *pdev) { struct net_device *net_dev = platform_get_drvdata(pdev); struct at91_private *lp = netdev_priv(net_dev); int phy_irq = lp->board_data.phy_irq_pin; if (netif_running(net_dev)) { clk_enable(lp->ether_clk); netif_device_attach(net_dev); netif_start_queue(net_dev); if (phy_irq) enable_irq(phy_irq); } return 0; } #else #define at91ether_suspend NULL #define at91ether_resume NULL #endif static struct platform_driver at91ether_driver = { .remove = __devexit_p(at91ether_remove), .suspend = at91ether_suspend, .resume = at91ether_resume, .driver = { .name = DRV_NAME, .owner = THIS_MODULE, }, }; static int __init at91ether_init(void) { return platform_driver_probe(&at91ether_driver, at91ether_probe); } static void __exit at91ether_exit(void) { platform_driver_unregister(&at91ether_driver); } module_init(at91ether_init) module_exit(at91ether_exit) MODULE_LICENSE("GPL"); MODULE_DESCRIPTION("AT91RM9200 EMAC Ethernet driver"); MODULE_AUTHOR("Andrew Victor"); MODULE_ALIAS("platform:" DRV_NAME);
gpl-2.0
novic/AniDroid-Kernel-N7000
arch/powerpc/kernel/pmc.c
3792
2380
/* * arch/powerpc/kernel/pmc.c * * Copyright (C) 2004 David Gibson, IBM Corporation. * Includes code formerly from arch/ppc/kernel/perfmon.c: * Author: Andy Fleming * Copyright (c) 2004 Freescale Semiconductor, Inc * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #include <linux/errno.h> #include <linux/spinlock.h> #include <linux/module.h> #include <asm/processor.h> #include <asm/cputable.h> #include <asm/pmc.h> #ifndef MMCR0_PMAO #define MMCR0_PMAO 0 #endif static void dummy_perf(struct pt_regs *regs) { #if defined(CONFIG_FSL_EMB_PERFMON) mtpmr(PMRN_PMGC0, mfpmr(PMRN_PMGC0) & ~PMGC0_PMIE); #elif defined(CONFIG_PPC64) || defined(CONFIG_6xx) if (cur_cpu_spec->pmc_type == PPC_PMC_IBM) mtspr(SPRN_MMCR0, mfspr(SPRN_MMCR0) & ~(MMCR0_PMXE|MMCR0_PMAO)); #else mtspr(SPRN_MMCR0, mfspr(SPRN_MMCR0) & ~MMCR0_PMXE); #endif } static DEFINE_RAW_SPINLOCK(pmc_owner_lock); static void *pmc_owner_caller; /* mostly for debugging */ perf_irq_t perf_irq = dummy_perf; int reserve_pmc_hardware(perf_irq_t new_perf_irq) { int err = 0; raw_spin_lock(&pmc_owner_lock); if (pmc_owner_caller) { printk(KERN_WARNING "reserve_pmc_hardware: " "PMC hardware busy (reserved by caller %p)\n", pmc_owner_caller); err = -EBUSY; goto out; } pmc_owner_caller = __builtin_return_address(0); perf_irq = new_perf_irq ? new_perf_irq : dummy_perf; out: raw_spin_unlock(&pmc_owner_lock); return err; } EXPORT_SYMBOL_GPL(reserve_pmc_hardware); void release_pmc_hardware(void) { raw_spin_lock(&pmc_owner_lock); WARN_ON(! pmc_owner_caller); pmc_owner_caller = NULL; perf_irq = dummy_perf; raw_spin_unlock(&pmc_owner_lock); } EXPORT_SYMBOL_GPL(release_pmc_hardware); #ifdef CONFIG_PPC64 void power4_enable_pmcs(void) { unsigned long hid0; hid0 = mfspr(SPRN_HID0); hid0 |= 1UL << (63 - 20); /* POWER4 requires the following sequence */ asm volatile( "sync\n" "mtspr %1, %0\n" "mfspr %0, %1\n" "mfspr %0, %1\n" "mfspr %0, %1\n" "mfspr %0, %1\n" "mfspr %0, %1\n" "mfspr %0, %1\n" "isync" : "=&r" (hid0) : "i" (SPRN_HID0), "0" (hid0): "memory"); } #endif /* CONFIG_PPC64 */
gpl-2.0
kodos96/backport
arch/powerpc/sysdev/qe_lib/usb.c
4560
1694
/* * QE USB routines * * Copyright (c) Freescale Semicondutor, Inc. 2006. * Shlomi Gridish <gridish@freescale.com> * Jerry Huang <Chang-Ming.Huang@freescale.com> * Copyright (c) MontaVista Software, Inc. 2008. * Anton Vorontsov <avorontsov@ru.mvista.com> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. */ #include <linux/kernel.h> #include <linux/errno.h> #include <linux/io.h> #include <asm/immap_qe.h> #include <asm/qe.h> int qe_usb_clock_set(enum qe_clock clk, int rate) { struct qe_mux __iomem *mux = &qe_immr->qmx; unsigned long flags; u32 val; switch (clk) { case QE_CLK3: val = QE_CMXGCR_USBCS_CLK3; break; case QE_CLK5: val = QE_CMXGCR_USBCS_CLK5; break; case QE_CLK7: val = QE_CMXGCR_USBCS_CLK7; break; case QE_CLK9: val = QE_CMXGCR_USBCS_CLK9; break; case QE_CLK13: val = QE_CMXGCR_USBCS_CLK13; break; case QE_CLK17: val = QE_CMXGCR_USBCS_CLK17; break; case QE_CLK19: val = QE_CMXGCR_USBCS_CLK19; break; case QE_CLK21: val = QE_CMXGCR_USBCS_CLK21; break; case QE_BRG9: val = QE_CMXGCR_USBCS_BRG9; break; case QE_BRG10: val = QE_CMXGCR_USBCS_BRG10; break; default: pr_err("%s: requested unknown clock %d\n", __func__, clk); return -EINVAL; } if (qe_clock_is_brg(clk)) qe_setbrg(clk, rate, 1); spin_lock_irqsave(&cmxgcr_lock, flags); clrsetbits_be32(&mux->cmxgcr, QE_CMXGCR_USBCS, val); spin_unlock_irqrestore(&cmxgcr_lock, flags); return 0; } EXPORT_SYMBOL(qe_usb_clock_set);
gpl-2.0
RenderBroken/msm8974_OPO-CAF_render_kernel
drivers/net/ethernet/sfc/mcdi_phy.c
4816
21262
/**************************************************************************** * Driver for Solarflare Solarstorm network controllers and boards * Copyright 2009-2010 Solarflare Communications Inc. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation, incorporated herein by reference. */ /* * Driver for PHY related operations via MCDI. */ #include <linux/slab.h> #include "efx.h" #include "phy.h" #include "mcdi.h" #include "mcdi_pcol.h" #include "nic.h" #include "selftest.h" struct efx_mcdi_phy_data { u32 flags; u32 type; u32 supported_cap; u32 channel; u32 port; u32 stats_mask; u8 name[20]; u32 media; u32 mmd_mask; u8 revision[20]; u32 forced_cap; }; static int efx_mcdi_get_phy_cfg(struct efx_nic *efx, struct efx_mcdi_phy_data *cfg) { u8 outbuf[MC_CMD_GET_PHY_CFG_OUT_LEN]; size_t outlen; int rc; BUILD_BUG_ON(MC_CMD_GET_PHY_CFG_IN_LEN != 0); BUILD_BUG_ON(MC_CMD_GET_PHY_CFG_OUT_NAME_LEN != sizeof(cfg->name)); rc = efx_mcdi_rpc(efx, MC_CMD_GET_PHY_CFG, NULL, 0, outbuf, sizeof(outbuf), &outlen); if (rc) goto fail; if (outlen < MC_CMD_GET_PHY_CFG_OUT_LEN) { rc = -EIO; goto fail; } cfg->flags = MCDI_DWORD(outbuf, GET_PHY_CFG_OUT_FLAGS); cfg->type = MCDI_DWORD(outbuf, GET_PHY_CFG_OUT_TYPE); cfg->supported_cap = MCDI_DWORD(outbuf, GET_PHY_CFG_OUT_SUPPORTED_CAP); cfg->channel = MCDI_DWORD(outbuf, GET_PHY_CFG_OUT_CHANNEL); cfg->port = MCDI_DWORD(outbuf, GET_PHY_CFG_OUT_PRT); cfg->stats_mask = MCDI_DWORD(outbuf, GET_PHY_CFG_OUT_STATS_MASK); memcpy(cfg->name, MCDI_PTR(outbuf, GET_PHY_CFG_OUT_NAME), sizeof(cfg->name)); cfg->media = MCDI_DWORD(outbuf, GET_PHY_CFG_OUT_MEDIA_TYPE); cfg->mmd_mask = MCDI_DWORD(outbuf, GET_PHY_CFG_OUT_MMD_MASK); memcpy(cfg->revision, MCDI_PTR(outbuf, GET_PHY_CFG_OUT_REVISION), sizeof(cfg->revision)); return 0; fail: netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc); return rc; } static int efx_mcdi_set_link(struct efx_nic *efx, u32 capabilities, u32 flags, u32 loopback_mode, u32 loopback_speed) { u8 inbuf[MC_CMD_SET_LINK_IN_LEN]; int rc; BUILD_BUG_ON(MC_CMD_SET_LINK_OUT_LEN != 0); MCDI_SET_DWORD(inbuf, SET_LINK_IN_CAP, capabilities); MCDI_SET_DWORD(inbuf, SET_LINK_IN_FLAGS, flags); MCDI_SET_DWORD(inbuf, SET_LINK_IN_LOOPBACK_MODE, loopback_mode); MCDI_SET_DWORD(inbuf, SET_LINK_IN_LOOPBACK_SPEED, loopback_speed); rc = efx_mcdi_rpc(efx, MC_CMD_SET_LINK, inbuf, sizeof(inbuf), NULL, 0, NULL); if (rc) goto fail; return 0; fail: netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc); return rc; } static int efx_mcdi_loopback_modes(struct efx_nic *efx, u64 *loopback_modes) { u8 outbuf[MC_CMD_GET_LOOPBACK_MODES_OUT_LEN]; size_t outlen; int rc; rc = efx_mcdi_rpc(efx, MC_CMD_GET_LOOPBACK_MODES, NULL, 0, outbuf, sizeof(outbuf), &outlen); if (rc) goto fail; if (outlen < MC_CMD_GET_LOOPBACK_MODES_OUT_LEN) { rc = -EIO; goto fail; } *loopback_modes = MCDI_QWORD(outbuf, GET_LOOPBACK_MODES_OUT_SUGGESTED); return 0; fail: netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc); return rc; } int efx_mcdi_mdio_read(struct efx_nic *efx, unsigned int bus, unsigned int prtad, unsigned int devad, u16 addr, u16 *value_out, u32 *status_out) { u8 inbuf[MC_CMD_MDIO_READ_IN_LEN]; u8 outbuf[MC_CMD_MDIO_READ_OUT_LEN]; size_t outlen; int rc; MCDI_SET_DWORD(inbuf, MDIO_READ_IN_BUS, bus); MCDI_SET_DWORD(inbuf, MDIO_READ_IN_PRTAD, prtad); MCDI_SET_DWORD(inbuf, MDIO_READ_IN_DEVAD, devad); MCDI_SET_DWORD(inbuf, MDIO_READ_IN_ADDR, addr); rc = efx_mcdi_rpc(efx, MC_CMD_MDIO_READ, inbuf, sizeof(inbuf), outbuf, sizeof(outbuf), &outlen); if (rc) goto fail; *value_out = (u16)MCDI_DWORD(outbuf, MDIO_READ_OUT_VALUE); *status_out = MCDI_DWORD(outbuf, MDIO_READ_OUT_STATUS); return 0; fail: netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc); return rc; } int efx_mcdi_mdio_write(struct efx_nic *efx, unsigned int bus, unsigned int prtad, unsigned int devad, u16 addr, u16 value, u32 *status_out) { u8 inbuf[MC_CMD_MDIO_WRITE_IN_LEN]; u8 outbuf[MC_CMD_MDIO_WRITE_OUT_LEN]; size_t outlen; int rc; MCDI_SET_DWORD(inbuf, MDIO_WRITE_IN_BUS, bus); MCDI_SET_DWORD(inbuf, MDIO_WRITE_IN_PRTAD, prtad); MCDI_SET_DWORD(inbuf, MDIO_WRITE_IN_DEVAD, devad); MCDI_SET_DWORD(inbuf, MDIO_WRITE_IN_ADDR, addr); MCDI_SET_DWORD(inbuf, MDIO_WRITE_IN_VALUE, value); rc = efx_mcdi_rpc(efx, MC_CMD_MDIO_WRITE, inbuf, sizeof(inbuf), outbuf, sizeof(outbuf), &outlen); if (rc) goto fail; *status_out = MCDI_DWORD(outbuf, MDIO_WRITE_OUT_STATUS); return 0; fail: netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc); return rc; } static u32 mcdi_to_ethtool_cap(u32 media, u32 cap) { u32 result = 0; switch (media) { case MC_CMD_MEDIA_KX4: result |= SUPPORTED_Backplane; if (cap & (1 << MC_CMD_PHY_CAP_1000FDX_LBN)) result |= SUPPORTED_1000baseKX_Full; if (cap & (1 << MC_CMD_PHY_CAP_10000FDX_LBN)) result |= SUPPORTED_10000baseKX4_Full; break; case MC_CMD_MEDIA_XFP: case MC_CMD_MEDIA_SFP_PLUS: result |= SUPPORTED_FIBRE; break; case MC_CMD_MEDIA_BASE_T: result |= SUPPORTED_TP; if (cap & (1 << MC_CMD_PHY_CAP_10HDX_LBN)) result |= SUPPORTED_10baseT_Half; if (cap & (1 << MC_CMD_PHY_CAP_10FDX_LBN)) result |= SUPPORTED_10baseT_Full; if (cap & (1 << MC_CMD_PHY_CAP_100HDX_LBN)) result |= SUPPORTED_100baseT_Half; if (cap & (1 << MC_CMD_PHY_CAP_100FDX_LBN)) result |= SUPPORTED_100baseT_Full; if (cap & (1 << MC_CMD_PHY_CAP_1000HDX_LBN)) result |= SUPPORTED_1000baseT_Half; if (cap & (1 << MC_CMD_PHY_CAP_1000FDX_LBN)) result |= SUPPORTED_1000baseT_Full; if (cap & (1 << MC_CMD_PHY_CAP_10000FDX_LBN)) result |= SUPPORTED_10000baseT_Full; break; } if (cap & (1 << MC_CMD_PHY_CAP_PAUSE_LBN)) result |= SUPPORTED_Pause; if (cap & (1 << MC_CMD_PHY_CAP_ASYM_LBN)) result |= SUPPORTED_Asym_Pause; if (cap & (1 << MC_CMD_PHY_CAP_AN_LBN)) result |= SUPPORTED_Autoneg; return result; } static u32 ethtool_to_mcdi_cap(u32 cap) { u32 result = 0; if (cap & SUPPORTED_10baseT_Half) result |= (1 << MC_CMD_PHY_CAP_10HDX_LBN); if (cap & SUPPORTED_10baseT_Full) result |= (1 << MC_CMD_PHY_CAP_10FDX_LBN); if (cap & SUPPORTED_100baseT_Half) result |= (1 << MC_CMD_PHY_CAP_100HDX_LBN); if (cap & SUPPORTED_100baseT_Full) result |= (1 << MC_CMD_PHY_CAP_100FDX_LBN); if (cap & SUPPORTED_1000baseT_Half) result |= (1 << MC_CMD_PHY_CAP_1000HDX_LBN); if (cap & (SUPPORTED_1000baseT_Full | SUPPORTED_1000baseKX_Full)) result |= (1 << MC_CMD_PHY_CAP_1000FDX_LBN); if (cap & (SUPPORTED_10000baseT_Full | SUPPORTED_10000baseKX4_Full)) result |= (1 << MC_CMD_PHY_CAP_10000FDX_LBN); if (cap & SUPPORTED_Pause) result |= (1 << MC_CMD_PHY_CAP_PAUSE_LBN); if (cap & SUPPORTED_Asym_Pause) result |= (1 << MC_CMD_PHY_CAP_ASYM_LBN); if (cap & SUPPORTED_Autoneg) result |= (1 << MC_CMD_PHY_CAP_AN_LBN); return result; } static u32 efx_get_mcdi_phy_flags(struct efx_nic *efx) { struct efx_mcdi_phy_data *phy_cfg = efx->phy_data; enum efx_phy_mode mode, supported; u32 flags; /* TODO: Advertise the capabilities supported by this PHY */ supported = 0; if (phy_cfg->flags & (1 << MC_CMD_GET_PHY_CFG_OUT_TXDIS_LBN)) supported |= PHY_MODE_TX_DISABLED; if (phy_cfg->flags & (1 << MC_CMD_GET_PHY_CFG_OUT_LOWPOWER_LBN)) supported |= PHY_MODE_LOW_POWER; if (phy_cfg->flags & (1 << MC_CMD_GET_PHY_CFG_OUT_POWEROFF_LBN)) supported |= PHY_MODE_OFF; mode = efx->phy_mode & supported; flags = 0; if (mode & PHY_MODE_TX_DISABLED) flags |= (1 << MC_CMD_SET_LINK_IN_TXDIS_LBN); if (mode & PHY_MODE_LOW_POWER) flags |= (1 << MC_CMD_SET_LINK_IN_LOWPOWER_LBN); if (mode & PHY_MODE_OFF) flags |= (1 << MC_CMD_SET_LINK_IN_POWEROFF_LBN); return flags; } static u32 mcdi_to_ethtool_media(u32 media) { switch (media) { case MC_CMD_MEDIA_XAUI: case MC_CMD_MEDIA_CX4: case MC_CMD_MEDIA_KX4: return PORT_OTHER; case MC_CMD_MEDIA_XFP: case MC_CMD_MEDIA_SFP_PLUS: return PORT_FIBRE; case MC_CMD_MEDIA_BASE_T: return PORT_TP; default: return PORT_OTHER; } } static int efx_mcdi_phy_probe(struct efx_nic *efx) { struct efx_mcdi_phy_data *phy_data; u8 outbuf[MC_CMD_GET_LINK_OUT_LEN]; u32 caps; int rc; /* Initialise and populate phy_data */ phy_data = kzalloc(sizeof(*phy_data), GFP_KERNEL); if (phy_data == NULL) return -ENOMEM; rc = efx_mcdi_get_phy_cfg(efx, phy_data); if (rc != 0) goto fail; /* Read initial link advertisement */ BUILD_BUG_ON(MC_CMD_GET_LINK_IN_LEN != 0); rc = efx_mcdi_rpc(efx, MC_CMD_GET_LINK, NULL, 0, outbuf, sizeof(outbuf), NULL); if (rc) goto fail; /* Fill out nic state */ efx->phy_data = phy_data; efx->phy_type = phy_data->type; efx->mdio_bus = phy_data->channel; efx->mdio.prtad = phy_data->port; efx->mdio.mmds = phy_data->mmd_mask & ~(1 << MC_CMD_MMD_CLAUSE22); efx->mdio.mode_support = 0; if (phy_data->mmd_mask & (1 << MC_CMD_MMD_CLAUSE22)) efx->mdio.mode_support |= MDIO_SUPPORTS_C22; if (phy_data->mmd_mask & ~(1 << MC_CMD_MMD_CLAUSE22)) efx->mdio.mode_support |= MDIO_SUPPORTS_C45 | MDIO_EMULATE_C22; caps = MCDI_DWORD(outbuf, GET_LINK_OUT_CAP); if (caps & (1 << MC_CMD_PHY_CAP_AN_LBN)) efx->link_advertising = mcdi_to_ethtool_cap(phy_data->media, caps); else phy_data->forced_cap = caps; /* Assert that we can map efx -> mcdi loopback modes */ BUILD_BUG_ON(LOOPBACK_NONE != MC_CMD_LOOPBACK_NONE); BUILD_BUG_ON(LOOPBACK_DATA != MC_CMD_LOOPBACK_DATA); BUILD_BUG_ON(LOOPBACK_GMAC != MC_CMD_LOOPBACK_GMAC); BUILD_BUG_ON(LOOPBACK_XGMII != MC_CMD_LOOPBACK_XGMII); BUILD_BUG_ON(LOOPBACK_XGXS != MC_CMD_LOOPBACK_XGXS); BUILD_BUG_ON(LOOPBACK_XAUI != MC_CMD_LOOPBACK_XAUI); BUILD_BUG_ON(LOOPBACK_GMII != MC_CMD_LOOPBACK_GMII); BUILD_BUG_ON(LOOPBACK_SGMII != MC_CMD_LOOPBACK_SGMII); BUILD_BUG_ON(LOOPBACK_XGBR != MC_CMD_LOOPBACK_XGBR); BUILD_BUG_ON(LOOPBACK_XFI != MC_CMD_LOOPBACK_XFI); BUILD_BUG_ON(LOOPBACK_XAUI_FAR != MC_CMD_LOOPBACK_XAUI_FAR); BUILD_BUG_ON(LOOPBACK_GMII_FAR != MC_CMD_LOOPBACK_GMII_FAR); BUILD_BUG_ON(LOOPBACK_SGMII_FAR != MC_CMD_LOOPBACK_SGMII_FAR); BUILD_BUG_ON(LOOPBACK_XFI_FAR != MC_CMD_LOOPBACK_XFI_FAR); BUILD_BUG_ON(LOOPBACK_GPHY != MC_CMD_LOOPBACK_GPHY); BUILD_BUG_ON(LOOPBACK_PHYXS != MC_CMD_LOOPBACK_PHYXS); BUILD_BUG_ON(LOOPBACK_PCS != MC_CMD_LOOPBACK_PCS); BUILD_BUG_ON(LOOPBACK_PMAPMD != MC_CMD_LOOPBACK_PMAPMD); BUILD_BUG_ON(LOOPBACK_XPORT != MC_CMD_LOOPBACK_XPORT); BUILD_BUG_ON(LOOPBACK_XGMII_WS != MC_CMD_LOOPBACK_XGMII_WS); BUILD_BUG_ON(LOOPBACK_XAUI_WS != MC_CMD_LOOPBACK_XAUI_WS); BUILD_BUG_ON(LOOPBACK_XAUI_WS_FAR != MC_CMD_LOOPBACK_XAUI_WS_FAR); BUILD_BUG_ON(LOOPBACK_XAUI_WS_NEAR != MC_CMD_LOOPBACK_XAUI_WS_NEAR); BUILD_BUG_ON(LOOPBACK_GMII_WS != MC_CMD_LOOPBACK_GMII_WS); BUILD_BUG_ON(LOOPBACK_XFI_WS != MC_CMD_LOOPBACK_XFI_WS); BUILD_BUG_ON(LOOPBACK_XFI_WS_FAR != MC_CMD_LOOPBACK_XFI_WS_FAR); BUILD_BUG_ON(LOOPBACK_PHYXS_WS != MC_CMD_LOOPBACK_PHYXS_WS); rc = efx_mcdi_loopback_modes(efx, &efx->loopback_modes); if (rc != 0) goto fail; /* The MC indicates that LOOPBACK_NONE is a valid loopback mode, * but by convention we don't */ efx->loopback_modes &= ~(1 << LOOPBACK_NONE); /* Set the initial link mode */ efx_mcdi_phy_decode_link( efx, &efx->link_state, MCDI_DWORD(outbuf, GET_LINK_OUT_LINK_SPEED), MCDI_DWORD(outbuf, GET_LINK_OUT_FLAGS), MCDI_DWORD(outbuf, GET_LINK_OUT_FCNTL)); /* Default to Autonegotiated flow control if the PHY supports it */ efx->wanted_fc = EFX_FC_RX | EFX_FC_TX; if (phy_data->supported_cap & (1 << MC_CMD_PHY_CAP_AN_LBN)) efx->wanted_fc |= EFX_FC_AUTO; efx_link_set_wanted_fc(efx, efx->wanted_fc); return 0; fail: kfree(phy_data); return rc; } int efx_mcdi_phy_reconfigure(struct efx_nic *efx) { struct efx_mcdi_phy_data *phy_cfg = efx->phy_data; u32 caps = (efx->link_advertising ? ethtool_to_mcdi_cap(efx->link_advertising) : phy_cfg->forced_cap); return efx_mcdi_set_link(efx, caps, efx_get_mcdi_phy_flags(efx), efx->loopback_mode, 0); } void efx_mcdi_phy_decode_link(struct efx_nic *efx, struct efx_link_state *link_state, u32 speed, u32 flags, u32 fcntl) { switch (fcntl) { case MC_CMD_FCNTL_AUTO: WARN_ON(1); /* This is not a link mode */ link_state->fc = EFX_FC_AUTO | EFX_FC_TX | EFX_FC_RX; break; case MC_CMD_FCNTL_BIDIR: link_state->fc = EFX_FC_TX | EFX_FC_RX; break; case MC_CMD_FCNTL_RESPOND: link_state->fc = EFX_FC_RX; break; default: WARN_ON(1); case MC_CMD_FCNTL_OFF: link_state->fc = 0; break; } link_state->up = !!(flags & (1 << MC_CMD_GET_LINK_OUT_LINK_UP_LBN)); link_state->fd = !!(flags & (1 << MC_CMD_GET_LINK_OUT_FULL_DUPLEX_LBN)); link_state->speed = speed; } /* Verify that the forced flow control settings (!EFX_FC_AUTO) are * supported by the link partner. Warn the user if this isn't the case */ void efx_mcdi_phy_check_fcntl(struct efx_nic *efx, u32 lpa) { struct efx_mcdi_phy_data *phy_cfg = efx->phy_data; u32 rmtadv; /* The link partner capabilities are only relevant if the * link supports flow control autonegotiation */ if (~phy_cfg->supported_cap & (1 << MC_CMD_PHY_CAP_AN_LBN)) return; /* If flow control autoneg is supported and enabled, then fine */ if (efx->wanted_fc & EFX_FC_AUTO) return; rmtadv = 0; if (lpa & (1 << MC_CMD_PHY_CAP_PAUSE_LBN)) rmtadv |= ADVERTISED_Pause; if (lpa & (1 << MC_CMD_PHY_CAP_ASYM_LBN)) rmtadv |= ADVERTISED_Asym_Pause; if ((efx->wanted_fc & EFX_FC_TX) && rmtadv == ADVERTISED_Asym_Pause) netif_err(efx, link, efx->net_dev, "warning: link partner doesn't support pause frames"); } static bool efx_mcdi_phy_poll(struct efx_nic *efx) { struct efx_link_state old_state = efx->link_state; u8 outbuf[MC_CMD_GET_LINK_OUT_LEN]; int rc; WARN_ON(!mutex_is_locked(&efx->mac_lock)); BUILD_BUG_ON(MC_CMD_GET_LINK_IN_LEN != 0); rc = efx_mcdi_rpc(efx, MC_CMD_GET_LINK, NULL, 0, outbuf, sizeof(outbuf), NULL); if (rc) { netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc); efx->link_state.up = false; } else { efx_mcdi_phy_decode_link( efx, &efx->link_state, MCDI_DWORD(outbuf, GET_LINK_OUT_LINK_SPEED), MCDI_DWORD(outbuf, GET_LINK_OUT_FLAGS), MCDI_DWORD(outbuf, GET_LINK_OUT_FCNTL)); } return !efx_link_state_equal(&efx->link_state, &old_state); } static void efx_mcdi_phy_remove(struct efx_nic *efx) { struct efx_mcdi_phy_data *phy_data = efx->phy_data; efx->phy_data = NULL; kfree(phy_data); } static void efx_mcdi_phy_get_settings(struct efx_nic *efx, struct ethtool_cmd *ecmd) { struct efx_mcdi_phy_data *phy_cfg = efx->phy_data; u8 outbuf[MC_CMD_GET_LINK_OUT_LEN]; int rc; ecmd->supported = mcdi_to_ethtool_cap(phy_cfg->media, phy_cfg->supported_cap); ecmd->advertising = efx->link_advertising; ethtool_cmd_speed_set(ecmd, efx->link_state.speed); ecmd->duplex = efx->link_state.fd; ecmd->port = mcdi_to_ethtool_media(phy_cfg->media); ecmd->phy_address = phy_cfg->port; ecmd->transceiver = XCVR_INTERNAL; ecmd->autoneg = !!(efx->link_advertising & ADVERTISED_Autoneg); ecmd->mdio_support = (efx->mdio.mode_support & (MDIO_SUPPORTS_C45 | MDIO_SUPPORTS_C22)); BUILD_BUG_ON(MC_CMD_GET_LINK_IN_LEN != 0); rc = efx_mcdi_rpc(efx, MC_CMD_GET_LINK, NULL, 0, outbuf, sizeof(outbuf), NULL); if (rc) { netif_err(efx, hw, efx->net_dev, "%s: failed rc=%d\n", __func__, rc); return; } ecmd->lp_advertising = mcdi_to_ethtool_cap(phy_cfg->media, MCDI_DWORD(outbuf, GET_LINK_OUT_LP_CAP)); } static int efx_mcdi_phy_set_settings(struct efx_nic *efx, struct ethtool_cmd *ecmd) { struct efx_mcdi_phy_data *phy_cfg = efx->phy_data; u32 caps; int rc; if (ecmd->autoneg) { caps = (ethtool_to_mcdi_cap(ecmd->advertising) | 1 << MC_CMD_PHY_CAP_AN_LBN); } else if (ecmd->duplex) { switch (ethtool_cmd_speed(ecmd)) { case 10: caps = 1 << MC_CMD_PHY_CAP_10FDX_LBN; break; case 100: caps = 1 << MC_CMD_PHY_CAP_100FDX_LBN; break; case 1000: caps = 1 << MC_CMD_PHY_CAP_1000FDX_LBN; break; case 10000: caps = 1 << MC_CMD_PHY_CAP_10000FDX_LBN; break; default: return -EINVAL; } } else { switch (ethtool_cmd_speed(ecmd)) { case 10: caps = 1 << MC_CMD_PHY_CAP_10HDX_LBN; break; case 100: caps = 1 << MC_CMD_PHY_CAP_100HDX_LBN; break; case 1000: caps = 1 << MC_CMD_PHY_CAP_1000HDX_LBN; break; default: return -EINVAL; } } rc = efx_mcdi_set_link(efx, caps, efx_get_mcdi_phy_flags(efx), efx->loopback_mode, 0); if (rc) return rc; if (ecmd->autoneg) { efx_link_set_advertising( efx, ecmd->advertising | ADVERTISED_Autoneg); phy_cfg->forced_cap = 0; } else { efx_link_set_advertising(efx, 0); phy_cfg->forced_cap = caps; } return 0; } static int efx_mcdi_phy_test_alive(struct efx_nic *efx) { u8 outbuf[MC_CMD_GET_PHY_STATE_OUT_LEN]; size_t outlen; int rc; BUILD_BUG_ON(MC_CMD_GET_PHY_STATE_IN_LEN != 0); rc = efx_mcdi_rpc(efx, MC_CMD_GET_PHY_STATE, NULL, 0, outbuf, sizeof(outbuf), &outlen); if (rc) return rc; if (outlen < MC_CMD_GET_PHY_STATE_OUT_LEN) return -EIO; if (MCDI_DWORD(outbuf, GET_PHY_STATE_OUT_STATE) != MC_CMD_PHY_STATE_OK) return -EINVAL; return 0; } static const char *const mcdi_sft9001_cable_diag_names[] = { "cable.pairA.length", "cable.pairB.length", "cable.pairC.length", "cable.pairD.length", "cable.pairA.status", "cable.pairB.status", "cable.pairC.status", "cable.pairD.status", }; static int efx_mcdi_bist(struct efx_nic *efx, unsigned int bist_mode, int *results) { unsigned int retry, i, count = 0; size_t outlen; u32 status; u8 *buf, *ptr; int rc; buf = kzalloc(0x100, GFP_KERNEL); if (buf == NULL) return -ENOMEM; BUILD_BUG_ON(MC_CMD_START_BIST_OUT_LEN != 0); MCDI_SET_DWORD(buf, START_BIST_IN_TYPE, bist_mode); rc = efx_mcdi_rpc(efx, MC_CMD_START_BIST, buf, MC_CMD_START_BIST_IN_LEN, NULL, 0, NULL); if (rc) goto out; /* Wait up to 10s for BIST to finish */ for (retry = 0; retry < 100; ++retry) { BUILD_BUG_ON(MC_CMD_POLL_BIST_IN_LEN != 0); rc = efx_mcdi_rpc(efx, MC_CMD_POLL_BIST, NULL, 0, buf, 0x100, &outlen); if (rc) goto out; status = MCDI_DWORD(buf, POLL_BIST_OUT_RESULT); if (status != MC_CMD_POLL_BIST_RUNNING) goto finished; msleep(100); } rc = -ETIMEDOUT; goto out; finished: results[count++] = (status == MC_CMD_POLL_BIST_PASSED) ? 1 : -1; /* SFT9001 specific cable diagnostics output */ if (efx->phy_type == PHY_TYPE_SFT9001B && (bist_mode == MC_CMD_PHY_BIST_CABLE_SHORT || bist_mode == MC_CMD_PHY_BIST_CABLE_LONG)) { ptr = MCDI_PTR(buf, POLL_BIST_OUT_SFT9001_CABLE_LENGTH_A); if (status == MC_CMD_POLL_BIST_PASSED && outlen >= MC_CMD_POLL_BIST_OUT_SFT9001_LEN) { for (i = 0; i < 8; i++) { results[count + i] = EFX_DWORD_FIELD(((efx_dword_t *)ptr)[i], EFX_DWORD_0); } } count += 8; } rc = count; out: kfree(buf); return rc; } static int efx_mcdi_phy_run_tests(struct efx_nic *efx, int *results, unsigned flags) { struct efx_mcdi_phy_data *phy_cfg = efx->phy_data; u32 mode; int rc; if (phy_cfg->flags & (1 << MC_CMD_GET_PHY_CFG_OUT_BIST_LBN)) { rc = efx_mcdi_bist(efx, MC_CMD_PHY_BIST, results); if (rc < 0) return rc; results += rc; } /* If we support both LONG and SHORT, then run each in response to * break or not. Otherwise, run the one we support */ mode = 0; if (phy_cfg->flags & (1 << MC_CMD_GET_PHY_CFG_OUT_BIST_CABLE_SHORT_LBN)) { if ((flags & ETH_TEST_FL_OFFLINE) && (phy_cfg->flags & (1 << MC_CMD_GET_PHY_CFG_OUT_BIST_CABLE_LONG_LBN))) mode = MC_CMD_PHY_BIST_CABLE_LONG; else mode = MC_CMD_PHY_BIST_CABLE_SHORT; } else if (phy_cfg->flags & (1 << MC_CMD_GET_PHY_CFG_OUT_BIST_CABLE_LONG_LBN)) mode = MC_CMD_PHY_BIST_CABLE_LONG; if (mode != 0) { rc = efx_mcdi_bist(efx, mode, results); if (rc < 0) return rc; results += rc; } return 0; } static const char *efx_mcdi_phy_test_name(struct efx_nic *efx, unsigned int index) { struct efx_mcdi_phy_data *phy_cfg = efx->phy_data; if (phy_cfg->flags & (1 << MC_CMD_GET_PHY_CFG_OUT_BIST_LBN)) { if (index == 0) return "bist"; --index; } if (phy_cfg->flags & ((1 << MC_CMD_GET_PHY_CFG_OUT_BIST_CABLE_SHORT_LBN) | (1 << MC_CMD_GET_PHY_CFG_OUT_BIST_CABLE_LONG_LBN))) { if (index == 0) return "cable"; --index; if (efx->phy_type == PHY_TYPE_SFT9001B) { if (index < ARRAY_SIZE(mcdi_sft9001_cable_diag_names)) return mcdi_sft9001_cable_diag_names[index]; index -= ARRAY_SIZE(mcdi_sft9001_cable_diag_names); } } return NULL; } const struct efx_phy_operations efx_mcdi_phy_ops = { .probe = efx_mcdi_phy_probe, .init = efx_port_dummy_op_int, .reconfigure = efx_mcdi_phy_reconfigure, .poll = efx_mcdi_phy_poll, .fini = efx_port_dummy_op_void, .remove = efx_mcdi_phy_remove, .get_settings = efx_mcdi_phy_get_settings, .set_settings = efx_mcdi_phy_set_settings, .test_alive = efx_mcdi_phy_test_alive, .run_tests = efx_mcdi_phy_run_tests, .test_name = efx_mcdi_phy_test_name, };
gpl-2.0
casinobrawl/exp_dt2w
drivers/input/keyboard/jornada680_kbd.c
5072
8087
/* * 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 __devinit 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 __devexit 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 = __devexit_p(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
SlimRoms/kernel_lge_msm7x27a-common
drivers/spi/spi-coldfire-qspi.c
5072
16365
/* * Freescale/Motorola Coldfire Queued SPI driver * * Copyright 2010 Steven King <sfking@fdwdc.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 St - Fifth Floor, Boston, MA 02110-1301 USA * */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/interrupt.h> #include <linux/errno.h> #include <linux/platform_device.h> #include <linux/sched.h> #include <linux/workqueue.h> #include <linux/delay.h> #include <linux/io.h> #include <linux/clk.h> #include <linux/err.h> #include <linux/spi/spi.h> #include <asm/coldfire.h> #include <asm/mcfsim.h> #include <asm/mcfqspi.h> #define DRIVER_NAME "mcfqspi" #define MCFQSPI_BUSCLK (MCF_BUSCLK / 2) #define MCFQSPI_QMR 0x00 #define MCFQSPI_QMR_MSTR 0x8000 #define MCFQSPI_QMR_CPOL 0x0200 #define MCFQSPI_QMR_CPHA 0x0100 #define MCFQSPI_QDLYR 0x04 #define MCFQSPI_QDLYR_SPE 0x8000 #define MCFQSPI_QWR 0x08 #define MCFQSPI_QWR_HALT 0x8000 #define MCFQSPI_QWR_WREN 0x4000 #define MCFQSPI_QWR_CSIV 0x1000 #define MCFQSPI_QIR 0x0C #define MCFQSPI_QIR_WCEFB 0x8000 #define MCFQSPI_QIR_ABRTB 0x4000 #define MCFQSPI_QIR_ABRTL 0x1000 #define MCFQSPI_QIR_WCEFE 0x0800 #define MCFQSPI_QIR_ABRTE 0x0400 #define MCFQSPI_QIR_SPIFE 0x0100 #define MCFQSPI_QIR_WCEF 0x0008 #define MCFQSPI_QIR_ABRT 0x0004 #define MCFQSPI_QIR_SPIF 0x0001 #define MCFQSPI_QAR 0x010 #define MCFQSPI_QAR_TXBUF 0x00 #define MCFQSPI_QAR_RXBUF 0x10 #define MCFQSPI_QAR_CMDBUF 0x20 #define MCFQSPI_QDR 0x014 #define MCFQSPI_QCR 0x014 #define MCFQSPI_QCR_CONT 0x8000 #define MCFQSPI_QCR_BITSE 0x4000 #define MCFQSPI_QCR_DT 0x2000 struct mcfqspi { void __iomem *iobase; int irq; struct clk *clk; struct mcfqspi_cs_control *cs_control; wait_queue_head_t waitq; struct work_struct work; struct workqueue_struct *workq; spinlock_t lock; struct list_head msgq; }; static void mcfqspi_wr_qmr(struct mcfqspi *mcfqspi, u16 val) { writew(val, mcfqspi->iobase + MCFQSPI_QMR); } static void mcfqspi_wr_qdlyr(struct mcfqspi *mcfqspi, u16 val) { writew(val, mcfqspi->iobase + MCFQSPI_QDLYR); } static u16 mcfqspi_rd_qdlyr(struct mcfqspi *mcfqspi) { return readw(mcfqspi->iobase + MCFQSPI_QDLYR); } static void mcfqspi_wr_qwr(struct mcfqspi *mcfqspi, u16 val) { writew(val, mcfqspi->iobase + MCFQSPI_QWR); } static void mcfqspi_wr_qir(struct mcfqspi *mcfqspi, u16 val) { writew(val, mcfqspi->iobase + MCFQSPI_QIR); } static void mcfqspi_wr_qar(struct mcfqspi *mcfqspi, u16 val) { writew(val, mcfqspi->iobase + MCFQSPI_QAR); } static void mcfqspi_wr_qdr(struct mcfqspi *mcfqspi, u16 val) { writew(val, mcfqspi->iobase + MCFQSPI_QDR); } static u16 mcfqspi_rd_qdr(struct mcfqspi *mcfqspi) { return readw(mcfqspi->iobase + MCFQSPI_QDR); } static void mcfqspi_cs_select(struct mcfqspi *mcfqspi, u8 chip_select, bool cs_high) { mcfqspi->cs_control->select(mcfqspi->cs_control, chip_select, cs_high); } static void mcfqspi_cs_deselect(struct mcfqspi *mcfqspi, u8 chip_select, bool cs_high) { mcfqspi->cs_control->deselect(mcfqspi->cs_control, chip_select, cs_high); } static int mcfqspi_cs_setup(struct mcfqspi *mcfqspi) { return (mcfqspi->cs_control && mcfqspi->cs_control->setup) ? mcfqspi->cs_control->setup(mcfqspi->cs_control) : 0; } static void mcfqspi_cs_teardown(struct mcfqspi *mcfqspi) { if (mcfqspi->cs_control && mcfqspi->cs_control->teardown) mcfqspi->cs_control->teardown(mcfqspi->cs_control); } static u8 mcfqspi_qmr_baud(u32 speed_hz) { return clamp((MCFQSPI_BUSCLK + speed_hz - 1) / speed_hz, 2u, 255u); } static bool mcfqspi_qdlyr_spe(struct mcfqspi *mcfqspi) { return mcfqspi_rd_qdlyr(mcfqspi) & MCFQSPI_QDLYR_SPE; } static irqreturn_t mcfqspi_irq_handler(int this_irq, void *dev_id) { struct mcfqspi *mcfqspi = dev_id; /* clear interrupt */ mcfqspi_wr_qir(mcfqspi, MCFQSPI_QIR_SPIFE | MCFQSPI_QIR_SPIF); wake_up(&mcfqspi->waitq); return IRQ_HANDLED; } static void mcfqspi_transfer_msg8(struct mcfqspi *mcfqspi, unsigned count, const u8 *txbuf, u8 *rxbuf) { unsigned i, n, offset = 0; n = min(count, 16u); mcfqspi_wr_qar(mcfqspi, MCFQSPI_QAR_CMDBUF); for (i = 0; i < n; ++i) mcfqspi_wr_qdr(mcfqspi, MCFQSPI_QCR_BITSE); mcfqspi_wr_qar(mcfqspi, MCFQSPI_QAR_TXBUF); if (txbuf) for (i = 0; i < n; ++i) mcfqspi_wr_qdr(mcfqspi, *txbuf++); else for (i = 0; i < count; ++i) mcfqspi_wr_qdr(mcfqspi, 0); count -= n; if (count) { u16 qwr = 0xf08; mcfqspi_wr_qwr(mcfqspi, 0x700); mcfqspi_wr_qdlyr(mcfqspi, MCFQSPI_QDLYR_SPE); do { wait_event(mcfqspi->waitq, !mcfqspi_qdlyr_spe(mcfqspi)); mcfqspi_wr_qwr(mcfqspi, qwr); mcfqspi_wr_qdlyr(mcfqspi, MCFQSPI_QDLYR_SPE); if (rxbuf) { mcfqspi_wr_qar(mcfqspi, MCFQSPI_QAR_RXBUF + offset); for (i = 0; i < 8; ++i) *rxbuf++ = mcfqspi_rd_qdr(mcfqspi); } n = min(count, 8u); if (txbuf) { mcfqspi_wr_qar(mcfqspi, MCFQSPI_QAR_TXBUF + offset); for (i = 0; i < n; ++i) mcfqspi_wr_qdr(mcfqspi, *txbuf++); } qwr = (offset ? 0x808 : 0) + ((n - 1) << 8); offset ^= 8; count -= n; } while (count); wait_event(mcfqspi->waitq, !mcfqspi_qdlyr_spe(mcfqspi)); mcfqspi_wr_qwr(mcfqspi, qwr); mcfqspi_wr_qdlyr(mcfqspi, MCFQSPI_QDLYR_SPE); if (rxbuf) { mcfqspi_wr_qar(mcfqspi, MCFQSPI_QAR_RXBUF + offset); for (i = 0; i < 8; ++i) *rxbuf++ = mcfqspi_rd_qdr(mcfqspi); offset ^= 8; } } else { mcfqspi_wr_qwr(mcfqspi, (n - 1) << 8); mcfqspi_wr_qdlyr(mcfqspi, MCFQSPI_QDLYR_SPE); } wait_event(mcfqspi->waitq, !mcfqspi_qdlyr_spe(mcfqspi)); if (rxbuf) { mcfqspi_wr_qar(mcfqspi, MCFQSPI_QAR_RXBUF + offset); for (i = 0; i < n; ++i) *rxbuf++ = mcfqspi_rd_qdr(mcfqspi); } } static void mcfqspi_transfer_msg16(struct mcfqspi *mcfqspi, unsigned count, const u16 *txbuf, u16 *rxbuf) { unsigned i, n, offset = 0; n = min(count, 16u); mcfqspi_wr_qar(mcfqspi, MCFQSPI_QAR_CMDBUF); for (i = 0; i < n; ++i) mcfqspi_wr_qdr(mcfqspi, MCFQSPI_QCR_BITSE); mcfqspi_wr_qar(mcfqspi, MCFQSPI_QAR_TXBUF); if (txbuf) for (i = 0; i < n; ++i) mcfqspi_wr_qdr(mcfqspi, *txbuf++); else for (i = 0; i < count; ++i) mcfqspi_wr_qdr(mcfqspi, 0); count -= n; if (count) { u16 qwr = 0xf08; mcfqspi_wr_qwr(mcfqspi, 0x700); mcfqspi_wr_qdlyr(mcfqspi, MCFQSPI_QDLYR_SPE); do { wait_event(mcfqspi->waitq, !mcfqspi_qdlyr_spe(mcfqspi)); mcfqspi_wr_qwr(mcfqspi, qwr); mcfqspi_wr_qdlyr(mcfqspi, MCFQSPI_QDLYR_SPE); if (rxbuf) { mcfqspi_wr_qar(mcfqspi, MCFQSPI_QAR_RXBUF + offset); for (i = 0; i < 8; ++i) *rxbuf++ = mcfqspi_rd_qdr(mcfqspi); } n = min(count, 8u); if (txbuf) { mcfqspi_wr_qar(mcfqspi, MCFQSPI_QAR_TXBUF + offset); for (i = 0; i < n; ++i) mcfqspi_wr_qdr(mcfqspi, *txbuf++); } qwr = (offset ? 0x808 : 0x000) + ((n - 1) << 8); offset ^= 8; count -= n; } while (count); wait_event(mcfqspi->waitq, !mcfqspi_qdlyr_spe(mcfqspi)); mcfqspi_wr_qwr(mcfqspi, qwr); mcfqspi_wr_qdlyr(mcfqspi, MCFQSPI_QDLYR_SPE); if (rxbuf) { mcfqspi_wr_qar(mcfqspi, MCFQSPI_QAR_RXBUF + offset); for (i = 0; i < 8; ++i) *rxbuf++ = mcfqspi_rd_qdr(mcfqspi); offset ^= 8; } } else { mcfqspi_wr_qwr(mcfqspi, (n - 1) << 8); mcfqspi_wr_qdlyr(mcfqspi, MCFQSPI_QDLYR_SPE); } wait_event(mcfqspi->waitq, !mcfqspi_qdlyr_spe(mcfqspi)); if (rxbuf) { mcfqspi_wr_qar(mcfqspi, MCFQSPI_QAR_RXBUF + offset); for (i = 0; i < n; ++i) *rxbuf++ = mcfqspi_rd_qdr(mcfqspi); } } static void mcfqspi_work(struct work_struct *work) { struct mcfqspi *mcfqspi = container_of(work, struct mcfqspi, work); unsigned long flags; spin_lock_irqsave(&mcfqspi->lock, flags); while (!list_empty(&mcfqspi->msgq)) { struct spi_message *msg; struct spi_device *spi; struct spi_transfer *xfer; int status = 0; msg = container_of(mcfqspi->msgq.next, struct spi_message, queue); list_del_init(&msg->queue); spin_unlock_irqrestore(&mcfqspi->lock, flags); spi = msg->spi; list_for_each_entry(xfer, &msg->transfers, transfer_list) { bool cs_high = spi->mode & SPI_CS_HIGH; u16 qmr = MCFQSPI_QMR_MSTR; if (xfer->bits_per_word) qmr |= xfer->bits_per_word << 10; else qmr |= spi->bits_per_word << 10; if (spi->mode & SPI_CPHA) qmr |= MCFQSPI_QMR_CPHA; if (spi->mode & SPI_CPOL) qmr |= MCFQSPI_QMR_CPOL; if (xfer->speed_hz) qmr |= mcfqspi_qmr_baud(xfer->speed_hz); else qmr |= mcfqspi_qmr_baud(spi->max_speed_hz); mcfqspi_wr_qmr(mcfqspi, qmr); mcfqspi_cs_select(mcfqspi, spi->chip_select, cs_high); mcfqspi_wr_qir(mcfqspi, MCFQSPI_QIR_SPIFE); if ((xfer->bits_per_word ? xfer->bits_per_word : spi->bits_per_word) == 8) mcfqspi_transfer_msg8(mcfqspi, xfer->len, xfer->tx_buf, xfer->rx_buf); else mcfqspi_transfer_msg16(mcfqspi, xfer->len / 2, xfer->tx_buf, xfer->rx_buf); mcfqspi_wr_qir(mcfqspi, 0); if (xfer->delay_usecs) udelay(xfer->delay_usecs); if (xfer->cs_change) { if (!list_is_last(&xfer->transfer_list, &msg->transfers)) mcfqspi_cs_deselect(mcfqspi, spi->chip_select, cs_high); } else { if (list_is_last(&xfer->transfer_list, &msg->transfers)) mcfqspi_cs_deselect(mcfqspi, spi->chip_select, cs_high); } msg->actual_length += xfer->len; } msg->status = status; msg->complete(msg->context); spin_lock_irqsave(&mcfqspi->lock, flags); } spin_unlock_irqrestore(&mcfqspi->lock, flags); } static int mcfqspi_transfer(struct spi_device *spi, struct spi_message *msg) { struct mcfqspi *mcfqspi; struct spi_transfer *xfer; unsigned long flags; mcfqspi = spi_master_get_devdata(spi->master); list_for_each_entry(xfer, &msg->transfers, transfer_list) { if (xfer->bits_per_word && ((xfer->bits_per_word < 8) || (xfer->bits_per_word > 16))) { dev_dbg(&spi->dev, "%d bits per word is not supported\n", xfer->bits_per_word); goto fail; } if (xfer->speed_hz) { u32 real_speed = MCFQSPI_BUSCLK / mcfqspi_qmr_baud(xfer->speed_hz); if (real_speed != xfer->speed_hz) dev_dbg(&spi->dev, "using speed %d instead of %d\n", real_speed, xfer->speed_hz); } } msg->status = -EINPROGRESS; msg->actual_length = 0; spin_lock_irqsave(&mcfqspi->lock, flags); list_add_tail(&msg->queue, &mcfqspi->msgq); queue_work(mcfqspi->workq, &mcfqspi->work); spin_unlock_irqrestore(&mcfqspi->lock, flags); return 0; fail: msg->status = -EINVAL; return -EINVAL; } static int mcfqspi_setup(struct spi_device *spi) { if ((spi->bits_per_word < 8) || (spi->bits_per_word > 16)) { dev_dbg(&spi->dev, "%d bits per word is not supported\n", spi->bits_per_word); return -EINVAL; } if (spi->chip_select >= spi->master->num_chipselect) { dev_dbg(&spi->dev, "%d chip select is out of range\n", spi->chip_select); return -EINVAL; } mcfqspi_cs_deselect(spi_master_get_devdata(spi->master), spi->chip_select, spi->mode & SPI_CS_HIGH); dev_dbg(&spi->dev, "bits per word %d, chip select %d, speed %d KHz\n", spi->bits_per_word, spi->chip_select, (MCFQSPI_BUSCLK / mcfqspi_qmr_baud(spi->max_speed_hz)) / 1000); return 0; } static int __devinit mcfqspi_probe(struct platform_device *pdev) { struct spi_master *master; struct mcfqspi *mcfqspi; struct resource *res; struct mcfqspi_platform_data *pdata; int status; master = spi_alloc_master(&pdev->dev, sizeof(*mcfqspi)); if (master == NULL) { dev_dbg(&pdev->dev, "spi_alloc_master failed\n"); return -ENOMEM; } mcfqspi = spi_master_get_devdata(master); res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) { dev_dbg(&pdev->dev, "platform_get_resource failed\n"); status = -ENXIO; goto fail0; } if (!request_mem_region(res->start, resource_size(res), pdev->name)) { dev_dbg(&pdev->dev, "request_mem_region failed\n"); status = -EBUSY; goto fail0; } mcfqspi->iobase = ioremap(res->start, resource_size(res)); if (!mcfqspi->iobase) { dev_dbg(&pdev->dev, "ioremap failed\n"); status = -ENOMEM; goto fail1; } mcfqspi->irq = platform_get_irq(pdev, 0); if (mcfqspi->irq < 0) { dev_dbg(&pdev->dev, "platform_get_irq failed\n"); status = -ENXIO; goto fail2; } status = request_irq(mcfqspi->irq, mcfqspi_irq_handler, 0, pdev->name, mcfqspi); if (status) { dev_dbg(&pdev->dev, "request_irq failed\n"); goto fail2; } mcfqspi->clk = clk_get(&pdev->dev, "qspi_clk"); if (IS_ERR(mcfqspi->clk)) { dev_dbg(&pdev->dev, "clk_get failed\n"); status = PTR_ERR(mcfqspi->clk); goto fail3; } clk_enable(mcfqspi->clk); mcfqspi->workq = create_singlethread_workqueue(dev_name(master->dev.parent)); if (!mcfqspi->workq) { dev_dbg(&pdev->dev, "create_workqueue failed\n"); status = -ENOMEM; goto fail4; } INIT_WORK(&mcfqspi->work, mcfqspi_work); spin_lock_init(&mcfqspi->lock); INIT_LIST_HEAD(&mcfqspi->msgq); init_waitqueue_head(&mcfqspi->waitq); pdata = pdev->dev.platform_data; if (!pdata) { dev_dbg(&pdev->dev, "platform data is missing\n"); goto fail5; } master->bus_num = pdata->bus_num; master->num_chipselect = pdata->num_chipselect; mcfqspi->cs_control = pdata->cs_control; status = mcfqspi_cs_setup(mcfqspi); if (status) { dev_dbg(&pdev->dev, "error initializing cs_control\n"); goto fail5; } master->mode_bits = SPI_CS_HIGH | SPI_CPOL | SPI_CPHA; master->setup = mcfqspi_setup; master->transfer = mcfqspi_transfer; platform_set_drvdata(pdev, master); status = spi_register_master(master); if (status) { dev_dbg(&pdev->dev, "spi_register_master failed\n"); goto fail6; } dev_info(&pdev->dev, "Coldfire QSPI bus driver\n"); return 0; fail6: mcfqspi_cs_teardown(mcfqspi); fail5: destroy_workqueue(mcfqspi->workq); fail4: clk_disable(mcfqspi->clk); clk_put(mcfqspi->clk); fail3: free_irq(mcfqspi->irq, mcfqspi); fail2: iounmap(mcfqspi->iobase); fail1: release_mem_region(res->start, resource_size(res)); fail0: spi_master_put(master); dev_dbg(&pdev->dev, "Coldfire QSPI probe failed\n"); return status; } static int __devexit mcfqspi_remove(struct platform_device *pdev) { struct spi_master *master = platform_get_drvdata(pdev); struct mcfqspi *mcfqspi = spi_master_get_devdata(master); struct resource *res = platform_get_resource(pdev, IORESOURCE_MEM, 0); /* disable the hardware (set the baud rate to 0) */ mcfqspi_wr_qmr(mcfqspi, MCFQSPI_QMR_MSTR); platform_set_drvdata(pdev, NULL); mcfqspi_cs_teardown(mcfqspi); destroy_workqueue(mcfqspi->workq); clk_disable(mcfqspi->clk); clk_put(mcfqspi->clk); free_irq(mcfqspi->irq, mcfqspi); iounmap(mcfqspi->iobase); release_mem_region(res->start, resource_size(res)); spi_unregister_master(master); spi_master_put(master); return 0; } #ifdef CONFIG_PM static int mcfqspi_suspend(struct device *dev) { struct mcfqspi *mcfqspi = platform_get_drvdata(to_platform_device(dev)); clk_disable(mcfqspi->clk); return 0; } static int mcfqspi_resume(struct device *dev) { struct mcfqspi *mcfqspi = platform_get_drvdata(to_platform_device(dev)); clk_enable(mcfqspi->clk); return 0; } static struct dev_pm_ops mcfqspi_dev_pm_ops = { .suspend = mcfqspi_suspend, .resume = mcfqspi_resume, }; #define MCFQSPI_DEV_PM_OPS (&mcfqspi_dev_pm_ops) #else #define MCFQSPI_DEV_PM_OPS NULL #endif static struct platform_driver mcfqspi_driver = { .driver.name = DRIVER_NAME, .driver.owner = THIS_MODULE, .driver.pm = MCFQSPI_DEV_PM_OPS, .probe = mcfqspi_probe, .remove = __devexit_p(mcfqspi_remove), }; module_platform_driver(mcfqspi_driver); MODULE_AUTHOR("Steven King <sfking@fdwdc.com>"); MODULE_DESCRIPTION("Coldfire QSPI Controller Driver"); MODULE_LICENSE("GPL"); MODULE_ALIAS("platform:" DRIVER_NAME);
gpl-2.0
maqiangddb/Android_kernel
drivers/usb/host/ohci-ppc-soc.c
5072
4976
/* * OHCI HCD (Host Controller Driver) for USB. * * (C) Copyright 1999 Roman Weissgaerber <weissg@vienna.at> * (C) Copyright 2000-2002 David Brownell <dbrownell@users.sourceforge.net> * (C) Copyright 2002 Hewlett-Packard Company * (C) Copyright 2003-2005 MontaVista Software Inc. * * Bus Glue for PPC On-Chip OHCI driver * Tested on Freescale MPC5200 and IBM STB04xxx * * Modified by Dale Farnsworth <dale@farnsworth.org> from ohci-sa1111.c * * This file is licenced under the GPL. */ #include <linux/platform_device.h> #include <linux/signal.h> /* configure so an HC device and id are always provided */ /* always called with process context; sleeping is OK */ /** * usb_hcd_ppc_soc_probe - initialize On-Chip HCDs * Context: !in_interrupt() * * Allocates basic resources for this USB host controller. * * Store this function in the HCD's struct pci_driver as probe(). */ static int usb_hcd_ppc_soc_probe(const struct hc_driver *driver, struct platform_device *pdev) { int retval; struct usb_hcd *hcd; struct ohci_hcd *ohci; struct resource *res; int irq; pr_debug("initializing PPC-SOC USB Controller\n"); res = platform_get_resource(pdev, IORESOURCE_IRQ, 0); if (!res) { pr_debug("%s: no irq\n", __FILE__); return -ENODEV; } irq = res->start; res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) { pr_debug("%s: no reg addr\n", __FILE__); return -ENODEV; } hcd = usb_create_hcd(driver, &pdev->dev, "PPC-SOC USB"); if (!hcd) return -ENOMEM; hcd->rsrc_start = res->start; hcd->rsrc_len = resource_size(res); if (!request_mem_region(hcd->rsrc_start, hcd->rsrc_len, hcd_name)) { pr_debug("%s: request_mem_region failed\n", __FILE__); retval = -EBUSY; goto err1; } hcd->regs = ioremap(hcd->rsrc_start, hcd->rsrc_len); if (!hcd->regs) { pr_debug("%s: ioremap failed\n", __FILE__); retval = -ENOMEM; goto err2; } ohci = hcd_to_ohci(hcd); ohci->flags |= OHCI_QUIRK_BE_MMIO | OHCI_QUIRK_BE_DESC; #ifdef CONFIG_PPC_MPC52xx /* MPC52xx doesn't need frame_no shift */ ohci->flags |= OHCI_QUIRK_FRAME_NO; #endif ohci_hcd_init(ohci); retval = usb_add_hcd(hcd, irq, 0); if (retval == 0) return retval; pr_debug("Removing PPC-SOC USB Controller\n"); iounmap(hcd->regs); err2: release_mem_region(hcd->rsrc_start, hcd->rsrc_len); err1: usb_put_hcd(hcd); return retval; } /* may be called without controller electrically present */ /* may be called with controller, bus, and devices active */ /** * usb_hcd_ppc_soc_remove - shutdown processing for On-Chip HCDs * @pdev: USB Host Controller being removed * Context: !in_interrupt() * * Reverses the effect of usb_hcd_ppc_soc_probe(). * It is always called from a thread * context, normally "rmmod", "apmd", or something similar. * */ static void usb_hcd_ppc_soc_remove(struct usb_hcd *hcd, struct platform_device *pdev) { usb_remove_hcd(hcd); pr_debug("stopping PPC-SOC USB Controller\n"); iounmap(hcd->regs); release_mem_region(hcd->rsrc_start, hcd->rsrc_len); usb_put_hcd(hcd); } static int __devinit ohci_ppc_soc_start(struct usb_hcd *hcd) { struct ohci_hcd *ohci = hcd_to_ohci(hcd); int ret; if ((ret = ohci_init(ohci)) < 0) return ret; if ((ret = ohci_run(ohci)) < 0) { err("can't start %s", ohci_to_hcd(ohci)->self.bus_name); ohci_stop(hcd); return ret; } return 0; } static const struct hc_driver ohci_ppc_soc_hc_driver = { .description = hcd_name, .hcd_priv_size = sizeof(struct ohci_hcd), /* * generic hardware linkage */ .irq = ohci_irq, .flags = HCD_USB11 | HCD_MEMORY, /* * basic lifecycle operations */ .start = ohci_ppc_soc_start, .stop = ohci_stop, .shutdown = ohci_shutdown, /* * managing i/o requests and associated device resources */ .urb_enqueue = ohci_urb_enqueue, .urb_dequeue = ohci_urb_dequeue, .endpoint_disable = ohci_endpoint_disable, /* * scheduling support */ .get_frame_number = ohci_get_frame, /* * root hub support */ .hub_status_data = ohci_hub_status_data, .hub_control = ohci_hub_control, #ifdef CONFIG_PM .bus_suspend = ohci_bus_suspend, .bus_resume = ohci_bus_resume, #endif .start_port_reset = ohci_start_port_reset, }; static int ohci_hcd_ppc_soc_drv_probe(struct platform_device *pdev) { int ret; if (usb_disabled()) return -ENODEV; ret = usb_hcd_ppc_soc_probe(&ohci_ppc_soc_hc_driver, pdev); return ret; } static int ohci_hcd_ppc_soc_drv_remove(struct platform_device *pdev) { struct usb_hcd *hcd = platform_get_drvdata(pdev); usb_hcd_ppc_soc_remove(hcd, pdev); return 0; } static struct platform_driver ohci_hcd_ppc_soc_driver = { .probe = ohci_hcd_ppc_soc_drv_probe, .remove = ohci_hcd_ppc_soc_drv_remove, .shutdown = usb_hcd_platform_shutdown, #ifdef CONFIG_PM /*.suspend = ohci_hcd_ppc_soc_drv_suspend,*/ /*.resume = ohci_hcd_ppc_soc_drv_resume,*/ #endif .driver = { .name = "ppc-soc-ohci", .owner = THIS_MODULE, }, }; MODULE_ALIAS("platform:ppc-soc-ohci");
gpl-2.0