repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
CyanogenMod/lge-kernel-iproj | drivers/infiniband/hw/amso1100/c2_pd.c | 9308 | 3036 | /*
* Copyright (c) 2004 Topspin Communications. All rights reserved.
* Copyright (c) 2005 Cisco Systems. All rights reserved.
* Copyright (c) 2005 Mellanox Technologies. All rights reserved.
* Copyright (c) 2005 Open Grid Computing, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include "c2.h"
#include "c2_provider.h"
int c2_pd_alloc(struct c2_dev *c2dev, int privileged, struct c2_pd *pd)
{
u32 obj;
int ret = 0;
spin_lock(&c2dev->pd_table.lock);
obj = find_next_zero_bit(c2dev->pd_table.table, c2dev->pd_table.max,
c2dev->pd_table.last);
if (obj >= c2dev->pd_table.max)
obj = find_first_zero_bit(c2dev->pd_table.table,
c2dev->pd_table.max);
if (obj < c2dev->pd_table.max) {
pd->pd_id = obj;
__set_bit(obj, c2dev->pd_table.table);
c2dev->pd_table.last = obj+1;
if (c2dev->pd_table.last >= c2dev->pd_table.max)
c2dev->pd_table.last = 0;
} else
ret = -ENOMEM;
spin_unlock(&c2dev->pd_table.lock);
return ret;
}
void c2_pd_free(struct c2_dev *c2dev, struct c2_pd *pd)
{
spin_lock(&c2dev->pd_table.lock);
__clear_bit(pd->pd_id, c2dev->pd_table.table);
spin_unlock(&c2dev->pd_table.lock);
}
int __devinit c2_init_pd_table(struct c2_dev *c2dev)
{
c2dev->pd_table.last = 0;
c2dev->pd_table.max = c2dev->props.max_pd;
spin_lock_init(&c2dev->pd_table.lock);
c2dev->pd_table.table = kmalloc(BITS_TO_LONGS(c2dev->props.max_pd) *
sizeof(long), GFP_KERNEL);
if (!c2dev->pd_table.table)
return -ENOMEM;
bitmap_zero(c2dev->pd_table.table, c2dev->props.max_pd);
return 0;
}
void __devexit c2_cleanup_pd_table(struct c2_dev *c2dev)
{
kfree(c2dev->pd_table.table);
}
| gpl-2.0 |
ephox-gcc-plugins/gcc-plugins_linux-next | drivers/staging/rtl8712/rtl871x_ioctl_linux.c | 93 | 67237 | /******************************************************************************
* rtl871x_ioctl_linux.c
*
* Copyright(c) 2007 - 2010 Realtek Corporation. All rights reserved.
* Linux device driver for RTL8192SU
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* Modifications for inclusion into the Linux staging tree are
* Copyright(c) 2010 Larry Finger. All rights reserved.
*
* Contact information:
* WLAN FAE <wlanfae@realtek.com>
* Larry Finger <Larry.Finger@lwfinger.net>
*
******************************************************************************/
#define _RTL871X_IOCTL_LINUX_C_
#define _RTL871X_MP_IOCTL_C_
#include "osdep_service.h"
#include "drv_types.h"
#include "wlan_bssdef.h"
#include "rtl871x_debug.h"
#include "wifi.h"
#include "rtl871x_mlme.h"
#include "rtl871x_ioctl.h"
#include "rtl871x_ioctl_set.h"
#include "rtl871x_mp_ioctl.h"
#include "mlme_osdep.h"
#include <linux/wireless.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/io.h>
#include <linux/semaphore.h>
#include <net/iw_handler.h>
#include <linux/if_arp.h>
#include <linux/etherdevice.h>
#define RTL_IOCTL_WPA_SUPPLICANT (SIOCIWFIRSTPRIV + 0x1E)
#define SCAN_ITEM_SIZE 768
#define MAX_CUSTOM_LEN 64
#define RATE_COUNT 4
static const u32 rtl8180_rates[] = {1000000, 2000000, 5500000, 11000000,
6000000, 9000000, 12000000, 18000000,
24000000, 36000000, 48000000, 54000000};
static const long ieee80211_wlan_frequencies[] = {
2412, 2417, 2422, 2427,
2432, 2437, 2442, 2447,
2452, 2457, 2462, 2467,
2472, 2484
};
static const char * const iw_operation_mode[] = {
"Auto", "Ad-Hoc", "Managed", "Master", "Repeater", "Secondary",
"Monitor"
};
void r8712_indicate_wx_assoc_event(struct _adapter *padapter)
{
union iwreq_data wrqu;
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
wrqu.ap_addr.sa_family = ARPHRD_ETHER;
memcpy(wrqu.ap_addr.sa_data, pmlmepriv->cur_network.network.MacAddress,
ETH_ALEN);
wireless_send_event(padapter->pnetdev, SIOCGIWAP, &wrqu, NULL);
}
void r8712_indicate_wx_disassoc_event(struct _adapter *padapter)
{
union iwreq_data wrqu;
wrqu.ap_addr.sa_family = ARPHRD_ETHER;
eth_zero_addr(wrqu.ap_addr.sa_data);
wireless_send_event(padapter->pnetdev, SIOCGIWAP, &wrqu, NULL);
}
static inline void handle_pairwise_key(struct sta_info *psta,
struct ieee_param *param,
struct _adapter *padapter)
{
/* pairwise key */
memcpy(psta->x_UncstKey.skey, param->u.crypt.key,
(param->u.crypt. key_len > 16 ? 16 : param->u.crypt.key_len));
if (strcmp(param->u.crypt.alg, "TKIP") == 0) { /* set mic key */
memcpy(psta->tkiptxmickey. skey, &(param->u.crypt.
key[16]), 8);
memcpy(psta->tkiprxmickey. skey, &(param->u.crypt.
key[24]), 8);
padapter->securitypriv. busetkipkey = false;
mod_timer(&padapter->securitypriv.tkip_timer,
jiffies + msecs_to_jiffies(50));
}
r8712_setstakey_cmd(padapter, (unsigned char *)psta, true);
}
static inline void handle_group_key(struct ieee_param *param,
struct _adapter *padapter)
{
if (param->u.crypt.idx > 0 &&
param->u.crypt.idx < 3) {
/* group key idx is 1 or 2 */
memcpy(padapter->securitypriv.XGrpKey[param->u.crypt.
idx - 1].skey, param->u.crypt.key,
(param->u.crypt.key_len > 16 ? 16 :
param->u.crypt.key_len));
memcpy(padapter->securitypriv.XGrptxmickey[param->
u.crypt.idx - 1].skey, &(param->u.crypt.key[16]), 8);
memcpy(padapter->securitypriv. XGrprxmickey[param->
u.crypt.idx - 1].skey, &(param->u.crypt.key[24]), 8);
padapter->securitypriv.binstallGrpkey = true;
r8712_set_key(padapter, &padapter->securitypriv,
param->u.crypt.idx);
if (padapter->registrypriv.power_mgnt > PS_MODE_ACTIVE) {
if (padapter->registrypriv.power_mgnt != padapter->
pwrctrlpriv.pwr_mode)
mod_timer(&padapter->mlmepriv.dhcp_timer,
jiffies + msecs_to_jiffies(60000));
}
}
}
static noinline_for_stack char *translate_scan(struct _adapter *padapter,
struct iw_request_info *info,
struct wlan_network *pnetwork,
char *start, char *stop)
{
struct iw_event iwe;
struct ieee80211_ht_cap *pht_capie;
char *current_val;
s8 *p;
u32 i = 0, ht_ielen = 0;
u16 cap, ht_cap = false, mcs_rate;
u8 rssi;
if ((pnetwork->network.Configuration.DSConfig < 1) ||
(pnetwork->network.Configuration.DSConfig > 14)) {
if (pnetwork->network.Configuration.DSConfig < 1)
pnetwork->network.Configuration.DSConfig = 1;
else
pnetwork->network.Configuration.DSConfig = 14;
}
/* AP MAC address */
iwe.cmd = SIOCGIWAP;
iwe.u.ap_addr.sa_family = ARPHRD_ETHER;
ether_addr_copy(iwe.u.ap_addr.sa_data, pnetwork->network.MacAddress);
start = iwe_stream_add_event(info, start, stop, &iwe, IW_EV_ADDR_LEN);
/* Add the ESSID */
iwe.cmd = SIOCGIWESSID;
iwe.u.data.flags = 1;
iwe.u.data.length = min_t(u32, pnetwork->network.Ssid.SsidLength, 32);
start = iwe_stream_add_point(info, start, stop, &iwe,
pnetwork->network.Ssid.Ssid);
/* parsing HT_CAP_IE */
p = r8712_get_ie(&pnetwork->network.IEs[12], _HT_CAPABILITY_IE_,
&ht_ielen, pnetwork->network.IELength - 12);
if (p && ht_ielen > 0) {
ht_cap = true;
pht_capie = (struct ieee80211_ht_cap *)(p + 2);
memcpy(&mcs_rate, pht_capie->supp_mcs_set, 2);
}
/* Add the protocol name */
iwe.cmd = SIOCGIWNAME;
if (r8712_is_cckratesonly_included(pnetwork->network.rates)) {
if (ht_cap)
snprintf(iwe.u.name, IFNAMSIZ, "IEEE 802.11bn");
else
snprintf(iwe.u.name, IFNAMSIZ, "IEEE 802.11b");
} else if (r8712_is_cckrates_included(pnetwork->network.rates)) {
if (ht_cap)
snprintf(iwe.u.name, IFNAMSIZ, "IEEE 802.11bgn");
else
snprintf(iwe.u.name, IFNAMSIZ, "IEEE 802.11bg");
} else {
if (ht_cap)
snprintf(iwe.u.name, IFNAMSIZ, "IEEE 802.11gn");
else
snprintf(iwe.u.name, IFNAMSIZ, "IEEE 802.11g");
}
start = iwe_stream_add_event(info, start, stop, &iwe, IW_EV_CHAR_LEN);
/* Add mode */
iwe.cmd = SIOCGIWMODE;
memcpy((u8 *)&cap, r8712_get_capability_from_ie(pnetwork->network.IEs),
2);
cap = le16_to_cpu(cap);
if (cap & (WLAN_CAPABILITY_IBSS | WLAN_CAPABILITY_BSS)) {
if (cap & WLAN_CAPABILITY_BSS)
iwe.u.mode = (u32)IW_MODE_MASTER;
else
iwe.u.mode = (u32)IW_MODE_ADHOC;
start = iwe_stream_add_event(info, start, stop, &iwe,
IW_EV_UINT_LEN);
}
/* Add frequency/channel */
iwe.cmd = SIOCGIWFREQ;
{
/* check legal index */
u8 dsconfig = pnetwork->network.Configuration.DSConfig;
if (dsconfig >= 1 && dsconfig <= sizeof(
ieee80211_wlan_frequencies) / sizeof(long))
iwe.u.freq.m = (s32)(ieee80211_wlan_frequencies[
pnetwork->network.Configuration.
DSConfig - 1] * 100000);
else
iwe.u.freq.m = 0;
}
iwe.u.freq.e = (s16)1;
iwe.u.freq.i = (u8)pnetwork->network.Configuration.DSConfig;
start = iwe_stream_add_event(info, start, stop, &iwe,
IW_EV_FREQ_LEN);
/* Add encryption capability */
iwe.cmd = SIOCGIWENCODE;
if (cap & WLAN_CAPABILITY_PRIVACY)
iwe.u.data.flags = (u16)(IW_ENCODE_ENABLED |
IW_ENCODE_NOKEY);
else
iwe.u.data.flags = (u16)(IW_ENCODE_DISABLED);
iwe.u.data.length = (u16)0;
start = iwe_stream_add_point(info, start, stop, &iwe,
pnetwork->network.Ssid.Ssid);
/*Add basic and extended rates */
current_val = start + iwe_stream_lcp_len(info);
iwe.cmd = SIOCGIWRATE;
iwe.u.bitrate.fixed = 0;
iwe.u.bitrate.disabled = 0;
iwe.u.bitrate.value = 0;
i = 0;
while (pnetwork->network.rates[i] != 0) {
/* Bit rate given in 500 kb/s units */
iwe.u.bitrate.value = (pnetwork->network.rates[i++] &
0x7F) * 500000;
current_val = iwe_stream_add_value(info, start, current_val,
stop, &iwe, IW_EV_PARAM_LEN);
}
/* Check if we added any event */
if ((current_val - start) > iwe_stream_lcp_len(info))
start = current_val;
/* parsing WPA/WPA2 IE */
{
u8 buf[MAX_WPA_IE_LEN];
u8 wpa_ie[255], rsn_ie[255];
u16 wpa_len = 0, rsn_len = 0;
int n;
r8712_get_sec_ie(pnetwork->network.IEs,
pnetwork->network.IELength, rsn_ie, &rsn_len,
wpa_ie, &wpa_len);
if (wpa_len > 0) {
memset(buf, 0, MAX_WPA_IE_LEN);
n = sprintf(buf, "wpa_ie=");
for (i = 0; i < wpa_len; i++) {
n += snprintf(buf + n, MAX_WPA_IE_LEN - n,
"%02x", wpa_ie[i]);
if (n >= MAX_WPA_IE_LEN)
break;
}
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = IWEVCUSTOM;
iwe.u.data.length = (u16)strlen(buf);
start = iwe_stream_add_point(info, start, stop,
&iwe, buf);
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = IWEVGENIE;
iwe.u.data.length = (u16)wpa_len;
start = iwe_stream_add_point(info, start, stop,
&iwe, wpa_ie);
}
if (rsn_len > 0) {
memset(buf, 0, MAX_WPA_IE_LEN);
n = sprintf(buf, "rsn_ie=");
for (i = 0; i < rsn_len; i++) {
n += snprintf(buf + n, MAX_WPA_IE_LEN - n,
"%02x", rsn_ie[i]);
if (n >= MAX_WPA_IE_LEN)
break;
}
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = IWEVCUSTOM;
iwe.u.data.length = strlen(buf);
start = iwe_stream_add_point(info, start, stop,
&iwe, buf);
memset(&iwe, 0, sizeof(iwe));
iwe.cmd = IWEVGENIE;
iwe.u.data.length = rsn_len;
start = iwe_stream_add_point(info, start, stop, &iwe,
rsn_ie);
}
}
{ /* parsing WPS IE */
u8 wps_ie[512];
uint wps_ielen;
if (r8712_get_wps_ie(pnetwork->network.IEs,
pnetwork->network.IELength,
wps_ie, &wps_ielen)) {
if (wps_ielen > 2) {
iwe.cmd = IWEVGENIE;
iwe.u.data.length = (u16)wps_ielen;
start = iwe_stream_add_point(info, start, stop,
&iwe, wps_ie);
}
}
}
/* Add quality statistics */
iwe.cmd = IWEVQUAL;
rssi = r8712_signal_scale_mapping(pnetwork->network.Rssi);
/* we only update signal_level (signal strength) that is rssi. */
iwe.u.qual.updated = (u8)(IW_QUAL_QUAL_INVALID | IW_QUAL_LEVEL_UPDATED |
IW_QUAL_NOISE_INVALID);
iwe.u.qual.level = rssi; /* signal strength */
iwe.u.qual.qual = 0; /* signal quality */
iwe.u.qual.noise = 0; /* noise level */
start = iwe_stream_add_event(info, start, stop, &iwe, IW_EV_QUAL_LEN);
/* how to translate rssi to ?% */
return start;
}
static int wpa_set_auth_algs(struct net_device *dev, u32 value)
{
struct _adapter *padapter = netdev_priv(dev);
int ret = 0;
if ((value & AUTH_ALG_SHARED_KEY) && (value & AUTH_ALG_OPEN_SYSTEM)) {
padapter->securitypriv.ndisencryptstatus =
Ndis802_11Encryption1Enabled;
padapter->securitypriv.ndisauthtype =
Ndis802_11AuthModeAutoSwitch;
padapter->securitypriv.AuthAlgrthm = 3;
} else if (value & AUTH_ALG_SHARED_KEY) {
padapter->securitypriv.ndisencryptstatus =
Ndis802_11Encryption1Enabled;
padapter->securitypriv.ndisauthtype = Ndis802_11AuthModeShared;
padapter->securitypriv.AuthAlgrthm = 1;
} else if (value & AUTH_ALG_OPEN_SYSTEM) {
if (padapter->securitypriv.ndisauthtype <
Ndis802_11AuthModeWPAPSK) {
padapter->securitypriv.ndisauthtype =
Ndis802_11AuthModeOpen;
padapter->securitypriv.AuthAlgrthm = 0;
}
} else {
ret = -EINVAL;
}
return ret;
}
static int wpa_set_encryption(struct net_device *dev, struct ieee_param *param,
u32 param_len)
{
int ret = 0;
u32 wep_key_idx, wep_key_len = 0;
struct NDIS_802_11_WEP *pwep = NULL;
struct _adapter *padapter = netdev_priv(dev);
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
struct security_priv *psecuritypriv = &padapter->securitypriv;
param->u.crypt.err = 0;
param->u.crypt.alg[IEEE_CRYPT_ALG_NAME_LEN - 1] = '\0';
if (param_len != (u32)((u8 *) param->u.crypt.key - (u8 *)param) +
param->u.crypt.key_len)
return -EINVAL;
if (is_broadcast_ether_addr(param->sta_addr)) {
if (param->u.crypt.idx >= WEP_KEYS) {
/* for large key indices, set the default (0) */
param->u.crypt.idx = 0;
}
} else {
return -EINVAL;
}
if (strcmp(param->u.crypt.alg, "WEP") == 0) {
netdev_info(dev, "r8712u: %s: crypt.alg = WEP\n", __func__);
padapter->securitypriv.ndisencryptstatus =
Ndis802_11Encryption1Enabled;
padapter->securitypriv.PrivacyAlgrthm = _WEP40_;
padapter->securitypriv.XGrpPrivacy = _WEP40_;
wep_key_idx = param->u.crypt.idx;
wep_key_len = param->u.crypt.key_len;
if (wep_key_idx >= WEP_KEYS)
wep_key_idx = 0;
if (wep_key_len > 0) {
wep_key_len = wep_key_len <= 5 ? 5 : 13;
pwep = kzalloc(sizeof(*pwep), GFP_ATOMIC);
if (!pwep)
return -ENOMEM;
pwep->KeyLength = wep_key_len;
pwep->Length = wep_key_len +
FIELD_OFFSET(struct NDIS_802_11_WEP,
KeyMaterial);
if (wep_key_len == 13) {
padapter->securitypriv.PrivacyAlgrthm =
_WEP104_;
padapter->securitypriv.XGrpPrivacy =
_WEP104_;
}
} else {
return -EINVAL;
}
pwep->KeyIndex = wep_key_idx;
pwep->KeyIndex |= 0x80000000;
memcpy(pwep->KeyMaterial, param->u.crypt.key, pwep->KeyLength);
if (param->u.crypt.set_tx) {
if (r8712_set_802_11_add_wep(padapter, pwep) ==
(u8)_FAIL)
ret = -EOPNOTSUPP;
} else {
/* don't update "psecuritypriv->PrivacyAlgrthm" and
* "psecuritypriv->PrivacyKeyIndex=keyid", but can
* r8712_set_key to fw/cam
*/
if (wep_key_idx >= WEP_KEYS) {
ret = -EOPNOTSUPP;
goto exit;
}
memcpy(&(psecuritypriv->DefKey[wep_key_idx].
skey[0]), pwep->KeyMaterial,
pwep->KeyLength);
psecuritypriv->DefKeylen[wep_key_idx] =
pwep->KeyLength;
r8712_set_key(padapter, psecuritypriv, wep_key_idx);
}
goto exit;
}
if (padapter->securitypriv.AuthAlgrthm == 2) { /* 802_1x */
struct sta_info *psta, *pbcmc_sta;
struct sta_priv *pstapriv = &padapter->stapriv;
if (check_fwstate(pmlmepriv, WIFI_STATION_STATE |
WIFI_MP_STATE)) { /* sta mode */
psta = r8712_get_stainfo(pstapriv,
get_bssid(pmlmepriv));
if (psta) {
psta->ieee8021x_blocked = false;
if ((padapter->securitypriv.ndisencryptstatus ==
Ndis802_11Encryption2Enabled) ||
(padapter->securitypriv.ndisencryptstatus ==
Ndis802_11Encryption3Enabled))
psta->XPrivacy = padapter->
securitypriv.PrivacyAlgrthm;
if (param->u.crypt.set_tx == 1)
handle_pairwise_key(psta, param,
padapter);
else /* group key */
handle_group_key(param, padapter);
}
pbcmc_sta = r8712_get_bcmc_stainfo(padapter);
if (pbcmc_sta) {
pbcmc_sta->ieee8021x_blocked = false;
if ((padapter->securitypriv.ndisencryptstatus ==
Ndis802_11Encryption2Enabled) ||
(padapter->securitypriv.ndisencryptstatus ==
Ndis802_11Encryption3Enabled))
pbcmc_sta->XPrivacy =
padapter->securitypriv.
PrivacyAlgrthm;
}
}
}
exit:
kfree(pwep);
return ret;
}
static int r871x_set_wpa_ie(struct _adapter *padapter, char *pie,
unsigned short ielen)
{
u8 *buf = NULL;
int group_cipher = 0, pairwise_cipher = 0;
int ret = 0;
if ((ielen > MAX_WPA_IE_LEN) || (pie == NULL))
return -EINVAL;
if (ielen) {
buf = kmemdup(pie, ielen, GFP_ATOMIC);
if (buf == NULL)
return -ENOMEM;
if (ielen < RSN_HEADER_LEN) {
ret = -EINVAL;
goto exit;
}
if (r8712_parse_wpa_ie(buf, ielen, &group_cipher,
&pairwise_cipher) == _SUCCESS) {
padapter->securitypriv.AuthAlgrthm = 2;
padapter->securitypriv.ndisauthtype =
Ndis802_11AuthModeWPAPSK;
}
if (r8712_parse_wpa2_ie(buf, ielen, &group_cipher,
&pairwise_cipher) == _SUCCESS) {
padapter->securitypriv.AuthAlgrthm = 2;
padapter->securitypriv.ndisauthtype =
Ndis802_11AuthModeWPA2PSK;
}
switch (group_cipher) {
case WPA_CIPHER_NONE:
padapter->securitypriv.XGrpPrivacy =
_NO_PRIVACY_;
padapter->securitypriv.ndisencryptstatus =
Ndis802_11EncryptionDisabled;
break;
case WPA_CIPHER_WEP40:
padapter->securitypriv.XGrpPrivacy = _WEP40_;
padapter->securitypriv.ndisencryptstatus =
Ndis802_11Encryption1Enabled;
break;
case WPA_CIPHER_TKIP:
padapter->securitypriv.XGrpPrivacy = _TKIP_;
padapter->securitypriv.ndisencryptstatus =
Ndis802_11Encryption2Enabled;
break;
case WPA_CIPHER_CCMP:
padapter->securitypriv.XGrpPrivacy = _AES_;
padapter->securitypriv.ndisencryptstatus =
Ndis802_11Encryption3Enabled;
break;
case WPA_CIPHER_WEP104:
padapter->securitypriv.XGrpPrivacy = _WEP104_;
padapter->securitypriv.ndisencryptstatus =
Ndis802_11Encryption1Enabled;
break;
}
switch (pairwise_cipher) {
case WPA_CIPHER_NONE:
padapter->securitypriv.PrivacyAlgrthm =
_NO_PRIVACY_;
padapter->securitypriv.ndisencryptstatus =
Ndis802_11EncryptionDisabled;
break;
case WPA_CIPHER_WEP40:
padapter->securitypriv.PrivacyAlgrthm = _WEP40_;
padapter->securitypriv.ndisencryptstatus =
Ndis802_11Encryption1Enabled;
break;
case WPA_CIPHER_TKIP:
padapter->securitypriv.PrivacyAlgrthm = _TKIP_;
padapter->securitypriv.ndisencryptstatus =
Ndis802_11Encryption2Enabled;
break;
case WPA_CIPHER_CCMP:
padapter->securitypriv.PrivacyAlgrthm = _AES_;
padapter->securitypriv.ndisencryptstatus =
Ndis802_11Encryption3Enabled;
break;
case WPA_CIPHER_WEP104:
padapter->securitypriv.PrivacyAlgrthm = _WEP104_;
padapter->securitypriv.ndisencryptstatus =
Ndis802_11Encryption1Enabled;
break;
}
padapter->securitypriv.wps_phase = false;
{/* set wps_ie */
u16 cnt = 0;
u8 eid, wps_oui[4] = {0x0, 0x50, 0xf2, 0x04};
while (cnt < ielen) {
eid = buf[cnt];
if ((eid == _VENDOR_SPECIFIC_IE_) &&
(!memcmp(&buf[cnt + 2], wps_oui, 4))) {
netdev_info(padapter->pnetdev, "r8712u: SET WPS_IE\n");
padapter->securitypriv.wps_ie_len =
((buf[cnt + 1] + 2) <
(MAX_WPA_IE_LEN << 2)) ?
(buf[cnt + 1] + 2) :
(MAX_WPA_IE_LEN << 2);
memcpy(padapter->securitypriv.wps_ie,
&buf[cnt],
padapter->securitypriv.wps_ie_len);
padapter->securitypriv.wps_phase =
true;
netdev_info(padapter->pnetdev, "r8712u: SET WPS_IE, wps_phase==true\n");
cnt += buf[cnt + 1] + 2;
break;
} else {
cnt += buf[cnt + 1] + 2;
}
}
}
}
exit:
kfree(buf);
return ret;
}
static int r8711_wx_get_name(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct _adapter *padapter = netdev_priv(dev);
u32 ht_ielen = 0;
char *p;
u8 ht_cap = false;
struct mlme_priv *pmlmepriv = &(padapter->mlmepriv);
struct wlan_bssid_ex *pcur_bss = &pmlmepriv->cur_network.network;
u8 *prates;
if (check_fwstate(pmlmepriv, _FW_LINKED | WIFI_ADHOC_MASTER_STATE) ==
true) {
/* parsing HT_CAP_IE */
p = r8712_get_ie(&pcur_bss->IEs[12], _HT_CAPABILITY_IE_,
&ht_ielen, pcur_bss->IELength - 12);
if (p && ht_ielen > 0)
ht_cap = true;
prates = pcur_bss->rates;
if (r8712_is_cckratesonly_included(prates)) {
if (ht_cap)
snprintf(wrqu->name, IFNAMSIZ,
"IEEE 802.11bn");
else
snprintf(wrqu->name, IFNAMSIZ,
"IEEE 802.11b");
} else if (r8712_is_cckrates_included(prates)) {
if (ht_cap)
snprintf(wrqu->name, IFNAMSIZ,
"IEEE 802.11bgn");
else
snprintf(wrqu->name, IFNAMSIZ,
"IEEE 802.11bg");
} else {
if (ht_cap)
snprintf(wrqu->name, IFNAMSIZ,
"IEEE 802.11gn");
else
snprintf(wrqu->name, IFNAMSIZ,
"IEEE 802.11g");
}
} else {
snprintf(wrqu->name, IFNAMSIZ, "unassociated");
}
return 0;
}
static const long frequency_list[] = {
2412, 2417, 2422, 2427, 2432, 2437, 2442, 2447, 2452, 2457, 2462,
2467, 2472, 2484, 4915, 4920, 4925, 4935, 4940, 4945, 4960, 4980,
5035, 5040, 5045, 5055, 5060, 5080, 5170, 5180, 5190, 5200, 5210,
5220, 5230, 5240, 5260, 5280, 5300, 5320, 5500, 5520, 5540, 5560,
5580, 5600, 5620, 5640, 5660, 5680, 5700, 5745, 5765, 5785, 5805,
5825
};
static int r8711_wx_set_freq(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct _adapter *padapter = netdev_priv(dev);
struct iw_freq *fwrq = &wrqu->freq;
int rc = 0;
/* If setting by frequency, convert to a channel */
if ((fwrq->e == 1) &&
(fwrq->m >= (int) 2.412e8) &&
(fwrq->m <= (int) 2.487e8)) {
int f = fwrq->m / 100000;
int c = 0;
while ((c < 14) && (f != frequency_list[c]))
c++;
fwrq->e = 0;
fwrq->m = c + 1;
}
/* Setting by channel number */
if ((fwrq->m > 14) || (fwrq->e > 0)) {
rc = -EOPNOTSUPP;
} else {
int channel = fwrq->m;
if ((channel < 1) || (channel > 14)) {
rc = -EINVAL;
} else {
/* Yes ! We can set it !!! */
padapter->registrypriv.channel = channel;
}
}
return rc;
}
static int r8711_wx_get_freq(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct _adapter *padapter = netdev_priv(dev);
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
struct wlan_bssid_ex *pcur_bss = &pmlmepriv->cur_network.network;
if (check_fwstate(pmlmepriv, _FW_LINKED)) {
wrqu->freq.m = ieee80211_wlan_frequencies[
pcur_bss->Configuration.DSConfig - 1] * 100000;
wrqu->freq.e = 1;
wrqu->freq.i = pcur_bss->Configuration.DSConfig;
} else {
return -ENOLINK;
}
return 0;
}
static int r8711_wx_set_mode(struct net_device *dev,
struct iw_request_info *a,
union iwreq_data *wrqu, char *b)
{
struct _adapter *padapter = netdev_priv(dev);
enum NDIS_802_11_NETWORK_INFRASTRUCTURE networkType;
switch (wrqu->mode) {
case IW_MODE_AUTO:
networkType = Ndis802_11AutoUnknown;
break;
case IW_MODE_ADHOC:
networkType = Ndis802_11IBSS;
break;
case IW_MODE_MASTER:
networkType = Ndis802_11APMode;
break;
case IW_MODE_INFRA:
networkType = Ndis802_11Infrastructure;
break;
default:
return -EINVAL;
}
if (Ndis802_11APMode == networkType)
r8712_setopmode_cmd(padapter, networkType);
else
r8712_setopmode_cmd(padapter, Ndis802_11AutoUnknown);
r8712_set_802_11_infrastructure_mode(padapter, networkType);
return 0;
}
static int r8711_wx_get_mode(struct net_device *dev, struct iw_request_info *a,
union iwreq_data *wrqu, char *b)
{
struct _adapter *padapter = netdev_priv(dev);
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
if (check_fwstate(pmlmepriv, WIFI_STATION_STATE))
wrqu->mode = IW_MODE_INFRA;
else if (check_fwstate(pmlmepriv,
WIFI_ADHOC_MASTER_STATE | WIFI_ADHOC_STATE))
wrqu->mode = IW_MODE_ADHOC;
else if (check_fwstate(pmlmepriv, WIFI_AP_STATE))
wrqu->mode = IW_MODE_MASTER;
else
wrqu->mode = IW_MODE_AUTO;
return 0;
}
static int r871x_wx_set_pmkid(struct net_device *dev,
struct iw_request_info *a,
union iwreq_data *wrqu, char *extra)
{
struct _adapter *padapter = netdev_priv(dev);
struct security_priv *psecuritypriv = &padapter->securitypriv;
struct iw_pmksa *pPMK = (struct iw_pmksa *) extra;
u8 strZeroMacAddress[ETH_ALEN] = {0x00};
u8 strIssueBssid[ETH_ALEN] = {0x00};
u8 j, blInserted = false;
int intReturn = false;
/*
* There are the BSSID information in the bssid.sa_data array.
* If cmd is IW_PMKSA_FLUSH, it means the wpa_supplicant wants to clear
* all the PMKID information. If cmd is IW_PMKSA_ADD, it means the
* wpa_supplicant wants to add a PMKID/BSSID to driver.
* If cmd is IW_PMKSA_REMOVE, it means the wpa_supplicant wants to
* remove a PMKID/BSSID from driver.
*/
if (pPMK == NULL)
return -EINVAL;
memcpy(strIssueBssid, pPMK->bssid.sa_data, ETH_ALEN);
switch (pPMK->cmd) {
case IW_PMKSA_ADD:
if (!memcmp(strIssueBssid, strZeroMacAddress, ETH_ALEN))
return intReturn;
intReturn = true;
blInserted = false;
/* overwrite PMKID */
for (j = 0; j < NUM_PMKID_CACHE; j++) {
if (!memcmp(psecuritypriv->PMKIDList[j].Bssid,
strIssueBssid, ETH_ALEN)) {
/* BSSID is matched, the same AP => rewrite
* with new PMKID.
*/
netdev_info(dev, "r8712u: %s: BSSID exists in the PMKList.\n",
__func__);
memcpy(psecuritypriv->PMKIDList[j].PMKID,
pPMK->pmkid, IW_PMKID_LEN);
psecuritypriv->PMKIDList[j].bUsed = true;
psecuritypriv->PMKIDIndex = j + 1;
blInserted = true;
break;
}
}
if (!blInserted) {
/* Find a new entry */
netdev_info(dev, "r8712u: %s: Use the new entry index = %d for this PMKID.\n",
__func__, psecuritypriv->PMKIDIndex);
memcpy(psecuritypriv->PMKIDList[psecuritypriv->
PMKIDIndex].Bssid, strIssueBssid, ETH_ALEN);
memcpy(psecuritypriv->PMKIDList[psecuritypriv->
PMKIDIndex].PMKID, pPMK->pmkid, IW_PMKID_LEN);
psecuritypriv->PMKIDList[psecuritypriv->PMKIDIndex].
bUsed = true;
psecuritypriv->PMKIDIndex++;
if (psecuritypriv->PMKIDIndex == NUM_PMKID_CACHE)
psecuritypriv->PMKIDIndex = 0;
}
break;
case IW_PMKSA_REMOVE:
intReturn = true;
for (j = 0; j < NUM_PMKID_CACHE; j++) {
if (!memcmp(psecuritypriv->PMKIDList[j].Bssid,
strIssueBssid, ETH_ALEN)) {
/* BSSID is matched, the same AP => Remove
* this PMKID information and reset it.
*/
eth_zero_addr(psecuritypriv->PMKIDList[j].Bssid);
psecuritypriv->PMKIDList[j].bUsed = false;
break;
}
}
break;
case IW_PMKSA_FLUSH:
memset(psecuritypriv->PMKIDList, 0,
sizeof(struct RT_PMKID_LIST) * NUM_PMKID_CACHE);
psecuritypriv->PMKIDIndex = 0;
intReturn = true;
break;
default:
netdev_info(dev, "r8712u: %s: unknown Command\n", __func__);
intReturn = false;
break;
}
return intReturn;
}
static int r8711_wx_get_sens(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
wrqu->sens.value = 0;
wrqu->sens.fixed = 0; /* no auto select */
wrqu->sens.disabled = 1;
return 0;
}
static int r8711_wx_get_range(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct iw_range *range = (struct iw_range *)extra;
u16 val;
int i;
wrqu->data.length = sizeof(*range);
memset(range, 0, sizeof(*range));
/* Let's try to keep this struct in the same order as in
* linux/include/wireless.h
*/
/* TODO: See what values we can set, and remove the ones we can't
* set, or fill them with some default data.
*/
/* ~5 Mb/s real (802.11b) */
range->throughput = 5 * 1000 * 1000;
/* TODO: 8711 sensitivity ? */
/* signal level threshold range */
/* percent values between 0 and 100. */
range->max_qual.qual = 100;
range->max_qual.level = 100;
range->max_qual.noise = 100;
range->max_qual.updated = 7; /* Updated all three */
range->avg_qual.qual = 92; /* > 8% missed beacons is 'bad' */
/* TODO: Find real 'good' to 'bad' threshold value for RSSI */
range->avg_qual.level = 0x100 - 78;
range->avg_qual.noise = 0;
range->avg_qual.updated = 7; /* Updated all three */
range->num_bitrates = RATE_COUNT;
for (i = 0; i < RATE_COUNT && i < IW_MAX_BITRATES; i++)
range->bitrate[i] = rtl8180_rates[i];
range->min_frag = MIN_FRAG_THRESHOLD;
range->max_frag = MAX_FRAG_THRESHOLD;
range->pm_capa = 0;
range->we_version_compiled = WIRELESS_EXT;
range->we_version_source = 16;
range->num_channels = 14;
for (i = 0, val = 0; i < 14; i++) {
/* Include only legal frequencies for some countries */
range->freq[val].i = i + 1;
range->freq[val].m = ieee80211_wlan_frequencies[i] * 100000;
range->freq[val].e = 1;
val++;
if (val == IW_MAX_FREQUENCIES)
break;
}
range->num_frequency = val;
range->enc_capa = IW_ENC_CAPA_WPA |
IW_ENC_CAPA_WPA2 |
IW_ENC_CAPA_CIPHER_TKIP |
IW_ENC_CAPA_CIPHER_CCMP;
return 0;
}
static int r8711_wx_get_rate(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra);
static int r871x_wx_set_priv(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *awrq,
char *extra)
{
int ret = 0, len = 0;
char *ext;
struct _adapter *padapter = netdev_priv(dev);
struct iw_point *dwrq = (struct iw_point *)awrq;
len = dwrq->length;
ext = memdup_user(dwrq->pointer, len);
if (IS_ERR(ext))
return PTR_ERR(ext);
if (!strcasecmp(ext, "RSSI")) {
/*Return received signal strength indicator in -db for */
/* current AP */
/*<ssid> Rssi xx */
struct mlme_priv *pmlmepriv = &(padapter->mlmepriv);
struct wlan_network *pcur_network = &pmlmepriv->cur_network;
/*static u8 xxxx; */
if (check_fwstate(pmlmepriv, _FW_LINKED)) {
sprintf(ext, "%s rssi %d",
pcur_network->network.Ssid.Ssid,
/*(xxxx=xxxx+10) */
((padapter->recvpriv.fw_rssi) >> 1) - 95
/*pcur_network->network.Rssi */
);
} else {
sprintf(ext, "OK");
}
} else if (!strcasecmp(ext, "LINKSPEED")) {
/*Return link speed in MBPS */
/*LinkSpeed xx */
union iwreq_data wrqd;
int ret_inner;
int mbps;
ret_inner = r8711_wx_get_rate(dev, info, &wrqd, extra);
if (ret_inner != 0)
mbps = 0;
else
mbps = wrqd.bitrate.value / 1000000;
sprintf(ext, "LINKSPEED %d", mbps);
} else if (!strcasecmp(ext, "MACADDR")) {
/*Return mac address of the station */
/* Macaddr = xx:xx:xx:xx:xx:xx */
sprintf(ext, "MACADDR = %pM", dev->dev_addr);
} else if (!strcasecmp(ext, "SCAN-ACTIVE")) {
/*Set scan type to active */
/*OK if successful */
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
pmlmepriv->passive_mode = 1;
sprintf(ext, "OK");
} else if (!strcasecmp(ext, "SCAN-PASSIVE")) {
/*Set scan type to passive */
/*OK if successful */
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
pmlmepriv->passive_mode = 0;
sprintf(ext, "OK");
} else if (!strncmp(ext, "DCE-E", 5)) {
/*Set scan type to passive */
/*OK if successful */
r8712_disconnectCtrlEx_cmd(padapter
, 1 /*u32 enableDrvCtrl */
, 5 /*u32 tryPktCnt */
, 100 /*u32 tryPktInterval */
, 5000 /*u32 firstStageTO */
);
sprintf(ext, "OK");
} else if (!strncmp(ext, "DCE-D", 5)) {
/*Set scan type to passive */
/*OK if successfu */
r8712_disconnectCtrlEx_cmd(padapter
, 0 /*u32 enableDrvCtrl */
, 5 /*u32 tryPktCnt */
, 100 /*u32 tryPktInterval */
, 5000 /*u32 firstStageTO */
);
sprintf(ext, "OK");
} else {
netdev_info(dev, "r8712u: %s: unknown Command %s.\n",
__func__, ext);
goto FREE_EXT;
}
if (copy_to_user(dwrq->pointer, ext,
min(dwrq->length, (__u16)(strlen(ext) + 1))))
ret = -EFAULT;
FREE_EXT:
kfree(ext);
return ret;
}
/* set bssid flow
* s1. set_802_11_infrastructure_mode()
* s2. set_802_11_authentication_mode()
* s3. set_802_11_encryption_mode()
* s4. set_802_11_bssid()
*
* This function intends to handle the Set AP command, which specifies the
* MAC# of a preferred Access Point.
* Currently, the request comes via Wireless Extensions' SIOCSIWAP ioctl.
*
* For this operation to succeed, there is no need for the interface to be up.
*
*/
static int r8711_wx_set_wap(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *awrq,
char *extra)
{
int ret = -EINPROGRESS;
struct _adapter *padapter = netdev_priv(dev);
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
struct __queue *queue = &pmlmepriv->scanned_queue;
struct sockaddr *temp = (struct sockaddr *)awrq;
unsigned long irqL;
struct list_head *phead;
u8 *dst_bssid;
struct wlan_network *pnetwork = NULL;
enum NDIS_802_11_AUTHENTICATION_MODE authmode;
if (check_fwstate(pmlmepriv, _FW_UNDER_SURVEY))
return -EBUSY;
if (check_fwstate(pmlmepriv, _FW_UNDER_LINKING))
return ret;
if (temp->sa_family != ARPHRD_ETHER)
return -EINVAL;
authmode = padapter->securitypriv.ndisauthtype;
spin_lock_irqsave(&queue->lock, irqL);
phead = &queue->queue;
pmlmepriv->pscanned = phead->next;
while (1) {
if (end_of_queue_search(phead, pmlmepriv->pscanned))
break;
pnetwork = container_of(pmlmepriv->pscanned,
struct wlan_network, list);
pmlmepriv->pscanned = pmlmepriv->pscanned->next;
dst_bssid = pnetwork->network.MacAddress;
if (!memcmp(dst_bssid, temp->sa_data, ETH_ALEN)) {
r8712_set_802_11_infrastructure_mode(padapter,
pnetwork->network.InfrastructureMode);
break;
}
}
spin_unlock_irqrestore(&queue->lock, irqL);
if (!ret) {
if (!r8712_set_802_11_authentication_mode(padapter, authmode)) {
ret = -ENOMEM;
} else {
if (!r8712_set_802_11_bssid(padapter, temp->sa_data))
ret = -1;
}
}
return ret;
}
static int r8711_wx_get_wap(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct _adapter *padapter = netdev_priv(dev);
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
struct wlan_bssid_ex *pcur_bss = &pmlmepriv->cur_network.network;
wrqu->ap_addr.sa_family = ARPHRD_ETHER;
if (check_fwstate(pmlmepriv, _FW_LINKED | WIFI_ADHOC_MASTER_STATE |
WIFI_AP_STATE))
ether_addr_copy(wrqu->ap_addr.sa_data, pcur_bss->MacAddress);
else
eth_zero_addr(wrqu->ap_addr.sa_data);
return 0;
}
static int r871x_wx_set_mlme(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
int ret = 0;
struct _adapter *padapter = netdev_priv(dev);
struct iw_mlme *mlme = (struct iw_mlme *) extra;
if (mlme == NULL)
return -1;
switch (mlme->cmd) {
case IW_MLME_DEAUTH:
if (!r8712_set_802_11_disassociate(padapter))
ret = -1;
break;
case IW_MLME_DISASSOC:
if (!r8712_set_802_11_disassociate(padapter))
ret = -1;
break;
default:
return -EOPNOTSUPP;
}
return ret;
}
/**
*
* This function intends to handle the Set Scan command.
* Currently, the request comes via Wireless Extensions' SIOCSIWSCAN ioctl.
*
* For this operation to succeed, the interface is brought Up beforehand.
*
*/
static int r8711_wx_set_scan(struct net_device *dev,
struct iw_request_info *a,
union iwreq_data *wrqu, char *extra)
{
struct _adapter *padapter = netdev_priv(dev);
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
u8 status = true;
if (padapter->bDriverStopped) {
netdev_info(dev, "In %s: bDriverStopped=%d\n",
__func__, padapter->bDriverStopped);
return -1;
}
if (!padapter->bup)
return -ENETDOWN;
if (!padapter->hw_init_completed)
return -1;
if ((check_fwstate(pmlmepriv, _FW_UNDER_SURVEY | _FW_UNDER_LINKING)) ||
(pmlmepriv->sitesurveyctrl.traffic_busy))
return 0;
if (wrqu->data.length == sizeof(struct iw_scan_req)) {
struct iw_scan_req *req = (struct iw_scan_req *)extra;
if (wrqu->data.flags & IW_SCAN_THIS_ESSID) {
struct ndis_802_11_ssid ssid;
unsigned long irqL;
u32 len = min_t(u8, req->essid_len, IW_ESSID_MAX_SIZE);
memset((unsigned char *)&ssid, 0,
sizeof(struct ndis_802_11_ssid));
memcpy(ssid.Ssid, req->essid, len);
ssid.SsidLength = len;
spin_lock_irqsave(&pmlmepriv->lock, irqL);
if ((check_fwstate(pmlmepriv, _FW_UNDER_SURVEY |
_FW_UNDER_LINKING)) ||
(pmlmepriv->sitesurveyctrl.traffic_busy)) {
if (check_fwstate(pmlmepriv, _FW_UNDER_LINKING))
status = false;
} else {
status = r8712_sitesurvey_cmd(padapter, &ssid);
}
spin_unlock_irqrestore(&pmlmepriv->lock, irqL);
}
} else {
status = r8712_set_802_11_bssid_list_scan(padapter);
}
if (!status)
return -1;
return 0;
}
static int r8711_wx_get_scan(struct net_device *dev,
struct iw_request_info *a,
union iwreq_data *wrqu, char *extra)
{
struct _adapter *padapter = netdev_priv(dev);
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
struct __queue *queue = &pmlmepriv->scanned_queue;
struct wlan_network *pnetwork = NULL;
unsigned long irqL;
struct list_head *plist, *phead;
char *ev = extra;
char *stop = ev + wrqu->data.length;
u32 ret = 0, cnt = 0;
if (padapter->bDriverStopped)
return -EINVAL;
while (check_fwstate(pmlmepriv, _FW_UNDER_SURVEY |
_FW_UNDER_LINKING)) {
msleep(30);
cnt++;
if (cnt > 100)
break;
}
spin_lock_irqsave(&queue->lock, irqL);
phead = &queue->queue;
plist = phead->next;
while (1) {
if (end_of_queue_search(phead, plist))
break;
if ((stop - ev) < SCAN_ITEM_SIZE) {
ret = -E2BIG;
break;
}
pnetwork = container_of(plist, struct wlan_network, list);
ev = translate_scan(padapter, a, pnetwork, ev, stop);
plist = plist->next;
}
spin_unlock_irqrestore(&queue->lock, irqL);
wrqu->data.length = ev - extra;
wrqu->data.flags = 0;
return ret;
}
/* set ssid flow
* s1. set_802_11_infrastructure_mode()
* s2. set_802_11_authenticaion_mode()
* s3. set_802_11_encryption_mode()
* s4. set_802_11_ssid()
*
* This function intends to handle the Set ESSID command.
* Currently, the request comes via the Wireless Extensions' SIOCSIWESSID ioctl.
*
* For this operation to succeed, there is no need for the interface to be Up.
*
*/
static int r8711_wx_set_essid(struct net_device *dev,
struct iw_request_info *a,
union iwreq_data *wrqu, char *extra)
{
struct _adapter *padapter = netdev_priv(dev);
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
struct __queue *queue = &pmlmepriv->scanned_queue;
struct wlan_network *pnetwork = NULL;
enum NDIS_802_11_AUTHENTICATION_MODE authmode;
struct ndis_802_11_ssid ndis_ssid;
u8 *dst_ssid, *src_ssid;
struct list_head *phead;
u32 len;
if (check_fwstate(pmlmepriv, _FW_UNDER_SURVEY))
return -EBUSY;
if (check_fwstate(pmlmepriv, _FW_UNDER_LINKING))
return 0;
if (wrqu->essid.length > IW_ESSID_MAX_SIZE)
return -E2BIG;
authmode = padapter->securitypriv.ndisauthtype;
if (wrqu->essid.flags && wrqu->essid.length) {
len = (wrqu->essid.length < IW_ESSID_MAX_SIZE) ?
wrqu->essid.length : IW_ESSID_MAX_SIZE;
memset(&ndis_ssid, 0, sizeof(struct ndis_802_11_ssid));
ndis_ssid.SsidLength = len;
memcpy(ndis_ssid.Ssid, extra, len);
src_ssid = ndis_ssid.Ssid;
phead = &queue->queue;
pmlmepriv->pscanned = phead->next;
while (1) {
if (end_of_queue_search(phead, pmlmepriv->pscanned))
break;
pnetwork = container_of(pmlmepriv->pscanned,
struct wlan_network, list);
pmlmepriv->pscanned = pmlmepriv->pscanned->next;
dst_ssid = pnetwork->network.Ssid.Ssid;
if ((!memcmp(dst_ssid, src_ssid, ndis_ssid.SsidLength))
&& (pnetwork->network.Ssid.SsidLength ==
ndis_ssid.SsidLength)) {
if (check_fwstate(pmlmepriv,
WIFI_ADHOC_STATE)) {
if (pnetwork->network.
InfrastructureMode
!=
padapter->mlmepriv.
cur_network.network.
InfrastructureMode)
continue;
}
r8712_set_802_11_infrastructure_mode(
padapter,
pnetwork->network.InfrastructureMode);
break;
}
}
r8712_set_802_11_authentication_mode(padapter, authmode);
r8712_set_802_11_ssid(padapter, &ndis_ssid);
}
return -EINPROGRESS;
}
static int r8711_wx_get_essid(struct net_device *dev,
struct iw_request_info *a,
union iwreq_data *wrqu, char *extra)
{
struct _adapter *padapter = netdev_priv(dev);
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
struct wlan_bssid_ex *pcur_bss = &pmlmepriv->cur_network.network;
u32 len, ret = 0;
if (check_fwstate(pmlmepriv, _FW_LINKED | WIFI_ADHOC_MASTER_STATE)) {
len = pcur_bss->Ssid.SsidLength;
wrqu->essid.length = len;
memcpy(extra, pcur_bss->Ssid.Ssid, len);
wrqu->essid.flags = 1;
} else {
ret = -ENOLINK;
}
return ret;
}
static int r8711_wx_set_rate(struct net_device *dev,
struct iw_request_info *a,
union iwreq_data *wrqu, char *extra)
{
struct _adapter *padapter = netdev_priv(dev);
u32 target_rate = wrqu->bitrate.value;
u32 fixed = wrqu->bitrate.fixed;
u32 ratevalue = 0;
u8 datarates[NumRates];
u8 mpdatarate[NumRates] = {11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0xff};
int i, ret = 0;
if (target_rate == -1) {
ratevalue = 11;
goto set_rate;
}
target_rate = target_rate / 100000;
switch (target_rate) {
case 10:
ratevalue = 0;
break;
case 20:
ratevalue = 1;
break;
case 55:
ratevalue = 2;
break;
case 60:
ratevalue = 3;
break;
case 90:
ratevalue = 4;
break;
case 110:
ratevalue = 5;
break;
case 120:
ratevalue = 6;
break;
case 180:
ratevalue = 7;
break;
case 240:
ratevalue = 8;
break;
case 360:
ratevalue = 9;
break;
case 480:
ratevalue = 10;
break;
case 540:
ratevalue = 11;
break;
default:
ratevalue = 11;
break;
}
set_rate:
for (i = 0; i < NumRates; i++) {
if (ratevalue == mpdatarate[i]) {
datarates[i] = mpdatarate[i];
if (fixed == 0)
break;
} else {
datarates[i] = 0xff;
}
}
if (r8712_setdatarate_cmd(padapter, datarates) != _SUCCESS)
ret = -ENOMEM;
return ret;
}
static int r8711_wx_get_rate(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct _adapter *padapter = netdev_priv(dev);
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
struct wlan_bssid_ex *pcur_bss = &pmlmepriv->cur_network.network;
struct ieee80211_ht_cap *pht_capie;
unsigned char rf_type = padapter->registrypriv.rf_config;
int i;
u8 *p;
u16 rate, max_rate = 0, ht_cap = false;
u32 ht_ielen = 0;
u8 bw_40MHz = 0, short_GI = 0;
u16 mcs_rate = 0;
i = 0;
if (check_fwstate(pmlmepriv, _FW_LINKED | WIFI_ADHOC_MASTER_STATE)) {
p = r8712_get_ie(&pcur_bss->IEs[12],
_HT_CAPABILITY_IE_, &ht_ielen,
pcur_bss->IELength - 12);
if (p && ht_ielen > 0) {
ht_cap = true;
pht_capie = (struct ieee80211_ht_cap *)(p + 2);
memcpy(&mcs_rate, pht_capie->supp_mcs_set, 2);
bw_40MHz = (pht_capie->cap_info &
IEEE80211_HT_CAP_SUP_WIDTH) ? 1 : 0;
short_GI = (pht_capie->cap_info &
(IEEE80211_HT_CAP_SGI_20 |
IEEE80211_HT_CAP_SGI_40)) ? 1 : 0;
}
while ((pcur_bss->rates[i] != 0) &&
(pcur_bss->rates[i] != 0xFF)) {
rate = pcur_bss->rates[i] & 0x7F;
if (rate > max_rate)
max_rate = rate;
wrqu->bitrate.fixed = 0; /* no auto select */
wrqu->bitrate.value = rate * 500000;
i++;
}
if (ht_cap) {
if (mcs_rate & 0x8000 /* MCS15 */
&&
rf_type == RTL8712_RF_2T2R)
max_rate = (bw_40MHz) ? ((short_GI) ? 300 :
270) : ((short_GI) ? 144 : 130);
else /* default MCS7 */
max_rate = (bw_40MHz) ? ((short_GI) ? 150 :
135) : ((short_GI) ? 72 : 65);
max_rate *= 2; /* Mbps/2 */
}
wrqu->bitrate.value = max_rate * 500000;
} else {
return -ENOLINK;
}
return 0;
}
static int r8711_wx_get_rts(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct _adapter *padapter = netdev_priv(dev);
wrqu->rts.value = padapter->registrypriv.rts_thresh;
wrqu->rts.fixed = 0; /* no auto select */
return 0;
}
static int r8711_wx_set_frag(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct _adapter *padapter = netdev_priv(dev);
if (wrqu->frag.disabled) {
padapter->xmitpriv.frag_len = MAX_FRAG_THRESHOLD;
} else {
if (wrqu->frag.value < MIN_FRAG_THRESHOLD ||
wrqu->frag.value > MAX_FRAG_THRESHOLD)
return -EINVAL;
padapter->xmitpriv.frag_len = wrqu->frag.value & ~0x1;
}
return 0;
}
static int r8711_wx_get_frag(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct _adapter *padapter = netdev_priv(dev);
wrqu->frag.value = padapter->xmitpriv.frag_len;
wrqu->frag.fixed = 0; /* no auto select */
return 0;
}
static int r8711_wx_get_retry(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
wrqu->retry.value = 7;
wrqu->retry.fixed = 0; /* no auto select */
wrqu->retry.disabled = 1;
return 0;
}
static int r8711_wx_set_enc(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *keybuf)
{
u32 key;
u32 keyindex_provided;
struct NDIS_802_11_WEP wep;
enum NDIS_802_11_AUTHENTICATION_MODE authmode;
struct iw_point *erq = &(wrqu->encoding);
struct _adapter *padapter = netdev_priv(dev);
key = erq->flags & IW_ENCODE_INDEX;
memset(&wep, 0, sizeof(struct NDIS_802_11_WEP));
if (erq->flags & IW_ENCODE_DISABLED) {
netdev_info(dev, "r8712u: %s: EncryptionDisabled\n", __func__);
padapter->securitypriv.ndisencryptstatus =
Ndis802_11EncryptionDisabled;
padapter->securitypriv.PrivacyAlgrthm = _NO_PRIVACY_;
padapter->securitypriv.XGrpPrivacy = _NO_PRIVACY_;
padapter->securitypriv.AuthAlgrthm = 0; /* open system */
authmode = Ndis802_11AuthModeOpen;
padapter->securitypriv.ndisauthtype = authmode;
return 0;
}
if (key) {
if (key > WEP_KEYS)
return -EINVAL;
key--;
keyindex_provided = 1;
} else {
keyindex_provided = 0;
key = padapter->securitypriv.PrivacyKeyIndex;
}
/* set authentication mode */
if (erq->flags & IW_ENCODE_OPEN) {
netdev_info(dev, "r8712u: %s: IW_ENCODE_OPEN\n", __func__);
padapter->securitypriv.ndisencryptstatus =
Ndis802_11Encryption1Enabled;
padapter->securitypriv.AuthAlgrthm = 0; /* open system */
padapter->securitypriv.PrivacyAlgrthm = _NO_PRIVACY_;
padapter->securitypriv.XGrpPrivacy = _NO_PRIVACY_;
authmode = Ndis802_11AuthModeOpen;
padapter->securitypriv.ndisauthtype = authmode;
} else if (erq->flags & IW_ENCODE_RESTRICTED) {
netdev_info(dev,
"r8712u: %s: IW_ENCODE_RESTRICTED\n", __func__);
padapter->securitypriv.ndisencryptstatus =
Ndis802_11Encryption1Enabled;
padapter->securitypriv.AuthAlgrthm = 1; /* shared system */
padapter->securitypriv.PrivacyAlgrthm = _WEP40_;
padapter->securitypriv.XGrpPrivacy = _WEP40_;
authmode = Ndis802_11AuthModeShared;
padapter->securitypriv.ndisauthtype = authmode;
} else {
padapter->securitypriv.ndisencryptstatus =
Ndis802_11Encryption1Enabled;
padapter->securitypriv.AuthAlgrthm = 0; /* open system */
padapter->securitypriv.PrivacyAlgrthm = _NO_PRIVACY_;
padapter->securitypriv.XGrpPrivacy = _NO_PRIVACY_;
authmode = Ndis802_11AuthModeOpen;
padapter->securitypriv.ndisauthtype = authmode;
}
wep.KeyIndex = key;
if (erq->length > 0) {
wep.KeyLength = erq->length <= 5 ? 5 : 13;
wep.Length = wep.KeyLength +
FIELD_OFFSET(struct NDIS_802_11_WEP, KeyMaterial);
} else {
wep.KeyLength = 0;
if (keyindex_provided == 1) { /* set key_id only, no given
* KeyMaterial(erq->length==0).
*/
padapter->securitypriv.PrivacyKeyIndex = key;
switch (padapter->securitypriv.DefKeylen[key]) {
case 5:
padapter->securitypriv.PrivacyAlgrthm =
_WEP40_;
break;
case 13:
padapter->securitypriv.PrivacyAlgrthm =
_WEP104_;
break;
default:
padapter->securitypriv.PrivacyAlgrthm =
_NO_PRIVACY_;
break;
}
return 0;
}
}
wep.KeyIndex |= 0x80000000; /* transmit key */
memcpy(wep.KeyMaterial, keybuf, wep.KeyLength);
if (r8712_set_802_11_add_wep(padapter, &wep) == _FAIL)
return -EOPNOTSUPP;
return 0;
}
static int r8711_wx_get_enc(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *keybuf)
{
uint key, ret = 0;
struct _adapter *padapter = netdev_priv(dev);
struct iw_point *erq = &(wrqu->encoding);
struct mlme_priv *pmlmepriv = &(padapter->mlmepriv);
if (!check_fwstate(pmlmepriv, _FW_LINKED)) {
if (!check_fwstate(pmlmepriv, WIFI_ADHOC_MASTER_STATE)) {
erq->length = 0;
erq->flags |= IW_ENCODE_DISABLED;
return 0;
}
}
key = erq->flags & IW_ENCODE_INDEX;
if (key) {
if (key > WEP_KEYS)
return -EINVAL;
key--;
} else {
key = padapter->securitypriv.PrivacyKeyIndex;
}
erq->flags = key + 1;
switch (padapter->securitypriv.ndisencryptstatus) {
case Ndis802_11EncryptionNotSupported:
case Ndis802_11EncryptionDisabled:
erq->length = 0;
erq->flags |= IW_ENCODE_DISABLED;
break;
case Ndis802_11Encryption1Enabled:
erq->length = padapter->securitypriv.DefKeylen[key];
if (erq->length) {
memcpy(keybuf, padapter->securitypriv.DefKey[
key].skey, padapter->securitypriv.
DefKeylen[key]);
erq->flags |= IW_ENCODE_ENABLED;
if (padapter->securitypriv.ndisauthtype ==
Ndis802_11AuthModeOpen)
erq->flags |= IW_ENCODE_OPEN;
else if (padapter->securitypriv.ndisauthtype ==
Ndis802_11AuthModeShared)
erq->flags |= IW_ENCODE_RESTRICTED;
} else {
erq->length = 0;
erq->flags |= IW_ENCODE_DISABLED;
}
break;
case Ndis802_11Encryption2Enabled:
case Ndis802_11Encryption3Enabled:
erq->length = 16;
erq->flags |= (IW_ENCODE_ENABLED | IW_ENCODE_OPEN |
IW_ENCODE_NOKEY);
break;
default:
erq->length = 0;
erq->flags |= IW_ENCODE_DISABLED;
break;
}
return ret;
}
static int r8711_wx_get_power(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
wrqu->power.value = 0;
wrqu->power.fixed = 0; /* no auto select */
wrqu->power.disabled = 1;
return 0;
}
static int r871x_wx_set_gen_ie(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct _adapter *padapter = netdev_priv(dev);
return r871x_set_wpa_ie(padapter, extra, wrqu->data.length);
}
static int r871x_wx_set_auth(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct _adapter *padapter = netdev_priv(dev);
struct iw_param *param = (struct iw_param *)&(wrqu->param);
int paramid;
int paramval;
int ret = 0;
paramid = param->flags & IW_AUTH_INDEX;
paramval = param->value;
switch (paramid) {
case IW_AUTH_WPA_VERSION:
break;
case IW_AUTH_CIPHER_PAIRWISE:
break;
case IW_AUTH_CIPHER_GROUP:
break;
case IW_AUTH_KEY_MGMT:
/*
* ??? does not use these parameters
*/
break;
case IW_AUTH_TKIP_COUNTERMEASURES:
if (paramval) {
/* wpa_supplicant is enabling tkip countermeasure. */
padapter->securitypriv.btkip_countermeasure = true;
} else {
/* wpa_supplicant is disabling tkip countermeasure. */
padapter->securitypriv.btkip_countermeasure = false;
}
break;
case IW_AUTH_DROP_UNENCRYPTED:
/* HACK:
*
* wpa_supplicant calls set_wpa_enabled when the driver
* is loaded and unloaded, regardless of if WPA is being
* used. No other calls are made which can be used to
* determine if encryption will be used or not prior to
* association being expected. If encryption is not being
* used, drop_unencrypted is set to false, else true -- we
* can use this to determine if the CAP_PRIVACY_ON bit should
* be set.
*/
if (padapter->securitypriv.ndisencryptstatus ==
Ndis802_11Encryption1Enabled) {
/* it means init value, or using wep,
* ndisencryptstatus =
* Ndis802_11Encryption1Enabled,
* then it needn't reset it;
*/
break;
}
if (paramval) {
padapter->securitypriv.ndisencryptstatus =
Ndis802_11EncryptionDisabled;
padapter->securitypriv.PrivacyAlgrthm =
_NO_PRIVACY_;
padapter->securitypriv.XGrpPrivacy =
_NO_PRIVACY_;
padapter->securitypriv.AuthAlgrthm = 0;
padapter->securitypriv.ndisauthtype =
Ndis802_11AuthModeOpen;
}
break;
case IW_AUTH_80211_AUTH_ALG:
ret = wpa_set_auth_algs(dev, (u32)paramval);
break;
case IW_AUTH_WPA_ENABLED:
break;
case IW_AUTH_RX_UNENCRYPTED_EAPOL:
break;
case IW_AUTH_PRIVACY_INVOKED:
break;
default:
return -EOPNOTSUPP;
}
return ret;
}
static int r871x_wx_set_enc_ext(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct iw_point *pencoding = &wrqu->encoding;
struct iw_encode_ext *pext = (struct iw_encode_ext *)extra;
struct ieee_param *param = NULL;
char *alg_name;
u32 param_len;
int ret = 0;
switch (pext->alg) {
case IW_ENCODE_ALG_NONE:
alg_name = "none";
break;
case IW_ENCODE_ALG_WEP:
alg_name = "WEP";
break;
case IW_ENCODE_ALG_TKIP:
alg_name = "TKIP";
break;
case IW_ENCODE_ALG_CCMP:
alg_name = "CCMP";
break;
default:
return -EINVAL;
}
param_len = sizeof(struct ieee_param) + pext->key_len;
param = kzalloc(param_len, GFP_ATOMIC);
if (!param)
return -ENOMEM;
param->cmd = IEEE_CMD_SET_ENCRYPTION;
eth_broadcast_addr(param->sta_addr);
strncpy((char *)param->u.crypt.alg, alg_name, IEEE_CRYPT_ALG_NAME_LEN);
if (pext->ext_flags & IW_ENCODE_EXT_GROUP_KEY)
param->u.crypt.set_tx = 0;
if (pext->ext_flags & IW_ENCODE_EXT_SET_TX_KEY)
param->u.crypt.set_tx = 1;
param->u.crypt.idx = (pencoding->flags & 0x00FF) - 1;
if (pext->ext_flags & IW_ENCODE_EXT_RX_SEQ_VALID)
memcpy(param->u.crypt.seq, pext->rx_seq, 8);
if (pext->key_len) {
param->u.crypt.key_len = pext->key_len;
memcpy(param + 1, pext + 1, pext->key_len);
}
ret = wpa_set_encryption(dev, param, param_len);
kfree(param);
return ret;
}
static int r871x_wx_get_nick(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
if (extra) {
wrqu->data.length = 8;
wrqu->data.flags = 1;
memcpy(extra, "rtl_wifi", 8);
}
return 0;
}
static int r8711_wx_read32(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *keybuf)
{
struct _adapter *padapter = netdev_priv(dev);
u32 addr;
u32 data32;
get_user(addr, (u32 __user *)wrqu->data.pointer);
data32 = r8712_read32(padapter, addr);
put_user(data32, (u32 __user *)wrqu->data.pointer);
wrqu->data.length = (data32 & 0xffff0000) >> 16;
wrqu->data.flags = data32 & 0xffff;
get_user(addr, (u32 __user *)wrqu->data.pointer);
return 0;
}
static int r8711_wx_write32(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *keybuf)
{
struct _adapter *padapter = netdev_priv(dev);
u32 addr;
u32 data32;
get_user(addr, (u32 __user *)wrqu->data.pointer);
data32 = ((u32)wrqu->data.length << 16) | (u32)wrqu->data.flags;
r8712_write32(padapter, addr, data32);
return 0;
}
static int dummy(struct net_device *dev,
struct iw_request_info *a,
union iwreq_data *wrqu, char *b)
{
return -ENOSYS;
}
static int r8711_drvext_hdl(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
return 0;
}
static int r871x_mp_ioctl_hdl(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct _adapter *padapter = netdev_priv(dev);
struct iw_point *p = &wrqu->data;
struct oid_par_priv oid_par;
struct mp_ioctl_handler *phandler;
struct mp_ioctl_param *poidparam;
unsigned long BytesRead, BytesWritten, BytesNeeded;
u8 *pparmbuf, bset;
u16 len;
uint status;
int ret = 0;
if ((!p->length) || (!p->pointer))
return -EINVAL;
bset = (u8)(p->flags & 0xFFFF);
len = p->length;
pparmbuf = memdup_user(p->pointer, len);
if (IS_ERR(pparmbuf))
return PTR_ERR(pparmbuf);
poidparam = (struct mp_ioctl_param *)pparmbuf;
if (poidparam->subcode >= MAX_MP_IOCTL_SUBCODE) {
ret = -EINVAL;
goto _r871x_mp_ioctl_hdl_exit;
}
phandler = mp_ioctl_hdl + poidparam->subcode;
if ((phandler->paramsize != 0) &&
(poidparam->len < phandler->paramsize)) {
ret = -EINVAL;
goto _r871x_mp_ioctl_hdl_exit;
}
if (phandler->oid == 0 && phandler->handler) {
status = phandler->handler(&oid_par);
} else if (phandler->handler) {
oid_par.adapter_context = padapter;
oid_par.oid = phandler->oid;
oid_par.information_buf = poidparam->data;
oid_par.information_buf_len = poidparam->len;
oid_par.dbg = 0;
BytesWritten = 0;
BytesNeeded = 0;
if (bset) {
oid_par.bytes_rw = &BytesRead;
oid_par.bytes_needed = &BytesNeeded;
oid_par.type_of_oid = SET_OID;
} else {
oid_par.bytes_rw = &BytesWritten;
oid_par.bytes_needed = &BytesNeeded;
oid_par.type_of_oid = QUERY_OID;
}
status = phandler->handler(&oid_par);
/* todo:check status, BytesNeeded, etc. */
} else {
netdev_info(dev, "r8712u: %s: err!, subcode=%d, oid=%d, handler=%p\n",
__func__, poidparam->subcode, phandler->oid,
phandler->handler);
ret = -EFAULT;
goto _r871x_mp_ioctl_hdl_exit;
}
if (bset == 0x00) { /* query info */
if (copy_to_user(p->pointer, pparmbuf, len))
ret = -EFAULT;
}
if (status) {
ret = -EFAULT;
goto _r871x_mp_ioctl_hdl_exit;
}
_r871x_mp_ioctl_hdl_exit:
kfree(pparmbuf);
return ret;
}
static int r871x_get_ap_info(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct _adapter *padapter = netdev_priv(dev);
struct mlme_priv *pmlmepriv = &padapter->mlmepriv;
struct __queue *queue = &pmlmepriv->scanned_queue;
struct iw_point *pdata = &wrqu->data;
struct wlan_network *pnetwork = NULL;
u32 cnt = 0, wpa_ielen;
unsigned long irqL;
struct list_head *plist, *phead;
unsigned char *pbuf;
u8 bssid[ETH_ALEN];
char data[33];
if (padapter->bDriverStopped || (pdata == NULL))
return -EINVAL;
while (check_fwstate(pmlmepriv, _FW_UNDER_SURVEY |
_FW_UNDER_LINKING)) {
msleep(30);
cnt++;
if (cnt > 100)
break;
}
pdata->flags = 0;
if (pdata->length >= 32) {
if (copy_from_user(data, pdata->pointer, 32))
return -EINVAL;
data[32] = 0;
} else {
return -EINVAL;
}
spin_lock_irqsave(&(pmlmepriv->scanned_queue.lock), irqL);
phead = &queue->queue;
plist = phead->next;
while (1) {
if (end_of_queue_search(phead, plist))
break;
pnetwork = container_of(plist, struct wlan_network, list);
if (!mac_pton(data, bssid)) {
netdev_info(dev, "r8712u: Invalid BSSID '%s'.\n",
(u8 *)data);
spin_unlock_irqrestore(&(pmlmepriv->scanned_queue.lock),
irqL);
return -EINVAL;
}
netdev_info(dev, "r8712u: BSSID:%pM\n", bssid);
if (ether_addr_equal(bssid, pnetwork->network.MacAddress)) {
/* BSSID match, then check if supporting wpa/wpa2 */
pbuf = r8712_get_wpa_ie(&pnetwork->network.IEs[12],
&wpa_ielen, pnetwork->network.IELength - 12);
if (pbuf && (wpa_ielen > 0)) {
pdata->flags = 1;
break;
}
pbuf = r8712_get_wpa2_ie(&pnetwork->network.IEs[12],
&wpa_ielen, pnetwork->network.IELength - 12);
if (pbuf && (wpa_ielen > 0)) {
pdata->flags = 2;
break;
}
}
plist = plist->next;
}
spin_unlock_irqrestore(&(pmlmepriv->scanned_queue.lock), irqL);
if (pdata->length >= 34) {
if (copy_to_user((u8 __user *)pdata->pointer + 32,
(u8 *)&pdata->flags, 1))
return -EINVAL;
}
return 0;
}
static int r871x_set_pid(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct _adapter *padapter = netdev_priv(dev);
struct iw_point *pdata = &wrqu->data;
if ((padapter->bDriverStopped) || (pdata == NULL))
return -EINVAL;
if (copy_from_user(&padapter->pid, pdata->pointer, sizeof(int)))
return -EINVAL;
return 0;
}
static int r871x_set_chplan(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
int ret = 0;
struct _adapter *padapter = netdev_priv(dev);
struct iw_point *pdata = &wrqu->data;
int ch_plan = -1;
if ((padapter->bDriverStopped) || (pdata == NULL)) {
ret = -EINVAL;
goto exit;
}
ch_plan = (int)*extra;
r8712_set_chplan_cmd(padapter, ch_plan);
exit:
return ret;
}
static int r871x_wps_start(struct net_device *dev,
struct iw_request_info *info,
union iwreq_data *wrqu, char *extra)
{
struct _adapter *padapter = netdev_priv(dev);
struct iw_point *pdata = &wrqu->data;
u32 u32wps_start = 0;
if ((padapter->bDriverStopped) || (pdata == NULL))
return -EINVAL;
if (copy_from_user((void *)&u32wps_start, pdata->pointer, 4))
return -EFAULT;
if (u32wps_start == 0)
u32wps_start = *extra;
if (u32wps_start == 1) /* WPS Start */
padapter->ledpriv.LedControlHandler(padapter,
LED_CTL_START_WPS);
else if (u32wps_start == 2) /* WPS Stop because of wps success */
padapter->ledpriv.LedControlHandler(padapter,
LED_CTL_STOP_WPS);
else if (u32wps_start == 3) /* WPS Stop because of wps fail */
padapter->ledpriv.LedControlHandler(padapter,
LED_CTL_STOP_WPS_FAIL);
return 0;
}
static int wpa_set_param(struct net_device *dev, u8 name, u32 value)
{
struct _adapter *padapter = netdev_priv(dev);
switch (name) {
case IEEE_PARAM_WPA_ENABLED:
padapter->securitypriv.AuthAlgrthm = 2; /* 802.1x */
switch ((value) & 0xff) {
case 1: /* WPA */
padapter->securitypriv.ndisauthtype =
Ndis802_11AuthModeWPAPSK; /* WPA_PSK */
padapter->securitypriv.ndisencryptstatus =
Ndis802_11Encryption2Enabled;
break;
case 2: /* WPA2 */
padapter->securitypriv.ndisauthtype =
Ndis802_11AuthModeWPA2PSK; /* WPA2_PSK */
padapter->securitypriv.ndisencryptstatus =
Ndis802_11Encryption3Enabled;
break;
}
break;
case IEEE_PARAM_TKIP_COUNTERMEASURES:
break;
case IEEE_PARAM_DROP_UNENCRYPTED:
/* HACK:
*
* wpa_supplicant calls set_wpa_enabled when the driver
* is loaded and unloaded, regardless of if WPA is being
* used. No other calls are made which can be used to
* determine if encryption will be used or not prior to
* association being expected. If encryption is not being
* used, drop_unencrypted is set to false, else true -- we
* can use this to determine if the CAP_PRIVACY_ON bit should
* be set.
*/
break;
case IEEE_PARAM_PRIVACY_INVOKED:
break;
case IEEE_PARAM_AUTH_ALGS:
return wpa_set_auth_algs(dev, value);
case IEEE_PARAM_IEEE_802_1X:
break;
case IEEE_PARAM_WPAX_SELECT:
/* added for WPA2 mixed mode */
break;
default:
return -EOPNOTSUPP;
}
return 0;
}
static int wpa_mlme(struct net_device *dev, u32 command, u32 reason)
{
struct _adapter *padapter = netdev_priv(dev);
switch (command) {
case IEEE_MLME_STA_DEAUTH:
if (!r8712_set_802_11_disassociate(padapter))
return -1;
break;
case IEEE_MLME_STA_DISASSOC:
if (!r8712_set_802_11_disassociate(padapter))
return -1;
break;
default:
return -EOPNOTSUPP;
}
return 0;
}
static int wpa_supplicant_ioctl(struct net_device *dev, struct iw_point *p)
{
struct ieee_param *param;
int ret = 0;
struct _adapter *padapter = netdev_priv(dev);
if (p->length < sizeof(struct ieee_param) || !p->pointer)
return -EINVAL;
param = memdup_user(p->pointer, p->length);
if (IS_ERR(param))
return PTR_ERR(param);
switch (param->cmd) {
case IEEE_CMD_SET_WPA_PARAM:
ret = wpa_set_param(dev, param->u.wpa_param.name,
param->u.wpa_param.value);
break;
case IEEE_CMD_SET_WPA_IE:
ret = r871x_set_wpa_ie(padapter, (char *)param->u.wpa_ie.data,
(u16)param->u.wpa_ie.len);
break;
case IEEE_CMD_SET_ENCRYPTION:
ret = wpa_set_encryption(dev, param, p->length);
break;
case IEEE_CMD_MLME:
ret = wpa_mlme(dev, param->u.mlme.command,
param->u.mlme.reason_code);
break;
default:
ret = -EOPNOTSUPP;
break;
}
if (ret == 0 && copy_to_user(p->pointer, param, p->length))
ret = -EFAULT;
kfree(param);
return ret;
}
/* based on "driver_ipw" and for hostapd */
int r871x_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
{
struct iwreq *wrq = (struct iwreq *)rq;
switch (cmd) {
case RTL_IOCTL_WPA_SUPPLICANT:
return wpa_supplicant_ioctl(dev, &wrq->u.data);
default:
return -EOPNOTSUPP;
}
return 0;
}
static iw_handler r8711_handlers[] = {
NULL, /* SIOCSIWCOMMIT */
r8711_wx_get_name, /* SIOCGIWNAME */
dummy, /* SIOCSIWNWID */
dummy, /* SIOCGIWNWID */
r8711_wx_set_freq, /* SIOCSIWFREQ */
r8711_wx_get_freq, /* SIOCGIWFREQ */
r8711_wx_set_mode, /* SIOCSIWMODE */
r8711_wx_get_mode, /* SIOCGIWMODE */
dummy, /* SIOCSIWSENS */
r8711_wx_get_sens, /* SIOCGIWSENS */
NULL, /* SIOCSIWRANGE */
r8711_wx_get_range, /* SIOCGIWRANGE */
r871x_wx_set_priv, /* SIOCSIWPRIV */
NULL, /* SIOCGIWPRIV */
NULL, /* SIOCSIWSTATS */
NULL, /* SIOCGIWSTATS */
dummy, /* SIOCSIWSPY */
dummy, /* SIOCGIWSPY */
NULL, /* SIOCGIWTHRSPY */
NULL, /* SIOCWIWTHRSPY */
r8711_wx_set_wap, /* SIOCSIWAP */
r8711_wx_get_wap, /* SIOCGIWAP */
r871x_wx_set_mlme, /* request MLME operation;
* uses struct iw_mlme
*/
dummy, /* SIOCGIWAPLIST -- deprecated */
r8711_wx_set_scan, /* SIOCSIWSCAN */
r8711_wx_get_scan, /* SIOCGIWSCAN */
r8711_wx_set_essid, /* SIOCSIWESSID */
r8711_wx_get_essid, /* SIOCGIWESSID */
dummy, /* SIOCSIWNICKN */
r871x_wx_get_nick, /* SIOCGIWNICKN */
NULL, /* -- hole -- */
NULL, /* -- hole -- */
r8711_wx_set_rate, /* SIOCSIWRATE */
r8711_wx_get_rate, /* SIOCGIWRATE */
dummy, /* SIOCSIWRTS */
r8711_wx_get_rts, /* SIOCGIWRTS */
r8711_wx_set_frag, /* SIOCSIWFRAG */
r8711_wx_get_frag, /* SIOCGIWFRAG */
dummy, /* SIOCSIWTXPOW */
dummy, /* SIOCGIWTXPOW */
dummy, /* SIOCSIWRETRY */
r8711_wx_get_retry, /* SIOCGIWRETRY */
r8711_wx_set_enc, /* SIOCSIWENCODE */
r8711_wx_get_enc, /* SIOCGIWENCODE */
dummy, /* SIOCSIWPOWER */
r8711_wx_get_power, /* SIOCGIWPOWER */
NULL, /*---hole---*/
NULL, /*---hole---*/
r871x_wx_set_gen_ie, /* SIOCSIWGENIE */
NULL, /* SIOCGIWGENIE */
r871x_wx_set_auth, /* SIOCSIWAUTH */
NULL, /* SIOCGIWAUTH */
r871x_wx_set_enc_ext, /* SIOCSIWENCODEEXT */
NULL, /* SIOCGIWENCODEEXT */
r871x_wx_set_pmkid, /* SIOCSIWPMKSA */
NULL, /*---hole---*/
};
static const struct iw_priv_args r8711_private_args[] = {
{
SIOCIWFIRSTPRIV + 0x0,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "read32"
},
{
SIOCIWFIRSTPRIV + 0x1,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "write32"
},
{
SIOCIWFIRSTPRIV + 0x2, 0, 0, "driver_ext"
},
{
SIOCIWFIRSTPRIV + 0x3, 0, 0, "mp_ioctl"
},
{
SIOCIWFIRSTPRIV + 0x4,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "apinfo"
},
{
SIOCIWFIRSTPRIV + 0x5,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "setpid"
},
{
SIOCIWFIRSTPRIV + 0x6,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "wps_start"
},
{
SIOCIWFIRSTPRIV + 0x7,
IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "chplan"
}
};
static iw_handler r8711_private_handler[] = {
r8711_wx_read32,
r8711_wx_write32,
r8711_drvext_hdl,
r871x_mp_ioctl_hdl,
r871x_get_ap_info, /*for MM DTV platform*/
r871x_set_pid,
r871x_wps_start,
r871x_set_chplan
};
static struct iw_statistics *r871x_get_wireless_stats(struct net_device *dev)
{
struct _adapter *padapter = netdev_priv(dev);
struct iw_statistics *piwstats = &padapter->iwstats;
int tmp_level = 0;
int tmp_qual = 0;
int tmp_noise = 0;
if (check_fwstate(&padapter->mlmepriv, _FW_LINKED) != true) {
piwstats->qual.qual = 0;
piwstats->qual.level = 0;
piwstats->qual.noise = 0;
} else {
/* show percentage, we need transfer dbm to orignal value. */
tmp_level = padapter->recvpriv.fw_rssi;
tmp_qual = padapter->recvpriv.signal;
tmp_noise = padapter->recvpriv.noise;
piwstats->qual.level = tmp_level;
piwstats->qual.qual = tmp_qual;
piwstats->qual.noise = tmp_noise;
}
piwstats->qual.updated = IW_QUAL_ALL_UPDATED;
return &padapter->iwstats;
}
struct iw_handler_def r871x_handlers_def = {
.standard = r8711_handlers,
.num_standard = ARRAY_SIZE(r8711_handlers),
.private = r8711_private_handler,
.private_args = (struct iw_priv_args *)r8711_private_args,
.num_private = ARRAY_SIZE(r8711_private_handler),
.num_private_args = sizeof(r8711_private_args) /
sizeof(struct iw_priv_args),
.get_wireless_stats = r871x_get_wireless_stats
};
| gpl-2.0 |
Kali-/tf101-kernel | drivers/staging/xgifb/vb_setmode.c | 93 | 338638 |
#include <asm/io.h>
#include <linux/types.h>
#include <linux/version.h>
#include "XGIfb.h"
#include "vb_def.h"
#include "vgatypes.h"
#include "vb_struct.h"
#include "vb_util.h"
#include "vb_table.h"
#define IndexMask 0xff
#ifndef XGI_MASK_DUAL_CHIP
#define XGI_MASK_DUAL_CHIP 0x04 /* SR3A */
#endif
unsigned char XGI_IsLCDDualLink(struct vb_device_info *pVBInfo);
unsigned char XGI_SetCRT2Group301(unsigned short ModeNo,
struct xgi_hw_device_info *HwDeviceExtension,
struct vb_device_info *pVBInfo);
unsigned char XGI_BacklightByDrv(struct vb_device_info *pVBInfo);
unsigned char XGI_IsLCDON(struct vb_device_info *pVBInfo);
unsigned char XGI_DisableChISLCD(struct vb_device_info *pVBInfo);
unsigned char XGI_EnableChISLCD(struct vb_device_info *pVBInfo);
unsigned char XGI_AjustCRT2Rate(unsigned short ModeNo,
unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
unsigned short *i, struct vb_device_info *pVBInfo);
unsigned char XGI_SearchModeID(unsigned short ModeNo,
unsigned short *ModeIdIndex,
struct vb_device_info *pVBInfo);
unsigned char XGI_GetLCDInfo(unsigned short ModeNo,
unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo);
unsigned char XGISetModeNew(struct xgi_hw_device_info *HwDeviceExtension,
unsigned short ModeNo);
unsigned char XGI_BridgeIsOn(struct vb_device_info *pVBInfo);
unsigned char XGI_GetModePtr(unsigned short ModeNo,
unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo);
unsigned short XGI_GetOffset(unsigned short ModeNo,
unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct xgi_hw_device_info *HwDeviceExtension,
struct vb_device_info *pVBInfo);
unsigned short XGI_GetRatePtrCRT2(struct xgi_hw_device_info *pXGIHWDE,
unsigned short ModeNo,
unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo);
unsigned short XGI_GetResInfo(unsigned short ModeNo,
unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo);
unsigned short XGI_GetColorDepth(unsigned short ModeNo,
unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo);
unsigned short XGI_GetVGAHT2(struct vb_device_info *pVBInfo);
unsigned short XGI_GetVCLK2Ptr(unsigned short ModeNo,
unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct xgi_hw_device_info *HwDeviceExtension,
struct vb_device_info *pVBInfo);
void XGI_VBLongWait(struct vb_device_info *pVBInfo);
void XGI_SaveCRT2Info(unsigned short ModeNo, struct vb_device_info *pVBInfo);
void XGI_GetCRT2Data(unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex, struct vb_device_info *pVBInfo);
void XGI_GetCRT2ResInfo(unsigned short ModeNo, unsigned short ModeIdIndex, struct vb_device_info *pVBInfo);
void XGI_PreSetGroup1(unsigned short ModeNo, unsigned short ModeIdIndex, struct xgi_hw_device_info *HwDeviceExtension, unsigned short RefreshRateTableIndex, struct vb_device_info *pVBInfo);
void XGI_SetGroup1(unsigned short ModeNo, unsigned short ModeIdIndex, struct xgi_hw_device_info *HwDeviceExtension, unsigned short RefreshRateTableIndex, struct vb_device_info *pVBInfo);
void XGI_SetLockRegs(unsigned short ModeNo, unsigned short ModeIdIndex, struct xgi_hw_device_info *HwDeviceExtension, unsigned short RefreshRateTableIndex, struct vb_device_info *pVBInfo);
void XGI_SetLCDRegs(unsigned short ModeNo, unsigned short ModeIdIndex, struct xgi_hw_device_info *HwDeviceExtension, unsigned short RefreshRateTableIndex, struct vb_device_info *pVBInfo);
void XGI_SetGroup2(unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex, struct xgi_hw_device_info *HwDeviceExtension, struct vb_device_info *pVBInfo);
void XGI_SetGroup3(unsigned short ModeNo, unsigned short ModeIdIndex, struct vb_device_info *pVBInfo);
void XGI_SetGroup4(unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex, struct xgi_hw_device_info *HwDeviceExtension, struct vb_device_info *pVBInfo);
void XGI_SetGroup5(unsigned short ModeNo, unsigned short ModeIdIndex, struct vb_device_info *pVBInfo);
void *XGI_GetLcdPtr(unsigned short BX, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex, struct vb_device_info *pVBInfo);
void *XGI_GetTVPtr(unsigned short BX, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex, struct vb_device_info *pVBInfo);
void XGI_FirePWDEnable(struct vb_device_info *pVBInfo);
void XGI_EnableGatingCRT(struct xgi_hw_device_info *HwDeviceExtension, struct vb_device_info *pVBInfo);
void XGI_DisableGatingCRT(struct xgi_hw_device_info *HwDeviceExtension, struct vb_device_info *pVBInfo);
void XGI_SetPanelDelay(unsigned short tempbl, struct vb_device_info *pVBInfo);
void XGI_SetPanelPower(unsigned short tempah, unsigned short tempbl, struct vb_device_info *pVBInfo);
void XGI_EnablePWD(struct vb_device_info *pVBInfo);
void XGI_DisablePWD(struct vb_device_info *pVBInfo);
void XGI_AutoThreshold(struct vb_device_info *pVBInfo);
void XGI_SetTap4Regs(struct vb_device_info *pVBInfo);
void XGI_DisplayOn(struct xgi_hw_device_info *, struct vb_device_info *pVBInfo);
void XGI_DisplayOff(struct xgi_hw_device_info *, struct vb_device_info *pVBInfo);
void XGI_SetCRT1Group(struct xgi_hw_device_info *HwDeviceExtension, unsigned short ModeNo, unsigned short ModeIdIndex, struct vb_device_info *pVBInfo);
void XGI_SetXG21CRTC(unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex, struct vb_device_info *pVBInfo);
void XGI_SetXG21LCD(struct vb_device_info *pVBInfo, unsigned short RefreshRateTableIndex, unsigned short ModeNo);
void XGI_SetXG27CRTC(unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex, struct vb_device_info *pVBInfo);
void XGI_SetXG27LCD(struct vb_device_info *pVBInfo, unsigned short RefreshRateTableIndex, unsigned short ModeNo);
void XGI_UpdateXG21CRTC(unsigned short ModeNo, struct vb_device_info *pVBInfo, unsigned short RefreshRateTableIndex);
void XGI_WaitDisply(struct vb_device_info *pVBInfo);
void XGI_SenseCRT1(struct vb_device_info *pVBInfo);
void XGI_SetSeqRegs(unsigned short ModeNo, unsigned short StandTableIndex, unsigned short ModeIdIndex, struct vb_device_info *pVBInfo);
void XGI_SetMiscRegs(unsigned short StandTableIndex, struct vb_device_info *pVBInfo);
void XGI_SetCRTCRegs(struct xgi_hw_device_info *HwDeviceExtension, unsigned short StandTableIndex, struct vb_device_info *pVBInfo);
void XGI_SetATTRegs(unsigned short ModeNo, unsigned short StandTableIndex, unsigned short ModeIdIndex, struct vb_device_info *pVBInfo);
void XGI_SetGRCRegs(unsigned short StandTableIndex, struct vb_device_info *pVBInfo);
void XGI_ClearExt1Regs(struct vb_device_info *pVBInfo);
void XGI_SetSync(unsigned short RefreshRateTableIndex, struct vb_device_info *pVBInfo);
void XGI_SetCRT1CRTC(unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex, struct vb_device_info *pVBInfo, struct xgi_hw_device_info *HwDeviceExtension);
void XGI_SetCRT1Timing_H(struct vb_device_info *pVBInfo, struct xgi_hw_device_info *HwDeviceExtension);
void XGI_SetCRT1Timing_V(unsigned short ModeIdIndex, unsigned short ModeNo, struct vb_device_info *pVBInfo);
void XGI_SetCRT1DE(struct xgi_hw_device_info *HwDeviceExtension, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex, struct vb_device_info *pVBInfo);
void XGI_SetCRT1VCLK(unsigned short ModeNo, unsigned short ModeIdIndex, struct xgi_hw_device_info *HwDeviceExtension, unsigned short RefreshRateTableIndex, struct vb_device_info *pVBInfo);
void XGI_SetCRT1FIFO(unsigned short ModeNo, struct xgi_hw_device_info *HwDeviceExtension, struct vb_device_info *pVBInfo);
void XGI_SetCRT1ModeRegs(struct xgi_hw_device_info *HwDeviceExtension, unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex, struct vb_device_info *pVBInfo);
void XGI_SetVCLKState(struct xgi_hw_device_info *HwDeviceExtension, unsigned short ModeNo, unsigned short RefreshRateTableIndex, struct vb_device_info *pVBInfo);
void XGI_LoadDAC(unsigned short ModeNo, unsigned short ModeIdIndex, struct vb_device_info *pVBInfo);
void XGI_WriteDAC(unsigned short dl, unsigned short ah, unsigned short al, unsigned short dh, struct vb_device_info *pVBInfo);
/*void XGI_ClearBuffer(struct xgi_hw_device_info *HwDeviceExtension, unsigned short ModeNo, struct vb_device_info *pVBInfo);*/
void XGI_SetLCDAGroup(unsigned short ModeNo, unsigned short ModeIdIndex, struct xgi_hw_device_info *HwDeviceExtension, struct vb_device_info *pVBInfo);
void XGI_GetLVDSResInfo(unsigned short ModeNo, unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo);
void XGI_GetLVDSData(unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex, struct vb_device_info *pVBInfo);
void XGI_ModCRT1Regs(unsigned short ModeNo, unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct xgi_hw_device_info *HwDeviceExtension,
struct vb_device_info *pVBInfo);
void XGI_SetLVDSRegs(unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex, struct vb_device_info *pVBInfo);
void XGI_UpdateModeInfo(struct xgi_hw_device_info *HwDeviceExtension, struct vb_device_info *pVBInfo);
void XGI_GetVGAType(struct xgi_hw_device_info *HwDeviceExtension, struct vb_device_info *pVBInfo);
void XGI_GetVBType(struct vb_device_info *pVBInfo);
void XGI_GetVBInfo(unsigned short ModeNo, unsigned short ModeIdIndex, struct xgi_hw_device_info *HwDeviceExtension, struct vb_device_info *pVBInfo);
void XGI_GetTVInfo(unsigned short ModeNo, unsigned short ModeIdIndex, struct vb_device_info *pVBInfo);
void XGI_SetCRT2ECLK(unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex, struct vb_device_info *pVBInfo);
void InitTo330Pointer(unsigned char, struct vb_device_info *pVBInfo);
void XGI_GetLCDSync(unsigned short *HSyncWidth, unsigned short *VSyncWidth, struct vb_device_info *pVBInfo);
void XGI_DisableBridge(struct xgi_hw_device_info *HwDeviceExtension, struct vb_device_info *pVBInfo);
void XGI_EnableBridge(struct xgi_hw_device_info *HwDeviceExtension, struct vb_device_info *pVBInfo);
void XGI_SetCRT2VCLK(unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex, struct vb_device_info *pVBInfo);
void XGI_OEM310Setting(unsigned short ModeNo, unsigned short ModeIdIndex, struct vb_device_info *pVBInfo);
void XGI_SetDelayComp(struct vb_device_info *pVBInfo);
void XGI_SetLCDCap(struct vb_device_info *pVBInfo);
void XGI_SetLCDCap_A(unsigned short tempcx, struct vb_device_info *pVBInfo);
void XGI_SetLCDCap_B(unsigned short tempcx, struct vb_device_info *pVBInfo);
void SetSpectrum(struct vb_device_info *pVBInfo);
void XGI_SetAntiFlicker(unsigned short ModeNo, unsigned short ModeIdIndex, struct vb_device_info *pVBInfo);
void XGI_SetEdgeEnhance(unsigned short ModeNo, unsigned short ModeIdIndex, struct vb_device_info *pVBInfo);
void XGI_SetPhaseIncr(struct vb_device_info *pVBInfo);
void XGI_SetYFilter(unsigned short ModeNo, unsigned short ModeIdIndex, struct vb_device_info *pVBInfo);
void XGI_GetTVPtrIndex2(unsigned short *tempbx, unsigned char* tempcl,
unsigned char *tempch, struct vb_device_info *pVBInfo);
unsigned short XGI_GetTVPtrIndex(struct vb_device_info *pVBInfo);
void XGI_SetCRT2ModeRegs(unsigned short ModeNo, struct xgi_hw_device_info *, struct vb_device_info *pVBInfo);
void XGI_CloseCRTC(struct xgi_hw_device_info *, struct vb_device_info *pVBInfo);
void XGI_OpenCRTC(struct xgi_hw_device_info *, struct vb_device_info *pVBInfo);
void XGI_GetRAMDAC2DATA(unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex, struct vb_device_info *pVBInfo);
void XGI_UnLockCRT2(struct xgi_hw_device_info *, struct vb_device_info *pVBInfo);
void XGI_LockCRT2(struct xgi_hw_device_info *, struct vb_device_info *pVBInfo);
void XGINew_EnableCRT2(struct vb_device_info *pVBInfo);
void XGINew_LCD_Wait_Time(unsigned char DelayTime, struct vb_device_info *pVBInfo);
void XGI_LongWait(struct vb_device_info *pVBInfo);
void XGI_SetCRT1Offset(unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex, struct xgi_hw_device_info *HwDeviceExtension, struct vb_device_info *pVBInfo);
void XGI_GetLCDVCLKPtr(unsigned char *di_0, unsigned char *di_1,
struct vb_device_info *pVBInfo);
unsigned char XGI_GetVCLKPtr(unsigned short RefreshRateTableIndex,
unsigned short ModeNo,
unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo);
void XGI_GetVCLKLen(unsigned char tempal, unsigned char *di_0,
unsigned char *di_1, struct vb_device_info *pVBInfo);
unsigned short XGI_GetLCDCapPtr(struct vb_device_info *pVBInfo);
unsigned short XGI_GetLCDCapPtr1(struct vb_device_info *pVBInfo);
struct XGI301C_Tap4TimingStruct *XGI_GetTap4Ptr(unsigned short tempcx, struct vb_device_info *pVBInfo);
void XGI_SetXG21FPBits(struct vb_device_info *pVBInfo);
void XGI_SetXG27FPBits(struct vb_device_info *pVBInfo);
unsigned char XGI_XG21GetPSCValue(struct vb_device_info *pVBInfo);
unsigned char XGI_XG27GetPSCValue(struct vb_device_info *pVBInfo);
void XGI_XG21BLSignalVDD(unsigned short tempbh, unsigned short tempbl, struct vb_device_info *pVBInfo);
void XGI_XG27BLSignalVDD(unsigned short tempbh, unsigned short tempbl, struct vb_device_info *pVBInfo);
void XGI_XG21SetPanelDelay(unsigned short tempbl, struct vb_device_info *pVBInfo);
unsigned char XGI_XG21CheckLVDSMode(unsigned short ModeNo, unsigned short ModeIdIndex, struct vb_device_info *pVBInfo);
void XGI_SetXG21LVDSPara(unsigned short ModeNo, unsigned short ModeIdIndex, struct vb_device_info *pVBInfo);
void XGI_SetXG27LVDSPara(unsigned short ModeNo, unsigned short ModeIdIndex, struct vb_device_info *pVBInfo);
unsigned char XGI_SetDefaultVCLK(struct vb_device_info *pVBInfo);
extern void ReadVBIOSTablData(unsigned char ChipType, struct vb_device_info *pVBInfo);
/* unsigned short XGINew_flag_clearbuffer; 0: no clear frame buffer 1:clear frame buffer */
unsigned short XGINew_MDA_DAC[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15,
0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15,
0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x15,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F};
unsigned short XGINew_CGA_DAC[] = {
0x00, 0x10, 0x04, 0x14, 0x01, 0x11, 0x09, 0x15,
0x00, 0x10, 0x04, 0x14, 0x01, 0x11, 0x09, 0x15,
0x2A, 0x3A, 0x2E, 0x3E, 0x2B, 0x3B, 0x2F, 0x3F,
0x2A, 0x3A, 0x2E, 0x3E, 0x2B, 0x3B, 0x2F, 0x3F,
0x00, 0x10, 0x04, 0x14, 0x01, 0x11, 0x09, 0x15,
0x00, 0x10, 0x04, 0x14, 0x01, 0x11, 0x09, 0x15,
0x2A, 0x3A, 0x2E, 0x3E, 0x2B, 0x3B, 0x2F, 0x3F,
0x2A, 0x3A, 0x2E, 0x3E, 0x2B, 0x3B, 0x2F, 0x3F};
unsigned short XGINew_EGA_DAC[] = {
0x00, 0x10, 0x04, 0x14, 0x01, 0x11, 0x05, 0x15,
0x20, 0x30, 0x24, 0x34, 0x21, 0x31, 0x25, 0x35,
0x08, 0x18, 0x0C, 0x1C, 0x09, 0x19, 0x0D, 0x1D,
0x28, 0x38, 0x2C, 0x3C, 0x29, 0x39, 0x2D, 0x3D,
0x02, 0x12, 0x06, 0x16, 0x03, 0x13, 0x07, 0x17,
0x22, 0x32, 0x26, 0x36, 0x23, 0x33, 0x27, 0x37,
0x0A, 0x1A, 0x0E, 0x1E, 0x0B, 0x1B, 0x0F, 0x1F,
0x2A, 0x3A, 0x2E, 0x3E, 0x2B, 0x3B, 0x2F, 0x3F};
unsigned short XGINew_VGA_DAC[] = {
0x00, 0x10, 0x04, 0x14, 0x01, 0x11, 0x09, 0x15,
0x2A, 0x3A, 0x2E, 0x3E, 0x2B, 0x3B, 0x2F, 0x3F,
0x00, 0x05, 0x08, 0x0B, 0x0E, 0x11, 0x14, 0x18,
0x1C, 0x20, 0x24, 0x28, 0x2D, 0x32, 0x38, 0x3F,
0x00, 0x10, 0x1F, 0x2F, 0x3F, 0x1F, 0x27, 0x2F,
0x37, 0x3F, 0x2D, 0x31, 0x36, 0x3A, 0x3F, 0x00,
0x07, 0x0E, 0x15, 0x1C, 0x0E, 0x11, 0x15, 0x18,
0x1C, 0x14, 0x16, 0x18, 0x1A, 0x1C, 0x00, 0x04,
0x08, 0x0C, 0x10, 0x08, 0x0A, 0x0C, 0x0E, 0x10,
0x0B, 0x0C, 0x0D, 0x0F, 0x10};
/* --------------------------------------------------------------------- */
/* Function : InitTo330Pointer */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void InitTo330Pointer(unsigned char ChipType, struct vb_device_info *pVBInfo)
{
pVBInfo->SModeIDTable = (struct XGI_StStruct *) XGI330_SModeIDTable ;
pVBInfo->StandTable = (struct XGI_StandTableStruct *) XGI330_StandTable ;
pVBInfo->EModeIDTable = (struct XGI_ExtStruct *) XGI330_EModeIDTable ;
pVBInfo->RefIndex = (struct XGI_Ext2Struct *) XGI330_RefIndex ;
pVBInfo->XGINEWUB_CRT1Table = (struct XGI_CRT1TableStruct *) XGI_CRT1Table ;
/* add for new UNIVGABIOS */
/* XGINew_UBLCDDataTable = (struct XGI_LCDDataTablStruct *) XGI_LCDDataTable ; */
/* XGINew_UBTVDataTable = (XGI_TVDataTablStruct *) XGI_TVDataTable ; */
if ( ChipType >= XG40 )
{
pVBInfo->MCLKData = (struct XGI_MCLKDataStruct *) XGI340New_MCLKData;
pVBInfo->ECLKData = (struct XGI_ECLKDataStruct *) XGI340_ECLKData;
}
else
{
pVBInfo->MCLKData = (struct XGI_MCLKDataStruct *) XGI330New_MCLKData;
pVBInfo->ECLKData = (struct XGI_ECLKDataStruct *) XGI330_ECLKData;
}
pVBInfo->VCLKData = (struct XGI_VCLKDataStruct *) XGI_VCLKData ;
pVBInfo->VBVCLKData = (struct XGI_VBVCLKDataStruct *) XGI_VBVCLKData ;
pVBInfo->ScreenOffset = XGI330_ScreenOffset ;
pVBInfo->StResInfo = (struct XGI_StResInfoStruct *) XGI330_StResInfo ;
pVBInfo->ModeResInfo = (struct XGI_ModeResInfoStruct *) XGI330_ModeResInfo ;
pVBInfo->pOutputSelect = &XGI330_OutputSelect ;
pVBInfo->pSoftSetting = &XGI330_SoftSetting ;
pVBInfo->pSR07 = &XGI330_SR07 ;
pVBInfo->LCDResInfo = 0 ;
pVBInfo->LCDTypeInfo = 0 ;
pVBInfo->LCDInfo = 0 ;
pVBInfo->VBInfo = 0 ;
pVBInfo->TVInfo = 0;
pVBInfo->SR15 = XGI340_SR13 ;
pVBInfo->CR40 = XGI340_cr41 ;
pVBInfo->SR25 = XGI330_sr25 ;
pVBInfo->pSR31 = &XGI330_sr31 ;
pVBInfo->pSR32 = &XGI330_sr32 ;
pVBInfo->CR6B = XGI340_CR6B ;
pVBInfo->CR6E = XGI340_CR6E ;
pVBInfo->CR6F = XGI340_CR6F ;
pVBInfo->CR89 = XGI340_CR89 ;
pVBInfo->AGPReg = XGI340_AGPReg ;
pVBInfo->SR16 = XGI340_SR16 ;
pVBInfo->pCRCF = &XG40_CRCF ;
pVBInfo->pXGINew_DRAMTypeDefinition = &XG40_DRAMTypeDefinition ;
pVBInfo->CR49 = XGI330_CR49 ;
pVBInfo->pSR1F = &XGI330_SR1F ;
pVBInfo->pSR21 = &XGI330_SR21 ;
pVBInfo->pSR22 = &XGI330_SR22 ;
pVBInfo->pSR23 = &XGI330_SR23 ;
pVBInfo->pSR24 = &XGI330_SR24 ;
pVBInfo->pSR33 = &XGI330_SR33 ;
pVBInfo->pCRT2Data_1_2 = &XGI330_CRT2Data_1_2 ;
pVBInfo->pCRT2Data_4_D = &XGI330_CRT2Data_4_D ;
pVBInfo->pCRT2Data_4_E = &XGI330_CRT2Data_4_E ;
pVBInfo->pCRT2Data_4_10 = &XGI330_CRT2Data_4_10 ;
pVBInfo->pRGBSenseData = &XGI330_RGBSenseData ;
pVBInfo->pVideoSenseData = &XGI330_VideoSenseData ;
pVBInfo->pYCSenseData = &XGI330_YCSenseData ;
pVBInfo->pRGBSenseData2 = &XGI330_RGBSenseData2 ;
pVBInfo->pVideoSenseData2 = &XGI330_VideoSenseData2 ;
pVBInfo->pYCSenseData2 = &XGI330_YCSenseData2 ;
pVBInfo->NTSCTiming = XGI330_NTSCTiming ;
pVBInfo->PALTiming = XGI330_PALTiming ;
pVBInfo->HiTVExtTiming = XGI330_HiTVExtTiming ;
pVBInfo->HiTVSt1Timing = XGI330_HiTVSt1Timing ;
pVBInfo->HiTVSt2Timing = XGI330_HiTVSt2Timing ;
pVBInfo->HiTVTextTiming = XGI330_HiTVTextTiming ;
pVBInfo->YPbPr750pTiming = XGI330_YPbPr750pTiming ;
pVBInfo->YPbPr525pTiming = XGI330_YPbPr525pTiming ;
pVBInfo->YPbPr525iTiming = XGI330_YPbPr525iTiming ;
pVBInfo->HiTVGroup3Data = XGI330_HiTVGroup3Data ;
pVBInfo->HiTVGroup3Simu = XGI330_HiTVGroup3Simu ;
pVBInfo->HiTVGroup3Text = XGI330_HiTVGroup3Text ;
pVBInfo->Ren525pGroup3 = XGI330_Ren525pGroup3 ;
pVBInfo->Ren750pGroup3 = XGI330_Ren750pGroup3 ;
pVBInfo->TimingH = (struct XGI_TimingHStruct *) XGI_TimingH ;
pVBInfo->TimingV = (struct XGI_TimingVStruct *) XGI_TimingV ;
pVBInfo->UpdateCRT1 = (struct XGI_XG21CRT1Struct *) XGI_UpdateCRT1Table ;
pVBInfo->CHTVVCLKUNTSC = XGI330_CHTVVCLKUNTSC ;
pVBInfo->CHTVVCLKONTSC = XGI330_CHTVVCLKONTSC ;
pVBInfo->CHTVVCLKUPAL = XGI330_CHTVVCLKUPAL ;
pVBInfo->CHTVVCLKOPAL = XGI330_CHTVVCLKOPAL ;
/* 310 customization related */
if ( ( pVBInfo->VBType & VB_XGI301LV ) || ( pVBInfo->VBType & VB_XGI302LV ) )
pVBInfo->LCDCapList = XGI_LCDDLCapList ;
else
pVBInfo->LCDCapList = XGI_LCDCapList ;
if ( ( ChipType == XG21 ) || ( ChipType == XG27 ) )
pVBInfo->XG21_LVDSCapList = XGI21_LCDCapList ;
pVBInfo->XGI_TVDelayList = XGI301TVDelayList ;
pVBInfo->XGI_TVDelayList2 = XGI301TVDelayList2 ;
pVBInfo->pXGINew_I2CDefinition = &XG40_I2CDefinition ;
if ( ChipType >= XG20 )
pVBInfo->pXGINew_CR97 = &XG20_CR97 ;
if ( ChipType == XG27 )
{
pVBInfo->MCLKData = (struct XGI_MCLKDataStruct *) XGI27New_MCLKData;
pVBInfo->CR40 = XGI27_cr41 ;
pVBInfo->pXGINew_CR97 = &XG27_CR97 ;
pVBInfo->pSR36 = &XG27_SR36 ;
pVBInfo->pCR8F = &XG27_CR8F ;
pVBInfo->pCRD0 = XG27_CRD0 ;
pVBInfo->pCRDE = XG27_CRDE ;
pVBInfo->pSR40 = &XG27_SR40 ;
pVBInfo->pSR41 = &XG27_SR41 ;
}
if ( ChipType >= XG20 )
{
pVBInfo->pDVOSetting = &XG21_DVOSetting ;
pVBInfo->pCR2E = &XG21_CR2E ;
pVBInfo->pCR2F = &XG21_CR2F ;
pVBInfo->pCR46 = &XG21_CR46 ;
pVBInfo->pCR47 = &XG21_CR47 ;
}
}
/* --------------------------------------------------------------------- */
/* Function : XGISetModeNew */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
unsigned char XGISetModeNew(struct xgi_hw_device_info *HwDeviceExtension,
unsigned short ModeNo)
{
unsigned short ModeIdIndex ;
/* unsigned char *pVBInfo->FBAddr = HwDeviceExtension->pjVideoMemoryAddress ; */
struct vb_device_info VBINF;
struct vb_device_info *pVBInfo = &VBINF;
pVBInfo->ROMAddr = HwDeviceExtension->pjVirtualRomBase ;
pVBInfo->BaseAddr = (unsigned long)HwDeviceExtension->pjIOAddress ;
pVBInfo->IF_DEF_LVDS = 0 ;
pVBInfo->IF_DEF_CH7005 = 0 ;
pVBInfo->IF_DEF_LCDA = 1 ;
pVBInfo->IF_DEF_CH7017 = 0 ;
pVBInfo->IF_DEF_CH7007 = 0 ; /* [Billy] 2007/05/14 */
pVBInfo->IF_DEF_VideoCapture = 0 ;
pVBInfo->IF_DEF_ScaleLCD = 0 ;
pVBInfo->IF_DEF_OEMUtil = 0 ;
pVBInfo->IF_DEF_PWD = 0 ;
if ( HwDeviceExtension->jChipType >= XG20 ) /* kuku 2004/06/25 */
{
pVBInfo->IF_DEF_YPbPr = 0 ;
pVBInfo->IF_DEF_HiVision = 0 ;
pVBInfo->IF_DEF_CRT2Monitor = 0 ;
pVBInfo->VBType = 0 ; /*set VBType default 0*/
}
else if ( HwDeviceExtension->jChipType >= XG40 )
{
pVBInfo->IF_DEF_YPbPr = 1 ;
pVBInfo->IF_DEF_HiVision = 1 ;
pVBInfo->IF_DEF_CRT2Monitor = 1 ;
}
else
{
pVBInfo->IF_DEF_YPbPr = 1 ;
pVBInfo->IF_DEF_HiVision = 1 ;
pVBInfo->IF_DEF_CRT2Monitor = 0 ;
}
pVBInfo->P3c4 = pVBInfo->BaseAddr + 0x14 ;
pVBInfo->P3d4 = pVBInfo->BaseAddr + 0x24 ;
pVBInfo->P3c0 = pVBInfo->BaseAddr + 0x10 ;
pVBInfo->P3ce = pVBInfo->BaseAddr + 0x1e ;
pVBInfo->P3c2 = pVBInfo->BaseAddr + 0x12 ;
pVBInfo->P3cc = pVBInfo->BaseAddr + 0x1C ;
pVBInfo->P3ca = pVBInfo->BaseAddr + 0x1a ;
pVBInfo->P3c6 = pVBInfo->BaseAddr + 0x16 ;
pVBInfo->P3c7 = pVBInfo->BaseAddr + 0x17 ;
pVBInfo->P3c8 = pVBInfo->BaseAddr + 0x18 ;
pVBInfo->P3c9 = pVBInfo->BaseAddr + 0x19 ;
pVBInfo->P3da = pVBInfo->BaseAddr + 0x2A ;
pVBInfo->Part0Port = pVBInfo->BaseAddr + XGI_CRT2_PORT_00 ;
pVBInfo->Part1Port = pVBInfo->BaseAddr + XGI_CRT2_PORT_04 ;
pVBInfo->Part2Port = pVBInfo->BaseAddr + XGI_CRT2_PORT_10 ;
pVBInfo->Part3Port = pVBInfo->BaseAddr + XGI_CRT2_PORT_12 ;
pVBInfo->Part4Port = pVBInfo->BaseAddr + XGI_CRT2_PORT_14 ;
pVBInfo->Part5Port = pVBInfo->BaseAddr + XGI_CRT2_PORT_14 + 2 ;
if ( HwDeviceExtension->jChipType == XG21 ) /* for x86 Linux, XG21 LVDS */
{
if ( ( XGINew_GetReg1( pVBInfo->P3d4 , 0x38 ) & 0xE0 ) == 0xC0 )
{
pVBInfo->IF_DEF_LVDS = 1 ;
}
}
if ( HwDeviceExtension->jChipType == XG27 )
{
if ( ( XGINew_GetReg1( pVBInfo->P3d4 , 0x38 ) & 0xE0 ) == 0xC0 )
{
if ( XGINew_GetReg1( pVBInfo->P3d4 , 0x30 ) & 0x20 )
{
pVBInfo->IF_DEF_LVDS = 1 ;
}
}
}
if ( HwDeviceExtension->jChipType < XG20 ) /* kuku 2004/06/25 */
XGI_GetVBType( pVBInfo ) ;
InitTo330Pointer( HwDeviceExtension->jChipType, pVBInfo ) ;
if ( ModeNo & 0x80 )
{
ModeNo = ModeNo & 0x7F ;
/* XGINew_flag_clearbuffer = 0 ; */
}
/* else
{
XGINew_flag_clearbuffer = 1 ;
}
*/
XGINew_SetReg1( pVBInfo->P3c4 , 0x05 , 0x86 ) ;
if ( HwDeviceExtension->jChipType < XG20 ) /* kuku 2004/06/25 1.Openkey */
XGI_UnLockCRT2( HwDeviceExtension , pVBInfo ) ;
XGI_SearchModeID( ModeNo , &ModeIdIndex, pVBInfo ) ;
XGI_GetVGAType(HwDeviceExtension, pVBInfo) ;
if ( HwDeviceExtension->jChipType < XG20 ) /* kuku 2004/06/25 */
{
XGI_GetVBInfo(ModeNo , ModeIdIndex , HwDeviceExtension, pVBInfo ) ;
XGI_GetTVInfo(ModeNo , ModeIdIndex, pVBInfo ) ;
XGI_GetLCDInfo(ModeNo , ModeIdIndex, pVBInfo ) ;
XGI_DisableBridge( HwDeviceExtension,pVBInfo ) ;
/* XGI_OpenCRTC( HwDeviceExtension, pVBInfo ) ; */
if ( pVBInfo->VBInfo & ( SetSimuScanMode | SetCRT2ToLCDA ) )
{
XGI_SetCRT1Group(HwDeviceExtension , ModeNo , ModeIdIndex, pVBInfo ) ;
if ( pVBInfo->VBInfo & SetCRT2ToLCDA )
{
XGI_SetLCDAGroup(ModeNo , ModeIdIndex , HwDeviceExtension, pVBInfo ) ;
}
}
else
{
if ( !( pVBInfo->VBInfo & SwitchToCRT2) )
{
XGI_SetCRT1Group( HwDeviceExtension , ModeNo , ModeIdIndex, pVBInfo ) ;
if ( pVBInfo->VBInfo & SetCRT2ToLCDA )
{
XGI_SetLCDAGroup( ModeNo , ModeIdIndex , HwDeviceExtension, pVBInfo ) ;
}
}
}
if ( pVBInfo->VBInfo & ( SetSimuScanMode | SwitchToCRT2 ) )
{
switch( HwDeviceExtension->ujVBChipID )
{
case VB_CHIP_301:
XGI_SetCRT2Group301( ModeNo , HwDeviceExtension, pVBInfo ) ; /*add for CRT2 */
break ;
case VB_CHIP_302:
XGI_SetCRT2Group301(ModeNo , HwDeviceExtension, pVBInfo ) ; /*add for CRT2 */
break ;
default:
break ;
}
}
XGI_SetCRT2ModeRegs( ModeNo, HwDeviceExtension,pVBInfo ) ;
XGI_OEM310Setting( ModeNo, ModeIdIndex,pVBInfo ) ; /*0212*/
XGI_CloseCRTC( HwDeviceExtension, pVBInfo ) ;
XGI_EnableBridge( HwDeviceExtension ,pVBInfo) ;
} /* !XG20 */
else
{
if (pVBInfo->IF_DEF_LVDS == 1)
if (!XGI_XG21CheckLVDSMode(ModeNo , ModeIdIndex, pVBInfo))
return 0;
if ( ModeNo <= 0x13 )
{
pVBInfo->ModeType = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag & ModeInfoFlag;
}
else
{
pVBInfo->ModeType = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag & ModeInfoFlag;
}
pVBInfo->SetFlag = 0 ;
if ( pVBInfo->IF_DEF_CH7007 != 1 )
{
pVBInfo->VBInfo = DisableCRT2Display ;
}
XGI_DisplayOff(HwDeviceExtension, pVBInfo) ;
XGI_SetCRT1Group(HwDeviceExtension , ModeNo , ModeIdIndex, pVBInfo ) ;
XGI_DisplayOn( HwDeviceExtension, pVBInfo ) ;
/*
if( HwDeviceExtension->jChipType == XG21 )
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x09 , ~0x80 , 0x80 ) ;
*/
}
/*
if ( ModeNo <= 0x13 )
{
modeflag = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ;
}
else
{
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ;
}
pVBInfo->ModeType = modeflag&ModeInfoFlag ;
pVBInfo->SetFlag = 0x00 ;
pVBInfo->VBInfo = DisableCRT2Display ;
temp = XGINew_CheckMemorySize( HwDeviceExtension , ModeNo , ModeIdIndex, pVBInfo ) ;
if ( temp == 0 )
return( 0 ) ;
XGI_DisplayOff( HwDeviceExtension, pVBInfo) ;
XGI_SetCRT1Group( HwDeviceExtension , ModeNo , ModeIdIndex, pVBInfo ) ;
XGI_DisplayOn( HwDeviceExtension, pVBInfo) ;
*/
XGI_UpdateModeInfo( HwDeviceExtension, pVBInfo ) ;
if ( HwDeviceExtension->jChipType < XG20 ) /* kuku 2004/06/25 */
{
XGI_LockCRT2( HwDeviceExtension, pVBInfo ) ;
}
return 1;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetCRT1Group */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetCRT1Group(struct xgi_hw_device_info *HwDeviceExtension,
unsigned short ModeNo,
unsigned short ModeIdIndex, struct vb_device_info *pVBInfo)
{
unsigned short StandTableIndex ,
RefreshRateTableIndex ,
b3CC ,
temp ;
unsigned short XGINew_P3cc = pVBInfo->P3cc;
/* XGINew_CRT1Mode = ModeNo ; // SaveModeID */
StandTableIndex = XGI_GetModePtr( ModeNo , ModeIdIndex, pVBInfo ) ;
/* XGI_SetBIOSData(ModeNo , ModeIdIndex ) ; */
/* XGI_ClearBankRegs( ModeNo , ModeIdIndex ) ; */
XGI_SetSeqRegs( ModeNo , StandTableIndex , ModeIdIndex, pVBInfo ) ;
XGI_SetMiscRegs( StandTableIndex, pVBInfo ) ;
XGI_SetCRTCRegs( HwDeviceExtension , StandTableIndex, pVBInfo) ;
XGI_SetATTRegs( ModeNo , StandTableIndex , ModeIdIndex, pVBInfo ) ;
XGI_SetGRCRegs( StandTableIndex, pVBInfo ) ;
XGI_ClearExt1Regs(pVBInfo) ;
/* if ( pVBInfo->IF_DEF_ExpLink ) */
if ( HwDeviceExtension->jChipType == XG27 )
{
if ( pVBInfo->IF_DEF_LVDS == 0 )
{
XGI_SetDefaultVCLK( pVBInfo ) ;
}
}
temp = ~ProgrammingCRT2 ;
pVBInfo->SetFlag &= temp ;
pVBInfo->SelectCRT2Rate = 0 ;
if ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{
if ( pVBInfo->VBInfo & ( SetSimuScanMode | SetCRT2ToLCDA | SetInSlaveMode ) )
{
pVBInfo->SetFlag |= ProgrammingCRT2 ;
}
}
RefreshRateTableIndex = XGI_GetRatePtrCRT2( HwDeviceExtension, ModeNo , ModeIdIndex, pVBInfo ) ;
if ( RefreshRateTableIndex != 0xFFFF )
{
XGI_SetSync( RefreshRateTableIndex, pVBInfo ) ;
XGI_SetCRT1CRTC( ModeNo , ModeIdIndex , RefreshRateTableIndex, pVBInfo, HwDeviceExtension ) ;
XGI_SetCRT1DE( HwDeviceExtension , ModeNo , ModeIdIndex , RefreshRateTableIndex, pVBInfo ) ;
XGI_SetCRT1Offset( ModeNo , ModeIdIndex , RefreshRateTableIndex , HwDeviceExtension, pVBInfo ) ;
XGI_SetCRT1VCLK( ModeNo , ModeIdIndex , HwDeviceExtension , RefreshRateTableIndex, pVBInfo ) ;
}
if ( ( HwDeviceExtension->jChipType >= XG20 )&&
( HwDeviceExtension->jChipType < XG27 ) ) /* fix H/W DCLK/2 bug */
{
if ( ( ModeNo == 0x00 ) | (ModeNo == 0x01) )
{
XGINew_SetReg1( pVBInfo->P3c4 , 0x2B , 0x4E) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2C , 0xE9) ;
b3CC = (unsigned char) XGINew_GetReg2(XGINew_P3cc) ;
XGINew_SetReg3(XGINew_P3cc , (b3CC |= 0x0C) ) ;
}
else if ( ( ModeNo == 0x04) | ( ModeNo == 0x05) | ( ModeNo == 0x0D) )
{
XGINew_SetReg1( pVBInfo->P3c4 , 0x2B , 0x1B) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2C , 0xE3) ;
b3CC = (unsigned char)XGINew_GetReg2(XGINew_P3cc) ;
XGINew_SetReg3(XGINew_P3cc , (b3CC |= 0x0C) ) ;
}
}
if ( HwDeviceExtension->jChipType >= XG21 )
{
temp = XGINew_GetReg1( pVBInfo->P3d4 , 0x38 ) ;
if ( temp & 0xA0 )
{
/*XGINew_SetRegAND( pVBInfo->P3d4 , 0x4A , ~0x20 ) ;*/ /* Enable write GPIOF */
/*XGINew_SetRegAND( pVBInfo->P3d4 , 0x48 , ~0x20 ) ;*/ /* P. DWN */
/* XG21 CRT1 Timing */
if ( HwDeviceExtension->jChipType == XG27 )
XGI_SetXG27CRTC( ModeNo, ModeIdIndex, RefreshRateTableIndex, pVBInfo );
else
XGI_SetXG21CRTC( ModeNo, ModeIdIndex, RefreshRateTableIndex, pVBInfo );
XGI_UpdateXG21CRTC( ModeNo , pVBInfo , RefreshRateTableIndex) ;
if ( HwDeviceExtension->jChipType == XG27 )
XGI_SetXG27LCD( pVBInfo , RefreshRateTableIndex , ModeNo );
else
XGI_SetXG21LCD( pVBInfo , RefreshRateTableIndex , ModeNo );
if ( pVBInfo->IF_DEF_LVDS == 1 )
{
if ( HwDeviceExtension->jChipType == XG27 )
XGI_SetXG27LVDSPara(ModeNo,ModeIdIndex, pVBInfo );
else
XGI_SetXG21LVDSPara(ModeNo,ModeIdIndex, pVBInfo );
}
/*XGINew_SetRegOR( pVBInfo->P3d4 , 0x48 , 0x20 ) ;*/ /* P. ON */
}
}
pVBInfo->SetFlag &= ( ~ProgrammingCRT2 ) ;
XGI_SetCRT1FIFO( ModeNo , HwDeviceExtension, pVBInfo ) ;
XGI_SetCRT1ModeRegs( HwDeviceExtension , ModeNo , ModeIdIndex , RefreshRateTableIndex , pVBInfo) ;
/* XGI_LoadCharacter(); //dif ifdef TVFont */
XGI_LoadDAC( ModeNo , ModeIdIndex, pVBInfo ) ;
/* XGI_ClearBuffer( HwDeviceExtension , ModeNo, pVBInfo ) ; */
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetModePtr */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
unsigned char XGI_GetModePtr(unsigned short ModeNo, unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned char index ;
if ( ModeNo <= 0x13 )
index = pVBInfo->SModeIDTable[ ModeIdIndex ].St_StTableIndex ;
else
{
if ( pVBInfo->ModeType <= 0x02 )
index = 0x1B ; /* 02 -> ModeEGA */
else
index = 0x0F ;
}
return( index ) ; /* Get pVBInfo->StandTable index */
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetBIOSData */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
/*unsigned char XGI_SetBIOSData(unsigned short ModeNo, unsigned short ModeIdIndex)
{
return( 0 ) ;
}
*/
/* --------------------------------------------------------------------- */
/* Function : XGI_ClearBankRegs */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
/*unsigned char XGI_ClearBankRegs(unsigned short ModeNo, unsigned short ModeIdIndex)
{
return( 0 ) ;
}
*/
/* --------------------------------------------------------------------- */
/* Function : XGI_SetSeqRegs */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetSeqRegs(unsigned short ModeNo, unsigned short StandTableIndex,
unsigned short ModeIdIndex, struct vb_device_info *pVBInfo)
{
unsigned char tempah ,
SRdata ;
unsigned short i ,
modeflag ;
if ( ModeNo <= 0x13 )
modeflag = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ;
else
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x00 , 0x03 ) ; /* Set SR0 */
tempah=pVBInfo->StandTable[ StandTableIndex ].SR[ 0 ] ;
i = SetCRT2ToLCDA ;
if ( pVBInfo->VBInfo & SetCRT2ToLCDA )
{
tempah |= 0x01 ;
}
else
{
if ( pVBInfo->VBInfo & ( SetCRT2ToTV | SetCRT2ToLCD ) )
{
if ( pVBInfo->VBInfo & SetInSlaveMode )
tempah |= 0x01 ;
}
}
tempah |= 0x20 ; /* screen off */
XGINew_SetReg1( pVBInfo->P3c4 , 0x01 , tempah ) ; /* Set SR1 */
for( i = 02 ; i <= 04 ; i++ )
{
SRdata = pVBInfo->StandTable[ StandTableIndex ].SR[ i - 1 ] ; /* Get SR2,3,4 from file */
XGINew_SetReg1( pVBInfo->P3c4 , i , SRdata ) ; /* Set SR2 3 4 */
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetMiscRegs */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetMiscRegs(unsigned short StandTableIndex, struct vb_device_info *pVBInfo)
{
unsigned char Miscdata ;
Miscdata = pVBInfo->StandTable[ StandTableIndex ].MISC ; /* Get Misc from file */
/*
if ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{
if ( pVBInfo->VBInfo & SetCRT2ToLCDA )
{
Miscdata |= 0x0C ;
}
}
*/
XGINew_SetReg3( pVBInfo->P3c2 , Miscdata ) ; /* Set Misc(3c2) */
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetCRTCRegs */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetCRTCRegs(struct xgi_hw_device_info *HwDeviceExtension,
unsigned short StandTableIndex, struct vb_device_info *pVBInfo)
{
unsigned char CRTCdata ;
unsigned short i ;
CRTCdata = (unsigned char)XGINew_GetReg1(pVBInfo->P3d4, 0x11);
CRTCdata &= 0x7f ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x11 , CRTCdata ) ; /* Unlock CRTC */
for( i = 0 ; i <= 0x18 ; i++ )
{
CRTCdata = pVBInfo->StandTable[ StandTableIndex ].CRTC[ i ] ; /* Get CRTC from file */
XGINew_SetReg1( pVBInfo->P3d4 , i , CRTCdata ) ; /* Set CRTC( 3d4 ) */
}
/*
if ( ( HwDeviceExtension->jChipType == XGI_630 )&& ( HwDeviceExtension->jChipRevision == 0x30 ) )
{
if ( pVBInfo->VBInfo & SetInSlaveMode )
{
if ( pVBInfo->VBInfo & ( SetCRT2ToLCD | SetCRT2ToTV ) )
{
XGINew_SetReg1( pVBInfo->P3d4 , 0x18 , 0xFE ) ;
}
}
}
*/
}
/* --------------------------------------------------------------------- */
/* Function : */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetATTRegs(unsigned short ModeNo, unsigned short StandTableIndex,
unsigned short ModeIdIndex, struct vb_device_info *pVBInfo)
{
unsigned char ARdata ;
unsigned short i, modeflag;
if ( ModeNo <= 0x13 )
modeflag = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ;
else
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ;
for( i = 0 ; i <= 0x13 ; i++ )
{
ARdata = pVBInfo->StandTable[ StandTableIndex ].ATTR[ i ] ;
if ( modeflag & Charx8Dot ) /* ifndef Dot9 */
{
if ( i == 0x13 )
{
if ( pVBInfo->VBInfo & SetCRT2ToLCDA )
ARdata = 0 ;
else
{
if ( pVBInfo->VBInfo & ( SetCRT2ToTV | SetCRT2ToLCD ) )
{
if ( pVBInfo->VBInfo & SetInSlaveMode )
ARdata = 0 ;
}
}
}
}
XGINew_GetReg2( pVBInfo->P3da ) ; /* reset 3da */
XGINew_SetReg3( pVBInfo->P3c0 , i ) ; /* set index */
XGINew_SetReg3( pVBInfo->P3c0 , ARdata ) ; /* set data */
}
XGINew_GetReg2( pVBInfo->P3da ) ; /* reset 3da */
XGINew_SetReg3( pVBInfo->P3c0 , 0x14 ) ; /* set index */
XGINew_SetReg3( pVBInfo->P3c0 , 0x00 ) ; /* set data */
XGINew_GetReg2( pVBInfo->P3da ) ; /* Enable Attribute */
XGINew_SetReg3( pVBInfo->P3c0 , 0x20 ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetGRCRegs */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetGRCRegs(unsigned short StandTableIndex, struct vb_device_info *pVBInfo)
{
unsigned char GRdata ;
unsigned short i ;
for( i = 0 ; i <= 0x08 ; i++ )
{
GRdata = pVBInfo->StandTable[ StandTableIndex ].GRC[ i ] ; /* Get GR from file */
XGINew_SetReg1( pVBInfo->P3ce , i , GRdata ) ; /* Set GR(3ce) */
}
if ( pVBInfo->ModeType > ModeVGA )
{
GRdata = (unsigned char)XGINew_GetReg1(pVBInfo->P3ce, 0x05);
GRdata &= 0xBF ; /* 256 color disable */
XGINew_SetReg1( pVBInfo->P3ce , 0x05 , GRdata ) ;
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_ClearExt1Regs */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_ClearExt1Regs(struct vb_device_info *pVBInfo)
{
unsigned short i ;
for( i = 0x0A ; i <= 0x0E ; i++ )
XGINew_SetReg1( pVBInfo->P3c4 , i , 0x00 ) ; /* Clear SR0A-SR0E */
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetDefaultVCLK */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
unsigned char XGI_SetDefaultVCLK(struct vb_device_info *pVBInfo)
{
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x31 , ~0x30 , 0x20 ) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2B , pVBInfo->VCLKData[ 0 ].SR2B ) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2C , pVBInfo->VCLKData[ 0 ].SR2C ) ;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x31 , ~0x30 , 0x10 ) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2B , pVBInfo->VCLKData[ 1 ].SR2B ) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2C , pVBInfo->VCLKData[ 1 ].SR2C ) ;
XGINew_SetRegAND( pVBInfo->P3c4 , 0x31 , ~0x30 ) ;
return( 0 ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetRatePtrCRT2 */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
unsigned short XGI_GetRatePtrCRT2(struct xgi_hw_device_info *pXGIHWDE,
unsigned short ModeNo,
unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
short LCDRefreshIndex[] = { 0x00 , 0x00 , 0x03 , 0x01 } ,
LCDARefreshIndex[] = { 0x00 , 0x00 , 0x03 , 0x01 , 0x01 , 0x01 , 0x01 } ;
unsigned short RefreshRateTableIndex, i, modeflag, index, temp;
if ( ModeNo <= 0x13 )
{
modeflag = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ;
}
else
{
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ;
}
if ( pVBInfo->IF_DEF_CH7005 == 1 )
{
if ( pVBInfo->VBInfo & SetCRT2ToTV )
{
if ( modeflag & HalfDCLK )
return( 0 ) ;
}
}
if ( ModeNo < 0x14 )
return( 0xFFFF ) ;
index = XGINew_GetReg1( pVBInfo->P3d4 , 0x33 ) ;
index = index >> pVBInfo->SelectCRT2Rate ;
index &= 0x0F ;
if ( pVBInfo->LCDInfo & LCDNonExpanding )
index = 0 ;
if ( index > 0 )
index-- ;
if ( pVBInfo->SetFlag & ProgrammingCRT2 )
{
if ( pVBInfo->IF_DEF_CH7005 == 1 )
{
if ( pVBInfo->VBInfo & SetCRT2ToTV )
{
index = 0 ;
}
}
if ( pVBInfo->VBInfo & ( SetCRT2ToLCD | SetCRT2ToLCDA ) )
{
if( pVBInfo->IF_DEF_LVDS == 0 )
{
if ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
temp = LCDARefreshIndex[ pVBInfo->LCDResInfo & 0x0F ] ; /* 301b */
else
temp = LCDRefreshIndex[ pVBInfo->LCDResInfo & 0x0F ] ;
if ( index > temp )
{
index = temp ;
}
}
else
{
index = 0 ;
}
}
}
RefreshRateTableIndex = pVBInfo->EModeIDTable[ ModeIdIndex ].REFindex ;
ModeNo = pVBInfo->RefIndex[ RefreshRateTableIndex ].ModeID ;
if ( pXGIHWDE->jChipType >= XG20 ) /* for XG20, XG21, XG27 */
{
/*
if ( pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_InfoFlag & XG2xNotSupport )
{
index++;
}
*/
if ( ( pVBInfo->RefIndex[ RefreshRateTableIndex ].XRes == 800 ) &&
( pVBInfo->RefIndex[ RefreshRateTableIndex ].YRes == 600 ) )
{
index++;
}
/* Alan 10/19/2007; do the similiar adjustment like XGISearchCRT1Rate() */
if ( ( pVBInfo->RefIndex[ RefreshRateTableIndex ].XRes == 1024 ) &&
( pVBInfo->RefIndex[ RefreshRateTableIndex ].YRes == 768 ) )
{
index++;
}
if ( ( pVBInfo->RefIndex[ RefreshRateTableIndex ].XRes == 1280 ) &&
( pVBInfo->RefIndex[ RefreshRateTableIndex ].YRes == 1024 ) )
{
index++;
}
}
i = 0 ;
do
{
if ( pVBInfo->RefIndex[ RefreshRateTableIndex + i ].ModeID != ModeNo )
break ;
temp = pVBInfo->RefIndex[ RefreshRateTableIndex + i ].Ext_InfoFlag ;
temp &= ModeInfoFlag ;
if ( temp < pVBInfo->ModeType )
break ;
i++ ;
index-- ;
} while( index != 0xFFFF ) ;
if ( !( pVBInfo->VBInfo & SetCRT2ToRAMDAC ) )
{
if ( pVBInfo->VBInfo & SetInSlaveMode )
{
temp = pVBInfo->RefIndex[ RefreshRateTableIndex + i - 1 ].Ext_InfoFlag ;
if ( temp & InterlaceMode )
{
i++ ;
}
}
}
i-- ;
if ( ( pVBInfo->SetFlag & ProgrammingCRT2 ) )
{
temp = XGI_AjustCRT2Rate( ModeNo , ModeIdIndex , RefreshRateTableIndex , &i, pVBInfo) ;
}
return( RefreshRateTableIndex + i ) ; /*return(0x01|(temp1<<1)); */
}
/* --------------------------------------------------------------------- */
/* Function : XGI_AjustCRT2Rate */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
unsigned char XGI_AjustCRT2Rate(unsigned short ModeNo, unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
unsigned short *i, struct vb_device_info *pVBInfo)
{
unsigned short tempax, tempbx, resinfo, modeflag, infoflag;
if ( ModeNo <= 0x13 )
{
modeflag = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ; /* si+St_ModeFlag */
}
else
{
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ;
}
resinfo = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_RESINFO ;
tempbx = pVBInfo->RefIndex[ RefreshRateTableIndex + ( *i ) ].ModeID ;
tempax = 0 ;
if ( pVBInfo->IF_DEF_LVDS == 0 )
{
if ( pVBInfo->VBInfo & SetCRT2ToRAMDAC )
{
tempax |= SupportRAMDAC2 ;
if ( pVBInfo->VBType & VB_XGI301C )
tempax |= SupportCRT2in301C ;
}
if ( pVBInfo->VBInfo & ( SetCRT2ToLCD | SetCRT2ToLCDA ) ) /* 301b */
{
tempax |= SupportLCD ;
if ( pVBInfo->LCDResInfo != Panel1280x1024 )
{
if ( pVBInfo->LCDResInfo != Panel1280x960 )
{
if ( pVBInfo->LCDInfo & LCDNonExpanding )
{
if ( resinfo >= 9 )
{
tempax = 0 ;
return( 0 ) ;
}
}
}
}
}
if ( pVBInfo->VBInfo & SetCRT2ToHiVisionTV ) /* for HiTV */
{
if ( ( pVBInfo->VBType & VB_XGI301LV ) && ( pVBInfo->VBExtInfo == VB_YPbPr1080i ) )
{
tempax |= SupportYPbPr ;
if ( pVBInfo->VBInfo & SetInSlaveMode )
{
if ( resinfo == 4 )
return( 0 ) ;
if ( resinfo == 3 )
return( 0 ) ;
if ( resinfo > 7 )
return( 0 ) ;
}
}
else
{
tempax |= SupportHiVisionTV ;
if ( pVBInfo->VBInfo & SetInSlaveMode )
{
if ( resinfo == 4 )
return( 0 ) ;
if ( resinfo == 3 )
{
if ( pVBInfo->SetFlag & TVSimuMode )
return( 0 ) ;
}
if ( resinfo > 7 )
return( 0 ) ;
}
}
}
else
{
if ( pVBInfo->VBInfo & ( SetCRT2ToAVIDEO | SetCRT2ToSVIDEO | SetCRT2ToSCART | SetCRT2ToYPbPr | SetCRT2ToHiVisionTV ) )
{
tempax |= SupportTV ;
if ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{
tempax |= SupportTV1024 ;
}
if ( !( pVBInfo->VBInfo & SetPALTV ) )
{
if ( modeflag & NoSupportSimuTV )
{
if ( pVBInfo->VBInfo & SetInSlaveMode )
{
if ( !( pVBInfo->VBInfo & SetNotSimuMode ) )
{
return( 0 ) ;
}
}
}
}
}
}
}
else /* for LVDS */
{
if ( pVBInfo->IF_DEF_CH7005 == 1 )
{
if ( pVBInfo->VBInfo & SetCRT2ToTV )
{
tempax |= SupportCHTV ;
}
}
if ( pVBInfo->VBInfo & SetCRT2ToLCD )
{
tempax |= SupportLCD ;
if ( resinfo > 0x08 )
return( 0 ) ; /* 1024x768 */
if ( pVBInfo->LCDResInfo < Panel1024x768 )
{
if ( resinfo > 0x07 )
return( 0 ) ; /* 800x600 */
if ( resinfo == 0x04 )
return( 0 ) ; /* 512x384 */
}
}
}
for( ; pVBInfo->RefIndex[ RefreshRateTableIndex + ( *i ) ].ModeID == tempbx ; ( *i )-- )
{
infoflag = pVBInfo->RefIndex[ RefreshRateTableIndex + ( *i ) ].Ext_InfoFlag ;
if ( infoflag & tempax )
{
return( 1 ) ;
}
if ( ( *i ) == 0 )
break ;
}
for( ( *i ) = 0 ; ; ( *i )++ )
{
infoflag = pVBInfo->RefIndex[ RefreshRateTableIndex + ( *i ) ].Ext_InfoFlag ;
if ( pVBInfo->RefIndex[ RefreshRateTableIndex + ( *i ) ].ModeID != tempbx )
{
return( 0 ) ;
}
if ( infoflag & tempax )
{
return( 1 ) ;
}
}
return( 1 ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetSync */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetSync(unsigned short RefreshRateTableIndex, struct vb_device_info *pVBInfo)
{
unsigned short sync ,
temp ;
sync = pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_InfoFlag >> 8 ; /* di+0x00 */
sync &= 0xC0 ;
temp = 0x2F ;
temp |= sync ;
XGINew_SetReg3( pVBInfo->P3c2 , temp ) ; /* Set Misc(3c2) */
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetCRT1CRTC */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetCRT1CRTC(unsigned short ModeNo, unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo,
struct xgi_hw_device_info *HwDeviceExtension)
{
unsigned char index, data;
unsigned short i;
index = pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_CRT1CRTC ; /* Get index */
index = index&IndexMask ;
data = (unsigned char)XGINew_GetReg1(pVBInfo->P3d4, 0x11);
data &= 0x7F ;
XGINew_SetReg1(pVBInfo->P3d4,0x11,data); /* Unlock CRTC */
for( i = 0 ; i < 8 ; i++ )
pVBInfo->TimingH[ 0 ].data[ i ] = pVBInfo->XGINEWUB_CRT1Table[ index ].CR[ i ] ;
for( i = 0 ; i < 7 ; i++ )
pVBInfo->TimingV[ 0 ].data[ i ] = pVBInfo->XGINEWUB_CRT1Table[ index ].CR[ i + 8 ] ;
XGI_SetCRT1Timing_H( pVBInfo, HwDeviceExtension ) ;
XGI_SetCRT1Timing_V( ModeIdIndex , ModeNo, pVBInfo ) ;
if( pVBInfo->ModeType > 0x03 )
XGINew_SetReg1( pVBInfo->P3d4 , 0x14 , 0x4F ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetCRT1Timing_H */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetCRT1Timing_H(struct vb_device_info *pVBInfo, struct xgi_hw_device_info *HwDeviceExtension)
{
unsigned char data, data1, pushax;
unsigned short i, j;
/* XGINew_SetReg1( pVBInfo->P3d4 , 0x51 , 0 ) ; */
/* XGINew_SetReg1( pVBInfo->P3d4 , 0x56 , 0 ) ; */
/* XGINew_SetRegANDOR( pVBInfo->P3d4 ,0x11 , 0x7f , 0x00 ) ; */
data = (unsigned char)XGINew_GetReg1(pVBInfo->P3d4, 0x11); /* unlock cr0-7 */
data &= 0x7F ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x11 , data ) ;
data = pVBInfo->TimingH[ 0 ].data[ 0 ] ;
XGINew_SetReg1( pVBInfo->P3d4 , 0 , data ) ;
for( i = 0x01 ; i <= 0x04 ; i++ )
{
data = pVBInfo->TimingH[ 0 ].data[ i ] ;
XGINew_SetReg1( pVBInfo->P3d4, (unsigned short)(i + 1), data);
}
for( i = 0x05 ; i <= 0x06 ; i++ )
{
data = pVBInfo->TimingH[ 0 ].data[ i ];
XGINew_SetReg1(pVBInfo->P3c4, (unsigned short)(i + 6), data);
}
j = (unsigned char)XGINew_GetReg1(pVBInfo->P3c4, 0x0e);
j &= 0x1F ;
data = pVBInfo->TimingH[ 0 ].data[ 7 ] ;
data &= 0xE0 ;
data |= j ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x0e , data ) ;
if ( HwDeviceExtension->jChipType >= XG20 )
{
data = (unsigned char)XGINew_GetReg1(pVBInfo->P3d4, 0x04);
data = data - 1 ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x04 , data ) ;
data = (unsigned char)XGINew_GetReg1(pVBInfo->P3d4, 0x05);
data1 = data ;
data1 &= 0xE0 ;
data &= 0x1F ;
if ( data == 0 )
{
pushax = data ;
data = (unsigned char)XGINew_GetReg1(pVBInfo->P3c4, 0x0c);
data &= 0xFB ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x0c , data ) ;
data = pushax ;
}
data = data - 1 ;
data |= data1 ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x05 , data ) ;
data = (unsigned char)XGINew_GetReg1(pVBInfo->P3c4, 0x0e);
data = data >> 5 ;
data = data + 3 ;
if ( data > 7 )
data = data - 7 ;
data = data << 5 ;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x0e , ~0xE0 , data ) ;
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetCRT1Timing_V */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetCRT1Timing_V(unsigned short ModeIdIndex,
unsigned short ModeNo,
struct vb_device_info *pVBInfo)
{
unsigned char data;
unsigned short i, j;
/* XGINew_SetReg1( pVBInfo->P3d4 , 0x51 , 0 ) ; */
/* XGINew_SetReg1( pVBInfo->P3d4 , 0x56 , 0 ) ; */
/* XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x11 , 0x7f , 0x00 ) ; */
for( i = 0x00 ; i <= 0x01 ; i++ )
{
data = pVBInfo->TimingV[ 0 ].data[ i ] ;
XGINew_SetReg1(pVBInfo->P3d4, (unsigned short)(i + 6), data);
}
for( i = 0x02 ; i <= 0x03 ; i++ )
{
data = pVBInfo->TimingV[ 0 ].data[ i ] ;
XGINew_SetReg1(pVBInfo->P3d4, (unsigned short)(i + 0x0e), data);
}
for( i = 0x04 ; i <= 0x05 ; i++ )
{
data = pVBInfo->TimingV[ 0 ].data[ i ] ;
XGINew_SetReg1(pVBInfo->P3d4, (unsigned short)(i + 0x11), data);
}
j = (unsigned char)XGINew_GetReg1(pVBInfo->P3c4, 0x0a);
j &= 0xC0 ;
data = pVBInfo->TimingV[ 0 ].data[ 6 ] ;
data &= 0x3F ;
data |= j ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x0a , data ) ;
data = pVBInfo->TimingV[ 0 ].data[ 6 ] ;
data &= 0x80 ;
data = data >> 2 ;
if ( ModeNo <= 0x13 )
i = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ;
else
i = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ;
i &= DoubleScanMode ;
if ( i )
data |= 0x80 ;
j = (unsigned char)XGINew_GetReg1(pVBInfo->P3d4, 0x09);
j &= 0x5F ;
data |= j ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x09 , data ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetXG21CRTC */
/* Input : Stand or enhance CRTC table */
/* Output : Fill CRT Hsync/Vsync to SR2E/SR2F/SR30/SR33/SR34/SR3F */
/* Description : Set LCD timing */
/* --------------------------------------------------------------------- */
void XGI_SetXG21CRTC(unsigned short ModeNo, unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned char StandTableIndex, index, Tempax, Tempbx, Tempcx, Tempdx;
unsigned short Temp1, Temp2, Temp3;
if ( ModeNo <= 0x13 )
{
StandTableIndex = XGI_GetModePtr( ModeNo , ModeIdIndex, pVBInfo ) ;
Tempax = pVBInfo->StandTable[ StandTableIndex ].CRTC[ 4 ] ; /* CR04 HRS */
XGINew_SetReg1( pVBInfo->P3c4 , 0x2E , Tempax ) ; /* SR2E [7:0]->HRS */
Tempbx = pVBInfo->StandTable[ StandTableIndex ].CRTC[ 5 ] ; /* Tempbx: CR05 HRE */
Tempbx &= 0x1F ; /* Tempbx: HRE[4:0] */
Tempcx = Tempax ;
Tempcx &= 0xE0 ; /* Tempcx: HRS[7:5] */
Tempdx = Tempcx | Tempbx ; /* Tempdx(HRE): HRS[7:5]HRE[4:0] */
if ( Tempbx < ( Tempax & 0x1F ) ) /* IF HRE < HRS */
Tempdx |= 0x20 ; /* Tempdx: HRE = HRE + 0x20 */
Tempdx <<= 2 ; /* Tempdx << 2 */
XGINew_SetReg1( pVBInfo->P3c4 , 0x2F , Tempdx ) ; /* SR2F [7:2]->HRE */
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x30 , 0xE3 , 00 ) ;
Tempax = pVBInfo->StandTable[ StandTableIndex ].CRTC[ 16 ] ; /* Tempax: CR16 VRS */
Tempbx = Tempax ; /* Tempbx=Tempax */
Tempax &= 0x01 ; /* Tempax: VRS[0] */
XGINew_SetRegOR( pVBInfo->P3c4 , 0x33 , Tempax ) ; /* SR33[0]->VRS */
Tempax = pVBInfo->StandTable[ StandTableIndex ].CRTC[ 7 ] ; /* Tempax: CR7 VRS */
Tempdx = Tempbx >> 1 ; /* Tempdx: VRS[7:1] */
Tempcx = Tempax & 0x04 ; /* Tempcx: CR7[2] */
Tempcx <<= 5 ; /* Tempcx[7]: VRS[8] */
Tempdx |= Tempcx ; /* Tempdx: VRS[8:1] */
XGINew_SetReg1( pVBInfo->P3c4 , 0x34 , Tempdx ) ; /* SR34[7:0]: VRS[8:1] */
Temp1 = Tempcx << 1 ; /* Temp1[8]: VRS[8] unsigned char -> unsigned short */
Temp1 |= Tempbx ; /* Temp1[8:0]: VRS[8:0] */
Tempax &= 0x80 ; /* Tempax[7]: CR7[7] */
Temp2 = Tempax << 2 ; /* Temp2[9]: VRS[9] */
Temp1 |= Temp2 ; /* Temp1[9:0]: VRS[9:0] */
Tempax = pVBInfo->StandTable[ StandTableIndex ].CRTC[ 17 ] ; /* CR16 VRE */
Tempax &= 0x0F ; /* Tempax[3:0]: VRE[3:0] */
Temp2 = Temp1 & 0x3F0 ; /* Temp2[9:4]: VRS[9:4] */
Temp2 |= Tempax ; /* Temp2[9:0]: VRE[9:0] */
Temp3 = Temp1 & 0x0F ; /* Temp3[3:0]: VRS[3:0] */
if ( Tempax < Temp3 ) /* VRE[3:0]<VRS[3:0] */
Temp2 |= 0x10 ; /* Temp2: VRE + 0x10 */
Temp2 &= 0xFF ; /* Temp2[7:0]: VRE[7:0] */
Tempax = (unsigned char)Temp2; /* Tempax[7:0]: VRE[7:0] */
Tempax <<= 2 ; /* Tempax << 2: VRE[5:0] */
Temp1 &= 0x600 ; /* Temp1[10:9]: VRS[10:9] */
Temp1 >>= 9 ; /* [10:9]->[1:0] */
Tempbx = (unsigned char)Temp1; /* Tempbx[1:0]: VRS[10:9] */
Tempax |= Tempbx ; /* VRE[5:0]VRS[10:9] */
Tempax &= 0x7F ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x3F , Tempax ) ; /* SR3F D[7:2]->VRE D[1:0]->VRS */
}
else
{
index = pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_CRT1CRTC ;
Tempax = pVBInfo->XGINEWUB_CRT1Table[ index ].CR[ 3 ] ; /* Tempax: CR4 HRS */
Tempcx = Tempax ; /* Tempcx: HRS */
XGINew_SetReg1( pVBInfo->P3c4 , 0x2E , Tempax ) ; /* SR2E[7:0]->HRS */
Tempdx = pVBInfo->XGINEWUB_CRT1Table[ index ].CR[ 5 ] ; /* SRB */
Tempdx &= 0xC0 ; /* Tempdx[7:6]: SRB[7:6] */
Temp1 = Tempdx ; /* Temp1[7:6]: HRS[9:8] */
Temp1 <<= 2 ; /* Temp1[9:8]: HRS[9:8] */
Temp1 |= Tempax ; /* Temp1[9:0]: HRS[9:0] */
Tempax = pVBInfo->XGINEWUB_CRT1Table[ index ].CR[ 4 ] ; /* CR5 HRE */
Tempax &= 0x1F ; /* Tempax[4:0]: HRE[4:0] */
Tempbx = pVBInfo->XGINEWUB_CRT1Table[ index ].CR[ 6 ] ; /* SRC */
Tempbx &= 0x04 ; /* Tempbx[2]: HRE[5] */
Tempbx <<= 3 ; /* Tempbx[5]: HRE[5] */
Tempax |= Tempbx ; /* Tempax[5:0]: HRE[5:0] */
Temp2 = Temp1 & 0x3C0 ; /* Temp2[9:6]: HRS[9:6] */
Temp2 |= Tempax ; /* Temp2[9:0]: HRE[9:0] */
Tempcx &= 0x3F ; /* Tempcx[5:0]: HRS[5:0] */
if( Tempax < Tempcx ) /* HRE < HRS */
Temp2 |= 0x40 ; /* Temp2 + 0x40 */
Temp2 &= 0xFF ;
Tempax = (unsigned char)Temp2; /* Tempax: HRE[7:0] */
Tempax <<= 2 ; /* Tempax[7:2]: HRE[5:0] */
Tempdx >>= 6 ; /* Tempdx[7:6]->[1:0] HRS[9:8] */
Tempax |= Tempdx ; /* HRE[5:0]HRS[9:8] */
XGINew_SetReg1( pVBInfo->P3c4 , 0x2F , Tempax ) ; /* SR2F D[7:2]->HRE, D[1:0]->HRS */
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x30 , 0xE3 , 00 ) ;
Tempax = pVBInfo->XGINEWUB_CRT1Table[ index ].CR[ 10 ] ; /* CR10 VRS */
Tempbx = Tempax ; /* Tempbx: VRS */
Tempax &= 0x01 ; /* Tempax[0]: VRS[0] */
XGINew_SetRegOR( pVBInfo->P3c4 , 0x33 , Tempax ) ; /* SR33[0]->VRS[0] */
Tempax = pVBInfo->XGINEWUB_CRT1Table[ index ].CR[ 9 ] ; /* CR7[2][7] VRE */
Tempcx = Tempbx >> 1 ; /* Tempcx[6:0]: VRS[7:1] */
Tempdx = Tempax & 0x04 ; /* Tempdx[2]: CR7[2] */
Tempdx <<= 5 ; /* Tempdx[7]: VRS[8] */
Tempcx |= Tempdx ; /* Tempcx[7:0]: VRS[8:1] */
XGINew_SetReg1( pVBInfo->P3c4 , 0x34 , Tempcx ) ; /* SR34[8:1]->VRS */
Temp1 = Tempdx ; /* Temp1[7]: Tempdx[7] */
Temp1 <<= 1 ; /* Temp1[8]: VRS[8] */
Temp1 |= Tempbx ; /* Temp1[8:0]: VRS[8:0] */
Tempax &= 0x80 ;
Temp2 = Tempax << 2 ; /* Temp2[9]: VRS[9] */
Temp1 |= Temp2 ; /* Temp1[9:0]: VRS[9:0] */
Tempax = pVBInfo->XGINEWUB_CRT1Table[ index ].CR[ 14 ] ; /* Tempax: SRA */
Tempax &= 0x08 ; /* Tempax[3]: VRS[3] */
Temp2 = Tempax ;
Temp2 <<= 7 ; /* Temp2[10]: VRS[10] */
Temp1 |= Temp2 ; /* Temp1[10:0]: VRS[10:0] */
Tempax = pVBInfo->XGINEWUB_CRT1Table[ index ].CR[ 11 ] ; /* Tempax: CR11 VRE */
Tempax &= 0x0F ; /* Tempax[3:0]: VRE[3:0] */
Tempbx = pVBInfo->XGINEWUB_CRT1Table[ index ].CR[ 14 ] ; /* Tempbx: SRA */
Tempbx &= 0x20 ; /* Tempbx[5]: VRE[5] */
Tempbx >>= 1 ; /* Tempbx[4]: VRE[4] */
Tempax |= Tempbx ; /* Tempax[4:0]: VRE[4:0] */
Temp2 = Temp1 & 0x7E0 ; /* Temp2[10:5]: VRS[10:5] */
Temp2 |= Tempax ; /* Temp2[10:5]: VRE[10:5] */
Temp3 = Temp1 & 0x1F ; /* Temp3[4:0]: VRS[4:0] */
if ( Tempax < Temp3 ) /* VRE < VRS */
Temp2 |= 0x20 ; /* VRE + 0x20 */
Temp2 &= 0xFF ;
Tempax = (unsigned char)Temp2; /* Tempax: VRE[7:0] */
Tempax <<= 2 ; /* Tempax[7:0]; VRE[5:0]00 */
Temp1 &= 0x600 ; /* Temp1[10:9]: VRS[10:9] */
Temp1 >>= 9 ; /* Temp1[1:0]: VRS[10:9] */
Tempbx = (unsigned char)Temp1;
Tempax |= Tempbx ; /* Tempax[7:0]: VRE[5:0]VRS[10:9] */
Tempax &= 0x7F ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x3F , Tempax ) ; /* SR3F D[7:2]->VRE D[1:0]->VRS */
}
}
void XGI_SetXG27CRTC(unsigned short ModeNo, unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned short StandTableIndex, index, Tempax, Tempbx, Tempcx, Tempdx;
if ( ModeNo <= 0x13 )
{
StandTableIndex = XGI_GetModePtr( ModeNo , ModeIdIndex, pVBInfo ) ;
Tempax = pVBInfo->StandTable[ StandTableIndex ].CRTC[ 4 ] ; /* CR04 HRS */
XGINew_SetReg1( pVBInfo->P3c4 , 0x2E , Tempax ) ; /* SR2E [7:0]->HRS */
Tempbx = pVBInfo->StandTable[ StandTableIndex ].CRTC[ 5 ] ; /* Tempbx: CR05 HRE */
Tempbx &= 0x1F ; /* Tempbx: HRE[4:0] */
Tempcx = Tempax ;
Tempcx &= 0xE0 ; /* Tempcx: HRS[7:5] */
Tempdx = Tempcx | Tempbx ; /* Tempdx(HRE): HRS[7:5]HRE[4:0] */
if ( Tempbx < ( Tempax & 0x1F ) ) /* IF HRE < HRS */
Tempdx |= 0x20 ; /* Tempdx: HRE = HRE + 0x20 */
Tempdx <<= 2 ; /* Tempdx << 2 */
XGINew_SetReg1( pVBInfo->P3c4 , 0x2F , Tempdx ) ; /* SR2F [7:2]->HRE */
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x30 , 0xE3 , 00 ) ;
Tempax = pVBInfo->StandTable[ StandTableIndex ].CRTC[ 16 ] ; /* Tempax: CR10 VRS */
XGINew_SetReg1( pVBInfo->P3c4 , 0x34 , Tempax ) ; /* SR34[7:0]->VRS */
Tempcx = Tempax ; /* Tempcx=Tempax=VRS[7:0] */
Tempax = pVBInfo->StandTable[ StandTableIndex ].CRTC[ 7 ] ; /* Tempax[7][2]: CR7[7][2] VRS[9][8] */
Tempbx = Tempax ; /* Tempbx=CR07 */
Tempax &= 0x04 ; /* Tempax[2]: CR07[2] VRS[8] */
Tempax >>= 2;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x35 , ~0x01, Tempax ) ; /* SR35 D[0]->VRS D[8] */
Tempcx |= (Tempax << 8) ; /* Tempcx[8] |= VRS[8] */
Tempcx |= (Tempbx & 0x80)<<2; /* Tempcx[9] |= VRS[9] */
Tempax = pVBInfo->StandTable[ StandTableIndex ].CRTC[ 17 ] ; /* CR11 VRE */
Tempax &= 0x0F ; /* Tempax: VRE[3:0] */
Tempbx = Tempcx ; /* Tempbx=Tempcx=VRS[9:0] */
Tempbx &= 0x3F0 ; /* Tempbx[9:4]: VRS[9:4] */
Tempbx |= Tempax ; /* Tempbx[9:0]: VRE[9:0] */
if ( Tempax <= (Tempcx & 0x0F) ) /* VRE[3:0]<=VRS[3:0] */
Tempbx |= 0x10 ; /* Tempbx: VRE + 0x10 */
Tempax = (unsigned char)Tempbx & 0xFF; /* Tempax[7:0]: VRE[7:0] */
Tempax <<= 2 ; /* Tempax << 2: VRE[5:0] */
Tempcx = (Tempcx&0x600)>>8; /* Tempcx VRS[10:9] */
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x3F , ~0xFC, Tempax ) ; /* SR3F D[7:2]->VRE D[5:0] */
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x35 , ~0x06, Tempcx ) ; /* SR35 D[2:1]->VRS[10:9] */
}
else
{
index = pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_CRT1CRTC ;
Tempax = pVBInfo->XGINEWUB_CRT1Table[ index ].CR[ 3 ] ; /* Tempax: CR4 HRS */
Tempbx = Tempax ; /* Tempbx: HRS[7:0] */
XGINew_SetReg1( pVBInfo->P3c4 , 0x2E , Tempax ) ; /* SR2E[7:0]->HRS */
Tempax = pVBInfo->XGINEWUB_CRT1Table[ index ].CR[ 5 ] ; /* SR0B */
Tempax &= 0xC0 ; /* Tempax[7:6]: SR0B[7:6]: HRS[9:8]*/
Tempbx |= (Tempax << 2); /* Tempbx: HRS[9:0] */
Tempax = pVBInfo->XGINEWUB_CRT1Table[ index ].CR[ 4 ] ; /* CR5 HRE */
Tempax &= 0x1F ; /* Tempax[4:0]: HRE[4:0] */
Tempcx = Tempax ; /* Tempcx: HRE[4:0] */
Tempax = pVBInfo->XGINEWUB_CRT1Table[ index ].CR[ 6 ] ; /* SRC */
Tempax &= 0x04 ; /* Tempax[2]: HRE[5] */
Tempax <<= 3 ; /* Tempax[5]: HRE[5] */
Tempcx |= Tempax ; /* Tempcx[5:0]: HRE[5:0] */
Tempbx = Tempbx & 0x3C0 ; /* Tempbx[9:6]: HRS[9:6] */
Tempbx |= Tempcx ; /* Tempbx: HRS[9:6]HRE[5:0] */
Tempax = pVBInfo->XGINEWUB_CRT1Table[ index ].CR[ 3 ] ; /* Tempax: CR4 HRS */
Tempax &= 0x3F ; /* Tempax: HRS[5:0] */
if( Tempcx <= Tempax ) /* HRE[5:0] < HRS[5:0] */
Tempbx += 0x40 ; /* Tempbx= Tempbx + 0x40 : HRE[9:0]*/
Tempax = pVBInfo->XGINEWUB_CRT1Table[ index ].CR[ 5 ] ; /* SR0B */
Tempax &= 0xC0 ; /* Tempax[7:6]: SR0B[7:6]: HRS[9:8]*/
Tempax >>= 6; /* Tempax[1:0]: HRS[9:8]*/
Tempax |= ((Tempbx << 2) & 0xFF); /* Tempax[7:2]: HRE[5:0] */
XGINew_SetReg1( pVBInfo->P3c4 , 0x2F , Tempax ) ; /* SR2F [7:2][1:0]: HRE[5:0]HRS[9:8] */
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x30 , 0xE3 , 00 ) ;
Tempax = pVBInfo->XGINEWUB_CRT1Table[ index ].CR[ 10 ] ; /* CR10 VRS */
XGINew_SetReg1( pVBInfo->P3c4 , 0x34 , Tempax ) ; /* SR34[7:0]->VRS[7:0] */
Tempcx = Tempax ; /* Tempcx <= VRS[7:0] */
Tempax = pVBInfo->XGINEWUB_CRT1Table[ index ].CR[ 9 ] ; /* CR7[7][2] VRS[9][8] */
Tempbx = Tempax ; /* Tempbx <= CR07[7:0] */
Tempax = Tempax & 0x04 ; /* Tempax[2]: CR7[2]: VRS[8] */
Tempax >>= 2 ; /* Tempax[0]: VRS[8] */
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x35 , ~0x01 , Tempax ) ; /* SR35[0]: VRS[8] */
Tempcx |= (Tempax<<8) ; /* Tempcx <= VRS[8:0] */
Tempcx |= ((Tempbx&0x80)<<2) ; /* Tempcx <= VRS[9:0] */
Tempax = pVBInfo->XGINEWUB_CRT1Table[ index ].CR[ 14 ] ; /* Tempax: SR0A */
Tempax &= 0x08; /* SR0A[3] VRS[10] */
Tempcx |= (Tempax<<7) ; /* Tempcx <= VRS[10:0] */
Tempax = pVBInfo->XGINEWUB_CRT1Table[ index ].CR[ 11 ] ; /* Tempax: CR11 VRE */
Tempax &= 0x0F ; /* Tempax[3:0]: VRE[3:0] */
Tempbx = pVBInfo->XGINEWUB_CRT1Table[ index ].CR[ 14 ] ; /* Tempbx: SR0A */
Tempbx &= 0x20 ; /* Tempbx[5]: SR0A[5]: VRE[4] */
Tempbx >>= 1 ; /* Tempbx[4]: VRE[4] */
Tempax |= Tempbx ; /* Tempax[4:0]: VRE[4:0] */
Tempbx = Tempcx ; /* Tempbx: VRS[10:0] */
Tempbx &= 0x7E0 ; /* Tempbx[10:5]: VRS[10:5] */
Tempbx |= Tempax ; /* Tempbx: VRS[10:5]VRE[4:0] */
if ( Tempbx <= Tempcx ) /* VRE <= VRS */
Tempbx |= 0x20 ; /* VRE + 0x20 */
Tempax = (Tempbx<<2) & 0xFF ; /* Tempax: Tempax[7:0]; VRE[5:0]00 */
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x3F , ~0xFC , Tempax ) ; /* SR3F[7:2]:VRE[5:0] */
Tempax = Tempcx >> 8;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x35 , ~0x07 , Tempax ) ; /* SR35[2:0]:VRS[10:8] */
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetXG21LCD */
/* Input : */
/* Output : FCLK duty cycle, FCLK delay compensation */
/* Description : All values set zero */
/* --------------------------------------------------------------------- */
void XGI_SetXG21LCD(struct vb_device_info *pVBInfo,
unsigned short RefreshRateTableIndex,
unsigned short ModeNo)
{
unsigned short Data, Temp, b3CC;
unsigned short XGI_P3cc;
XGI_P3cc = pVBInfo->P3cc ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x2E , 0x00 ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x2F , 0x00 ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x46 , 0x00 ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x47 , 0x00 ) ;
if ( ((*pVBInfo->pDVOSetting)&0xC0) == 0xC0 )
{
XGINew_SetReg1( pVBInfo->P3d4 , 0x2E , *pVBInfo->pCR2E ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x2F , *pVBInfo->pCR2F ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x46 , *pVBInfo->pCR46 ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x47 , *pVBInfo->pCR47 ) ;
}
Temp = XGINew_GetReg1( pVBInfo->P3d4 , 0x37 ) ;
if ( Temp & 0x01 )
{
XGINew_SetRegOR( pVBInfo->P3c4 , 0x06 , 0x40 ) ; /* 18 bits FP */
XGINew_SetRegOR( pVBInfo->P3c4 , 0x09 , 0x40 ) ;
}
XGINew_SetRegOR( pVBInfo->P3c4 , 0x1E , 0x01 ) ; /* Negative blank polarity */
XGINew_SetRegAND( pVBInfo->P3c4 , 0x30 , ~0x20 ) ;
XGINew_SetRegAND( pVBInfo->P3c4 , 0x35 , ~0x80 ) ;
if ( ModeNo <= 0x13 )
{
b3CC = (unsigned char) XGINew_GetReg2(XGI_P3cc);
if ( b3CC & 0x40 )
XGINew_SetRegOR( pVBInfo->P3c4 , 0x30 , 0x20 ) ; /* Hsync polarity */
if ( b3CC & 0x80 )
XGINew_SetRegOR( pVBInfo->P3c4 , 0x35 , 0x80 ) ; /* Vsync polarity */
}
else
{
Data = pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_InfoFlag ;
if ( Data & 0x4000 )
XGINew_SetRegOR( pVBInfo->P3c4 , 0x30 , 0x20 ) ; /* Hsync polarity */
if ( Data & 0x8000 )
XGINew_SetRegOR( pVBInfo->P3c4 , 0x35 , 0x80 ) ; /* Vsync polarity */
}
}
void XGI_SetXG27LCD(struct vb_device_info *pVBInfo,
unsigned short RefreshRateTableIndex,
unsigned short ModeNo)
{
unsigned short Data , Temp , b3CC ;
unsigned short XGI_P3cc ;
XGI_P3cc = pVBInfo->P3cc ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x2E , 0x00 ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x2F , 0x00 ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x46 , 0x00 ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x47 , 0x00 ) ;
Temp = XGINew_GetReg1( pVBInfo->P3d4 , 0x37 ) ;
if ( ( Temp & 0x03 ) == 0 ) /* dual 12 */
{
XGINew_SetReg1( pVBInfo->P3d4 , 0x46 , 0x13 ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x47 , 0x13 ) ;
}
if ( ((*pVBInfo->pDVOSetting)&0xC0) == 0xC0 )
{
XGINew_SetReg1( pVBInfo->P3d4 , 0x2E , *pVBInfo->pCR2E ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x2F , *pVBInfo->pCR2F ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x46 , *pVBInfo->pCR46 ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x47 , *pVBInfo->pCR47 ) ;
}
XGI_SetXG27FPBits(pVBInfo);
XGINew_SetRegOR( pVBInfo->P3c4 , 0x1E , 0x01 ) ; /* Negative blank polarity */
XGINew_SetRegAND( pVBInfo->P3c4 , 0x30 , ~0x20 ) ; /* Hsync polarity */
XGINew_SetRegAND( pVBInfo->P3c4 , 0x35 , ~0x80 ) ; /* Vsync polarity */
if ( ModeNo <= 0x13 )
{
b3CC = (unsigned char) XGINew_GetReg2(XGI_P3cc);
if ( b3CC & 0x40 )
XGINew_SetRegOR( pVBInfo->P3c4 , 0x30 , 0x20 ) ; /* Hsync polarity */
if ( b3CC & 0x80 )
XGINew_SetRegOR( pVBInfo->P3c4 , 0x35 , 0x80 ) ; /* Vsync polarity */
}
else
{
Data = pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_InfoFlag ;
if ( Data & 0x4000 )
XGINew_SetRegOR( pVBInfo->P3c4 , 0x30 , 0x20 ) ; /* Hsync polarity */
if ( Data & 0x8000 )
XGINew_SetRegOR( pVBInfo->P3c4 , 0x35 , 0x80 ) ; /* Vsync polarity */
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_UpdateXG21CRTC */
/* Input : */
/* Output : CRT1 CRTC */
/* Description : Modify CRT1 Hsync/Vsync to fix LCD mode timing */
/* --------------------------------------------------------------------- */
void XGI_UpdateXG21CRTC(unsigned short ModeNo,
struct vb_device_info *pVBInfo,
unsigned short RefreshRateTableIndex)
{
int i , index = -1;
XGINew_SetRegAND( pVBInfo->P3d4 , 0x11 , 0x7F ) ; /* Unlock CR0~7 */
if ( ModeNo <= 0x13 )
{
for( i = 0 ; i < 12 ; i++ )
{
if ( ModeNo == pVBInfo->UpdateCRT1[ i ].ModeID )
index = i ;
}
}
else
{
if ( ModeNo == 0x2E && ( pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_CRT1CRTC == RES640x480x60 ) )
index = 12 ;
else if ( ModeNo == 0x2E && ( pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_CRT1CRTC == RES640x480x72 ) )
index = 13 ;
else if ( ModeNo == 0x2F )
index = 14 ;
else if ( ModeNo == 0x50 )
index = 15 ;
else if ( ModeNo == 0x59 )
index = 16 ;
}
if( index != -1 )
{
XGINew_SetReg1( pVBInfo->P3d4 , 0x02 , pVBInfo->UpdateCRT1[ index ].CR02 ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x03 , pVBInfo->UpdateCRT1[ index ].CR03 ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x15 , pVBInfo->UpdateCRT1[ index ].CR15 ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x16 , pVBInfo->UpdateCRT1[ index ].CR16 ) ;
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetCRT1DE */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetCRT1DE(struct xgi_hw_device_info *HwDeviceExtension,
unsigned short ModeNo,
unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned short resindex, tempax, tempbx, tempcx, temp, modeflag;
unsigned char data;
resindex = XGI_GetResInfo( ModeNo , ModeIdIndex, pVBInfo ) ;
if ( ModeNo <= 0x13 )
{
modeflag = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ;
tempax = pVBInfo->StResInfo[ resindex ].HTotal ;
tempbx = pVBInfo->StResInfo[ resindex ].VTotal ;
}
else
{
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ;
tempax = pVBInfo->ModeResInfo[ resindex ].HTotal ;
tempbx = pVBInfo->ModeResInfo[ resindex ].VTotal ;
}
if ( modeflag & HalfDCLK )
tempax = tempax >> 1 ;
if ( ModeNo > 0x13 )
{
if ( modeflag & HalfDCLK )
tempax = tempax << 1 ;
temp = pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_InfoFlag ;
if ( temp & InterlaceMode )
tempbx = tempbx >> 1 ;
if ( modeflag & DoubleScanMode )
tempbx = tempbx << 1 ;
}
tempcx = 8 ;
/* if ( !( modeflag & Charx8Dot ) ) */
/* tempcx = 9 ; */
tempax /= tempcx ;
tempax -= 1 ;
tempbx -= 1 ;
tempcx = tempax ;
temp = (unsigned char)XGINew_GetReg1(pVBInfo->P3d4, 0x11);
data = (unsigned char)XGINew_GetReg1(pVBInfo->P3d4, 0x11);
data &= 0x7F ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x11 , data ) ; /* Unlock CRTC */
XGINew_SetReg1(pVBInfo->P3d4, 0x01, (unsigned short)(tempcx & 0xff));
XGINew_SetRegANDOR(pVBInfo->P3d4, 0x0b, ~0x0c, (unsigned short)((tempcx & 0x0ff00) >> 10));
XGINew_SetReg1(pVBInfo->P3d4, 0x12, (unsigned short)(tempbx & 0xff));
tempax = 0 ;
tempbx = tempbx >> 8 ;
if ( tempbx & 0x01 )
tempax |= 0x02 ;
if ( tempbx & 0x02 )
tempax |= 0x40 ;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x07 , ~0x42 , tempax ) ;
data = (unsigned char)XGINew_GetReg1(pVBInfo->P3d4, 0x07);
data &= 0xFF ;
tempax = 0 ;
if ( tempbx & 0x04 )
tempax |= 0x02 ;
XGINew_SetRegANDOR( pVBInfo->P3d4 ,0x0a , ~0x02 , tempax ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x11 , temp ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetResInfo */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
unsigned short XGI_GetResInfo(unsigned short ModeNo,
unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned short resindex;
if ( ModeNo <= 0x13 )
{
resindex = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ResInfo ; /* si+St_ResInfo */
}
else
{
resindex = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_RESINFO ; /* si+Ext_ResInfo */
}
return( resindex ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetCRT1Offset */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetCRT1Offset(unsigned short ModeNo,
unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct xgi_hw_device_info *HwDeviceExtension,
struct vb_device_info *pVBInfo)
{
unsigned short temp ,
ah ,
al ,
temp2 ,
i ,
DisplayUnit ;
/* GetOffset */
temp = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeInfo ;
temp = temp >> 8 ;
temp = pVBInfo->ScreenOffset[ temp ] ;
temp2 = pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_InfoFlag ;
temp2 &= InterlaceMode ;
if ( temp2 )
temp = temp << 1;
temp2 = pVBInfo->ModeType - ModeEGA ;
switch( temp2 )
{
case 0:
temp2 = 1 ;
break ;
case 1:
temp2 = 2 ;
break ;
case 2:
temp2 = 4 ;
break ;
case 3:
temp2 = 4 ;
break ;
case 4:
temp2 = 6 ;
break;
case 5:
temp2 = 8 ;
break ;
default:
break ;
}
if ( ( ModeNo >= 0x26 ) && ( ModeNo <= 0x28 ) )
temp = temp * temp2 + temp2 / 2 ;
else
temp *= temp2 ;
/* SetOffset */
DisplayUnit = temp ;
temp2 = temp ;
temp = temp >> 8 ; /* ah */
temp &= 0x0F ;
i = XGINew_GetReg1( pVBInfo->P3c4 , 0x0E ) ;
i &= 0xF0 ;
i |= temp ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x0E , i ) ;
temp = (unsigned char)temp2;
temp &= 0xFF ; /* al */
XGINew_SetReg1( pVBInfo->P3d4 , 0x13 , temp ) ;
/* SetDisplayUnit */
temp2 = pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_InfoFlag ;
temp2 &= InterlaceMode ;
if ( temp2 )
DisplayUnit >>= 1 ;
DisplayUnit = DisplayUnit << 5 ;
ah = ( DisplayUnit & 0xff00 ) >> 8 ;
al = DisplayUnit & 0x00ff ;
if ( al == 0 )
ah += 1 ;
else
ah += 2 ;
if ( HwDeviceExtension->jChipType >= XG20 )
if ( ( ModeNo == 0x4A ) | (ModeNo == 0x49 ) )
ah -= 1 ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x10 , ah ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetCRT1VCLK */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetCRT1VCLK(unsigned short ModeNo, unsigned short ModeIdIndex,
struct xgi_hw_device_info *HwDeviceExtension,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned char index, data;
unsigned short vclkindex ;
if ( pVBInfo->IF_DEF_LVDS == 1 )
{
index = pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_CRTVCLK ;
data = XGINew_GetReg1( pVBInfo->P3c4 , 0x31 ) & 0xCF ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x31 , data ) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2B , pVBInfo->VCLKData[ index ].SR2B ) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2C , pVBInfo->VCLKData[ index ].SR2C ) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2D , 0x01 ) ;
}
else if ( ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) ) && ( pVBInfo->VBInfo & SetCRT2ToLCDA ) )
{
vclkindex = XGI_GetVCLK2Ptr( ModeNo , ModeIdIndex , RefreshRateTableIndex , HwDeviceExtension, pVBInfo ) ;
data = XGINew_GetReg1( pVBInfo->P3c4 , 0x31 ) & 0xCF ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x31 , data ) ;
data = pVBInfo->VBVCLKData[ vclkindex ].Part4_A ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2B , data ) ;
data = pVBInfo->VBVCLKData[ vclkindex ].Part4_B ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2C , data ) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2D , 0x01 ) ;
}
else
{
index = pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_CRTVCLK ;
data = XGINew_GetReg1( pVBInfo->P3c4 , 0x31 ) & 0xCF ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x31 , data ) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2B , pVBInfo->VCLKData[ index ].SR2B ) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2C , pVBInfo->VCLKData[ index ].SR2C ) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2D , 0x01 ) ;
}
if ( HwDeviceExtension->jChipType >= XG20 )
{
if ( pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag & HalfDCLK )
{
data = XGINew_GetReg1( pVBInfo->P3c4 , 0x2B ) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2B , data ) ;
data = XGINew_GetReg1( pVBInfo->P3c4 , 0x2C ) ;
index = data ;
index &= 0xE0 ;
data &= 0x1F ;
data = data << 1 ;
data += 1 ;
data |= index ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2C , data ) ;
}
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetCRT1FIFO */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetCRT1FIFO(unsigned short ModeNo,
struct xgi_hw_device_info *HwDeviceExtension,
struct vb_device_info *pVBInfo)
{
unsigned short data ;
data = XGINew_GetReg1( pVBInfo->P3c4 , 0x3D ) ;
data &= 0xfe ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x3D , data ) ; /* diable auto-threshold */
if ( ModeNo > 0x13 )
{
XGINew_SetReg1( pVBInfo->P3c4 , 0x08 , 0x34 ) ;
data = XGINew_GetReg1( pVBInfo->P3c4 , 0x09 ) ;
data &= 0xC0 ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x09 , data | 0x30) ;
data = XGINew_GetReg1( pVBInfo->P3c4 , 0x3D ) ;
data |= 0x01 ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x3D , data ) ;
}
else
{
if (HwDeviceExtension->jChipType == XG27)
{
XGINew_SetReg1( pVBInfo->P3c4 , 0x08 , 0x0E ) ;
data = XGINew_GetReg1( pVBInfo->P3c4 , 0x09 ) ;
data &= 0xC0 ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x09 , data | 0x20 ) ;
}
else
{
XGINew_SetReg1( pVBInfo->P3c4 , 0x08 , 0xAE ) ;
data = XGINew_GetReg1( pVBInfo->P3c4 , 0x09 ) ;
data &= 0xF0 ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x09 , data ) ;
}
}
if (HwDeviceExtension->jChipType == XG21)
{
XGI_SetXG21FPBits(pVBInfo); /* Fix SR9[7:6] can't read back */
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetCRT1ModeRegs */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetCRT1ModeRegs(struct xgi_hw_device_info *HwDeviceExtension,
unsigned short ModeNo, unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned short data ,
data2 ,
data3 ,
infoflag = 0 ,
modeflag ,
resindex ,
xres ;
if ( ModeNo > 0x13 )
{
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ;
infoflag = pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_InfoFlag ;
}
else
modeflag = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ; /* si+St_ModeFlag */
if ( XGINew_GetReg1( pVBInfo->P3d4 , 0x31 ) & 0x01 )
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x1F , 0x3F , 0x00 ) ;
if ( ModeNo > 0x13 )
data = infoflag ;
else
data = 0 ;
data2 = 0 ;
if ( ModeNo > 0x13 )
{
if ( pVBInfo->ModeType > 0x02 )
{
data2 |= 0x02 ;
data3 = pVBInfo->ModeType - ModeVGA ;
data3 = data3 << 2 ;
data2 |= data3 ;
}
}
data &= InterlaceMode ;
if ( data )
data2 |= 0x20 ;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x06 , ~0x3F , data2 ) ;
/* XGINew_SetReg1(pVBInfo->P3c4,0x06,data2); */
resindex = XGI_GetResInfo( ModeNo , ModeIdIndex, pVBInfo ) ;
if ( ModeNo <= 0x13 )
xres = pVBInfo->StResInfo[ resindex ].HTotal ;
else
xres = pVBInfo->ModeResInfo[ resindex ].HTotal ; /* xres->ax */
data = 0x0000 ;
if ( infoflag & InterlaceMode )
{
if ( xres == 1024 )
data = 0x0035 ;
else if ( xres == 1280 )
data = 0x0048 ;
}
data2 = data & 0x00FF ;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x19 , 0xFF , data2 ) ;
data2 = ( data & 0xFF00 ) >> 8 ;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x19 , 0xFC , data2 ) ;
if( modeflag & HalfDCLK )
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x01 , 0xF7 , 0x08 ) ;
data2 = 0 ;
if ( modeflag & LineCompareOff )
data2 |= 0x08 ;
if ( ModeNo > 0x13 )
{
if ( pVBInfo->ModeType == ModeEGA )
data2 |= 0x40 ;
}
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x0F , ~0x48 , data2 ) ;
data = 0x60 ;
if ( pVBInfo->ModeType != ModeText )
{
data = data ^ 0x60 ;
if ( pVBInfo->ModeType != ModeEGA )
{
data = data ^ 0xA0 ;
}
}
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x21 , 0x1F , data ) ;
XGI_SetVCLKState( HwDeviceExtension , ModeNo , RefreshRateTableIndex, pVBInfo) ;
/* if(modeflag&HalfDCLK)//030305 fix lowresolution bug */
/* if(XGINew_IF_DEF_NEW_LOWRES) */
/* XGI_VesaLowResolution(ModeNo,ModeIdIndex);//030305 fix lowresolution bug */
data=XGINew_GetReg1( pVBInfo->P3d4 , 0x31 ) ;
if (HwDeviceExtension->jChipType == XG27 )
{
if ( data & 0x40 )
data = 0x2c ;
else
data = 0x6c ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x52 , data ) ;
XGINew_SetRegOR( pVBInfo->P3d4 , 0x51 , 0x10 ) ;
}
else
if (HwDeviceExtension->jChipType >= XG20 )
{
if ( data & 0x40 )
data = 0x33 ;
else
data = 0x73 ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x52 , data ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x51 , 0x02 ) ;
}
else
{
if ( data & 0x40 )
data = 0x2c ;
else
data = 0x6c ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x52 , data ) ;
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetVCLKState */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetVCLKState(struct xgi_hw_device_info *HwDeviceExtension,
unsigned short ModeNo,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned short data ,
data2 = 0 ;
short VCLK ;
unsigned char index;
if ( ModeNo <= 0x13 )
VCLK = 0 ;
else
{
index = pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_CRTVCLK ;
index &= IndexMask ;
VCLK = pVBInfo->VCLKData[ index ].CLOCK ;
}
data = XGINew_GetReg1( pVBInfo->P3c4 , 0x32 ) ;
data &= 0xf3 ;
if ( VCLK >= 200 )
data |= 0x0c ; /* VCLK > 200 */
if ( HwDeviceExtension->jChipType >= XG20 )
data &= ~0x04 ; /* 2 pixel mode */
XGINew_SetReg1( pVBInfo->P3c4 , 0x32 , data ) ;
if ( HwDeviceExtension->jChipType < XG20 )
{
data = XGINew_GetReg1( pVBInfo->P3c4 , 0x1F ) ;
data &= 0xE7 ;
if ( VCLK < 200 )
data |= 0x10 ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x1F , data ) ;
}
/* Jong for Adavantech LCD ripple issue
if ( ( VCLK >= 0 ) && ( VCLK < 135 ) )
data2 = 0x03 ;
else if ( ( VCLK >= 135 ) && ( VCLK < 160 ) )
data2 = 0x02 ;
else if ( ( VCLK >= 160 ) && ( VCLK < 260 ) )
data2 = 0x01 ;
else if ( VCLK > 260 )
data2 = 0x00 ;
*/
data2 = 0x00 ;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x07 , 0xFC , data2 ) ;
if (HwDeviceExtension->jChipType >= XG27 )
{
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x40 , 0xFC , data2&0x03 ) ;
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_VesaLowResolution */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
/*void XGI_VesaLowResolution(unsigned short ModeNo, unsigned short ModeIdIndex, struct vb_device_info *pVBInfo)
{
unsigned short modeflag;
if ( ModeNo > 0x13 )
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ;
else
modeflag = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ;
if ( ModeNo > 0x13 )
{
if ( modeflag & DoubleScanMode )
{
if ( modeflag & HalfDCLK )
{
if ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{
if ( !( pVBInfo->VBInfo & SetCRT2ToRAMDAC ) )
{
if ( pVBInfo->VBInfo & SetInSlaveMode )
{
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x01 , 0xf7 , 0x00 ) ;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x0f , 0x7f , 0x00 ) ;
return ;
}
}
}
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x0f , 0xff , 0x80 ) ;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x01 , 0xf7 , 0x00 ) ;
return ;
}
}
}
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x0f , 0x7f , 0x00 ) ;
}
*/
/* --------------------------------------------------------------------- */
/* Function : XGI_LoadDAC */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_LoadDAC(unsigned short ModeNo,
unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned short data , data2 , time ,
i , j , k , m , n , o ,
si , di , bx , dl , al , ah , dh ,
*table = NULL ;
if ( ModeNo <= 0x13 )
data = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ;
else
data = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ;
data &= DACInfoFlag ;
time = 64 ;
if ( data == 0x00 )
table = XGINew_MDA_DAC ;
else if ( data == 0x08 )
table = XGINew_CGA_DAC ;
else if ( data == 0x10 )
table = XGINew_EGA_DAC ;
else if ( data == 0x18 )
{
time = 256 ;
table = XGINew_VGA_DAC ;
}
if ( time == 256 )
j = 16 ;
else
j = time ;
XGINew_SetReg3( pVBInfo->P3c6 , 0xFF ) ;
XGINew_SetReg3( pVBInfo->P3c8 , 0x00 ) ;
for( i = 0 ; i < j ; i++ )
{
data = table[ i ] ;
for( k = 0 ; k < 3 ; k++ )
{
data2 = 0 ;
if ( data & 0x01 )
data2 = 0x2A ;
if ( data & 0x02 )
data2 += 0x15 ;
XGINew_SetReg3( pVBInfo->P3c9 , data2 ) ;
data = data >> 2 ;
}
}
if ( time == 256 )
{
for( i = 16 ; i < 32 ; i++ )
{
data = table[ i ] ;
for( k = 0 ; k < 3 ; k++ )
XGINew_SetReg3( pVBInfo->P3c9 , data ) ;
}
si = 32 ;
for( m = 0 ; m < 9 ; m++ )
{
di = si ;
bx = si + 0x04 ;
dl = 0 ;
for( n = 0 ; n < 3 ; n++ )
{
for( o = 0 ; o < 5 ; o++ )
{
dh = table[ si ] ;
ah = table[ di ] ;
al = table[ bx ] ;
si++ ;
XGI_WriteDAC( dl , ah , al , dh, pVBInfo ) ;
}
si -= 2 ;
for( o = 0 ; o < 3 ; o++ )
{
dh = table[ bx ] ;
ah = table[ di ] ;
al = table[ si ] ;
si-- ;
XGI_WriteDAC( dl , ah , al , dh, pVBInfo ) ;
}
dl++ ;
}
si += 5 ;
}
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_WriteDAC */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_WriteDAC(unsigned short dl, unsigned short ah,
unsigned short al, unsigned short dh,
struct vb_device_info *pVBInfo)
{
unsigned short temp , bh , bl ;
bh = ah ;
bl = al ;
if ( dl != 0 )
{
temp = bh ;
bh = dh ;
dh = temp ;
if ( dl == 1 )
{
temp = bl ;
bl = dh ;
dh = temp ;
}
else
{
temp = bl ;
bl = bh ;
bh = temp ;
}
}
XGINew_SetReg3(pVBInfo->P3c9, (unsigned short)dh);
XGINew_SetReg3(pVBInfo->P3c9, (unsigned short)bh);
XGINew_SetReg3(pVBInfo->P3c9, (unsigned short)bl);
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetLCDAGroup */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetLCDAGroup(unsigned short ModeNo,
unsigned short ModeIdIndex,
struct xgi_hw_device_info *HwDeviceExtension,
struct vb_device_info *pVBInfo)
{
unsigned short RefreshRateTableIndex ;
/* unsigned short temp ; */
/* pVBInfo->SelectCRT2Rate = 0 ; */
pVBInfo->SetFlag |= ProgrammingCRT2 ;
RefreshRateTableIndex = XGI_GetRatePtrCRT2( HwDeviceExtension, ModeNo , ModeIdIndex, pVBInfo ) ;
XGI_GetLVDSResInfo( ModeNo , ModeIdIndex, pVBInfo ) ;
XGI_GetLVDSData( ModeNo , ModeIdIndex , RefreshRateTableIndex, pVBInfo);
XGI_ModCRT1Regs( ModeNo , ModeIdIndex , RefreshRateTableIndex , HwDeviceExtension, pVBInfo ) ;
XGI_SetLVDSRegs( ModeNo , ModeIdIndex , RefreshRateTableIndex, pVBInfo ) ;
XGI_SetCRT2ECLK( ModeNo , ModeIdIndex , RefreshRateTableIndex, pVBInfo ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetLVDSResInfo */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_GetLVDSResInfo(unsigned short ModeNo,
unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned short resindex , xres , yres , modeflag ;
if ( ModeNo <= 0x13 )
{
modeflag = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ResInfo ; /* si+St_ResInfo */
}
else
{
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_RESINFO ; /* si+Ext_ResInfo */
}
/* if ( ModeNo > 0x13 ) */
/* modeflag = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ; */
/* else */
/* modeflag = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ; */
if ( ModeNo <= 0x13 )
{
resindex = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ResInfo ; /* si+St_ResInfo */
}
else
{
resindex = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_RESINFO ; /* si+Ext_ResInfo */
}
/* resindex = XGI_GetResInfo( ModeNo , ModeIdIndex, pVBInfo ) ; */
if ( ModeNo <= 0x13 )
{
xres = pVBInfo->StResInfo[ resindex ].HTotal ;
yres = pVBInfo->StResInfo[ resindex ].VTotal ;
}
else
{
xres = pVBInfo->ModeResInfo[ resindex ].HTotal ;
yres = pVBInfo->ModeResInfo[ resindex ].VTotal ;
}
if ( ModeNo > 0x13 )
{
if ( modeflag & HalfDCLK )
xres = xres << 1 ;
if ( modeflag & DoubleScanMode )
yres = yres << 1 ;
}
/* if ( modeflag & Charx8Dot ) */
/* { */
if ( xres == 720 )
xres = 640 ;
/* } */
pVBInfo->VGAHDE = xres ;
pVBInfo->HDE = xres ;
pVBInfo->VGAVDE = yres ;
pVBInfo->VDE = yres ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetLVDSData */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_GetLVDSData(unsigned short ModeNo,
unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned short tempbx ;
struct XGI330_LVDSDataStruct *LCDPtr = NULL ;
struct XGI330_CHTVDataStruct *TVPtr = NULL ;
tempbx = 2 ;
if ( pVBInfo->VBInfo & ( SetCRT2ToLCD | SetCRT2ToLCDA ) )
{
LCDPtr = (struct XGI330_LVDSDataStruct *)XGI_GetLcdPtr(tempbx, ModeNo, ModeIdIndex, RefreshRateTableIndex, pVBInfo);
pVBInfo->VGAHT = LCDPtr->VGAHT ;
pVBInfo->VGAVT = LCDPtr->VGAVT ;
pVBInfo->HT = LCDPtr->LCDHT ;
pVBInfo->VT = LCDPtr->LCDVT ;
}
if ( pVBInfo->IF_DEF_CH7017 == 1 )
{
if ( pVBInfo->VBInfo & SetCRT2ToTV )
{
TVPtr = (struct XGI330_CHTVDataStruct *)XGI_GetTVPtr(tempbx, ModeNo, ModeIdIndex, RefreshRateTableIndex, pVBInfo);
pVBInfo->VGAHT = TVPtr->VGAHT ;
pVBInfo->VGAVT = TVPtr->VGAVT ;
pVBInfo->HT = TVPtr->LCDHT ;
pVBInfo->VT = TVPtr->LCDVT ;
}
}
if ( pVBInfo->VBInfo & ( SetCRT2ToLCD | SetCRT2ToLCDA ) )
{
if ( !( pVBInfo->LCDInfo & ( SetLCDtoNonExpanding | EnableScalingLCD ) ) )
{
if ( ( pVBInfo->LCDResInfo == Panel1024x768 ) || ( pVBInfo->LCDResInfo == Panel1024x768x75 ) )
{
pVBInfo->HDE = 1024 ;
pVBInfo->VDE = 768 ;
}
else if ( ( pVBInfo->LCDResInfo == Panel1280x1024 ) || ( pVBInfo->LCDResInfo == Panel1280x1024x75 ) )
{
pVBInfo->HDE = 1280 ;
pVBInfo->VDE = 1024 ;
}
else if ( pVBInfo->LCDResInfo == Panel1400x1050 )
{
pVBInfo->HDE = 1400 ;
pVBInfo->VDE = 1050 ;
}
else
{
pVBInfo->HDE = 1600 ;
pVBInfo->VDE = 1200 ;
}
}
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_ModCRT1Regs */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_ModCRT1Regs(unsigned short ModeNo, unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct xgi_hw_device_info *HwDeviceExtension,
struct vb_device_info *pVBInfo)
{
unsigned char index;
unsigned short tempbx , i ;
struct XGI_LVDSCRT1HDataStruct *LCDPtr = NULL;
struct XGI_LVDSCRT1VDataStruct *LCDPtr1 = NULL;
/* struct XGI330_CHTVDataStruct *TVPtr = NULL ; */
struct XGI_CH7007TV_TimingHStruct *CH7007TV_TimingHPtr = NULL;
struct XGI_CH7007TV_TimingVStruct *CH7007TV_TimingVPtr = NULL;
if( ModeNo <= 0x13 )
index = pVBInfo->SModeIDTable[ ModeIdIndex ].St_CRT2CRTC ;
else
index = pVBInfo->RefIndex[RefreshRateTableIndex].Ext_CRT2CRTC;
index= index & IndexMask ;
if ( ( pVBInfo->IF_DEF_ScaleLCD == 0 ) || ( ( pVBInfo->IF_DEF_ScaleLCD == 1 ) && ( !( pVBInfo->LCDInfo & EnableScalingLCD ) ) ) )
{
tempbx = 0 ;
if ( pVBInfo->VBInfo & ( SetCRT2ToLCD | SetCRT2ToLCDA ) )
{
LCDPtr = (struct XGI_LVDSCRT1HDataStruct *)XGI_GetLcdPtr(tempbx, ModeNo, ModeIdIndex, RefreshRateTableIndex, pVBInfo);
for( i = 0 ; i < 8 ; i++ )
pVBInfo->TimingH[ 0 ].data[ i ] = LCDPtr[ 0 ].Reg[ i ] ;
}
if ( pVBInfo->IF_DEF_CH7007 == 1 )
{
if ( pVBInfo->VBInfo & SetCRT2ToTV )
{
CH7007TV_TimingHPtr = (struct XGI_CH7007TV_TimingHStruct *)XGI_GetTVPtr(tempbx, ModeNo, ModeIdIndex, RefreshRateTableIndex, pVBInfo);
for( i = 0 ; i < 8 ; i++ )
pVBInfo->TimingH[ 0 ].data[ i ] = CH7007TV_TimingHPtr[ 0 ].data[ i ] ;
}
}
/* if ( pVBInfo->IF_DEF_CH7017 == 1 )
{
if ( pVBInfo->VBInfo & SetCRT2ToTV )
TVPtr = ( struct XGI330_CHTVDataStruct *)XGI_GetTVPtr( tempbx , ModeNo , ModeIdIndex , RefreshRateTableIndex, pVBInfo ) ;
} */
XGI_SetCRT1Timing_H(pVBInfo,HwDeviceExtension) ;
if ( pVBInfo->IF_DEF_CH7007 == 1 )
{
XGINew_SetReg1( pVBInfo->P3c4 , 0x2E , CH7007TV_TimingHPtr[ 0 ].data[ 8 ] ) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2F , CH7007TV_TimingHPtr[ 0 ].data[ 9 ] ) ;
}
tempbx = 1 ;
if ( pVBInfo->VBInfo & ( SetCRT2ToLCD | SetCRT2ToLCDA ) )
{
LCDPtr1 = (struct XGI_LVDSCRT1VDataStruct *)XGI_GetLcdPtr(tempbx, ModeNo, ModeIdIndex, RefreshRateTableIndex, pVBInfo);
for( i = 0 ; i < 7 ; i++ )
pVBInfo->TimingV[ 0 ].data[ i ] = LCDPtr1[ 0 ].Reg[ i ] ;
}
if ( pVBInfo->IF_DEF_CH7007 == 1 )
{
if ( pVBInfo->VBInfo & SetCRT2ToTV )
{
CH7007TV_TimingVPtr = (struct XGI_CH7007TV_TimingVStruct *)XGI_GetTVPtr(tempbx, ModeNo, ModeIdIndex, RefreshRateTableIndex, pVBInfo);
for( i = 0 ; i < 7 ; i++ )
pVBInfo->TimingV[ 0 ].data[ i ] = CH7007TV_TimingVPtr[ 0 ].data[ i ] ;
}
}
/* if ( pVBInfo->IF_DEF_CH7017 == 1 )
{
if ( pVBInfo->VBInfo & SetCRT2ToTV )
TVPtr = ( struct XGI330_CHTVDataStruct *)XGI_GetTVPtr( tempbx , ModeNo , ModeIdIndex , RefreshRateTableIndex, pVBInfo ) ;
} */
XGI_SetCRT1Timing_V( ModeIdIndex , ModeNo , pVBInfo) ;
if ( pVBInfo->IF_DEF_CH7007 == 1 )
{
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x33 , ~0x01 , CH7007TV_TimingVPtr[ 0 ].data[ 7 ]&0x01 ) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x34 , CH7007TV_TimingVPtr[ 0 ].data[8 ] ) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x3F , CH7007TV_TimingVPtr[ 0 ].data[9 ] ) ;
}
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetLVDSRegs */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetLVDSRegs(unsigned short ModeNo, unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned short tempbx , tempax , tempcx , tempdx , push1 , push2 , modeflag ;
unsigned long temp , temp1 , temp2 , temp3 , push3 ;
struct XGI330_LCDDataDesStruct *LCDPtr = NULL ;
struct XGI330_LCDDataDesStruct2 *LCDPtr1 = NULL ;
if ( ModeNo > 0x13 )
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ;
else
modeflag = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ;
if ( !( pVBInfo->SetFlag & Win9xDOSMode ) )
{
if ( ( pVBInfo->IF_DEF_CH7017 == 0 ) || ( pVBInfo->VBInfo & ( SetCRT2ToLCD | SetCRT2ToLCDA ) ) )
{
if ( pVBInfo->IF_DEF_OEMUtil == 1 )
{
tempbx = 8 ;
LCDPtr = (struct XGI330_LCDDataDesStruct *)XGI_GetLcdPtr(tempbx, ModeNo, ModeIdIndex, RefreshRateTableIndex, pVBInfo);
}
if ( ( pVBInfo->IF_DEF_OEMUtil == 0 ) || ( LCDPtr == 0 ) )
{
tempbx = 3 ;
if ( pVBInfo->LCDInfo & EnableScalingLCD )
LCDPtr1 = (struct XGI330_LCDDataDesStruct2 *)XGI_GetLcdPtr(tempbx, ModeNo, ModeIdIndex, RefreshRateTableIndex, pVBInfo);
else
LCDPtr = (struct XGI330_LCDDataDesStruct *)XGI_GetLcdPtr(tempbx, ModeNo, ModeIdIndex, RefreshRateTableIndex, pVBInfo);
}
XGI_GetLCDSync( &tempax , &tempbx ,pVBInfo) ;
push1 = tempbx ;
push2 = tempax ;
/* GetLCDResInfo */
if ( ( pVBInfo->LCDResInfo == Panel1024x768 ) || ( pVBInfo->LCDResInfo == Panel1024x768x75 ) )
{
tempax = 1024 ;
tempbx = 768 ;
}
else if ( ( pVBInfo->LCDResInfo == Panel1280x1024 ) || ( pVBInfo->LCDResInfo == Panel1280x1024x75 ) )
{
tempax = 1280 ;
tempbx = 1024 ;
}
else if ( pVBInfo->LCDResInfo == Panel1400x1050 )
{
tempax = 1400 ;
tempbx = 1050 ;
}
else
{
tempax = 1600 ;
tempbx = 1200 ;
}
if ( pVBInfo->LCDInfo & SetLCDtoNonExpanding )
{
pVBInfo->HDE=tempax;
pVBInfo->VDE=tempbx;
pVBInfo->VGAHDE=tempax;
pVBInfo->VGAVDE=tempbx;
}
if ( ( pVBInfo->IF_DEF_ScaleLCD == 1 ) && ( pVBInfo->LCDInfo & EnableScalingLCD ) )
{
tempax=pVBInfo->HDE;
tempbx=pVBInfo->VDE;
}
tempax = pVBInfo->HT ;
if ( pVBInfo->LCDInfo & EnableScalingLCD )
tempbx = LCDPtr1->LCDHDES ;
else
tempbx = LCDPtr->LCDHDES ;
tempcx = pVBInfo->HDE ;
tempbx = tempbx & 0x0fff ;
tempcx += tempbx ;
if ( tempcx >= tempax )
tempcx -= tempax ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x1A , tempbx & 0x07 ) ;
tempcx = tempcx >> 3 ;
tempbx = tempbx >> 3 ;
XGINew_SetReg1(pVBInfo->Part1Port, 0x16, (unsigned short)(tempbx & 0xff));
XGINew_SetReg1(pVBInfo->Part1Port, 0x17, (unsigned short)(tempcx & 0xff));
tempax = pVBInfo->HT ;
if ( pVBInfo->LCDInfo & EnableScalingLCD )
tempbx = LCDPtr1->LCDHRS ;
else
tempbx = LCDPtr->LCDHRS ;
tempcx = push2 ;
if ( pVBInfo->LCDInfo & EnableScalingLCD )
tempcx = LCDPtr1->LCDHSync ;
tempcx += tempbx ;
if ( tempcx >= tempax )
tempcx -= tempax ;
tempax = tempbx & 0x07 ;
tempax = tempax >> 5 ;
tempcx = tempcx >> 3 ;
tempbx = tempbx >> 3 ;
tempcx &= 0x1f ;
tempax |= tempcx ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x15 , tempax ) ;
XGINew_SetReg1(pVBInfo->Part1Port, 0x14, (unsigned short)(tempbx & 0xff));
tempax = pVBInfo->VT ;
if ( pVBInfo->LCDInfo & EnableScalingLCD )
tempbx = LCDPtr1->LCDVDES ;
else
tempbx = LCDPtr->LCDVDES ;
tempcx = pVBInfo->VDE ;
tempbx = tempbx & 0x0fff ;
tempcx += tempbx ;
if ( tempcx >= tempax )
tempcx -= tempax ;
XGINew_SetReg1(pVBInfo->Part1Port, 0x1b, (unsigned short)(tempbx & 0xff));
XGINew_SetReg1(pVBInfo->Part1Port, 0x1c, (unsigned short)(tempcx & 0xff));
tempbx = ( tempbx >> 8 ) & 0x07 ;
tempcx = ( tempcx >> 8 ) & 0x07 ;
XGINew_SetReg1(pVBInfo->Part1Port, 0x1d, (unsigned short)((tempcx << 3) | tempbx));
tempax = pVBInfo->VT ;
if ( pVBInfo->LCDInfo & EnableScalingLCD )
tempbx = LCDPtr1->LCDVRS ;
else
tempbx = LCDPtr->LCDVRS ;
/* tempbx = tempbx >> 4 ; */
tempcx = push1 ;
if ( pVBInfo->LCDInfo & EnableScalingLCD )
tempcx = LCDPtr1->LCDVSync ;
tempcx += tempbx ;
if ( tempcx >= tempax )
tempcx -= tempax ;
XGINew_SetReg1(pVBInfo->Part1Port, 0x18, (unsigned short)(tempbx & 0xff));
XGINew_SetRegANDOR(pVBInfo->Part1Port, 0x19, ~0x0f, (unsigned short)(tempcx & 0x0f));
tempax = ( ( tempbx >> 8 ) & 0x07 ) << 3 ;
tempbx = pVBInfo->VGAVDE ;
if ( tempbx != pVBInfo->VDE )
tempax |= 0x40 ;
if ( pVBInfo->LCDInfo & EnableLVDSDDA )
tempax |= 0x40 ;
XGINew_SetRegANDOR( pVBInfo->Part1Port , 0x1a , 0x07 , tempax ) ;
tempcx = pVBInfo->VGAVT ;
tempbx = pVBInfo->VDE ;
tempax = pVBInfo->VGAVDE ;
tempcx -= tempax ;
temp = tempax ; /* 0430 ylshieh */
temp1 = ( temp << 18 ) / tempbx ;
tempdx = (unsigned short)((temp << 18) % tempbx);
if ( tempdx != 0 )
temp1 += 1 ;
temp2 = temp1 ;
push3 = temp2 ;
XGINew_SetReg1(pVBInfo->Part1Port, 0x37, (unsigned short)(temp2 & 0xff));
XGINew_SetReg1(pVBInfo->Part1Port, 0x36, (unsigned short)((temp2 >> 8) & 0xff));
tempbx = (unsigned short)(temp2 >> 16);
tempax = tempbx & 0x03 ;
tempbx = pVBInfo->VGAVDE ;
if ( tempbx == pVBInfo->VDE )
tempax |= 0x04 ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x35 , tempax ) ;
if ( pVBInfo->VBType & VB_XGI301C )
{
temp2 = push3 ;
XGINew_SetReg1(pVBInfo->Part4Port, 0x3c, (unsigned short)(temp2 & 0xff));
XGINew_SetReg1(pVBInfo->Part4Port, 0x3b, (unsigned short)((temp2 >> 8) & 0xff));
tempbx = (unsigned short)(temp2 >> 16);
XGINew_SetRegANDOR(pVBInfo->Part4Port, 0x3a, ~0xc0, (unsigned short)((tempbx & 0xff) << 6));
tempcx = pVBInfo->VGAVDE ;
if ( tempcx == pVBInfo->VDE )
XGINew_SetRegANDOR( pVBInfo->Part4Port , 0x30 , ~0x0c , 0x00 ) ;
else
XGINew_SetRegANDOR( pVBInfo->Part4Port , 0x30 , ~0x0c , 0x08 ) ;
}
tempcx = pVBInfo->VGAHDE ;
tempbx = pVBInfo->HDE ;
temp1 = tempcx << 16 ;
tempax = (unsigned short)(temp1 / tempbx);
if ( ( tempbx & 0xffff ) == ( tempcx & 0xffff ) )
tempax = 65535 ;
temp3 = tempax ;
temp1 = pVBInfo->VGAHDE << 16 ;
temp1 /= temp3 ;
temp3 = temp3 << 16 ;
temp1 -= 1 ;
temp3 = ( temp3 & 0xffff0000 ) + ( temp1 & 0xffff ) ;
tempax = (unsigned short)(temp3 & 0xff);
XGINew_SetReg1( pVBInfo->Part1Port , 0x1f , tempax ) ;
temp1 = pVBInfo->VGAVDE << 18 ;
temp1 = temp1 / push3 ;
tempbx = (unsigned short)(temp1 & 0xffff);
if ( pVBInfo->LCDResInfo == Panel1024x768 )
tempbx -= 1 ;
tempax = ( ( tempbx >> 8 ) & 0xff ) << 3 ;
tempax |= (unsigned short)((temp3 >> 8) & 0x07);
XGINew_SetReg1(pVBInfo->Part1Port, 0x20, (unsigned short)(tempax & 0xff));
XGINew_SetReg1(pVBInfo->Part1Port, 0x21, (unsigned short)(tempbx & 0xff));
temp3 = temp3 >> 16 ;
if ( modeflag & HalfDCLK )
temp3 = temp3 >> 1 ;
XGINew_SetReg1(pVBInfo->Part1Port , 0x22, (unsigned short)((temp3 >> 8) & 0xff));
XGINew_SetReg1(pVBInfo->Part1Port , 0x23, (unsigned short)(temp3 & 0xff));
}
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetCRT2ECLK */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetCRT2ECLK(unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex, struct vb_device_info *pVBInfo)
{
unsigned char di_0, di_1, tempal;
int i ;
tempal = XGI_GetVCLKPtr( RefreshRateTableIndex , ModeNo , ModeIdIndex, pVBInfo ) ;
XGI_GetVCLKLen( tempal , &di_0 , &di_1, pVBInfo ) ;
XGI_GetLCDVCLKPtr( &di_0 , &di_1, pVBInfo ) ;
for( i = 0 ; i < 4 ; i++ )
{
XGINew_SetRegANDOR(pVBInfo->P3d4, 0x31, ~0x30, (unsigned short)(0x10 * i));
if ( pVBInfo->IF_DEF_CH7007 == 1 )
{
XGINew_SetReg1( pVBInfo->P3c4 , 0x2b , di_0 ) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2c , di_1 ) ;
}
else if ( ( !( pVBInfo->VBInfo & SetCRT2ToLCDA ) ) && ( !( pVBInfo->VBInfo & SetInSlaveMode ) ) )
{
XGINew_SetReg1( pVBInfo->P3c4 , 0x2e , di_0 ) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2f , di_1 ) ;
}
else
{
XGINew_SetReg1( pVBInfo->P3c4 , 0x2b , di_0 ) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2c , di_1 ) ;
}
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_UpdateModeInfo */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_UpdateModeInfo(struct xgi_hw_device_info *HwDeviceExtension, struct vb_device_info *pVBInfo)
{
unsigned short tempcl ,
tempch ,
temp ,
tempbl ,
tempax ;
if ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{
tempcl = 0 ;
tempch = 0 ;
temp = XGINew_GetReg1( pVBInfo->P3c4 , 0x01 ) ;
if ( !( temp & 0x20 ) )
{
temp = XGINew_GetReg1( pVBInfo->P3d4 , 0x17 ) ;
if ( temp & 0x80 )
{
if ( ( HwDeviceExtension->jChipType >= XG20 ) || ( HwDeviceExtension->jChipType >= XG40 ) )
temp = XGINew_GetReg1( pVBInfo->P3d4 , 0x53 ) ;
else
temp = XGINew_GetReg1( pVBInfo->P3d4 , 0x63 ) ;
if ( !( temp & 0x40 ) )
tempcl |= ActiveCRT1 ;
}
}
temp = XGINew_GetReg1( pVBInfo->Part1Port , 0x2e ) ;
temp &= 0x0f ;
if ( !( temp == 0x08 ) )
{
tempax = XGINew_GetReg1( pVBInfo->Part1Port , 0x13 ) ; /* Check ChannelA by Part1_13 [2003/10/03] */
if ( tempax & 0x04 )
tempcl = tempcl | ActiveLCD ;
temp &= 0x05 ;
if ( !( tempcl & ActiveLCD ) )
if ( temp == 0x01 )
tempcl |= ActiveCRT2 ;
if ( temp == 0x04 )
tempcl |= ActiveLCD ;
if ( temp == 0x05 )
{
temp = XGINew_GetReg1( pVBInfo->Part2Port , 0x00 ) ;
if( !( temp & 0x08 ) )
tempch |= ActiveAVideo ;
if ( !( temp & 0x04 ) )
tempch |= ActiveSVideo ;
if ( temp & 0x02 )
tempch |= ActiveSCART ;
if ( pVBInfo->VBInfo & SetCRT2ToHiVisionTV )
{
if ( temp & 0x01 )
tempch |= ActiveHiTV ;
}
if ( pVBInfo->VBInfo & SetCRT2ToYPbPr )
{
temp = XGINew_GetReg1( pVBInfo->Part2Port , 0x4d ) ;
if ( temp & 0x10 )
tempch |= ActiveYPbPr ;
}
if ( tempch != 0 )
tempcl |= ActiveTV ;
}
}
temp = XGINew_GetReg1( pVBInfo->P3d4 , 0x3d ) ;
if ( tempcl & ActiveLCD )
{
if ( ( pVBInfo->SetFlag & ReserveTVOption ) )
{
if ( temp & ActiveTV )
tempcl |= ActiveTV ;
}
}
temp = tempcl ;
tempbl = ~ModeSwitchStatus ;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x3d , tempbl , temp ) ;
if ( !( pVBInfo->SetFlag & ReserveTVOption ) )
XGINew_SetReg1( pVBInfo->P3d4 , 0x3e , tempch ) ;
}
else
{
return ;
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetVGAType */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_GetVGAType(struct xgi_hw_device_info *HwDeviceExtension, struct vb_device_info *pVBInfo)
{
/*
if ( HwDeviceExtension->jChipType >= XG20 )
{
pVBInfo->Set_VGAType = XG20;
}
else if ( HwDeviceExtension->jChipType >= XG40 )
{
pVBInfo->Set_VGAType = VGA_XGI340 ;
}
*/
pVBInfo->Set_VGAType = HwDeviceExtension->jChipType;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetVBType */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_GetVBType(struct vb_device_info *pVBInfo)
{
unsigned short flag , tempbx , tempah ;
if ( pVBInfo->IF_DEF_CH7007 == 1 )
{
pVBInfo->VBType = VB_CH7007 ;
return;
}
if ( pVBInfo->IF_DEF_LVDS == 0 )
{
tempbx = VB_XGI302B ;
flag = XGINew_GetReg1( pVBInfo->Part4Port , 0x00 ) ;
if ( flag != 0x02 )
{
tempbx = VB_XGI301 ;
flag = XGINew_GetReg1( pVBInfo->Part4Port , 0x01 ) ;
if ( flag >= 0xB0 )
{
tempbx = VB_XGI301B ;
if ( flag >= 0xC0 )
{
tempbx = VB_XGI301C ;
if ( flag >= 0xD0 )
{
tempbx = VB_XGI301LV ;
if ( flag >= 0xE0 )
{
tempbx = VB_XGI302LV ;
tempah = XGINew_GetReg1( pVBInfo->Part4Port , 0x39 ) ;
if ( tempah != 0xFF )
tempbx = VB_XGI301C ;
}
}
}
if ( tempbx & ( VB_XGI301B | VB_XGI302B ) )
{
flag = XGINew_GetReg1( pVBInfo->Part4Port , 0x23 ) ;
if ( !( flag & 0x02 ) )
tempbx = tempbx | VB_NoLCD ;
}
}
}
pVBInfo->VBType = tempbx ;
}
/*
else if ( pVBInfo->IF_DEF_CH7017 == 1 )
pVBInfo->VBType = VB_CH7017 ;
else //LVDS
pVBInfo->VBType = VB_LVDS_NS ;
*/
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetVBInfo */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_GetVBInfo(unsigned short ModeNo, unsigned short ModeIdIndex, struct xgi_hw_device_info *HwDeviceExtension, struct vb_device_info *pVBInfo)
{
unsigned short tempax ,
push ,
tempbx ,
temp ,
modeflag ;
if ( ModeNo <= 0x13 )
{
modeflag = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ;
}
else
{
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ;
}
pVBInfo->SetFlag = 0 ;
pVBInfo->ModeType = modeflag & ModeInfoFlag ;
tempbx = 0 ;
if ( pVBInfo->VBType & 0xFFFF )
{
temp = XGINew_GetReg1( pVBInfo->P3d4 , 0x30 ) ; /* Check Display Device */
tempbx = tempbx | temp ;
temp = XGINew_GetReg1( pVBInfo->P3d4 , 0x31 ) ;
push = temp ;
push = push << 8 ;
tempax = temp << 8 ;
tempbx = tempbx | tempax ;
temp = ( SetCRT2ToDualEdge | SetCRT2ToYPbPr | SetCRT2ToLCDA | SetInSlaveMode | DisableCRT2Display ) ;
temp = 0xFFFF ^ temp ;
tempbx &= temp ;
temp = XGINew_GetReg1( pVBInfo->P3d4 , 0x38 ) ;
if ( pVBInfo->IF_DEF_LCDA == 1 )
{
if ( ( pVBInfo->Set_VGAType >= XG20 ) || ( pVBInfo->Set_VGAType >= XG40 ))
{
if ( pVBInfo->IF_DEF_LVDS == 0 )
{
/* if ( ( pVBInfo->VBType & VB_XGI302B ) || ( pVBInfo->VBType & VB_XGI301LV ) || ( pVBInfo->VBType & VB_XGI302LV ) || ( pVBInfo->VBType & VB_XGI301C ) ) */
if ( pVBInfo->VBType & ( VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{
if ( temp & EnableDualEdge )
{
tempbx |= SetCRT2ToDualEdge ;
if ( temp & SetToLCDA )
tempbx |= SetCRT2ToLCDA ;
}
}
}
else if ( pVBInfo->IF_DEF_CH7017 == 1 )
{
if ( pVBInfo->VBType & VB_CH7017 )
{
if ( temp & EnableDualEdge )
{
tempbx |= SetCRT2ToDualEdge ;
if ( temp & SetToLCDA )
tempbx |= SetCRT2ToLCDA ;
}
}
}
}
}
if ( pVBInfo->IF_DEF_YPbPr == 1 )
{
if ( ( ( pVBInfo->IF_DEF_LVDS == 0 ) && ( ( pVBInfo->VBType & VB_XGI301LV ) || ( pVBInfo->VBType & VB_XGI302LV ) || ( pVBInfo->VBType & VB_XGI301C ) ) )
|| ( ( pVBInfo->IF_DEF_CH7017 == 1 ) && ( pVBInfo->VBType&VB_CH7017 ) ) || ( (pVBInfo->IF_DEF_CH7007 == 1) && (pVBInfo->VBType&VB_CH7007) ) ) /* [Billy] 07/05/04 */
{
if ( temp & SetYPbPr ) /* temp = CR38 */
{
if ( pVBInfo->IF_DEF_HiVision == 1 )
{
temp = XGINew_GetReg1( pVBInfo->P3d4 , 0x35 ) ; /* shampoo add for new scratch */
temp &= YPbPrMode ;
tempbx |= SetCRT2ToHiVisionTV ;
if ( temp != YPbPrMode1080i ) {
tempbx &= ( ~SetCRT2ToHiVisionTV ) ;
tempbx |= SetCRT2ToYPbPr ; }
}
/* tempbx |= SetCRT2ToYPbPr ; */
}
}
}
tempax = push ; /* restore CR31 */
if ( pVBInfo->IF_DEF_LVDS == 0 )
{
if ( pVBInfo->IF_DEF_YPbPr == 1 )
{
if ( pVBInfo->IF_DEF_HiVision == 1 )
temp = 0x09FC ;
else
temp = 0x097C ;
}
else
{
if ( pVBInfo->IF_DEF_HiVision == 1 )
temp = 0x01FC ;
else
temp = 0x017C ;
}
}
else /* 3nd party chip */
{
if ( pVBInfo->IF_DEF_CH7017 == 1 )
temp = ( SetCRT2ToTV | SetCRT2ToLCD | SetCRT2ToLCDA ) ;
else if ( pVBInfo->IF_DEF_CH7007 == 1 ) /* [Billy] 07/05/03 */
{
temp = SetCRT2ToTV ;
}
else
temp = SetCRT2ToLCD ;
}
if ( !( tempbx & temp ) )
{
tempax |= DisableCRT2Display ;
tempbx = 0 ;
}
if ( pVBInfo->IF_DEF_LCDA == 1 ) /* Select Display Device */
{
if ( !( pVBInfo->VBType & VB_NoLCD ) )
{
if ( tempbx & SetCRT2ToLCDA )
{
if ( tempbx & SetSimuScanMode )
tempbx &= ( ~( SetCRT2ToLCD | SetCRT2ToRAMDAC | SwitchToCRT2 ) ) ;
else
tempbx &= ( ~( SetCRT2ToLCD | SetCRT2ToRAMDAC | SetCRT2ToTV | SwitchToCRT2 ) ) ;
}
}
}
/* shampoo add */
if ( !( tempbx & ( SwitchToCRT2 | SetSimuScanMode ) ) ) /* for driver abnormal */
{
if ( pVBInfo->IF_DEF_CRT2Monitor == 1 )
{
if ( tempbx & SetCRT2ToRAMDAC )
{
tempbx &= ( 0xFF00 | SetCRT2ToRAMDAC | SwitchToCRT2 | SetSimuScanMode ) ;
tempbx &= ( 0x00FF | ( ~SetCRT2ToYPbPr ) ) ;
}
}
else
tempbx &= ( ~( SetCRT2ToRAMDAC | SetCRT2ToLCD | SetCRT2ToTV ) ) ;
}
if ( !( pVBInfo->VBType & VB_NoLCD ) )
{
if ( tempbx & SetCRT2ToLCD )
{
tempbx &= ( 0xFF00 | SetCRT2ToLCD | SwitchToCRT2 | SetSimuScanMode ) ;
tempbx &= ( 0x00FF | ( ~SetCRT2ToYPbPr ) ) ;
}
}
if ( tempbx & SetCRT2ToSCART )
{
tempbx &= ( 0xFF00 | SetCRT2ToSCART | SwitchToCRT2 | SetSimuScanMode ) ;
tempbx &= ( 0x00FF | ( ~SetCRT2ToYPbPr ) ) ;
}
if ( pVBInfo->IF_DEF_YPbPr == 1 )
{
if ( tempbx & SetCRT2ToYPbPr )
tempbx &= ( 0xFF00 | SwitchToCRT2 | SetSimuScanMode ) ;
}
if ( pVBInfo->IF_DEF_HiVision == 1 )
{
if ( tempbx & SetCRT2ToHiVisionTV )
tempbx &= ( 0xFF00 | SetCRT2ToHiVisionTV | SwitchToCRT2 | SetSimuScanMode ) ;
}
if ( tempax & DisableCRT2Display ) /* Set Display Device Info */
{
if ( !( tempbx & ( SwitchToCRT2 | SetSimuScanMode ) ) )
tempbx = DisableCRT2Display ;
}
if ( !( tempbx & DisableCRT2Display ) )
{
if ( ( !( tempbx & DriverMode ) ) || ( !( modeflag & CRT2Mode ) ) )
{
if ( pVBInfo->IF_DEF_LCDA == 1 )
{
if ( !( tempbx & SetCRT2ToLCDA ) )
tempbx |= ( SetInSlaveMode | SetSimuScanMode ) ;
}
if ( pVBInfo->IF_DEF_VideoCapture == 1 )
{
if ( ( ( HwDeviceExtension->jChipType == XG40 ) && ( pVBInfo->Set_VGAType == XG40 ) )
|| ( ( HwDeviceExtension->jChipType == XG41 ) && ( pVBInfo->Set_VGAType == XG41 ) )
|| ( ( HwDeviceExtension->jChipType == XG42 ) && ( pVBInfo->Set_VGAType == XG42 ) )
|| ( ( HwDeviceExtension->jChipType == XG45 ) && ( pVBInfo->Set_VGAType == XG45 ) ) )
{
if ( ModeNo <= 13 )
{
if ( !( tempbx & SetCRT2ToRAMDAC ) ) /*CRT2 not need to support*/
{
tempbx &= ( 0x00FF | ( ~SetInSlaveMode ) ) ;
pVBInfo->SetFlag |= EnableVCMode ;
}
}
}
}
}
/*LCD+TV can't support in slave mode (Force LCDA+TV->LCDB)*/
if ( ( tempbx & SetInSlaveMode ) && ( tempbx & SetCRT2ToLCDA ) )
{
tempbx ^= ( SetCRT2ToLCD | SetCRT2ToLCDA | SetCRT2ToDualEdge ) ;
pVBInfo->SetFlag |= ReserveTVOption ;
}
}
}
pVBInfo->VBInfo = tempbx ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetTVInfo */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_GetTVInfo(unsigned short ModeNo, unsigned short ModeIdIndex, struct vb_device_info *pVBInfo)
{
unsigned short temp ,
tempbx = 0 ,
resinfo = 0 ,
modeflag ,
index1 ;
tempbx = 0 ;
resinfo = 0 ;
if ( pVBInfo->VBInfo & SetCRT2ToTV )
{
if ( ModeNo <= 0x13 )
{
modeflag = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ; /* si+St_ModeFlag */
resinfo = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ResInfo ; /* si+St_ResInfo */
}
else
{
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ;
resinfo = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_RESINFO ; /* si+Ext_ResInfo */
}
if ( pVBInfo->VBInfo & SetCRT2ToTV )
{
temp = XGINew_GetReg1( pVBInfo->P3d4 , 0x35 ) ;
tempbx = temp;
if ( tempbx & SetPALTV )
{
tempbx &= ( SetCHTVOverScan | SetPALMTV | SetPALNTV | SetPALTV ) ;
if ( tempbx & SetPALMTV )
tempbx &= ~SetPALTV ; /* set to NTSC if PAL-M */
}
else
tempbx &= ( SetCHTVOverScan | SetNTSCJ | SetPALTV ) ;
/*
if ( pVBInfo->IF_DEF_LVDS == 0 )
{
index1 = XGINew_GetReg1( pVBInfo->P3d4 , 0x38 ) ; //PAL-M/PAL-N Info
temp2 = ( index1 & 0xC0 ) >> 5 ; //00:PAL, 01:PAL-M, 10:PAL-N
tempbx |= temp2 ;
if ( temp2 & 0x02 ) //PAL-M
tempbx &= ( ~SetPALTV ) ;
}
*/
}
if ( pVBInfo->IF_DEF_CH7017 == 1 )
{
tempbx = XGINew_GetReg1( pVBInfo->P3d4 , 0x35 ) ;
if ( tempbx & TVOverScan )
tempbx |= SetCHTVOverScan ;
}
if ( pVBInfo->IF_DEF_CH7007 == 1 ) /* [Billy] 07/05/04 */
{
tempbx = XGINew_GetReg1( pVBInfo->P3d4 , 0x35 ) ;
if ( tempbx & TVOverScan )
{
tempbx |= SetCHTVOverScan ;
}
}
if ( pVBInfo->IF_DEF_LVDS == 0 )
{
if ( pVBInfo->VBInfo & SetCRT2ToSCART )
tempbx |= SetPALTV ;
}
if ( pVBInfo->IF_DEF_YPbPr == 1 )
{
if ( pVBInfo->VBInfo & SetCRT2ToYPbPr )
{
index1 = XGINew_GetReg1( pVBInfo->P3d4 , 0x35 ) ;
index1 &= YPbPrMode ;
if ( index1 == YPbPrMode525i )
tempbx |= SetYPbPrMode525i ;
if ( index1 == YPbPrMode525p )
tempbx = tempbx | SetYPbPrMode525p;
if ( index1 == YPbPrMode750p)
tempbx = tempbx | SetYPbPrMode750p;
}
}
if ( pVBInfo->IF_DEF_HiVision == 1 )
{
if ( pVBInfo->VBInfo & SetCRT2ToHiVisionTV )
{
tempbx = tempbx | SetYPbPrMode1080i | SetPALTV ;
}
}
if ( pVBInfo->IF_DEF_LVDS == 0 )
{ /* shampoo */
if ( ( pVBInfo->VBInfo & SetInSlaveMode ) && ( !( pVBInfo->VBInfo & SetNotSimuMode ) ) )
tempbx |= TVSimuMode ;
if ( !( tempbx & SetPALTV ) && ( modeflag > 13 ) && ( resinfo == 8 ) ) /* NTSC 1024x768, */
tempbx |= NTSC1024x768 ;
tempbx |= RPLLDIV2XO ;
if ( pVBInfo->VBInfo & SetCRT2ToHiVisionTV )
{
if ( pVBInfo->VBInfo & SetInSlaveMode )
tempbx &=( ~RPLLDIV2XO ) ;
}
else
{
if ( tempbx & ( SetYPbPrMode525p | SetYPbPrMode750p ) )
tempbx &= ( ~RPLLDIV2XO ) ;
else if ( !( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) ) )
{
if ( tempbx & TVSimuMode )
tempbx &= ( ~RPLLDIV2XO ) ;
}
}
}
}
pVBInfo->TVInfo = tempbx ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetLCDInfo */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
unsigned char XGI_GetLCDInfo(unsigned short ModeNo, unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned short temp ,
tempax ,
tempbx ,
modeflag ,
resinfo = 0 ,
LCDIdIndex ;
pVBInfo->LCDResInfo = 0 ;
pVBInfo->LCDTypeInfo = 0 ;
pVBInfo->LCDInfo = 0 ;
if ( ModeNo <= 0x13 )
{
modeflag = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ; /* si+St_ModeFlag // */
}
else
{
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ;
resinfo = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_RESINFO ; /* si+Ext_ResInfo// */
}
temp = XGINew_GetReg1( pVBInfo->P3d4 , 0x36 ) ; /* Get LCD Res.Info */
tempbx = temp & 0x0F ;
if ( tempbx == 0 )
tempbx = Panel1024x768 ; /* default */
/* LCD75 [2003/8/22] Vicent */
if ( ( tempbx == Panel1024x768 ) || ( tempbx == Panel1280x1024 ) )
{
if ( pVBInfo->VBInfo & DriverMode )
{
tempax = XGINew_GetReg1( pVBInfo->P3d4 , 0x33 ) ;
if ( pVBInfo->VBInfo & SetCRT2ToLCDA )
tempax &= 0x0F ;
else
tempax = tempax >> 4 ;
if ( ( resinfo == 6 ) || ( resinfo == 9 ) )
{
if ( tempax >= 3 )
tempbx |= PanelRef75Hz ;
}
else if ( ( resinfo == 7 ) || ( resinfo == 8 ) )
{
if ( tempax >= 4 )
tempbx |= PanelRef75Hz ;
}
}
}
pVBInfo->LCDResInfo = tempbx ;
/* End of LCD75 */
if( pVBInfo->IF_DEF_OEMUtil == 1 )
{
pVBInfo->LCDTypeInfo = ( temp & 0xf0 ) >> 4 ;
}
if ( !( pVBInfo->VBInfo & ( SetCRT2ToLCD | SetCRT2ToLCDA ) ) )
{
return 0;
}
tempbx = 0 ;
temp = XGINew_GetReg1( pVBInfo->P3d4 , 0x37 ) ;
temp &= ( ScalingLCD | LCDNonExpanding | LCDSyncBit | SetPWDEnable ) ;
if ( ( pVBInfo->IF_DEF_ScaleLCD == 1 ) && ( temp & LCDNonExpanding ) )
temp &= ~EnableScalingLCD ;
tempbx |= temp ;
LCDIdIndex = XGI_GetLCDCapPtr1(pVBInfo) ;
tempax = pVBInfo->LCDCapList[ LCDIdIndex ].LCD_Capability ;
if ( pVBInfo->IF_DEF_LVDS == 0 ) /* shampoo */
{
if ( ( ( pVBInfo->VBType & VB_XGI302LV ) || ( pVBInfo->VBType & VB_XGI301C ) ) && ( tempax & LCDDualLink ) )
{
tempbx |= SetLCDDualLink ;
}
}
if ( pVBInfo->IF_DEF_CH7017 == 1 )
{
if ( tempax & LCDDualLink )
{
tempbx |= SetLCDDualLink ;
}
}
if ( pVBInfo->IF_DEF_LVDS == 0 )
{
if ( ( pVBInfo->LCDResInfo == Panel1400x1050 ) && ( pVBInfo->VBInfo & SetCRT2ToLCD ) && ( ModeNo > 0x13 ) && ( resinfo == 9 ) && ( !( tempbx & EnableScalingLCD ) ) )
tempbx |= SetLCDtoNonExpanding ; /* set to center in 1280x1024 LCDB for Panel1400x1050 */
}
/*
if ( tempax & LCDBToA )
{
tempbx |= SetLCDBToA ;
}
*/
if ( pVBInfo->IF_DEF_ExpLink == 1 )
{
if ( modeflag & HalfDCLK )
{
/* if ( !( pVBInfo->LCDInfo&LCDNonExpanding ) ) */
if ( !( tempbx & SetLCDtoNonExpanding ) )
{
tempbx |= EnableLVDSDDA ;
}
else
{
if ( ModeNo > 0x13 )
{
if ( pVBInfo->LCDResInfo == Panel1024x768 )
{
if ( resinfo == 4 )
{ /* 512x384 */
tempbx |= EnableLVDSDDA ;
}
}
}
}
}
}
if ( pVBInfo->VBInfo & SetInSlaveMode )
{
if ( pVBInfo->VBInfo & SetNotSimuMode )
{
tempbx |= LCDVESATiming ;
}
}
else
{
tempbx |= LCDVESATiming ;
}
pVBInfo->LCDInfo = tempbx ;
if ( pVBInfo->IF_DEF_PWD == 1 )
{
if ( pVBInfo->LCDInfo & SetPWDEnable )
{
if ( ( pVBInfo->VBType & VB_XGI302LV ) || ( pVBInfo->VBType & VB_XGI301C ) )
{
if ( !( tempax & PWDEnable ) )
{
pVBInfo->LCDInfo &= ~SetPWDEnable ;
}
}
}
}
if ( pVBInfo->IF_DEF_LVDS == 0 )
{
if ( tempax & ( LockLCDBToA | StLCDBToA ) )
{
if ( pVBInfo->VBInfo & SetInSlaveMode )
{
if ( !( tempax & LockLCDBToA ) )
{
if ( ModeNo <= 0x13 )
{
pVBInfo->VBInfo &= ~( SetSimuScanMode | SetInSlaveMode | SetCRT2ToLCD ) ;
pVBInfo->VBInfo |= SetCRT2ToLCDA | SetCRT2ToDualEdge ;
}
}
}
}
}
/*
if ( pVBInfo->IF_DEF_LVDS == 0 )
{
if ( tempax & ( LockLCDBToA | StLCDBToA ) )
{
if ( pVBInfo->VBInfo & SetInSlaveMode )
{
if ( !( ( !( tempax & LockLCDBToA ) ) && ( ModeNo > 0x13 ) ) )
{
pVBInfo->VBInfo&=~(SetSimuScanMode|SetInSlaveMode|SetCRT2ToLCD);
pVBInfo->VBInfo|=SetCRT2ToLCDA|SetCRT2ToDualEdge;
}
}
}
}
*/
return( 1 ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SearchModeID */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
unsigned char XGI_SearchModeID(unsigned short ModeNo,
unsigned short *ModeIdIndex,
struct vb_device_info *pVBInfo)
{
#ifdef LINUX /* chiawen for linux solution */
if ( ModeNo <= 5 )
ModeNo |= 1 ;
if ( ModeNo <= 0x13 )
{
/* for (*ModeIdIndex=0;*ModeIdIndex<sizeof(pVBInfo->SModeIDTable)/sizeof(struct XGI_StStruct);(*ModeIdIndex)++) */
for( *ModeIdIndex = 0 ; ; ( *ModeIdIndex )++ )
{
if (pVBInfo->SModeIDTable[*ModeIdIndex].St_ModeID == ModeNo)
break;
if (pVBInfo->SModeIDTable[*ModeIdIndex].St_ModeID == 0xFF)
return 0;
}
if ( ModeNo == 0x07 )
( *ModeIdIndex )++ ; /* 400 lines */
if ( ModeNo <= 3 )
( *ModeIdIndex ) += 2 ; /* 400 lines */
/* else 350 lines */
}
else
{
/* for (*ModeIdIndex=0;*ModeIdIndex<sizeof(pVBInfo->EModeIDTable)/sizeof(struct XGI_ExtStruct);(*ModeIdIndex)++) */
for( *ModeIdIndex = 0 ; ; ( *ModeIdIndex )++ )
{
if (pVBInfo->EModeIDTable[*ModeIdIndex].Ext_ModeID == ModeNo)
break;
if (pVBInfo->EModeIDTable[*ModeIdIndex].Ext_ModeID == 0xFF)
return 0;
}
}
#endif
return 1;
}
/* win2000 MM adapter not support standard mode! */
/* --------------------------------------------------------------------- */
/* Function : */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
unsigned char XGINew_CheckMemorySize(struct xgi_hw_device_info *HwDeviceExtension,
unsigned short ModeNo,
unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned short memorysize ,
modeflag ,
temp ,
temp1 ,
tmp ;
/* if ( ( HwDeviceExtension->jChipType == XGI_650 ) ||
( HwDeviceExtension->jChipType == XGI_650M ) )
{
return 1;
} */
if ( ModeNo <= 0x13 )
{
modeflag = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ;
}
else {
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ;
}
/* ModeType = modeflag&ModeInfoFlag ; // Get mode type */
memorysize = modeflag & MemoryInfoFlag ;
memorysize = memorysize > MemorySizeShift ;
memorysize++ ; /* Get memory size */
temp = XGINew_GetReg1( pVBInfo->P3c4 , 0x14 ) ; /* Get DRAM Size */
tmp = temp ;
if ( HwDeviceExtension->jChipType == XG40 )
{
temp = 1 << ( ( temp & 0x0F0 ) >> 4 ) ; /* memory size per channel SR14[7:4] */
if ( ( tmp & 0x0c ) == 0x0C ) /* Qual channels */
{
temp <<= 2 ;
}
else if ( ( tmp & 0x0c ) == 0x08 ) /* Dual channels */
{
temp <<= 1 ;
}
}
else if ( HwDeviceExtension->jChipType == XG42 )
{
temp = 1 << ( ( temp & 0x0F0 ) >> 4 ) ; /* memory size per channel SR14[7:4] */
if ( ( tmp & 0x04 ) == 0x04 ) /* Dual channels */
{
temp <<= 1 ;
}
}
else if ( HwDeviceExtension->jChipType == XG45 )
{
temp = 1 << ( ( temp & 0x0F0 ) >> 4 ) ; /* memory size per channel SR14[7:4] */
if ( ( tmp & 0x0c ) == 0x0C ) /* Qual channels */
{
temp <<= 2 ;
}
else if ( ( tmp & 0x0c ) == 0x08 ) /* triple channels */
{
temp1 = temp ;
temp <<= 1 ;
temp += temp1 ;
}
else if ( ( tmp & 0x0c ) == 0x04 ) /* Dual channels */
{
temp <<= 1 ;
}
}
if (temp < memorysize)
return 0;
else
return 1;
}
/* --------------------------------------------------------------------- */
/* Function : XGINew_IsLowResolution */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
/*void XGINew_IsLowResolution(unsigned short ModeNo, unsigned short ModeIdIndex, unsigned char XGINew_CheckMemorySize(struct xgi_hw_device_info *HwDeviceExtension, unsigned short ModeNo, unsigned short ModeIdIndex, struct vb_device_info *pVBInfo)
{
unsigned short data ;
unsigned short ModeFlag ;
data = XGINew_GetReg1( pVBInfo->P3c4 , 0x0F ) ;
data &= 0x7F ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x0F , data ) ;
if ( ModeNo > 0x13 )
{
ModeFlag = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ;
if ( ( ModeFlag & HalfDCLK ) && ( ModeFlag & DoubleScanMode ) )
{
data = XGINew_GetReg1( pVBInfo->P3c4 , 0x0F ) ;
data |= 0x80 ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x0F , data ) ;
data = XGINew_GetReg1( pVBInfo->P3c4 , 0x01 ) ;
data &= 0xF7 ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x01 , data ) ;
}
}
}
*/
/* --------------------------------------------------------------------- */
/* Function : XGI_DisplayOn */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_DisplayOn(struct xgi_hw_device_info *pXGIHWDE, struct vb_device_info *pVBInfo)
{
XGINew_SetRegANDOR(pVBInfo->P3c4,0x01,0xDF,0x00);
if ( pXGIHWDE->jChipType == XG21 )
{
if ( pVBInfo->IF_DEF_LVDS == 1 )
{
if (!(XGI_XG21GetPSCValue( pVBInfo )&0x1))
{
XGI_XG21BLSignalVDD( 0x01 , 0x01, pVBInfo ) ; /* LVDS VDD on */
XGI_XG21SetPanelDelay( 2,pVBInfo ) ;
}
if (!(XGI_XG21GetPSCValue( pVBInfo )&0x20))
{
XGI_XG21BLSignalVDD( 0x20 , 0x20, pVBInfo ) ; /* LVDS signal on */
}
XGI_XG21SetPanelDelay( 3,pVBInfo ) ;
XGI_XG21BLSignalVDD( 0x02 , 0x02, pVBInfo ) ; /* LVDS backlight on */
}
else
{
XGI_XG21BLSignalVDD( 0x20 , 0x20, pVBInfo ) ; /* DVO/DVI signal on */
}
}
if (pVBInfo->IF_DEF_CH7007 == 1) /* [Billy] 07/05/23 For CH7007 */
{
}
if ( pXGIHWDE->jChipType == XG27 )
{
if ( pVBInfo->IF_DEF_LVDS == 1 )
{
if (!(XGI_XG27GetPSCValue( pVBInfo )&0x1))
{
XGI_XG27BLSignalVDD( 0x01 , 0x01, pVBInfo ) ; /* LVDS VDD on */
XGI_XG21SetPanelDelay( 2,pVBInfo ) ;
}
if (!(XGI_XG27GetPSCValue( pVBInfo )&0x20))
{
XGI_XG27BLSignalVDD( 0x20 , 0x20, pVBInfo ) ; /* LVDS signal on */
}
XGI_XG21SetPanelDelay( 3,pVBInfo ) ;
XGI_XG27BLSignalVDD( 0x02 , 0x02, pVBInfo ) ; /* LVDS backlight on */
}
else
{
XGI_XG27BLSignalVDD( 0x20 , 0x20, pVBInfo ) ; /* DVO/DVI signal on */
}
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_DisplayOff */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_DisplayOff(struct xgi_hw_device_info *pXGIHWDE, struct vb_device_info *pVBInfo)
{
if ( pXGIHWDE->jChipType == XG21 )
{
if ( pVBInfo->IF_DEF_LVDS == 1 )
{
XGI_XG21BLSignalVDD( 0x02 , 0x00, pVBInfo ) ; /* LVDS backlight off */
XGI_XG21SetPanelDelay( 3,pVBInfo ) ;
}
else
{
XGI_XG21BLSignalVDD( 0x20 , 0x00, pVBInfo ) ; /* DVO/DVI signal off */
}
}
if (pVBInfo->IF_DEF_CH7007 == 1) /*[Billy] 07/05/23 For CH7007 */
{
/* if( IsCH7007TVMode( pVBInfo ) == 0 ) */
{
}
}
if ( pXGIHWDE->jChipType == XG27 )
{
if ((XGI_XG27GetPSCValue( pVBInfo )&0x2))
{
XGI_XG27BLSignalVDD( 0x02 , 0x00, pVBInfo ) ; /* LVDS backlight off */
XGI_XG21SetPanelDelay( 3,pVBInfo ) ;
}
if ( pVBInfo->IF_DEF_LVDS == 0 )
{
XGI_XG27BLSignalVDD( 0x20 , 0x00, pVBInfo ) ; /* DVO/DVI signal off */
}
}
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x01 , 0xDF , 0x20 ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_WaitDisply */
/* Input : */
/* Output : */
/* Description : chiawen for sensecrt1 */
/* --------------------------------------------------------------------- */
void XGI_WaitDisply(struct vb_device_info *pVBInfo)
{
while( ( XGINew_GetReg2( pVBInfo->P3da ) & 0x01 ) )
break ;
while( !( XGINew_GetReg2( pVBInfo->P3da ) & 0x01 ) )
break ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SenseCRT1 */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SenseCRT1(struct vb_device_info *pVBInfo)
{
unsigned char CRTCData[17] = {
0x5F , 0x4F , 0x50 , 0x82 , 0x55 , 0x81 ,
0x0B , 0x3E , 0xE9 , 0x0B , 0xDF , 0xE7 ,
0x04 , 0x00 , 0x00 , 0x05 , 0x00 };
unsigned char SR01 = 0, SR1F = 0, SR07 = 0, SR06 = 0;
unsigned char CR17, CR63, SR31;
unsigned short temp ;
unsigned char DAC_TEST_PARMS[3] = { 0x0F, 0x0F, 0x0F } ;
int i ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x05 , 0x86 ) ;
/* [2004/05/06] Vicent to fix XG42 single LCD sense to CRT+LCD */
XGINew_SetReg1( pVBInfo->P3d4 , 0x57 , 0x4A ) ;
XGINew_SetReg1(pVBInfo->P3d4, 0x53, (unsigned char)(XGINew_GetReg1(pVBInfo->P3d4, 0x53) | 0x02));
SR31 = (unsigned char)XGINew_GetReg1(pVBInfo->P3c4, 0x31);
CR63 = (unsigned char)XGINew_GetReg1(pVBInfo->P3d4, 0x63);
SR01 = (unsigned char)XGINew_GetReg1(pVBInfo->P3c4, 0x01);
XGINew_SetReg1(pVBInfo->P3c4, 0x01, (unsigned char)(SR01 & 0xDF));
XGINew_SetReg1(pVBInfo->P3d4, 0x63, (unsigned char)(CR63 & 0xBF));
CR17 = (unsigned char)XGINew_GetReg1(pVBInfo->P3d4, 0x17);
XGINew_SetReg1(pVBInfo->P3d4, 0x17, (unsigned char)(CR17 | 0x80)) ;
SR1F = (unsigned char)XGINew_GetReg1(pVBInfo->P3c4, 0x1F);
XGINew_SetReg1(pVBInfo->P3c4, 0x1F, (unsigned char)(SR1F | 0x04));
SR07 = (unsigned char)XGINew_GetReg1(pVBInfo->P3c4, 0x07);
XGINew_SetReg1(pVBInfo->P3c4, 0x07, (unsigned char)(SR07 & 0xFB));
SR06 = (unsigned char)XGINew_GetReg1(pVBInfo->P3c4, 0x06);
XGINew_SetReg1(pVBInfo->P3c4, 0x06, (unsigned char)(SR06 & 0xC3));
XGINew_SetReg1( pVBInfo->P3d4 , 0x11 , 0x00 ) ;
for( i = 0 ; i < 8 ; i++ )
XGINew_SetReg1(pVBInfo->P3d4, (unsigned short)i, CRTCData[i]);
for( i = 8 ; i < 11 ; i++ )
XGINew_SetReg1(pVBInfo->P3d4, (unsigned short)(i + 8), CRTCData[i]);
for( i = 11 ; i < 13 ; i++ )
XGINew_SetReg1(pVBInfo->P3d4, (unsigned short)(i + 4), CRTCData[i]);
for( i = 13 ; i < 16 ; i++ )
XGINew_SetReg1(pVBInfo->P3c4, (unsigned short)(i - 3), CRTCData[i]);
XGINew_SetReg1(pVBInfo->P3c4, 0x0E, (unsigned char)(CRTCData[16] & 0xE0));
XGINew_SetReg1( pVBInfo->P3c4 , 0x31 , 0x00 ) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2B , 0x1B ) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2C , 0xE1 ) ;
XGINew_SetReg3( pVBInfo->P3c8 , 0x00 ) ;
for( i = 0 ; i < 256 ; i++ )
{
XGINew_SetReg3((pVBInfo->P3c8 + 1), (unsigned char)DAC_TEST_PARMS[0]);
XGINew_SetReg3((pVBInfo->P3c8 + 1), (unsigned char)DAC_TEST_PARMS[1]);
XGINew_SetReg3((pVBInfo->P3c8 + 1), (unsigned char)DAC_TEST_PARMS[2]);
}
XGI_VBLongWait( pVBInfo ) ;
XGI_VBLongWait( pVBInfo ) ;
XGI_VBLongWait( pVBInfo ) ;
XGINew_LCD_Wait_Time( 0x01 , pVBInfo ) ;
XGI_WaitDisply( pVBInfo ) ;
temp = XGINew_GetReg2( pVBInfo->P3c2 ) ;
if( temp & 0x10 )
{
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x32 , 0xDF , 0x20 ) ;
}
else
{
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x32 , 0xDF , 0x00 ) ;
}
/* alan, avoid display something, set BLACK DAC if not restore DAC */
XGINew_SetReg3( pVBInfo->P3c8 , 0x00 ) ;
for( i = 0 ; i < 256 ; i++ )
{
XGINew_SetReg3( ( pVBInfo->P3c8 + 1 ) , 0 ) ;
XGINew_SetReg3( ( pVBInfo->P3c8 + 1 ) , 0 ) ;
XGINew_SetReg3( ( pVBInfo->P3c8 + 1 ) , 0 ) ;
}
XGINew_SetReg1( pVBInfo->P3c4 , 0x01 , SR01 ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x63 , CR63 ) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x31 , SR31 ) ;
/* [2004/05/11] Vicent */
XGINew_SetReg1(pVBInfo->P3d4, 0x53,
(unsigned char)(XGINew_GetReg1(pVBInfo->P3d4, 0x53) & 0xFD));
XGINew_SetReg1(pVBInfo->P3c4, 0x1F, (unsigned char)SR1F);
}
/* --------------------------------------------------------------------- */
/* Function : XGI_WaitDisplay */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_WaitDisplay(struct vb_device_info *pVBInfo)
{
while( !( XGINew_GetReg2( pVBInfo->P3da ) & 0x01 ) ) ;
while( XGINew_GetReg2( pVBInfo->P3da ) & 0x01 ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetCRT2Group301 */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
unsigned char XGI_SetCRT2Group301(unsigned short ModeNo,
struct xgi_hw_device_info *HwDeviceExtension,
struct vb_device_info *pVBInfo)
{
unsigned short tempbx ,
ModeIdIndex ,
RefreshRateTableIndex ;
tempbx=pVBInfo->VBInfo ;
pVBInfo->SetFlag |= ProgrammingCRT2 ;
XGI_SearchModeID( ModeNo , &ModeIdIndex, pVBInfo ) ;
pVBInfo->SelectCRT2Rate = 4 ;
RefreshRateTableIndex = XGI_GetRatePtrCRT2( HwDeviceExtension, ModeNo , ModeIdIndex, pVBInfo ) ;
XGI_SaveCRT2Info( ModeNo, pVBInfo ) ;
XGI_GetCRT2ResInfo( ModeNo , ModeIdIndex, pVBInfo) ;
XGI_GetCRT2Data( ModeNo , ModeIdIndex , RefreshRateTableIndex, pVBInfo ) ;
XGI_PreSetGroup1( ModeNo , ModeIdIndex , HwDeviceExtension , RefreshRateTableIndex, pVBInfo ) ;
XGI_SetGroup1( ModeNo , ModeIdIndex , HwDeviceExtension , RefreshRateTableIndex, pVBInfo ) ;
XGI_SetLockRegs( ModeNo , ModeIdIndex , HwDeviceExtension , RefreshRateTableIndex, pVBInfo ) ;
XGI_SetGroup2( ModeNo , ModeIdIndex , RefreshRateTableIndex , HwDeviceExtension, pVBInfo ) ;
XGI_SetLCDRegs(ModeNo , ModeIdIndex , HwDeviceExtension , RefreshRateTableIndex, pVBInfo ) ;
XGI_SetTap4Regs(pVBInfo) ;
XGI_SetGroup3(ModeNo, ModeIdIndex, pVBInfo);
XGI_SetGroup4( ModeNo , ModeIdIndex , RefreshRateTableIndex , HwDeviceExtension, pVBInfo ) ;
XGI_SetCRT2VCLK( ModeNo , ModeIdIndex , RefreshRateTableIndex, pVBInfo ) ;
XGI_SetGroup5( ModeNo , ModeIdIndex, pVBInfo) ;
XGI_AutoThreshold( pVBInfo) ;
return 1 ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_AutoThreshold */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_AutoThreshold(struct vb_device_info *pVBInfo)
{
if ( !( pVBInfo->SetFlag & Win9xDOSMode ) )
XGINew_SetRegOR( pVBInfo->Part1Port , 0x01 , 0x40 ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SaveCRT2Info */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SaveCRT2Info(unsigned short ModeNo, struct vb_device_info *pVBInfo)
{
unsigned short temp1 ,
temp2 ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x34 , ModeNo ) ; /* reserve CR34 for CRT1 Mode No */
temp1 = ( pVBInfo->VBInfo&SetInSlaveMode ) >> 8 ;
temp2 = ~( SetInSlaveMode >> 8 ) ;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x31 , temp2 , temp1 ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetCRT2ResInfo */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_GetCRT2ResInfo(unsigned short ModeNo,
unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned short xres ,
yres ,
modeflag ,
resindex ;
resindex = XGI_GetResInfo( ModeNo , ModeIdIndex, pVBInfo) ;
if ( ModeNo <= 0x13 )
{
xres = pVBInfo->StResInfo[ resindex ].HTotal ;
yres = pVBInfo->StResInfo[ resindex ].VTotal ;
/* modeflag = pVBInfo->SModeIDTable[ModeIdIndex].St_ModeFlag; si+St_ResInfo */
}
else
{
xres = pVBInfo->ModeResInfo[ resindex ].HTotal ; /* xres->ax */
yres = pVBInfo->ModeResInfo[ resindex ].VTotal ; /* yres->bx */
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex].Ext_ModeFlag ; /* si+St_ModeFlag */
/* if ( pVBInfo->IF_DEF_FSTN )
{
xres *= 2 ;
yres *= 2 ;
}
else
{
*/
if ( modeflag & HalfDCLK )
xres *= 2;
if ( modeflag & DoubleScanMode )
yres *= 2 ;
/* } */
}
if ( pVBInfo->VBInfo & SetCRT2ToLCD )
{
if ( pVBInfo->IF_DEF_LVDS == 0 )
{
if ( pVBInfo->LCDResInfo == Panel1600x1200 )
{
if ( !( pVBInfo->LCDInfo & LCDVESATiming ) )
{
if ( yres == 1024 )
yres = 1056 ;
}
}
if ( pVBInfo->LCDResInfo == Panel1280x1024 )
{
if ( yres == 400 )
yres = 405 ;
else if ( yres == 350 )
yres = 360 ;
if ( pVBInfo->LCDInfo & LCDVESATiming )
{
if ( yres == 360 )
yres = 375 ;
}
}
if ( pVBInfo->LCDResInfo == Panel1024x768 )
{
if ( !( pVBInfo->LCDInfo & LCDVESATiming ) )
{
if ( !( pVBInfo->LCDInfo & LCDNonExpanding ) )
{
if ( yres == 350 )
yres = 357 ;
else if ( yres == 400 )
yres = 420 ;
else if ( yres == 480 )
yres = 525 ;
}
}
}
}
if ( xres == 720 )
xres = 640 ;
}
pVBInfo->VGAHDE = xres ;
pVBInfo->HDE = xres ;
pVBInfo->VGAVDE = yres ;
pVBInfo->VDE = yres ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_IsLCDDualLink */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
unsigned char XGI_IsLCDDualLink(struct vb_device_info *pVBInfo)
{
if ( ( ( ( pVBInfo->VBInfo & SetCRT2ToLCD ) | SetCRT2ToLCDA ) ) && ( pVBInfo->LCDInfo & SetLCDDualLink ) ) /* shampoo0129 */
return ( 1 ) ;
return( 0 ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetCRT2Data */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_GetCRT2Data(unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex, struct vb_device_info *pVBInfo)
{
unsigned short tempax = 0,
tempbx ,
modeflag ,
resinfo ;
struct XGI_LCDDataStruct *LCDPtr = NULL ;
struct XGI_TVDataStruct *TVPtr = NULL ;
if ( ModeNo <= 0x13 )
{
modeflag = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ; /* si+St_ResInfo */
resinfo = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ResInfo ;
}
else
{
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ; /* si+Ext_ResInfo */
resinfo = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_RESINFO ;
}
pVBInfo->NewFlickerMode = 0 ;
pVBInfo->RVBHRS = 50 ;
if ( pVBInfo->VBInfo & SetCRT2ToRAMDAC )
{
XGI_GetRAMDAC2DATA( ModeNo , ModeIdIndex , RefreshRateTableIndex,pVBInfo ) ;
return ;
}
tempbx = 4 ;
if ( pVBInfo->VBInfo & ( SetCRT2ToLCD | SetCRT2ToLCDA ) )
{
LCDPtr = (struct XGI_LCDDataStruct *)XGI_GetLcdPtr(tempbx, ModeNo, ModeIdIndex, RefreshRateTableIndex, pVBInfo);
pVBInfo->RVBHCMAX = LCDPtr->RVBHCMAX ;
pVBInfo->RVBHCFACT = LCDPtr->RVBHCFACT ;
pVBInfo->VGAHT = LCDPtr->VGAHT ;
pVBInfo->VGAVT = LCDPtr->VGAVT ;
pVBInfo->HT = LCDPtr->LCDHT ;
pVBInfo->VT = LCDPtr->LCDVT ;
if ( pVBInfo->LCDResInfo == Panel1024x768 )
{
tempax = 1024 ;
tempbx = 768 ;
if ( !( pVBInfo->LCDInfo & LCDVESATiming ) )
{
if ( pVBInfo->VGAVDE == 357 )
tempbx = 527 ;
else if ( pVBInfo->VGAVDE == 420 )
tempbx = 620 ;
else if ( pVBInfo->VGAVDE == 525 )
tempbx = 775 ;
else if ( pVBInfo->VGAVDE == 600 )
tempbx = 775 ;
/* else if(pVBInfo->VGAVDE==350) tempbx=560; */
/* else if(pVBInfo->VGAVDE==400) tempbx=640; */
else
tempbx = 768 ;
}
else
tempbx = 768 ;
}
else if ( pVBInfo->LCDResInfo == Panel1024x768x75 )
{
tempax = 1024 ;
tempbx = 768 ;
}
else if ( pVBInfo->LCDResInfo == Panel1280x1024 )
{
tempax = 1280 ;
if ( pVBInfo->VGAVDE == 360 )
tempbx = 768 ;
else if ( pVBInfo->VGAVDE == 375 )
tempbx = 800 ;
else if ( pVBInfo->VGAVDE == 405 )
tempbx = 864 ;
else
tempbx = 1024 ;
}
else if ( pVBInfo->LCDResInfo == Panel1280x1024x75 )
{
tempax = 1280 ;
tempbx = 1024 ;
}
else if ( pVBInfo->LCDResInfo == Panel1280x960 )
{
tempax = 1280 ;
if ( pVBInfo->VGAVDE == 350 )
tempbx = 700 ;
else if ( pVBInfo->VGAVDE == 400 )
tempbx = 800 ;
else if ( pVBInfo->VGAVDE == 1024 )
tempbx = 960 ;
else
tempbx = 960 ;
}
else if ( pVBInfo->LCDResInfo == Panel1400x1050 )
{
tempax = 1400 ;
tempbx = 1050 ;
if ( pVBInfo->VGAVDE == 1024 )
{
tempax = 1280 ;
tempbx = 1024 ;
}
}
else if ( pVBInfo->LCDResInfo == Panel1600x1200 )
{
tempax = 1600 ;
tempbx = 1200 ; /* alan 10/14/2003 */
if ( !( pVBInfo->LCDInfo & LCDVESATiming ) )
{
if ( pVBInfo->VGAVDE == 350 )
tempbx = 875 ;
else if ( pVBInfo->VGAVDE == 400 )
tempbx = 1000 ;
}
}
if ( pVBInfo->LCDInfo & LCDNonExpanding )
{
tempax = pVBInfo->VGAHDE ;
tempbx = pVBInfo->VGAVDE ;
}
pVBInfo->HDE = tempax ;
pVBInfo->VDE = tempbx ;
return ;
}
if ( pVBInfo->VBInfo & ( SetCRT2ToTV ) )
{
tempbx = 4 ;
TVPtr = (struct XGI_TVDataStruct *)XGI_GetTVPtr(tempbx, ModeNo, ModeIdIndex, RefreshRateTableIndex, pVBInfo);
pVBInfo->RVBHCMAX = TVPtr->RVBHCMAX ;
pVBInfo->RVBHCFACT = TVPtr->RVBHCFACT ;
pVBInfo->VGAHT = TVPtr->VGAHT ;
pVBInfo->VGAVT = TVPtr->VGAVT ;
pVBInfo->HDE = TVPtr->TVHDE ;
pVBInfo->VDE = TVPtr->TVVDE ;
pVBInfo->RVBHRS = TVPtr->RVBHRS ;
pVBInfo->NewFlickerMode = TVPtr->FlickerMode ;
if ( pVBInfo->VBInfo & SetCRT2ToHiVisionTV )
{
if ( resinfo == 0x08 )
pVBInfo->NewFlickerMode = 0x40 ;
else if ( resinfo == 0x09 )
pVBInfo->NewFlickerMode = 0x40 ;
else if ( resinfo == 0x12 )
pVBInfo->NewFlickerMode = 0x40 ;
if ( pVBInfo->VGAVDE == 350 )
pVBInfo->TVInfo |= TVSimuMode ;
tempax = ExtHiTVHT ;
tempbx = ExtHiTVVT ;
if ( pVBInfo->VBInfo & SetInSlaveMode )
{
if ( pVBInfo->TVInfo & TVSimuMode )
{
tempax = StHiTVHT ;
tempbx = StHiTVVT ;
if ( !( modeflag & Charx8Dot ) )
{
tempax = StHiTextTVHT ;
tempbx = StHiTextTVVT ;
}
}
}
}
else if ( pVBInfo->VBInfo & SetCRT2ToYPbPr )
{
if ( pVBInfo->TVInfo & SetYPbPrMode750p )
{
tempax = YPbPrTV750pHT ; /* Ext750pTVHT */
tempbx = YPbPrTV750pVT ; /* Ext750pTVVT */
}
if ( pVBInfo->TVInfo & SetYPbPrMode525p )
{
tempax = YPbPrTV525pHT ; /* Ext525pTVHT */
tempbx = YPbPrTV525pVT ; /* Ext525pTVVT */
}
else if ( pVBInfo->TVInfo & SetYPbPrMode525i )
{
tempax = YPbPrTV525iHT ; /* Ext525iTVHT */
tempbx = YPbPrTV525iVT ; /* Ext525iTVVT */
if ( pVBInfo->TVInfo & NTSC1024x768 )
tempax = NTSC1024x768HT ;
}
}
else
{
tempax = PALHT ;
tempbx = PALVT ;
if ( !( pVBInfo->TVInfo & SetPALTV ) )
{
tempax = NTSCHT ;
tempbx = NTSCVT ;
if ( pVBInfo->TVInfo & NTSC1024x768 )
tempax = NTSC1024x768HT ;
}
}
pVBInfo->HT = tempax ;
pVBInfo->VT = tempbx ;
return ;
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetCRT2VCLK */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetCRT2VCLK(unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex, struct vb_device_info *pVBInfo)
{
unsigned char di_0, di_1, tempal;
tempal = XGI_GetVCLKPtr( RefreshRateTableIndex , ModeNo , ModeIdIndex, pVBInfo ) ;
XGI_GetVCLKLen( tempal, &di_0 , &di_1, pVBInfo ) ;
XGI_GetLCDVCLKPtr( &di_0 , &di_1, pVBInfo ) ;
if ( pVBInfo->VBType & VB_XGI301 ) /* shampoo 0129 */
{ /* 301 */
XGINew_SetReg1(pVBInfo->Part4Port , 0x0A , 0x10 ) ;
XGINew_SetReg1(pVBInfo->Part4Port , 0x0B , di_1 ) ;
XGINew_SetReg1(pVBInfo->Part4Port , 0x0A , di_0 ) ;
}
else
{ /* 301b/302b/301lv/302lv */
XGINew_SetReg1( pVBInfo->Part4Port , 0x0A , di_0 ) ;
XGINew_SetReg1( pVBInfo->Part4Port , 0x0B , di_1 ) ;
}
XGINew_SetReg1( pVBInfo->Part4Port , 0x00 , 0x12 ) ;
if ( pVBInfo->VBInfo & SetCRT2ToRAMDAC )
XGINew_SetRegOR( pVBInfo->Part4Port , 0x12 , 0x28 ) ;
else
XGINew_SetRegOR( pVBInfo->Part4Port , 0x12 , 0x08 ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GETLCDVCLKPtr */
/* Input : */
/* Output : al -> VCLK Index */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_GetLCDVCLKPtr(unsigned char *di_0, unsigned char *di_1,
struct vb_device_info *pVBInfo)
{
unsigned short index ;
if ( pVBInfo->VBInfo & ( SetCRT2ToLCD | SetCRT2ToLCDA ) )
{
if ( pVBInfo->IF_DEF_ScaleLCD == 1 )
{
if ( pVBInfo->LCDInfo & EnableScalingLCD )
return ;
}
/* index = XGI_GetLCDCapPtr(pVBInfo) ; */
index = XGI_GetLCDCapPtr1( pVBInfo) ;
if ( pVBInfo->VBInfo & SetCRT2ToLCD )
{ /* LCDB */
*di_0 = pVBInfo->LCDCapList[ index ].LCUCHAR_VCLKData1 ;
*di_1 = pVBInfo->LCDCapList[ index ].LCUCHAR_VCLKData2 ;
}
else
{ /* LCDA */
*di_0 = pVBInfo->LCDCapList[ index ].LCDA_VCLKData1 ;
*di_1 = pVBInfo->LCDCapList[ index ].LCDA_VCLKData2 ;
}
}
return ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetVCLKPtr */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
unsigned char XGI_GetVCLKPtr(unsigned short RefreshRateTableIndex,
unsigned short ModeNo, unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned short index ,
modeflag ;
unsigned short tempbx ;
unsigned char tempal;
unsigned char *CHTVVCLKPtr = NULL;
if ( ModeNo <= 0x13 )
modeflag = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ; /* si+St_ResInfo */
else
modeflag = pVBInfo->EModeIDTable[ModeIdIndex].Ext_ModeFlag; /* si+Ext_ResInfo */
if ( ( pVBInfo->SetFlag & ProgrammingCRT2 ) && ( !( pVBInfo->LCDInfo & EnableScalingLCD ) ) )
{ /* {LCDA/LCDB} */
index = XGI_GetLCDCapPtr(pVBInfo) ;
tempal = pVBInfo->LCDCapList[ index ].LCD_VCLK ;
if ( pVBInfo->VBInfo & ( SetCRT2ToLCD | SetCRT2ToLCDA ) )
return tempal ;
/* {TV} */
if ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV| VB_XGI302LV| VB_XGI301C ) )
{
if(pVBInfo->VBInfo&SetCRT2ToHiVisionTV)
{
tempal = HiTVVCLKDIV2;
if(!(pVBInfo->TVInfo & RPLLDIV2XO))
tempal = HiTVVCLK;
if(pVBInfo->TVInfo & TVSimuMode)
{
tempal = HiTVSimuVCLK;
if(!(modeflag & Charx8Dot))
tempal = HiTVTextVCLK;
}
return tempal;
}
if ( pVBInfo->TVInfo & SetYPbPrMode750p )
{
tempal = YPbPr750pVCLK ;
return tempal ;
}
if ( pVBInfo->TVInfo & SetYPbPrMode525p )
{
tempal = YPbPr525pVCLK ;
return tempal ;
}
tempal = NTSC1024VCLK ;
if ( !( pVBInfo->TVInfo & NTSC1024x768 ) )
{
tempal = TVVCLKDIV2 ;
if ( !( pVBInfo->TVInfo & RPLLDIV2XO ) )
tempal = TVVCLK ;
}
if ( pVBInfo->VBInfo & SetCRT2ToTV )
return tempal ;
}
/*else
if((pVBInfo->IF_DEF_CH7017==1)&&(pVBInfo->VBType&VB_CH7017))
{
if(ModeNo<=0x13)
*tempal = pVBInfo->SModeIDTable[ModeIdIndex].St_CRT2CRTC;
else
*tempal = pVBInfo->RefIndex[RefreshRateTableIndex].Ext_CRT2CRTC;
*tempal = *tempal & 0x1F;
tempbx = 0;
if(pVBInfo->TVInfo & SetPALTV)
tempbx = tempbx + 2;
if(pVBInfo->TVInfo & SetCHTVOverScan)
tempbx++;
tempbx = tempbx << 1;
} */
} /* {End of VB} */
if((pVBInfo->IF_DEF_CH7007==1)&&(pVBInfo->VBType&VB_CH7007)) /* [Billy] 07/05/08 CH7007 */
{
/* VideoDebugPrint((0, "XGI_GetVCLKPtr: pVBInfo->IF_DEF_CH7007==1\n")); */
if ( (pVBInfo->VBInfo & SetCRT2ToTV) )
{
if( ModeNo <= 0x13 )
{
tempal = pVBInfo->SModeIDTable[ ModeIdIndex ].St_CRT2CRTC ;
}
else
{
tempal = pVBInfo->RefIndex[RefreshRateTableIndex].Ext_CRT2CRTC;
}
tempal = tempal & 0x0F;
tempbx = 0;
if(pVBInfo->TVInfo & SetPALTV)
{
tempbx = tempbx + 2;
}
if(pVBInfo->TVInfo & SetCHTVOverScan)
{
tempbx++;
}
/** tempbx = tempbx << 1; CH7007 ? **/
/*[Billy]07/05/29 CH7007*/
if ( pVBInfo->IF_DEF_CH7007 == 1 )
{
switch( tempbx )
{
case 0:
CHTVVCLKPtr = XGI7007_CHTVVCLKUNTSC ;
break ;
case 1:
CHTVVCLKPtr = XGI7007_CHTVVCLKONTSC ;
break ;
case 2:
CHTVVCLKPtr = XGI7007_CHTVVCLKUPAL ;
break ;
case 3:
CHTVVCLKPtr = XGI7007_CHTVVCLKOPAL ;
break ;
default:
break ;
}
}
/*else
{
switch( tempbx )
{
case 0:
CHTVVCLKPtr = pVBInfo->CHTVVCLKUNTSC ;
break ;
case 1:
CHTVVCLKPtr = pVBInfo->CHTVVCLKONTSC ;
break ;
case 2:
CHTVVCLKPtr = pVBInfo->CHTVVCLKUPAL ;
break ;
case 3:
CHTVVCLKPtr = pVBInfo->CHTVVCLKOPAL ;
break ;
default:
break ;
}
}*/
tempal = CHTVVCLKPtr[ tempal ] ;
return tempal ;
}
}
tempal = (unsigned char)XGINew_GetReg2((pVBInfo->P3ca + 0x02));
tempal = tempal >> 2 ;
tempal &= 0x03 ;
if ( ( pVBInfo->LCDInfo & EnableScalingLCD ) && ( modeflag & Charx8Dot ) ) /* for Dot8 Scaling LCD */
tempal = tempal ^ tempal ; /* ; set to VCLK25MHz always */
if ( ModeNo <= 0x13 )
return tempal ;
tempal = pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_CRTVCLK ;
return tempal ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetVCLKLen */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_GetVCLKLen(unsigned char tempal, unsigned char *di_0,
unsigned char *di_1, struct vb_device_info *pVBInfo)
{
if ( pVBInfo->IF_DEF_CH7007 == 1 ) /* [Billy] 2007/05/16 */
{
/* VideoDebugPrint((0, "XGI_GetVCLKLen: pVBInfo->IF_DEF_CH7007==1\n")); */
*di_0 = (unsigned char)XGI_CH7007VCLKData[tempal].SR2B;
*di_1 = (unsigned char)XGI_CH7007VCLKData[tempal].SR2C;
}
else if ( pVBInfo->VBType & ( VB_XGI301 | VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{
if ( ( !( pVBInfo->VBInfo & SetCRT2ToLCDA ) ) && ( pVBInfo->SetFlag & ProgrammingCRT2 ) )
{
*di_0 = (unsigned char)XGI_VBVCLKData[tempal].SR2B;
*di_1 = XGI_VBVCLKData[ tempal ].SR2C ;
}
}
else
{
*di_0 = XGI_VCLKData[ tempal ].SR2B ;
*di_1 = XGI_VCLKData[ tempal ].SR2C ;
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetCRT2Offset */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetCRT2Offset(unsigned short ModeNo,
unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct xgi_hw_device_info *HwDeviceExtension,
struct vb_device_info *pVBInfo)
{
unsigned short offset ;
unsigned char temp;
if ( pVBInfo->VBInfo & SetInSlaveMode )
{
return ;
}
offset = XGI_GetOffset( ModeNo , ModeIdIndex , RefreshRateTableIndex , HwDeviceExtension, pVBInfo ) ;
temp = (unsigned char)(offset & 0xFF);
XGINew_SetReg1( pVBInfo->Part1Port , 0x07 , temp ) ;
temp = (unsigned char)((offset & 0xFF00) >> 8);
XGINew_SetReg1(pVBInfo->Part1Port , 0x09 , temp);
temp = (unsigned char)(((offset >> 3) & 0xFF) + 1) ;
XGINew_SetReg1(pVBInfo->Part1Port, 0x03, temp);
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetOffset */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
unsigned short XGI_GetOffset(unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex, struct xgi_hw_device_info *HwDeviceExtension, struct vb_device_info *pVBInfo)
{
unsigned short temp ,
colordepth ,
modeinfo ,
index ,
infoflag ,
ColorDepth[] = { 0x01 , 0x02 , 0x04 } ;
modeinfo = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeInfo ;
if ( ModeNo <= 0x14 )
infoflag = 0 ;
else
infoflag = pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_InfoFlag ;
index = ( modeinfo >> 8 ) & 0xFF ;
temp = pVBInfo->ScreenOffset[ index ] ;
if ( infoflag & InterlaceMode )
{
temp = temp << 1 ;
}
colordepth = XGI_GetColorDepth( ModeNo , ModeIdIndex, pVBInfo ) ;
if ( ( ModeNo >= 0x7C ) && ( ModeNo <= 0x7E ) )
{
temp = ModeNo - 0x7C ;
colordepth = ColorDepth[ temp ] ;
temp = 0x6B ;
if ( infoflag & InterlaceMode )
{
temp = temp << 1 ;
}
return( temp * colordepth ) ;
}
else
return( temp * colordepth ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetCRT2FIFO */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetCRT2FIFO(struct vb_device_info *pVBInfo)
{
XGINew_SetReg1( pVBInfo->Part1Port , 0x01 , 0x3B ) ; /* threshold high ,disable auto threshold */
XGINew_SetRegANDOR( pVBInfo->Part1Port , 0x02 , ~( 0x3F ) , 0x04 ) ; /* threshold low default 04h */
}
/* --------------------------------------------------------------------- */
/* Function : XGI_PreSetGroup1 */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_PreSetGroup1(unsigned short ModeNo, unsigned short ModeIdIndex,
struct xgi_hw_device_info *HwDeviceExtension,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned short tempcx = 0 ,
CRT1Index = 0 ,
resinfo = 0 ;
if ( ModeNo > 0x13 )
{
CRT1Index = pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_CRT1CRTC ;
CRT1Index &= IndexMask ;
resinfo = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_RESINFO ;
}
XGI_SetCRT2Offset( ModeNo , ModeIdIndex , RefreshRateTableIndex , HwDeviceExtension, pVBInfo ) ;
XGI_SetCRT2FIFO(pVBInfo) ;
/* XGI_SetCRT2Sync(ModeNo,RefreshRateTableIndex); */
for( tempcx = 4 ; tempcx < 7 ; tempcx++ )
{
XGINew_SetReg1( pVBInfo->Part1Port , tempcx , 0x0 ) ;
}
XGINew_SetReg1( pVBInfo->Part1Port , 0x50 , 0x00 ) ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x02 , 0x44 ) ; /* temp 0206 */
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetGroup1 */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetGroup1(unsigned short ModeNo, unsigned short ModeIdIndex,
struct xgi_hw_device_info *HwDeviceExtension,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned short temp = 0 ,
tempax = 0 ,
tempbx = 0 ,
tempcx = 0 ,
pushbx = 0 ,
CRT1Index = 0 ,
modeflag ,
resinfo = 0 ;
if ( ModeNo > 0x13 )
{
CRT1Index = pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_CRT1CRTC ;
CRT1Index &= IndexMask ;
resinfo = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_RESINFO ;
}
if ( ModeNo <= 0x13 )
{
modeflag = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ;
}
else
{
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ;
}
/* bainy change table name */
if ( modeflag & HalfDCLK )
{
temp = ( pVBInfo->VGAHT / 2 - 1 ) & 0x0FF ; /* BTVGA2HT 0x08,0x09 */
XGINew_SetReg1( pVBInfo->Part1Port , 0x08 , temp ) ;
temp = ( ( ( pVBInfo->VGAHT / 2 - 1 ) & 0xFF00 ) >> 8 ) << 4 ;
XGINew_SetRegANDOR( pVBInfo->Part1Port , 0x09 , ~0x0F0 , temp ) ;
temp = ( pVBInfo->VGAHDE / 2 + 16 ) & 0x0FF ; /* BTVGA2HDEE 0x0A,0x0C */
XGINew_SetReg1( pVBInfo->Part1Port , 0x0A , temp ) ;
tempcx = ( ( pVBInfo->VGAHT - pVBInfo->VGAHDE ) / 2 ) >> 2 ;
pushbx = pVBInfo->VGAHDE / 2 + 16 ;
tempcx = tempcx >> 1 ;
tempbx = pushbx + tempcx ; /* bx BTVGA@HRS 0x0B,0x0C */
tempcx += tempbx ;
if ( pVBInfo->VBInfo & SetCRT2ToRAMDAC )
{
tempbx = pVBInfo->XGINEWUB_CRT1Table[ CRT1Index ].CR[ 4 ] ;
tempbx |= ( ( pVBInfo->XGINEWUB_CRT1Table[ CRT1Index ].CR[ 14 ] & 0xC0 ) << 2 ) ;
tempbx = ( tempbx - 3 ) << 3 ; /* (VGAHRS-3)*8 */
tempcx = pVBInfo->XGINEWUB_CRT1Table[CRT1Index].CR[ 5 ] ;
tempcx &= 0x1F ;
temp = pVBInfo->XGINEWUB_CRT1Table[ CRT1Index ].CR[ 15 ] ;
temp = ( temp & 0x04 ) << ( 5 - 2 ) ; /* VGAHRE D[5] */
tempcx = ( ( tempcx | temp ) - 3 ) << 3 ; /* (VGAHRE-3)*8 */
}
tempbx += 4 ;
tempcx += 4 ;
if ( tempcx > ( pVBInfo->VGAHT / 2 ) )
tempcx = pVBInfo->VGAHT / 2 ;
temp = tempbx & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x0B , temp ) ;
}
else
{
temp = ( pVBInfo->VGAHT - 1 ) & 0x0FF ; /* BTVGA2HT 0x08,0x09 */
XGINew_SetReg1( pVBInfo->Part1Port , 0x08 , temp ) ;
temp = ( ( ( pVBInfo->VGAHT - 1 ) & 0xFF00 ) >> 8 ) << 4 ;
XGINew_SetRegANDOR( pVBInfo->Part1Port , 0x09 , ~0x0F0 , temp ) ;
temp = ( pVBInfo->VGAHDE + 16 ) & 0x0FF ; /* BTVGA2HDEE 0x0A,0x0C */
XGINew_SetReg1( pVBInfo->Part1Port , 0x0A , temp ) ;
tempcx = ( pVBInfo->VGAHT - pVBInfo->VGAHDE ) >> 2 ; /* cx */
pushbx = pVBInfo->VGAHDE + 16 ;
tempcx = tempcx >> 1 ;
tempbx = pushbx + tempcx ; /* bx BTVGA@HRS 0x0B,0x0C */
tempcx += tempbx ;
if ( pVBInfo->VBInfo & SetCRT2ToRAMDAC )
{
tempbx = pVBInfo->XGINEWUB_CRT1Table[ CRT1Index ].CR[ 3 ] ;
tempbx |= ( ( pVBInfo->XGINEWUB_CRT1Table[ CRT1Index ].CR[ 5 ] & 0xC0 ) << 2 ) ;
tempbx = ( tempbx - 3 ) << 3 ; /* (VGAHRS-3)*8 */
tempcx = pVBInfo->XGINEWUB_CRT1Table[ CRT1Index ].CR[ 4 ] ;
tempcx &= 0x1F ;
temp = pVBInfo->XGINEWUB_CRT1Table[ CRT1Index ].CR[ 6 ] ;
temp = ( temp & 0x04 ) << ( 5 - 2 ) ; /* VGAHRE D[5] */
tempcx = ( ( tempcx | temp ) - 3 ) << 3 ; /* (VGAHRE-3)*8 */
tempbx += 16 ;
tempcx += 16 ;
}
if ( tempcx > pVBInfo->VGAHT )
tempcx = pVBInfo->VGAHT ;
temp = tempbx & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x0B , temp ) ;
}
tempax = ( tempax & 0x00FF ) | ( tempbx & 0xFF00 ) ;
tempbx = pushbx ;
tempbx = ( tempbx & 0x00FF ) | ( ( tempbx & 0xFF00 ) << 4 ) ;
tempax |= ( tempbx & 0xFF00 ) ;
temp = ( tempax & 0xFF00 ) >> 8 ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x0C , temp ) ;
temp = tempcx & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x0D , temp ) ;
tempcx = ( pVBInfo->VGAVT - 1 ) ;
temp = tempcx & 0x00FF ;
if ( pVBInfo->IF_DEF_CH7005 == 1 )
{
if ( pVBInfo->VBInfo & 0x0C )
{
temp-- ;
}
}
XGINew_SetReg1( pVBInfo->Part1Port , 0x0E , temp ) ;
tempbx = pVBInfo->VGAVDE - 1 ;
temp = tempbx & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x0F , temp ) ;
temp = ( ( tempbx & 0xFF00 ) << 3 ) >> 8 ;
temp |= ( ( tempcx & 0xFF00 ) >> 8 ) ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x12 , temp ) ;
tempax = pVBInfo->VGAVDE ;
tempbx = pVBInfo->VGAVDE ;
tempcx = pVBInfo->VGAVT ;
tempbx = ( pVBInfo->VGAVT + pVBInfo->VGAVDE ) >> 1 ; /* BTVGA2VRS 0x10,0x11 */
tempcx = ( ( pVBInfo->VGAVT - pVBInfo->VGAVDE ) >> 4 ) + tempbx + 1 ; /* BTVGA2VRE 0x11 */
if ( pVBInfo->VBInfo & SetCRT2ToRAMDAC )
{
tempbx = pVBInfo->XGINEWUB_CRT1Table[ CRT1Index ].CR[ 10 ] ;
temp = pVBInfo->XGINEWUB_CRT1Table[ CRT1Index ].CR[ 9 ] ;
if ( temp & 0x04 )
tempbx |= 0x0100 ;
if ( temp & 0x080 )
tempbx |= 0x0200 ;
temp = pVBInfo->XGINEWUB_CRT1Table[ CRT1Index ].CR[ 14 ] ;
if ( temp & 0x08 )
tempbx |= 0x0400 ;
temp = pVBInfo->XGINEWUB_CRT1Table[ CRT1Index ].CR[ 11 ] ;
tempcx = ( tempcx & 0xFF00 ) | ( temp & 0x00FF ) ;
}
temp = tempbx & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x10 , temp ) ;
temp = ( ( tempbx & 0xFF00 ) >> 8 ) << 4 ;
temp = ( ( tempcx & 0x000F ) | ( temp ) ) ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x11 , temp ) ;
tempax = 0 ;
if ( modeflag & DoubleScanMode )
tempax |= 0x80 ;
if ( modeflag & HalfDCLK )
tempax |= 0x40 ;
XGINew_SetRegANDOR( pVBInfo->Part1Port , 0x2C , ~0x0C0 , tempax ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetLockRegs */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetLockRegs(unsigned short ModeNo, unsigned short ModeIdIndex,
struct xgi_hw_device_info *HwDeviceExtension,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned short push1 ,
push2 ,
tempax ,
tempbx = 0 ,
tempcx ,
temp ,
resinfo ,
modeflag ,
CRT1Index ;
if ( ModeNo <= 0x13 )
{
modeflag = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ; /* si+St_ResInfo */
resinfo = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ResInfo ;
}
else
{
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ; /* si+Ext_ResInfo */
resinfo = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_RESINFO ;
CRT1Index = pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_CRT1CRTC ;
CRT1Index &= IndexMask;
}
if ( !( pVBInfo->VBInfo & SetInSlaveMode ) )
{
return ;
}
temp = 0xFF ; /* set MAX HT */
XGINew_SetReg1( pVBInfo->Part1Port , 0x03 , temp ) ;
/* if ( modeflag & Charx8Dot ) tempcx = 0x08 ; */
/* else */
tempcx=0x08;
if ( pVBInfo->VBType & ( VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
modeflag |= Charx8Dot ;
tempax = pVBInfo->VGAHDE ; /* 0x04 Horizontal Display End */
if ( modeflag & HalfDCLK )
tempax = tempax >> 1 ;
tempax = ( tempax / tempcx ) - 1 ;
tempbx |= ( ( tempax & 0x00FF ) << 8 ) ;
temp = tempax & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x04 , temp ) ;
temp = ( tempbx & 0xFF00 ) >> 8 ;
if ( pVBInfo->VBInfo & SetCRT2ToTV )
{
if ( !( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) ) )
temp += 2 ;
if ( pVBInfo->VBInfo & SetCRT2ToHiVisionTV )
{
if ( pVBInfo->VBType & VB_XGI301LV )
{
if ( pVBInfo->VBExtInfo == VB_YPbPr1080i )
{
if ( resinfo == 7 )
temp -= 2 ;
}
}
else
if ( resinfo == 7 )
temp -= 2 ;
}
}
XGINew_SetReg1( pVBInfo->Part1Port , 0x05 , temp ) ; /* 0x05 Horizontal Display Start */
XGINew_SetReg1( pVBInfo->Part1Port , 0x06 , 0x03 ) ; /* 0x06 Horizontal Blank end */
if ( !( pVBInfo->VBInfo & DisableCRT2Display ) )
{ /* 030226 bainy */
if ( pVBInfo->VBInfo & SetCRT2ToTV )
tempax = pVBInfo->VGAHT ;
else
tempax = XGI_GetVGAHT2( pVBInfo) ;
}
if ( tempax >= pVBInfo->VGAHT )
{
tempax = pVBInfo->VGAHT ;
}
if ( modeflag & HalfDCLK )
{
tempax = tempax >> 1 ;
}
tempax = ( tempax / tempcx ) - 5 ;
tempcx = tempax ; /* 20030401 0x07 horizontal Retrace Start */
if ( pVBInfo->VBInfo & SetCRT2ToHiVisionTV )
{
temp = ( tempbx & 0x00FF ) - 1 ;
if ( !( modeflag & HalfDCLK ) )
{
temp -= 6 ;
if ( pVBInfo->TVInfo & TVSimuMode )
{
temp -= 4 ;
if ( ModeNo > 0x13 )
temp -= 10 ;
}
}
}
else
{
/* tempcx = tempbx & 0x00FF ; */
tempbx = ( tempbx & 0xFF00 ) >> 8 ;
tempcx = ( tempcx + tempbx ) >> 1 ;
temp = ( tempcx & 0x00FF ) + 2 ;
if ( pVBInfo->VBInfo & SetCRT2ToTV )
{
temp -= 1 ;
if ( !( modeflag & HalfDCLK ) )
{
if ( ( modeflag & Charx8Dot ) )
{
temp += 4 ;
if ( pVBInfo->VGAHDE >= 800 )
{
temp -= 6 ;
}
}
}
}
else
{
if ( !( modeflag & HalfDCLK ) )
{
temp -= 4 ;
if ( pVBInfo->LCDResInfo != Panel1280x960 )
{
if( pVBInfo->VGAHDE >= 800 )
{
temp -= 7 ;
if ( pVBInfo->ModeType == ModeEGA )
{
if ( pVBInfo->VGAVDE == 1024 )
{
temp += 15 ;
if ( pVBInfo->LCDResInfo != Panel1280x1024 )
{
temp += 7 ;
}
}
}
if ( pVBInfo->VGAHDE >= 1280 )
{
if ( pVBInfo->LCDResInfo != Panel1280x960 )
{
if ( pVBInfo->LCDInfo & LCDNonExpanding )
{
temp += 28 ;
}
}
}
}
}
}
}
}
XGINew_SetReg1( pVBInfo->Part1Port , 0x07 , temp ) ; /* 0x07 Horizontal Retrace Start */
XGINew_SetReg1( pVBInfo->Part1Port , 0x08 , 0 ) ; /* 0x08 Horizontal Retrace End */
if ( pVBInfo->VBInfo & SetCRT2ToTV )
{
if ( pVBInfo->TVInfo & TVSimuMode )
{
if ( ( ModeNo == 0x06 ) || ( ModeNo == 0x10 ) || ( ModeNo == 0x11 ) || ( ModeNo == 0x13 ) || ( ModeNo == 0x0F ) )
{
XGINew_SetReg1( pVBInfo->Part1Port , 0x07 , 0x5b ) ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x08 , 0x03 ) ;
}
if ( ( ModeNo == 0x00 ) || ( ModeNo == 0x01 ) )
{
if ( pVBInfo->TVInfo & SetNTSCTV )
{
XGINew_SetReg1( pVBInfo->Part1Port , 0x07 , 0x2A ) ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x08 , 0x61 ) ;
}
else
{
XGINew_SetReg1( pVBInfo->Part1Port , 0x07 , 0x2A ) ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x08 , 0x41 ) ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x0C , 0xF0 ) ;
}
}
if ( ( ModeNo == 0x02 ) || ( ModeNo == 0x03 ) || ( ModeNo == 0x07 ) )
{
if ( pVBInfo->TVInfo & SetNTSCTV )
{
XGINew_SetReg1( pVBInfo->Part1Port , 0x07 , 0x54 ) ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x08 , 0x00 ) ;
}
else
{
XGINew_SetReg1( pVBInfo->Part1Port , 0x07 , 0x55 ) ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x08 , 0x00 ) ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x0C , 0xF0 ) ;
}
}
if ( ( ModeNo == 0x04 ) || ( ModeNo == 0x05 ) || ( ModeNo == 0x0D ) || ( ModeNo == 0x50 ) )
{
if ( pVBInfo->TVInfo & SetNTSCTV )
{
XGINew_SetReg1( pVBInfo->Part1Port , 0x07 , 0x30 ) ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x08 , 0x03 ) ;
}
else
{
XGINew_SetReg1( pVBInfo->Part1Port , 0x07 , 0x2f ) ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x08 , 0x02 ) ;
}
}
}
}
XGINew_SetReg1( pVBInfo->Part1Port , 0x18 , 0x03 ) ; /* 0x18 SR0B */
XGINew_SetRegANDOR( pVBInfo->Part1Port , 0x19 , 0xF0 , 0x00 ) ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x09 , 0xFF ) ; /* 0x09 Set Max VT */
tempbx = pVBInfo->VGAVT ;
push1 = tempbx ;
tempcx = 0x121 ;
tempbx = pVBInfo->VGAVDE ; /* 0x0E Virtical Display End */
if ( tempbx == 357 )
tempbx = 350 ;
if ( tempbx == 360 )
tempbx =350 ;
if ( tempbx == 375 )
tempbx = 350 ;
if ( tempbx == 405 )
tempbx = 400 ;
if ( tempbx == 525 )
tempbx = 480 ;
push2 = tempbx ;
if ( pVBInfo->VBInfo & SetCRT2ToLCD )
{
if ( pVBInfo->LCDResInfo == Panel1024x768 )
{
if ( !( pVBInfo->LCDInfo & LCDVESATiming ) )
{
if ( tempbx == 350 )
tempbx += 5 ;
if ( tempbx == 480 )
tempbx += 5 ;
}
}
}
tempbx-- ;
temp = tempbx & 0x00FF ;
tempbx-- ;
temp = tempbx & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x10 ,temp ) ; /* 0x10 vertical Blank Start */
tempbx = push2 ;
tempbx-- ;
temp = tempbx & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x0E , temp ) ;
if ( tempbx & 0x0100 )
{
tempcx |= 0x0002 ;
}
tempax = 0x000B ;
if ( modeflag & DoubleScanMode )
{
tempax |= 0x08000 ;
}
if ( tempbx & 0x0200 )
{
tempcx |= 0x0040 ;
}
temp = ( tempax & 0xFF00 ) >> 8 ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x0B , temp ) ;
if ( tempbx & 0x0400 )
{
tempcx |= 0x0600 ;
}
XGINew_SetReg1( pVBInfo->Part1Port , 0x11 , 0x00 ) ; /* 0x11 Vertival Blank End */
tempax = push1 ;
tempax -= tempbx ; /* 0x0C Vertical Retrace Start */
tempax = tempax >> 2 ;
push1 = tempax ; /* push ax */
if ( resinfo != 0x09 )
{
tempax = tempax << 1 ;
tempbx += tempax ;
}
if ( pVBInfo->VBInfo & SetCRT2ToHiVisionTV )
{
if ( pVBInfo->VBType & VB_XGI301LV )
{
if ( pVBInfo->TVInfo & SetYPbPrMode1080i )
tempbx -= 10 ;
else
{
if ( pVBInfo->TVInfo & TVSimuMode )
{
if ( pVBInfo->TVInfo & SetPALTV )
{
if ( pVBInfo->VBType & VB_XGI301LV )
{
if ( !( pVBInfo->TVInfo & ( SetYPbPrMode525p | SetYPbPrMode750p | SetYPbPrMode1080i ) ) )
tempbx += 40 ;
}
else
tempbx += 40 ;
}
}
}
}
else
tempbx -= 10 ;
}
else
{
if ( pVBInfo->TVInfo & TVSimuMode )
{
if ( pVBInfo->TVInfo & SetPALTV )
{
if ( pVBInfo->VBType & VB_XGI301LV )
{
if ( !( pVBInfo->TVInfo & ( SetYPbPrMode525p | SetYPbPrMode750p | SetYPbPrMode1080i ) ) )
tempbx += 40 ;
}
else
tempbx += 40 ;
}
}
}
tempax = push1 ;
tempax = tempax >> 2 ;
tempax++ ;
tempax += tempbx ;
push1 = tempax ; /* push ax */
if ( ( pVBInfo->TVInfo & SetPALTV ) )
{
if ( tempbx <= 513 )
{
if ( tempax >= 513 )
{
tempbx = 513 ;
}
}
}
temp = tempbx & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x0C , temp ) ;
tempbx-- ;
temp = tempbx & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x10 , temp ) ;
if ( tempbx & 0x0100 )
{
tempcx |= 0x0008 ;
}
if ( tempbx & 0x0200 )
{
XGINew_SetRegANDOR( pVBInfo->Part1Port , 0x0B , 0x0FF , 0x20 ) ;
}
tempbx++ ;
if ( tempbx & 0x0100 )
{
tempcx |= 0x0004 ;
}
if ( tempbx & 0x0200 )
{
tempcx |= 0x0080 ;
}
if ( tempbx & 0x0400 )
{
tempcx |= 0x0C00 ;
}
tempbx = push1 ; /* pop ax */
temp = tempbx & 0x00FF ;
temp &= 0x0F ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x0D , temp ) ; /* 0x0D vertical Retrace End */
if ( tempbx & 0x0010 )
{
tempcx |= 0x2000 ;
}
temp = tempcx & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x0A , temp ) ; /* 0x0A CR07 */
temp = ( tempcx & 0x0FF00 ) >> 8 ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x17 , temp ) ; /* 0x17 SR0A */
tempax = modeflag ;
temp = ( tempax & 0xFF00 ) >> 8 ;
temp = ( temp >> 1 ) & 0x09 ;
if ( pVBInfo->VBType & ( VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
temp |= 0x01 ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x16 , temp ) ; /* 0x16 SR01 */
XGINew_SetReg1( pVBInfo->Part1Port , 0x0F , 0 ) ; /* 0x0F CR14 */
XGINew_SetReg1( pVBInfo->Part1Port , 0x12 , 0 ) ; /* 0x12 CR17 */
if ( pVBInfo->LCDInfo & LCDRGB18Bit )
temp = 0x80 ;
else
temp = 0x00 ;
XGINew_SetReg1( pVBInfo->Part1Port , 0x1A , temp ) ; /* 0x1A SR0E */
return ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetGroup2 */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetGroup2(unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex,
struct xgi_hw_device_info *HwDeviceExtension, struct vb_device_info *pVBInfo)
{
unsigned short i ,
j ,
tempax ,
tempbx ,
tempcx ,
temp ,
push1 ,
push2 ,
modeflag ,
resinfo ,
crt2crtc ;
unsigned char *TimingPoint ;
unsigned long longtemp ,
tempeax ,
tempebx ,
temp2 ,
tempecx ;
if ( ModeNo <= 0x13 )
{
modeflag = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ; /* si+St_ResInfo */
resinfo = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ResInfo ;
crt2crtc = pVBInfo->SModeIDTable[ ModeIdIndex ].St_CRT2CRTC ;
}
else
{
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ; /* si+Ext_ResInfo */
resinfo = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_RESINFO ;
crt2crtc = pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_CRT2CRTC ;
}
tempax = 0 ;
if ( !( pVBInfo->VBInfo & SetCRT2ToAVIDEO ) )
tempax |= 0x0800 ;
if ( !( pVBInfo->VBInfo & SetCRT2ToSVIDEO ) )
tempax |= 0x0400 ;
if ( pVBInfo->VBInfo & SetCRT2ToSCART )
tempax |= 0x0200 ;
if ( !( pVBInfo->TVInfo & SetPALTV ) )
tempax |= 0x1000 ;
if ( pVBInfo->VBInfo & SetCRT2ToHiVisionTV )
tempax |= 0x0100 ;
if ( pVBInfo->TVInfo & ( SetYPbPrMode525p | SetYPbPrMode750p ) )
tempax &= 0xfe00 ;
tempax = ( tempax & 0xff00 ) >> 8 ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x0 , tempax ) ;
TimingPoint = pVBInfo->NTSCTiming ;
if ( pVBInfo->TVInfo & SetPALTV )
{
TimingPoint = pVBInfo->PALTiming ;
}
if ( pVBInfo->VBInfo & SetCRT2ToHiVisionTV )
{
TimingPoint = pVBInfo->HiTVExtTiming ;
if ( pVBInfo->VBInfo & SetInSlaveMode )
TimingPoint = pVBInfo->HiTVSt2Timing ;
if ( pVBInfo->SetFlag & TVSimuMode )
TimingPoint = pVBInfo->HiTVSt1Timing ;
if ( !(modeflag & Charx8Dot) )
TimingPoint = pVBInfo->HiTVTextTiming ;
}
if ( pVBInfo->VBInfo & SetCRT2ToYPbPr )
{
if ( pVBInfo->TVInfo & SetYPbPrMode525i )
TimingPoint = pVBInfo->YPbPr525iTiming ;
if ( pVBInfo->TVInfo & SetYPbPrMode525p )
TimingPoint = pVBInfo->YPbPr525pTiming ;
if ( pVBInfo->TVInfo & SetYPbPrMode750p )
TimingPoint = pVBInfo->YPbPr750pTiming ;
}
for( i = 0x01 , j = 0 ; i <= 0x2D ; i++ , j++ )
{
XGINew_SetReg1( pVBInfo->Part2Port , i , TimingPoint[ j ] ) ;
}
for( i = 0x39 ; i <= 0x45 ; i++ , j++ )
{
XGINew_SetReg1( pVBInfo->Part2Port , i , TimingPoint[ j ] ) ; /* di->temp2[j] */
}
if ( pVBInfo->VBInfo & SetCRT2ToTV )
{
XGINew_SetRegANDOR( pVBInfo->Part2Port , 0x3A , 0x1F , 0x00 ) ;
}
temp = pVBInfo->NewFlickerMode ;
temp &= 0x80 ;
XGINew_SetRegANDOR( pVBInfo->Part2Port , 0x0A , 0xFF , temp ) ;
if ( pVBInfo->VBInfo & SetCRT2ToHiVisionTV )
tempax = 950 ;
if ( pVBInfo->TVInfo & SetPALTV )
tempax = 520 ;
else
tempax = 440 ;
if ( pVBInfo->VDE <= tempax )
{
tempax -= pVBInfo->VDE ;
tempax = tempax >> 2 ;
tempax = ( tempax & 0x00FF ) | ( ( tempax & 0x00FF ) << 8 ) ;
push1 = tempax ;
temp = ( tempax & 0xFF00 ) >> 8 ;
temp += (unsigned short)TimingPoint[0];
if ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{
if ( pVBInfo->VBInfo & ( SetCRT2ToAVIDEO | SetCRT2ToSVIDEO | SetCRT2ToSCART | SetCRT2ToYPbPr ) )
{
tempcx=pVBInfo->VGAHDE;
if ( tempcx >= 1024 )
{
temp = 0x17 ; /* NTSC */
if ( pVBInfo->TVInfo & SetPALTV )
temp = 0x19 ; /* PAL */
}
}
}
XGINew_SetReg1( pVBInfo->Part2Port , 0x01 , temp ) ;
tempax = push1 ;
temp = ( tempax & 0xFF00 ) >> 8 ;
temp += TimingPoint[ 1 ] ;
if ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{
if ( ( pVBInfo->VBInfo & ( SetCRT2ToAVIDEO | SetCRT2ToSVIDEO | SetCRT2ToSCART | SetCRT2ToYPbPr ) ) )
{
tempcx = pVBInfo->VGAHDE ;
if ( tempcx >= 1024 )
{
temp = 0x1D ; /* NTSC */
if ( pVBInfo->TVInfo & SetPALTV )
temp = 0x52 ; /* PAL */
}
}
}
XGINew_SetReg1( pVBInfo->Part2Port , 0x02 , temp ) ;
}
/* 301b */
tempcx = pVBInfo->HT ;
if ( XGI_IsLCDDualLink( pVBInfo ) )
tempcx = tempcx >> 1 ;
tempcx -= 2 ;
temp = tempcx & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x1B , temp ) ;
temp = ( tempcx & 0xFF00 ) >> 8 ;
XGINew_SetRegANDOR( pVBInfo->Part2Port , 0x1D , ~0x0F , temp ) ;
tempcx = pVBInfo->HT >> 1 ;
push1 = tempcx ; /* push cx */
tempcx += 7 ;
if ( pVBInfo->VBInfo & SetCRT2ToHiVisionTV )
{
tempcx -= 4 ;
}
temp = tempcx & 0x00FF ;
temp = temp << 4 ;
XGINew_SetRegANDOR( pVBInfo->Part2Port , 0x22 , 0x0F , temp ) ;
tempbx = TimingPoint[ j ] | ( ( TimingPoint[ j + 1 ] ) << 8 ) ;
tempbx += tempcx ;
push2 = tempbx ;
temp = tempbx & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x24 , temp ) ;
temp = ( tempbx & 0xFF00 ) >> 8 ;
temp = temp << 4 ;
XGINew_SetRegANDOR(pVBInfo->Part2Port,0x25,0x0F,temp);
tempbx=push2;
tempbx=tempbx+8;
if ( pVBInfo->VBInfo & SetCRT2ToHiVisionTV )
{
tempbx=tempbx-4;
tempcx=tempbx;
}
temp = ( tempbx & 0x00FF ) << 4 ;
XGINew_SetRegANDOR( pVBInfo->Part2Port , 0x29 , 0x0F , temp ) ;
j += 2 ;
tempcx += ( TimingPoint[ j ] | ( ( TimingPoint[ j + 1 ] ) << 8 ) ) ;
temp = tempcx & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x27 , temp ) ;
temp = ( ( tempcx & 0xFF00 ) >> 8 ) << 4 ;
XGINew_SetRegANDOR( pVBInfo->Part2Port , 0x28 , 0x0F , temp ) ;
tempcx += 8 ;
if ( pVBInfo->VBInfo & SetCRT2ToHiVisionTV )
{
tempcx -= 4 ;
}
temp = tempcx & 0xFF ;
temp = temp << 4 ;
XGINew_SetRegANDOR( pVBInfo->Part2Port , 0x2A , 0x0F , temp ) ;
tempcx = push1 ; /* pop cx */
j += 2 ;
temp = TimingPoint[ j ] | ( ( TimingPoint[ j + 1 ] ) << 8 ) ;
tempcx -= temp ;
temp = tempcx & 0x00FF ;
temp = temp << 4 ;
XGINew_SetRegANDOR( pVBInfo->Part2Port , 0x2D , 0x0F ,temp ) ;
tempcx -= 11 ;
if ( !( pVBInfo->VBInfo & SetCRT2ToTV ) )
{
tempax = XGI_GetVGAHT2( pVBInfo) ;
tempcx = tempax - 1 ;
}
temp = tempcx & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x2E , temp ) ;
tempbx = pVBInfo->VDE ;
if ( pVBInfo->VGAVDE == 360 )
tempbx = 746 ;
if ( pVBInfo->VGAVDE == 375 )
tempbx = 746 ;
if ( pVBInfo->VGAVDE == 405 )
tempbx = 853 ;
if ( pVBInfo->VBInfo & SetCRT2ToTV )
{
if ( pVBInfo->VBType & ( VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{
if ( !( pVBInfo->TVInfo & ( SetYPbPrMode525p | SetYPbPrMode750p ) ) )
tempbx = tempbx >> 1 ;
}
else
tempbx = tempbx >> 1 ;
}
tempbx -= 2 ;
temp = tempbx & 0x00FF ;
if ( pVBInfo->VBInfo & SetCRT2ToHiVisionTV )
{
if ( pVBInfo->VBType & VB_XGI301LV )
{
if ( pVBInfo->TVInfo & SetYPbPrMode1080i )
{
if ( pVBInfo->VBInfo & SetInSlaveMode )
{
if ( ModeNo == 0x2f )
temp += 1 ;
}
}
}
else
{
if ( pVBInfo->VBInfo & SetInSlaveMode )
{
if ( ModeNo == 0x2f )
temp += 1 ;
}
}
}
XGINew_SetReg1( pVBInfo->Part2Port , 0x2F , temp ) ;
temp = ( tempcx & 0xFF00 ) >> 8 ;
temp |= ( ( tempbx & 0xFF00 ) >> 8 ) << 6 ;
if ( !( pVBInfo->VBInfo & SetCRT2ToHiVisionTV ) )
{
if ( pVBInfo->VBType & VB_XGI301LV )
{
if ( pVBInfo->TVInfo & SetYPbPrMode1080i )
{
temp |= 0x10 ;
if ( !( pVBInfo->VBInfo & SetCRT2ToSVIDEO ) )
temp |= 0x20 ;
}
}
else
{
temp |= 0x10 ;
if ( !( pVBInfo->VBInfo & SetCRT2ToSVIDEO ) )
temp |= 0x20 ;
}
}
XGINew_SetReg1( pVBInfo->Part2Port , 0x30 , temp ) ;
if ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) ) /* TV gatingno */
{
tempbx = pVBInfo->VDE ;
tempcx = tempbx - 2 ;
if ( pVBInfo->VBInfo & SetCRT2ToTV )
{
if ( !( pVBInfo->TVInfo & ( SetYPbPrMode525p | SetYPbPrMode750p ) ) )
tempbx = tempbx >> 1 ;
}
if ( pVBInfo->VBType & ( VB_XGI302LV | VB_XGI301C ) )
{
temp=0;
if( tempcx & 0x0400 )
temp |= 0x20 ;
if ( tempbx & 0x0400 )
temp |= 0x40 ;
XGINew_SetReg1( pVBInfo->Part4Port , 0x10 , temp ) ;
}
temp = ( ( ( tempbx - 3 ) & 0x0300 ) >> 8 ) << 5 ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x46 , temp ) ;
temp = ( tempbx - 3 ) & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x47 , temp ) ;
}
tempbx = tempbx & 0x00FF ;
if ( !( modeflag & HalfDCLK ) )
{
tempcx = pVBInfo->VGAHDE ;
if ( tempcx >= pVBInfo->HDE )
{
tempbx |= 0x2000 ;
tempax &= 0x00FF ;
}
}
tempcx = 0x0101 ;
if( pVBInfo->VBInfo & SetCRT2ToTV ) { /*301b*/
if(pVBInfo->VGAHDE>=1024)
{
tempcx=0x1920;
if(pVBInfo->VGAHDE>=1280)
{
tempcx=0x1420;
tempbx=tempbx&0xDFFF;
}
}
}
if ( !( tempbx & 0x2000 ) )
{
if ( modeflag & HalfDCLK )
{
tempcx = ( tempcx & 0xFF00 ) | ( ( tempcx & 0x00FF ) << 1 ) ;
}
push1 = tempbx ;
tempeax = pVBInfo->VGAHDE ;
tempebx = ( tempcx & 0xFF00 ) >> 8 ;
longtemp = tempeax * tempebx ;
tempecx = tempcx & 0x00FF ;
longtemp = longtemp / tempecx ;
/* 301b */
tempecx = 8 * 1024 ;
if ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{
tempecx = tempecx * 8 ;
}
longtemp = longtemp * tempecx ;
tempecx = pVBInfo->HDE ;
temp2 = longtemp % tempecx ;
tempeax = longtemp / tempecx ;
if ( temp2 != 0 )
{
tempeax += 1 ;
}
tempax = (unsigned short)tempeax;
/* 301b */
if ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{
tempcx = ( ( tempax & 0xFF00 ) >> 5 ) >> 8 ;
}
/* end 301b */
tempbx = push1 ;
tempbx = (unsigned short)(((tempeax & 0x0000FF00) & 0x1F00) | (tempbx & 0x00FF));
tempax = (unsigned short)(((tempeax & 0x000000FF) << 8) | (tempax & 0x00FF));
temp = ( tempax & 0xFF00 ) >> 8 ;
}
else
{
temp = ( tempax & 0x00FF ) >> 8 ;
}
XGINew_SetReg1( pVBInfo->Part2Port , 0x44 , temp ) ;
temp = ( tempbx & 0xFF00 ) >> 8 ;
XGINew_SetRegANDOR( pVBInfo->Part2Port , 0x45 , ~0x03F , temp ) ;
temp = tempcx & 0x00FF ;
if ( tempbx & 0x2000 )
temp = 0 ;
if ( !( pVBInfo->VBInfo & SetCRT2ToLCD ) )
temp |= 0x18 ;
XGINew_SetRegANDOR(pVBInfo->Part2Port,0x46,~0x1F,temp);
if ( pVBInfo->TVInfo & SetPALTV )
{
tempbx = 0x0382 ;
tempcx = 0x007e ;
}
else
{
tempbx = 0x0369 ;
tempcx = 0x0061 ;
}
temp = tempbx & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x4b , temp ) ;
temp = tempcx & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x4c , temp ) ;
temp = ( ( tempcx & 0xFF00 ) >> 8 ) & 0x03 ;
temp = temp << 2 ;
temp |= ( ( tempbx & 0xFF00 ) >> 8 ) & 0x03 ;
if ( pVBInfo->VBInfo & SetCRT2ToYPbPr )
{
temp |= 0x10 ;
if ( pVBInfo->TVInfo & SetYPbPrMode525p )
temp |= 0x20 ;
if ( pVBInfo->TVInfo & SetYPbPrMode750p )
temp |= 0x60 ;
}
XGINew_SetReg1( pVBInfo->Part2Port , 0x4d , temp ) ;
temp=XGINew_GetReg1( pVBInfo->Part2Port , 0x43 ) ; /* 301b change */
XGINew_SetReg1( pVBInfo->Part2Port , 0x43, (unsigned short)( temp - 3 ) ) ;
if ( !( pVBInfo->TVInfo & ( SetYPbPrMode525p | SetYPbPrMode750p ) ) )
{
if ( pVBInfo->TVInfo & NTSC1024x768 )
{
TimingPoint = XGI_NTSC1024AdjTime ;
for( i = 0x1c , j = 0 ; i <= 0x30 ; i++ , j++ )
{
XGINew_SetReg1( pVBInfo->Part2Port , i , TimingPoint[ j ] ) ;
}
XGINew_SetReg1( pVBInfo->Part2Port , 0x43 , 0x72 ) ;
}
}
/* [ycchen] 01/14/03 Modify for 301C PALM Support */
if ( pVBInfo->VBType & VB_XGI301C )
{
if ( pVBInfo->TVInfo & SetPALMTV )
XGINew_SetRegANDOR( pVBInfo->Part2Port , 0x4E , ~0x08 , 0x08 ) ; /* PALM Mode */
}
if ( pVBInfo->TVInfo & SetPALMTV )
{
tempax = (unsigned char)XGINew_GetReg1(pVBInfo->Part2Port, 0x01);
tempax-- ;
XGINew_SetRegAND( pVBInfo->Part2Port , 0x01 , tempax ) ;
/* if ( !( pVBInfo->VBType & VB_XGI301C ) ) */
XGINew_SetRegAND( pVBInfo->Part2Port , 0x00 , 0xEF ) ;
}
if ( pVBInfo->VBInfo & SetCRT2ToHiVisionTV )
{
if ( !( pVBInfo->VBInfo & SetInSlaveMode ) )
{
XGINew_SetReg1( pVBInfo->Part2Port , 0x0B , 0x00 ) ;
}
}
if ( pVBInfo->VBInfo & SetCRT2ToTV )
{
return ;
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetLCDRegs */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetLCDRegs(unsigned short ModeNo, unsigned short ModeIdIndex, struct xgi_hw_device_info *HwDeviceExtension, unsigned short RefreshRateTableIndex, struct vb_device_info *pVBInfo)
{
unsigned short push1 ,
push2 ,
pushbx ,
tempax ,
tempbx ,
tempcx ,
temp ,
tempah ,
tempbh ,
tempch ,
resinfo ,
modeflag ,
CRT1Index ;
struct XGI_LCDDesStruct *LCDBDesPtr = NULL ;
if ( ModeNo <= 0x13 )
{
modeflag = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ; /* si+St_ResInfo */
resinfo = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ResInfo ;
}
else
{
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ; /* si+Ext_ResInfo */
resinfo = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_RESINFO ;
CRT1Index = pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_CRT1CRTC ;
CRT1Index &= IndexMask ;
}
if ( !( pVBInfo->VBInfo & SetCRT2ToLCD ) )
{
return ;
}
tempbx = pVBInfo->HDE ; /* RHACTE=HDE-1 */
if ( XGI_IsLCDDualLink( pVBInfo ) )
tempbx = tempbx >> 1 ;
tempbx -= 1 ;
temp = tempbx & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x2C , temp ) ;
temp = ( tempbx & 0xFF00 ) >> 8 ;
temp = temp << 4 ;
XGINew_SetRegANDOR( pVBInfo->Part2Port , 0x2B , 0x0F , temp ) ;
temp = 0x01 ;
if ( pVBInfo->LCDResInfo == Panel1280x1024 )
{
if ( pVBInfo->ModeType == ModeEGA )
{
if ( pVBInfo->VGAHDE >= 1024 )
{
temp = 0x02 ;
if ( pVBInfo->LCDInfo & LCDVESATiming )
temp = 0x01 ;
}
}
}
XGINew_SetReg1( pVBInfo->Part2Port , 0x0B , temp ) ;
tempbx = pVBInfo->VDE ; /* RTVACTEO=(VDE-1)&0xFF */
push1 = tempbx ;
tempbx-- ;
temp = tempbx & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x03 , temp ) ;
temp = ( ( tempbx & 0xFF00 ) >> 8 ) & 0x07 ;
XGINew_SetRegANDOR( pVBInfo->Part2Port , 0x0C , ~0x07 , temp ) ;
tempcx = pVBInfo->VT - 1 ;
push2 = tempcx + 1 ;
temp = tempcx & 0x00FF ; /* RVTVT=VT-1 */
XGINew_SetReg1( pVBInfo->Part2Port , 0x19 , temp ) ;
temp = ( tempcx & 0xFF00 ) >> 8 ;
temp = temp << 5 ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x1A , temp ) ;
XGINew_SetRegANDOR( pVBInfo->Part2Port , 0x09 , 0xF0 , 0x00 ) ;
XGINew_SetRegANDOR( pVBInfo->Part2Port , 0x0A , 0xF0 , 0x00 ) ;
XGINew_SetRegANDOR( pVBInfo->Part2Port , 0x17 , 0xFB , 0x00 ) ;
XGINew_SetRegANDOR( pVBInfo->Part2Port , 0x18 , 0xDF , 0x00 ) ;
/* Customized LCDB Des no add */
tempbx = 5 ;
LCDBDesPtr = (struct XGI_LCDDesStruct *)XGI_GetLcdPtr(tempbx, ModeNo, ModeIdIndex, RefreshRateTableIndex, pVBInfo);
tempah = pVBInfo->LCDResInfo ;
tempah &= PanelResInfo ;
if ( ( tempah == Panel1024x768 ) || ( tempah == Panel1024x768x75 ) )
{
tempbx = 1024 ;
tempcx = 768 ;
}
else if ( ( tempah == Panel1280x1024 ) || ( tempah == Panel1280x1024x75 ) )
{
tempbx = 1280 ;
tempcx = 1024 ;
}
else if ( tempah == Panel1400x1050 )
{
tempbx = 1400 ;
tempcx = 1050 ;
}
else
{
tempbx = 1600 ;
tempcx = 1200 ;
}
if ( pVBInfo->LCDInfo & EnableScalingLCD )
{
tempbx = pVBInfo->HDE ;
tempcx = pVBInfo->VDE ;
}
pushbx = tempbx ;
tempax = pVBInfo->VT ;
pVBInfo->LCDHDES = LCDBDesPtr->LCDHDES ;
pVBInfo->LCDHRS = LCDBDesPtr->LCDHRS ;
pVBInfo->LCDVDES = LCDBDesPtr->LCDVDES ;
pVBInfo->LCDVRS = LCDBDesPtr->LCDVRS ;
tempbx = pVBInfo->LCDVDES ;
tempcx += tempbx ;
if ( tempcx >= tempax )
tempcx -= tempax ; /* lcdvdes */
temp = tempbx & 0x00FF ; /* RVEQ1EQ=lcdvdes */
XGINew_SetReg1( pVBInfo->Part2Port , 0x05 , temp ) ;
temp = tempcx & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x06 , temp ) ;
tempch = ( ( tempcx & 0xFF00 ) >> 8 ) & 0x07 ;
tempbh = ( ( tempbx & 0xFF00 ) >> 8 ) & 0x07 ;
tempah = tempch ;
tempah = tempah << 3 ;
tempah |= tempbh ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x02 , tempah ) ;
/* getlcdsync() */
XGI_GetLCDSync( &tempax , &tempbx,pVBInfo ) ;
tempcx = tempbx ;
tempax = pVBInfo->VT ;
tempbx = pVBInfo->LCDVRS ;
/* if ( SetLCD_Info & EnableScalingLCD ) */
tempcx += tempbx ;
if ( tempcx >= tempax )
tempcx -= tempax ;
temp = tempbx & 0x00FF ; /* RTVACTEE=lcdvrs */
XGINew_SetReg1( pVBInfo->Part2Port , 0x04 , temp ) ;
temp = ( tempbx & 0xFF00 ) >> 8 ;
temp = temp << 4 ;
temp |= ( tempcx & 0x000F ) ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x01 , temp ) ;
tempcx = pushbx ;
tempax = pVBInfo->HT ;
tempbx = pVBInfo->LCDHDES ;
tempbx &= 0x0FFF ;
if ( XGI_IsLCDDualLink( pVBInfo ) )
{
tempax = tempax >> 1 ;
tempbx = tempbx >> 1 ;
tempcx = tempcx >> 1 ;
}
if ( pVBInfo->VBType & VB_XGI302LV )
tempbx += 1 ;
if ( pVBInfo->VBType & VB_XGI301C ) /* tap4 */
tempbx += 1 ;
tempcx += tempbx ;
if ( tempcx >= tempax )
tempcx -= tempax ;
temp = tempbx & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x1F , temp ) ; /* RHBLKE=lcdhdes */
temp = ( ( tempbx & 0xFF00 ) >> 8 ) << 4 ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x20 , temp ) ;
temp = tempcx & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x23 , temp ) ; /* RHEQPLE=lcdhdee */
temp = ( tempcx & 0xFF00 ) >> 8 ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x25 , temp ) ;
/* getlcdsync() */
XGI_GetLCDSync( &tempax , &tempbx ,pVBInfo) ;
tempcx = tempax ;
tempax = pVBInfo->HT ;
tempbx = pVBInfo->LCDHRS ;
/* if ( SetLCD_Info & EnableScalingLCD) */
if ( XGI_IsLCDDualLink( pVBInfo) )
{
tempax = tempax >> 1 ;
tempbx = tempbx >> 1 ;
tempcx = tempcx >> 1 ;
}
if ( pVBInfo->VBType & VB_XGI302LV )
tempbx += 1 ;
tempcx += tempbx ;
if ( tempcx >= tempax )
tempcx -= tempax ;
temp = tempbx & 0x00FF ; /* RHBURSTS=lcdhrs */
XGINew_SetReg1( pVBInfo->Part2Port , 0x1C , temp ) ;
temp = ( tempbx & 0xFF00 ) >> 8 ;
temp = temp << 4 ;
XGINew_SetRegANDOR( pVBInfo->Part2Port , 0x1D , ~0x0F0 , temp ) ;
temp = tempcx & 0x00FF ; /* RHSYEXP2S=lcdhre */
XGINew_SetReg1( pVBInfo->Part2Port , 0x21 , temp ) ;
if ( !( pVBInfo->LCDInfo & LCDVESATiming ) )
{
if ( pVBInfo->VGAVDE == 525 )
{
if ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{
temp = 0xC6 ;
}
else
temp = 0xC4 ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x2f , temp ) ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x30 , 0xB3 ) ;
}
if ( pVBInfo->VGAVDE == 420 )
{
if ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{
temp = 0x4F ;
}
else
temp = 0x4E ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x2f , temp ) ;
}
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetTap4Ptr */
/* Input : */
/* Output : di -> Tap4 Reg. Setting Pointer */
/* Description : */
/* --------------------------------------------------------------------- */
struct XGI301C_Tap4TimingStruct *XGI_GetTap4Ptr(unsigned short tempcx,
struct vb_device_info *pVBInfo)
{
unsigned short tempax ,
tempbx ,
i ;
struct XGI301C_Tap4TimingStruct *Tap4TimingPtr ;
if ( tempcx == 0 )
{
tempax = pVBInfo->VGAHDE ;
tempbx = pVBInfo->HDE ;
}
else
{
tempax = pVBInfo->VGAVDE ;
tempbx = pVBInfo->VDE ;
}
if ( tempax < tempbx )
return &EnlargeTap4Timing[ 0 ] ;
else if( tempax == tempbx )
return &NoScaleTap4Timing[ 0 ] ; /* 1:1 */
else
Tap4TimingPtr = NTSCTap4Timing ; /* NTSC */
if ( pVBInfo->TVInfo & SetPALTV )
Tap4TimingPtr = PALTap4Timing ;
if ( pVBInfo->VBInfo & SetCRT2ToYPbPr )
{
if ( pVBInfo->TVInfo & SetYPbPrMode525i )
Tap4TimingPtr = YPbPr525iTap4Timing ;
if ( pVBInfo->TVInfo & SetYPbPrMode525p )
Tap4TimingPtr = YPbPr525pTap4Timing ;
if ( pVBInfo->TVInfo & SetYPbPrMode750p )
Tap4TimingPtr = YPbPr750pTap4Timing ;
}
if ( pVBInfo->VBInfo & SetCRT2ToHiVisionTV )
Tap4TimingPtr = HiTVTap4Timing ;
i = 0 ;
while( Tap4TimingPtr[ i ].DE != 0xFFFF )
{
if ( Tap4TimingPtr[ i ].DE == tempax )
break ;
i++ ;
}
return &Tap4TimingPtr[ i ] ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetTap4Regs */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetTap4Regs(struct vb_device_info *pVBInfo)
{
unsigned short i ,
j ;
struct XGI301C_Tap4TimingStruct *Tap4TimingPtr ;
if ( !( pVBInfo->VBType & VB_XGI301C ) )
return ;
#ifndef Tap4
XGINew_SetRegAND( pVBInfo->Part2Port , 0x4E , 0xEB ) ; /* Disable Tap4 */
#else /* Tap4 Setting */
Tap4TimingPtr = XGI_GetTap4Ptr( 0 , pVBInfo) ; /* Set Horizontal Scaling */
for( i = 0x80 , j = 0 ; i <= 0xBF ; i++ , j++ )
XGINew_SetReg1( pVBInfo->Part2Port , i , Tap4TimingPtr->Reg[ j ] ) ;
if ( ( pVBInfo->VBInfo & SetCRT2ToTV ) && ( !( pVBInfo->VBInfo & SetCRT2ToHiVisionTV ) ) )
{
Tap4TimingPtr = XGI_GetTap4Ptr( 1 , pVBInfo); /* Set Vertical Scaling */
for( i = 0xC0 , j = 0 ; i < 0xFF ; i++ , j++ )
XGINew_SetReg1( pVBInfo->Part2Port , i , Tap4TimingPtr->Reg[ j ] ) ;
}
if ( ( pVBInfo->VBInfo & SetCRT2ToTV ) && ( !( pVBInfo->VBInfo & SetCRT2ToHiVisionTV ) ) )
XGINew_SetRegANDOR( pVBInfo->Part2Port , 0x4E , ~0x14 , 0x04 ) ; /* Enable V.Scaling */
else
XGINew_SetRegANDOR( pVBInfo->Part2Port , 0x4E , ~0x14 , 0x10 ) ; /* Enable H.Scaling */
#endif
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetGroup3 */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetGroup3(unsigned short ModeNo, unsigned short ModeIdIndex, struct vb_device_info *pVBInfo)
{
unsigned short i;
unsigned char *tempdi;
unsigned short modeflag;
if(ModeNo<=0x13)
{
modeflag = pVBInfo->SModeIDTable[ModeIdIndex].St_ModeFlag; /* si+St_ResInfo */
}
else
{
modeflag = pVBInfo->EModeIDTable[ModeIdIndex].Ext_ModeFlag; /* si+Ext_ResInfo */
}
XGINew_SetReg1(pVBInfo->Part3Port,0x00,0x00);
if(pVBInfo->TVInfo&SetPALTV)
{
XGINew_SetReg1(pVBInfo->Part3Port,0x13,0xFA);
XGINew_SetReg1(pVBInfo->Part3Port,0x14,0xC8);
}
else
{
XGINew_SetReg1(pVBInfo->Part3Port,0x13,0xF5);
XGINew_SetReg1(pVBInfo->Part3Port,0x14,0xB7);
}
if(!(pVBInfo->VBInfo&SetCRT2ToTV))
{
return;
}
if(pVBInfo->TVInfo&SetPALMTV)
{
XGINew_SetReg1(pVBInfo->Part3Port,0x13,0xFA);
XGINew_SetReg1(pVBInfo->Part3Port,0x14,0xC8);
XGINew_SetReg1(pVBInfo->Part3Port,0x3D,0xA8);
}
if((pVBInfo->VBInfo&SetCRT2ToHiVisionTV)|| (pVBInfo->VBInfo&SetCRT2ToYPbPr))
{
if(pVBInfo->TVInfo & SetYPbPrMode525i)
{
return;
}
tempdi=pVBInfo->HiTVGroup3Data;
if(pVBInfo->SetFlag&TVSimuMode)
{
tempdi=pVBInfo->HiTVGroup3Simu;
if(!(modeflag&Charx8Dot))
{
tempdi=pVBInfo->HiTVGroup3Text;
}
}
if(pVBInfo->TVInfo & SetYPbPrMode525p)
{
tempdi=pVBInfo->Ren525pGroup3;
}
if(pVBInfo->TVInfo & SetYPbPrMode750p)
{
tempdi=pVBInfo->Ren750pGroup3;
}
for(i=0;i<=0x3E;i++)
{
XGINew_SetReg1(pVBInfo->Part3Port,i,tempdi[i]);
}
if(pVBInfo->VBType&VB_XGI301C) /* Marcovision */
{
if(pVBInfo->TVInfo & SetYPbPrMode525p)
{
XGINew_SetReg1(pVBInfo->Part3Port,0x28,0x3f);
}
}
}
return;
} /* {end of XGI_SetGroup3} */
/* --------------------------------------------------------------------- */
/* Function : XGI_SetGroup4 */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetGroup4(unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex, struct xgi_hw_device_info *HwDeviceExtension, struct vb_device_info *pVBInfo)
{
unsigned short tempax ,
tempcx ,
tempbx ,
modeflag ,
temp ,
temp2 ;
unsigned long tempebx ,
tempeax ,
templong ;
if ( ModeNo <= 0x13 )
{
modeflag = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ; /* si+St_ResInfo */
}
else
{
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ; /* si+Ext_ResInfo */
}
temp = pVBInfo->RVBHCFACT ;
XGINew_SetReg1( pVBInfo->Part4Port , 0x13 , temp ) ;
tempbx = pVBInfo->RVBHCMAX ;
temp = tempbx & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part4Port , 0x14 , temp ) ;
temp2 = ( ( tempbx & 0xFF00 ) >> 8 ) << 7 ;
tempcx = pVBInfo->VGAHT - 1 ;
temp = tempcx & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part4Port , 0x16 , temp ) ;
temp =( ( tempcx & 0xFF00 ) >> 8 ) << 3 ;
temp2 |= temp ;
tempcx = pVBInfo->VGAVT - 1 ;
if ( !( pVBInfo->VBInfo & SetCRT2ToTV ) )
{
tempcx -= 5 ;
}
temp = tempcx & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part4Port , 0x17 , temp ) ;
temp = temp2 | ( ( tempcx & 0xFF00 ) >> 8 ) ;
XGINew_SetReg1( pVBInfo->Part4Port , 0x15 , temp ) ;
XGINew_SetRegOR( pVBInfo->Part4Port , 0x0D , 0x08 ) ;
tempcx = pVBInfo->VBInfo ;
tempbx = pVBInfo->VGAHDE ;
if ( modeflag & HalfDCLK )
{
tempbx = tempbx >> 1 ;
}
if ( XGI_IsLCDDualLink( pVBInfo ) )
tempbx = tempbx >> 1 ;
if(tempcx&SetCRT2ToHiVisionTV)
{
temp=0;
if(tempbx<=1024)
temp=0xA0;
if(tempbx == 1280)
temp = 0xC0;
}
else if(tempcx&SetCRT2ToTV)
{
temp=0xA0;
if(tempbx <= 800)
temp=0x80;
}
else
{
temp=0x80;
if(pVBInfo->VBInfo&SetCRT2ToLCD)
{
temp=0;
if(tempbx>800)
temp=0x60;
}
}
if ( pVBInfo->TVInfo & ( SetYPbPrMode525p | SetYPbPrMode750p ) )
{
temp = 0x00 ;
if ( pVBInfo->VGAHDE == 1280 )
temp = 0x40 ;
if ( pVBInfo->VGAHDE == 1024 )
temp = 0x20 ;
}
XGINew_SetRegANDOR( pVBInfo->Part4Port , 0x0E , ~0xEF , temp ) ;
tempebx = pVBInfo->VDE ;
if ( tempcx & SetCRT2ToHiVisionTV )
{
if ( !( temp & 0xE000 ) )
tempbx = tempbx >> 1 ;
}
tempcx = pVBInfo->RVBHRS ;
temp = tempcx & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part4Port , 0x18 , temp );
tempeax = pVBInfo->VGAVDE ;
tempcx |= 0x04000 ;
if ( tempeax <= tempebx )
{
tempcx=(tempcx&(~0x4000));
tempeax = pVBInfo->VGAVDE ;
}
else
{
tempeax -= tempebx ;
}
templong = ( tempeax * 256 * 1024 ) % tempebx ;
tempeax = ( tempeax * 256 * 1024 ) / tempebx ;
tempebx = tempeax ;
if ( templong != 0 )
{
tempebx++ ;
}
temp = (unsigned short)(tempebx & 0x000000FF);
XGINew_SetReg1( pVBInfo->Part4Port , 0x1B , temp ) ;
temp = (unsigned short)((tempebx & 0x0000FF00) >> 8);
XGINew_SetReg1( pVBInfo->Part4Port , 0x1A , temp ) ;
tempbx = (unsigned short)(tempebx >> 16);
temp = tempbx & 0x00FF ;
temp = temp << 4 ;
temp |= ( ( tempcx & 0xFF00 ) >> 8 ) ;
XGINew_SetReg1( pVBInfo->Part4Port , 0x19 , temp ) ;
/* 301b */
if ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{
temp = 0x0028 ;
XGINew_SetReg1( pVBInfo->Part4Port , 0x1C , temp ) ;
tempax = pVBInfo->VGAHDE ;
if ( modeflag & HalfDCLK )
{
tempax = tempax >> 1 ;
}
if ( XGI_IsLCDDualLink( pVBInfo ) )
tempax = tempax >> 1 ;
/* if((pVBInfo->VBInfo&(SetCRT2ToLCD))||((pVBInfo->TVInfo&SetYPbPrMode525p)||(pVBInfo->TVInfo&SetYPbPrMode750p))) { */
if ( pVBInfo->VBInfo & SetCRT2ToLCD )
{
if ( tempax > 800 )
tempax -= 800 ;
}
else
{
if ( pVBInfo->VGAHDE > 800 )
{
if ( pVBInfo->VGAHDE == 1024 )
tempax = ( tempax * 25 / 32 ) - 1 ;
else
tempax = ( tempax * 20 / 32 ) - 1 ;
}
}
tempax -= 1 ;
/*
if ( pVBInfo->VBInfo & ( SetCRT2ToTV | SetCRT2ToHiVisionTV ) )
{
if ( pVBInfo->VBType & VB_XGI301LV )
{
if ( !( pVBInfo->TVInfo & ( SetYPbPrMode525p | SetYPbPrMode750p | SetYPbPrMode1080i ) ) )
{
if ( pVBInfo->VGAHDE > 800 )
{
if ( pVBInfo->VGAHDE == 1024 )
tempax = ( tempax * 25 / 32 ) - 1 ;
else
tempax = ( tempax * 20 / 32 ) - 1 ;
}
}
}
else
{
if ( pVBInfo->VGAHDE > 800 )
{
if ( pVBInfo->VGAHDE == 1024 )
tempax = ( tempax * 25 / 32 ) - 1 ;
else
tempax = ( tempax * 20 / 32 ) - 1 ;
}
}
}
*/
temp = ( tempax & 0xFF00 ) >> 8 ;
temp = ( ( temp & 0x0003 ) << 4 ) ;
XGINew_SetReg1( pVBInfo->Part4Port , 0x1E , temp ) ;
temp = ( tempax & 0x00FF ) ;
XGINew_SetReg1( pVBInfo->Part4Port , 0x1D , temp ) ;
if ( pVBInfo->VBInfo & ( SetCRT2ToTV | SetCRT2ToHiVisionTV ) )
{
if ( pVBInfo->VGAHDE > 800 )
{
XGINew_SetRegOR( pVBInfo->Part4Port , 0x1E , 0x08 ) ;
}
}
temp = 0x0036 ;
if ( pVBInfo->VBInfo & SetCRT2ToTV )
{
if ( !( pVBInfo->TVInfo & ( NTSC1024x768 | SetYPbPrMode525p | SetYPbPrMode750p | SetYPbPrMode1080i ) ) )
{
temp |= 0x0001 ;
if ( ( pVBInfo->VBInfo & SetInSlaveMode ) && ( !( pVBInfo->TVInfo & TVSimuMode ) ) )
temp &= ( ~0x0001 ) ;
}
}
XGINew_SetRegANDOR( pVBInfo->Part4Port , 0x1F , 0x00C0 , temp ) ;
tempbx = pVBInfo->HT ;
if ( XGI_IsLCDDualLink( pVBInfo ) )
tempbx = tempbx >> 1 ;
tempbx = ( tempbx >> 1 ) - 2 ;
temp = ( ( tempbx & 0x0700 ) >> 8 ) << 3 ;
XGINew_SetRegANDOR( pVBInfo->Part4Port , 0x21 , 0x00C0 , temp ) ;
temp = tempbx & 0x00FF ;
XGINew_SetReg1( pVBInfo->Part4Port , 0x22 , temp ) ;
}
/* end 301b */
if ( pVBInfo->ISXPDOS == 0 )
XGI_SetCRT2VCLK( ModeNo , ModeIdIndex , RefreshRateTableIndex, pVBInfo ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetGroup5 */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetGroup5(unsigned short ModeNo, unsigned short ModeIdIndex, struct vb_device_info *pVBInfo)
{
unsigned short Pindex ,
Pdata ;
Pindex = pVBInfo->Part5Port ;
Pdata = pVBInfo->Part5Port + 1 ;
if ( pVBInfo->ModeType == ModeVGA )
{
if ( !( pVBInfo->VBInfo & ( SetInSlaveMode | LoadDACFlag | CRT2DisplayFlag ) ) )
{
XGINew_EnableCRT2(pVBInfo) ;
/* LoadDAC2(pVBInfo->Part5Port,ModeNo,ModeIdIndex); */
}
}
return ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetLcdPtr */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void *XGI_GetLcdPtr(unsigned short BX,
unsigned short ModeNo,
unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned short i ,
tempdx ,
tempcx ,
tempbx ,
tempal ,
modeflag ,
table ;
struct XGI330_LCDDataTablStruct *tempdi = 0 ;
tempbx = BX;
if ( ModeNo <= 0x13 )
{
modeflag = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ;
tempal = pVBInfo->SModeIDTable[ ModeIdIndex ].St_CRT2CRTC ;
}
else
{
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ;
tempal = pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_CRT2CRTC ;
}
tempal = tempal & 0x0f ;
if ( tempbx <= 1 ) /* ExpLink */
{
if ( ModeNo <= 0x13 )
{
tempal = pVBInfo->SModeIDTable[ ModeIdIndex ].St_CRT2CRTC ; /* find no Ext_CRT2CRTC2 */
}
else
{
tempal= pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_CRT2CRTC ;
}
if ( pVBInfo->VBInfo & SetCRT2ToLCDA )
{
if ( ModeNo <= 0x13 )
tempal = pVBInfo->SModeIDTable[ ModeIdIndex ].St_CRT2CRTC2 ;
else
tempal= pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_CRT2CRTC2 ;
}
if ( tempbx & 0x01 )
tempal = ( tempal >> 4 ) ;
tempal = ( tempal & 0x0f ) ;
}
tempcx = LCDLenList[ tempbx ] ; /* mov cl,byte ptr cs:LCDLenList[bx] */
if ( pVBInfo->LCDInfo & EnableScalingLCD ) /* ScaleLCD */
{
if ( ( tempbx == 5 ) || ( tempbx ) == 7 )
tempcx = LCDDesDataLen2 ;
else if ( ( tempbx == 3 ) || ( tempbx == 8 ) )
tempcx = LVDSDesDataLen2 ;
}
/* mov di, word ptr cs:LCDDataList[bx] */
/* tempdi=pVideoMemory[LCDDataList+tempbx*2]|(pVideoMemory[LCDDataList+tempbx*2+1]<<8); */
switch( tempbx )
{
case 0:
tempdi = XGI_EPLLCDCRT1Ptr_H ;
break ;
case 1:
tempdi = XGI_EPLLCDCRT1Ptr_V ;
break ;
case 2:
tempdi = XGI_EPLLCDDataPtr ;
break ;
case 3:
tempdi = XGI_EPLLCDDesDataPtr ;
break ;
case 4:
tempdi = XGI_LCDDataTable ;
break ;
case 5:
tempdi = XGI_LCDDesDataTable ;
break ;
case 6:
tempdi = XGI_EPLCHLCDRegPtr ;
break ;
case 7:
case 8:
case 9:
tempdi = 0 ;
break ;
default:
break ;
}
if ( tempdi == 0x00 ) /* OEMUtil */
return 0 ;
table = tempbx ;
i = 0 ;
while( tempdi[ i ].PANELID != 0xff )
{
tempdx = pVBInfo->LCDResInfo ;
if ( tempbx & 0x0080 ) /* OEMUtil */
{
tempbx &= ( ~0x0080 ) ;
tempdx = pVBInfo->LCDTypeInfo ;
}
if ( pVBInfo->LCDInfo & EnableScalingLCD )
tempdx &= ( ~PanelResInfo ) ;
if ( tempdi[ i ].PANELID == tempdx )
{
tempbx = tempdi[ i ].MASK ;
tempdx = pVBInfo->LCDInfo ;
if ( ModeNo <= 0x13 ) /* alan 09/10/2003 */
tempdx |= SetLCDStdMode ;
if ( modeflag & HalfDCLK )
tempdx |= SetLCDLowResolution ;
tempbx &= tempdx;
if ( tempbx == tempdi[ i ].CAP )
break ;
}
i++ ;
}
if ( table == 0 )
{
switch( tempdi[ i ].DATAPTR )
{
case 0:
return &XGI_LVDSCRT11024x768_1_H[ tempal ] ;
break ;
case 1:
return &XGI_LVDSCRT11024x768_2_H[ tempal ] ;
break ;
case 2:
return &XGI_LVDSCRT11280x1024_1_H[ tempal ] ;
break ;
case 3:
return &XGI_LVDSCRT11280x1024_2_H[ tempal ] ;
break ;
case 4:
return &XGI_LVDSCRT11400x1050_1_H[ tempal ] ;
break ;
case 5:
return &XGI_LVDSCRT11400x1050_2_H[ tempal ] ;
break ;
case 6:
return &XGI_LVDSCRT11600x1200_1_H[ tempal ] ;
break ;
case 7:
return &XGI_LVDSCRT11024x768_1_Hx75[ tempal ] ;
break ;
case 8:
return &XGI_LVDSCRT11024x768_2_Hx75[ tempal ] ;
break ;
case 9:
return &XGI_LVDSCRT11280x1024_1_Hx75[ tempal ] ;
break ;
case 10:
return &XGI_LVDSCRT11280x1024_2_Hx75[ tempal ] ;
break ;
default:
break ;
}
}
else if ( table == 1 )
{
switch( tempdi[ i ].DATAPTR )
{
case 0:
return &XGI_LVDSCRT11024x768_1_V[ tempal ] ;
break ;
case 1:
return &XGI_LVDSCRT11024x768_2_V[ tempal ] ;
break ;
case 2:
return &XGI_LVDSCRT11280x1024_1_V[ tempal ] ;
break ;
case 3:
return &XGI_LVDSCRT11280x1024_2_V[ tempal ] ;
break ;
case 4:
return &XGI_LVDSCRT11400x1050_1_V[ tempal ] ;
break ;
case 5:
return &XGI_LVDSCRT11400x1050_2_V[ tempal ] ;
break ;
case 6:
return &XGI_LVDSCRT11600x1200_1_V[ tempal ] ;
break ;
case 7:
return &XGI_LVDSCRT11024x768_1_Vx75[ tempal ] ;
break ;
case 8:
return &XGI_LVDSCRT11024x768_2_Vx75[ tempal ] ;
break ;
case 9:
return &XGI_LVDSCRT11280x1024_1_Vx75[ tempal ] ;
break ;
case 10:
return &XGI_LVDSCRT11280x1024_2_Vx75[ tempal ] ;
break ;
default:
break ;
}
}
else if ( table == 2 )
{
switch( tempdi[ i ].DATAPTR )
{
case 0:
return &XGI_LVDS1024x768Data_1[ tempal ] ;
break ;
case 1:
return &XGI_LVDS1024x768Data_2[ tempal ] ;
break ;
case 2:
return &XGI_LVDS1280x1024Data_1[ tempal ] ;
break ;
case 3:
return &XGI_LVDS1280x1024Data_2[ tempal ] ;
break ;
case 4:
return &XGI_LVDS1400x1050Data_1[ tempal ] ;
break ;
case 5:
return &XGI_LVDS1400x1050Data_2[ tempal ] ;
break ;
case 6:
return &XGI_LVDS1600x1200Data_1[ tempal ] ;
break ;
case 7:
return &XGI_LVDSNoScalingData[ tempal ] ;
break ;
case 8:
return &XGI_LVDS1024x768Data_1x75[ tempal ] ;
break ;
case 9:
return &XGI_LVDS1024x768Data_2x75[ tempal ] ;
break ;
case 10:
return &XGI_LVDS1280x1024Data_1x75[ tempal ] ;
break ;
case 11:
return &XGI_LVDS1280x1024Data_2x75[ tempal ] ;
break ;
case 12:
return &XGI_LVDSNoScalingDatax75[ tempal ] ;
break ;
default:
break ;
}
}
else if ( table == 3 )
{
switch( tempdi[ i ].DATAPTR )
{
case 0:
return &XGI_LVDS1024x768Des_1[ tempal ] ;
break ;
case 1:
return &XGI_LVDS1024x768Des_3[ tempal ] ;
break ;
case 2:
return &XGI_LVDS1024x768Des_2[ tempal ] ;
break ;
case 3:
return &XGI_LVDS1280x1024Des_1[ tempal ] ;
break ;
case 4:
return &XGI_LVDS1280x1024Des_2[ tempal ] ;
break ;
case 5:
return &XGI_LVDS1400x1050Des_1[ tempal ] ;
break ;
case 6:
return &XGI_LVDS1400x1050Des_2[ tempal ] ;
break ;
case 7:
return &XGI_LVDS1600x1200Des_1[ tempal ] ;
break ;
case 8:
return &XGI_LVDSNoScalingDesData[ tempal ] ;
break ;
case 9:
return &XGI_LVDS1024x768Des_1x75[ tempal ] ;
break ;
case 10:
return &XGI_LVDS1024x768Des_3x75[ tempal ] ;
break ;
case 11:
return &XGI_LVDS1024x768Des_2x75[ tempal ] ;
break;
case 12:
return &XGI_LVDS1280x1024Des_1x75[ tempal ] ;
break ;
case 13:
return &XGI_LVDS1280x1024Des_2x75[ tempal ] ;
break ;
case 14:
return &XGI_LVDSNoScalingDesDatax75[ tempal ] ;
break ;
default:
break ;
}
}
else if ( table == 4 )
{
switch( tempdi[ i ].DATAPTR )
{
case 0:
return &XGI_ExtLCD1024x768Data[ tempal ] ;
break ;
case 1:
return &XGI_StLCD1024x768Data[ tempal ] ;
break ;
case 2:
return &XGI_CetLCD1024x768Data[ tempal ] ;
break ;
case 3:
return &XGI_ExtLCD1280x1024Data[ tempal ] ;
break ;
case 4:
return &XGI_StLCD1280x1024Data[ tempal ] ;
break ;
case 5:
return &XGI_CetLCD1280x1024Data[ tempal ] ;
break ;
case 6:
return &XGI_ExtLCD1400x1050Data[ tempal ] ;
break ;
case 7:
return &XGI_StLCD1400x1050Data[ tempal ] ;
break ;
case 8:
return &XGI_CetLCD1400x1050Data[ tempal ] ;
break ;
case 9:
return &XGI_ExtLCD1600x1200Data[ tempal ] ;
break ;
case 10:
return &XGI_StLCD1600x1200Data[ tempal ] ;
break ;
case 11:
return &XGI_NoScalingData[ tempal ] ;
break ;
case 12:
return &XGI_ExtLCD1024x768x75Data[ tempal ] ;
break ;
case 13:
return &XGI_ExtLCD1024x768x75Data[ tempal ] ;
break ;
case 14:
return &XGI_CetLCD1024x768x75Data[ tempal ] ;
break ;
case 15:
return &XGI_ExtLCD1280x1024x75Data[ tempal ] ;
break ;
case 16:
return &XGI_StLCD1280x1024x75Data[ tempal ] ;
break;
case 17:
return &XGI_CetLCD1280x1024x75Data[ tempal ] ;
break;
case 18:
return &XGI_NoScalingDatax75[ tempal ] ;
break ;
default:
break ;
}
}
else if ( table == 5 )
{
switch( tempdi[ i ].DATAPTR )
{
case 0:
return &XGI_ExtLCDDes1024x768Data[ tempal ] ;
break ;
case 1:
return &XGI_StLCDDes1024x768Data[ tempal ] ;
break ;
case 2:
return &XGI_CetLCDDes1024x768Data[ tempal ] ;
break ;
case 3:
if ( ( pVBInfo->VBType & VB_XGI301LV ) || ( pVBInfo->VBType & VB_XGI302LV ) )
return &XGI_ExtLCDDLDes1280x1024Data[ tempal ] ;
else
return &XGI_ExtLCDDes1280x1024Data[ tempal ] ;
break ;
case 4:
if ( ( pVBInfo->VBType & VB_XGI301LV ) || ( pVBInfo->VBType & VB_XGI302LV ) )
return &XGI_StLCDDLDes1280x1024Data[ tempal ] ;
else
return &XGI_StLCDDes1280x1024Data[ tempal ] ;
break ;
case 5:
if ( ( pVBInfo->VBType & VB_XGI301LV ) || ( pVBInfo->VBType & VB_XGI302LV ) )
return &XGI_CetLCDDLDes1280x1024Data[ tempal ] ;
else
return &XGI_CetLCDDes1280x1024Data[ tempal ] ;
break ;
case 6:
if ( ( pVBInfo->VBType & VB_XGI301LV ) || ( pVBInfo->VBType & VB_XGI302LV ) )
return &XGI_ExtLCDDLDes1400x1050Data[ tempal ] ;
else
return &XGI_ExtLCDDes1400x1050Data[ tempal ] ;
break ;
case 7:
if ( ( pVBInfo->VBType & VB_XGI301LV ) || ( pVBInfo->VBType & VB_XGI302LV ) )
return &XGI_StLCDDLDes1400x1050Data[ tempal ] ;
else
return &XGI_StLCDDes1400x1050Data[ tempal ] ;
break ;
case 8:
return &XGI_CetLCDDes1400x1050Data[ tempal ] ;
break ;
case 9:
return &XGI_CetLCDDes1400x1050Data2[ tempal ] ;
break ;
case 10:
if ( ( pVBInfo->VBType & VB_XGI301LV ) || ( pVBInfo->VBType & VB_XGI302LV ) )
return &XGI_ExtLCDDLDes1600x1200Data[ tempal ] ;
else
return &XGI_ExtLCDDes1600x1200Data[ tempal ] ;
break ;
case 11:
if ( ( pVBInfo->VBType & VB_XGI301LV ) || ( pVBInfo->VBType & VB_XGI302LV ) )
return &XGI_StLCDDLDes1600x1200Data[ tempal ] ;
else
return &XGI_StLCDDes1600x1200Data[ tempal ] ;
break ;
case 12:
return &XGI_NoScalingDesData[ tempal ] ;
break;
case 13:
return &XGI_ExtLCDDes1024x768x75Data[ tempal ] ;
break ;
case 14:
return &XGI_StLCDDes1024x768x75Data[ tempal ] ;
break ;
case 15:
return &XGI_CetLCDDes1024x768x75Data[ tempal ] ;
break ;
case 16:
if ( ( pVBInfo->VBType & VB_XGI301LV ) || ( pVBInfo->VBType & VB_XGI302LV ) )
return &XGI_ExtLCDDLDes1280x1024x75Data[ tempal ] ;
else
return &XGI_ExtLCDDes1280x1024x75Data[ tempal ] ;
break ;
case 17:
if ( ( pVBInfo->VBType & VB_XGI301LV ) || ( pVBInfo->VBType & VB_XGI302LV ) )
return &XGI_StLCDDLDes1280x1024x75Data[ tempal ] ;
else
return &XGI_StLCDDes1280x1024x75Data[ tempal ] ;
break ;
case 18:
if ( ( pVBInfo->VBType & VB_XGI301LV ) || ( pVBInfo->VBType & VB_XGI302LV ) )
return &XGI_CetLCDDLDes1280x1024x75Data[ tempal ] ;
else
return &XGI_CetLCDDes1280x1024x75Data[ tempal ] ;
break ;
case 19:
return &XGI_NoScalingDesDatax75[ tempal ] ;
break ;
default:
break ;
}
}
else if ( table == 6 )
{
switch( tempdi[ i ].DATAPTR )
{
case 0:
return &XGI_CH7017LV1024x768[ tempal ] ;
break ;
case 1:
return &XGI_CH7017LV1400x1050[ tempal ] ;
break ;
default:
break ;
}
}
return 0 ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetTVPtr */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void *XGI_GetTVPtr(unsigned short BX, unsigned short ModeNo,
unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct vb_device_info *pVBInfo)
{
unsigned short i , tempdx , tempbx , tempal , modeflag , table ;
struct XGI330_TVDataTablStruct *tempdi = 0 ;
tempbx = BX ;
if ( ModeNo <= 0x13 )
{
modeflag = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ;
tempal = pVBInfo->SModeIDTable[ ModeIdIndex ].St_CRT2CRTC ;
}
else
{
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ;
tempal = pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_CRT2CRTC ;
}
tempal = tempal & 0x3f ;
table = tempbx ;
switch( tempbx )
{
case 0:
tempdi = 0 ; /*EPLCHTVCRT1Ptr_H;*/
if ( pVBInfo->IF_DEF_CH7007 == 1 )
{
tempdi = XGI_EPLCHTVCRT1Ptr;
}
break ;
case 1:
tempdi = 0 ; /*EPLCHTVCRT1Ptr_V;*/
if ( pVBInfo->IF_DEF_CH7007 == 1 )
{
tempdi = XGI_EPLCHTVCRT1Ptr;
}
break ;
case 2:
tempdi = XGI_EPLCHTVDataPtr ;
break ;
case 3:
tempdi = 0 ;
break ;
case 4:
tempdi = XGI_TVDataTable ;
break ;
case 5:
tempdi = 0 ;
break ;
case 6:
tempdi = XGI_EPLCHTVRegPtr ;
break ;
default:
break ;
}
if ( tempdi == 0x00 ) /* OEMUtil */
return( 0 ) ;
tempdx = pVBInfo->TVInfo ;
if ( pVBInfo->VBInfo & SetInSlaveMode )
tempdx = tempdx | SetTVLockMode ;
if ( modeflag & HalfDCLK )
tempdx = tempdx | SetTVLowResolution ;
i = 0 ;
while( tempdi[ i ].MASK != 0xffff )
{
if ( ( tempdx & tempdi[ i ].MASK ) == tempdi[ i ].CAP )
break ;
i++ ;
}
if ( table == 0x00 ) /* 07/05/22 */
{
}
else if ( table == 0x01 )
{
}
else if ( table == 0x04 )
{
switch( tempdi[ i ].DATAPTR )
{
case 0:
return &XGI_ExtPALData[ tempal ] ;
break ;
case 1:
return &XGI_ExtNTSCData[ tempal ] ;
break ;
case 2:
return &XGI_StPALData[ tempal ] ;
break ;
case 3:
return &XGI_StNTSCData[ tempal ] ;
break ;
case 4:
return &XGI_ExtHiTVData[ tempal ] ;
break ;
case 5:
return &XGI_St2HiTVData[ tempal ] ;
break ;
case 6:
return &XGI_ExtYPbPr525iData[ tempal ] ;
break ;
case 7:
return &XGI_ExtYPbPr525pData[ tempal ] ;
break ;
case 8:
return &XGI_ExtYPbPr750pData[ tempal ] ;
break ;
case 9:
return &XGI_StYPbPr525iData[ tempal ] ;
break ;
case 10:
return &XGI_StYPbPr525pData[ tempal ] ;
break ;
case 11:
return &XGI_StYPbPr750pData[ tempal ] ;
break;
case 12: /* avoid system hang */
return &XGI_ExtNTSCData[ tempal ] ;
break ;
case 13:
return &XGI_St1HiTVData[ tempal ] ;
break ;
default:
break ;
}
}
else if( table == 0x02 )
{
switch( tempdi[ i ].DATAPTR )
{
case 0:
return &XGI_CHTVUNTSCData[ tempal ] ;
break ;
case 1:
return &XGI_CHTVONTSCData[ tempal ] ;
break ;
case 2:
return &XGI_CHTVUPALData[ tempal ] ;
break ;
case 3:
return &XGI_CHTVOPALData[ tempal ] ;
break ;
default:
break ;
}
}
else if( table == 0x06 )
{
}
return( 0 ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_BacklightByDrv */
/* Input : */
/* Output : 1 -> Skip backlight control */
/* Description : */
/* --------------------------------------------------------------------- */
unsigned char XGI_BacklightByDrv(struct vb_device_info *pVBInfo)
{
unsigned char tempah ;
tempah = (unsigned char)XGINew_GetReg1(pVBInfo->P3d4, 0x3A) ;
if (tempah & BacklightControlBit)
return 1;
else
return 0;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_FirePWDDisable */
/* Input : */
/* Output : */
/* Description : Turn off VDD & Backlight : Fire disable procedure */
/* --------------------------------------------------------------------- */
/*
void XGI_FirePWDDisable(struct vb_device_info *pVBInfo)
{
XGINew_SetRegANDOR( pVBInfo->Part1Port , 0x26 , 0x00 , 0xFC ) ;
}
*/
/* --------------------------------------------------------------------- */
/* Function : XGI_FirePWDEnable */
/* Input : */
/* Output : */
/* Description : Turn on VDD & Backlight : Fire enable procedure */
/* --------------------------------------------------------------------- */
void XGI_FirePWDEnable(struct vb_device_info *pVBInfo)
{
XGINew_SetRegANDOR( pVBInfo->Part1Port , 0x26 , 0x03 , 0xFC ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_EnableGatingCRT */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_EnableGatingCRT(struct xgi_hw_device_info *HwDeviceExtension, struct vb_device_info *pVBInfo)
{
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x63 , 0xBF , 0x40 ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_DisableGatingCRT */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_DisableGatingCRT(struct xgi_hw_device_info *HwDeviceExtension, struct vb_device_info *pVBInfo)
{
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x63 , 0xBF , 0x00 ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetPanelDelay */
/* Input : */
/* Output : */
/* Description : */
/* I/P : bl : 1 ; T1 : the duration between CPL on and signal on */
/* : bl : 2 ; T2 : the duration signal on and Vdd on */
/* : bl : 3 ; T3 : the duration between CPL off and signal off */
/* : bl : 4 ; T4 : the duration signal off and Vdd off */
/* --------------------------------------------------------------------- */
void XGI_SetPanelDelay(unsigned short tempbl, struct vb_device_info *pVBInfo)
{
unsigned short index ;
index = XGI_GetLCDCapPtr(pVBInfo) ;
if ( tempbl == 1 )
XGINew_LCD_Wait_Time( pVBInfo->LCDCapList[ index ].PSC_S1, pVBInfo ) ;
if ( tempbl == 2 )
XGINew_LCD_Wait_Time( pVBInfo->LCDCapList[ index ].PSC_S2, pVBInfo ) ;
if ( tempbl == 3 )
XGINew_LCD_Wait_Time( pVBInfo->LCDCapList[ index ].PSC_S3, pVBInfo ) ;
if ( tempbl == 4 )
XGINew_LCD_Wait_Time( pVBInfo->LCDCapList[ index ].PSC_S4, pVBInfo ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetPanelPower */
/* Input : */
/* Output : */
/* Description : */
/* I/O : ah = 0011b = 03h ; Backlight on, Power on */
/* = 0111b = 07h ; Backlight on, Power off */
/* = 1011b = 0Bh ; Backlight off, Power on */
/* = 1111b = 0Fh ; Backlight off, Power off */
/* --------------------------------------------------------------------- */
void XGI_SetPanelPower(unsigned short tempah, unsigned short tempbl, struct vb_device_info *pVBInfo)
{
if ( pVBInfo->VBType & ( VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
XGINew_SetRegANDOR( pVBInfo->Part4Port , 0x26 , tempbl , tempah ) ;
else
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x11 , tempbl , tempah ) ;
}
unsigned char XG21GPIODataTransfer(unsigned char ujDate)
{
unsigned char ujRet = 0;
unsigned char i = 0;
for (i=0; i<8; i++)
{
ujRet = ujRet << 1;
/* ujRet |= GETBITS(ujDate >> i, 0:0); */
ujRet |= (ujDate >> i) & 1;
}
return ujRet;
}
/*----------------------------------------------------------------------------*/
/* output */
/* bl[5] : LVDS signal */
/* bl[1] : LVDS backlight */
/* bl[0] : LVDS VDD */
/*----------------------------------------------------------------------------*/
unsigned char XGI_XG21GetPSCValue(struct vb_device_info *pVBInfo)
{
unsigned char CR4A, temp;
CR4A = XGINew_GetReg1( pVBInfo->P3d4 , 0x4A ) ;
XGINew_SetRegAND( pVBInfo->P3d4 , 0x4A , ~0x23 ) ; /* enable GPIO write */
temp = XGINew_GetReg1( pVBInfo->P3d4 , 0x48 ) ;
temp = XG21GPIODataTransfer(temp);
temp &= 0x23;
XGINew_SetReg1( pVBInfo->P3d4 , 0x4A , CR4A ) ;
return temp;
}
/*----------------------------------------------------------------------------*/
/* output */
/* bl[5] : LVDS signal */
/* bl[1] : LVDS backlight */
/* bl[0] : LVDS VDD */
/*----------------------------------------------------------------------------*/
unsigned char XGI_XG27GetPSCValue(struct vb_device_info *pVBInfo)
{
unsigned char CR4A, CRB4, temp;
CR4A = XGINew_GetReg1( pVBInfo->P3d4 , 0x4A ) ;
XGINew_SetRegAND( pVBInfo->P3d4 , 0x4A , ~0x0C ) ; /* enable GPIO write */
temp = XGINew_GetReg1( pVBInfo->P3d4 , 0x48 ) ;
temp &= 0x0C;
temp >>= 2;
XGINew_SetReg1( pVBInfo->P3d4 , 0x4A , CR4A ) ;
CRB4 = XGINew_GetReg1( pVBInfo->P3d4 , 0xB4 ) ;
temp |= ((CRB4&0x04)<<3);
return temp;
}
/*----------------------------------------------------------------------------*/
/* input */
/* bl[5] : 1;LVDS signal on */
/* bl[1] : 1;LVDS backlight on */
/* bl[0] : 1:LVDS VDD on */
/* bh: 100000b : clear bit 5, to set bit5 */
/* 000010b : clear bit 1, to set bit1 */
/* 000001b : clear bit 0, to set bit0 */
/*----------------------------------------------------------------------------*/
void XGI_XG21BLSignalVDD(unsigned short tempbh, unsigned short tempbl, struct vb_device_info *pVBInfo)
{
unsigned char CR4A, temp;
CR4A = XGINew_GetReg1( pVBInfo->P3d4 , 0x4A ) ;
tempbh &= 0x23;
tempbl &= 0x23;
XGINew_SetRegAND( pVBInfo->P3d4 , 0x4A , ~tempbh ) ; /* enable GPIO write */
if (tempbh&0x20)
{
temp = (tempbl>>4)&0x02;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0xB4 , ~0x02 , temp) ; /* CR B4[1] */
}
temp = XGINew_GetReg1( pVBInfo->P3d4 , 0x48 ) ;
temp = XG21GPIODataTransfer(temp);
temp &= ~tempbh;
temp |= tempbl;
XGINew_SetReg1( pVBInfo->P3d4 , 0x48 , temp ) ;
}
void XGI_XG27BLSignalVDD(unsigned short tempbh, unsigned short tempbl, struct vb_device_info *pVBInfo)
{
unsigned char CR4A, temp;
unsigned short tempbh0, tempbl0;
tempbh0 = tempbh;
tempbl0 = tempbl;
tempbh0 &= 0x20;
tempbl0 &= 0x20;
tempbh0 >>= 3;
tempbl0 >>= 3;
if (tempbh&0x20)
{
temp = (tempbl>>4)&0x02;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0xB4 , ~0x02 , temp) ; /* CR B4[1] */
}
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0xB4 , ~tempbh0 , tempbl0 ) ;
CR4A = XGINew_GetReg1( pVBInfo->P3d4 , 0x4A ) ;
tempbh &= 0x03;
tempbl &= 0x03;
tempbh <<= 2;
tempbl <<= 2; /* GPIOC,GPIOD */
XGINew_SetRegAND( pVBInfo->P3d4 , 0x4A , ~tempbh ) ; /* enable GPIO write */
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x48 , ~tempbh , tempbl ) ;
}
/* --------------------------------------------------------------------- */
unsigned short XGI_GetLVDSOEMTableIndex(struct vb_device_info *pVBInfo)
{
unsigned short index ;
index = XGINew_GetReg1( pVBInfo->P3d4 , 0x36 ) ;
if (index < sizeof(XGI21_LCDCapList)/sizeof(struct XGI21_LVDSCapStruct))
return index;
return 0;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_XG21SetPanelDelay */
/* Input : */
/* Output : */
/* Description : */
/* I/P : bl : 1 ; T1 : the duration between CPL on and signal on */
/* : bl : 2 ; T2 : the duration signal on and Vdd on */
/* : bl : 3 ; T3 : the duration between CPL off and signal off */
/* : bl : 4 ; T4 : the duration signal off and Vdd off */
/* --------------------------------------------------------------------- */
void XGI_XG21SetPanelDelay(unsigned short tempbl, struct vb_device_info *pVBInfo)
{
unsigned short index ;
index = XGI_GetLVDSOEMTableIndex( pVBInfo );
if ( tempbl == 1 )
XGINew_LCD_Wait_Time( pVBInfo->XG21_LVDSCapList[ index ].PSC_S1, pVBInfo ) ;
if ( tempbl == 2 )
XGINew_LCD_Wait_Time( pVBInfo->XG21_LVDSCapList[ index ].PSC_S2, pVBInfo ) ;
if ( tempbl == 3 )
XGINew_LCD_Wait_Time( pVBInfo->XG21_LVDSCapList[ index ].PSC_S3, pVBInfo ) ;
if ( tempbl == 4 )
XGINew_LCD_Wait_Time( pVBInfo->XG21_LVDSCapList[ index ].PSC_S4, pVBInfo ) ;
}
unsigned char XGI_XG21CheckLVDSMode(unsigned short ModeNo,
unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned short xres ,
yres ,
colordepth ,
modeflag ,
resindex ,
lvdstableindex;
resindex = XGI_GetResInfo( ModeNo , ModeIdIndex, pVBInfo ) ;
if ( ModeNo <= 0x13 )
{
xres = pVBInfo->StResInfo[ resindex ].HTotal ;
yres = pVBInfo->StResInfo[ resindex ].VTotal ;
modeflag = pVBInfo->SModeIDTable[ModeIdIndex].St_ModeFlag; /* si+St_ResInfo */
}
else
{
xres = pVBInfo->ModeResInfo[ resindex ].HTotal ; /* xres->ax */
yres = pVBInfo->ModeResInfo[ resindex ].VTotal ; /* yres->bx */
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex].Ext_ModeFlag ; /* si+St_ModeFlag */
}
if ( !( modeflag & Charx8Dot ) )
{
xres /= 9;
xres *= 8;
}
if ( ModeNo > 0x13 )
{
if ( ( ModeNo>0x13 ) && ( modeflag & HalfDCLK ) )
{
xres *= 2 ;
}
if ( ( ModeNo>0x13 ) && ( modeflag & DoubleScanMode ) )
{
yres *= 2 ;
}
}
lvdstableindex = XGI_GetLVDSOEMTableIndex( pVBInfo );
if ( xres > (pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDSHDE) )
return 0;
if ( yres > (pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDSVDE) )
return 0;
if ( ModeNo > 0x13 )
{
if ( ( xres != (pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDSHDE) ) ||
( yres != (pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDSVDE)) )
{
colordepth = XGI_GetColorDepth( ModeNo , ModeIdIndex, pVBInfo ) ;
if (colordepth > 2)
return 0;
}
}
return 1;
}
void XGI_SetXG21FPBits(struct vb_device_info *pVBInfo)
{
unsigned char temp;
temp = XGINew_GetReg1( pVBInfo->P3d4 , 0x37 ) ; /* D[0] 1: 18bit */
temp = ( temp & 1 ) << 6;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x06 , ~0x40 , temp ) ; /* SR06[6] 18bit Dither */
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x09 , ~0xc0 , temp | 0x80 ) ; /* SR09[7] enable FP output, SR09[6] 1: sigle 18bits, 0: dual 12bits */
}
void XGI_SetXG27FPBits(struct vb_device_info *pVBInfo)
{
unsigned char temp;
temp = XGINew_GetReg1( pVBInfo->P3d4 , 0x37 ) ; /* D[1:0] 01: 18bit, 00: dual 12, 10: single 24 */
temp = ( temp & 3 ) << 6;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x06 , ~0xc0 , temp & 0x80 ) ; /* SR06[7]0: dual 12/1: single 24 [6] 18bit Dither <= 0 h/w recommend */
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x09 , ~0xc0 , temp | 0x80 ) ; /* SR09[7] enable FP output, SR09[6] 1: sigle 18bits, 0: 24bits */
}
void XGI_SetXG21LVDSPara(unsigned short ModeNo, unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned char temp, Miscdata;
unsigned short xres ,
yres ,
modeflag ,
resindex ,
lvdstableindex ;
unsigned short LVDSHT,LVDSHBS,LVDSHRS,LVDSHRE,LVDSHBE;
unsigned short LVDSVT,LVDSVBS,LVDSVRS,LVDSVRE,LVDSVBE;
unsigned short value;
lvdstableindex = XGI_GetLVDSOEMTableIndex( pVBInfo );
temp = (unsigned char) ((pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDS_Capability & (LCDPolarity << 8)) >> 8);
temp &= LCDPolarity;
Miscdata = (unsigned char) XGINew_GetReg2(pVBInfo->P3cc) ;
XGINew_SetReg3( pVBInfo->P3c2 , (Miscdata & 0x3F) | temp ) ;
temp = (unsigned char) (pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDS_Capability & LCDPolarity) ;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x35 , ~0x80 , temp&0x80 ) ; /* SR35[7] FP VSync polarity */
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x30 , ~0x20 , (temp&0x40)>>1 ) ; /* SR30[5] FP HSync polarity */
XGI_SetXG21FPBits(pVBInfo);
resindex = XGI_GetResInfo( ModeNo , ModeIdIndex, pVBInfo ) ;
if ( ModeNo <= 0x13 )
{
xres = pVBInfo->StResInfo[ resindex ].HTotal ;
yres = pVBInfo->StResInfo[ resindex ].VTotal ;
modeflag = pVBInfo->SModeIDTable[ModeIdIndex].St_ModeFlag; /* si+St_ResInfo */
}
else
{
xres = pVBInfo->ModeResInfo[ resindex ].HTotal ; /* xres->ax */
yres = pVBInfo->ModeResInfo[ resindex ].VTotal ; /* yres->bx */
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex].Ext_ModeFlag ; /* si+St_ModeFlag */
}
if (!( modeflag & Charx8Dot ))
xres = xres * 8 / 9;
LVDSHT = pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDSHT;
LVDSHBS = xres + ( pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDSHDE - xres ) / 2 ;
if ( ( ModeNo<=0x13 ) && ( modeflag & HalfDCLK ) )
{
LVDSHBS -= xres/4 ;
}
if (LVDSHBS > LVDSHT) LVDSHBS -= LVDSHT ;
LVDSHRS = LVDSHBS + pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDSHFP ;
if (LVDSHRS > LVDSHT) LVDSHRS -= LVDSHT ;
LVDSHRE = LVDSHRS + pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDSHSYNC ;
if (LVDSHRE > LVDSHT) LVDSHRE -= LVDSHT ;
LVDSHBE = LVDSHBS + LVDSHT - pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDSHDE ;
LVDSVT = pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDSVT;
LVDSVBS = yres + ( pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDSVDE - yres ) / 2 ;
if ( ( ModeNo>0x13 ) && ( modeflag & DoubleScanMode ) )
{
LVDSVBS += yres/2 ;
}
if (LVDSVBS > LVDSVT) LVDSVBS -= LVDSVT ;
LVDSVRS = LVDSVBS + pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDSVFP ;
if (LVDSVRS > LVDSVT) LVDSVRS -= LVDSVT ;
LVDSVRE = LVDSVRS + pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDSVSYNC ;
if (LVDSVRE > LVDSVT) LVDSVRE -= LVDSVT ;
LVDSVBE = LVDSVBS + LVDSVT - pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDSVDE ;
temp = (unsigned char)XGINew_GetReg1(pVBInfo->P3d4, 0x11) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x11 , temp & 0x7f ) ; /* Unlock CRTC */
if (!( modeflag & Charx8Dot ))
{
XGINew_SetRegOR( pVBInfo->P3c4 , 0x1 , 0x1 ) ;
}
/* HT SR0B[1:0] CR00 */
value = ( LVDSHT >> 3 ) - 5;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x0B , ~0x03 , ( value & 0x300 ) >> 8 ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x0 , (value & 0xFF) ) ;
/* HBS SR0B[5:4] CR02 */
value = ( LVDSHBS >> 3 ) - 1;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x0B , ~0x30 , ( value & 0x300 ) >> 4 ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x2 , (value & 0xFF) ) ;
/* HBE SR0C[1:0] CR05[7] CR03[4:0] */
value = ( LVDSHBE >> 3 ) - 1;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x0C , ~0x03 , ( value & 0xC0 ) >> 6 ) ;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x05 , ~0x80 , ( value & 0x20 ) << 2 ) ;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x03 , ~0x1F , value & 0x1F ) ;
/* HRS SR0B[7:6] CR04 */
value = ( LVDSHRS >> 3 ) + 2;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x0B , ~0xC0 , ( value & 0x300 ) >> 2 ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x4 , (value & 0xFF) ) ;
/* Panel HRS SR2F[1:0] SR2E[7:0] */
value--;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x2F , ~0x03 , ( value & 0x300 ) >> 8 ) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2E , (value & 0xFF) ) ;
/* HRE SR0C[2] CR05[4:0] */
value = ( LVDSHRE >> 3 ) + 2;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x0C , ~0x04 , ( value & 0x20 ) >> 3 ) ;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x05 , ~0x1F , value & 0x1F ) ;
/* Panel HRE SR2F[7:2] */
value--;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x2F , ~0xFC , value << 2 ) ;
/* VT SR0A[0] CR07[5][0] CR06 */
value = LVDSVT - 2 ;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x0A , ~0x01 , ( value & 0x400 ) >> 10 ) ;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x07 , ~0x20 , ( value & 0x200 ) >> 4 ) ;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x07 , ~0x01 , ( value & 0x100 ) >> 8 ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x06 , (value & 0xFF) ) ;
/* VBS SR0A[2] CR09[5] CR07[3] CR15 */
value = LVDSVBS - 1 ;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x0A , ~0x04 , ( value & 0x400 ) >> 8 ) ;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x09 , ~0x20 , ( value & 0x200 ) >> 4 ) ;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x07 , ~0x08 , ( value & 0x100 ) >> 5 ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x15 , (value & 0xFF) ) ;
/* VBE SR0A[4] CR16 */
value = LVDSVBE - 1;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x0A , ~0x10 , ( value & 0x100 ) >> 4 ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x16 , (value & 0xFF) ) ;
/* VRS SR0A[3] CR7[7][2] CR10 */
value = LVDSVRS - 1 ;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x0A , ~0x08 , ( value & 0x400 ) >> 7 ) ;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x07 , ~0x80 , ( value & 0x200 ) >> 2 ) ;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x07 , ~0x04 , ( value & 0x100 ) >> 6 ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x10 , (value & 0xFF) ) ;
/* Panel VRS SR3F[1:0] SR34[7:0] SR33[0] */
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x3F , ~0x03 , ( value & 0x600 ) >> 9 ) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x34 , (value >> 1) & 0xFF ) ;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x33 , ~0x01 , value & 0x01 ) ;
/* VRE SR0A[5] CR11[3:0] */
value = LVDSVRE - 1;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x0A , ~0x20 , ( value & 0x10 ) << 1 ) ;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x11 , ~0x0F , value & 0x0F ) ;
/* Panel VRE SR3F[7:2] */ /* SR3F[7] has to be 0, h/w bug */
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x3F , ~0xFC , ( value << 2 ) & 0x7C ) ;
for ( temp=0, value = 0; temp < 3; temp++)
{
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x31 , ~0x30 , value ) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2B , pVBInfo->XG21_LVDSCapList[lvdstableindex].VCLKData1) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2C , pVBInfo->XG21_LVDSCapList[lvdstableindex].VCLKData2) ;
value += 0x10;
}
if (!( modeflag & Charx8Dot ))
{
XGINew_GetReg2( pVBInfo->P3da ) ; /* reset 3da */
XGINew_SetReg3( pVBInfo->P3c0 , 0x13 ) ; /* set index */
XGINew_SetReg3( pVBInfo->P3c0 , 0x00 ) ; /* set data, panning = 0, shift left 1 dot*/
XGINew_GetReg2( pVBInfo->P3da ) ; /* Enable Attribute */
XGINew_SetReg3( pVBInfo->P3c0 , 0x20 ) ;
XGINew_GetReg2( pVBInfo->P3da ) ; /* reset 3da */
}
}
/* no shadow case */
void XGI_SetXG27LVDSPara(unsigned short ModeNo, unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned char temp, Miscdata;
unsigned short xres ,
yres ,
modeflag ,
resindex ,
lvdstableindex ;
unsigned short LVDSHT,LVDSHBS,LVDSHRS,LVDSHRE,LVDSHBE;
unsigned short LVDSVT,LVDSVBS,LVDSVRS,LVDSVRE,LVDSVBE;
unsigned short value;
lvdstableindex = XGI_GetLVDSOEMTableIndex( pVBInfo );
temp = (unsigned char) ((pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDS_Capability & (LCDPolarity << 8)) >> 8);
temp &= LCDPolarity;
Miscdata = (unsigned char) XGINew_GetReg2(pVBInfo->P3cc);
XGINew_SetReg3( pVBInfo->P3c2 , (Miscdata & 0x3F) | temp ) ;
temp = (unsigned char) (pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDS_Capability & LCDPolarity) ;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x35 , ~0x80 , temp&0x80 ) ; /* SR35[7] FP VSync polarity */
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x30 , ~0x20 , (temp&0x40)>>1 ) ; /* SR30[5] FP HSync polarity */
XGI_SetXG27FPBits(pVBInfo);
resindex = XGI_GetResInfo( ModeNo , ModeIdIndex, pVBInfo ) ;
if ( ModeNo <= 0x13 )
{
xres = pVBInfo->StResInfo[ resindex ].HTotal ;
yres = pVBInfo->StResInfo[ resindex ].VTotal ;
modeflag = pVBInfo->SModeIDTable[ModeIdIndex].St_ModeFlag; /* si+St_ResInfo */
}
else
{
xres = pVBInfo->ModeResInfo[ resindex ].HTotal ; /* xres->ax */
yres = pVBInfo->ModeResInfo[ resindex ].VTotal ; /* yres->bx */
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex].Ext_ModeFlag ; /* si+St_ModeFlag */
}
if (!( modeflag & Charx8Dot ))
xres = xres * 8 / 9;
LVDSHT = pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDSHT;
LVDSHBS = xres + ( pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDSHDE - xres ) / 2 ;
if ( ( ModeNo<=0x13 ) && ( modeflag & HalfDCLK ) )
{
LVDSHBS -= xres/4 ;
}
if (LVDSHBS > LVDSHT) LVDSHBS -= LVDSHT ;
LVDSHRS = LVDSHBS + pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDSHFP ;
if (LVDSHRS > LVDSHT) LVDSHRS -= LVDSHT ;
LVDSHRE = LVDSHRS + pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDSHSYNC ;
if (LVDSHRE > LVDSHT) LVDSHRE -= LVDSHT ;
LVDSHBE = LVDSHBS + LVDSHT - pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDSHDE ;
LVDSVT = pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDSVT;
LVDSVBS = yres + ( pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDSVDE - yres ) / 2 ;
if ( ( ModeNo>0x13 ) && ( modeflag & DoubleScanMode ) )
{
LVDSVBS += yres/2 ;
}
if (LVDSVBS > LVDSVT) LVDSVBS -= LVDSVT ;
LVDSVRS = LVDSVBS + pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDSVFP ;
if (LVDSVRS > LVDSVT) LVDSVRS -= LVDSVT ;
LVDSVRE = LVDSVRS + pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDSVSYNC ;
if (LVDSVRE > LVDSVT) LVDSVRE -= LVDSVT ;
LVDSVBE = LVDSVBS + LVDSVT - pVBInfo->XG21_LVDSCapList[lvdstableindex].LVDSVDE ;
temp = (unsigned char)XGINew_GetReg1(pVBInfo->P3d4, 0x11) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x11 , temp & 0x7f ) ; /* Unlock CRTC */
if (!( modeflag & Charx8Dot ))
{
XGINew_SetRegOR( pVBInfo->P3c4 , 0x1 , 0x1 ) ;
}
/* HT SR0B[1:0] CR00 */
value = ( LVDSHT >> 3 ) - 5;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x0B , ~0x03 , ( value & 0x300 ) >> 8 ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x0 , (value & 0xFF) ) ;
/* HBS SR0B[5:4] CR02 */
value = ( LVDSHBS >> 3 ) - 1;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x0B , ~0x30 , ( value & 0x300 ) >> 4 ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x2 , (value & 0xFF) ) ;
/* HBE SR0C[1:0] CR05[7] CR03[4:0] */
value = ( LVDSHBE >> 3 ) - 1;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x0C , ~0x03 , ( value & 0xC0 ) >> 6 ) ;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x05 , ~0x80 , ( value & 0x20 ) << 2 ) ;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x03 , ~0x1F , value & 0x1F ) ;
/* HRS SR0B[7:6] CR04 */
value = ( LVDSHRS >> 3 ) + 2;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x0B , ~0xC0 , ( value & 0x300 ) >> 2 ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x4 , (value & 0xFF) ) ;
/* Panel HRS SR2F[1:0] SR2E[7:0] */
value--;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x2F , ~0x03 , ( value & 0x300 ) >> 8 ) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2E , (value & 0xFF) ) ;
/* HRE SR0C[2] CR05[4:0] */
value = ( LVDSHRE >> 3 ) + 2;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x0C , ~0x04 , ( value & 0x20 ) >> 3 ) ;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x05 , ~0x1F , value & 0x1F ) ;
/* Panel HRE SR2F[7:2] */
value--;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x2F , ~0xFC , value << 2 ) ;
/* VT SR0A[0] CR07[5][0] CR06 */
value = LVDSVT - 2 ;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x0A , ~0x01 , ( value & 0x400 ) >> 10 ) ;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x07 , ~0x20 , ( value & 0x200 ) >> 4 ) ;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x07 , ~0x01 , ( value & 0x100 ) >> 8 ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x06 , (value & 0xFF) ) ;
/* VBS SR0A[2] CR09[5] CR07[3] CR15 */
value = LVDSVBS - 1 ;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x0A , ~0x04 , ( value & 0x400 ) >> 8 ) ;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x09 , ~0x20 , ( value & 0x200 ) >> 4 ) ;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x07 , ~0x08 , ( value & 0x100 ) >> 5 ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x15 , (value & 0xFF) ) ;
/* VBE SR0A[4] CR16 */
value = LVDSVBE - 1;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x0A , ~0x10 , ( value & 0x100 ) >> 4 ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x16 , (value & 0xFF) ) ;
/* VRS SR0A[3] CR7[7][2] CR10 */
value = LVDSVRS - 1 ;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x0A , ~0x08 , ( value & 0x400 ) >> 7 ) ;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x07 , ~0x80 , ( value & 0x200 ) >> 2 ) ;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x07 , ~0x04 , ( value & 0x100 ) >> 6 ) ;
XGINew_SetReg1( pVBInfo->P3d4 , 0x10 , (value & 0xFF) ) ;
/* Panel VRS SR35[2:0] SR34[7:0] */
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x35 , ~0x07 , ( value & 0x700 ) >> 8 ) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x34 , value & 0xFF ) ;
/* VRE SR0A[5] CR11[3:0] */
value = LVDSVRE - 1;
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x0A , ~0x20 , ( value & 0x10 ) << 1 ) ;
XGINew_SetRegANDOR( pVBInfo->P3d4 , 0x11 , ~0x0F , value & 0x0F ) ;
/* Panel VRE SR3F[7:2] */
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x3F , ~0xFC , ( value << 2 ) & 0xFC ) ;
for ( temp=0, value = 0; temp < 3; temp++)
{
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x31 , ~0x30 , value ) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2B , pVBInfo->XG21_LVDSCapList[lvdstableindex].VCLKData1) ;
XGINew_SetReg1( pVBInfo->P3c4 , 0x2C , pVBInfo->XG21_LVDSCapList[lvdstableindex].VCLKData2) ;
value += 0x10;
}
if (!( modeflag & Charx8Dot ))
{
XGINew_GetReg2( pVBInfo->P3da ) ; /* reset 3da */
XGINew_SetReg3( pVBInfo->P3c0 , 0x13 ) ; /* set index */
XGINew_SetReg3( pVBInfo->P3c0 , 0x00 ) ; /* set data, panning = 0, shift left 1 dot*/
XGINew_GetReg2( pVBInfo->P3da ) ; /* Enable Attribute */
XGINew_SetReg3( pVBInfo->P3c0 , 0x20 ) ;
XGINew_GetReg2( pVBInfo->P3da ) ; /* reset 3da */
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_IsLCDON */
/* Input : */
/* Output : 0 : Skip PSC Control */
/* 1: Disable PSC */
/* Description : */
/* --------------------------------------------------------------------- */
unsigned char XGI_IsLCDON(struct vb_device_info *pVBInfo)
{
unsigned short tempax ;
tempax = pVBInfo->VBInfo ;
if ( tempax & SetCRT2ToDualEdge )
return 0;
else if ( tempax & ( DisableCRT2Display | SwitchToCRT2 | SetSimuScanMode ) )
return 1;
return 0;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_EnablePWD */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_EnablePWD(struct vb_device_info *pVBInfo)
{
unsigned short index ,
temp ;
index = XGI_GetLCDCapPtr(pVBInfo) ;
temp = pVBInfo->LCDCapList[ index ].PWD_2B ;
XGINew_SetReg1( pVBInfo->Part4Port , 0x2B , temp ) ;
XGINew_SetReg1( pVBInfo->Part4Port , 0x2C , pVBInfo->LCDCapList[ index ].PWD_2C ) ;
XGINew_SetReg1( pVBInfo->Part4Port , 0x2D , pVBInfo->LCDCapList[ index ].PWD_2D ) ;
XGINew_SetReg1( pVBInfo->Part4Port , 0x2E , pVBInfo->LCDCapList[ index ].PWD_2E ) ;
XGINew_SetReg1( pVBInfo->Part4Port , 0x2F , pVBInfo->LCDCapList[ index ].PWD_2F ) ;
XGINew_SetRegOR( pVBInfo->Part4Port , 0x27 , 0x80 ) ; /* enable PWD */
}
/* --------------------------------------------------------------------- */
/* Function : XGI_DisablePWD */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_DisablePWD(struct vb_device_info *pVBInfo)
{
XGINew_SetRegAND( pVBInfo->Part4Port , 0x27 , 0x7F ) ; /* disable PWD */
}
/* --------------------------------------------------------------------- */
/* Function : XGI_DisableChISLCD */
/* Input : */
/* Output : 0 -> Not LCD Mode */
/* Description : */
/* --------------------------------------------------------------------- */
unsigned char XGI_DisableChISLCD(struct vb_device_info *pVBInfo)
{
unsigned short tempbx ,
tempah ;
tempbx = pVBInfo->SetFlag & ( DisableChA | DisableChB ) ;
tempah = ~((unsigned short) XGINew_GetReg1(pVBInfo->Part1Port, 0x2E));
if ( tempbx & ( EnableChA | DisableChA ) )
{
if ( !( tempah & 0x08 ) ) /* Chk LCDA Mode */
return 0 ;
}
if ( !( tempbx & ( EnableChB | DisableChB ) ) )
return 0;
if ( tempah & 0x01 ) /* Chk LCDB Mode */
return 1;
return 0;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_EnableChISLCD */
/* Input : */
/* Output : 0 -> Not LCD mode */
/* Description : */
/* --------------------------------------------------------------------- */
unsigned char XGI_EnableChISLCD(struct vb_device_info *pVBInfo)
{
unsigned short tempbx ,
tempah ;
tempbx = pVBInfo->SetFlag & ( EnableChA | EnableChB ) ;
tempah = ~( (unsigned short)XGINew_GetReg1( pVBInfo->Part1Port , 0x2E ) ) ;
if ( tempbx & ( EnableChA | DisableChA ) )
{
if ( !( tempah & 0x08 ) ) /* Chk LCDA Mode */
return 0;
}
if ( !( tempbx & ( EnableChB | DisableChB ) ) )
return 0;
if ( tempah & 0x01 ) /* Chk LCDB Mode */
return 1;
return 0;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetLCDCapPtr */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
unsigned short XGI_GetLCDCapPtr(struct vb_device_info *pVBInfo)
{
unsigned char tempal ,
tempah ,
tempbl ,
i ;
tempah = XGINew_GetReg1( pVBInfo->P3d4 , 0x36 ) ;
tempal = tempah & 0x0F ;
tempah = tempah & 0xF0 ;
i = 0 ;
tempbl = pVBInfo->LCDCapList[ i ].LCD_ID ;
while( tempbl != 0xFF )
{
if ( tempbl & 0x80 ) /* OEMUtil */
{
tempal = tempah ;
tempbl = tempbl & ~( 0x80 ) ;
}
if ( tempal == tempbl )
break ;
i++ ;
tempbl = pVBInfo->LCDCapList[ i ].LCD_ID ;
}
return i ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetLCDCapPtr1 */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
unsigned short XGI_GetLCDCapPtr1(struct vb_device_info *pVBInfo)
{
unsigned short tempah ,
tempal ,
tempbl ,
i ;
tempal = pVBInfo->LCDResInfo ;
tempah = pVBInfo->LCDTypeInfo ;
i = 0 ;
tempbl = pVBInfo->LCDCapList[ i ].LCD_ID;
while( tempbl != 0xFF )
{
if ( ( tempbl & 0x80 ) && ( tempbl != 0x80 ) )
{
tempal = tempah ;
tempbl &= ~0x80 ;
}
if ( tempal == tempbl )
break ;
i++ ;
tempbl = pVBInfo->LCDCapList[ i ].LCD_ID ;
}
if ( tempbl == 0xFF )
{
pVBInfo->LCDResInfo = Panel1024x768 ;
pVBInfo->LCDTypeInfo = 0 ;
i = 0 ;
}
return i ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetLCDSync */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_GetLCDSync(unsigned short *HSyncWidth , unsigned short *VSyncWidth,
struct vb_device_info *pVBInfo)
{
unsigned short Index ;
Index = XGI_GetLCDCapPtr(pVBInfo) ;
*HSyncWidth = pVBInfo->LCDCapList[ Index ].LCD_HSyncWidth ;
*VSyncWidth = pVBInfo->LCDCapList[ Index ].LCD_VSyncWidth ;
return ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_EnableBridge */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_EnableBridge(struct xgi_hw_device_info *HwDeviceExtension, struct vb_device_info *pVBInfo)
{
unsigned short tempbl ,
tempah ;
if ( pVBInfo->SetFlag == Win9xDOSMode )
{
if ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{
XGI_DisplayOn( HwDeviceExtension, pVBInfo) ;
return ;
}
else /* LVDS or CH7017 */
return ;
}
if ( HwDeviceExtension->jChipType < XG40 )
{
if ( !XGI_DisableChISLCD(pVBInfo) )
{
if ( ( XGI_EnableChISLCD(pVBInfo) ) || ( pVBInfo->VBInfo & ( SetCRT2ToLCD | SetCRT2ToLCDA ) ) )
{
if ( pVBInfo->LCDInfo & SetPWDEnable )
{
XGI_EnablePWD( pVBInfo);
}
else
{
pVBInfo->LCDInfo &= ( ~SetPWDEnable ) ;
if ( pVBInfo->VBType & ( VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{
tempbl = 0xFD ;
tempah = 0x02 ;
}
else
{
tempbl = 0xFB ;
tempah = 0x00 ;
}
XGI_SetPanelPower( tempah , tempbl, pVBInfo ) ;
XGI_SetPanelDelay( 1,pVBInfo ) ;
}
}
}
} /* Not 340 */
if ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{
if ( !( pVBInfo->SetFlag & DisableChA ) )
{
if ( pVBInfo->SetFlag & EnableChA )
{
XGINew_SetReg1( pVBInfo->Part1Port , 0x1E , 0x20 ) ; /* Power on */
}
else
{
if ( pVBInfo->VBInfo & SetCRT2ToDualEdge ) /* SetCRT2ToLCDA ) */
{
XGINew_SetReg1(pVBInfo->Part1Port,0x1E,0x20); /* Power on */
}
}
}
if ( !( pVBInfo->SetFlag & DisableChB ) )
{
if ( ( pVBInfo->SetFlag & EnableChB ) || ( pVBInfo->VBInfo & ( SetCRT2ToLCD | SetCRT2ToTV | SetCRT2ToRAMDAC ) ) )
{
tempah = (unsigned char)XGINew_GetReg1(pVBInfo->P3c4, 0x32);
tempah &= 0xDF;
if ( pVBInfo->VBInfo & SetInSlaveMode )
{
if ( !( pVBInfo->VBInfo & SetCRT2ToRAMDAC ) )
tempah |= 0x20 ;
}
XGINew_SetReg1( pVBInfo->P3c4 , 0x32 , tempah ) ;
XGINew_SetRegOR( pVBInfo->P3c4 , 0x1E , 0x20 ) ;
tempah = (unsigned char)XGINew_GetReg1(pVBInfo->Part1Port, 0x2E);
if ( !( tempah & 0x80 ) )
XGINew_SetRegOR( pVBInfo->Part1Port , 0x2E , 0x80 ) ; /* BVBDOENABLE = 1 */
XGINew_SetRegAND( pVBInfo->Part1Port , 0x00 , 0x7F ) ; /* BScreenOFF = 0 */
}
}
if ( ( pVBInfo->SetFlag & ( EnableChA | EnableChB ) ) || ( !( pVBInfo->VBInfo & DisableCRT2Display ) ) )
{
XGINew_SetRegANDOR( pVBInfo->Part2Port , 0x00 , ~0xE0 , 0x20 ) ; /* shampoo 0129 */
if ( pVBInfo->VBType & ( VB_XGI302LV | VB_XGI301C ) )
{
if ( !XGI_DisableChISLCD(pVBInfo) )
{
if ( XGI_EnableChISLCD( pVBInfo) || ( pVBInfo->VBInfo & ( SetCRT2ToLCD | SetCRT2ToLCDA ) ) )
XGINew_SetRegAND( pVBInfo->Part4Port ,0x2A , 0x7F ) ; /* LVDS PLL power on */
}
XGINew_SetRegAND( pVBInfo->Part4Port , 0x30 , 0x7F ) ; /* LVDS Driver power on */
}
}
tempah = 0x00 ;
if ( !( pVBInfo->VBInfo & DisableCRT2Display ) )
{
tempah = 0xc0 ;
if ( !( pVBInfo->VBInfo & SetSimuScanMode ) )
{
if ( pVBInfo->VBInfo & SetCRT2ToLCDA )
{
if ( pVBInfo->VBInfo & SetCRT2ToDualEdge )
{
tempah = tempah & 0x40;
if ( pVBInfo->VBInfo & SetCRT2ToLCDA )
tempah = tempah ^ 0xC0 ;
if ( pVBInfo->SetFlag & DisableChB )
tempah &= 0xBF ;
if ( pVBInfo->SetFlag & DisableChA )
tempah &= 0x7F ;
if ( pVBInfo->SetFlag & EnableChB )
tempah |= 0x40 ;
if ( pVBInfo->SetFlag & EnableChA )
tempah |= 0x80 ;
}
}
}
}
XGINew_SetRegOR( pVBInfo->Part4Port , 0x1F , tempah ) ; /* EnablePart4_1F */
if ( pVBInfo->SetFlag & Win9xDOSMode )
{
XGI_DisplayOn( HwDeviceExtension, pVBInfo) ;
return ;
}
if ( !( pVBInfo->SetFlag & DisableChA ) )
{
XGI_VBLongWait( pVBInfo) ;
if ( !( pVBInfo->SetFlag & GatingCRT ) )
{
XGI_DisableGatingCRT( HwDeviceExtension, pVBInfo ) ;
XGI_DisplayOn( HwDeviceExtension, pVBInfo) ;
XGI_VBLongWait( pVBInfo) ;
}
}
} /* 301 */
else /* LVDS */
{
if ( pVBInfo->VBInfo & ( SetCRT2ToTV | SetCRT2ToLCD | SetCRT2ToLCDA ) )
XGINew_SetRegOR( pVBInfo->Part1Port , 0x1E , 0x20 ) ; /* enable CRT2 */
tempah = (unsigned char)XGINew_GetReg1(pVBInfo->Part1Port, 0x2E);
if ( !( tempah & 0x80 ) )
XGINew_SetRegOR( pVBInfo->Part1Port , 0x2E , 0x80 ) ; /* BVBDOENABLE = 1 */
XGINew_SetRegAND(pVBInfo->Part1Port,0x00,0x7F);
XGI_DisplayOn( HwDeviceExtension, pVBInfo);
} /* End of VB */
if ( HwDeviceExtension->jChipType < XG40 )
{
if ( !XGI_EnableChISLCD(pVBInfo) )
{
if ( pVBInfo->VBInfo & ( SetCRT2ToLCD | SetCRT2ToLCDA ) )
{
if ( XGI_BacklightByDrv(pVBInfo) )
return ;
}
else
return ;
}
if ( pVBInfo->LCDInfo & SetPWDEnable )
{
XGI_FirePWDEnable(pVBInfo) ;
return ;
}
XGI_SetPanelDelay( 2,pVBInfo ) ;
if ( pVBInfo->VBType & ( VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{
tempah = 0x01 ;
tempbl = 0xFE ; /* turn on backlght */
}
else
{
tempbl = 0xF7 ;
tempah = 0x00 ;
}
XGI_SetPanelPower( tempah , tempbl , pVBInfo) ;
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_DisableBridge */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_DisableBridge(struct xgi_hw_device_info *HwDeviceExtension, struct vb_device_info *pVBInfo)
{
unsigned short tempax ,
tempbx ,
tempah = 0 ,
tempbl = 0 ;
if ( pVBInfo->SetFlag == Win9xDOSMode )
return ;
if ( HwDeviceExtension->jChipType < XG40 )
{
if ( ( !( pVBInfo->VBInfo & ( SetCRT2ToLCD | SetCRT2ToLCDA ) ) ) || ( XGI_DisableChISLCD(pVBInfo) ) )
{
if ( !XGI_IsLCDON(pVBInfo) )
{
if ( pVBInfo->LCDInfo & SetPWDEnable )
XGI_EnablePWD( pVBInfo) ;
else
{
pVBInfo->LCDInfo &= ~SetPWDEnable ;
XGI_DisablePWD(pVBInfo) ;
if ( pVBInfo->VBType & ( VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{
tempbx = 0xFE ; /* not 01h */
tempax = 0 ;
}
else
{
tempbx = 0xF7 ; /* not 08h */
tempax = 0x08 ;
}
XGI_SetPanelPower( tempax , tempbx , pVBInfo) ;
XGI_SetPanelDelay( 3,pVBInfo ) ;
}
} /* end if(!XGI_IsLCDON(pVBInfo)) */
}
}
/* if ( CH7017 )
{
if ( !( pVBInfo->VBInfo & ( SetCRT2ToLCD | SetCRT2toLCDA ) ) || ( XGI_DisableChISLCD(pVBInfo) ) )
{
if ( !XGI_IsLCDON(pVBInfo) )
{
if ( DISCHARGE )
{
tempbx = XGINew_GetCH7005( 0x61 ) ;
if ( tempbx < 0x01 ) //first time we power up
XGINew_SetCH7005( 0x0066 ) ; //and disable power sequence
else
XGINew_SetCH7005( 0x5f66 ) ; //leave VDD on - disable power
}
}
}
} */
if ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B| VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{
tempah = 0x3F ;
if ( !( pVBInfo->VBInfo & ( DisableCRT2Display | SetSimuScanMode ) ) )
{
if ( pVBInfo->VBInfo & SetCRT2ToLCDA )
{
if ( pVBInfo->VBInfo & SetCRT2ToDualEdge )
{
tempah = 0x7F; /* Disable Channel A */
if ( !( pVBInfo->VBInfo & SetCRT2ToLCDA ) )
tempah = 0xBF ; /* Disable Channel B */
if ( pVBInfo->SetFlag & DisableChB )
tempah &= 0xBF ; /* force to disable Cahnnel */
if ( pVBInfo->SetFlag & DisableChA )
tempah &= 0x7F ; /* Force to disable Channel B */
}
}
}
XGINew_SetRegAND( pVBInfo->Part4Port , 0x1F , tempah ) ; /* disable part4_1f */
if ( pVBInfo->VBType & ( VB_XGI302LV | VB_XGI301C ) )
{
if ( ( ( pVBInfo->VBInfo & ( SetCRT2ToLCD | SetCRT2ToLCDA ) ) ) || ( XGI_DisableChISLCD(pVBInfo) ) || ( XGI_IsLCDON(pVBInfo) ) )
XGINew_SetRegOR( pVBInfo->Part4Port , 0x30 , 0x80 ) ; /* LVDS Driver power down */
}
if ( ( pVBInfo->SetFlag & DisableChA ) || ( pVBInfo->VBInfo & ( DisableCRT2Display | SetCRT2ToLCDA | SetSimuScanMode ) ) )
{
if ( pVBInfo->SetFlag & GatingCRT )
XGI_EnableGatingCRT( HwDeviceExtension, pVBInfo ) ;
XGI_DisplayOff( HwDeviceExtension, pVBInfo) ;
}
if ( pVBInfo->VBInfo & SetCRT2ToLCDA )
{
if ( ( pVBInfo->SetFlag & DisableChA ) || ( pVBInfo->VBInfo & SetCRT2ToLCDA ) )
XGINew_SetRegAND( pVBInfo->Part1Port , 0x1e , 0xdf ) ; /* Power down */
}
XGINew_SetRegAND( pVBInfo->P3c4 , 0x32 , 0xdf ) ; /* disable TV as primary VGA swap */
if ( ( pVBInfo->VBInfo & ( SetSimuScanMode | SetCRT2ToDualEdge ) ) )
XGINew_SetRegAND(pVBInfo->Part2Port,0x00,0xdf);
if ( ( pVBInfo->SetFlag & DisableChB ) || ( pVBInfo->VBInfo & ( DisableCRT2Display | SetSimuScanMode ) )
|| ( ( !( pVBInfo->VBInfo & SetCRT2ToLCDA ) ) && ( pVBInfo->VBInfo & ( SetCRT2ToRAMDAC | SetCRT2ToLCD | SetCRT2ToTV ) ) ) )
XGINew_SetRegOR( pVBInfo->Part1Port , 0x00 , 0x80 ) ; /* BScreenOff=1 */
if ( ( pVBInfo->SetFlag & DisableChB ) || ( pVBInfo->VBInfo & ( DisableCRT2Display | SetSimuScanMode ) )
|| ( !( pVBInfo->VBInfo & SetCRT2ToLCDA ) ) || ( pVBInfo->VBInfo & ( SetCRT2ToRAMDAC | SetCRT2ToLCD | SetCRT2ToTV ) ) )
{
tempah= XGINew_GetReg1( pVBInfo->Part1Port , 0x00 ) ; /* save Part1 index 0 */
XGINew_SetRegOR( pVBInfo->Part1Port , 0x00 , 0x10 ) ; /* BTDAC = 1, avoid VB reset */
XGINew_SetRegAND( pVBInfo->Part1Port , 0x1E , 0xDF ) ; /* disable CRT2 */
XGINew_SetReg1( pVBInfo->Part1Port , 0x00 , tempah ) ; /* restore Part1 index 0 */
}
}
else /* {301} */
{
if ( pVBInfo->VBInfo & ( SetCRT2ToLCD | SetCRT2ToTV ) )
{
XGINew_SetRegOR( pVBInfo->Part1Port , 0x00 , 0x80 ) ; /* BScreenOff=1 */
XGINew_SetRegAND( pVBInfo->Part1Port , 0x1E , 0xDF ) ; /* Disable CRT2 */
XGINew_SetRegAND( pVBInfo->P3c4 , 0x32 , 0xDF ) ; /* Disable TV asPrimary VGA swap */
}
if ( pVBInfo->VBInfo & ( DisableCRT2Display | SetCRT2ToLCDA | SetSimuScanMode ) )
XGI_DisplayOff( HwDeviceExtension, pVBInfo) ;
}
if ( HwDeviceExtension->jChipType < XG40 )
{
if ( !( pVBInfo->VBInfo & ( SetCRT2ToLCD | SetCRT2ToLCDA ) ) || ( XGI_DisableChISLCD(pVBInfo) ) || ( XGI_IsLCDON(pVBInfo) ) )
{
if ( pVBInfo->LCDInfo & SetPWDEnable )
{
if ( pVBInfo->LCDInfo & SetPWDEnable )
XGI_BacklightByDrv(pVBInfo) ;
else
{
XGI_SetPanelDelay( 4 ,pVBInfo) ;
if ( pVBInfo->VBType & VB_XGI301LV )
{
tempbl = 0xFD ;
tempah = 0x00 ;
}
else
{
tempbl = 0xFB ;
tempah = 0x04 ;
}
}
}
XGI_SetPanelPower( tempah , tempbl , pVBInfo) ;
}
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetTVPtrIndex */
/* Input : */
/* Output : */
/* Description : bx 0 : ExtNTSC */
/* 1 : StNTSC */
/* 2 : ExtPAL */
/* 3 : StPAL */
/* 4 : ExtHiTV */
/* 5 : StHiTV */
/* 6 : Ext525i */
/* 7 : St525i */
/* 8 : Ext525p */
/* 9 : St525p */
/* A : Ext750p */
/* B : St750p */
/* --------------------------------------------------------------------- */
unsigned short XGI_GetTVPtrIndex(struct vb_device_info *pVBInfo)
{
unsigned short tempbx = 0 ;
if ( pVBInfo->TVInfo & SetPALTV )
tempbx = 2 ;
if ( pVBInfo->TVInfo & SetYPbPrMode1080i )
tempbx = 4 ;
if ( pVBInfo->TVInfo & SetYPbPrMode525i )
tempbx = 6 ;
if ( pVBInfo->TVInfo & SetYPbPrMode525p )
tempbx = 8 ;
if ( pVBInfo->TVInfo & SetYPbPrMode750p )
tempbx = 10 ;
if ( pVBInfo->TVInfo & TVSimuMode )
tempbx++ ;
return tempbx ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_OEM310Setting */
/* Input : */
/* Output : */
/* Description : Customized Param. for 301 */
/* --------------------------------------------------------------------- */
void XGI_OEM310Setting(unsigned short ModeNo, unsigned short ModeIdIndex, struct vb_device_info *pVBInfo)
{
if ( pVBInfo->SetFlag & Win9xDOSMode )
return ;
/* GetPart1IO(); */
XGI_SetDelayComp(pVBInfo) ;
if ( pVBInfo->VBInfo & ( SetCRT2ToLCD | SetCRT2ToLCDA ) )
XGI_SetLCDCap(pVBInfo) ;
if ( pVBInfo->VBInfo & SetCRT2ToTV )
{
/* GetPart2IO() */
XGI_SetPhaseIncr(pVBInfo) ;
XGI_SetYFilter( ModeNo , ModeIdIndex,pVBInfo ) ;
XGI_SetAntiFlicker( ModeNo , ModeIdIndex,pVBInfo ) ;
if ( pVBInfo->VBType&VB_XGI301)
XGI_SetEdgeEnhance( ModeNo , ModeIdIndex ,pVBInfo) ;
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetDelayComp */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetDelayComp(struct vb_device_info *pVBInfo)
{
unsigned short index ;
unsigned char tempah ,
tempbl ,
tempbh ;
if ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{
if ( pVBInfo->VBInfo & ( SetCRT2ToLCD | SetCRT2ToLCDA | SetCRT2ToTV | SetCRT2ToRAMDAC ) )
{
tempbl = 0;
tempbh = 0;
index = XGI_GetTVPtrIndex(pVBInfo ) ; /* Get TV Delay */
tempbl = pVBInfo->XGI_TVDelayList[ index ] ;
if ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
tempbl = pVBInfo->XGI_TVDelayList2[ index ] ;
if ( pVBInfo->VBInfo & SetCRT2ToDualEdge )
tempbl = tempbl >> 4 ;
/*
if ( pVBInfo->VBInfo & SetCRT2ToRAMDAC )
tempbl = CRT2Delay1 ; // Get CRT2 Delay
if ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
tempbl = CRT2Delay2 ;
*/
if ( pVBInfo->VBInfo & ( SetCRT2ToLCD | SetCRT2ToLCDA ) )
{
index = XGI_GetLCDCapPtr(pVBInfo) ; /* Get LCD Delay */
tempbh=pVBInfo->LCDCapList[ index ].LCD_DelayCompensation ;
if ( !( pVBInfo->VBInfo & SetCRT2ToLCDA ) )
tempbl = tempbh ;
}
tempbl &= 0x0F ;
tempbh &= 0xF0 ;
tempah = XGINew_GetReg1( pVBInfo->Part1Port , 0x2D ) ;
if ( pVBInfo->VBInfo & ( SetCRT2ToRAMDAC | SetCRT2ToLCD | SetCRT2ToTV ) ) /* Channel B */
{
tempah &= 0xF0 ;
tempah |= tempbl ;
}
if ( pVBInfo->VBInfo & SetCRT2ToLCDA ) /* Channel A */
{
tempah &= 0x0F ;
tempah |= tempbh ;
}
XGINew_SetReg1(pVBInfo->Part1Port,0x2D,tempah);
}
}
else if ( pVBInfo->IF_DEF_LVDS == 1 )
{
tempbl = 0;
tempbh = 0;
if ( pVBInfo->VBInfo & SetCRT2ToLCD )
{
tempah = pVBInfo->LCDCapList[ XGI_GetLCDCapPtr(pVBInfo) ].LCD_DelayCompensation ; /* / Get LCD Delay */
tempah &= 0x0f ;
tempah = tempah << 4 ;
XGINew_SetRegANDOR( pVBInfo->Part1Port , 0x2D , 0x0f , tempah ) ;
}
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetLCDCap */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetLCDCap(struct vb_device_info *pVBInfo)
{
unsigned short tempcx ;
tempcx = pVBInfo->LCDCapList[ XGI_GetLCDCapPtr(pVBInfo) ].LCD_Capability ;
if ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{
if ( pVBInfo->VBType & ( VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{ /* 301LV/302LV only */
/* Set 301LV Capability */
XGINew_SetReg1(pVBInfo->Part4Port, 0x24, (unsigned char)(tempcx & 0x1F));
}
/* VB Driving */
XGINew_SetRegANDOR(pVBInfo->Part4Port, 0x0D,
~((EnableVBCLKDRVLOW | EnablePLLSPLOW) >> 8),
(unsigned short)((tempcx & (EnableVBCLKDRVLOW | EnablePLLSPLOW)) >> 8));
}
if ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{
if ( pVBInfo->VBInfo & SetCRT2ToLCD )
XGI_SetLCDCap_B( tempcx,pVBInfo ) ;
else if ( pVBInfo->VBInfo & SetCRT2ToLCDA )
XGI_SetLCDCap_A( tempcx,pVBInfo ) ;
if ( pVBInfo->VBType & ( VB_XGI302LV | VB_XGI301C ) )
{
if ( tempcx & EnableSpectrum )
SetSpectrum( pVBInfo) ;
}
}
else /* LVDS,CH7017 */
XGI_SetLCDCap_A( tempcx, pVBInfo ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetLCDCap_A */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetLCDCap_A(unsigned short tempcx, struct vb_device_info *pVBInfo)
{
unsigned short temp ;
temp = XGINew_GetReg1( pVBInfo->P3d4 , 0x37 ) ;
if ( temp & LCDRGB18Bit )
{
XGINew_SetRegANDOR(pVBInfo->Part1Port, 0x19, 0x0F,
(unsigned short)(0x20 | (tempcx & 0x00C0))); /* Enable Dither */
XGINew_SetRegANDOR( pVBInfo->Part1Port , 0x1A , 0x7F , 0x80 ) ;
}
else
{
XGINew_SetRegANDOR(pVBInfo->Part1Port, 0x19, 0x0F,
(unsigned short)(0x30 | (tempcx & 0x00C0)));
XGINew_SetRegANDOR( pVBInfo->Part1Port , 0x1A , 0x7F , 0x00 ) ;
}
/*
if ( tempcx & EnableLCD24bpp ) // 24bits
{
XGINew_SetRegANDOR(pVBInfo->Part1Port,0x19, 0x0F,(unsigned short)(0x30|(tempcx&0x00C0)) );
XGINew_SetRegANDOR(pVBInfo->Part1Port,0x1A,0x7F,0x00);
}
else
{
XGINew_SetRegANDOR(pVBInfo->Part1Port,0x19, 0x0F,(unsigned short)(0x20|(tempcx&0x00C0)) ); // Enable Dither
XGINew_SetRegANDOR(pVBInfo->Part1Port,0x1A,0x7F,0x80);
}
*/
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetLCDCap_B */
/* Input : cx -> LCD Capability */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetLCDCap_B(unsigned short tempcx, struct vb_device_info *pVBInfo)
{
if ( tempcx & EnableLCD24bpp ) /* 24bits */
XGINew_SetRegANDOR(pVBInfo->Part2Port, 0x1A, 0xE0,
(unsigned short)(((tempcx & 0x00ff) >> 6) | 0x0c));
else
XGINew_SetRegANDOR(pVBInfo->Part2Port, 0x1A, 0xE0,
(unsigned short)(((tempcx & 0x00ff) >> 6) | 0x18)); /* Enable Dither */
}
/* --------------------------------------------------------------------- */
/* Function : SetSpectrum */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void SetSpectrum(struct vb_device_info *pVBInfo)
{
unsigned short index ;
index = XGI_GetLCDCapPtr(pVBInfo) ;
XGINew_SetRegAND( pVBInfo->Part4Port , 0x30 , 0x8F ) ; /* disable down spectrum D[4] */
XGI_LongWait(pVBInfo) ;
XGINew_SetRegOR( pVBInfo->Part4Port , 0x30 , 0x20 ) ; /* reset spectrum */
XGI_LongWait(pVBInfo) ;
XGINew_SetReg1( pVBInfo->Part4Port , 0x31 , pVBInfo->LCDCapList[ index ].Spectrum_31 ) ;
XGINew_SetReg1( pVBInfo->Part4Port , 0x32 , pVBInfo->LCDCapList[ index ].Spectrum_32 ) ;
XGINew_SetReg1( pVBInfo->Part4Port , 0x33 , pVBInfo->LCDCapList[ index ].Spectrum_33 ) ;
XGINew_SetReg1( pVBInfo->Part4Port , 0x34 , pVBInfo->LCDCapList[ index ].Spectrum_34 ) ;
XGI_LongWait(pVBInfo) ;
XGINew_SetRegOR( pVBInfo->Part4Port , 0x30 , 0x40 ) ; /* enable spectrum */
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetAntiFlicker */
/* Input : */
/* Output : */
/* Description : Set TV Customized Param. */
/* --------------------------------------------------------------------- */
void XGI_SetAntiFlicker(unsigned short ModeNo, unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned short tempbx ,
index ;
unsigned char tempah ;
if (pVBInfo->TVInfo & ( SetYPbPrMode525p | SetYPbPrMode750p ) )
return ;
tempbx = XGI_GetTVPtrIndex(pVBInfo ) ;
tempbx &= 0xFE ;
if ( ModeNo <= 0x13 )
{
index = pVBInfo->SModeIDTable[ ModeIdIndex ].VB_StTVFlickerIndex ;
}
else
{
index = pVBInfo->EModeIDTable[ ModeIdIndex ].VB_ExtTVFlickerIndex ;
}
tempbx += index ;
tempah = TVAntiFlickList[ tempbx ] ;
tempah = tempah << 4 ;
XGINew_SetRegANDOR( pVBInfo->Part2Port , 0x0A , 0x8F , tempah ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetEdgeEnhance */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetEdgeEnhance(unsigned short ModeNo, unsigned short ModeIdIndex, struct vb_device_info *pVBInfo)
{
unsigned short tempbx ,
index ;
unsigned char tempah ;
tempbx = XGI_GetTVPtrIndex(pVBInfo ) ;
tempbx &= 0xFE ;
if ( ModeNo <= 0x13 )
{
index = pVBInfo->SModeIDTable[ ModeIdIndex ].VB_StTVEdgeIndex ;
}
else
{
index = pVBInfo->EModeIDTable[ ModeIdIndex ].VB_ExtTVEdgeIndex ;
}
tempbx += index ;
tempah = TVEdgeList[ tempbx ] ;
tempah = tempah << 5 ;
XGINew_SetRegANDOR( pVBInfo->Part2Port , 0x3A , 0x1F , tempah ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetPhaseIncr */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetPhaseIncr(struct vb_device_info *pVBInfo)
{
unsigned short tempbx ;
unsigned char tempcl ,
tempch ;
unsigned long tempData ;
XGI_GetTVPtrIndex2( &tempbx , &tempcl , &tempch, pVBInfo ) ; /* bx, cl, ch */
tempData = TVPhaseList[ tempbx ] ;
XGINew_SetReg1(pVBInfo->Part2Port, 0x31,
(unsigned short)(tempData & 0x000000FF));
XGINew_SetReg1(pVBInfo->Part2Port, 0x32,
(unsigned short)((tempData & 0x0000FF00) >> 8));
XGINew_SetReg1(pVBInfo->Part2Port, 0x33,
(unsigned short)((tempData & 0x00FF0000) >> 16));
XGINew_SetReg1(pVBInfo->Part2Port, 0x34,
(unsigned short)((tempData & 0xFF000000) >> 24));
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetYFilter */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_SetYFilter(unsigned short ModeNo, unsigned short ModeIdIndex,
struct vb_device_info *pVBInfo)
{
unsigned short tempbx ,
index ;
unsigned char tempcl ,
tempch ,
tempal ,
*filterPtr ;
XGI_GetTVPtrIndex2( &tempbx , &tempcl , &tempch, pVBInfo ) ; /* bx, cl, ch */
switch( tempbx )
{
case 0x00:
case 0x04:
filterPtr = NTSCYFilter1 ;
break ;
case 0x01:
filterPtr = PALYFilter1 ;
break ;
case 0x02:
case 0x05:
case 0x0D:
filterPtr = PALMYFilter1 ;
break ;
case 0x03:
filterPtr = PALNYFilter1 ;
break ;
case 0x08:
case 0x0C:
filterPtr = NTSCYFilter2 ;
break ;
case 0x0A:
filterPtr = PALMYFilter2 ;
break ;
case 0x0B:
filterPtr = PALNYFilter2 ;
break ;
case 0x09:
filterPtr = PALYFilter2 ;
break ;
default:
return ;
}
if ( ModeNo <= 0x13 )
tempal = pVBInfo->SModeIDTable[ ModeIdIndex ].VB_StTVYFilterIndex ;
else
tempal = pVBInfo->EModeIDTable[ ModeIdIndex ].VB_ExtTVYFilterIndex ;
if ( tempcl == 0 )
index = tempal * 4;
else
index = tempal * 7;
if ( ( tempcl == 0 ) && ( tempch == 1 ) )
{
XGINew_SetReg1( pVBInfo->Part2Port , 0x35 , 0 ) ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x36 , 0 ) ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x37 , 0 ) ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x38 , filterPtr[ index++ ] ) ;
}
else
{
XGINew_SetReg1( pVBInfo->Part2Port , 0x35 , filterPtr[ index++ ] ) ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x36 , filterPtr[ index++ ] ) ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x37 , filterPtr[ index++ ] ) ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x38 , filterPtr[ index++ ] ) ;
}
if ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{
XGINew_SetReg1( pVBInfo->Part2Port , 0x48 , filterPtr[ index++ ] ) ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x49 , filterPtr[ index++ ] ) ;
XGINew_SetReg1( pVBInfo->Part2Port , 0x4A , filterPtr[ index++ ] ) ;
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetTVPtrIndex2 */
/* Input : */
/* Output : bx 0 : NTSC */
/* 1 : PAL */
/* 2 : PALM */
/* 3 : PALN */
/* 4 : NTSC1024x768 */
/* 5 : PAL-M 1024x768 */
/* 6-7: reserved */
/* cl 0 : YFilter1 */
/* 1 : YFilter2 */
/* ch 0 : 301A */
/* 1 : 301B/302B/301LV/302LV */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_GetTVPtrIndex2(unsigned short *tempbx, unsigned char *tempcl,
unsigned char *tempch, struct vb_device_info *pVBInfo)
{
*tempbx = 0 ;
*tempcl = 0 ;
*tempch = 0 ;
if ( pVBInfo->TVInfo & SetPALTV )
*tempbx = 1 ;
if ( pVBInfo->TVInfo & SetPALMTV )
*tempbx = 2 ;
if ( pVBInfo->TVInfo & SetPALNTV )
*tempbx = 3 ;
if ( pVBInfo->TVInfo & NTSC1024x768 )
{
*tempbx = 4 ;
if ( pVBInfo->TVInfo & SetPALMTV )
*tempbx = 5 ;
}
if ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{
if ( ( !( pVBInfo->VBInfo & SetInSlaveMode ) ) || ( pVBInfo->TVInfo & TVSimuMode ) )
{
*tempbx += 8 ;
*tempcl += 1 ;
}
}
if ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
(*tempch)++ ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_SetCRT2ModeRegs */
/* Input : */
/* Output : */
/* Description : Origin code for crt2group */
/* --------------------------------------------------------------------- */
void XGI_SetCRT2ModeRegs(unsigned short ModeNo,
struct xgi_hw_device_info *HwDeviceExtension,
struct vb_device_info *pVBInfo)
{
unsigned short tempbl ;
short tempcl ;
unsigned char tempah ;
/* XGINew_SetReg1( pVBInfo->Part1Port , 0x03 , 0x00 ) ; // fix write part1 index 0 BTDRAM bit Bug */
tempah=0;
if ( !( pVBInfo->VBInfo & DisableCRT2Display ) )
{
tempah=XGINew_GetReg1( pVBInfo->Part1Port , 0x00 ) ;
tempah &= ~0x10 ; /* BTRAMDAC */
tempah |= 0x40 ; /* BTRAM */
if ( pVBInfo->VBInfo & ( SetCRT2ToRAMDAC | SetCRT2ToTV | SetCRT2ToLCD ) )
{
tempah=0x40; /* BTDRAM */
if ( ModeNo > 0x13 )
{
tempcl = pVBInfo->ModeType ;
tempcl -= ModeVGA ;
if ( tempcl >= 0 )
{
tempah = ( 0x008 >> tempcl ) ; /* BT Color */
if ( tempah == 0 )
tempah = 1 ;
tempah |= 0x040 ;
}
}
if ( pVBInfo->VBInfo & SetInSlaveMode )
tempah ^= 0x50 ; /* BTDAC */
}
}
/* 0210 shampoo
if ( pVBInfo->VBInfo & DisableCRT2Display )
{
tempah = 0 ;
}
XGINew_SetReg1( pVBInfo->Part1Port , 0x00 , tempah ) ;
if ( pVBInfo->VBInfo & ( SetCRT2ToRAMDAC | SetCRT2ToTV | SetCRT2ToLCD ) )
{
tempcl = pVBInfo->ModeType ;
if ( ModeNo > 0x13 )
{
tempcl -= ModeVGA ;
if ( ( tempcl > 0 ) || ( tempcl == 0 ) )
{
tempah=(0x008>>tempcl) ;
if ( tempah == 0 )
tempah = 1 ;
tempah |= 0x040;
}
}
else
{
tempah = 0x040 ;
}
if ( pVBInfo->VBInfo & SetInSlaveMode )
{
tempah = ( tempah ^ 0x050 ) ;
}
}
*/
XGINew_SetReg1( pVBInfo->Part1Port , 0x00 , tempah ) ;
tempah = 0x08 ;
tempbl = 0xf0 ;
if ( pVBInfo->VBInfo & DisableCRT2Display )
XGINew_SetRegANDOR( pVBInfo->Part1Port , 0x2e , tempbl , tempah ) ;
else
{
tempah = 0x00 ;
tempbl = 0xff ;
if ( pVBInfo->VBInfo & ( SetCRT2ToRAMDAC | SetCRT2ToTV | SetCRT2ToLCD | SetCRT2ToLCDA ) )
{
if ( ( pVBInfo->VBInfo & SetCRT2ToLCDA ) && ( !( pVBInfo->VBInfo & SetSimuScanMode ) ) )
{
tempbl &= 0xf7 ;
tempah |= 0x01 ;
XGINew_SetRegANDOR( pVBInfo->Part1Port , 0x2e , tempbl , tempah ) ;
}
else
{
if ( pVBInfo->VBInfo & SetCRT2ToLCDA )
{
tempbl &= 0xf7 ;
tempah |= 0x01 ;
}
if ( pVBInfo->VBInfo & ( SetCRT2ToRAMDAC | SetCRT2ToTV | SetCRT2ToLCD ) )
{
tempbl &= 0xf8 ;
tempah = 0x01 ;
if ( !( pVBInfo->VBInfo & SetInSlaveMode ) )
tempah |= 0x02 ;
if ( !( pVBInfo->VBInfo & SetCRT2ToRAMDAC ) )
{
tempah = tempah ^ 0x05 ;
if ( !( pVBInfo->VBInfo & SetCRT2ToLCD ) )
tempah = tempah ^ 0x01 ;
}
if ( !( pVBInfo->VBInfo & SetCRT2ToDualEdge ) )
tempah |= 0x08 ;
XGINew_SetRegANDOR( pVBInfo->Part1Port , 0x2e , tempbl , tempah ) ;
}
else
XGINew_SetRegANDOR( pVBInfo->Part1Port , 0x2e , tempbl , tempah ) ;
}
}
else
XGINew_SetRegANDOR( pVBInfo->Part1Port , 0x2e , tempbl , tempah ) ;
}
if ( pVBInfo->VBInfo & ( SetCRT2ToRAMDAC | SetCRT2ToTV | SetCRT2ToLCD | SetCRT2ToLCDA ) )
{
tempah &= ( ~0x08 ) ;
if ( ( pVBInfo->ModeType == ModeVGA ) && ( !( pVBInfo->VBInfo & SetInSlaveMode ) ) )
{
tempah |= 0x010 ;
}
tempah |= 0x080 ;
if ( pVBInfo->VBInfo & SetCRT2ToTV )
{
/* if ( !( pVBInfo->TVInfo & ( SetYPbPrMode525p | SetYPbPrMode750p ) ) ) */
/* { */
tempah |= 0x020 ;
if ( ModeNo > 0x13 )
{
if ( pVBInfo->VBInfo & DriverMode )
tempah = tempah ^ 0x20 ;
}
/* } */
}
XGINew_SetRegANDOR( pVBInfo->Part4Port , 0x0D , ~0x0BF , tempah ) ;
tempah = 0 ;
if ( pVBInfo->LCDInfo & SetLCDDualLink )
tempah |= 0x40 ;
if ( pVBInfo->VBInfo & SetCRT2ToTV )
{
/* if ( ( !( pVBInfo->VBInfo & SetCRT2ToHiVisionTV ) ) && ( !( pVBInfo->TVInfo & ( SetYPbPrMode525p | SetYPbPrMode750p ) ) ) ) */
/* { */
if ( pVBInfo->TVInfo & RPLLDIV2XO )
tempah |= 0x40 ;
/* } */
}
if ( ( pVBInfo->LCDResInfo == Panel1280x1024 ) || ( pVBInfo->LCDResInfo == Panel1280x1024x75 ) )
tempah |= 0x80 ;
if ( pVBInfo->LCDResInfo == Panel1280x960 )
tempah |= 0x80 ;
XGINew_SetReg1( pVBInfo->Part4Port , 0x0C , tempah ) ;
}
if ( pVBInfo->VBType & ( VB_XGI301B | VB_XGI302B | VB_XGI301LV | VB_XGI302LV | VB_XGI301C ) )
{
tempah = 0 ;
tempbl = 0xfb ;
if ( pVBInfo->VBInfo & SetCRT2ToDualEdge )
{
tempbl=0xff;
if ( pVBInfo->VBInfo & SetCRT2ToLCDA )
tempah |= 0x04 ; /* shampoo 0129 */
}
XGINew_SetRegANDOR( pVBInfo->Part1Port , 0x13 , tempbl , tempah ) ;
tempah = 0x00 ;
tempbl = 0xcf ;
if ( !( pVBInfo->VBInfo & DisableCRT2Display ) )
{
if ( pVBInfo->VBInfo & SetCRT2ToDualEdge )
tempah |= 0x30 ;
}
XGINew_SetRegANDOR( pVBInfo->Part1Port , 0x2c , tempbl , tempah ) ;
tempah = 0 ;
tempbl = 0x3f ;
if ( !( pVBInfo->VBInfo & DisableCRT2Display ) )
{
if ( pVBInfo->VBInfo & SetCRT2ToDualEdge )
tempah |= 0xc0 ;
}
XGINew_SetRegANDOR( pVBInfo->Part4Port , 0x21 , tempbl , tempah ) ;
}
tempah = 0 ;
tempbl = 0x7f ;
if ( !( pVBInfo->VBInfo & SetCRT2ToLCDA ) )
{
tempbl = 0xff ;
if ( !( pVBInfo->VBInfo & SetCRT2ToDualEdge ) )
tempah |= 0x80 ;
}
XGINew_SetRegANDOR( pVBInfo->Part4Port , 0x23 , tempbl , tempah ) ;
if ( pVBInfo->VBType & ( VB_XGI302LV | VB_XGI301C ) )
{
if ( pVBInfo->LCDInfo & SetLCDDualLink )
{
XGINew_SetRegOR( pVBInfo->Part4Port , 0x27 , 0x20 ) ;
XGINew_SetRegOR( pVBInfo->Part4Port , 0x34 , 0x10 ) ;
}
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_CloseCRTC */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_CloseCRTC(struct xgi_hw_device_info *HwDeviceExtension, struct vb_device_info *pVBInfo)
{
unsigned short tempbx ;
tempbx = 0 ;
if ( pVBInfo->VBInfo & SetCRT2ToLCDA )
tempbx = 0x08A0 ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_OpenCRTC */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_OpenCRTC(struct xgi_hw_device_info *HwDeviceExtension, struct vb_device_info *pVBInfo)
{
unsigned short tempbx ;
tempbx = 0 ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetRAMDAC2DATA */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_GetRAMDAC2DATA(unsigned short ModeNo, unsigned short ModeIdIndex, unsigned short RefreshRateTableIndex, struct vb_device_info *pVBInfo)
{
unsigned short tempax ,
tempbx ,
temp1 ,
temp2 ,
modeflag = 0 ,
tempcx ,
StandTableIndex ,
CRT1Index ;
pVBInfo->RVBHCMAX = 1 ;
pVBInfo->RVBHCFACT = 1 ;
if ( ModeNo <= 0x13 )
{
modeflag = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ;
StandTableIndex = XGI_GetModePtr( ModeNo , ModeIdIndex, pVBInfo ) ;
tempax = pVBInfo->StandTable[ StandTableIndex ].CRTC[ 0 ] ;
tempbx = pVBInfo->StandTable[StandTableIndex ].CRTC[ 6 ] ;
temp1 = pVBInfo->StandTable[ StandTableIndex ].CRTC[ 7 ] ;
}
else
{
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ;
CRT1Index = pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_CRT1CRTC ;
CRT1Index &= IndexMask ;
temp1 = (unsigned short)pVBInfo->XGINEWUB_CRT1Table[CRT1Index].CR[0];
temp2 = (unsigned short)pVBInfo->XGINEWUB_CRT1Table[CRT1Index].CR[5];
tempax = ( temp1 & 0xFF ) | ( ( temp2 & 0x03 ) << 8 ) ;
tempbx = (unsigned short)pVBInfo->XGINEWUB_CRT1Table[CRT1Index].CR[8];
tempcx = (unsigned short)pVBInfo->XGINEWUB_CRT1Table[CRT1Index].CR[14] << 8;
tempcx &= 0x0100 ;
tempcx = tempcx << 2 ;
tempbx |= tempcx;
temp1 = (unsigned short)pVBInfo->XGINEWUB_CRT1Table[CRT1Index].CR[9];
}
if ( temp1 & 0x01 )
tempbx |= 0x0100 ;
if ( temp1 & 0x20 )
tempbx |= 0x0200 ;
tempax += 5 ;
if ( modeflag & Charx8Dot )
tempax *= 8 ;
else
tempax *= 9 ;
pVBInfo->VGAHT = tempax ;
pVBInfo->HT = tempax ;
tempbx++ ;
pVBInfo->VGAVT = tempbx ;
pVBInfo->VT = tempbx ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetColorDepth */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
unsigned short XGI_GetColorDepth(unsigned short ModeNo, unsigned short ModeIdIndex, struct vb_device_info *pVBInfo)
{
unsigned short ColorDepth[ 6 ] = { 1 , 2 , 4 , 4 , 6 , 8 } ;
short index ;
unsigned short modeflag ;
if ( ModeNo <= 0x13 )
{
modeflag = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ;
}
else
{
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ;
}
index=(modeflag&ModeInfoFlag)-ModeEGA;
if ( index < 0 )
index = 0 ;
return( ColorDepth[ index ] ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_UnLockCRT2 */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_UnLockCRT2(struct xgi_hw_device_info *HwDeviceExtension, struct vb_device_info *pVBInfo)
{
XGINew_SetRegANDOR( pVBInfo->Part1Port , 0x2f , 0xFF , 0x01 ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_LockCRT2 */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_LockCRT2(struct xgi_hw_device_info *HwDeviceExtension, struct vb_device_info *pVBInfo)
{
XGINew_SetRegANDOR( pVBInfo->Part1Port , 0x2F , 0xFE , 0x00 ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGINew_EnableCRT2 */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGINew_EnableCRT2(struct vb_device_info *pVBInfo)
{
XGINew_SetRegANDOR( pVBInfo->P3c4 , 0x1E , 0xFF , 0x20 ) ;
}
/* --------------------------------------------------------------------- */
/* Function : */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGINew_LCD_Wait_Time(unsigned char DelayTime, struct vb_device_info *pVBInfo)
{
unsigned short i ,
j ;
unsigned long temp ,
flag ;
flag = 0 ;
//printk("XGINew_LCD_Wait_Time");
//return;
for( i = 0 ; i < DelayTime ; i++ )
{
for( j = 0 ; j < 66 ; j++ )
{
temp = XGINew_GetReg3( 0x61 ) ;
//temp &= 0x10000000;
temp &= 0x10;
if ( temp == flag )
continue ;
flag = temp ;
}
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_BridgeIsOn */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
unsigned char XGI_BridgeIsOn(struct vb_device_info *pVBInfo)
{
unsigned short flag ;
if ( pVBInfo->IF_DEF_LVDS == 1 )
{
return( 1 ) ;
}
else
{
flag = XGINew_GetReg1( pVBInfo->Part4Port , 0x00 ) ;
if ( ( flag == 1 ) || ( flag == 2 ) )
return( 1 ) ; /* 301b */
else
return( 0 ) ;
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_LongWait */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_LongWait(struct vb_device_info *pVBInfo)
{
unsigned short i ;
i = XGINew_GetReg1( pVBInfo->P3c4 , 0x1F ) ;
if ( !( i & 0xC0 ) )
{
for( i = 0 ; i < 0xFFFF ; i++ )
{
if ( !( XGINew_GetReg2( pVBInfo->P3da ) & 0x08 ) )
break ;
}
for( i = 0 ; i < 0xFFFF ; i++ )
{
if ( ( XGINew_GetReg2( pVBInfo->P3da ) & 0x08 ) )
break ;
}
}
}
/* --------------------------------------------------------------------- */
/* Function : XGI_VBLongWait */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
void XGI_VBLongWait(struct vb_device_info *pVBInfo)
{
unsigned short tempal ,
temp ,
i ,
j ;
return ;
if ( !( pVBInfo->VBInfo & SetCRT2ToTV ) )
{
temp = 0 ;
for( i = 0 ; i < 3 ; i++ )
{
for( j = 0 ; j < 100 ; j++ )
{
tempal = XGINew_GetReg2( pVBInfo->P3da ) ;
if ( temp & 0x01 )
{ /* VBWaitMode2 */
if ( ( tempal & 0x08 ) )
{
continue ;
}
if ( !( tempal & 0x08 ) )
{
break ;
}
}
else
{ /* VBWaitMode1 */
if ( !( tempal & 0x08 ) )
{
continue ;
}
if ( ( tempal & 0x08 ) )
{
break ;
}
}
}
temp = temp ^ 0x01 ;
}
}
else
{
XGI_LongWait(pVBInfo) ;
}
return ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetVGAHT2 */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
unsigned short XGI_GetVGAHT2(struct vb_device_info *pVBInfo)
{
unsigned long tempax ,
tempbx ;
tempbx = ( ( pVBInfo->VGAVT - pVBInfo->VGAVDE ) * pVBInfo->RVBHCMAX ) & 0xFFFF ;
tempax = ( pVBInfo->VT - pVBInfo->VDE ) * pVBInfo->RVBHCFACT ;
tempax = ( tempax * pVBInfo->HT ) /tempbx ;
return( (unsigned short)tempax ) ;
}
/* --------------------------------------------------------------------- */
/* Function : XGI_GetVCLK2Ptr */
/* Input : */
/* Output : */
/* Description : */
/* --------------------------------------------------------------------- */
unsigned short XGI_GetVCLK2Ptr(unsigned short ModeNo,
unsigned short ModeIdIndex,
unsigned short RefreshRateTableIndex,
struct xgi_hw_device_info *HwDeviceExtension,
struct vb_device_info *pVBInfo)
{
unsigned short tempbx ;
unsigned short LCDXlat1VCLK[ 4 ] = { VCLK65 + 2 , VCLK65 + 2 , VCLK65 + 2 , VCLK65 + 2 } ;
unsigned short LCDXlat2VCLK[ 4 ] = { VCLK108_2 + 5 , VCLK108_2 + 5 , VCLK108_2 + 5 , VCLK108_2 + 5 } ;
unsigned short LVDSXlat1VCLK[ 4 ] = { VCLK40 , VCLK40 , VCLK40 , VCLK40 } ;
unsigned short LVDSXlat2VCLK[ 4 ] = { VCLK65 + 2 , VCLK65 + 2 , VCLK65 + 2 , VCLK65 + 2 } ;
unsigned short LVDSXlat3VCLK[ 4 ] = { VCLK65 + 2 , VCLK65 + 2 , VCLK65 + 2 , VCLK65 + 2 } ;
unsigned short CRT2Index , VCLKIndex ;
unsigned short modeflag , resinfo ;
unsigned char *CHTVVCLKPtr = NULL ;
if ( ModeNo <= 0x13 )
{
modeflag = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ModeFlag ; /* si+St_ResInfo */
resinfo = pVBInfo->SModeIDTable[ ModeIdIndex ].St_ResInfo ;
CRT2Index = pVBInfo->SModeIDTable[ ModeIdIndex ].St_CRT2CRTC ;
}
else
{
modeflag = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_ModeFlag ; /* si+Ext_ResInfo */
resinfo = pVBInfo->EModeIDTable[ ModeIdIndex ].Ext_RESINFO ;
CRT2Index = pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_CRT2CRTC ;
}
if ( pVBInfo->IF_DEF_LVDS == 0 )
{
CRT2Index = CRT2Index >> 6 ; /* for LCD */
if ( ( ( pVBInfo->VBInfo & SetCRT2ToLCD ) | SetCRT2ToLCDA ) ) /*301b*/
{
if ( pVBInfo->LCDResInfo != Panel1024x768 )
{
VCLKIndex = LCDXlat2VCLK[ CRT2Index ] ;
}
else
{
VCLKIndex = LCDXlat1VCLK[ CRT2Index ] ;
}
}
else /* for TV */
{
if ( pVBInfo->VBInfo & SetCRT2ToTV )
{
if ( pVBInfo->VBInfo & SetCRT2ToHiVisionTV )
{
if ( pVBInfo->SetFlag & RPLLDIV2XO )
{
VCLKIndex = HiTVVCLKDIV2 ;
VCLKIndex += 25 ;
}
else
{
VCLKIndex = HiTVVCLK ;
VCLKIndex += 25 ;
}
if ( pVBInfo->SetFlag & TVSimuMode )
{
if( modeflag & Charx8Dot )
{
VCLKIndex = HiTVSimuVCLK ;
VCLKIndex += 25 ;
}
else
{
VCLKIndex = HiTVTextVCLK ;
VCLKIndex += 25 ;
}
}
if ( pVBInfo->VBType & VB_XGI301LV ) /* 301lv */
{
if ( !( pVBInfo->VBExtInfo == VB_YPbPr1080i ) )
{
VCLKIndex = YPbPr750pVCLK ;
if ( !( pVBInfo->VBExtInfo == VB_YPbPr750p ) )
{
VCLKIndex = YPbPr525pVCLK ;
if ( !( pVBInfo->VBExtInfo == VB_YPbPr525p ) )
{
VCLKIndex = YPbPr525iVCLK_2 ;
if ( !( pVBInfo->SetFlag & RPLLDIV2XO ) )
VCLKIndex = YPbPr525iVCLK ;
}
}
}
}
}
else
{
if ( pVBInfo->VBInfo & SetCRT2ToTV )
{
if ( pVBInfo->SetFlag & RPLLDIV2XO )
{
VCLKIndex = TVVCLKDIV2 ;
VCLKIndex += 25 ;
}
else
{
VCLKIndex = TVVCLK ;
VCLKIndex += 25 ;
}
}
}
}
else
{ /* for CRT2 */
VCLKIndex = (unsigned char)XGINew_GetReg2((pVBInfo->P3ca + 0x02)); /* Port 3cch */
VCLKIndex = ( ( VCLKIndex >> 2 ) & 0x03 ) ;
if ( ModeNo > 0x13 )
{
VCLKIndex = pVBInfo->RefIndex[ RefreshRateTableIndex ].Ext_CRTVCLK ; /* di+Ext_CRTVCLK */
VCLKIndex &= IndexMask ;
}
}
}
}
else
{ /* LVDS */
if ( ModeNo <= 0x13 )
VCLKIndex = CRT2Index ;
else
VCLKIndex = CRT2Index ;
if ( pVBInfo->IF_DEF_CH7005 == 1 )
{
if ( !( pVBInfo->VBInfo & SetCRT2ToLCD ) )
{
VCLKIndex &= 0x1f ;
tempbx = 0 ;
if ( pVBInfo->VBInfo & SetPALTV )
tempbx += 2 ;
if ( pVBInfo->VBInfo & SetCHTVOverScan )
tempbx += 1 ;
switch( tempbx )
{
case 0:
CHTVVCLKPtr = pVBInfo->CHTVVCLKUNTSC ;
break ;
case 1:
CHTVVCLKPtr = pVBInfo->CHTVVCLKONTSC ;
break;
case 2:
CHTVVCLKPtr = pVBInfo->CHTVVCLKUPAL ;
break ;
case 3:
CHTVVCLKPtr = pVBInfo->CHTVVCLKOPAL ;
break ;
default:
break ;
}
VCLKIndex = CHTVVCLKPtr[ VCLKIndex ] ;
}
}
else
{
VCLKIndex = VCLKIndex >> 6 ;
if ( ( pVBInfo->LCDResInfo == Panel800x600 ) || ( pVBInfo->LCDResInfo == Panel320x480 ) )
VCLKIndex = LVDSXlat1VCLK[ VCLKIndex ] ;
else if ( ( pVBInfo->LCDResInfo == Panel1024x768 ) || ( pVBInfo->LCDResInfo == Panel1024x768x75 ) )
VCLKIndex = LVDSXlat2VCLK[ VCLKIndex ] ;
else
VCLKIndex = LVDSXlat3VCLK[ VCLKIndex ] ;
}
}
/* VCLKIndex = VCLKIndex&IndexMask ; */
return( VCLKIndex ) ;
}
| gpl-2.0 |
arunkuttiyara/linux | fs/fuse/dev.c | 93 | 53181 | /*
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/init.h>
#include <linux/module.h>
#include <linux/poll.h>
#include <linux/uio.h>
#include <linux/miscdevice.h>
#include <linux/pagemap.h>
#include <linux/file.h>
#include <linux/slab.h>
#include <linux/pipe_fs_i.h>
#include <linux/swap.h>
#include <linux/splice.h>
MODULE_ALIAS_MISCDEV(FUSE_MINOR);
MODULE_ALIAS("devname:fuse");
static struct kmem_cache *fuse_req_cachep;
static struct fuse_dev *fuse_get_dev(struct file *file)
{
/*
* Lockless access is OK, because file->private data is set
* once during mount and is valid until the file is released.
*/
return ACCESS_ONCE(file->private_data);
}
static void fuse_request_init(struct fuse_req *req, struct page **pages,
struct fuse_page_desc *page_descs,
unsigned npages)
{
memset(req, 0, sizeof(*req));
memset(pages, 0, sizeof(*pages) * npages);
memset(page_descs, 0, sizeof(*page_descs) * npages);
INIT_LIST_HEAD(&req->list);
INIT_LIST_HEAD(&req->intr_entry);
init_waitqueue_head(&req->waitq);
atomic_set(&req->count, 1);
req->pages = pages;
req->page_descs = page_descs;
req->max_pages = npages;
__set_bit(FR_PENDING, &req->flags);
}
static struct fuse_req *__fuse_request_alloc(unsigned npages, gfp_t flags)
{
struct fuse_req *req = kmem_cache_alloc(fuse_req_cachep, flags);
if (req) {
struct page **pages;
struct fuse_page_desc *page_descs;
if (npages <= FUSE_REQ_INLINE_PAGES) {
pages = req->inline_pages;
page_descs = req->inline_page_descs;
} else {
pages = kmalloc(sizeof(struct page *) * npages, flags);
page_descs = kmalloc(sizeof(struct fuse_page_desc) *
npages, flags);
}
if (!pages || !page_descs) {
kfree(pages);
kfree(page_descs);
kmem_cache_free(fuse_req_cachep, req);
return NULL;
}
fuse_request_init(req, pages, page_descs, npages);
}
return req;
}
struct fuse_req *fuse_request_alloc(unsigned npages)
{
return __fuse_request_alloc(npages, GFP_KERNEL);
}
EXPORT_SYMBOL_GPL(fuse_request_alloc);
struct fuse_req *fuse_request_alloc_nofs(unsigned npages)
{
return __fuse_request_alloc(npages, GFP_NOFS);
}
void fuse_request_free(struct fuse_req *req)
{
if (req->pages != req->inline_pages) {
kfree(req->pages);
kfree(req->page_descs);
}
kmem_cache_free(fuse_req_cachep, req);
}
static void block_sigs(sigset_t *oldset)
{
sigset_t mask;
siginitsetinv(&mask, sigmask(SIGKILL));
sigprocmask(SIG_BLOCK, &mask, oldset);
}
static void restore_sigs(sigset_t *oldset)
{
sigprocmask(SIG_SETMASK, oldset, NULL);
}
void __fuse_get_request(struct fuse_req *req)
{
atomic_inc(&req->count);
}
/* Must be called with > 1 refcount */
static void __fuse_put_request(struct fuse_req *req)
{
BUG_ON(atomic_read(&req->count) < 2);
atomic_dec(&req->count);
}
static void fuse_req_init_context(struct fuse_req *req)
{
req->in.h.uid = from_kuid_munged(&init_user_ns, current_fsuid());
req->in.h.gid = from_kgid_munged(&init_user_ns, current_fsgid());
req->in.h.pid = current->pid;
}
void fuse_set_initialized(struct fuse_conn *fc)
{
/* Make sure stores before this are seen on another CPU */
smp_wmb();
fc->initialized = 1;
}
static bool fuse_block_alloc(struct fuse_conn *fc, bool for_background)
{
return !fc->initialized || (for_background && fc->blocked);
}
static struct fuse_req *__fuse_get_req(struct fuse_conn *fc, unsigned npages,
bool for_background)
{
struct fuse_req *req;
int err;
atomic_inc(&fc->num_waiting);
if (fuse_block_alloc(fc, for_background)) {
sigset_t oldset;
int intr;
block_sigs(&oldset);
intr = wait_event_interruptible_exclusive(fc->blocked_waitq,
!fuse_block_alloc(fc, for_background));
restore_sigs(&oldset);
err = -EINTR;
if (intr)
goto out;
}
/* Matches smp_wmb() in fuse_set_initialized() */
smp_rmb();
err = -ENOTCONN;
if (!fc->connected)
goto out;
err = -ECONNREFUSED;
if (fc->conn_error)
goto out;
req = fuse_request_alloc(npages);
err = -ENOMEM;
if (!req) {
if (for_background)
wake_up(&fc->blocked_waitq);
goto out;
}
fuse_req_init_context(req);
__set_bit(FR_WAITING, &req->flags);
if (for_background)
__set_bit(FR_BACKGROUND, &req->flags);
return req;
out:
atomic_dec(&fc->num_waiting);
return ERR_PTR(err);
}
struct fuse_req *fuse_get_req(struct fuse_conn *fc, unsigned npages)
{
return __fuse_get_req(fc, npages, false);
}
EXPORT_SYMBOL_GPL(fuse_get_req);
struct fuse_req *fuse_get_req_for_background(struct fuse_conn *fc,
unsigned npages)
{
return __fuse_get_req(fc, npages, true);
}
EXPORT_SYMBOL_GPL(fuse_get_req_for_background);
/*
* Return request in fuse_file->reserved_req. However that may
* currently be in use. If that is the case, wait for it to become
* available.
*/
static struct fuse_req *get_reserved_req(struct fuse_conn *fc,
struct file *file)
{
struct fuse_req *req = NULL;
struct fuse_file *ff = file->private_data;
do {
wait_event(fc->reserved_req_waitq, ff->reserved_req);
spin_lock(&fc->lock);
if (ff->reserved_req) {
req = ff->reserved_req;
ff->reserved_req = NULL;
req->stolen_file = get_file(file);
}
spin_unlock(&fc->lock);
} while (!req);
return req;
}
/*
* Put stolen request back into fuse_file->reserved_req
*/
static void put_reserved_req(struct fuse_conn *fc, struct fuse_req *req)
{
struct file *file = req->stolen_file;
struct fuse_file *ff = file->private_data;
spin_lock(&fc->lock);
fuse_request_init(req, req->pages, req->page_descs, req->max_pages);
BUG_ON(ff->reserved_req);
ff->reserved_req = req;
wake_up_all(&fc->reserved_req_waitq);
spin_unlock(&fc->lock);
fput(file);
}
/*
* Gets a requests for a file operation, always succeeds
*
* This is used for sending the FLUSH request, which must get to
* userspace, due to POSIX locks which may need to be unlocked.
*
* If allocation fails due to OOM, use the reserved request in
* fuse_file.
*
* This is very unlikely to deadlock accidentally, since the
* filesystem should not have it's own file open. If deadlock is
* intentional, it can still be broken by "aborting" the filesystem.
*/
struct fuse_req *fuse_get_req_nofail_nopages(struct fuse_conn *fc,
struct file *file)
{
struct fuse_req *req;
atomic_inc(&fc->num_waiting);
wait_event(fc->blocked_waitq, fc->initialized);
/* Matches smp_wmb() in fuse_set_initialized() */
smp_rmb();
req = fuse_request_alloc(0);
if (!req)
req = get_reserved_req(fc, file);
fuse_req_init_context(req);
__set_bit(FR_WAITING, &req->flags);
__clear_bit(FR_BACKGROUND, &req->flags);
return req;
}
void fuse_put_request(struct fuse_conn *fc, struct fuse_req *req)
{
if (atomic_dec_and_test(&req->count)) {
if (test_bit(FR_BACKGROUND, &req->flags)) {
/*
* We get here in the unlikely case that a background
* request was allocated but not sent
*/
spin_lock(&fc->lock);
if (!fc->blocked)
wake_up(&fc->blocked_waitq);
spin_unlock(&fc->lock);
}
if (test_bit(FR_WAITING, &req->flags)) {
__clear_bit(FR_WAITING, &req->flags);
atomic_dec(&fc->num_waiting);
}
if (req->stolen_file)
put_reserved_req(fc, req);
else
fuse_request_free(req);
}
}
EXPORT_SYMBOL_GPL(fuse_put_request);
static unsigned len_args(unsigned numargs, struct fuse_arg *args)
{
unsigned nbytes = 0;
unsigned i;
for (i = 0; i < numargs; i++)
nbytes += args[i].size;
return nbytes;
}
static u64 fuse_get_unique(struct fuse_iqueue *fiq)
{
return ++fiq->reqctr;
}
static void queue_request(struct fuse_iqueue *fiq, struct fuse_req *req)
{
req->in.h.len = sizeof(struct fuse_in_header) +
len_args(req->in.numargs, (struct fuse_arg *) req->in.args);
list_add_tail(&req->list, &fiq->pending);
wake_up_locked(&fiq->waitq);
kill_fasync(&fiq->fasync, SIGIO, POLL_IN);
}
void fuse_queue_forget(struct fuse_conn *fc, struct fuse_forget_link *forget,
u64 nodeid, u64 nlookup)
{
struct fuse_iqueue *fiq = &fc->iq;
forget->forget_one.nodeid = nodeid;
forget->forget_one.nlookup = nlookup;
spin_lock(&fiq->waitq.lock);
if (fiq->connected) {
fiq->forget_list_tail->next = forget;
fiq->forget_list_tail = forget;
wake_up_locked(&fiq->waitq);
kill_fasync(&fiq->fasync, SIGIO, POLL_IN);
} else {
kfree(forget);
}
spin_unlock(&fiq->waitq.lock);
}
static void flush_bg_queue(struct fuse_conn *fc)
{
while (fc->active_background < fc->max_background &&
!list_empty(&fc->bg_queue)) {
struct fuse_req *req;
struct fuse_iqueue *fiq = &fc->iq;
req = list_entry(fc->bg_queue.next, struct fuse_req, list);
list_del(&req->list);
fc->active_background++;
spin_lock(&fiq->waitq.lock);
req->in.h.unique = fuse_get_unique(fiq);
queue_request(fiq, req);
spin_unlock(&fiq->waitq.lock);
}
}
/*
* This function is called when a request is finished. Either a reply
* has arrived or it was aborted (and not yet sent) or some error
* occurred during communication with userspace, or the device file
* was closed. The requester thread is woken up (if still waiting),
* the 'end' callback is called if given, else the reference to the
* request is released
*/
static void request_end(struct fuse_conn *fc, struct fuse_req *req)
{
struct fuse_iqueue *fiq = &fc->iq;
if (test_and_set_bit(FR_FINISHED, &req->flags))
return;
spin_lock(&fiq->waitq.lock);
list_del_init(&req->intr_entry);
spin_unlock(&fiq->waitq.lock);
WARN_ON(test_bit(FR_PENDING, &req->flags));
WARN_ON(test_bit(FR_SENT, &req->flags));
if (test_bit(FR_BACKGROUND, &req->flags)) {
spin_lock(&fc->lock);
clear_bit(FR_BACKGROUND, &req->flags);
if (fc->num_background == fc->max_background)
fc->blocked = 0;
/* Wake up next waiter, if any */
if (!fc->blocked && waitqueue_active(&fc->blocked_waitq))
wake_up(&fc->blocked_waitq);
if (fc->num_background == fc->congestion_threshold &&
fc->connected && fc->bdi_initialized) {
clear_bdi_congested(&fc->bdi, BLK_RW_SYNC);
clear_bdi_congested(&fc->bdi, BLK_RW_ASYNC);
}
fc->num_background--;
fc->active_background--;
flush_bg_queue(fc);
spin_unlock(&fc->lock);
}
wake_up(&req->waitq);
if (req->end)
req->end(fc, req);
fuse_put_request(fc, req);
}
static void queue_interrupt(struct fuse_iqueue *fiq, struct fuse_req *req)
{
spin_lock(&fiq->waitq.lock);
if (list_empty(&req->intr_entry)) {
list_add_tail(&req->intr_entry, &fiq->interrupts);
wake_up_locked(&fiq->waitq);
}
spin_unlock(&fiq->waitq.lock);
kill_fasync(&fiq->fasync, SIGIO, POLL_IN);
}
static void request_wait_answer(struct fuse_conn *fc, struct fuse_req *req)
{
struct fuse_iqueue *fiq = &fc->iq;
int err;
if (!fc->no_interrupt) {
/* Any signal may interrupt this */
err = wait_event_interruptible(req->waitq,
test_bit(FR_FINISHED, &req->flags));
if (!err)
return;
set_bit(FR_INTERRUPTED, &req->flags);
/* matches barrier in fuse_dev_do_read() */
smp_mb__after_atomic();
if (test_bit(FR_SENT, &req->flags))
queue_interrupt(fiq, req);
}
if (!test_bit(FR_FORCE, &req->flags)) {
sigset_t oldset;
/* Only fatal signals may interrupt this */
block_sigs(&oldset);
err = wait_event_interruptible(req->waitq,
test_bit(FR_FINISHED, &req->flags));
restore_sigs(&oldset);
if (!err)
return;
spin_lock(&fiq->waitq.lock);
/* Request is not yet in userspace, bail out */
if (test_bit(FR_PENDING, &req->flags)) {
list_del(&req->list);
spin_unlock(&fiq->waitq.lock);
__fuse_put_request(req);
req->out.h.error = -EINTR;
return;
}
spin_unlock(&fiq->waitq.lock);
}
/*
* Either request is already in userspace, or it was forced.
* Wait it out.
*/
wait_event(req->waitq, test_bit(FR_FINISHED, &req->flags));
}
static void __fuse_request_send(struct fuse_conn *fc, struct fuse_req *req)
{
struct fuse_iqueue *fiq = &fc->iq;
BUG_ON(test_bit(FR_BACKGROUND, &req->flags));
spin_lock(&fiq->waitq.lock);
if (!fiq->connected) {
spin_unlock(&fiq->waitq.lock);
req->out.h.error = -ENOTCONN;
} else {
req->in.h.unique = fuse_get_unique(fiq);
queue_request(fiq, req);
/* acquire extra reference, since request is still needed
after request_end() */
__fuse_get_request(req);
spin_unlock(&fiq->waitq.lock);
request_wait_answer(fc, req);
/* Pairs with smp_wmb() in request_end() */
smp_rmb();
}
}
void fuse_request_send(struct fuse_conn *fc, struct fuse_req *req)
{
__set_bit(FR_ISREPLY, &req->flags);
if (!test_bit(FR_WAITING, &req->flags)) {
__set_bit(FR_WAITING, &req->flags);
atomic_inc(&fc->num_waiting);
}
__fuse_request_send(fc, req);
}
EXPORT_SYMBOL_GPL(fuse_request_send);
static void fuse_adjust_compat(struct fuse_conn *fc, struct fuse_args *args)
{
if (fc->minor < 4 && args->in.h.opcode == FUSE_STATFS)
args->out.args[0].size = FUSE_COMPAT_STATFS_SIZE;
if (fc->minor < 9) {
switch (args->in.h.opcode) {
case FUSE_LOOKUP:
case FUSE_CREATE:
case FUSE_MKNOD:
case FUSE_MKDIR:
case FUSE_SYMLINK:
case FUSE_LINK:
args->out.args[0].size = FUSE_COMPAT_ENTRY_OUT_SIZE;
break;
case FUSE_GETATTR:
case FUSE_SETATTR:
args->out.args[0].size = FUSE_COMPAT_ATTR_OUT_SIZE;
break;
}
}
if (fc->minor < 12) {
switch (args->in.h.opcode) {
case FUSE_CREATE:
args->in.args[0].size = sizeof(struct fuse_open_in);
break;
case FUSE_MKNOD:
args->in.args[0].size = FUSE_COMPAT_MKNOD_IN_SIZE;
break;
}
}
}
ssize_t fuse_simple_request(struct fuse_conn *fc, struct fuse_args *args)
{
struct fuse_req *req;
ssize_t ret;
req = fuse_get_req(fc, 0);
if (IS_ERR(req))
return PTR_ERR(req);
/* Needs to be done after fuse_get_req() so that fc->minor is valid */
fuse_adjust_compat(fc, args);
req->in.h.opcode = args->in.h.opcode;
req->in.h.nodeid = args->in.h.nodeid;
req->in.numargs = args->in.numargs;
memcpy(req->in.args, args->in.args,
args->in.numargs * sizeof(struct fuse_in_arg));
req->out.argvar = args->out.argvar;
req->out.numargs = args->out.numargs;
memcpy(req->out.args, args->out.args,
args->out.numargs * sizeof(struct fuse_arg));
fuse_request_send(fc, req);
ret = req->out.h.error;
if (!ret && args->out.argvar) {
BUG_ON(args->out.numargs != 1);
ret = req->out.args[0].size;
}
fuse_put_request(fc, req);
return ret;
}
/*
* Called under fc->lock
*
* fc->connected must have been checked previously
*/
void fuse_request_send_background_locked(struct fuse_conn *fc,
struct fuse_req *req)
{
BUG_ON(!test_bit(FR_BACKGROUND, &req->flags));
if (!test_bit(FR_WAITING, &req->flags)) {
__set_bit(FR_WAITING, &req->flags);
atomic_inc(&fc->num_waiting);
}
__set_bit(FR_ISREPLY, &req->flags);
fc->num_background++;
if (fc->num_background == fc->max_background)
fc->blocked = 1;
if (fc->num_background == fc->congestion_threshold &&
fc->bdi_initialized) {
set_bdi_congested(&fc->bdi, BLK_RW_SYNC);
set_bdi_congested(&fc->bdi, BLK_RW_ASYNC);
}
list_add_tail(&req->list, &fc->bg_queue);
flush_bg_queue(fc);
}
void fuse_request_send_background(struct fuse_conn *fc, struct fuse_req *req)
{
BUG_ON(!req->end);
spin_lock(&fc->lock);
if (fc->connected) {
fuse_request_send_background_locked(fc, req);
spin_unlock(&fc->lock);
} else {
spin_unlock(&fc->lock);
req->out.h.error = -ENOTCONN;
req->end(fc, req);
fuse_put_request(fc, req);
}
}
EXPORT_SYMBOL_GPL(fuse_request_send_background);
static int fuse_request_send_notify_reply(struct fuse_conn *fc,
struct fuse_req *req, u64 unique)
{
int err = -ENODEV;
struct fuse_iqueue *fiq = &fc->iq;
__clear_bit(FR_ISREPLY, &req->flags);
req->in.h.unique = unique;
spin_lock(&fiq->waitq.lock);
if (fiq->connected) {
queue_request(fiq, req);
err = 0;
}
spin_unlock(&fiq->waitq.lock);
return err;
}
void fuse_force_forget(struct file *file, u64 nodeid)
{
struct inode *inode = file_inode(file);
struct fuse_conn *fc = get_fuse_conn(inode);
struct fuse_req *req;
struct fuse_forget_in inarg;
memset(&inarg, 0, sizeof(inarg));
inarg.nlookup = 1;
req = fuse_get_req_nofail_nopages(fc, file);
req->in.h.opcode = FUSE_FORGET;
req->in.h.nodeid = nodeid;
req->in.numargs = 1;
req->in.args[0].size = sizeof(inarg);
req->in.args[0].value = &inarg;
__clear_bit(FR_ISREPLY, &req->flags);
__fuse_request_send(fc, req);
/* ignore errors */
fuse_put_request(fc, req);
}
/*
* Lock the request. Up to the next unlock_request() there mustn't be
* anything that could cause a page-fault. If the request was already
* aborted bail out.
*/
static int lock_request(struct fuse_req *req)
{
int err = 0;
if (req) {
spin_lock(&req->waitq.lock);
if (test_bit(FR_ABORTED, &req->flags))
err = -ENOENT;
else
set_bit(FR_LOCKED, &req->flags);
spin_unlock(&req->waitq.lock);
}
return err;
}
/*
* Unlock request. If it was aborted while locked, caller is responsible
* for unlocking and ending the request.
*/
static int unlock_request(struct fuse_req *req)
{
int err = 0;
if (req) {
spin_lock(&req->waitq.lock);
if (test_bit(FR_ABORTED, &req->flags))
err = -ENOENT;
else
clear_bit(FR_LOCKED, &req->flags);
spin_unlock(&req->waitq.lock);
}
return err;
}
struct fuse_copy_state {
int write;
struct fuse_req *req;
struct iov_iter *iter;
struct pipe_buffer *pipebufs;
struct pipe_buffer *currbuf;
struct pipe_inode_info *pipe;
unsigned long nr_segs;
struct page *pg;
unsigned len;
unsigned offset;
unsigned move_pages:1;
};
static void fuse_copy_init(struct fuse_copy_state *cs, int write,
struct iov_iter *iter)
{
memset(cs, 0, sizeof(*cs));
cs->write = write;
cs->iter = iter;
}
/* Unmap and put previous page of userspace buffer */
static void fuse_copy_finish(struct fuse_copy_state *cs)
{
if (cs->currbuf) {
struct pipe_buffer *buf = cs->currbuf;
if (cs->write)
buf->len = PAGE_SIZE - cs->len;
cs->currbuf = NULL;
} else if (cs->pg) {
if (cs->write) {
flush_dcache_page(cs->pg);
set_page_dirty_lock(cs->pg);
}
put_page(cs->pg);
}
cs->pg = NULL;
}
/*
* Get another pagefull of userspace buffer, and map it to kernel
* address space, and lock request
*/
static int fuse_copy_fill(struct fuse_copy_state *cs)
{
struct page *page;
int err;
err = unlock_request(cs->req);
if (err)
return err;
fuse_copy_finish(cs);
if (cs->pipebufs) {
struct pipe_buffer *buf = cs->pipebufs;
if (!cs->write) {
err = buf->ops->confirm(cs->pipe, buf);
if (err)
return err;
BUG_ON(!cs->nr_segs);
cs->currbuf = buf;
cs->pg = buf->page;
cs->offset = buf->offset;
cs->len = buf->len;
cs->pipebufs++;
cs->nr_segs--;
} else {
if (cs->nr_segs == cs->pipe->buffers)
return -EIO;
page = alloc_page(GFP_HIGHUSER);
if (!page)
return -ENOMEM;
buf->page = page;
buf->offset = 0;
buf->len = 0;
cs->currbuf = buf;
cs->pg = page;
cs->offset = 0;
cs->len = PAGE_SIZE;
cs->pipebufs++;
cs->nr_segs++;
}
} else {
size_t off;
err = iov_iter_get_pages(cs->iter, &page, PAGE_SIZE, 1, &off);
if (err < 0)
return err;
BUG_ON(!err);
cs->len = err;
cs->offset = off;
cs->pg = page;
cs->offset = off;
iov_iter_advance(cs->iter, err);
}
return lock_request(cs->req);
}
/* Do as much copy to/from userspace buffer as we can */
static int fuse_copy_do(struct fuse_copy_state *cs, void **val, unsigned *size)
{
unsigned ncpy = min(*size, cs->len);
if (val) {
void *pgaddr = kmap_atomic(cs->pg);
void *buf = pgaddr + cs->offset;
if (cs->write)
memcpy(buf, *val, ncpy);
else
memcpy(*val, buf, ncpy);
kunmap_atomic(pgaddr);
*val += ncpy;
}
*size -= ncpy;
cs->len -= ncpy;
cs->offset += ncpy;
return ncpy;
}
static int fuse_check_page(struct page *page)
{
if (page_mapcount(page) ||
page->mapping != NULL ||
page_count(page) != 1 ||
(page->flags & PAGE_FLAGS_CHECK_AT_PREP &
~(1 << PG_locked |
1 << PG_referenced |
1 << PG_uptodate |
1 << PG_lru |
1 << PG_active |
1 << PG_reclaim))) {
printk(KERN_WARNING "fuse: trying to steal weird page\n");
printk(KERN_WARNING " page=%p index=%li flags=%08lx, count=%i, mapcount=%i, mapping=%p\n", page, page->index, page->flags, page_count(page), page_mapcount(page), page->mapping);
return 1;
}
return 0;
}
static int fuse_try_move_page(struct fuse_copy_state *cs, struct page **pagep)
{
int err;
struct page *oldpage = *pagep;
struct page *newpage;
struct pipe_buffer *buf = cs->pipebufs;
err = unlock_request(cs->req);
if (err)
return err;
fuse_copy_finish(cs);
err = buf->ops->confirm(cs->pipe, buf);
if (err)
return err;
BUG_ON(!cs->nr_segs);
cs->currbuf = buf;
cs->len = buf->len;
cs->pipebufs++;
cs->nr_segs--;
if (cs->len != PAGE_SIZE)
goto out_fallback;
if (buf->ops->steal(cs->pipe, buf) != 0)
goto out_fallback;
newpage = buf->page;
if (!PageUptodate(newpage))
SetPageUptodate(newpage);
ClearPageMappedToDisk(newpage);
if (fuse_check_page(newpage) != 0)
goto out_fallback_unlock;
/*
* This is a new and locked page, it shouldn't be mapped or
* have any special flags on it
*/
if (WARN_ON(page_mapped(oldpage)))
goto out_fallback_unlock;
if (WARN_ON(page_has_private(oldpage)))
goto out_fallback_unlock;
if (WARN_ON(PageDirty(oldpage) || PageWriteback(oldpage)))
goto out_fallback_unlock;
if (WARN_ON(PageMlocked(oldpage)))
goto out_fallback_unlock;
err = replace_page_cache_page(oldpage, newpage, GFP_KERNEL);
if (err) {
unlock_page(newpage);
return err;
}
page_cache_get(newpage);
if (!(buf->flags & PIPE_BUF_FLAG_LRU))
lru_cache_add_file(newpage);
err = 0;
spin_lock(&cs->req->waitq.lock);
if (test_bit(FR_ABORTED, &cs->req->flags))
err = -ENOENT;
else
*pagep = newpage;
spin_unlock(&cs->req->waitq.lock);
if (err) {
unlock_page(newpage);
page_cache_release(newpage);
return err;
}
unlock_page(oldpage);
page_cache_release(oldpage);
cs->len = 0;
return 0;
out_fallback_unlock:
unlock_page(newpage);
out_fallback:
cs->pg = buf->page;
cs->offset = buf->offset;
err = lock_request(cs->req);
if (err)
return err;
return 1;
}
static int fuse_ref_page(struct fuse_copy_state *cs, struct page *page,
unsigned offset, unsigned count)
{
struct pipe_buffer *buf;
int err;
if (cs->nr_segs == cs->pipe->buffers)
return -EIO;
err = unlock_request(cs->req);
if (err)
return err;
fuse_copy_finish(cs);
buf = cs->pipebufs;
page_cache_get(page);
buf->page = page;
buf->offset = offset;
buf->len = count;
cs->pipebufs++;
cs->nr_segs++;
cs->len = 0;
return 0;
}
/*
* Copy a page in the request to/from the userspace buffer. Must be
* done atomically
*/
static int fuse_copy_page(struct fuse_copy_state *cs, struct page **pagep,
unsigned offset, unsigned count, int zeroing)
{
int err;
struct page *page = *pagep;
if (page && zeroing && count < PAGE_SIZE)
clear_highpage(page);
while (count) {
if (cs->write && cs->pipebufs && page) {
return fuse_ref_page(cs, page, offset, count);
} else if (!cs->len) {
if (cs->move_pages && page &&
offset == 0 && count == PAGE_SIZE) {
err = fuse_try_move_page(cs, pagep);
if (err <= 0)
return err;
} else {
err = fuse_copy_fill(cs);
if (err)
return err;
}
}
if (page) {
void *mapaddr = kmap_atomic(page);
void *buf = mapaddr + offset;
offset += fuse_copy_do(cs, &buf, &count);
kunmap_atomic(mapaddr);
} else
offset += fuse_copy_do(cs, NULL, &count);
}
if (page && !cs->write)
flush_dcache_page(page);
return 0;
}
/* Copy pages in the request to/from userspace buffer */
static int fuse_copy_pages(struct fuse_copy_state *cs, unsigned nbytes,
int zeroing)
{
unsigned i;
struct fuse_req *req = cs->req;
for (i = 0; i < req->num_pages && (nbytes || zeroing); i++) {
int err;
unsigned offset = req->page_descs[i].offset;
unsigned count = min(nbytes, req->page_descs[i].length);
err = fuse_copy_page(cs, &req->pages[i], offset, count,
zeroing);
if (err)
return err;
nbytes -= count;
}
return 0;
}
/* Copy a single argument in the request to/from userspace buffer */
static int fuse_copy_one(struct fuse_copy_state *cs, void *val, unsigned size)
{
while (size) {
if (!cs->len) {
int err = fuse_copy_fill(cs);
if (err)
return err;
}
fuse_copy_do(cs, &val, &size);
}
return 0;
}
/* Copy request arguments to/from userspace buffer */
static int fuse_copy_args(struct fuse_copy_state *cs, unsigned numargs,
unsigned argpages, struct fuse_arg *args,
int zeroing)
{
int err = 0;
unsigned i;
for (i = 0; !err && i < numargs; i++) {
struct fuse_arg *arg = &args[i];
if (i == numargs - 1 && argpages)
err = fuse_copy_pages(cs, arg->size, zeroing);
else
err = fuse_copy_one(cs, arg->value, arg->size);
}
return err;
}
static int forget_pending(struct fuse_iqueue *fiq)
{
return fiq->forget_list_head.next != NULL;
}
static int request_pending(struct fuse_iqueue *fiq)
{
return !list_empty(&fiq->pending) || !list_empty(&fiq->interrupts) ||
forget_pending(fiq);
}
/*
* Transfer an interrupt request to userspace
*
* Unlike other requests this is assembled on demand, without a need
* to allocate a separate fuse_req structure.
*
* Called with fiq->waitq.lock held, releases it
*/
static int fuse_read_interrupt(struct fuse_iqueue *fiq,
struct fuse_copy_state *cs,
size_t nbytes, struct fuse_req *req)
__releases(fiq->waitq.lock)
{
struct fuse_in_header ih;
struct fuse_interrupt_in arg;
unsigned reqsize = sizeof(ih) + sizeof(arg);
int err;
list_del_init(&req->intr_entry);
req->intr_unique = fuse_get_unique(fiq);
memset(&ih, 0, sizeof(ih));
memset(&arg, 0, sizeof(arg));
ih.len = reqsize;
ih.opcode = FUSE_INTERRUPT;
ih.unique = req->intr_unique;
arg.unique = req->in.h.unique;
spin_unlock(&fiq->waitq.lock);
if (nbytes < reqsize)
return -EINVAL;
err = fuse_copy_one(cs, &ih, sizeof(ih));
if (!err)
err = fuse_copy_one(cs, &arg, sizeof(arg));
fuse_copy_finish(cs);
return err ? err : reqsize;
}
static struct fuse_forget_link *dequeue_forget(struct fuse_iqueue *fiq,
unsigned max,
unsigned *countp)
{
struct fuse_forget_link *head = fiq->forget_list_head.next;
struct fuse_forget_link **newhead = &head;
unsigned count;
for (count = 0; *newhead != NULL && count < max; count++)
newhead = &(*newhead)->next;
fiq->forget_list_head.next = *newhead;
*newhead = NULL;
if (fiq->forget_list_head.next == NULL)
fiq->forget_list_tail = &fiq->forget_list_head;
if (countp != NULL)
*countp = count;
return head;
}
static int fuse_read_single_forget(struct fuse_iqueue *fiq,
struct fuse_copy_state *cs,
size_t nbytes)
__releases(fiq->waitq.lock)
{
int err;
struct fuse_forget_link *forget = dequeue_forget(fiq, 1, NULL);
struct fuse_forget_in arg = {
.nlookup = forget->forget_one.nlookup,
};
struct fuse_in_header ih = {
.opcode = FUSE_FORGET,
.nodeid = forget->forget_one.nodeid,
.unique = fuse_get_unique(fiq),
.len = sizeof(ih) + sizeof(arg),
};
spin_unlock(&fiq->waitq.lock);
kfree(forget);
if (nbytes < ih.len)
return -EINVAL;
err = fuse_copy_one(cs, &ih, sizeof(ih));
if (!err)
err = fuse_copy_one(cs, &arg, sizeof(arg));
fuse_copy_finish(cs);
if (err)
return err;
return ih.len;
}
static int fuse_read_batch_forget(struct fuse_iqueue *fiq,
struct fuse_copy_state *cs, size_t nbytes)
__releases(fiq->waitq.lock)
{
int err;
unsigned max_forgets;
unsigned count;
struct fuse_forget_link *head;
struct fuse_batch_forget_in arg = { .count = 0 };
struct fuse_in_header ih = {
.opcode = FUSE_BATCH_FORGET,
.unique = fuse_get_unique(fiq),
.len = sizeof(ih) + sizeof(arg),
};
if (nbytes < ih.len) {
spin_unlock(&fiq->waitq.lock);
return -EINVAL;
}
max_forgets = (nbytes - ih.len) / sizeof(struct fuse_forget_one);
head = dequeue_forget(fiq, max_forgets, &count);
spin_unlock(&fiq->waitq.lock);
arg.count = count;
ih.len += count * sizeof(struct fuse_forget_one);
err = fuse_copy_one(cs, &ih, sizeof(ih));
if (!err)
err = fuse_copy_one(cs, &arg, sizeof(arg));
while (head) {
struct fuse_forget_link *forget = head;
if (!err) {
err = fuse_copy_one(cs, &forget->forget_one,
sizeof(forget->forget_one));
}
head = forget->next;
kfree(forget);
}
fuse_copy_finish(cs);
if (err)
return err;
return ih.len;
}
static int fuse_read_forget(struct fuse_conn *fc, struct fuse_iqueue *fiq,
struct fuse_copy_state *cs,
size_t nbytes)
__releases(fiq->waitq.lock)
{
if (fc->minor < 16 || fiq->forget_list_head.next->next == NULL)
return fuse_read_single_forget(fiq, cs, nbytes);
else
return fuse_read_batch_forget(fiq, cs, nbytes);
}
/*
* Read a single request into the userspace filesystem's buffer. This
* function waits until a request is available, then removes it from
* the pending list and copies request data to userspace buffer. If
* no reply is needed (FORGET) or request has been aborted or there
* was an error during the copying then it's finished by calling
* request_end(). Otherwise add it to the processing list, and set
* the 'sent' flag.
*/
static ssize_t fuse_dev_do_read(struct fuse_dev *fud, struct file *file,
struct fuse_copy_state *cs, size_t nbytes)
{
ssize_t err;
struct fuse_conn *fc = fud->fc;
struct fuse_iqueue *fiq = &fc->iq;
struct fuse_pqueue *fpq = &fud->pq;
struct fuse_req *req;
struct fuse_in *in;
unsigned reqsize;
restart:
spin_lock(&fiq->waitq.lock);
err = -EAGAIN;
if ((file->f_flags & O_NONBLOCK) && fiq->connected &&
!request_pending(fiq))
goto err_unlock;
err = wait_event_interruptible_exclusive_locked(fiq->waitq,
!fiq->connected || request_pending(fiq));
if (err)
goto err_unlock;
err = -ENODEV;
if (!fiq->connected)
goto err_unlock;
if (!list_empty(&fiq->interrupts)) {
req = list_entry(fiq->interrupts.next, struct fuse_req,
intr_entry);
return fuse_read_interrupt(fiq, cs, nbytes, req);
}
if (forget_pending(fiq)) {
if (list_empty(&fiq->pending) || fiq->forget_batch-- > 0)
return fuse_read_forget(fc, fiq, cs, nbytes);
if (fiq->forget_batch <= -8)
fiq->forget_batch = 16;
}
req = list_entry(fiq->pending.next, struct fuse_req, list);
clear_bit(FR_PENDING, &req->flags);
list_del_init(&req->list);
spin_unlock(&fiq->waitq.lock);
in = &req->in;
reqsize = in->h.len;
/* If request is too large, reply with an error and restart the read */
if (nbytes < reqsize) {
req->out.h.error = -EIO;
/* SETXATTR is special, since it may contain too large data */
if (in->h.opcode == FUSE_SETXATTR)
req->out.h.error = -E2BIG;
request_end(fc, req);
goto restart;
}
spin_lock(&fpq->lock);
list_add(&req->list, &fpq->io);
spin_unlock(&fpq->lock);
cs->req = req;
err = fuse_copy_one(cs, &in->h, sizeof(in->h));
if (!err)
err = fuse_copy_args(cs, in->numargs, in->argpages,
(struct fuse_arg *) in->args, 0);
fuse_copy_finish(cs);
spin_lock(&fpq->lock);
clear_bit(FR_LOCKED, &req->flags);
if (!fpq->connected) {
err = -ENODEV;
goto out_end;
}
if (err) {
req->out.h.error = -EIO;
goto out_end;
}
if (!test_bit(FR_ISREPLY, &req->flags)) {
err = reqsize;
goto out_end;
}
list_move_tail(&req->list, &fpq->processing);
spin_unlock(&fpq->lock);
set_bit(FR_SENT, &req->flags);
/* matches barrier in request_wait_answer() */
smp_mb__after_atomic();
if (test_bit(FR_INTERRUPTED, &req->flags))
queue_interrupt(fiq, req);
return reqsize;
out_end:
if (!test_bit(FR_PRIVATE, &req->flags))
list_del_init(&req->list);
spin_unlock(&fpq->lock);
request_end(fc, req);
return err;
err_unlock:
spin_unlock(&fiq->waitq.lock);
return err;
}
static int fuse_dev_open(struct inode *inode, struct file *file)
{
/*
* The fuse device's file's private_data is used to hold
* the fuse_conn(ection) when it is mounted, and is used to
* keep track of whether the file has been mounted already.
*/
file->private_data = NULL;
return 0;
}
static ssize_t fuse_dev_read(struct kiocb *iocb, struct iov_iter *to)
{
struct fuse_copy_state cs;
struct file *file = iocb->ki_filp;
struct fuse_dev *fud = fuse_get_dev(file);
if (!fud)
return -EPERM;
if (!iter_is_iovec(to))
return -EINVAL;
fuse_copy_init(&cs, 1, to);
return fuse_dev_do_read(fud, file, &cs, iov_iter_count(to));
}
static ssize_t fuse_dev_splice_read(struct file *in, loff_t *ppos,
struct pipe_inode_info *pipe,
size_t len, unsigned int flags)
{
int ret;
int page_nr = 0;
int do_wakeup = 0;
struct pipe_buffer *bufs;
struct fuse_copy_state cs;
struct fuse_dev *fud = fuse_get_dev(in);
if (!fud)
return -EPERM;
bufs = kmalloc(pipe->buffers * sizeof(struct pipe_buffer), GFP_KERNEL);
if (!bufs)
return -ENOMEM;
fuse_copy_init(&cs, 1, NULL);
cs.pipebufs = bufs;
cs.pipe = pipe;
ret = fuse_dev_do_read(fud, in, &cs, len);
if (ret < 0)
goto out;
ret = 0;
pipe_lock(pipe);
if (!pipe->readers) {
send_sig(SIGPIPE, current, 0);
if (!ret)
ret = -EPIPE;
goto out_unlock;
}
if (pipe->nrbufs + cs.nr_segs > pipe->buffers) {
ret = -EIO;
goto out_unlock;
}
while (page_nr < cs.nr_segs) {
int newbuf = (pipe->curbuf + pipe->nrbufs) & (pipe->buffers - 1);
struct pipe_buffer *buf = pipe->bufs + newbuf;
buf->page = bufs[page_nr].page;
buf->offset = bufs[page_nr].offset;
buf->len = bufs[page_nr].len;
/*
* Need to be careful about this. Having buf->ops in module
* code can Oops if the buffer persists after module unload.
*/
buf->ops = &nosteal_pipe_buf_ops;
pipe->nrbufs++;
page_nr++;
ret += buf->len;
if (pipe->files)
do_wakeup = 1;
}
out_unlock:
pipe_unlock(pipe);
if (do_wakeup) {
smp_mb();
if (waitqueue_active(&pipe->wait))
wake_up_interruptible(&pipe->wait);
kill_fasync(&pipe->fasync_readers, SIGIO, POLL_IN);
}
out:
for (; page_nr < cs.nr_segs; page_nr++)
page_cache_release(bufs[page_nr].page);
kfree(bufs);
return ret;
}
static int fuse_notify_poll(struct fuse_conn *fc, unsigned int size,
struct fuse_copy_state *cs)
{
struct fuse_notify_poll_wakeup_out outarg;
int err = -EINVAL;
if (size != sizeof(outarg))
goto err;
err = fuse_copy_one(cs, &outarg, sizeof(outarg));
if (err)
goto err;
fuse_copy_finish(cs);
return fuse_notify_poll_wakeup(fc, &outarg);
err:
fuse_copy_finish(cs);
return err;
}
static int fuse_notify_inval_inode(struct fuse_conn *fc, unsigned int size,
struct fuse_copy_state *cs)
{
struct fuse_notify_inval_inode_out outarg;
int err = -EINVAL;
if (size != sizeof(outarg))
goto err;
err = fuse_copy_one(cs, &outarg, sizeof(outarg));
if (err)
goto err;
fuse_copy_finish(cs);
down_read(&fc->killsb);
err = -ENOENT;
if (fc->sb) {
err = fuse_reverse_inval_inode(fc->sb, outarg.ino,
outarg.off, outarg.len);
}
up_read(&fc->killsb);
return err;
err:
fuse_copy_finish(cs);
return err;
}
static int fuse_notify_inval_entry(struct fuse_conn *fc, unsigned int size,
struct fuse_copy_state *cs)
{
struct fuse_notify_inval_entry_out outarg;
int err = -ENOMEM;
char *buf;
struct qstr name;
buf = kzalloc(FUSE_NAME_MAX + 1, GFP_KERNEL);
if (!buf)
goto err;
err = -EINVAL;
if (size < sizeof(outarg))
goto err;
err = fuse_copy_one(cs, &outarg, sizeof(outarg));
if (err)
goto err;
err = -ENAMETOOLONG;
if (outarg.namelen > FUSE_NAME_MAX)
goto err;
err = -EINVAL;
if (size != sizeof(outarg) + outarg.namelen + 1)
goto err;
name.name = buf;
name.len = outarg.namelen;
err = fuse_copy_one(cs, buf, outarg.namelen + 1);
if (err)
goto err;
fuse_copy_finish(cs);
buf[outarg.namelen] = 0;
name.hash = full_name_hash(name.name, name.len);
down_read(&fc->killsb);
err = -ENOENT;
if (fc->sb)
err = fuse_reverse_inval_entry(fc->sb, outarg.parent, 0, &name);
up_read(&fc->killsb);
kfree(buf);
return err;
err:
kfree(buf);
fuse_copy_finish(cs);
return err;
}
static int fuse_notify_delete(struct fuse_conn *fc, unsigned int size,
struct fuse_copy_state *cs)
{
struct fuse_notify_delete_out outarg;
int err = -ENOMEM;
char *buf;
struct qstr name;
buf = kzalloc(FUSE_NAME_MAX + 1, GFP_KERNEL);
if (!buf)
goto err;
err = -EINVAL;
if (size < sizeof(outarg))
goto err;
err = fuse_copy_one(cs, &outarg, sizeof(outarg));
if (err)
goto err;
err = -ENAMETOOLONG;
if (outarg.namelen > FUSE_NAME_MAX)
goto err;
err = -EINVAL;
if (size != sizeof(outarg) + outarg.namelen + 1)
goto err;
name.name = buf;
name.len = outarg.namelen;
err = fuse_copy_one(cs, buf, outarg.namelen + 1);
if (err)
goto err;
fuse_copy_finish(cs);
buf[outarg.namelen] = 0;
name.hash = full_name_hash(name.name, name.len);
down_read(&fc->killsb);
err = -ENOENT;
if (fc->sb)
err = fuse_reverse_inval_entry(fc->sb, outarg.parent,
outarg.child, &name);
up_read(&fc->killsb);
kfree(buf);
return err;
err:
kfree(buf);
fuse_copy_finish(cs);
return err;
}
static int fuse_notify_store(struct fuse_conn *fc, unsigned int size,
struct fuse_copy_state *cs)
{
struct fuse_notify_store_out outarg;
struct inode *inode;
struct address_space *mapping;
u64 nodeid;
int err;
pgoff_t index;
unsigned int offset;
unsigned int num;
loff_t file_size;
loff_t end;
err = -EINVAL;
if (size < sizeof(outarg))
goto out_finish;
err = fuse_copy_one(cs, &outarg, sizeof(outarg));
if (err)
goto out_finish;
err = -EINVAL;
if (size - sizeof(outarg) != outarg.size)
goto out_finish;
nodeid = outarg.nodeid;
down_read(&fc->killsb);
err = -ENOENT;
if (!fc->sb)
goto out_up_killsb;
inode = ilookup5(fc->sb, nodeid, fuse_inode_eq, &nodeid);
if (!inode)
goto out_up_killsb;
mapping = inode->i_mapping;
index = outarg.offset >> PAGE_CACHE_SHIFT;
offset = outarg.offset & ~PAGE_CACHE_MASK;
file_size = i_size_read(inode);
end = outarg.offset + outarg.size;
if (end > file_size) {
file_size = end;
fuse_write_update_size(inode, file_size);
}
num = outarg.size;
while (num) {
struct page *page;
unsigned int this_num;
err = -ENOMEM;
page = find_or_create_page(mapping, index,
mapping_gfp_mask(mapping));
if (!page)
goto out_iput;
this_num = min_t(unsigned, num, PAGE_CACHE_SIZE - offset);
err = fuse_copy_page(cs, &page, offset, this_num, 0);
if (!err && offset == 0 &&
(this_num == PAGE_CACHE_SIZE || file_size == end))
SetPageUptodate(page);
unlock_page(page);
page_cache_release(page);
if (err)
goto out_iput;
num -= this_num;
offset = 0;
index++;
}
err = 0;
out_iput:
iput(inode);
out_up_killsb:
up_read(&fc->killsb);
out_finish:
fuse_copy_finish(cs);
return err;
}
static void fuse_retrieve_end(struct fuse_conn *fc, struct fuse_req *req)
{
release_pages(req->pages, req->num_pages, false);
}
static int fuse_retrieve(struct fuse_conn *fc, struct inode *inode,
struct fuse_notify_retrieve_out *outarg)
{
int err;
struct address_space *mapping = inode->i_mapping;
struct fuse_req *req;
pgoff_t index;
loff_t file_size;
unsigned int num;
unsigned int offset;
size_t total_len = 0;
int num_pages;
offset = outarg->offset & ~PAGE_CACHE_MASK;
file_size = i_size_read(inode);
num = outarg->size;
if (outarg->offset > file_size)
num = 0;
else if (outarg->offset + num > file_size)
num = file_size - outarg->offset;
num_pages = (num + offset + PAGE_SIZE - 1) >> PAGE_SHIFT;
num_pages = min(num_pages, FUSE_MAX_PAGES_PER_REQ);
req = fuse_get_req(fc, num_pages);
if (IS_ERR(req))
return PTR_ERR(req);
req->in.h.opcode = FUSE_NOTIFY_REPLY;
req->in.h.nodeid = outarg->nodeid;
req->in.numargs = 2;
req->in.argpages = 1;
req->page_descs[0].offset = offset;
req->end = fuse_retrieve_end;
index = outarg->offset >> PAGE_CACHE_SHIFT;
while (num && req->num_pages < num_pages) {
struct page *page;
unsigned int this_num;
page = find_get_page(mapping, index);
if (!page)
break;
this_num = min_t(unsigned, num, PAGE_CACHE_SIZE - offset);
req->pages[req->num_pages] = page;
req->page_descs[req->num_pages].length = this_num;
req->num_pages++;
offset = 0;
num -= this_num;
total_len += this_num;
index++;
}
req->misc.retrieve_in.offset = outarg->offset;
req->misc.retrieve_in.size = total_len;
req->in.args[0].size = sizeof(req->misc.retrieve_in);
req->in.args[0].value = &req->misc.retrieve_in;
req->in.args[1].size = total_len;
err = fuse_request_send_notify_reply(fc, req, outarg->notify_unique);
if (err)
fuse_retrieve_end(fc, req);
return err;
}
static int fuse_notify_retrieve(struct fuse_conn *fc, unsigned int size,
struct fuse_copy_state *cs)
{
struct fuse_notify_retrieve_out outarg;
struct inode *inode;
int err;
err = -EINVAL;
if (size != sizeof(outarg))
goto copy_finish;
err = fuse_copy_one(cs, &outarg, sizeof(outarg));
if (err)
goto copy_finish;
fuse_copy_finish(cs);
down_read(&fc->killsb);
err = -ENOENT;
if (fc->sb) {
u64 nodeid = outarg.nodeid;
inode = ilookup5(fc->sb, nodeid, fuse_inode_eq, &nodeid);
if (inode) {
err = fuse_retrieve(fc, inode, &outarg);
iput(inode);
}
}
up_read(&fc->killsb);
return err;
copy_finish:
fuse_copy_finish(cs);
return err;
}
static int fuse_notify(struct fuse_conn *fc, enum fuse_notify_code code,
unsigned int size, struct fuse_copy_state *cs)
{
/* Don't try to move pages (yet) */
cs->move_pages = 0;
switch (code) {
case FUSE_NOTIFY_POLL:
return fuse_notify_poll(fc, size, cs);
case FUSE_NOTIFY_INVAL_INODE:
return fuse_notify_inval_inode(fc, size, cs);
case FUSE_NOTIFY_INVAL_ENTRY:
return fuse_notify_inval_entry(fc, size, cs);
case FUSE_NOTIFY_STORE:
return fuse_notify_store(fc, size, cs);
case FUSE_NOTIFY_RETRIEVE:
return fuse_notify_retrieve(fc, size, cs);
case FUSE_NOTIFY_DELETE:
return fuse_notify_delete(fc, size, cs);
default:
fuse_copy_finish(cs);
return -EINVAL;
}
}
/* Look up request on processing list by unique ID */
static struct fuse_req *request_find(struct fuse_pqueue *fpq, u64 unique)
{
struct fuse_req *req;
list_for_each_entry(req, &fpq->processing, list) {
if (req->in.h.unique == unique || req->intr_unique == unique)
return req;
}
return NULL;
}
static int copy_out_args(struct fuse_copy_state *cs, struct fuse_out *out,
unsigned nbytes)
{
unsigned reqsize = sizeof(struct fuse_out_header);
if (out->h.error)
return nbytes != reqsize ? -EINVAL : 0;
reqsize += len_args(out->numargs, out->args);
if (reqsize < nbytes || (reqsize > nbytes && !out->argvar))
return -EINVAL;
else if (reqsize > nbytes) {
struct fuse_arg *lastarg = &out->args[out->numargs-1];
unsigned diffsize = reqsize - nbytes;
if (diffsize > lastarg->size)
return -EINVAL;
lastarg->size -= diffsize;
}
return fuse_copy_args(cs, out->numargs, out->argpages, out->args,
out->page_zeroing);
}
/*
* Write a single reply to a request. First the header is copied from
* the write buffer. The request is then searched on the processing
* list by the unique ID found in the header. If found, then remove
* it from the list and copy the rest of the buffer to the request.
* The request is finished by calling request_end()
*/
static ssize_t fuse_dev_do_write(struct fuse_dev *fud,
struct fuse_copy_state *cs, size_t nbytes)
{
int err;
struct fuse_conn *fc = fud->fc;
struct fuse_pqueue *fpq = &fud->pq;
struct fuse_req *req;
struct fuse_out_header oh;
if (nbytes < sizeof(struct fuse_out_header))
return -EINVAL;
err = fuse_copy_one(cs, &oh, sizeof(oh));
if (err)
goto err_finish;
err = -EINVAL;
if (oh.len != nbytes)
goto err_finish;
/*
* Zero oh.unique indicates unsolicited notification message
* and error contains notification code.
*/
if (!oh.unique) {
err = fuse_notify(fc, oh.error, nbytes - sizeof(oh), cs);
return err ? err : nbytes;
}
err = -EINVAL;
if (oh.error <= -1000 || oh.error > 0)
goto err_finish;
spin_lock(&fpq->lock);
err = -ENOENT;
if (!fpq->connected)
goto err_unlock_pq;
req = request_find(fpq, oh.unique);
if (!req)
goto err_unlock_pq;
/* Is it an interrupt reply? */
if (req->intr_unique == oh.unique) {
spin_unlock(&fpq->lock);
err = -EINVAL;
if (nbytes != sizeof(struct fuse_out_header))
goto err_finish;
if (oh.error == -ENOSYS)
fc->no_interrupt = 1;
else if (oh.error == -EAGAIN)
queue_interrupt(&fc->iq, req);
fuse_copy_finish(cs);
return nbytes;
}
clear_bit(FR_SENT, &req->flags);
list_move(&req->list, &fpq->io);
req->out.h = oh;
set_bit(FR_LOCKED, &req->flags);
spin_unlock(&fpq->lock);
cs->req = req;
if (!req->out.page_replace)
cs->move_pages = 0;
err = copy_out_args(cs, &req->out, nbytes);
fuse_copy_finish(cs);
spin_lock(&fpq->lock);
clear_bit(FR_LOCKED, &req->flags);
if (!fpq->connected)
err = -ENOENT;
else if (err)
req->out.h.error = -EIO;
if (!test_bit(FR_PRIVATE, &req->flags))
list_del_init(&req->list);
spin_unlock(&fpq->lock);
request_end(fc, req);
return err ? err : nbytes;
err_unlock_pq:
spin_unlock(&fpq->lock);
err_finish:
fuse_copy_finish(cs);
return err;
}
static ssize_t fuse_dev_write(struct kiocb *iocb, struct iov_iter *from)
{
struct fuse_copy_state cs;
struct fuse_dev *fud = fuse_get_dev(iocb->ki_filp);
if (!fud)
return -EPERM;
if (!iter_is_iovec(from))
return -EINVAL;
fuse_copy_init(&cs, 0, from);
return fuse_dev_do_write(fud, &cs, iov_iter_count(from));
}
static ssize_t fuse_dev_splice_write(struct pipe_inode_info *pipe,
struct file *out, loff_t *ppos,
size_t len, unsigned int flags)
{
unsigned nbuf;
unsigned idx;
struct pipe_buffer *bufs;
struct fuse_copy_state cs;
struct fuse_dev *fud;
size_t rem;
ssize_t ret;
fud = fuse_get_dev(out);
if (!fud)
return -EPERM;
bufs = kmalloc(pipe->buffers * sizeof(struct pipe_buffer), GFP_KERNEL);
if (!bufs)
return -ENOMEM;
pipe_lock(pipe);
nbuf = 0;
rem = 0;
for (idx = 0; idx < pipe->nrbufs && rem < len; idx++)
rem += pipe->bufs[(pipe->curbuf + idx) & (pipe->buffers - 1)].len;
ret = -EINVAL;
if (rem < len) {
pipe_unlock(pipe);
goto out;
}
rem = len;
while (rem) {
struct pipe_buffer *ibuf;
struct pipe_buffer *obuf;
BUG_ON(nbuf >= pipe->buffers);
BUG_ON(!pipe->nrbufs);
ibuf = &pipe->bufs[pipe->curbuf];
obuf = &bufs[nbuf];
if (rem >= ibuf->len) {
*obuf = *ibuf;
ibuf->ops = NULL;
pipe->curbuf = (pipe->curbuf + 1) & (pipe->buffers - 1);
pipe->nrbufs--;
} else {
ibuf->ops->get(pipe, ibuf);
*obuf = *ibuf;
obuf->flags &= ~PIPE_BUF_FLAG_GIFT;
obuf->len = rem;
ibuf->offset += obuf->len;
ibuf->len -= obuf->len;
}
nbuf++;
rem -= obuf->len;
}
pipe_unlock(pipe);
fuse_copy_init(&cs, 0, NULL);
cs.pipebufs = bufs;
cs.nr_segs = nbuf;
cs.pipe = pipe;
if (flags & SPLICE_F_MOVE)
cs.move_pages = 1;
ret = fuse_dev_do_write(fud, &cs, len);
for (idx = 0; idx < nbuf; idx++) {
struct pipe_buffer *buf = &bufs[idx];
buf->ops->release(pipe, buf);
}
out:
kfree(bufs);
return ret;
}
static unsigned fuse_dev_poll(struct file *file, poll_table *wait)
{
unsigned mask = POLLOUT | POLLWRNORM;
struct fuse_iqueue *fiq;
struct fuse_dev *fud = fuse_get_dev(file);
if (!fud)
return POLLERR;
fiq = &fud->fc->iq;
poll_wait(file, &fiq->waitq, wait);
spin_lock(&fiq->waitq.lock);
if (!fiq->connected)
mask = POLLERR;
else if (request_pending(fiq))
mask |= POLLIN | POLLRDNORM;
spin_unlock(&fiq->waitq.lock);
return mask;
}
/*
* Abort all requests on the given list (pending or processing)
*
* This function releases and reacquires fc->lock
*/
static void end_requests(struct fuse_conn *fc, struct list_head *head)
{
while (!list_empty(head)) {
struct fuse_req *req;
req = list_entry(head->next, struct fuse_req, list);
req->out.h.error = -ECONNABORTED;
clear_bit(FR_PENDING, &req->flags);
clear_bit(FR_SENT, &req->flags);
list_del_init(&req->list);
request_end(fc, req);
}
}
static void end_polls(struct fuse_conn *fc)
{
struct rb_node *p;
p = rb_first(&fc->polled_files);
while (p) {
struct fuse_file *ff;
ff = rb_entry(p, struct fuse_file, polled_node);
wake_up_interruptible_all(&ff->poll_wait);
p = rb_next(p);
}
}
/*
* Abort all requests.
*
* Emergency exit in case of a malicious or accidental deadlock, or just a hung
* filesystem.
*
* The same effect is usually achievable through killing the filesystem daemon
* and all users of the filesystem. The exception is the combination of an
* asynchronous request and the tricky deadlock (see
* Documentation/filesystems/fuse.txt).
*
* Aborting requests under I/O goes as follows: 1: Separate out unlocked
* requests, they should be finished off immediately. Locked requests will be
* finished after unlock; see unlock_request(). 2: Finish off the unlocked
* requests. It is possible that some request will finish before we can. This
* is OK, the request will in that case be removed from the list before we touch
* it.
*/
void fuse_abort_conn(struct fuse_conn *fc)
{
struct fuse_iqueue *fiq = &fc->iq;
spin_lock(&fc->lock);
if (fc->connected) {
struct fuse_dev *fud;
struct fuse_req *req, *next;
LIST_HEAD(to_end1);
LIST_HEAD(to_end2);
fc->connected = 0;
fc->blocked = 0;
fuse_set_initialized(fc);
list_for_each_entry(fud, &fc->devices, entry) {
struct fuse_pqueue *fpq = &fud->pq;
spin_lock(&fpq->lock);
fpq->connected = 0;
list_for_each_entry_safe(req, next, &fpq->io, list) {
req->out.h.error = -ECONNABORTED;
spin_lock(&req->waitq.lock);
set_bit(FR_ABORTED, &req->flags);
if (!test_bit(FR_LOCKED, &req->flags)) {
set_bit(FR_PRIVATE, &req->flags);
list_move(&req->list, &to_end1);
}
spin_unlock(&req->waitq.lock);
}
list_splice_init(&fpq->processing, &to_end2);
spin_unlock(&fpq->lock);
}
fc->max_background = UINT_MAX;
flush_bg_queue(fc);
spin_lock(&fiq->waitq.lock);
fiq->connected = 0;
list_splice_init(&fiq->pending, &to_end2);
while (forget_pending(fiq))
kfree(dequeue_forget(fiq, 1, NULL));
wake_up_all_locked(&fiq->waitq);
spin_unlock(&fiq->waitq.lock);
kill_fasync(&fiq->fasync, SIGIO, POLL_IN);
end_polls(fc);
wake_up_all(&fc->blocked_waitq);
spin_unlock(&fc->lock);
while (!list_empty(&to_end1)) {
req = list_first_entry(&to_end1, struct fuse_req, list);
__fuse_get_request(req);
list_del_init(&req->list);
request_end(fc, req);
}
end_requests(fc, &to_end2);
} else {
spin_unlock(&fc->lock);
}
}
EXPORT_SYMBOL_GPL(fuse_abort_conn);
int fuse_dev_release(struct inode *inode, struct file *file)
{
struct fuse_dev *fud = fuse_get_dev(file);
if (fud) {
struct fuse_conn *fc = fud->fc;
struct fuse_pqueue *fpq = &fud->pq;
WARN_ON(!list_empty(&fpq->io));
end_requests(fc, &fpq->processing);
/* Are we the last open device? */
if (atomic_dec_and_test(&fc->dev_count)) {
WARN_ON(fc->iq.fasync != NULL);
fuse_abort_conn(fc);
}
fuse_dev_free(fud);
}
return 0;
}
EXPORT_SYMBOL_GPL(fuse_dev_release);
static int fuse_dev_fasync(int fd, struct file *file, int on)
{
struct fuse_dev *fud = fuse_get_dev(file);
if (!fud)
return -EPERM;
/* No locking - fasync_helper does its own locking */
return fasync_helper(fd, file, on, &fud->fc->iq.fasync);
}
static int fuse_device_clone(struct fuse_conn *fc, struct file *new)
{
struct fuse_dev *fud;
if (new->private_data)
return -EINVAL;
fud = fuse_dev_alloc(fc);
if (!fud)
return -ENOMEM;
new->private_data = fud;
atomic_inc(&fc->dev_count);
return 0;
}
static long fuse_dev_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
int err = -ENOTTY;
if (cmd == FUSE_DEV_IOC_CLONE) {
int oldfd;
err = -EFAULT;
if (!get_user(oldfd, (__u32 __user *) arg)) {
struct file *old = fget(oldfd);
err = -EINVAL;
if (old) {
struct fuse_dev *fud = fuse_get_dev(old);
if (fud) {
mutex_lock(&fuse_mutex);
err = fuse_device_clone(fud->fc, file);
mutex_unlock(&fuse_mutex);
}
fput(old);
}
}
}
return err;
}
const struct file_operations fuse_dev_operations = {
.owner = THIS_MODULE,
.open = fuse_dev_open,
.llseek = no_llseek,
.read_iter = fuse_dev_read,
.splice_read = fuse_dev_splice_read,
.write_iter = fuse_dev_write,
.splice_write = fuse_dev_splice_write,
.poll = fuse_dev_poll,
.release = fuse_dev_release,
.fasync = fuse_dev_fasync,
.unlocked_ioctl = fuse_dev_ioctl,
.compat_ioctl = fuse_dev_ioctl,
};
EXPORT_SYMBOL_GPL(fuse_dev_operations);
static struct miscdevice fuse_miscdevice = {
.minor = FUSE_MINOR,
.name = "fuse",
.fops = &fuse_dev_operations,
};
int __init fuse_dev_init(void)
{
int err = -ENOMEM;
fuse_req_cachep = kmem_cache_create("fuse_request",
sizeof(struct fuse_req),
0, 0, NULL);
if (!fuse_req_cachep)
goto out;
err = misc_register(&fuse_miscdevice);
if (err)
goto out_cache_clean;
return 0;
out_cache_clean:
kmem_cache_destroy(fuse_req_cachep);
out:
return err;
}
void fuse_dev_cleanup(void)
{
misc_deregister(&fuse_miscdevice);
kmem_cache_destroy(fuse_req_cachep);
}
| gpl-2.0 |
junhe/linux | drivers/mtd/nand/denali.c | 605 | 46478 | /*
* NAND Flash Controller Device Driver
* Copyright © 2009-2010, Intel Corporation and its suppliers.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/dma-mapping.h>
#include <linux/wait.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <linux/mtd/mtd.h>
#include <linux/module.h>
#include "denali.h"
MODULE_LICENSE("GPL");
/*
* We define a module parameter that allows the user to override
* the hardware and decide what timing mode should be used.
*/
#define NAND_DEFAULT_TIMINGS -1
static int onfi_timing_mode = NAND_DEFAULT_TIMINGS;
module_param(onfi_timing_mode, int, S_IRUGO);
MODULE_PARM_DESC(onfi_timing_mode,
"Overrides default ONFI setting. -1 indicates use default timings");
#define DENALI_NAND_NAME "denali-nand"
/*
* We define a macro here that combines all interrupts this driver uses into
* a single constant value, for convenience.
*/
#define DENALI_IRQ_ALL (INTR_STATUS__DMA_CMD_COMP | \
INTR_STATUS__ECC_TRANSACTION_DONE | \
INTR_STATUS__ECC_ERR | \
INTR_STATUS__PROGRAM_FAIL | \
INTR_STATUS__LOAD_COMP | \
INTR_STATUS__PROGRAM_COMP | \
INTR_STATUS__TIME_OUT | \
INTR_STATUS__ERASE_FAIL | \
INTR_STATUS__RST_COMP | \
INTR_STATUS__ERASE_COMP)
/*
* indicates whether or not the internal value for the flash bank is
* valid or not
*/
#define CHIP_SELECT_INVALID -1
#define SUPPORT_8BITECC 1
/*
* This macro divides two integers and rounds fractional values up
* to the nearest integer value.
*/
#define CEIL_DIV(X, Y) (((X)%(Y)) ? ((X)/(Y)+1) : ((X)/(Y)))
/*
* this macro allows us to convert from an MTD structure to our own
* device context (denali) structure.
*/
#define mtd_to_denali(m) container_of(m, struct denali_nand_info, mtd)
/*
* These constants are defined by the driver to enable common driver
* configuration options.
*/
#define SPARE_ACCESS 0x41
#define MAIN_ACCESS 0x42
#define MAIN_SPARE_ACCESS 0x43
#define PIPELINE_ACCESS 0x2000
#define DENALI_READ 0
#define DENALI_WRITE 0x100
/* types of device accesses. We can issue commands and get status */
#define COMMAND_CYCLE 0
#define ADDR_CYCLE 1
#define STATUS_CYCLE 2
/*
* this is a helper macro that allows us to
* format the bank into the proper bits for the controller
*/
#define BANK(x) ((x) << 24)
/* forward declarations */
static void clear_interrupts(struct denali_nand_info *denali);
static uint32_t wait_for_irq(struct denali_nand_info *denali,
uint32_t irq_mask);
static void denali_irq_enable(struct denali_nand_info *denali,
uint32_t int_mask);
static uint32_t read_interrupt_status(struct denali_nand_info *denali);
/*
* Certain operations for the denali NAND controller use an indexed mode to
* read/write data. The operation is performed by writing the address value
* of the command to the device memory followed by the data. This function
* abstracts this common operation.
*/
static void index_addr(struct denali_nand_info *denali,
uint32_t address, uint32_t data)
{
iowrite32(address, denali->flash_mem);
iowrite32(data, denali->flash_mem + 0x10);
}
/* Perform an indexed read of the device */
static void index_addr_read_data(struct denali_nand_info *denali,
uint32_t address, uint32_t *pdata)
{
iowrite32(address, denali->flash_mem);
*pdata = ioread32(denali->flash_mem + 0x10);
}
/*
* We need to buffer some data for some of the NAND core routines.
* The operations manage buffering that data.
*/
static void reset_buf(struct denali_nand_info *denali)
{
denali->buf.head = denali->buf.tail = 0;
}
static void write_byte_to_buf(struct denali_nand_info *denali, uint8_t byte)
{
denali->buf.buf[denali->buf.tail++] = byte;
}
/* reads the status of the device */
static void read_status(struct denali_nand_info *denali)
{
uint32_t cmd;
/* initialize the data buffer to store status */
reset_buf(denali);
cmd = ioread32(denali->flash_reg + WRITE_PROTECT);
if (cmd)
write_byte_to_buf(denali, NAND_STATUS_WP);
else
write_byte_to_buf(denali, 0);
}
/* resets a specific device connected to the core */
static void reset_bank(struct denali_nand_info *denali)
{
uint32_t irq_status;
uint32_t irq_mask = INTR_STATUS__RST_COMP | INTR_STATUS__TIME_OUT;
clear_interrupts(denali);
iowrite32(1 << denali->flash_bank, denali->flash_reg + DEVICE_RESET);
irq_status = wait_for_irq(denali, irq_mask);
if (irq_status & INTR_STATUS__TIME_OUT)
dev_err(denali->dev, "reset bank failed.\n");
}
/* Reset the flash controller */
static uint16_t denali_nand_reset(struct denali_nand_info *denali)
{
int i;
dev_dbg(denali->dev, "%s, Line %d, Function: %s\n",
__FILE__, __LINE__, __func__);
for (i = 0; i < denali->max_banks; i++)
iowrite32(INTR_STATUS__RST_COMP | INTR_STATUS__TIME_OUT,
denali->flash_reg + INTR_STATUS(i));
for (i = 0; i < denali->max_banks; i++) {
iowrite32(1 << i, denali->flash_reg + DEVICE_RESET);
while (!(ioread32(denali->flash_reg + INTR_STATUS(i)) &
(INTR_STATUS__RST_COMP | INTR_STATUS__TIME_OUT)))
cpu_relax();
if (ioread32(denali->flash_reg + INTR_STATUS(i)) &
INTR_STATUS__TIME_OUT)
dev_dbg(denali->dev,
"NAND Reset operation timed out on bank %d\n", i);
}
for (i = 0; i < denali->max_banks; i++)
iowrite32(INTR_STATUS__RST_COMP | INTR_STATUS__TIME_OUT,
denali->flash_reg + INTR_STATUS(i));
return PASS;
}
/*
* this routine calculates the ONFI timing values for a given mode and
* programs the clocking register accordingly. The mode is determined by
* the get_onfi_nand_para routine.
*/
static void nand_onfi_timing_set(struct denali_nand_info *denali,
uint16_t mode)
{
uint16_t Trea[6] = {40, 30, 25, 20, 20, 16};
uint16_t Trp[6] = {50, 25, 17, 15, 12, 10};
uint16_t Treh[6] = {30, 15, 15, 10, 10, 7};
uint16_t Trc[6] = {100, 50, 35, 30, 25, 20};
uint16_t Trhoh[6] = {0, 15, 15, 15, 15, 15};
uint16_t Trloh[6] = {0, 0, 0, 0, 5, 5};
uint16_t Tcea[6] = {100, 45, 30, 25, 25, 25};
uint16_t Tadl[6] = {200, 100, 100, 100, 70, 70};
uint16_t Trhw[6] = {200, 100, 100, 100, 100, 100};
uint16_t Trhz[6] = {200, 100, 100, 100, 100, 100};
uint16_t Twhr[6] = {120, 80, 80, 60, 60, 60};
uint16_t Tcs[6] = {70, 35, 25, 25, 20, 15};
uint16_t data_invalid_rhoh, data_invalid_rloh, data_invalid;
uint16_t dv_window = 0;
uint16_t en_lo, en_hi;
uint16_t acc_clks;
uint16_t addr_2_data, re_2_we, re_2_re, we_2_re, cs_cnt;
dev_dbg(denali->dev, "%s, Line %d, Function: %s\n",
__FILE__, __LINE__, __func__);
en_lo = CEIL_DIV(Trp[mode], CLK_X);
en_hi = CEIL_DIV(Treh[mode], CLK_X);
#if ONFI_BLOOM_TIME
if ((en_hi * CLK_X) < (Treh[mode] + 2))
en_hi++;
#endif
if ((en_lo + en_hi) * CLK_X < Trc[mode])
en_lo += CEIL_DIV((Trc[mode] - (en_lo + en_hi) * CLK_X), CLK_X);
if ((en_lo + en_hi) < CLK_MULTI)
en_lo += CLK_MULTI - en_lo - en_hi;
while (dv_window < 8) {
data_invalid_rhoh = en_lo * CLK_X + Trhoh[mode];
data_invalid_rloh = (en_lo + en_hi) * CLK_X + Trloh[mode];
data_invalid = data_invalid_rhoh < data_invalid_rloh ?
data_invalid_rhoh : data_invalid_rloh;
dv_window = data_invalid - Trea[mode];
if (dv_window < 8)
en_lo++;
}
acc_clks = CEIL_DIV(Trea[mode], CLK_X);
while (acc_clks * CLK_X - Trea[mode] < 3)
acc_clks++;
if (data_invalid - acc_clks * CLK_X < 2)
dev_warn(denali->dev, "%s, Line %d: Warning!\n",
__FILE__, __LINE__);
addr_2_data = CEIL_DIV(Tadl[mode], CLK_X);
re_2_we = CEIL_DIV(Trhw[mode], CLK_X);
re_2_re = CEIL_DIV(Trhz[mode], CLK_X);
we_2_re = CEIL_DIV(Twhr[mode], CLK_X);
cs_cnt = CEIL_DIV((Tcs[mode] - Trp[mode]), CLK_X);
if (cs_cnt == 0)
cs_cnt = 1;
if (Tcea[mode]) {
while (cs_cnt * CLK_X + Trea[mode] < Tcea[mode])
cs_cnt++;
}
#if MODE5_WORKAROUND
if (mode == 5)
acc_clks = 5;
#endif
/* Sighting 3462430: Temporary hack for MT29F128G08CJABAWP:B */
if (ioread32(denali->flash_reg + MANUFACTURER_ID) == 0 &&
ioread32(denali->flash_reg + DEVICE_ID) == 0x88)
acc_clks = 6;
iowrite32(acc_clks, denali->flash_reg + ACC_CLKS);
iowrite32(re_2_we, denali->flash_reg + RE_2_WE);
iowrite32(re_2_re, denali->flash_reg + RE_2_RE);
iowrite32(we_2_re, denali->flash_reg + WE_2_RE);
iowrite32(addr_2_data, denali->flash_reg + ADDR_2_DATA);
iowrite32(en_lo, denali->flash_reg + RDWR_EN_LO_CNT);
iowrite32(en_hi, denali->flash_reg + RDWR_EN_HI_CNT);
iowrite32(cs_cnt, denali->flash_reg + CS_SETUP_CNT);
}
/* queries the NAND device to see what ONFI modes it supports. */
static uint16_t get_onfi_nand_para(struct denali_nand_info *denali)
{
int i;
/*
* we needn't to do a reset here because driver has already
* reset all the banks before
*/
if (!(ioread32(denali->flash_reg + ONFI_TIMING_MODE) &
ONFI_TIMING_MODE__VALUE))
return FAIL;
for (i = 5; i > 0; i--) {
if (ioread32(denali->flash_reg + ONFI_TIMING_MODE) &
(0x01 << i))
break;
}
nand_onfi_timing_set(denali, i);
/*
* By now, all the ONFI devices we know support the page cache
* rw feature. So here we enable the pipeline_rw_ahead feature
*/
/* iowrite32(1, denali->flash_reg + CACHE_WRITE_ENABLE); */
/* iowrite32(1, denali->flash_reg + CACHE_READ_ENABLE); */
return PASS;
}
static void get_samsung_nand_para(struct denali_nand_info *denali,
uint8_t device_id)
{
if (device_id == 0xd3) { /* Samsung K9WAG08U1A */
/* Set timing register values according to datasheet */
iowrite32(5, denali->flash_reg + ACC_CLKS);
iowrite32(20, denali->flash_reg + RE_2_WE);
iowrite32(12, denali->flash_reg + WE_2_RE);
iowrite32(14, denali->flash_reg + ADDR_2_DATA);
iowrite32(3, denali->flash_reg + RDWR_EN_LO_CNT);
iowrite32(2, denali->flash_reg + RDWR_EN_HI_CNT);
iowrite32(2, denali->flash_reg + CS_SETUP_CNT);
}
}
static void get_toshiba_nand_para(struct denali_nand_info *denali)
{
uint32_t tmp;
/*
* Workaround to fix a controller bug which reports a wrong
* spare area size for some kind of Toshiba NAND device
*/
if ((ioread32(denali->flash_reg + DEVICE_MAIN_AREA_SIZE) == 4096) &&
(ioread32(denali->flash_reg + DEVICE_SPARE_AREA_SIZE) == 64)) {
iowrite32(216, denali->flash_reg + DEVICE_SPARE_AREA_SIZE);
tmp = ioread32(denali->flash_reg + DEVICES_CONNECTED) *
ioread32(denali->flash_reg + DEVICE_SPARE_AREA_SIZE);
iowrite32(tmp,
denali->flash_reg + LOGICAL_PAGE_SPARE_SIZE);
#if SUPPORT_15BITECC
iowrite32(15, denali->flash_reg + ECC_CORRECTION);
#elif SUPPORT_8BITECC
iowrite32(8, denali->flash_reg + ECC_CORRECTION);
#endif
}
}
static void get_hynix_nand_para(struct denali_nand_info *denali,
uint8_t device_id)
{
uint32_t main_size, spare_size;
switch (device_id) {
case 0xD5: /* Hynix H27UAG8T2A, H27UBG8U5A or H27UCG8VFA */
case 0xD7: /* Hynix H27UDG8VEM, H27UCG8UDM or H27UCG8V5A */
iowrite32(128, denali->flash_reg + PAGES_PER_BLOCK);
iowrite32(4096, denali->flash_reg + DEVICE_MAIN_AREA_SIZE);
iowrite32(224, denali->flash_reg + DEVICE_SPARE_AREA_SIZE);
main_size = 4096 *
ioread32(denali->flash_reg + DEVICES_CONNECTED);
spare_size = 224 *
ioread32(denali->flash_reg + DEVICES_CONNECTED);
iowrite32(main_size,
denali->flash_reg + LOGICAL_PAGE_DATA_SIZE);
iowrite32(spare_size,
denali->flash_reg + LOGICAL_PAGE_SPARE_SIZE);
iowrite32(0, denali->flash_reg + DEVICE_WIDTH);
#if SUPPORT_15BITECC
iowrite32(15, denali->flash_reg + ECC_CORRECTION);
#elif SUPPORT_8BITECC
iowrite32(8, denali->flash_reg + ECC_CORRECTION);
#endif
break;
default:
dev_warn(denali->dev,
"Spectra: Unknown Hynix NAND (Device ID: 0x%x).\n"
"Will use default parameter values instead.\n",
device_id);
}
}
/*
* determines how many NAND chips are connected to the controller. Note for
* Intel CE4100 devices we don't support more than one device.
*/
static void find_valid_banks(struct denali_nand_info *denali)
{
uint32_t id[denali->max_banks];
int i;
denali->total_used_banks = 1;
for (i = 0; i < denali->max_banks; i++) {
index_addr(denali, MODE_11 | (i << 24) | 0, 0x90);
index_addr(denali, MODE_11 | (i << 24) | 1, 0);
index_addr_read_data(denali, MODE_11 | (i << 24) | 2, &id[i]);
dev_dbg(denali->dev,
"Return 1st ID for bank[%d]: %x\n", i, id[i]);
if (i == 0) {
if (!(id[i] & 0x0ff))
break; /* WTF? */
} else {
if ((id[i] & 0x0ff) == (id[0] & 0x0ff))
denali->total_used_banks++;
else
break;
}
}
if (denali->platform == INTEL_CE4100) {
/*
* Platform limitations of the CE4100 device limit
* users to a single chip solution for NAND.
* Multichip support is not enabled.
*/
if (denali->total_used_banks != 1) {
dev_err(denali->dev,
"Sorry, Intel CE4100 only supports a single NAND device.\n");
BUG();
}
}
dev_dbg(denali->dev,
"denali->total_used_banks: %d\n", denali->total_used_banks);
}
/*
* Use the configuration feature register to determine the maximum number of
* banks that the hardware supports.
*/
static void detect_max_banks(struct denali_nand_info *denali)
{
uint32_t features = ioread32(denali->flash_reg + FEATURES);
denali->max_banks = 2 << (features & FEATURES__N_BANKS);
}
static void detect_partition_feature(struct denali_nand_info *denali)
{
/*
* For MRST platform, denali->fwblks represent the
* number of blocks firmware is taken,
* FW is in protect partition and MTD driver has no
* permission to access it. So let driver know how many
* blocks it can't touch.
*/
if (ioread32(denali->flash_reg + FEATURES) & FEATURES__PARTITION) {
if ((ioread32(denali->flash_reg + PERM_SRC_ID(1)) &
PERM_SRC_ID__SRCID) == SPECTRA_PARTITION_ID) {
denali->fwblks =
((ioread32(denali->flash_reg + MIN_MAX_BANK(1)) &
MIN_MAX_BANK__MIN_VALUE) *
denali->blksperchip)
+
(ioread32(denali->flash_reg + MIN_BLK_ADDR(1)) &
MIN_BLK_ADDR__VALUE);
} else {
denali->fwblks = SPECTRA_START_BLOCK;
}
} else {
denali->fwblks = SPECTRA_START_BLOCK;
}
}
static uint16_t denali_nand_timing_set(struct denali_nand_info *denali)
{
uint16_t status = PASS;
uint32_t id_bytes[8], addr;
uint8_t maf_id, device_id;
int i;
dev_dbg(denali->dev, "%s, Line %d, Function: %s\n",
__FILE__, __LINE__, __func__);
/*
* Use read id method to get device ID and other params.
* For some NAND chips, controller can't report the correct
* device ID by reading from DEVICE_ID register
*/
addr = MODE_11 | BANK(denali->flash_bank);
index_addr(denali, addr | 0, 0x90);
index_addr(denali, addr | 1, 0);
for (i = 0; i < 8; i++)
index_addr_read_data(denali, addr | 2, &id_bytes[i]);
maf_id = id_bytes[0];
device_id = id_bytes[1];
if (ioread32(denali->flash_reg + ONFI_DEVICE_NO_OF_LUNS) &
ONFI_DEVICE_NO_OF_LUNS__ONFI_DEVICE) { /* ONFI 1.0 NAND */
if (FAIL == get_onfi_nand_para(denali))
return FAIL;
} else if (maf_id == 0xEC) { /* Samsung NAND */
get_samsung_nand_para(denali, device_id);
} else if (maf_id == 0x98) { /* Toshiba NAND */
get_toshiba_nand_para(denali);
} else if (maf_id == 0xAD) { /* Hynix NAND */
get_hynix_nand_para(denali, device_id);
}
dev_info(denali->dev,
"Dump timing register values:\n"
"acc_clks: %d, re_2_we: %d, re_2_re: %d\n"
"we_2_re: %d, addr_2_data: %d, rdwr_en_lo_cnt: %d\n"
"rdwr_en_hi_cnt: %d, cs_setup_cnt: %d\n",
ioread32(denali->flash_reg + ACC_CLKS),
ioread32(denali->flash_reg + RE_2_WE),
ioread32(denali->flash_reg + RE_2_RE),
ioread32(denali->flash_reg + WE_2_RE),
ioread32(denali->flash_reg + ADDR_2_DATA),
ioread32(denali->flash_reg + RDWR_EN_LO_CNT),
ioread32(denali->flash_reg + RDWR_EN_HI_CNT),
ioread32(denali->flash_reg + CS_SETUP_CNT));
find_valid_banks(denali);
detect_partition_feature(denali);
/*
* If the user specified to override the default timings
* with a specific ONFI mode, we apply those changes here.
*/
if (onfi_timing_mode != NAND_DEFAULT_TIMINGS)
nand_onfi_timing_set(denali, onfi_timing_mode);
return status;
}
static void denali_set_intr_modes(struct denali_nand_info *denali,
uint16_t INT_ENABLE)
{
dev_dbg(denali->dev, "%s, Line %d, Function: %s\n",
__FILE__, __LINE__, __func__);
if (INT_ENABLE)
iowrite32(1, denali->flash_reg + GLOBAL_INT_ENABLE);
else
iowrite32(0, denali->flash_reg + GLOBAL_INT_ENABLE);
}
/*
* validation function to verify that the controlling software is making
* a valid request
*/
static inline bool is_flash_bank_valid(int flash_bank)
{
return flash_bank >= 0 && flash_bank < 4;
}
static void denali_irq_init(struct denali_nand_info *denali)
{
uint32_t int_mask;
int i;
/* Disable global interrupts */
denali_set_intr_modes(denali, false);
int_mask = DENALI_IRQ_ALL;
/* Clear all status bits */
for (i = 0; i < denali->max_banks; ++i)
iowrite32(0xFFFF, denali->flash_reg + INTR_STATUS(i));
denali_irq_enable(denali, int_mask);
}
static void denali_irq_cleanup(int irqnum, struct denali_nand_info *denali)
{
denali_set_intr_modes(denali, false);
free_irq(irqnum, denali);
}
static void denali_irq_enable(struct denali_nand_info *denali,
uint32_t int_mask)
{
int i;
for (i = 0; i < denali->max_banks; ++i)
iowrite32(int_mask, denali->flash_reg + INTR_EN(i));
}
/*
* This function only returns when an interrupt that this driver cares about
* occurs. This is to reduce the overhead of servicing interrupts
*/
static inline uint32_t denali_irq_detected(struct denali_nand_info *denali)
{
return read_interrupt_status(denali) & DENALI_IRQ_ALL;
}
/* Interrupts are cleared by writing a 1 to the appropriate status bit */
static inline void clear_interrupt(struct denali_nand_info *denali,
uint32_t irq_mask)
{
uint32_t intr_status_reg;
intr_status_reg = INTR_STATUS(denali->flash_bank);
iowrite32(irq_mask, denali->flash_reg + intr_status_reg);
}
static void clear_interrupts(struct denali_nand_info *denali)
{
uint32_t status;
spin_lock_irq(&denali->irq_lock);
status = read_interrupt_status(denali);
clear_interrupt(denali, status);
denali->irq_status = 0x0;
spin_unlock_irq(&denali->irq_lock);
}
static uint32_t read_interrupt_status(struct denali_nand_info *denali)
{
uint32_t intr_status_reg;
intr_status_reg = INTR_STATUS(denali->flash_bank);
return ioread32(denali->flash_reg + intr_status_reg);
}
/*
* This is the interrupt service routine. It handles all interrupts
* sent to this device. Note that on CE4100, this is a shared interrupt.
*/
static irqreturn_t denali_isr(int irq, void *dev_id)
{
struct denali_nand_info *denali = dev_id;
uint32_t irq_status;
irqreturn_t result = IRQ_NONE;
spin_lock(&denali->irq_lock);
/* check to see if a valid NAND chip has been selected. */
if (is_flash_bank_valid(denali->flash_bank)) {
/*
* check to see if controller generated the interrupt,
* since this is a shared interrupt
*/
irq_status = denali_irq_detected(denali);
if (irq_status != 0) {
/* handle interrupt */
/* first acknowledge it */
clear_interrupt(denali, irq_status);
/*
* store the status in the device context for someone
* to read
*/
denali->irq_status |= irq_status;
/* notify anyone who cares that it happened */
complete(&denali->complete);
/* tell the OS that we've handled this */
result = IRQ_HANDLED;
}
}
spin_unlock(&denali->irq_lock);
return result;
}
#define BANK(x) ((x) << 24)
static uint32_t wait_for_irq(struct denali_nand_info *denali, uint32_t irq_mask)
{
unsigned long comp_res;
uint32_t intr_status;
unsigned long timeout = msecs_to_jiffies(1000);
do {
comp_res =
wait_for_completion_timeout(&denali->complete, timeout);
spin_lock_irq(&denali->irq_lock);
intr_status = denali->irq_status;
if (intr_status & irq_mask) {
denali->irq_status &= ~irq_mask;
spin_unlock_irq(&denali->irq_lock);
/* our interrupt was detected */
break;
}
/*
* these are not the interrupts you are looking for -
* need to wait again
*/
spin_unlock_irq(&denali->irq_lock);
} while (comp_res != 0);
if (comp_res == 0) {
/* timeout */
pr_err("timeout occurred, status = 0x%x, mask = 0x%x\n",
intr_status, irq_mask);
intr_status = 0;
}
return intr_status;
}
/*
* This helper function setups the registers for ECC and whether or not
* the spare area will be transferred.
*/
static void setup_ecc_for_xfer(struct denali_nand_info *denali, bool ecc_en,
bool transfer_spare)
{
int ecc_en_flag, transfer_spare_flag;
/* set ECC, transfer spare bits if needed */
ecc_en_flag = ecc_en ? ECC_ENABLE__FLAG : 0;
transfer_spare_flag = transfer_spare ? TRANSFER_SPARE_REG__FLAG : 0;
/* Enable spare area/ECC per user's request. */
iowrite32(ecc_en_flag, denali->flash_reg + ECC_ENABLE);
iowrite32(transfer_spare_flag, denali->flash_reg + TRANSFER_SPARE_REG);
}
/*
* sends a pipeline command operation to the controller. See the Denali NAND
* controller's user guide for more information (section 4.2.3.6).
*/
static int denali_send_pipeline_cmd(struct denali_nand_info *denali,
bool ecc_en, bool transfer_spare,
int access_type, int op)
{
int status = PASS;
uint32_t page_count = 1;
uint32_t addr, cmd, irq_status, irq_mask;
if (op == DENALI_READ)
irq_mask = INTR_STATUS__LOAD_COMP;
else if (op == DENALI_WRITE)
irq_mask = 0;
else
BUG();
setup_ecc_for_xfer(denali, ecc_en, transfer_spare);
clear_interrupts(denali);
addr = BANK(denali->flash_bank) | denali->page;
if (op == DENALI_WRITE && access_type != SPARE_ACCESS) {
cmd = MODE_01 | addr;
iowrite32(cmd, denali->flash_mem);
} else if (op == DENALI_WRITE && access_type == SPARE_ACCESS) {
/* read spare area */
cmd = MODE_10 | addr;
index_addr(denali, cmd, access_type);
cmd = MODE_01 | addr;
iowrite32(cmd, denali->flash_mem);
} else if (op == DENALI_READ) {
/* setup page read request for access type */
cmd = MODE_10 | addr;
index_addr(denali, cmd, access_type);
/*
* page 33 of the NAND controller spec indicates we should not
* use the pipeline commands in Spare area only mode.
* So we don't.
*/
if (access_type == SPARE_ACCESS) {
cmd = MODE_01 | addr;
iowrite32(cmd, denali->flash_mem);
} else {
index_addr(denali, cmd,
PIPELINE_ACCESS | op | page_count);
/*
* wait for command to be accepted
* can always use status0 bit as the
* mask is identical for each bank.
*/
irq_status = wait_for_irq(denali, irq_mask);
if (irq_status == 0) {
dev_err(denali->dev,
"cmd, page, addr on timeout (0x%x, 0x%x, 0x%x)\n",
cmd, denali->page, addr);
status = FAIL;
} else {
cmd = MODE_01 | addr;
iowrite32(cmd, denali->flash_mem);
}
}
}
return status;
}
/* helper function that simply writes a buffer to the flash */
static int write_data_to_flash_mem(struct denali_nand_info *denali,
const uint8_t *buf, int len)
{
uint32_t *buf32;
int i;
/*
* verify that the len is a multiple of 4.
* see comment in read_data_from_flash_mem()
*/
BUG_ON((len % 4) != 0);
/* write the data to the flash memory */
buf32 = (uint32_t *)buf;
for (i = 0; i < len / 4; i++)
iowrite32(*buf32++, denali->flash_mem + 0x10);
return i * 4; /* intent is to return the number of bytes read */
}
/* helper function that simply reads a buffer from the flash */
static int read_data_from_flash_mem(struct denali_nand_info *denali,
uint8_t *buf, int len)
{
uint32_t *buf32;
int i;
/*
* we assume that len will be a multiple of 4, if not it would be nice
* to know about it ASAP rather than have random failures...
* This assumption is based on the fact that this function is designed
* to be used to read flash pages, which are typically multiples of 4.
*/
BUG_ON((len % 4) != 0);
/* transfer the data from the flash */
buf32 = (uint32_t *)buf;
for (i = 0; i < len / 4; i++)
*buf32++ = ioread32(denali->flash_mem + 0x10);
return i * 4; /* intent is to return the number of bytes read */
}
/* writes OOB data to the device */
static int write_oob_data(struct mtd_info *mtd, uint8_t *buf, int page)
{
struct denali_nand_info *denali = mtd_to_denali(mtd);
uint32_t irq_status;
uint32_t irq_mask = INTR_STATUS__PROGRAM_COMP |
INTR_STATUS__PROGRAM_FAIL;
int status = 0;
denali->page = page;
if (denali_send_pipeline_cmd(denali, false, false, SPARE_ACCESS,
DENALI_WRITE) == PASS) {
write_data_to_flash_mem(denali, buf, mtd->oobsize);
/* wait for operation to complete */
irq_status = wait_for_irq(denali, irq_mask);
if (irq_status == 0) {
dev_err(denali->dev, "OOB write failed\n");
status = -EIO;
}
} else {
dev_err(denali->dev, "unable to send pipeline command\n");
status = -EIO;
}
return status;
}
/* reads OOB data from the device */
static void read_oob_data(struct mtd_info *mtd, uint8_t *buf, int page)
{
struct denali_nand_info *denali = mtd_to_denali(mtd);
uint32_t irq_mask = INTR_STATUS__LOAD_COMP;
uint32_t irq_status, addr, cmd;
denali->page = page;
if (denali_send_pipeline_cmd(denali, false, true, SPARE_ACCESS,
DENALI_READ) == PASS) {
read_data_from_flash_mem(denali, buf, mtd->oobsize);
/*
* wait for command to be accepted
* can always use status0 bit as the
* mask is identical for each bank.
*/
irq_status = wait_for_irq(denali, irq_mask);
if (irq_status == 0)
dev_err(denali->dev, "page on OOB timeout %d\n",
denali->page);
/*
* We set the device back to MAIN_ACCESS here as I observed
* instability with the controller if you do a block erase
* and the last transaction was a SPARE_ACCESS. Block erase
* is reliable (according to the MTD test infrastructure)
* if you are in MAIN_ACCESS.
*/
addr = BANK(denali->flash_bank) | denali->page;
cmd = MODE_10 | addr;
index_addr(denali, cmd, MAIN_ACCESS);
}
}
/*
* this function examines buffers to see if they contain data that
* indicate that the buffer is part of an erased region of flash.
*/
static bool is_erased(uint8_t *buf, int len)
{
int i;
for (i = 0; i < len; i++)
if (buf[i] != 0xFF)
return false;
return true;
}
#define ECC_SECTOR_SIZE 512
#define ECC_SECTOR(x) (((x) & ECC_ERROR_ADDRESS__SECTOR_NR) >> 12)
#define ECC_BYTE(x) (((x) & ECC_ERROR_ADDRESS__OFFSET))
#define ECC_CORRECTION_VALUE(x) ((x) & ERR_CORRECTION_INFO__BYTEMASK)
#define ECC_ERROR_CORRECTABLE(x) (!((x) & ERR_CORRECTION_INFO__ERROR_TYPE))
#define ECC_ERR_DEVICE(x) (((x) & ERR_CORRECTION_INFO__DEVICE_NR) >> 8)
#define ECC_LAST_ERR(x) ((x) & ERR_CORRECTION_INFO__LAST_ERR_INFO)
static bool handle_ecc(struct denali_nand_info *denali, uint8_t *buf,
uint32_t irq_status, unsigned int *max_bitflips)
{
bool check_erased_page = false;
unsigned int bitflips = 0;
if (irq_status & INTR_STATUS__ECC_ERR) {
/* read the ECC errors. we'll ignore them for now */
uint32_t err_address, err_correction_info, err_byte,
err_sector, err_device, err_correction_value;
denali_set_intr_modes(denali, false);
do {
err_address = ioread32(denali->flash_reg +
ECC_ERROR_ADDRESS);
err_sector = ECC_SECTOR(err_address);
err_byte = ECC_BYTE(err_address);
err_correction_info = ioread32(denali->flash_reg +
ERR_CORRECTION_INFO);
err_correction_value =
ECC_CORRECTION_VALUE(err_correction_info);
err_device = ECC_ERR_DEVICE(err_correction_info);
if (ECC_ERROR_CORRECTABLE(err_correction_info)) {
/*
* If err_byte is larger than ECC_SECTOR_SIZE,
* means error happened in OOB, so we ignore
* it. It's no need for us to correct it
* err_device is represented the NAND error
* bits are happened in if there are more
* than one NAND connected.
*/
if (err_byte < ECC_SECTOR_SIZE) {
int offset;
offset = (err_sector *
ECC_SECTOR_SIZE +
err_byte) *
denali->devnum +
err_device;
/* correct the ECC error */
buf[offset] ^= err_correction_value;
denali->mtd.ecc_stats.corrected++;
bitflips++;
}
} else {
/*
* if the error is not correctable, need to
* look at the page to see if it is an erased
* page. if so, then it's not a real ECC error
*/
check_erased_page = true;
}
} while (!ECC_LAST_ERR(err_correction_info));
/*
* Once handle all ecc errors, controller will triger
* a ECC_TRANSACTION_DONE interrupt, so here just wait
* for a while for this interrupt
*/
while (!(read_interrupt_status(denali) &
INTR_STATUS__ECC_TRANSACTION_DONE))
cpu_relax();
clear_interrupts(denali);
denali_set_intr_modes(denali, true);
}
*max_bitflips = bitflips;
return check_erased_page;
}
/* programs the controller to either enable/disable DMA transfers */
static void denali_enable_dma(struct denali_nand_info *denali, bool en)
{
iowrite32(en ? DMA_ENABLE__FLAG : 0, denali->flash_reg + DMA_ENABLE);
ioread32(denali->flash_reg + DMA_ENABLE);
}
/* setups the HW to perform the data DMA */
static void denali_setup_dma(struct denali_nand_info *denali, int op)
{
uint32_t mode;
const int page_count = 1;
uint32_t addr = denali->buf.dma_buf;
mode = MODE_10 | BANK(denali->flash_bank);
/* DMA is a four step process */
/* 1. setup transfer type and # of pages */
index_addr(denali, mode | denali->page, 0x2000 | op | page_count);
/* 2. set memory high address bits 23:8 */
index_addr(denali, mode | ((addr >> 16) << 8), 0x2200);
/* 3. set memory low address bits 23:8 */
index_addr(denali, mode | ((addr & 0xffff) << 8), 0x2300);
/* 4. interrupt when complete, burst len = 64 bytes */
index_addr(denali, mode | 0x14000, 0x2400);
}
/*
* writes a page. user specifies type, and this function handles the
* configuration details.
*/
static int write_page(struct mtd_info *mtd, struct nand_chip *chip,
const uint8_t *buf, bool raw_xfer)
{
struct denali_nand_info *denali = mtd_to_denali(mtd);
dma_addr_t addr = denali->buf.dma_buf;
size_t size = denali->mtd.writesize + denali->mtd.oobsize;
uint32_t irq_status;
uint32_t irq_mask = INTR_STATUS__DMA_CMD_COMP |
INTR_STATUS__PROGRAM_FAIL;
/*
* if it is a raw xfer, we want to disable ecc and send the spare area.
* !raw_xfer - enable ecc
* raw_xfer - transfer spare
*/
setup_ecc_for_xfer(denali, !raw_xfer, raw_xfer);
/* copy buffer into DMA buffer */
memcpy(denali->buf.buf, buf, mtd->writesize);
if (raw_xfer) {
/* transfer the data to the spare area */
memcpy(denali->buf.buf + mtd->writesize,
chip->oob_poi,
mtd->oobsize);
}
dma_sync_single_for_device(denali->dev, addr, size, DMA_TO_DEVICE);
clear_interrupts(denali);
denali_enable_dma(denali, true);
denali_setup_dma(denali, DENALI_WRITE);
/* wait for operation to complete */
irq_status = wait_for_irq(denali, irq_mask);
if (irq_status == 0) {
dev_err(denali->dev, "timeout on write_page (type = %d)\n",
raw_xfer);
denali->status = NAND_STATUS_FAIL;
}
denali_enable_dma(denali, false);
dma_sync_single_for_cpu(denali->dev, addr, size, DMA_TO_DEVICE);
return 0;
}
/* NAND core entry points */
/*
* this is the callback that the NAND core calls to write a page. Since
* writing a page with ECC or without is similar, all the work is done
* by write_page above.
*/
static int denali_write_page(struct mtd_info *mtd, struct nand_chip *chip,
const uint8_t *buf, int oob_required)
{
/*
* for regular page writes, we let HW handle all the ECC
* data written to the device.
*/
return write_page(mtd, chip, buf, false);
}
/*
* This is the callback that the NAND core calls to write a page without ECC.
* raw access is similar to ECC page writes, so all the work is done in the
* write_page() function above.
*/
static int denali_write_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
const uint8_t *buf, int oob_required)
{
/*
* for raw page writes, we want to disable ECC and simply write
* whatever data is in the buffer.
*/
return write_page(mtd, chip, buf, true);
}
static int denali_write_oob(struct mtd_info *mtd, struct nand_chip *chip,
int page)
{
return write_oob_data(mtd, chip->oob_poi, page);
}
static int denali_read_oob(struct mtd_info *mtd, struct nand_chip *chip,
int page)
{
read_oob_data(mtd, chip->oob_poi, page);
return 0;
}
static int denali_read_page(struct mtd_info *mtd, struct nand_chip *chip,
uint8_t *buf, int oob_required, int page)
{
unsigned int max_bitflips;
struct denali_nand_info *denali = mtd_to_denali(mtd);
dma_addr_t addr = denali->buf.dma_buf;
size_t size = denali->mtd.writesize + denali->mtd.oobsize;
uint32_t irq_status;
uint32_t irq_mask = INTR_STATUS__ECC_TRANSACTION_DONE |
INTR_STATUS__ECC_ERR;
bool check_erased_page = false;
if (page != denali->page) {
dev_err(denali->dev,
"IN %s: page %d is not equal to denali->page %d",
__func__, page, denali->page);
BUG();
}
setup_ecc_for_xfer(denali, true, false);
denali_enable_dma(denali, true);
dma_sync_single_for_device(denali->dev, addr, size, DMA_FROM_DEVICE);
clear_interrupts(denali);
denali_setup_dma(denali, DENALI_READ);
/* wait for operation to complete */
irq_status = wait_for_irq(denali, irq_mask);
dma_sync_single_for_cpu(denali->dev, addr, size, DMA_FROM_DEVICE);
memcpy(buf, denali->buf.buf, mtd->writesize);
check_erased_page = handle_ecc(denali, buf, irq_status, &max_bitflips);
denali_enable_dma(denali, false);
if (check_erased_page) {
read_oob_data(&denali->mtd, chip->oob_poi, denali->page);
/* check ECC failures that may have occurred on erased pages */
if (check_erased_page) {
if (!is_erased(buf, denali->mtd.writesize))
denali->mtd.ecc_stats.failed++;
if (!is_erased(buf, denali->mtd.oobsize))
denali->mtd.ecc_stats.failed++;
}
}
return max_bitflips;
}
static int denali_read_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
uint8_t *buf, int oob_required, int page)
{
struct denali_nand_info *denali = mtd_to_denali(mtd);
dma_addr_t addr = denali->buf.dma_buf;
size_t size = denali->mtd.writesize + denali->mtd.oobsize;
uint32_t irq_mask = INTR_STATUS__DMA_CMD_COMP;
if (page != denali->page) {
dev_err(denali->dev,
"IN %s: page %d is not equal to denali->page %d",
__func__, page, denali->page);
BUG();
}
setup_ecc_for_xfer(denali, false, true);
denali_enable_dma(denali, true);
dma_sync_single_for_device(denali->dev, addr, size, DMA_FROM_DEVICE);
clear_interrupts(denali);
denali_setup_dma(denali, DENALI_READ);
/* wait for operation to complete */
wait_for_irq(denali, irq_mask);
dma_sync_single_for_cpu(denali->dev, addr, size, DMA_FROM_DEVICE);
denali_enable_dma(denali, false);
memcpy(buf, denali->buf.buf, mtd->writesize);
memcpy(chip->oob_poi, denali->buf.buf + mtd->writesize, mtd->oobsize);
return 0;
}
static uint8_t denali_read_byte(struct mtd_info *mtd)
{
struct denali_nand_info *denali = mtd_to_denali(mtd);
uint8_t result = 0xff;
if (denali->buf.head < denali->buf.tail)
result = denali->buf.buf[denali->buf.head++];
return result;
}
static void denali_select_chip(struct mtd_info *mtd, int chip)
{
struct denali_nand_info *denali = mtd_to_denali(mtd);
spin_lock_irq(&denali->irq_lock);
denali->flash_bank = chip;
spin_unlock_irq(&denali->irq_lock);
}
static int denali_waitfunc(struct mtd_info *mtd, struct nand_chip *chip)
{
struct denali_nand_info *denali = mtd_to_denali(mtd);
int status = denali->status;
denali->status = 0;
return status;
}
static int denali_erase(struct mtd_info *mtd, int page)
{
struct denali_nand_info *denali = mtd_to_denali(mtd);
uint32_t cmd, irq_status;
clear_interrupts(denali);
/* setup page read request for access type */
cmd = MODE_10 | BANK(denali->flash_bank) | page;
index_addr(denali, cmd, 0x1);
/* wait for erase to complete or failure to occur */
irq_status = wait_for_irq(denali, INTR_STATUS__ERASE_COMP |
INTR_STATUS__ERASE_FAIL);
return irq_status & INTR_STATUS__ERASE_FAIL ? NAND_STATUS_FAIL : PASS;
}
static void denali_cmdfunc(struct mtd_info *mtd, unsigned int cmd, int col,
int page)
{
struct denali_nand_info *denali = mtd_to_denali(mtd);
uint32_t addr, id;
int i;
switch (cmd) {
case NAND_CMD_PAGEPROG:
break;
case NAND_CMD_STATUS:
read_status(denali);
break;
case NAND_CMD_READID:
case NAND_CMD_PARAM:
reset_buf(denali);
/*
* sometimes ManufactureId read from register is not right
* e.g. some of Micron MT29F32G08QAA MLC NAND chips
* So here we send READID cmd to NAND insteand
*/
addr = MODE_11 | BANK(denali->flash_bank);
index_addr(denali, addr | 0, 0x90);
index_addr(denali, addr | 1, 0);
for (i = 0; i < 8; i++) {
index_addr_read_data(denali, addr | 2, &id);
write_byte_to_buf(denali, id);
}
break;
case NAND_CMD_READ0:
case NAND_CMD_SEQIN:
denali->page = page;
break;
case NAND_CMD_RESET:
reset_bank(denali);
break;
case NAND_CMD_READOOB:
/* TODO: Read OOB data */
break;
default:
pr_err(": unsupported command received 0x%x\n", cmd);
break;
}
}
/* end NAND core entry points */
/* Initialization code to bring the device up to a known good state */
static void denali_hw_init(struct denali_nand_info *denali)
{
/*
* tell driver how many bit controller will skip before
* writing ECC code in OOB, this register may be already
* set by firmware. So we read this value out.
* if this value is 0, just let it be.
*/
denali->bbtskipbytes = ioread32(denali->flash_reg +
SPARE_AREA_SKIP_BYTES);
detect_max_banks(denali);
denali_nand_reset(denali);
iowrite32(0x0F, denali->flash_reg + RB_PIN_ENABLED);
iowrite32(CHIP_EN_DONT_CARE__FLAG,
denali->flash_reg + CHIP_ENABLE_DONT_CARE);
iowrite32(0xffff, denali->flash_reg + SPARE_AREA_MARKER);
/* Should set value for these registers when init */
iowrite32(0, denali->flash_reg + TWO_ROW_ADDR_CYCLES);
iowrite32(1, denali->flash_reg + ECC_ENABLE);
denali_nand_timing_set(denali);
denali_irq_init(denali);
}
/*
* Althogh controller spec said SLC ECC is forceb to be 4bit,
* but denali controller in MRST only support 15bit and 8bit ECC
* correction
*/
#define ECC_8BITS 14
static struct nand_ecclayout nand_8bit_oob = {
.eccbytes = 14,
};
#define ECC_15BITS 26
static struct nand_ecclayout nand_15bit_oob = {
.eccbytes = 26,
};
static uint8_t bbt_pattern[] = {'B', 'b', 't', '0' };
static uint8_t mirror_pattern[] = {'1', 't', 'b', 'B' };
static struct nand_bbt_descr bbt_main_descr = {
.options = NAND_BBT_LASTBLOCK | NAND_BBT_CREATE | NAND_BBT_WRITE
| NAND_BBT_2BIT | NAND_BBT_VERSION | NAND_BBT_PERCHIP,
.offs = 8,
.len = 4,
.veroffs = 12,
.maxblocks = 4,
.pattern = bbt_pattern,
};
static struct nand_bbt_descr bbt_mirror_descr = {
.options = NAND_BBT_LASTBLOCK | NAND_BBT_CREATE | NAND_BBT_WRITE
| NAND_BBT_2BIT | NAND_BBT_VERSION | NAND_BBT_PERCHIP,
.offs = 8,
.len = 4,
.veroffs = 12,
.maxblocks = 4,
.pattern = mirror_pattern,
};
/* initialize driver data structures */
static void denali_drv_init(struct denali_nand_info *denali)
{
denali->idx = 0;
/* setup interrupt handler */
/*
* the completion object will be used to notify
* the callee that the interrupt is done
*/
init_completion(&denali->complete);
/*
* the spinlock will be used to synchronize the ISR with any
* element that might be access shared data (interrupt status)
*/
spin_lock_init(&denali->irq_lock);
/* indicate that MTD has not selected a valid bank yet */
denali->flash_bank = CHIP_SELECT_INVALID;
/* initialize our irq_status variable to indicate no interrupts */
denali->irq_status = 0;
}
int denali_init(struct denali_nand_info *denali)
{
int ret;
if (denali->platform == INTEL_CE4100) {
/*
* Due to a silicon limitation, we can only support
* ONFI timing mode 1 and below.
*/
if (onfi_timing_mode < -1 || onfi_timing_mode > 1) {
pr_err("Intel CE4100 only supports ONFI timing mode 1 or below\n");
return -EINVAL;
}
}
/* allocate a temporary buffer for nand_scan_ident() */
denali->buf.buf = devm_kzalloc(denali->dev, PAGE_SIZE,
GFP_DMA | GFP_KERNEL);
if (!denali->buf.buf)
return -ENOMEM;
denali->mtd.dev.parent = denali->dev;
denali_hw_init(denali);
denali_drv_init(denali);
/*
* denali_isr register is done after all the hardware
* initilization is finished
*/
if (request_irq(denali->irq, denali_isr, IRQF_SHARED,
DENALI_NAND_NAME, denali)) {
pr_err("Spectra: Unable to allocate IRQ\n");
return -ENODEV;
}
/* now that our ISR is registered, we can enable interrupts */
denali_set_intr_modes(denali, true);
denali->mtd.name = "denali-nand";
denali->mtd.owner = THIS_MODULE;
denali->mtd.priv = &denali->nand;
/* register the driver with the NAND core subsystem */
denali->nand.select_chip = denali_select_chip;
denali->nand.cmdfunc = denali_cmdfunc;
denali->nand.read_byte = denali_read_byte;
denali->nand.waitfunc = denali_waitfunc;
/*
* scan for NAND devices attached to the controller
* this is the first stage in a two step process to register
* with the nand subsystem
*/
if (nand_scan_ident(&denali->mtd, denali->max_banks, NULL)) {
ret = -ENXIO;
goto failed_req_irq;
}
/* allocate the right size buffer now */
devm_kfree(denali->dev, denali->buf.buf);
denali->buf.buf = devm_kzalloc(denali->dev,
denali->mtd.writesize + denali->mtd.oobsize,
GFP_KERNEL);
if (!denali->buf.buf) {
ret = -ENOMEM;
goto failed_req_irq;
}
/* Is 32-bit DMA supported? */
ret = dma_set_mask(denali->dev, DMA_BIT_MASK(32));
if (ret) {
pr_err("Spectra: no usable DMA configuration\n");
goto failed_req_irq;
}
denali->buf.dma_buf = dma_map_single(denali->dev, denali->buf.buf,
denali->mtd.writesize + denali->mtd.oobsize,
DMA_BIDIRECTIONAL);
if (dma_mapping_error(denali->dev, denali->buf.dma_buf)) {
dev_err(denali->dev, "Spectra: failed to map DMA buffer\n");
ret = -EIO;
goto failed_req_irq;
}
/*
* support for multi nand
* MTD known nothing about multi nand, so we should tell it
* the real pagesize and anything necessery
*/
denali->devnum = ioread32(denali->flash_reg + DEVICES_CONNECTED);
denali->nand.chipsize <<= (denali->devnum - 1);
denali->nand.page_shift += (denali->devnum - 1);
denali->nand.pagemask = (denali->nand.chipsize >>
denali->nand.page_shift) - 1;
denali->nand.bbt_erase_shift += (denali->devnum - 1);
denali->nand.phys_erase_shift = denali->nand.bbt_erase_shift;
denali->nand.chip_shift += (denali->devnum - 1);
denali->mtd.writesize <<= (denali->devnum - 1);
denali->mtd.oobsize <<= (denali->devnum - 1);
denali->mtd.erasesize <<= (denali->devnum - 1);
denali->mtd.size = denali->nand.numchips * denali->nand.chipsize;
denali->bbtskipbytes *= denali->devnum;
/*
* second stage of the NAND scan
* this stage requires information regarding ECC and
* bad block management.
*/
/* Bad block management */
denali->nand.bbt_td = &bbt_main_descr;
denali->nand.bbt_md = &bbt_mirror_descr;
/* skip the scan for now until we have OOB read and write support */
denali->nand.bbt_options |= NAND_BBT_USE_FLASH;
denali->nand.options |= NAND_SKIP_BBTSCAN;
denali->nand.ecc.mode = NAND_ECC_HW_SYNDROME;
/* no subpage writes on denali */
denali->nand.options |= NAND_NO_SUBPAGE_WRITE;
/*
* Denali Controller only support 15bit and 8bit ECC in MRST,
* so just let controller do 15bit ECC for MLC and 8bit ECC for
* SLC if possible.
* */
if (!nand_is_slc(&denali->nand) &&
(denali->mtd.oobsize > (denali->bbtskipbytes +
ECC_15BITS * (denali->mtd.writesize /
ECC_SECTOR_SIZE)))) {
/* if MLC OOB size is large enough, use 15bit ECC*/
denali->nand.ecc.strength = 15;
denali->nand.ecc.layout = &nand_15bit_oob;
denali->nand.ecc.bytes = ECC_15BITS;
iowrite32(15, denali->flash_reg + ECC_CORRECTION);
} else if (denali->mtd.oobsize < (denali->bbtskipbytes +
ECC_8BITS * (denali->mtd.writesize /
ECC_SECTOR_SIZE))) {
pr_err("Your NAND chip OOB is not large enough to contain 8bit ECC correction codes");
goto failed_req_irq;
} else {
denali->nand.ecc.strength = 8;
denali->nand.ecc.layout = &nand_8bit_oob;
denali->nand.ecc.bytes = ECC_8BITS;
iowrite32(8, denali->flash_reg + ECC_CORRECTION);
}
denali->nand.ecc.bytes *= denali->devnum;
denali->nand.ecc.strength *= denali->devnum;
denali->nand.ecc.layout->eccbytes *=
denali->mtd.writesize / ECC_SECTOR_SIZE;
denali->nand.ecc.layout->oobfree[0].offset =
denali->bbtskipbytes + denali->nand.ecc.layout->eccbytes;
denali->nand.ecc.layout->oobfree[0].length =
denali->mtd.oobsize - denali->nand.ecc.layout->eccbytes -
denali->bbtskipbytes;
/*
* Let driver know the total blocks number and how many blocks
* contained by each nand chip. blksperchip will help driver to
* know how many blocks is taken by FW.
*/
denali->totalblks = denali->mtd.size >> denali->nand.phys_erase_shift;
denali->blksperchip = denali->totalblks / denali->nand.numchips;
/* override the default read operations */
denali->nand.ecc.size = ECC_SECTOR_SIZE * denali->devnum;
denali->nand.ecc.read_page = denali_read_page;
denali->nand.ecc.read_page_raw = denali_read_page_raw;
denali->nand.ecc.write_page = denali_write_page;
denali->nand.ecc.write_page_raw = denali_write_page_raw;
denali->nand.ecc.read_oob = denali_read_oob;
denali->nand.ecc.write_oob = denali_write_oob;
denali->nand.erase = denali_erase;
if (nand_scan_tail(&denali->mtd)) {
ret = -ENXIO;
goto failed_req_irq;
}
ret = mtd_device_register(&denali->mtd, NULL, 0);
if (ret) {
dev_err(denali->dev, "Spectra: Failed to register MTD: %d\n",
ret);
goto failed_req_irq;
}
return 0;
failed_req_irq:
denali_irq_cleanup(denali->irq, denali);
return ret;
}
EXPORT_SYMBOL(denali_init);
/* driver exit point */
void denali_remove(struct denali_nand_info *denali)
{
denali_irq_cleanup(denali->irq, denali);
dma_unmap_single(denali->dev, denali->buf.dma_buf,
denali->mtd.writesize + denali->mtd.oobsize,
DMA_BIDIRECTIONAL);
}
EXPORT_SYMBOL(denali_remove);
| gpl-2.0 |
fards/ainol_elfii_common | fs/cifs/cifsfs.c | 1629 | 32230 | /*
* fs/cifs/cifsfs.c
*
* Copyright (C) International Business Machines Corp., 2002,2008
* Author(s): Steve French (sfrench@us.ibm.com)
*
* Common Internet FileSystem (CIFS) client
*
* 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
*/
/* Note that BB means BUGBUG (ie something to fix eventually) */
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/mount.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/list.h>
#include <linux/seq_file.h>
#include <linux/vfs.h>
#include <linux/mempool.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/freezer.h>
#include <linux/namei.h>
#include <net/ipv6.h>
#include "cifsfs.h"
#include "cifspdu.h"
#define DECLARE_GLOBALS_HERE
#include "cifsglob.h"
#include "cifsproto.h"
#include "cifs_debug.h"
#include "cifs_fs_sb.h"
#include <linux/mm.h>
#include <linux/key-type.h>
#include "cifs_spnego.h"
#include "fscache.h"
#define CIFS_MAGIC_NUMBER 0xFF534D42 /* the first four bytes of SMB PDUs */
int cifsFYI = 0;
int cifsERROR = 1;
int traceSMB = 0;
unsigned int oplockEnabled = 1;
unsigned int linuxExtEnabled = 1;
unsigned int lookupCacheEnabled = 1;
unsigned int multiuser_mount = 0;
unsigned int global_secflags = CIFSSEC_DEF;
/* unsigned int ntlmv2_support = 0; */
unsigned int sign_CIFS_PDUs = 1;
static const struct super_operations cifs_super_ops;
unsigned int CIFSMaxBufSize = CIFS_MAX_MSGSIZE;
module_param(CIFSMaxBufSize, int, 0);
MODULE_PARM_DESC(CIFSMaxBufSize, "Network buffer size (not including header). "
"Default: 16384 Range: 8192 to 130048");
unsigned int cifs_min_rcv = CIFS_MIN_RCV_POOL;
module_param(cifs_min_rcv, int, 0);
MODULE_PARM_DESC(cifs_min_rcv, "Network buffers in pool. Default: 4 Range: "
"1 to 64");
unsigned int cifs_min_small = 30;
module_param(cifs_min_small, int, 0);
MODULE_PARM_DESC(cifs_min_small, "Small network buffers in pool. Default: 30 "
"Range: 2 to 256");
unsigned int cifs_max_pending = CIFS_MAX_REQ;
module_param(cifs_max_pending, int, 0);
MODULE_PARM_DESC(cifs_max_pending, "Simultaneous requests to server. "
"Default: 50 Range: 2 to 256");
unsigned short echo_retries = 5;
module_param(echo_retries, ushort, 0644);
MODULE_PARM_DESC(echo_retries, "Number of echo attempts before giving up and "
"reconnecting server. Default: 5. 0 means "
"never reconnect.");
extern mempool_t *cifs_sm_req_poolp;
extern mempool_t *cifs_req_poolp;
extern mempool_t *cifs_mid_poolp;
void
cifs_sb_active(struct super_block *sb)
{
struct cifs_sb_info *server = CIFS_SB(sb);
if (atomic_inc_return(&server->active) == 1)
atomic_inc(&sb->s_active);
}
void
cifs_sb_deactive(struct super_block *sb)
{
struct cifs_sb_info *server = CIFS_SB(sb);
if (atomic_dec_and_test(&server->active))
deactivate_super(sb);
}
static int
cifs_read_super(struct super_block *sb)
{
struct inode *inode;
struct cifs_sb_info *cifs_sb;
int rc = 0;
cifs_sb = CIFS_SB(sb);
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_POSIXACL)
sb->s_flags |= MS_POSIXACL;
if (cifs_sb_master_tcon(cifs_sb)->ses->capabilities & CAP_LARGE_FILES)
sb->s_maxbytes = MAX_LFS_FILESIZE;
else
sb->s_maxbytes = MAX_NON_LFS;
/* BB FIXME fix time_gran to be larger for LANMAN sessions */
sb->s_time_gran = 100;
sb->s_magic = CIFS_MAGIC_NUMBER;
sb->s_op = &cifs_super_ops;
sb->s_bdi = &cifs_sb->bdi;
sb->s_blocksize = CIFS_MAX_MSGSIZE;
sb->s_blocksize_bits = 14; /* default 2**14 = CIFS_MAX_MSGSIZE */
inode = cifs_root_iget(sb);
if (IS_ERR(inode)) {
rc = PTR_ERR(inode);
inode = NULL;
goto out_no_root;
}
sb->s_root = d_alloc_root(inode);
if (!sb->s_root) {
rc = -ENOMEM;
goto out_no_root;
}
/* do that *after* d_alloc_root() - we want NULL ->d_op for root here */
if (cifs_sb_master_tcon(cifs_sb)->nocase)
sb->s_d_op = &cifs_ci_dentry_ops;
else
sb->s_d_op = &cifs_dentry_ops;
#ifdef CIFS_NFSD_EXPORT
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_SERVER_INUM) {
cFYI(1, "export ops supported");
sb->s_export_op = &cifs_export_ops;
}
#endif /* CIFS_NFSD_EXPORT */
return 0;
out_no_root:
cERROR(1, "cifs_read_super: get root inode failed");
if (inode)
iput(inode);
return rc;
}
static void cifs_kill_sb(struct super_block *sb)
{
struct cifs_sb_info *cifs_sb = CIFS_SB(sb);
kill_anon_super(sb);
cifs_umount(cifs_sb);
}
static int
cifs_statfs(struct dentry *dentry, struct kstatfs *buf)
{
struct super_block *sb = dentry->d_sb;
struct cifs_sb_info *cifs_sb = CIFS_SB(sb);
struct cifs_tcon *tcon = cifs_sb_master_tcon(cifs_sb);
int rc = -EOPNOTSUPP;
int xid;
xid = GetXid();
buf->f_type = CIFS_MAGIC_NUMBER;
/*
* PATH_MAX may be too long - it would presumably be total path,
* but note that some servers (includinng Samba 3) have a shorter
* maximum path.
*
* Instead could get the real value via SMB_QUERY_FS_ATTRIBUTE_INFO.
*/
buf->f_namelen = PATH_MAX;
buf->f_files = 0; /* undefined */
buf->f_ffree = 0; /* unlimited */
/*
* We could add a second check for a QFS Unix capability bit
*/
if ((tcon->ses->capabilities & CAP_UNIX) &&
(CIFS_POSIX_EXTENSIONS & le64_to_cpu(tcon->fsUnixInfo.Capability)))
rc = CIFSSMBQFSPosixInfo(xid, tcon, buf);
/*
* Only need to call the old QFSInfo if failed on newer one,
* e.g. by OS/2.
**/
if (rc && (tcon->ses->capabilities & CAP_NT_SMBS))
rc = CIFSSMBQFSInfo(xid, tcon, buf);
/*
* Some old Windows servers also do not support level 103, retry with
* older level one if old server failed the previous call or we
* bypassed it because we detected that this was an older LANMAN sess
*/
if (rc)
rc = SMBOldQFSInfo(xid, tcon, buf);
FreeXid(xid);
return 0;
}
static int cifs_permission(struct inode *inode, int mask, unsigned int flags)
{
struct cifs_sb_info *cifs_sb;
cifs_sb = CIFS_SB(inode->i_sb);
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_PERM) {
if ((mask & MAY_EXEC) && !execute_ok(inode))
return -EACCES;
else
return 0;
} else /* file mode might have been restricted at mount time
on the client (above and beyond ACL on servers) for
servers which do not support setting and viewing mode bits,
so allowing client to check permissions is useful */
return generic_permission(inode, mask, flags, NULL);
}
static struct kmem_cache *cifs_inode_cachep;
static struct kmem_cache *cifs_req_cachep;
static struct kmem_cache *cifs_mid_cachep;
static struct kmem_cache *cifs_sm_req_cachep;
mempool_t *cifs_sm_req_poolp;
mempool_t *cifs_req_poolp;
mempool_t *cifs_mid_poolp;
static struct inode *
cifs_alloc_inode(struct super_block *sb)
{
struct cifsInodeInfo *cifs_inode;
cifs_inode = kmem_cache_alloc(cifs_inode_cachep, GFP_KERNEL);
if (!cifs_inode)
return NULL;
cifs_inode->cifsAttrs = 0x20; /* default */
cifs_inode->time = 0;
/* Until the file is open and we have gotten oplock
info back from the server, can not assume caching of
file data or metadata */
cifs_set_oplock_level(cifs_inode, 0);
cifs_inode->delete_pending = false;
cifs_inode->invalid_mapping = false;
cifs_inode->vfs_inode.i_blkbits = 14; /* 2**14 = CIFS_MAX_MSGSIZE */
cifs_inode->server_eof = 0;
cifs_inode->uniqueid = 0;
cifs_inode->createtime = 0;
/* Can not set i_flags here - they get immediately overwritten
to zero by the VFS */
/* cifs_inode->vfs_inode.i_flags = S_NOATIME | S_NOCMTIME;*/
INIT_LIST_HEAD(&cifs_inode->openFileList);
return &cifs_inode->vfs_inode;
}
static void cifs_i_callback(struct rcu_head *head)
{
struct inode *inode = container_of(head, struct inode, i_rcu);
INIT_LIST_HEAD(&inode->i_dentry);
kmem_cache_free(cifs_inode_cachep, CIFS_I(inode));
}
static void
cifs_destroy_inode(struct inode *inode)
{
call_rcu(&inode->i_rcu, cifs_i_callback);
}
static void
cifs_evict_inode(struct inode *inode)
{
truncate_inode_pages(&inode->i_data, 0);
end_writeback(inode);
cifs_fscache_release_inode_cookie(inode);
}
static void
cifs_show_address(struct seq_file *s, struct TCP_Server_Info *server)
{
struct sockaddr_in *sa = (struct sockaddr_in *) &server->dstaddr;
struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *) &server->dstaddr;
seq_printf(s, ",addr=");
switch (server->dstaddr.ss_family) {
case AF_INET:
seq_printf(s, "%pI4", &sa->sin_addr.s_addr);
break;
case AF_INET6:
seq_printf(s, "%pI6", &sa6->sin6_addr.s6_addr);
if (sa6->sin6_scope_id)
seq_printf(s, "%%%u", sa6->sin6_scope_id);
break;
default:
seq_printf(s, "(unknown)");
}
}
static void
cifs_show_security(struct seq_file *s, struct TCP_Server_Info *server)
{
seq_printf(s, ",sec=");
switch (server->secType) {
case LANMAN:
seq_printf(s, "lanman");
break;
case NTLMv2:
seq_printf(s, "ntlmv2");
break;
case NTLM:
seq_printf(s, "ntlm");
break;
case Kerberos:
seq_printf(s, "krb5");
break;
case RawNTLMSSP:
seq_printf(s, "ntlmssp");
break;
default:
/* shouldn't ever happen */
seq_printf(s, "unknown");
break;
}
if (server->sec_mode & (SECMODE_SIGN_REQUIRED | SECMODE_SIGN_ENABLED))
seq_printf(s, "i");
}
/*
* cifs_show_options() is for displaying mount options in /proc/mounts.
* Not all settable options are displayed but most of the important
* ones are.
*/
static int
cifs_show_options(struct seq_file *s, struct vfsmount *m)
{
struct cifs_sb_info *cifs_sb = CIFS_SB(m->mnt_sb);
struct cifs_tcon *tcon = cifs_sb_master_tcon(cifs_sb);
struct sockaddr *srcaddr;
srcaddr = (struct sockaddr *)&tcon->ses->server->srcaddr;
cifs_show_security(s, tcon->ses->server);
seq_printf(s, ",unc=%s", tcon->treeName);
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MULTIUSER)
seq_printf(s, ",multiuser");
else if (tcon->ses->user_name)
seq_printf(s, ",username=%s", tcon->ses->user_name);
if (tcon->ses->domainName)
seq_printf(s, ",domain=%s", tcon->ses->domainName);
if (srcaddr->sa_family != AF_UNSPEC) {
struct sockaddr_in *saddr4;
struct sockaddr_in6 *saddr6;
saddr4 = (struct sockaddr_in *)srcaddr;
saddr6 = (struct sockaddr_in6 *)srcaddr;
if (srcaddr->sa_family == AF_INET6)
seq_printf(s, ",srcaddr=%pI6c",
&saddr6->sin6_addr);
else if (srcaddr->sa_family == AF_INET)
seq_printf(s, ",srcaddr=%pI4",
&saddr4->sin_addr.s_addr);
else
seq_printf(s, ",srcaddr=BAD-AF:%i",
(int)(srcaddr->sa_family));
}
seq_printf(s, ",uid=%d", cifs_sb->mnt_uid);
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_OVERR_UID)
seq_printf(s, ",forceuid");
else
seq_printf(s, ",noforceuid");
seq_printf(s, ",gid=%d", cifs_sb->mnt_gid);
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_OVERR_GID)
seq_printf(s, ",forcegid");
else
seq_printf(s, ",noforcegid");
cifs_show_address(s, tcon->ses->server);
if (!tcon->unix_ext)
seq_printf(s, ",file_mode=0%o,dir_mode=0%o",
cifs_sb->mnt_file_mode,
cifs_sb->mnt_dir_mode);
if (tcon->seal)
seq_printf(s, ",seal");
if (tcon->nocase)
seq_printf(s, ",nocase");
if (tcon->retry)
seq_printf(s, ",hard");
if (tcon->unix_ext)
seq_printf(s, ",unix");
else
seq_printf(s, ",nounix");
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_POSIX_PATHS)
seq_printf(s, ",posixpaths");
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_SET_UID)
seq_printf(s, ",setuids");
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_SERVER_INUM)
seq_printf(s, ",serverino");
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_RWPIDFORWARD)
seq_printf(s, ",rwpidforward");
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NOPOSIXBRL)
seq_printf(s, ",forcemand");
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_DIRECT_IO)
seq_printf(s, ",directio");
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_XATTR)
seq_printf(s, ",nouser_xattr");
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MAP_SPECIAL_CHR)
seq_printf(s, ",mapchars");
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_UNX_EMUL)
seq_printf(s, ",sfu");
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_NO_BRL)
seq_printf(s, ",nobrl");
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_CIFS_ACL)
seq_printf(s, ",cifsacl");
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_DYNPERM)
seq_printf(s, ",dynperm");
if (m->mnt_sb->s_flags & MS_POSIXACL)
seq_printf(s, ",acl");
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_MF_SYMLINKS)
seq_printf(s, ",mfsymlinks");
if (cifs_sb->mnt_cifs_flags & CIFS_MOUNT_FSCACHE)
seq_printf(s, ",fsc");
seq_printf(s, ",rsize=%d", cifs_sb->rsize);
seq_printf(s, ",wsize=%d", cifs_sb->wsize);
/* convert actimeo and display it in seconds */
seq_printf(s, ",actimeo=%lu", cifs_sb->actimeo / HZ);
return 0;
}
static void cifs_umount_begin(struct super_block *sb)
{
struct cifs_sb_info *cifs_sb = CIFS_SB(sb);
struct cifs_tcon *tcon;
if (cifs_sb == NULL)
return;
tcon = cifs_sb_master_tcon(cifs_sb);
spin_lock(&cifs_tcp_ses_lock);
if ((tcon->tc_count > 1) || (tcon->tidStatus == CifsExiting)) {
/* we have other mounts to same share or we have
already tried to force umount this and woken up
all waiting network requests, nothing to do */
spin_unlock(&cifs_tcp_ses_lock);
return;
} else if (tcon->tc_count == 1)
tcon->tidStatus = CifsExiting;
spin_unlock(&cifs_tcp_ses_lock);
/* cancel_brl_requests(tcon); */ /* BB mark all brl mids as exiting */
/* cancel_notify_requests(tcon); */
if (tcon->ses && tcon->ses->server) {
cFYI(1, "wake up tasks now - umount begin not complete");
wake_up_all(&tcon->ses->server->request_q);
wake_up_all(&tcon->ses->server->response_q);
msleep(1); /* yield */
/* we have to kick the requests once more */
wake_up_all(&tcon->ses->server->response_q);
msleep(1);
}
return;
}
#ifdef CONFIG_CIFS_STATS2
static int cifs_show_stats(struct seq_file *s, struct vfsmount *mnt)
{
/* BB FIXME */
return 0;
}
#endif
static int cifs_remount(struct super_block *sb, int *flags, char *data)
{
*flags |= MS_NODIRATIME;
return 0;
}
static int cifs_drop_inode(struct inode *inode)
{
struct cifs_sb_info *cifs_sb = CIFS_SB(inode->i_sb);
/* no serverino => unconditional eviction */
return !(cifs_sb->mnt_cifs_flags & CIFS_MOUNT_SERVER_INUM) ||
generic_drop_inode(inode);
}
static const struct super_operations cifs_super_ops = {
.statfs = cifs_statfs,
.alloc_inode = cifs_alloc_inode,
.destroy_inode = cifs_destroy_inode,
.drop_inode = cifs_drop_inode,
.evict_inode = cifs_evict_inode,
/* .delete_inode = cifs_delete_inode, */ /* Do not need above
function unless later we add lazy close of inodes or unless the
kernel forgets to call us with the same number of releases (closes)
as opens */
.show_options = cifs_show_options,
.umount_begin = cifs_umount_begin,
.remount_fs = cifs_remount,
#ifdef CONFIG_CIFS_STATS2
.show_stats = cifs_show_stats,
#endif
};
/*
* Get root dentry from superblock according to prefix path mount option.
* Return dentry with refcount + 1 on success and NULL otherwise.
*/
static struct dentry *
cifs_get_root(struct smb_vol *vol, struct super_block *sb)
{
struct dentry *dentry;
struct cifs_sb_info *cifs_sb = CIFS_SB(sb);
char *full_path = NULL;
char *s, *p;
char sep;
int xid;
full_path = cifs_build_path_to_root(vol, cifs_sb,
cifs_sb_master_tcon(cifs_sb));
if (full_path == NULL)
return ERR_PTR(-ENOMEM);
cFYI(1, "Get root dentry for %s", full_path);
xid = GetXid();
sep = CIFS_DIR_SEP(cifs_sb);
dentry = dget(sb->s_root);
p = s = full_path;
do {
struct inode *dir = dentry->d_inode;
struct dentry *child;
if (!dir) {
dput(dentry);
dentry = ERR_PTR(-ENOENT);
break;
}
/* skip separators */
while (*s == sep)
s++;
if (!*s)
break;
p = s++;
/* next separator */
while (*s && *s != sep)
s++;
mutex_lock(&dir->i_mutex);
child = lookup_one_len(p, dentry, s - p);
mutex_unlock(&dir->i_mutex);
dput(dentry);
dentry = child;
} while (!IS_ERR(dentry));
_FreeXid(xid);
kfree(full_path);
return dentry;
}
static int cifs_set_super(struct super_block *sb, void *data)
{
struct cifs_mnt_data *mnt_data = data;
sb->s_fs_info = mnt_data->cifs_sb;
return set_anon_super(sb, NULL);
}
static struct dentry *
cifs_do_mount(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data)
{
int rc;
struct super_block *sb;
struct cifs_sb_info *cifs_sb;
struct smb_vol *volume_info;
struct cifs_mnt_data mnt_data;
struct dentry *root;
cFYI(1, "Devname: %s flags: %d ", dev_name, flags);
volume_info = cifs_get_volume_info((char *)data, dev_name);
if (IS_ERR(volume_info))
return ERR_CAST(volume_info);
cifs_sb = kzalloc(sizeof(struct cifs_sb_info), GFP_KERNEL);
if (cifs_sb == NULL) {
root = ERR_PTR(-ENOMEM);
goto out_nls;
}
cifs_sb->mountdata = kstrndup(data, PAGE_SIZE, GFP_KERNEL);
if (cifs_sb->mountdata == NULL) {
root = ERR_PTR(-ENOMEM);
goto out_cifs_sb;
}
cifs_setup_cifs_sb(volume_info, cifs_sb);
rc = cifs_mount(cifs_sb, volume_info);
if (rc) {
if (!(flags & MS_SILENT))
cERROR(1, "cifs_mount failed w/return code = %d", rc);
root = ERR_PTR(rc);
goto out_mountdata;
}
mnt_data.vol = volume_info;
mnt_data.cifs_sb = cifs_sb;
mnt_data.flags = flags;
sb = sget(fs_type, cifs_match_super, cifs_set_super, &mnt_data);
if (IS_ERR(sb)) {
root = ERR_CAST(sb);
cifs_umount(cifs_sb);
goto out;
}
if (sb->s_root) {
cFYI(1, "Use existing superblock");
cifs_umount(cifs_sb);
} else {
sb->s_flags = flags;
/* BB should we make this contingent on mount parm? */
sb->s_flags |= MS_NODIRATIME | MS_NOATIME;
rc = cifs_read_super(sb);
if (rc) {
root = ERR_PTR(rc);
goto out_super;
}
sb->s_flags |= MS_ACTIVE;
}
root = cifs_get_root(volume_info, sb);
if (IS_ERR(root))
goto out_super;
cFYI(1, "dentry root is: %p", root);
goto out;
out_super:
deactivate_locked_super(sb);
out:
cifs_cleanup_volume_info(volume_info);
return root;
out_mountdata:
kfree(cifs_sb->mountdata);
out_cifs_sb:
kfree(cifs_sb);
out_nls:
unload_nls(volume_info->local_nls);
goto out;
}
static ssize_t cifs_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
unsigned long nr_segs, loff_t pos)
{
struct inode *inode = iocb->ki_filp->f_path.dentry->d_inode;
ssize_t written;
int rc;
written = generic_file_aio_write(iocb, iov, nr_segs, pos);
if (CIFS_I(inode)->clientCanCacheAll)
return written;
rc = filemap_fdatawrite(inode->i_mapping);
if (rc)
cFYI(1, "cifs_file_aio_write: %d rc on %p inode", rc, inode);
return written;
}
static loff_t cifs_llseek(struct file *file, loff_t offset, int origin)
{
/* origin == SEEK_END => we must revalidate the cached file length */
if (origin == SEEK_END) {
int rc;
struct inode *inode = file->f_path.dentry->d_inode;
/*
* We need to be sure that all dirty pages are written and the
* server has the newest file length.
*/
if (!CIFS_I(inode)->clientCanCacheRead && inode->i_mapping &&
inode->i_mapping->nrpages != 0) {
rc = filemap_fdatawait(inode->i_mapping);
if (rc) {
mapping_set_error(inode->i_mapping, rc);
return rc;
}
}
/*
* Some applications poll for the file length in this strange
* way so we must seek to end on non-oplocked files by
* setting the revalidate time to zero.
*/
CIFS_I(inode)->time = 0;
rc = cifs_revalidate_file_attr(file);
if (rc < 0)
return (loff_t)rc;
}
return generic_file_llseek_unlocked(file, offset, origin);
}
static int cifs_setlease(struct file *file, long arg, struct file_lock **lease)
{
/* note that this is called by vfs setlease with lock_flocks held
to protect *lease from going away */
struct inode *inode = file->f_path.dentry->d_inode;
struct cifsFileInfo *cfile = file->private_data;
if (!(S_ISREG(inode->i_mode)))
return -EINVAL;
/* check if file is oplocked */
if (((arg == F_RDLCK) &&
(CIFS_I(inode)->clientCanCacheRead)) ||
((arg == F_WRLCK) &&
(CIFS_I(inode)->clientCanCacheAll)))
return generic_setlease(file, arg, lease);
else if (tlink_tcon(cfile->tlink)->local_lease &&
!CIFS_I(inode)->clientCanCacheRead)
/* If the server claims to support oplock on this
file, then we still need to check oplock even
if the local_lease mount option is set, but there
are servers which do not support oplock for which
this mount option may be useful if the user
knows that the file won't be changed on the server
by anyone else */
return generic_setlease(file, arg, lease);
else
return -EAGAIN;
}
struct file_system_type cifs_fs_type = {
.owner = THIS_MODULE,
.name = "cifs",
.mount = cifs_do_mount,
.kill_sb = cifs_kill_sb,
/* .fs_flags */
};
const struct inode_operations cifs_dir_inode_ops = {
.create = cifs_create,
.lookup = cifs_lookup,
.getattr = cifs_getattr,
.unlink = cifs_unlink,
.link = cifs_hardlink,
.mkdir = cifs_mkdir,
.rmdir = cifs_rmdir,
.rename = cifs_rename,
.permission = cifs_permission,
/* revalidate:cifs_revalidate, */
.setattr = cifs_setattr,
.symlink = cifs_symlink,
.mknod = cifs_mknod,
#ifdef CONFIG_CIFS_XATTR
.setxattr = cifs_setxattr,
.getxattr = cifs_getxattr,
.listxattr = cifs_listxattr,
.removexattr = cifs_removexattr,
#endif
};
const struct inode_operations cifs_file_inode_ops = {
/* revalidate:cifs_revalidate, */
.setattr = cifs_setattr,
.getattr = cifs_getattr, /* do we need this anymore? */
.rename = cifs_rename,
.permission = cifs_permission,
#ifdef CONFIG_CIFS_XATTR
.setxattr = cifs_setxattr,
.getxattr = cifs_getxattr,
.listxattr = cifs_listxattr,
.removexattr = cifs_removexattr,
#endif
};
const struct inode_operations cifs_symlink_inode_ops = {
.readlink = generic_readlink,
.follow_link = cifs_follow_link,
.put_link = cifs_put_link,
.permission = cifs_permission,
/* BB add the following two eventually */
/* revalidate: cifs_revalidate,
setattr: cifs_notify_change, *//* BB do we need notify change */
#ifdef CONFIG_CIFS_XATTR
.setxattr = cifs_setxattr,
.getxattr = cifs_getxattr,
.listxattr = cifs_listxattr,
.removexattr = cifs_removexattr,
#endif
};
const struct file_operations cifs_file_ops = {
.read = do_sync_read,
.write = do_sync_write,
.aio_read = generic_file_aio_read,
.aio_write = cifs_file_aio_write,
.open = cifs_open,
.release = cifs_close,
.lock = cifs_lock,
.fsync = cifs_fsync,
.flush = cifs_flush,
.mmap = cifs_file_mmap,
.splice_read = generic_file_splice_read,
.llseek = cifs_llseek,
#ifdef CONFIG_CIFS_POSIX
.unlocked_ioctl = cifs_ioctl,
#endif /* CONFIG_CIFS_POSIX */
.setlease = cifs_setlease,
};
const struct file_operations cifs_file_strict_ops = {
.read = do_sync_read,
.write = do_sync_write,
.aio_read = cifs_strict_readv,
.aio_write = cifs_strict_writev,
.open = cifs_open,
.release = cifs_close,
.lock = cifs_lock,
.fsync = cifs_strict_fsync,
.flush = cifs_flush,
.mmap = cifs_file_strict_mmap,
.splice_read = generic_file_splice_read,
.llseek = cifs_llseek,
#ifdef CONFIG_CIFS_POSIX
.unlocked_ioctl = cifs_ioctl,
#endif /* CONFIG_CIFS_POSIX */
.setlease = cifs_setlease,
};
const struct file_operations cifs_file_direct_ops = {
/* BB reevaluate whether they can be done with directio, no cache */
.read = do_sync_read,
.write = do_sync_write,
.aio_read = cifs_user_readv,
.aio_write = cifs_user_writev,
.open = cifs_open,
.release = cifs_close,
.lock = cifs_lock,
.fsync = cifs_fsync,
.flush = cifs_flush,
.mmap = cifs_file_mmap,
.splice_read = generic_file_splice_read,
#ifdef CONFIG_CIFS_POSIX
.unlocked_ioctl = cifs_ioctl,
#endif /* CONFIG_CIFS_POSIX */
.llseek = cifs_llseek,
.setlease = cifs_setlease,
};
const struct file_operations cifs_file_nobrl_ops = {
.read = do_sync_read,
.write = do_sync_write,
.aio_read = generic_file_aio_read,
.aio_write = cifs_file_aio_write,
.open = cifs_open,
.release = cifs_close,
.fsync = cifs_fsync,
.flush = cifs_flush,
.mmap = cifs_file_mmap,
.splice_read = generic_file_splice_read,
.llseek = cifs_llseek,
#ifdef CONFIG_CIFS_POSIX
.unlocked_ioctl = cifs_ioctl,
#endif /* CONFIG_CIFS_POSIX */
.setlease = cifs_setlease,
};
const struct file_operations cifs_file_strict_nobrl_ops = {
.read = do_sync_read,
.write = do_sync_write,
.aio_read = cifs_strict_readv,
.aio_write = cifs_strict_writev,
.open = cifs_open,
.release = cifs_close,
.fsync = cifs_strict_fsync,
.flush = cifs_flush,
.mmap = cifs_file_strict_mmap,
.splice_read = generic_file_splice_read,
.llseek = cifs_llseek,
#ifdef CONFIG_CIFS_POSIX
.unlocked_ioctl = cifs_ioctl,
#endif /* CONFIG_CIFS_POSIX */
.setlease = cifs_setlease,
};
const struct file_operations cifs_file_direct_nobrl_ops = {
/* BB reevaluate whether they can be done with directio, no cache */
.read = do_sync_read,
.write = do_sync_write,
.aio_read = cifs_user_readv,
.aio_write = cifs_user_writev,
.open = cifs_open,
.release = cifs_close,
.fsync = cifs_fsync,
.flush = cifs_flush,
.mmap = cifs_file_mmap,
.splice_read = generic_file_splice_read,
#ifdef CONFIG_CIFS_POSIX
.unlocked_ioctl = cifs_ioctl,
#endif /* CONFIG_CIFS_POSIX */
.llseek = cifs_llseek,
.setlease = cifs_setlease,
};
const struct file_operations cifs_dir_ops = {
.readdir = cifs_readdir,
.release = cifs_closedir,
.read = generic_read_dir,
.unlocked_ioctl = cifs_ioctl,
.llseek = generic_file_llseek,
};
static void
cifs_init_once(void *inode)
{
struct cifsInodeInfo *cifsi = inode;
inode_init_once(&cifsi->vfs_inode);
INIT_LIST_HEAD(&cifsi->lockList);
}
static int
cifs_init_inodecache(void)
{
cifs_inode_cachep = kmem_cache_create("cifs_inode_cache",
sizeof(struct cifsInodeInfo),
0, (SLAB_RECLAIM_ACCOUNT|
SLAB_MEM_SPREAD),
cifs_init_once);
if (cifs_inode_cachep == NULL)
return -ENOMEM;
return 0;
}
static void
cifs_destroy_inodecache(void)
{
kmem_cache_destroy(cifs_inode_cachep);
}
static int
cifs_init_request_bufs(void)
{
if (CIFSMaxBufSize < 8192) {
/* Buffer size can not be smaller than 2 * PATH_MAX since maximum
Unicode path name has to fit in any SMB/CIFS path based frames */
CIFSMaxBufSize = 8192;
} else if (CIFSMaxBufSize > 1024*127) {
CIFSMaxBufSize = 1024 * 127;
} else {
CIFSMaxBufSize &= 0x1FE00; /* Round size to even 512 byte mult*/
}
/* cERROR(1, "CIFSMaxBufSize %d 0x%x",CIFSMaxBufSize,CIFSMaxBufSize); */
cifs_req_cachep = kmem_cache_create("cifs_request",
CIFSMaxBufSize +
MAX_CIFS_HDR_SIZE, 0,
SLAB_HWCACHE_ALIGN, NULL);
if (cifs_req_cachep == NULL)
return -ENOMEM;
if (cifs_min_rcv < 1)
cifs_min_rcv = 1;
else if (cifs_min_rcv > 64) {
cifs_min_rcv = 64;
cERROR(1, "cifs_min_rcv set to maximum (64)");
}
cifs_req_poolp = mempool_create_slab_pool(cifs_min_rcv,
cifs_req_cachep);
if (cifs_req_poolp == NULL) {
kmem_cache_destroy(cifs_req_cachep);
return -ENOMEM;
}
/* MAX_CIFS_SMALL_BUFFER_SIZE bytes is enough for most SMB responses and
almost all handle based requests (but not write response, nor is it
sufficient for path based requests). A smaller size would have
been more efficient (compacting multiple slab items on one 4k page)
for the case in which debug was on, but this larger size allows
more SMBs to use small buffer alloc and is still much more
efficient to alloc 1 per page off the slab compared to 17K (5page)
alloc of large cifs buffers even when page debugging is on */
cifs_sm_req_cachep = kmem_cache_create("cifs_small_rq",
MAX_CIFS_SMALL_BUFFER_SIZE, 0, SLAB_HWCACHE_ALIGN,
NULL);
if (cifs_sm_req_cachep == NULL) {
mempool_destroy(cifs_req_poolp);
kmem_cache_destroy(cifs_req_cachep);
return -ENOMEM;
}
if (cifs_min_small < 2)
cifs_min_small = 2;
else if (cifs_min_small > 256) {
cifs_min_small = 256;
cFYI(1, "cifs_min_small set to maximum (256)");
}
cifs_sm_req_poolp = mempool_create_slab_pool(cifs_min_small,
cifs_sm_req_cachep);
if (cifs_sm_req_poolp == NULL) {
mempool_destroy(cifs_req_poolp);
kmem_cache_destroy(cifs_req_cachep);
kmem_cache_destroy(cifs_sm_req_cachep);
return -ENOMEM;
}
return 0;
}
static void
cifs_destroy_request_bufs(void)
{
mempool_destroy(cifs_req_poolp);
kmem_cache_destroy(cifs_req_cachep);
mempool_destroy(cifs_sm_req_poolp);
kmem_cache_destroy(cifs_sm_req_cachep);
}
static int
cifs_init_mids(void)
{
cifs_mid_cachep = kmem_cache_create("cifs_mpx_ids",
sizeof(struct mid_q_entry), 0,
SLAB_HWCACHE_ALIGN, NULL);
if (cifs_mid_cachep == NULL)
return -ENOMEM;
/* 3 is a reasonable minimum number of simultaneous operations */
cifs_mid_poolp = mempool_create_slab_pool(3, cifs_mid_cachep);
if (cifs_mid_poolp == NULL) {
kmem_cache_destroy(cifs_mid_cachep);
return -ENOMEM;
}
return 0;
}
static void
cifs_destroy_mids(void)
{
mempool_destroy(cifs_mid_poolp);
kmem_cache_destroy(cifs_mid_cachep);
}
static int __init
init_cifs(void)
{
int rc = 0;
cifs_proc_init();
INIT_LIST_HEAD(&cifs_tcp_ses_list);
#ifdef CONFIG_CIFS_DNOTIFY_EXPERIMENTAL /* unused temporarily */
INIT_LIST_HEAD(&GlobalDnotifyReqList);
INIT_LIST_HEAD(&GlobalDnotifyRsp_Q);
#endif /* was needed for dnotify, and will be needed for inotify when VFS fix */
/*
* Initialize Global counters
*/
atomic_set(&sesInfoAllocCount, 0);
atomic_set(&tconInfoAllocCount, 0);
atomic_set(&tcpSesAllocCount, 0);
atomic_set(&tcpSesReconnectCount, 0);
atomic_set(&tconInfoReconnectCount, 0);
atomic_set(&bufAllocCount, 0);
atomic_set(&smBufAllocCount, 0);
#ifdef CONFIG_CIFS_STATS2
atomic_set(&totBufAllocCount, 0);
atomic_set(&totSmBufAllocCount, 0);
#endif /* CONFIG_CIFS_STATS2 */
atomic_set(&midCount, 0);
GlobalCurrentXid = 0;
GlobalTotalActiveXid = 0;
GlobalMaxActiveXid = 0;
spin_lock_init(&cifs_tcp_ses_lock);
spin_lock_init(&cifs_file_list_lock);
spin_lock_init(&GlobalMid_Lock);
if (cifs_max_pending < 2) {
cifs_max_pending = 2;
cFYI(1, "cifs_max_pending set to min of 2");
} else if (cifs_max_pending > 256) {
cifs_max_pending = 256;
cFYI(1, "cifs_max_pending set to max of 256");
}
rc = cifs_fscache_register();
if (rc)
goto out_clean_proc;
rc = cifs_init_inodecache();
if (rc)
goto out_unreg_fscache;
rc = cifs_init_mids();
if (rc)
goto out_destroy_inodecache;
rc = cifs_init_request_bufs();
if (rc)
goto out_destroy_mids;
#ifdef CONFIG_CIFS_UPCALL
rc = register_key_type(&cifs_spnego_key_type);
if (rc)
goto out_destroy_request_bufs;
#endif /* CONFIG_CIFS_UPCALL */
#ifdef CONFIG_CIFS_ACL
rc = init_cifs_idmap();
if (rc)
goto out_register_key_type;
#endif /* CONFIG_CIFS_ACL */
rc = register_filesystem(&cifs_fs_type);
if (rc)
goto out_init_cifs_idmap;
return 0;
out_init_cifs_idmap:
#ifdef CONFIG_CIFS_ACL
exit_cifs_idmap();
out_register_key_type:
#endif
#ifdef CONFIG_CIFS_UPCALL
unregister_key_type(&cifs_spnego_key_type);
out_destroy_request_bufs:
#endif
cifs_destroy_request_bufs();
out_destroy_mids:
cifs_destroy_mids();
out_destroy_inodecache:
cifs_destroy_inodecache();
out_unreg_fscache:
cifs_fscache_unregister();
out_clean_proc:
cifs_proc_clean();
return rc;
}
static void __exit
exit_cifs(void)
{
cFYI(DBG2, "exit_cifs");
cifs_proc_clean();
cifs_fscache_unregister();
#ifdef CONFIG_CIFS_DFS_UPCALL
cifs_dfs_release_automount_timer();
#endif
#ifdef CONFIG_CIFS_ACL
cifs_destroy_idmaptrees();
exit_cifs_idmap();
#endif
#ifdef CONFIG_CIFS_UPCALL
unregister_key_type(&cifs_spnego_key_type);
#endif
unregister_filesystem(&cifs_fs_type);
cifs_destroy_inodecache();
cifs_destroy_mids();
cifs_destroy_request_bufs();
}
MODULE_AUTHOR("Steve French <sfrench@us.ibm.com>");
MODULE_LICENSE("GPL"); /* combination of LGPL + GPL source behaves as GPL */
MODULE_DESCRIPTION
("VFS to access servers complying with the SNIA CIFS Specification "
"e.g. Samba and Windows");
MODULE_VERSION(CIFS_VERSION);
module_init(init_cifs)
module_exit(exit_cifs)
| gpl-2.0 |
The-Demon12/msm8916 | drivers/iio/magnetometer/hid-sensor-magn-3d.c | 2141 | 11358 | /*
* HID Sensors Driver
* Copyright (c) 2012, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/slab.h>
#include <linux/hid-sensor-hub.h>
#include <linux/iio/iio.h>
#include <linux/iio/sysfs.h>
#include <linux/iio/buffer.h>
#include <linux/iio/trigger_consumer.h>
#include <linux/iio/triggered_buffer.h>
#include "../common/hid-sensors/hid-sensor-trigger.h"
/*Format: HID-SENSOR-usage_id_in_hex*/
/*Usage ID from spec for Magnetometer-3D: 0x200083*/
#define DRIVER_NAME "HID-SENSOR-200083"
enum magn_3d_channel {
CHANNEL_SCAN_INDEX_X,
CHANNEL_SCAN_INDEX_Y,
CHANNEL_SCAN_INDEX_Z,
MAGN_3D_CHANNEL_MAX,
};
struct magn_3d_state {
struct hid_sensor_hub_callbacks callbacks;
struct hid_sensor_common common_attributes;
struct hid_sensor_hub_attribute_info magn[MAGN_3D_CHANNEL_MAX];
u32 magn_val[MAGN_3D_CHANNEL_MAX];
};
static const u32 magn_3d_addresses[MAGN_3D_CHANNEL_MAX] = {
HID_USAGE_SENSOR_ORIENT_MAGN_FLUX_X_AXIS,
HID_USAGE_SENSOR_ORIENT_MAGN_FLUX_Y_AXIS,
HID_USAGE_SENSOR_ORIENT_MAGN_FLUX_Z_AXIS
};
/* Channel definitions */
static const struct iio_chan_spec magn_3d_channels[] = {
{
.type = IIO_MAGN,
.modified = 1,
.channel2 = IIO_MOD_X,
.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_OFFSET) |
BIT(IIO_CHAN_INFO_SCALE) |
BIT(IIO_CHAN_INFO_SAMP_FREQ) |
BIT(IIO_CHAN_INFO_HYSTERESIS),
.scan_index = CHANNEL_SCAN_INDEX_X,
}, {
.type = IIO_MAGN,
.modified = 1,
.channel2 = IIO_MOD_Y,
.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_OFFSET) |
BIT(IIO_CHAN_INFO_SCALE) |
BIT(IIO_CHAN_INFO_SAMP_FREQ) |
BIT(IIO_CHAN_INFO_HYSTERESIS),
.scan_index = CHANNEL_SCAN_INDEX_Y,
}, {
.type = IIO_MAGN,
.modified = 1,
.channel2 = IIO_MOD_Z,
.info_mask_shared_by_type = BIT(IIO_CHAN_INFO_OFFSET) |
BIT(IIO_CHAN_INFO_SCALE) |
BIT(IIO_CHAN_INFO_SAMP_FREQ) |
BIT(IIO_CHAN_INFO_HYSTERESIS),
.scan_index = CHANNEL_SCAN_INDEX_Z,
}
};
/* Adjust channel real bits based on report descriptor */
static void magn_3d_adjust_channel_bit_mask(struct iio_chan_spec *channels,
int channel, int size)
{
channels[channel].scan_type.sign = 's';
/* Real storage bits will change based on the report desc. */
channels[channel].scan_type.realbits = size * 8;
/* Maximum size of a sample to capture is u32 */
channels[channel].scan_type.storagebits = sizeof(u32) * 8;
}
/* Channel read_raw handler */
static int magn_3d_read_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int *val, int *val2,
long mask)
{
struct magn_3d_state *magn_state = iio_priv(indio_dev);
int report_id = -1;
u32 address;
int ret;
int ret_type;
*val = 0;
*val2 = 0;
switch (mask) {
case 0:
report_id =
magn_state->magn[chan->scan_index].report_id;
address = magn_3d_addresses[chan->scan_index];
if (report_id >= 0)
*val = sensor_hub_input_attr_get_raw_value(
magn_state->common_attributes.hsdev,
HID_USAGE_SENSOR_COMPASS_3D, address,
report_id);
else {
*val = 0;
return -EINVAL;
}
ret_type = IIO_VAL_INT;
break;
case IIO_CHAN_INFO_SCALE:
*val = magn_state->magn[CHANNEL_SCAN_INDEX_X].units;
ret_type = IIO_VAL_INT;
break;
case IIO_CHAN_INFO_OFFSET:
*val = hid_sensor_convert_exponent(
magn_state->magn[CHANNEL_SCAN_INDEX_X].unit_expo);
ret_type = IIO_VAL_INT;
break;
case IIO_CHAN_INFO_SAMP_FREQ:
ret = hid_sensor_read_samp_freq_value(
&magn_state->common_attributes, val, val2);
ret_type = IIO_VAL_INT_PLUS_MICRO;
break;
case IIO_CHAN_INFO_HYSTERESIS:
ret = hid_sensor_read_raw_hyst_value(
&magn_state->common_attributes, val, val2);
ret_type = IIO_VAL_INT_PLUS_MICRO;
break;
default:
ret_type = -EINVAL;
break;
}
return ret_type;
}
/* Channel write_raw handler */
static int magn_3d_write_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int val,
int val2,
long mask)
{
struct magn_3d_state *magn_state = iio_priv(indio_dev);
int ret = 0;
switch (mask) {
case IIO_CHAN_INFO_SAMP_FREQ:
ret = hid_sensor_write_samp_freq_value(
&magn_state->common_attributes, val, val2);
break;
case IIO_CHAN_INFO_HYSTERESIS:
ret = hid_sensor_write_raw_hyst_value(
&magn_state->common_attributes, val, val2);
break;
default:
ret = -EINVAL;
}
return ret;
}
static int magn_3d_write_raw_get_fmt(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
long mask)
{
return IIO_VAL_INT_PLUS_MICRO;
}
static const struct iio_info magn_3d_info = {
.driver_module = THIS_MODULE,
.read_raw = &magn_3d_read_raw,
.write_raw = &magn_3d_write_raw,
.write_raw_get_fmt = &magn_3d_write_raw_get_fmt,
};
/* Function to push data to buffer */
static void hid_sensor_push_data(struct iio_dev *indio_dev, u8 *data, int len)
{
dev_dbg(&indio_dev->dev, "hid_sensor_push_data\n");
iio_push_to_buffers(indio_dev, (u8 *)data);
}
/* Callback handler to send event after all samples are received and captured */
static int magn_3d_proc_event(struct hid_sensor_hub_device *hsdev,
unsigned usage_id,
void *priv)
{
struct iio_dev *indio_dev = platform_get_drvdata(priv);
struct magn_3d_state *magn_state = iio_priv(indio_dev);
dev_dbg(&indio_dev->dev, "magn_3d_proc_event [%d]\n",
magn_state->common_attributes.data_ready);
if (magn_state->common_attributes.data_ready)
hid_sensor_push_data(indio_dev,
(u8 *)magn_state->magn_val,
sizeof(magn_state->magn_val));
return 0;
}
/* Capture samples in local storage */
static int magn_3d_capture_sample(struct hid_sensor_hub_device *hsdev,
unsigned usage_id,
size_t raw_len, char *raw_data,
void *priv)
{
struct iio_dev *indio_dev = platform_get_drvdata(priv);
struct magn_3d_state *magn_state = iio_priv(indio_dev);
int offset;
int ret = -EINVAL;
switch (usage_id) {
case HID_USAGE_SENSOR_ORIENT_MAGN_FLUX_X_AXIS:
case HID_USAGE_SENSOR_ORIENT_MAGN_FLUX_Y_AXIS:
case HID_USAGE_SENSOR_ORIENT_MAGN_FLUX_Z_AXIS:
offset = usage_id - HID_USAGE_SENSOR_ORIENT_MAGN_FLUX_X_AXIS;
magn_state->magn_val[CHANNEL_SCAN_INDEX_X + offset] =
*(u32 *)raw_data;
ret = 0;
break;
default:
break;
}
return ret;
}
/* Parse report which is specific to an usage id*/
static int magn_3d_parse_report(struct platform_device *pdev,
struct hid_sensor_hub_device *hsdev,
struct iio_chan_spec *channels,
unsigned usage_id,
struct magn_3d_state *st)
{
int ret;
int i;
for (i = 0; i <= CHANNEL_SCAN_INDEX_Z; ++i) {
ret = sensor_hub_input_get_attribute_info(hsdev,
HID_INPUT_REPORT,
usage_id,
HID_USAGE_SENSOR_ORIENT_MAGN_FLUX_X_AXIS + i,
&st->magn[CHANNEL_SCAN_INDEX_X + i]);
if (ret < 0)
break;
magn_3d_adjust_channel_bit_mask(channels,
CHANNEL_SCAN_INDEX_X + i,
st->magn[CHANNEL_SCAN_INDEX_X + i].size);
}
dev_dbg(&pdev->dev, "magn_3d %x:%x, %x:%x, %x:%x\n",
st->magn[0].index,
st->magn[0].report_id,
st->magn[1].index, st->magn[1].report_id,
st->magn[2].index, st->magn[2].report_id);
return ret;
}
/* Function to initialize the processing for usage id */
static int hid_magn_3d_probe(struct platform_device *pdev)
{
int ret = 0;
static char *name = "magn_3d";
struct iio_dev *indio_dev;
struct magn_3d_state *magn_state;
struct hid_sensor_hub_device *hsdev = pdev->dev.platform_data;
struct iio_chan_spec *channels;
indio_dev = iio_device_alloc(sizeof(struct magn_3d_state));
if (indio_dev == NULL) {
ret = -ENOMEM;
goto error_ret;
}
platform_set_drvdata(pdev, indio_dev);
magn_state = iio_priv(indio_dev);
magn_state->common_attributes.hsdev = hsdev;
magn_state->common_attributes.pdev = pdev;
ret = hid_sensor_parse_common_attributes(hsdev,
HID_USAGE_SENSOR_COMPASS_3D,
&magn_state->common_attributes);
if (ret) {
dev_err(&pdev->dev, "failed to setup common attributes\n");
goto error_free_dev;
}
channels = kmemdup(magn_3d_channels, sizeof(magn_3d_channels),
GFP_KERNEL);
if (!channels) {
ret = -ENOMEM;
dev_err(&pdev->dev, "failed to duplicate channels\n");
goto error_free_dev;
}
ret = magn_3d_parse_report(pdev, hsdev, channels,
HID_USAGE_SENSOR_COMPASS_3D, magn_state);
if (ret) {
dev_err(&pdev->dev, "failed to setup attributes\n");
goto error_free_dev_mem;
}
indio_dev->channels = channels;
indio_dev->num_channels = ARRAY_SIZE(magn_3d_channels);
indio_dev->dev.parent = &pdev->dev;
indio_dev->info = &magn_3d_info;
indio_dev->name = name;
indio_dev->modes = INDIO_DIRECT_MODE;
ret = iio_triggered_buffer_setup(indio_dev, &iio_pollfunc_store_time,
NULL, NULL);
if (ret) {
dev_err(&pdev->dev, "failed to initialize trigger buffer\n");
goto error_free_dev_mem;
}
magn_state->common_attributes.data_ready = false;
ret = hid_sensor_setup_trigger(indio_dev, name,
&magn_state->common_attributes);
if (ret < 0) {
dev_err(&pdev->dev, "trigger setup failed\n");
goto error_unreg_buffer_funcs;
}
ret = iio_device_register(indio_dev);
if (ret) {
dev_err(&pdev->dev, "device register failed\n");
goto error_remove_trigger;
}
magn_state->callbacks.send_event = magn_3d_proc_event;
magn_state->callbacks.capture_sample = magn_3d_capture_sample;
magn_state->callbacks.pdev = pdev;
ret = sensor_hub_register_callback(hsdev, HID_USAGE_SENSOR_COMPASS_3D,
&magn_state->callbacks);
if (ret < 0) {
dev_err(&pdev->dev, "callback reg failed\n");
goto error_iio_unreg;
}
return ret;
error_iio_unreg:
iio_device_unregister(indio_dev);
error_remove_trigger:
hid_sensor_remove_trigger(indio_dev);
error_unreg_buffer_funcs:
iio_triggered_buffer_cleanup(indio_dev);
error_free_dev_mem:
kfree(indio_dev->channels);
error_free_dev:
iio_device_free(indio_dev);
error_ret:
return ret;
}
/* Function to deinitialize the processing for usage id */
static int hid_magn_3d_remove(struct platform_device *pdev)
{
struct hid_sensor_hub_device *hsdev = pdev->dev.platform_data;
struct iio_dev *indio_dev = platform_get_drvdata(pdev);
sensor_hub_remove_callback(hsdev, HID_USAGE_SENSOR_COMPASS_3D);
iio_device_unregister(indio_dev);
hid_sensor_remove_trigger(indio_dev);
iio_triggered_buffer_cleanup(indio_dev);
kfree(indio_dev->channels);
iio_device_free(indio_dev);
return 0;
}
static struct platform_driver hid_magn_3d_platform_driver = {
.driver = {
.name = DRIVER_NAME,
.owner = THIS_MODULE,
},
.probe = hid_magn_3d_probe,
.remove = hid_magn_3d_remove,
};
module_platform_driver(hid_magn_3d_platform_driver);
MODULE_DESCRIPTION("HID Sensor Magnetometer 3D");
MODULE_AUTHOR("Srinivas Pandruvada <srinivas.pandruvada@intel.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
crimsonthunder/TRLTE_AOSP_Kernel | arch/x86/kernel/kprobes/opt.c | 2141 | 14066 | /*
* Kernel Probes Jump Optimization (Optprobes)
*
* 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.
*
* Copyright (C) IBM Corporation, 2002, 2004
* Copyright (C) Hitachi Ltd., 2012
*/
#include <linux/kprobes.h>
#include <linux/ptrace.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/hardirq.h>
#include <linux/preempt.h>
#include <linux/module.h>
#include <linux/kdebug.h>
#include <linux/kallsyms.h>
#include <linux/ftrace.h>
#include <asm/cacheflush.h>
#include <asm/desc.h>
#include <asm/pgtable.h>
#include <asm/uaccess.h>
#include <asm/alternative.h>
#include <asm/insn.h>
#include <asm/debugreg.h>
#include "common.h"
unsigned long __recover_optprobed_insn(kprobe_opcode_t *buf, unsigned long addr)
{
struct optimized_kprobe *op;
struct kprobe *kp;
long offs;
int i;
for (i = 0; i < RELATIVEJUMP_SIZE; i++) {
kp = get_kprobe((void *)addr - i);
/* This function only handles jump-optimized kprobe */
if (kp && kprobe_optimized(kp)) {
op = container_of(kp, struct optimized_kprobe, kp);
/* If op->list is not empty, op is under optimizing */
if (list_empty(&op->list))
goto found;
}
}
return addr;
found:
/*
* If the kprobe can be optimized, original bytes which can be
* overwritten by jump destination address. In this case, original
* bytes must be recovered from op->optinsn.copied_insn buffer.
*/
memcpy(buf, (void *)addr, MAX_INSN_SIZE * sizeof(kprobe_opcode_t));
if (addr == (unsigned long)kp->addr) {
buf[0] = kp->opcode;
memcpy(buf + 1, op->optinsn.copied_insn, RELATIVE_ADDR_SIZE);
} else {
offs = addr - (unsigned long)kp->addr - 1;
memcpy(buf, op->optinsn.copied_insn + offs, RELATIVE_ADDR_SIZE - offs);
}
return (unsigned long)buf;
}
/* Insert a move instruction which sets a pointer to eax/rdi (1st arg). */
static void __kprobes synthesize_set_arg1(kprobe_opcode_t *addr, unsigned long val)
{
#ifdef CONFIG_X86_64
*addr++ = 0x48;
*addr++ = 0xbf;
#else
*addr++ = 0xb8;
#endif
*(unsigned long *)addr = val;
}
static void __used __kprobes kprobes_optinsn_template_holder(void)
{
asm volatile (
".global optprobe_template_entry\n"
"optprobe_template_entry:\n"
#ifdef CONFIG_X86_64
/* We don't bother saving the ss register */
" pushq %rsp\n"
" pushfq\n"
SAVE_REGS_STRING
" movq %rsp, %rsi\n"
".global optprobe_template_val\n"
"optprobe_template_val:\n"
ASM_NOP5
ASM_NOP5
".global optprobe_template_call\n"
"optprobe_template_call:\n"
ASM_NOP5
/* Move flags to rsp */
" movq 144(%rsp), %rdx\n"
" movq %rdx, 152(%rsp)\n"
RESTORE_REGS_STRING
/* Skip flags entry */
" addq $8, %rsp\n"
" popfq\n"
#else /* CONFIG_X86_32 */
" pushf\n"
SAVE_REGS_STRING
" movl %esp, %edx\n"
".global optprobe_template_val\n"
"optprobe_template_val:\n"
ASM_NOP5
".global optprobe_template_call\n"
"optprobe_template_call:\n"
ASM_NOP5
RESTORE_REGS_STRING
" addl $4, %esp\n" /* skip cs */
" popf\n"
#endif
".global optprobe_template_end\n"
"optprobe_template_end:\n");
}
#define TMPL_MOVE_IDX \
((long)&optprobe_template_val - (long)&optprobe_template_entry)
#define TMPL_CALL_IDX \
((long)&optprobe_template_call - (long)&optprobe_template_entry)
#define TMPL_END_IDX \
((long)&optprobe_template_end - (long)&optprobe_template_entry)
#define INT3_SIZE sizeof(kprobe_opcode_t)
/* Optimized kprobe call back function: called from optinsn */
static void __kprobes optimized_callback(struct optimized_kprobe *op, struct pt_regs *regs)
{
struct kprobe_ctlblk *kcb = get_kprobe_ctlblk();
unsigned long flags;
/* This is possible if op is under delayed unoptimizing */
if (kprobe_disabled(&op->kp))
return;
local_irq_save(flags);
if (kprobe_running()) {
kprobes_inc_nmissed_count(&op->kp);
} else {
/* Save skipped registers */
#ifdef CONFIG_X86_64
regs->cs = __KERNEL_CS;
#else
regs->cs = __KERNEL_CS | get_kernel_rpl();
regs->gs = 0;
#endif
regs->ip = (unsigned long)op->kp.addr + INT3_SIZE;
regs->orig_ax = ~0UL;
__this_cpu_write(current_kprobe, &op->kp);
kcb->kprobe_status = KPROBE_HIT_ACTIVE;
opt_pre_handler(&op->kp, regs);
__this_cpu_write(current_kprobe, NULL);
}
local_irq_restore(flags);
}
static int __kprobes copy_optimized_instructions(u8 *dest, u8 *src)
{
int len = 0, ret;
while (len < RELATIVEJUMP_SIZE) {
ret = __copy_instruction(dest + len, src + len);
if (!ret || !can_boost(dest + len))
return -EINVAL;
len += ret;
}
/* Check whether the address range is reserved */
if (ftrace_text_reserved(src, src + len - 1) ||
alternatives_text_reserved(src, src + len - 1) ||
jump_label_text_reserved(src, src + len - 1))
return -EBUSY;
return len;
}
/* Check whether insn is indirect jump */
static int __kprobes insn_is_indirect_jump(struct insn *insn)
{
return ((insn->opcode.bytes[0] == 0xff &&
(X86_MODRM_REG(insn->modrm.value) & 6) == 4) || /* Jump */
insn->opcode.bytes[0] == 0xea); /* Segment based jump */
}
/* Check whether insn jumps into specified address range */
static int insn_jump_into_range(struct insn *insn, unsigned long start, int len)
{
unsigned long target = 0;
switch (insn->opcode.bytes[0]) {
case 0xe0: /* loopne */
case 0xe1: /* loope */
case 0xe2: /* loop */
case 0xe3: /* jcxz */
case 0xe9: /* near relative jump */
case 0xeb: /* short relative jump */
break;
case 0x0f:
if ((insn->opcode.bytes[1] & 0xf0) == 0x80) /* jcc near */
break;
return 0;
default:
if ((insn->opcode.bytes[0] & 0xf0) == 0x70) /* jcc short */
break;
return 0;
}
target = (unsigned long)insn->next_byte + insn->immediate.value;
return (start <= target && target <= start + len);
}
/* Decode whole function to ensure any instructions don't jump into target */
static int __kprobes can_optimize(unsigned long paddr)
{
unsigned long addr, size = 0, offset = 0;
struct insn insn;
kprobe_opcode_t buf[MAX_INSN_SIZE];
/* Lookup symbol including addr */
if (!kallsyms_lookup_size_offset(paddr, &size, &offset))
return 0;
/*
* Do not optimize in the entry code due to the unstable
* stack handling.
*/
if ((paddr >= (unsigned long)__entry_text_start) &&
(paddr < (unsigned long)__entry_text_end))
return 0;
/* Check there is enough space for a relative jump. */
if (size - offset < RELATIVEJUMP_SIZE)
return 0;
/* Decode instructions */
addr = paddr - offset;
while (addr < paddr - offset + size) { /* Decode until function end */
if (search_exception_tables(addr))
/*
* Since some fixup code will jumps into this function,
* we can't optimize kprobe in this function.
*/
return 0;
kernel_insn_init(&insn, (void *)recover_probed_instruction(buf, addr));
insn_get_length(&insn);
/* Another subsystem puts a breakpoint */
if (insn.opcode.bytes[0] == BREAKPOINT_INSTRUCTION)
return 0;
/* Recover address */
insn.kaddr = (void *)addr;
insn.next_byte = (void *)(addr + insn.length);
/* Check any instructions don't jump into target */
if (insn_is_indirect_jump(&insn) ||
insn_jump_into_range(&insn, paddr + INT3_SIZE,
RELATIVE_ADDR_SIZE))
return 0;
addr += insn.length;
}
return 1;
}
/* Check optimized_kprobe can actually be optimized. */
int __kprobes arch_check_optimized_kprobe(struct optimized_kprobe *op)
{
int i;
struct kprobe *p;
for (i = 1; i < op->optinsn.size; i++) {
p = get_kprobe(op->kp.addr + i);
if (p && !kprobe_disabled(p))
return -EEXIST;
}
return 0;
}
/* Check the addr is within the optimized instructions. */
int __kprobes
arch_within_optimized_kprobe(struct optimized_kprobe *op, unsigned long addr)
{
return ((unsigned long)op->kp.addr <= addr &&
(unsigned long)op->kp.addr + op->optinsn.size > addr);
}
/* Free optimized instruction slot */
static __kprobes
void __arch_remove_optimized_kprobe(struct optimized_kprobe *op, int dirty)
{
if (op->optinsn.insn) {
free_optinsn_slot(op->optinsn.insn, dirty);
op->optinsn.insn = NULL;
op->optinsn.size = 0;
}
}
void __kprobes arch_remove_optimized_kprobe(struct optimized_kprobe *op)
{
__arch_remove_optimized_kprobe(op, 1);
}
/*
* Copy replacing target instructions
* Target instructions MUST be relocatable (checked inside)
* This is called when new aggr(opt)probe is allocated or reused.
*/
int __kprobes arch_prepare_optimized_kprobe(struct optimized_kprobe *op)
{
u8 *buf;
int ret;
long rel;
if (!can_optimize((unsigned long)op->kp.addr))
return -EILSEQ;
op->optinsn.insn = get_optinsn_slot();
if (!op->optinsn.insn)
return -ENOMEM;
/*
* Verify if the address gap is in 2GB range, because this uses
* a relative jump.
*/
rel = (long)op->optinsn.insn - (long)op->kp.addr + RELATIVEJUMP_SIZE;
if (abs(rel) > 0x7fffffff)
return -ERANGE;
buf = (u8 *)op->optinsn.insn;
/* Copy instructions into the out-of-line buffer */
ret = copy_optimized_instructions(buf + TMPL_END_IDX, op->kp.addr);
if (ret < 0) {
__arch_remove_optimized_kprobe(op, 0);
return ret;
}
op->optinsn.size = ret;
/* Copy arch-dep-instance from template */
memcpy(buf, &optprobe_template_entry, TMPL_END_IDX);
/* Set probe information */
synthesize_set_arg1(buf + TMPL_MOVE_IDX, (unsigned long)op);
/* Set probe function call */
synthesize_relcall(buf + TMPL_CALL_IDX, optimized_callback);
/* Set returning jmp instruction at the tail of out-of-line buffer */
synthesize_reljump(buf + TMPL_END_IDX + op->optinsn.size,
(u8 *)op->kp.addr + op->optinsn.size);
flush_icache_range((unsigned long) buf,
(unsigned long) buf + TMPL_END_IDX +
op->optinsn.size + RELATIVEJUMP_SIZE);
return 0;
}
#define MAX_OPTIMIZE_PROBES 256
static struct text_poke_param *jump_poke_params;
static struct jump_poke_buffer {
u8 buf[RELATIVEJUMP_SIZE];
} *jump_poke_bufs;
static void __kprobes setup_optimize_kprobe(struct text_poke_param *tprm,
u8 *insn_buf,
struct optimized_kprobe *op)
{
s32 rel = (s32)((long)op->optinsn.insn -
((long)op->kp.addr + RELATIVEJUMP_SIZE));
/* Backup instructions which will be replaced by jump address */
memcpy(op->optinsn.copied_insn, op->kp.addr + INT3_SIZE,
RELATIVE_ADDR_SIZE);
insn_buf[0] = RELATIVEJUMP_OPCODE;
*(s32 *)(&insn_buf[1]) = rel;
tprm->addr = op->kp.addr;
tprm->opcode = insn_buf;
tprm->len = RELATIVEJUMP_SIZE;
}
/*
* Replace breakpoints (int3) with relative jumps.
* Caller must call with locking kprobe_mutex and text_mutex.
*/
void __kprobes arch_optimize_kprobes(struct list_head *oplist)
{
struct optimized_kprobe *op, *tmp;
int c = 0;
list_for_each_entry_safe(op, tmp, oplist, list) {
WARN_ON(kprobe_disabled(&op->kp));
/* Setup param */
setup_optimize_kprobe(&jump_poke_params[c],
jump_poke_bufs[c].buf, op);
list_del_init(&op->list);
if (++c >= MAX_OPTIMIZE_PROBES)
break;
}
/*
* text_poke_smp doesn't support NMI/MCE code modifying.
* However, since kprobes itself also doesn't support NMI/MCE
* code probing, it's not a problem.
*/
text_poke_smp_batch(jump_poke_params, c);
}
static void __kprobes setup_unoptimize_kprobe(struct text_poke_param *tprm,
u8 *insn_buf,
struct optimized_kprobe *op)
{
/* Set int3 to first byte for kprobes */
insn_buf[0] = BREAKPOINT_INSTRUCTION;
memcpy(insn_buf + 1, op->optinsn.copied_insn, RELATIVE_ADDR_SIZE);
tprm->addr = op->kp.addr;
tprm->opcode = insn_buf;
tprm->len = RELATIVEJUMP_SIZE;
}
/*
* Recover original instructions and breakpoints from relative jumps.
* Caller must call with locking kprobe_mutex.
*/
extern void arch_unoptimize_kprobes(struct list_head *oplist,
struct list_head *done_list)
{
struct optimized_kprobe *op, *tmp;
int c = 0;
list_for_each_entry_safe(op, tmp, oplist, list) {
/* Setup param */
setup_unoptimize_kprobe(&jump_poke_params[c],
jump_poke_bufs[c].buf, op);
list_move(&op->list, done_list);
if (++c >= MAX_OPTIMIZE_PROBES)
break;
}
/*
* text_poke_smp doesn't support NMI/MCE code modifying.
* However, since kprobes itself also doesn't support NMI/MCE
* code probing, it's not a problem.
*/
text_poke_smp_batch(jump_poke_params, c);
}
/* Replace a relative jump with a breakpoint (int3). */
void __kprobes arch_unoptimize_kprobe(struct optimized_kprobe *op)
{
u8 buf[RELATIVEJUMP_SIZE];
/* Set int3 to first byte for kprobes */
buf[0] = BREAKPOINT_INSTRUCTION;
memcpy(buf + 1, op->optinsn.copied_insn, RELATIVE_ADDR_SIZE);
text_poke_smp(op->kp.addr, buf, RELATIVEJUMP_SIZE);
}
int __kprobes
setup_detour_execution(struct kprobe *p, struct pt_regs *regs, int reenter)
{
struct optimized_kprobe *op;
if (p->flags & KPROBE_FLAG_OPTIMIZED) {
/* This kprobe is really able to run optimized path. */
op = container_of(p, struct optimized_kprobe, kp);
/* Detour through copied instructions */
regs->ip = (unsigned long)op->optinsn.insn + TMPL_END_IDX;
if (!reenter)
reset_current_kprobe();
preempt_enable_no_resched();
return 1;
}
return 0;
}
int __kprobes arch_init_optprobes(void)
{
/* Allocate code buffer and parameter array */
jump_poke_bufs = kmalloc(sizeof(struct jump_poke_buffer) *
MAX_OPTIMIZE_PROBES, GFP_KERNEL);
if (!jump_poke_bufs)
return -ENOMEM;
jump_poke_params = kmalloc(sizeof(struct text_poke_param) *
MAX_OPTIMIZE_PROBES, GFP_KERNEL);
if (!jump_poke_params) {
kfree(jump_poke_bufs);
jump_poke_bufs = NULL;
return -ENOMEM;
}
return 0;
}
| gpl-2.0 |
abhishekr700/Z00L_cmkernel | drivers/input/keyboard/spear-keyboard.c | 2141 | 9683 | /*
* SPEAr Keyboard Driver
* Based on omap-keypad driver
*
* Copyright (C) 2010 ST Microelectronics
* Rajeev Kumar<rajeev-dlh.kumar@st.com>
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*/
#include <linux/clk.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/input.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <linux/pm_wakeup.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/platform_data/keyboard-spear.h>
/* Keyboard Registers */
#define MODE_CTL_REG 0x00
#define STATUS_REG 0x0C
#define DATA_REG 0x10
#define INTR_MASK 0x54
/* Register Values */
#define NUM_ROWS 16
#define NUM_COLS 16
#define MODE_CTL_PCLK_FREQ_SHIFT 9
#define MODE_CTL_PCLK_FREQ_MSK 0x7F
#define MODE_CTL_KEYBOARD (0x2 << 0)
#define MODE_CTL_SCAN_RATE_10 (0x0 << 2)
#define MODE_CTL_SCAN_RATE_20 (0x1 << 2)
#define MODE_CTL_SCAN_RATE_40 (0x2 << 2)
#define MODE_CTL_SCAN_RATE_80 (0x3 << 2)
#define MODE_CTL_KEYNUM_SHIFT 6
#define MODE_CTL_START_SCAN (0x1 << 8)
#define STATUS_DATA_AVAIL (0x1 << 1)
#define DATA_ROW_MASK 0xF0
#define DATA_COLUMN_MASK 0x0F
#define ROW_SHIFT 4
struct spear_kbd {
struct input_dev *input;
void __iomem *io_base;
struct clk *clk;
unsigned int irq;
unsigned int mode;
unsigned int suspended_rate;
unsigned short last_key;
unsigned short keycodes[NUM_ROWS * NUM_COLS];
bool rep;
bool irq_wake_enabled;
u32 mode_ctl_reg;
};
static irqreturn_t spear_kbd_interrupt(int irq, void *dev_id)
{
struct spear_kbd *kbd = dev_id;
struct input_dev *input = kbd->input;
unsigned int key;
u32 sts, val;
sts = readl_relaxed(kbd->io_base + STATUS_REG);
if (!(sts & STATUS_DATA_AVAIL))
return IRQ_NONE;
if (kbd->last_key != KEY_RESERVED) {
input_report_key(input, kbd->last_key, 0);
kbd->last_key = KEY_RESERVED;
}
/* following reads active (row, col) pair */
val = readl_relaxed(kbd->io_base + DATA_REG) &
(DATA_ROW_MASK | DATA_COLUMN_MASK);
key = kbd->keycodes[val];
input_event(input, EV_MSC, MSC_SCAN, val);
input_report_key(input, key, 1);
input_sync(input);
kbd->last_key = key;
/* clear interrupt */
writel_relaxed(0, kbd->io_base + STATUS_REG);
return IRQ_HANDLED;
}
static int spear_kbd_open(struct input_dev *dev)
{
struct spear_kbd *kbd = input_get_drvdata(dev);
int error;
u32 val;
kbd->last_key = KEY_RESERVED;
error = clk_enable(kbd->clk);
if (error)
return error;
/* keyboard rate to be programmed is input clock (in MHz) - 1 */
val = clk_get_rate(kbd->clk) / 1000000 - 1;
val = (val & MODE_CTL_PCLK_FREQ_MSK) << MODE_CTL_PCLK_FREQ_SHIFT;
/* program keyboard */
val = MODE_CTL_SCAN_RATE_80 | MODE_CTL_KEYBOARD | val |
(kbd->mode << MODE_CTL_KEYNUM_SHIFT);
writel_relaxed(val, kbd->io_base + MODE_CTL_REG);
writel_relaxed(1, kbd->io_base + STATUS_REG);
/* start key scan */
val = readl_relaxed(kbd->io_base + MODE_CTL_REG);
val |= MODE_CTL_START_SCAN;
writel_relaxed(val, kbd->io_base + MODE_CTL_REG);
return 0;
}
static void spear_kbd_close(struct input_dev *dev)
{
struct spear_kbd *kbd = input_get_drvdata(dev);
u32 val;
/* stop key scan */
val = readl_relaxed(kbd->io_base + MODE_CTL_REG);
val &= ~MODE_CTL_START_SCAN;
writel_relaxed(val, kbd->io_base + MODE_CTL_REG);
clk_disable(kbd->clk);
kbd->last_key = KEY_RESERVED;
}
#ifdef CONFIG_OF
static int spear_kbd_parse_dt(struct platform_device *pdev,
struct spear_kbd *kbd)
{
struct device_node *np = pdev->dev.of_node;
int error;
u32 val, suspended_rate;
if (!np) {
dev_err(&pdev->dev, "Missing DT data\n");
return -EINVAL;
}
if (of_property_read_bool(np, "autorepeat"))
kbd->rep = true;
if (of_property_read_u32(np, "suspended_rate", &suspended_rate))
kbd->suspended_rate = suspended_rate;
error = of_property_read_u32(np, "st,mode", &val);
if (error) {
dev_err(&pdev->dev, "DT: Invalid or missing mode\n");
return error;
}
kbd->mode = val;
return 0;
}
#else
static inline int spear_kbd_parse_dt(struct platform_device *pdev,
struct spear_kbd *kbd)
{
return -ENOSYS;
}
#endif
static int spear_kbd_probe(struct platform_device *pdev)
{
struct kbd_platform_data *pdata = dev_get_platdata(&pdev->dev);
const struct matrix_keymap_data *keymap = pdata ? pdata->keymap : NULL;
struct spear_kbd *kbd;
struct input_dev *input_dev;
struct resource *res;
int irq;
int error;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&pdev->dev, "no keyboard resource defined\n");
return -EBUSY;
}
irq = platform_get_irq(pdev, 0);
if (irq < 0) {
dev_err(&pdev->dev, "not able to get irq for the device\n");
return irq;
}
kbd = devm_kzalloc(&pdev->dev, sizeof(*kbd), GFP_KERNEL);
if (!kbd) {
dev_err(&pdev->dev, "not enough memory for driver data\n");
return -ENOMEM;
}
input_dev = devm_input_allocate_device(&pdev->dev);
if (!input_dev) {
dev_err(&pdev->dev, "unable to allocate input device\n");
return -ENOMEM;
}
kbd->input = input_dev;
kbd->irq = irq;
if (!pdata) {
error = spear_kbd_parse_dt(pdev, kbd);
if (error)
return error;
} else {
kbd->mode = pdata->mode;
kbd->rep = pdata->rep;
kbd->suspended_rate = pdata->suspended_rate;
}
kbd->io_base = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(kbd->io_base))
return PTR_ERR(kbd->io_base);
kbd->clk = devm_clk_get(&pdev->dev, NULL);
if (IS_ERR(kbd->clk))
return PTR_ERR(kbd->clk);
input_dev->name = "Spear Keyboard";
input_dev->phys = "keyboard/input0";
input_dev->id.bustype = BUS_HOST;
input_dev->id.vendor = 0x0001;
input_dev->id.product = 0x0001;
input_dev->id.version = 0x0100;
input_dev->open = spear_kbd_open;
input_dev->close = spear_kbd_close;
error = matrix_keypad_build_keymap(keymap, NULL, NUM_ROWS, NUM_COLS,
kbd->keycodes, input_dev);
if (error) {
dev_err(&pdev->dev, "Failed to build keymap\n");
return error;
}
if (kbd->rep)
__set_bit(EV_REP, input_dev->evbit);
input_set_capability(input_dev, EV_MSC, MSC_SCAN);
input_set_drvdata(input_dev, kbd);
error = devm_request_irq(&pdev->dev, irq, spear_kbd_interrupt, 0,
"keyboard", kbd);
if (error) {
dev_err(&pdev->dev, "request_irq failed\n");
return error;
}
error = clk_prepare(kbd->clk);
if (error)
return error;
error = input_register_device(input_dev);
if (error) {
dev_err(&pdev->dev, "Unable to register keyboard device\n");
clk_unprepare(kbd->clk);
return error;
}
device_init_wakeup(&pdev->dev, 1);
platform_set_drvdata(pdev, kbd);
return 0;
}
static int spear_kbd_remove(struct platform_device *pdev)
{
struct spear_kbd *kbd = platform_get_drvdata(pdev);
input_unregister_device(kbd->input);
clk_unprepare(kbd->clk);
device_init_wakeup(&pdev->dev, 0);
platform_set_drvdata(pdev, NULL);
return 0;
}
#ifdef CONFIG_PM
static int spear_kbd_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct spear_kbd *kbd = platform_get_drvdata(pdev);
struct input_dev *input_dev = kbd->input;
unsigned int rate = 0, mode_ctl_reg, val;
mutex_lock(&input_dev->mutex);
/* explicitly enable clock as we may program device */
clk_enable(kbd->clk);
mode_ctl_reg = readl_relaxed(kbd->io_base + MODE_CTL_REG);
if (device_may_wakeup(&pdev->dev)) {
if (!enable_irq_wake(kbd->irq))
kbd->irq_wake_enabled = true;
/*
* reprogram the keyboard operating frequency as on some
* platform it may change during system suspended
*/
if (kbd->suspended_rate)
rate = kbd->suspended_rate / 1000000 - 1;
else
rate = clk_get_rate(kbd->clk) / 1000000 - 1;
val = mode_ctl_reg &
~(MODE_CTL_PCLK_FREQ_MSK << MODE_CTL_PCLK_FREQ_SHIFT);
val |= (rate & MODE_CTL_PCLK_FREQ_MSK)
<< MODE_CTL_PCLK_FREQ_SHIFT;
writel_relaxed(val, kbd->io_base + MODE_CTL_REG);
} else {
if (input_dev->users) {
writel_relaxed(mode_ctl_reg & ~MODE_CTL_START_SCAN,
kbd->io_base + MODE_CTL_REG);
clk_disable(kbd->clk);
}
}
/* store current configuration */
if (input_dev->users)
kbd->mode_ctl_reg = mode_ctl_reg;
/* restore previous clk state */
clk_disable(kbd->clk);
mutex_unlock(&input_dev->mutex);
return 0;
}
static int spear_kbd_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct spear_kbd *kbd = platform_get_drvdata(pdev);
struct input_dev *input_dev = kbd->input;
mutex_lock(&input_dev->mutex);
if (device_may_wakeup(&pdev->dev)) {
if (kbd->irq_wake_enabled) {
kbd->irq_wake_enabled = false;
disable_irq_wake(kbd->irq);
}
} else {
if (input_dev->users)
clk_enable(kbd->clk);
}
/* restore current configuration */
if (input_dev->users)
writel_relaxed(kbd->mode_ctl_reg, kbd->io_base + MODE_CTL_REG);
mutex_unlock(&input_dev->mutex);
return 0;
}
#endif
static SIMPLE_DEV_PM_OPS(spear_kbd_pm_ops, spear_kbd_suspend, spear_kbd_resume);
#ifdef CONFIG_OF
static const struct of_device_id spear_kbd_id_table[] = {
{ .compatible = "st,spear300-kbd" },
{}
};
MODULE_DEVICE_TABLE(of, spear_kbd_id_table);
#endif
static struct platform_driver spear_kbd_driver = {
.probe = spear_kbd_probe,
.remove = spear_kbd_remove,
.driver = {
.name = "keyboard",
.owner = THIS_MODULE,
.pm = &spear_kbd_pm_ops,
.of_match_table = of_match_ptr(spear_kbd_id_table),
},
};
module_platform_driver(spear_kbd_driver);
MODULE_AUTHOR("Rajeev Kumar");
MODULE_DESCRIPTION("SPEAr Keyboard Driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
pseudonymous-foss/clydefs | drivers/usb/host/ehci-sead3.c | 2141 | 4301 | /*
* MIPS CI13320A EHCI Host Controller driver
* Based on "ehci-au1xxx.c" by K.Boge <karsten.boge@amd.com>
*
* Copyright (C) 2012 MIPS Technologies, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This 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/err.h>
#include <linux/platform_device.h>
static int ehci_sead3_setup(struct usb_hcd *hcd)
{
int ret;
struct ehci_hcd *ehci = hcd_to_ehci(hcd);
ehci->caps = hcd->regs + 0x100;
#ifdef __BIG_ENDIAN
ehci->big_endian_mmio = 1;
ehci->big_endian_desc = 1;
#endif
ret = ehci_setup(hcd);
if (ret)
return ret;
ehci->need_io_watchdog = 0;
/* Set burst length to 16 words. */
ehci_writel(ehci, 0x1010, &ehci->regs->reserved1[1]);
return ret;
}
const struct hc_driver ehci_sead3_hc_driver = {
.description = hcd_name,
.product_desc = "SEAD-3 EHCI",
.hcd_priv_size = sizeof(struct ehci_hcd),
/*
* generic hardware linkage
*/
.irq = ehci_irq,
.flags = HCD_MEMORY | HCD_USB2,
/*
* basic lifecycle operations
*
*/
.reset = ehci_sead3_setup,
.start = ehci_run,
.stop = ehci_stop,
.shutdown = ehci_shutdown,
/*
* managing i/o requests and associated device resources
*/
.urb_enqueue = ehci_urb_enqueue,
.urb_dequeue = ehci_urb_dequeue,
.endpoint_disable = ehci_endpoint_disable,
.endpoint_reset = ehci_endpoint_reset,
/*
* scheduling support
*/
.get_frame_number = ehci_get_frame,
/*
* root hub support
*/
.hub_status_data = ehci_hub_status_data,
.hub_control = ehci_hub_control,
.bus_suspend = ehci_bus_suspend,
.bus_resume = ehci_bus_resume,
.relinquish_port = ehci_relinquish_port,
.port_handed_over = ehci_port_handed_over,
.clear_tt_buffer_complete = ehci_clear_tt_buffer_complete,
};
static int ehci_hcd_sead3_drv_probe(struct platform_device *pdev)
{
struct usb_hcd *hcd;
struct resource *res;
int ret;
if (usb_disabled())
return -ENODEV;
if (pdev->resource[1].flags != IORESOURCE_IRQ) {
pr_debug("resource[1] is not IORESOURCE_IRQ");
return -ENOMEM;
}
hcd = usb_create_hcd(&ehci_sead3_hc_driver, &pdev->dev, "SEAD-3");
if (!hcd)
return -ENOMEM;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
hcd->rsrc_start = res->start;
hcd->rsrc_len = resource_size(res);
hcd->regs = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(hcd->regs)) {
ret = PTR_ERR(hcd->regs);
goto err1;
}
/* Root hub has integrated TT. */
hcd->has_tt = 1;
ret = usb_add_hcd(hcd, pdev->resource[1].start,
IRQF_SHARED);
if (ret == 0) {
platform_set_drvdata(pdev, hcd);
return ret;
}
err1:
usb_put_hcd(hcd);
return ret;
}
static int ehci_hcd_sead3_drv_remove(struct platform_device *pdev)
{
struct usb_hcd *hcd = platform_get_drvdata(pdev);
usb_remove_hcd(hcd);
usb_put_hcd(hcd);
platform_set_drvdata(pdev, NULL);
return 0;
}
#ifdef CONFIG_PM
static int ehci_hcd_sead3_drv_suspend(struct device *dev)
{
struct usb_hcd *hcd = dev_get_drvdata(dev);
bool do_wakeup = device_may_wakeup(dev);
return ehci_suspend(hcd, do_wakeup);
}
static int ehci_hcd_sead3_drv_resume(struct device *dev)
{
struct usb_hcd *hcd = dev_get_drvdata(dev);
ehci_resume(hcd, false);
return 0;
}
static const struct dev_pm_ops sead3_ehci_pmops = {
.suspend = ehci_hcd_sead3_drv_suspend,
.resume = ehci_hcd_sead3_drv_resume,
};
#define SEAD3_EHCI_PMOPS (&sead3_ehci_pmops)
#else
#define SEAD3_EHCI_PMOPS NULL
#endif
static struct platform_driver ehci_hcd_sead3_driver = {
.probe = ehci_hcd_sead3_drv_probe,
.remove = ehci_hcd_sead3_drv_remove,
.shutdown = usb_hcd_platform_shutdown,
.driver = {
.name = "sead3-ehci",
.owner = THIS_MODULE,
.pm = SEAD3_EHCI_PMOPS,
}
};
MODULE_ALIAS("platform:sead3-ehci");
| gpl-2.0 |
abeobk/sam9x35 | drivers/ide/cs5536.c | 2397 | 7736 | /*
* CS5536 PATA support
* (C) 2007 Martin K. Petersen <mkp@mkp.net>
* (C) 2009 Bartlomiej Zolnierkiewicz
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Documentation:
* Available from AMD web site.
*
* The IDE timing registers for the CS5536 live in the Geode Machine
* Specific Register file and not PCI config space. Most BIOSes
* virtualize the PCI registers so the chip looks like a standard IDE
* controller. Unfortunately not all implementations get this right.
* In particular some have problems with unaligned accesses to the
* virtualized PCI registers. This driver always does full dword
* writes to work around the issue. Also, in case of a bad BIOS this
* driver can be loaded with the "msr=1" parameter which forces using
* the Machine Specific Registers to configure the device.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/ide.h>
#include <asm/msr.h>
#define DRV_NAME "cs5536"
enum {
MSR_IDE_CFG = 0x51300010,
PCI_IDE_CFG = 0x40,
CFG = 0,
DTC = 2,
CAST = 3,
ETC = 4,
IDE_CFG_CHANEN = (1 << 1),
IDE_CFG_CABLE = (1 << 17) | (1 << 16),
IDE_D0_SHIFT = 24,
IDE_D1_SHIFT = 16,
IDE_DRV_MASK = 0xff,
IDE_CAST_D0_SHIFT = 6,
IDE_CAST_D1_SHIFT = 4,
IDE_CAST_DRV_MASK = 0x3,
IDE_CAST_CMD_SHIFT = 24,
IDE_CAST_CMD_MASK = 0xff,
IDE_ETC_UDMA_MASK = 0xc0,
};
static int use_msr;
static int cs5536_read(struct pci_dev *pdev, int reg, u32 *val)
{
if (unlikely(use_msr)) {
u32 dummy;
rdmsr(MSR_IDE_CFG + reg, *val, dummy);
return 0;
}
return pci_read_config_dword(pdev, PCI_IDE_CFG + reg * 4, val);
}
static int cs5536_write(struct pci_dev *pdev, int reg, int val)
{
if (unlikely(use_msr)) {
wrmsr(MSR_IDE_CFG + reg, val, 0);
return 0;
}
return pci_write_config_dword(pdev, PCI_IDE_CFG + reg * 4, val);
}
static void cs5536_program_dtc(ide_drive_t *drive, u8 tim)
{
struct pci_dev *pdev = to_pci_dev(drive->hwif->dev);
int dshift = (drive->dn & 1) ? IDE_D1_SHIFT : IDE_D0_SHIFT;
u32 dtc;
cs5536_read(pdev, DTC, &dtc);
dtc &= ~(IDE_DRV_MASK << dshift);
dtc |= tim << dshift;
cs5536_write(pdev, DTC, dtc);
}
/**
* cs5536_cable_detect - detect cable type
* @hwif: Port to detect on
*
* Perform cable detection for ATA66 capable cable.
*
* Returns a cable type.
*/
static u8 cs5536_cable_detect(ide_hwif_t *hwif)
{
struct pci_dev *pdev = to_pci_dev(hwif->dev);
u32 cfg;
cs5536_read(pdev, CFG, &cfg);
if (cfg & IDE_CFG_CABLE)
return ATA_CBL_PATA80;
else
return ATA_CBL_PATA40;
}
/**
* cs5536_set_pio_mode - PIO timing setup
* @hwif: ATA port
* @drive: ATA device
*/
static void cs5536_set_pio_mode(ide_hwif_t *hwif, ide_drive_t *drive)
{
static const u8 drv_timings[5] = {
0x98, 0x55, 0x32, 0x21, 0x20,
};
static const u8 addr_timings[5] = {
0x2, 0x1, 0x0, 0x0, 0x0,
};
static const u8 cmd_timings[5] = {
0x99, 0x92, 0x90, 0x22, 0x20,
};
struct pci_dev *pdev = to_pci_dev(hwif->dev);
ide_drive_t *pair = ide_get_pair_dev(drive);
int cshift = (drive->dn & 1) ? IDE_CAST_D1_SHIFT : IDE_CAST_D0_SHIFT;
unsigned long timings = (unsigned long)ide_get_drivedata(drive);
u32 cast;
const u8 pio = drive->pio_mode - XFER_PIO_0;
u8 cmd_pio = pio;
if (pair)
cmd_pio = min_t(u8, pio, pair->pio_mode - XFER_PIO_0);
timings &= (IDE_DRV_MASK << 8);
timings |= drv_timings[pio];
ide_set_drivedata(drive, (void *)timings);
cs5536_program_dtc(drive, drv_timings[pio]);
cs5536_read(pdev, CAST, &cast);
cast &= ~(IDE_CAST_DRV_MASK << cshift);
cast |= addr_timings[pio] << cshift;
cast &= ~(IDE_CAST_CMD_MASK << IDE_CAST_CMD_SHIFT);
cast |= cmd_timings[cmd_pio] << IDE_CAST_CMD_SHIFT;
cs5536_write(pdev, CAST, cast);
}
/**
* cs5536_set_dma_mode - DMA timing setup
* @hwif: ATA port
* @drive: ATA device
*/
static void cs5536_set_dma_mode(ide_hwif_t *hwif, ide_drive_t *drive)
{
static const u8 udma_timings[6] = {
0xc2, 0xc1, 0xc0, 0xc4, 0xc5, 0xc6,
};
static const u8 mwdma_timings[3] = {
0x67, 0x21, 0x20,
};
struct pci_dev *pdev = to_pci_dev(hwif->dev);
int dshift = (drive->dn & 1) ? IDE_D1_SHIFT : IDE_D0_SHIFT;
unsigned long timings = (unsigned long)ide_get_drivedata(drive);
u32 etc;
const u8 mode = drive->dma_mode;
cs5536_read(pdev, ETC, &etc);
if (mode >= XFER_UDMA_0) {
etc &= ~(IDE_DRV_MASK << dshift);
etc |= udma_timings[mode - XFER_UDMA_0] << dshift;
} else { /* MWDMA */
etc &= ~(IDE_ETC_UDMA_MASK << dshift);
timings &= IDE_DRV_MASK;
timings |= mwdma_timings[mode - XFER_MW_DMA_0] << 8;
ide_set_drivedata(drive, (void *)timings);
}
cs5536_write(pdev, ETC, etc);
}
static void cs5536_dma_start(ide_drive_t *drive)
{
unsigned long timings = (unsigned long)ide_get_drivedata(drive);
if (drive->current_speed < XFER_UDMA_0 &&
(timings >> 8) != (timings & IDE_DRV_MASK))
cs5536_program_dtc(drive, timings >> 8);
ide_dma_start(drive);
}
static int cs5536_dma_end(ide_drive_t *drive)
{
int ret = ide_dma_end(drive);
unsigned long timings = (unsigned long)ide_get_drivedata(drive);
if (drive->current_speed < XFER_UDMA_0 &&
(timings >> 8) != (timings & IDE_DRV_MASK))
cs5536_program_dtc(drive, timings & IDE_DRV_MASK);
return ret;
}
static const struct ide_port_ops cs5536_port_ops = {
.set_pio_mode = cs5536_set_pio_mode,
.set_dma_mode = cs5536_set_dma_mode,
.cable_detect = cs5536_cable_detect,
};
static const struct ide_dma_ops cs5536_dma_ops = {
.dma_host_set = ide_dma_host_set,
.dma_setup = ide_dma_setup,
.dma_start = cs5536_dma_start,
.dma_end = cs5536_dma_end,
.dma_test_irq = ide_dma_test_irq,
.dma_lost_irq = ide_dma_lost_irq,
.dma_timer_expiry = ide_dma_sff_timer_expiry,
.dma_sff_read_status = ide_dma_sff_read_status,
};
static const struct ide_port_info cs5536_info = {
.name = DRV_NAME,
.port_ops = &cs5536_port_ops,
.dma_ops = &cs5536_dma_ops,
.host_flags = IDE_HFLAG_SINGLE,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA5,
};
/**
* cs5536_init_one
* @dev: PCI device
* @id: Entry in match table
*/
static int cs5536_init_one(struct pci_dev *dev, const struct pci_device_id *id)
{
u32 cfg;
if (use_msr)
printk(KERN_INFO DRV_NAME ": Using MSR regs instead of PCI\n");
cs5536_read(dev, CFG, &cfg);
if ((cfg & IDE_CFG_CHANEN) == 0) {
printk(KERN_ERR DRV_NAME ": disabled by BIOS\n");
return -ENODEV;
}
return ide_pci_init_one(dev, &cs5536_info, NULL);
}
static const struct pci_device_id cs5536_pci_tbl[] = {
{ PCI_VDEVICE(AMD, PCI_DEVICE_ID_AMD_CS5536_IDE), },
{ },
};
static struct pci_driver cs5536_pci_driver = {
.name = DRV_NAME,
.id_table = cs5536_pci_tbl,
.probe = cs5536_init_one,
.remove = ide_pci_remove,
.suspend = ide_pci_suspend,
.resume = ide_pci_resume,
};
module_pci_driver(cs5536_pci_driver);
MODULE_AUTHOR("Martin K. Petersen, Bartlomiej Zolnierkiewicz");
MODULE_DESCRIPTION("low-level driver for the CS5536 IDE controller");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, cs5536_pci_tbl);
module_param_named(msr, use_msr, int, 0644);
MODULE_PARM_DESC(msr, "Force using MSR to configure IDE function (Default: 0)");
| gpl-2.0 |
SamsungGalaxyS6/kernel_samsung_exynos7420 | drivers/input/touchscreen/mtouch.c | 2653 | 5091 | /*
* MicroTouch (3M) serial touchscreen driver
*
* Copyright (c) 2004 Vojtech Pavlik
*/
/*
* 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.
*/
/*
* 2005/02/19 Dan Streetman <ddstreet@ieee.org>
* Copied elo.c and edited for MicroTouch protocol
*/
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/serio.h>
#include <linux/init.h>
#define DRIVER_DESC "MicroTouch serial touchscreen driver"
MODULE_AUTHOR("Vojtech Pavlik <vojtech@ucw.cz>");
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
/*
* Definitions & global arrays.
*/
#define MTOUCH_FORMAT_TABLET_STATUS_BIT 0x80
#define MTOUCH_FORMAT_TABLET_TOUCH_BIT 0x40
#define MTOUCH_FORMAT_TABLET_LENGTH 5
#define MTOUCH_RESPONSE_BEGIN_BYTE 0x01
#define MTOUCH_RESPONSE_END_BYTE 0x0d
/* todo: check specs for max length of all responses */
#define MTOUCH_MAX_LENGTH 16
#define MTOUCH_MIN_XC 0
#define MTOUCH_MAX_XC 0x3fff
#define MTOUCH_MIN_YC 0
#define MTOUCH_MAX_YC 0x3fff
#define MTOUCH_GET_XC(data) (((data[2])<<7) | data[1])
#define MTOUCH_GET_YC(data) (((data[4])<<7) | data[3])
#define MTOUCH_GET_TOUCHED(data) (MTOUCH_FORMAT_TABLET_TOUCH_BIT & data[0])
/*
* Per-touchscreen data.
*/
struct mtouch {
struct input_dev *dev;
struct serio *serio;
int idx;
unsigned char data[MTOUCH_MAX_LENGTH];
char phys[32];
};
static void mtouch_process_format_tablet(struct mtouch *mtouch)
{
struct input_dev *dev = mtouch->dev;
if (MTOUCH_FORMAT_TABLET_LENGTH == ++mtouch->idx) {
input_report_abs(dev, ABS_X, MTOUCH_GET_XC(mtouch->data));
input_report_abs(dev, ABS_Y, MTOUCH_MAX_YC - MTOUCH_GET_YC(mtouch->data));
input_report_key(dev, BTN_TOUCH, MTOUCH_GET_TOUCHED(mtouch->data));
input_sync(dev);
mtouch->idx = 0;
}
}
static void mtouch_process_response(struct mtouch *mtouch)
{
if (MTOUCH_RESPONSE_END_BYTE == mtouch->data[mtouch->idx++]) {
/* FIXME - process response */
mtouch->idx = 0;
} else if (MTOUCH_MAX_LENGTH == mtouch->idx) {
printk(KERN_ERR "mtouch.c: too many response bytes\n");
mtouch->idx = 0;
}
}
static irqreturn_t mtouch_interrupt(struct serio *serio,
unsigned char data, unsigned int flags)
{
struct mtouch* mtouch = serio_get_drvdata(serio);
mtouch->data[mtouch->idx] = data;
if (MTOUCH_FORMAT_TABLET_STATUS_BIT & mtouch->data[0])
mtouch_process_format_tablet(mtouch);
else if (MTOUCH_RESPONSE_BEGIN_BYTE == mtouch->data[0])
mtouch_process_response(mtouch);
else
printk(KERN_DEBUG "mtouch.c: unknown/unsynchronized data from device, byte %x\n",mtouch->data[0]);
return IRQ_HANDLED;
}
/*
* mtouch_disconnect() is the opposite of mtouch_connect()
*/
static void mtouch_disconnect(struct serio *serio)
{
struct mtouch* mtouch = serio_get_drvdata(serio);
input_get_device(mtouch->dev);
input_unregister_device(mtouch->dev);
serio_close(serio);
serio_set_drvdata(serio, NULL);
input_put_device(mtouch->dev);
kfree(mtouch);
}
/*
* mtouch_connect() is the routine that is called when someone adds a
* new serio device that supports MicroTouch (Format Tablet) protocol and registers it as
* an input device.
*/
static int mtouch_connect(struct serio *serio, struct serio_driver *drv)
{
struct mtouch *mtouch;
struct input_dev *input_dev;
int err;
mtouch = kzalloc(sizeof(struct mtouch), GFP_KERNEL);
input_dev = input_allocate_device();
if (!mtouch || !input_dev) {
err = -ENOMEM;
goto fail1;
}
mtouch->serio = serio;
mtouch->dev = input_dev;
snprintf(mtouch->phys, sizeof(mtouch->phys), "%s/input0", serio->phys);
input_dev->name = "MicroTouch Serial TouchScreen";
input_dev->phys = mtouch->phys;
input_dev->id.bustype = BUS_RS232;
input_dev->id.vendor = SERIO_MICROTOUCH;
input_dev->id.product = 0;
input_dev->id.version = 0x0100;
input_dev->dev.parent = &serio->dev;
input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
input_dev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH);
input_set_abs_params(mtouch->dev, ABS_X, MTOUCH_MIN_XC, MTOUCH_MAX_XC, 0, 0);
input_set_abs_params(mtouch->dev, ABS_Y, MTOUCH_MIN_YC, MTOUCH_MAX_YC, 0, 0);
serio_set_drvdata(serio, mtouch);
err = serio_open(serio, drv);
if (err)
goto fail2;
err = input_register_device(mtouch->dev);
if (err)
goto fail3;
return 0;
fail3: serio_close(serio);
fail2: serio_set_drvdata(serio, NULL);
fail1: input_free_device(input_dev);
kfree(mtouch);
return err;
}
/*
* The serio driver structure.
*/
static struct serio_device_id mtouch_serio_ids[] = {
{
.type = SERIO_RS232,
.proto = SERIO_MICROTOUCH,
.id = SERIO_ANY,
.extra = SERIO_ANY,
},
{ 0 }
};
MODULE_DEVICE_TABLE(serio, mtouch_serio_ids);
static struct serio_driver mtouch_drv = {
.driver = {
.name = "mtouch",
},
.description = DRIVER_DESC,
.id_table = mtouch_serio_ids,
.interrupt = mtouch_interrupt,
.connect = mtouch_connect,
.disconnect = mtouch_disconnect,
};
module_serio_driver(mtouch_drv);
| gpl-2.0 |
smihir/wireless-testing | arch/arm/mach-omap2/usb-tusb6010.c | 2653 | 6096 | /*
* linux/arch/arm/mach-omap2/usb-tusb6010.c
*
* Copyright (C) 2006 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.
*/
#include <linux/err.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/export.h>
#include <linux/platform_data/usb-omap.h>
#include <linux/usb/musb.h>
#include "gpmc.h"
#include "mux.h"
static u8 async_cs, sync_cs;
static unsigned refclk_psec;
static struct gpmc_settings tusb_async = {
.wait_on_read = true,
.wait_on_write = true,
.device_width = GPMC_DEVWIDTH_16BIT,
.mux_add_data = GPMC_MUX_AD,
};
static struct gpmc_settings tusb_sync = {
.burst_read = true,
.burst_write = true,
.sync_read = true,
.sync_write = true,
.wait_on_read = true,
.wait_on_write = true,
.burst_len = GPMC_BURST_16,
.device_width = GPMC_DEVWIDTH_16BIT,
.mux_add_data = GPMC_MUX_AD,
};
/* NOTE: timings are from tusb 6010 datasheet Rev 1.8, 12-Sept 2006 */
static int tusb_set_async_mode(unsigned sysclk_ps)
{
struct gpmc_device_timings dev_t;
struct gpmc_timings t;
unsigned t_acsnh_advnh = sysclk_ps + 3000;
memset(&dev_t, 0, sizeof(dev_t));
dev_t.t_ceasu = 8 * 1000;
dev_t.t_avdasu = t_acsnh_advnh - 7000;
dev_t.t_ce_avd = 1000;
dev_t.t_avdp_r = t_acsnh_advnh;
dev_t.t_oeasu = t_acsnh_advnh + 1000;
dev_t.t_oe = 300;
dev_t.t_cez_r = 7000;
dev_t.t_cez_w = dev_t.t_cez_r;
dev_t.t_avdp_w = t_acsnh_advnh;
dev_t.t_weasu = t_acsnh_advnh + 1000;
dev_t.t_wpl = 300;
dev_t.cyc_aavdh_we = 1;
gpmc_calc_timings(&t, &tusb_async, &dev_t);
return gpmc_cs_set_timings(async_cs, &t);
}
static int tusb_set_sync_mode(unsigned sysclk_ps)
{
struct gpmc_device_timings dev_t;
struct gpmc_timings t;
unsigned t_scsnh_advnh = sysclk_ps + 3000;
memset(&dev_t, 0, sizeof(dev_t));
dev_t.clk = 11100;
dev_t.t_bacc = 1000;
dev_t.t_ces = 1000;
dev_t.t_ceasu = 8 * 1000;
dev_t.t_avdasu = t_scsnh_advnh - 7000;
dev_t.t_ce_avd = 1000;
dev_t.t_avdp_r = t_scsnh_advnh;
dev_t.cyc_aavdh_oe = 3;
dev_t.cyc_oe = 5;
dev_t.t_ce_rdyz = 7000;
dev_t.t_avdp_w = t_scsnh_advnh;
dev_t.cyc_aavdh_we = 3;
dev_t.cyc_wpl = 6;
dev_t.t_ce_rdyz = 7000;
gpmc_calc_timings(&t, &tusb_sync, &dev_t);
return gpmc_cs_set_timings(sync_cs, &t);
}
/* tusb driver calls this when it changes the chip's clocking */
int tusb6010_platform_retime(unsigned is_refclk)
{
static const char error[] =
KERN_ERR "tusb6010 %s retime error %d\n";
unsigned sysclk_ps;
int status;
if (!refclk_psec)
return -ENODEV;
sysclk_ps = is_refclk ? refclk_psec : TUSB6010_OSCCLK_60;
status = tusb_set_async_mode(sysclk_ps);
if (status < 0) {
printk(error, "async", status);
goto done;
}
status = tusb_set_sync_mode(sysclk_ps);
if (status < 0)
printk(error, "sync", status);
done:
return status;
}
EXPORT_SYMBOL_GPL(tusb6010_platform_retime);
static struct resource tusb_resources[] = {
/* Order is significant! The start/end fields
* are updated during setup..
*/
{ /* Asynchronous access */
.flags = IORESOURCE_MEM,
},
{ /* Synchronous access */
.flags = IORESOURCE_MEM,
},
{ /* IRQ */
.name = "mc",
.flags = IORESOURCE_IRQ,
},
};
static u64 tusb_dmamask = ~(u32)0;
static struct platform_device tusb_device = {
.name = "musb-tusb",
.id = -1,
.dev = {
.dma_mask = &tusb_dmamask,
.coherent_dma_mask = 0xffffffff,
},
.num_resources = ARRAY_SIZE(tusb_resources),
.resource = tusb_resources,
};
/* this may be called only from board-*.c setup code */
int __init
tusb6010_setup_interface(struct musb_hdrc_platform_data *data,
unsigned ps_refclk, unsigned waitpin,
unsigned async, unsigned sync,
unsigned irq, unsigned dmachan)
{
int status;
static char error[] __initdata =
KERN_ERR "tusb6010 init error %d, %d\n";
/* ASYNC region, primarily for PIO */
status = gpmc_cs_request(async, SZ_16M, (unsigned long *)
&tusb_resources[0].start);
if (status < 0) {
printk(error, 1, status);
return status;
}
tusb_resources[0].end = tusb_resources[0].start + 0x9ff;
tusb_async.wait_pin = waitpin;
async_cs = async;
status = gpmc_cs_program_settings(async_cs, &tusb_async);
if (status < 0)
return status;
/* SYNC region, primarily for DMA */
status = gpmc_cs_request(sync, SZ_16M, (unsigned long *)
&tusb_resources[1].start);
if (status < 0) {
printk(error, 2, status);
return status;
}
tusb_resources[1].end = tusb_resources[1].start + 0x9ff;
tusb_sync.wait_pin = waitpin;
sync_cs = sync;
status = gpmc_cs_program_settings(sync_cs, &tusb_sync);
if (status < 0)
return status;
/* IRQ */
status = gpio_request_one(irq, GPIOF_IN, "TUSB6010 irq");
if (status < 0) {
printk(error, 3, status);
return status;
}
tusb_resources[2].start = gpio_to_irq(irq);
/* set up memory timings ... can speed them up later */
if (!ps_refclk) {
printk(error, 4, status);
return -ENODEV;
}
refclk_psec = ps_refclk;
status = tusb6010_platform_retime(1);
if (status < 0) {
printk(error, 5, status);
return status;
}
/* finish device setup ... */
if (!data) {
printk(error, 6, status);
return -ENODEV;
}
tusb_device.dev.platform_data = data;
/* REVISIT let the driver know what DMA channels work */
if (!dmachan)
tusb_device.dev.dma_mask = NULL;
else {
/* assume OMAP 2420 ES2.0 and later */
if (dmachan & (1 << 0))
omap_mux_init_signal("sys_ndmareq0", 0);
if (dmachan & (1 << 1))
omap_mux_init_signal("sys_ndmareq1", 0);
if (dmachan & (1 << 2))
omap_mux_init_signal("sys_ndmareq2", 0);
if (dmachan & (1 << 3))
omap_mux_init_signal("sys_ndmareq3", 0);
if (dmachan & (1 << 4))
omap_mux_init_signal("sys_ndmareq4", 0);
if (dmachan & (1 << 5))
omap_mux_init_signal("sys_ndmareq5", 0);
}
/* so far so good ... register the device */
status = platform_device_register(&tusb_device);
if (status < 0) {
printk(error, 7, status);
return status;
}
return 0;
}
| gpl-2.0 |
Zzomborg/Learning-2 | lib/timerqueue.c | 3165 | 3155 | /*
* Generic Timer-queue
*
* Manages a simple queue of timers, ordered by expiration time.
* Uses rbtrees for quick list adds and expiration.
*
* NOTE: All of the following functions need to be serialized
* to avoid races. No locking is done by this library code.
*
* 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/timerqueue.h>
#include <linux/rbtree.h>
#include <linux/module.h>
/**
* timerqueue_add - Adds timer to timerqueue.
*
* @head: head of timerqueue
* @node: timer node to be added
*
* Adds the timer node to the timerqueue, sorted by the
* node's expires value.
*/
void timerqueue_add(struct timerqueue_head *head, struct timerqueue_node *node)
{
struct rb_node **p = &head->head.rb_node;
struct rb_node *parent = NULL;
struct timerqueue_node *ptr;
/* Make sure we don't add nodes that are already added */
WARN_ON_ONCE(!RB_EMPTY_NODE(&node->node));
while (*p) {
parent = *p;
ptr = rb_entry(parent, struct timerqueue_node, node);
if (node->expires.tv64 < ptr->expires.tv64)
p = &(*p)->rb_left;
else
p = &(*p)->rb_right;
}
rb_link_node(&node->node, parent, p);
rb_insert_color(&node->node, &head->head);
if (!head->next || node->expires.tv64 < head->next->expires.tv64)
head->next = node;
}
EXPORT_SYMBOL_GPL(timerqueue_add);
/**
* timerqueue_del - Removes a timer from the timerqueue.
*
* @head: head of timerqueue
* @node: timer node to be removed
*
* Removes the timer node from the timerqueue.
*/
void timerqueue_del(struct timerqueue_head *head, struct timerqueue_node *node)
{
WARN_ON_ONCE(RB_EMPTY_NODE(&node->node));
/* update next pointer */
if (head->next == node) {
struct rb_node *rbn = rb_next(&node->node);
head->next = rbn ?
rb_entry(rbn, struct timerqueue_node, node) : NULL;
}
rb_erase(&node->node, &head->head);
RB_CLEAR_NODE(&node->node);
}
EXPORT_SYMBOL_GPL(timerqueue_del);
/**
* timerqueue_iterate_next - Returns the timer after the provided timer
*
* @node: Pointer to a timer.
*
* Provides the timer that is after the given node. This is used, when
* necessary, to iterate through the list of timers in a timer list
* without modifying the list.
*/
struct timerqueue_node *timerqueue_iterate_next(struct timerqueue_node *node)
{
struct rb_node *next;
if (!node)
return NULL;
next = rb_next(&node->node);
if (!next)
return NULL;
return container_of(next, struct timerqueue_node, node);
}
EXPORT_SYMBOL_GPL(timerqueue_iterate_next);
| gpl-2.0 |
yank555-lu/TF101G_V9.2.2.6 | lib/timerqueue.c | 3165 | 3155 | /*
* Generic Timer-queue
*
* Manages a simple queue of timers, ordered by expiration time.
* Uses rbtrees for quick list adds and expiration.
*
* NOTE: All of the following functions need to be serialized
* to avoid races. No locking is done by this library code.
*
* 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/timerqueue.h>
#include <linux/rbtree.h>
#include <linux/module.h>
/**
* timerqueue_add - Adds timer to timerqueue.
*
* @head: head of timerqueue
* @node: timer node to be added
*
* Adds the timer node to the timerqueue, sorted by the
* node's expires value.
*/
void timerqueue_add(struct timerqueue_head *head, struct timerqueue_node *node)
{
struct rb_node **p = &head->head.rb_node;
struct rb_node *parent = NULL;
struct timerqueue_node *ptr;
/* Make sure we don't add nodes that are already added */
WARN_ON_ONCE(!RB_EMPTY_NODE(&node->node));
while (*p) {
parent = *p;
ptr = rb_entry(parent, struct timerqueue_node, node);
if (node->expires.tv64 < ptr->expires.tv64)
p = &(*p)->rb_left;
else
p = &(*p)->rb_right;
}
rb_link_node(&node->node, parent, p);
rb_insert_color(&node->node, &head->head);
if (!head->next || node->expires.tv64 < head->next->expires.tv64)
head->next = node;
}
EXPORT_SYMBOL_GPL(timerqueue_add);
/**
* timerqueue_del - Removes a timer from the timerqueue.
*
* @head: head of timerqueue
* @node: timer node to be removed
*
* Removes the timer node from the timerqueue.
*/
void timerqueue_del(struct timerqueue_head *head, struct timerqueue_node *node)
{
WARN_ON_ONCE(RB_EMPTY_NODE(&node->node));
/* update next pointer */
if (head->next == node) {
struct rb_node *rbn = rb_next(&node->node);
head->next = rbn ?
rb_entry(rbn, struct timerqueue_node, node) : NULL;
}
rb_erase(&node->node, &head->head);
RB_CLEAR_NODE(&node->node);
}
EXPORT_SYMBOL_GPL(timerqueue_del);
/**
* timerqueue_iterate_next - Returns the timer after the provided timer
*
* @node: Pointer to a timer.
*
* Provides the timer that is after the given node. This is used, when
* necessary, to iterate through the list of timers in a timer list
* without modifying the list.
*/
struct timerqueue_node *timerqueue_iterate_next(struct timerqueue_node *node)
{
struct rb_node *next;
if (!node)
return NULL;
next = rb_next(&node->node);
if (!next)
return NULL;
return container_of(next, struct timerqueue_node, node);
}
EXPORT_SYMBOL_GPL(timerqueue_iterate_next);
| gpl-2.0 |
uoaerg/linux-ecn | net/lapb/lapb_iface.c | 3421 | 9073 | /*
* LAPB release 002
*
* This code REQUIRES 2.1.15 or higher/ NET3.038
*
* This module:
* This module is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* History
* LAPB 001 Jonathan Naylor Started Coding
* LAPB 002 Jonathan Naylor New timer architecture.
* 2000-10-29 Henner Eisen lapb_data_indication() return status.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/jiffies.h>
#include <linux/timer.h>
#include <linux/string.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/inet.h>
#include <linux/if_arp.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <asm/uaccess.h>
#include <linux/fcntl.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/stat.h>
#include <linux/init.h>
#include <net/lapb.h>
static LIST_HEAD(lapb_list);
static DEFINE_RWLOCK(lapb_list_lock);
/*
* Free an allocated lapb control block.
*/
static void lapb_free_cb(struct lapb_cb *lapb)
{
kfree(lapb);
}
static __inline__ void lapb_hold(struct lapb_cb *lapb)
{
atomic_inc(&lapb->refcnt);
}
static __inline__ void lapb_put(struct lapb_cb *lapb)
{
if (atomic_dec_and_test(&lapb->refcnt))
lapb_free_cb(lapb);
}
/*
* Socket removal during an interrupt is now safe.
*/
static void __lapb_remove_cb(struct lapb_cb *lapb)
{
if (lapb->node.next) {
list_del(&lapb->node);
lapb_put(lapb);
}
}
/*
* Add a socket to the bound sockets list.
*/
static void __lapb_insert_cb(struct lapb_cb *lapb)
{
list_add(&lapb->node, &lapb_list);
lapb_hold(lapb);
}
static struct lapb_cb *__lapb_devtostruct(struct net_device *dev)
{
struct list_head *entry;
struct lapb_cb *lapb, *use = NULL;
list_for_each(entry, &lapb_list) {
lapb = list_entry(entry, struct lapb_cb, node);
if (lapb->dev == dev) {
use = lapb;
break;
}
}
if (use)
lapb_hold(use);
return use;
}
static struct lapb_cb *lapb_devtostruct(struct net_device *dev)
{
struct lapb_cb *rc;
read_lock_bh(&lapb_list_lock);
rc = __lapb_devtostruct(dev);
read_unlock_bh(&lapb_list_lock);
return rc;
}
/*
* Create an empty LAPB control block.
*/
static struct lapb_cb *lapb_create_cb(void)
{
struct lapb_cb *lapb = kzalloc(sizeof(*lapb), GFP_ATOMIC);
if (!lapb)
goto out;
skb_queue_head_init(&lapb->write_queue);
skb_queue_head_init(&lapb->ack_queue);
init_timer(&lapb->t1timer);
init_timer(&lapb->t2timer);
lapb->t1 = LAPB_DEFAULT_T1;
lapb->t2 = LAPB_DEFAULT_T2;
lapb->n2 = LAPB_DEFAULT_N2;
lapb->mode = LAPB_DEFAULT_MODE;
lapb->window = LAPB_DEFAULT_WINDOW;
lapb->state = LAPB_STATE_0;
atomic_set(&lapb->refcnt, 1);
out:
return lapb;
}
int lapb_register(struct net_device *dev,
const struct lapb_register_struct *callbacks)
{
struct lapb_cb *lapb;
int rc = LAPB_BADTOKEN;
write_lock_bh(&lapb_list_lock);
lapb = __lapb_devtostruct(dev);
if (lapb) {
lapb_put(lapb);
goto out;
}
lapb = lapb_create_cb();
rc = LAPB_NOMEM;
if (!lapb)
goto out;
lapb->dev = dev;
lapb->callbacks = callbacks;
__lapb_insert_cb(lapb);
lapb_start_t1timer(lapb);
rc = LAPB_OK;
out:
write_unlock_bh(&lapb_list_lock);
return rc;
}
int lapb_unregister(struct net_device *dev)
{
struct lapb_cb *lapb;
int rc = LAPB_BADTOKEN;
write_lock_bh(&lapb_list_lock);
lapb = __lapb_devtostruct(dev);
if (!lapb)
goto out;
lapb_stop_t1timer(lapb);
lapb_stop_t2timer(lapb);
lapb_clear_queues(lapb);
__lapb_remove_cb(lapb);
lapb_put(lapb);
rc = LAPB_OK;
out:
write_unlock_bh(&lapb_list_lock);
return rc;
}
int lapb_getparms(struct net_device *dev, struct lapb_parms_struct *parms)
{
int rc = LAPB_BADTOKEN;
struct lapb_cb *lapb = lapb_devtostruct(dev);
if (!lapb)
goto out;
parms->t1 = lapb->t1 / HZ;
parms->t2 = lapb->t2 / HZ;
parms->n2 = lapb->n2;
parms->n2count = lapb->n2count;
parms->state = lapb->state;
parms->window = lapb->window;
parms->mode = lapb->mode;
if (!timer_pending(&lapb->t1timer))
parms->t1timer = 0;
else
parms->t1timer = (lapb->t1timer.expires - jiffies) / HZ;
if (!timer_pending(&lapb->t2timer))
parms->t2timer = 0;
else
parms->t2timer = (lapb->t2timer.expires - jiffies) / HZ;
lapb_put(lapb);
rc = LAPB_OK;
out:
return rc;
}
int lapb_setparms(struct net_device *dev, struct lapb_parms_struct *parms)
{
int rc = LAPB_BADTOKEN;
struct lapb_cb *lapb = lapb_devtostruct(dev);
if (!lapb)
goto out;
rc = LAPB_INVALUE;
if (parms->t1 < 1 || parms->t2 < 1 || parms->n2 < 1)
goto out_put;
if (lapb->state == LAPB_STATE_0) {
if (parms->mode & LAPB_EXTENDED) {
if (parms->window < 1 || parms->window > 127)
goto out_put;
} else {
if (parms->window < 1 || parms->window > 7)
goto out_put;
}
lapb->mode = parms->mode;
lapb->window = parms->window;
}
lapb->t1 = parms->t1 * HZ;
lapb->t2 = parms->t2 * HZ;
lapb->n2 = parms->n2;
rc = LAPB_OK;
out_put:
lapb_put(lapb);
out:
return rc;
}
int lapb_connect_request(struct net_device *dev)
{
struct lapb_cb *lapb = lapb_devtostruct(dev);
int rc = LAPB_BADTOKEN;
if (!lapb)
goto out;
rc = LAPB_OK;
if (lapb->state == LAPB_STATE_1)
goto out_put;
rc = LAPB_CONNECTED;
if (lapb->state == LAPB_STATE_3 || lapb->state == LAPB_STATE_4)
goto out_put;
lapb_establish_data_link(lapb);
lapb_dbg(0, "(%p) S0 -> S1\n", lapb->dev);
lapb->state = LAPB_STATE_1;
rc = LAPB_OK;
out_put:
lapb_put(lapb);
out:
return rc;
}
int lapb_disconnect_request(struct net_device *dev)
{
struct lapb_cb *lapb = lapb_devtostruct(dev);
int rc = LAPB_BADTOKEN;
if (!lapb)
goto out;
switch (lapb->state) {
case LAPB_STATE_0:
rc = LAPB_NOTCONNECTED;
goto out_put;
case LAPB_STATE_1:
lapb_dbg(1, "(%p) S1 TX DISC(1)\n", lapb->dev);
lapb_dbg(0, "(%p) S1 -> S0\n", lapb->dev);
lapb_send_control(lapb, LAPB_DISC, LAPB_POLLON, LAPB_COMMAND);
lapb->state = LAPB_STATE_0;
lapb_start_t1timer(lapb);
rc = LAPB_NOTCONNECTED;
goto out_put;
case LAPB_STATE_2:
rc = LAPB_OK;
goto out_put;
}
lapb_clear_queues(lapb);
lapb->n2count = 0;
lapb_send_control(lapb, LAPB_DISC, LAPB_POLLON, LAPB_COMMAND);
lapb_start_t1timer(lapb);
lapb_stop_t2timer(lapb);
lapb->state = LAPB_STATE_2;
lapb_dbg(1, "(%p) S3 DISC(1)\n", lapb->dev);
lapb_dbg(0, "(%p) S3 -> S2\n", lapb->dev);
rc = LAPB_OK;
out_put:
lapb_put(lapb);
out:
return rc;
}
int lapb_data_request(struct net_device *dev, struct sk_buff *skb)
{
struct lapb_cb *lapb = lapb_devtostruct(dev);
int rc = LAPB_BADTOKEN;
if (!lapb)
goto out;
rc = LAPB_NOTCONNECTED;
if (lapb->state != LAPB_STATE_3 && lapb->state != LAPB_STATE_4)
goto out_put;
skb_queue_tail(&lapb->write_queue, skb);
lapb_kick(lapb);
rc = LAPB_OK;
out_put:
lapb_put(lapb);
out:
return rc;
}
int lapb_data_received(struct net_device *dev, struct sk_buff *skb)
{
struct lapb_cb *lapb = lapb_devtostruct(dev);
int rc = LAPB_BADTOKEN;
if (lapb) {
lapb_data_input(lapb, skb);
lapb_put(lapb);
rc = LAPB_OK;
}
return rc;
}
void lapb_connect_confirmation(struct lapb_cb *lapb, int reason)
{
if (lapb->callbacks->connect_confirmation)
lapb->callbacks->connect_confirmation(lapb->dev, reason);
}
void lapb_connect_indication(struct lapb_cb *lapb, int reason)
{
if (lapb->callbacks->connect_indication)
lapb->callbacks->connect_indication(lapb->dev, reason);
}
void lapb_disconnect_confirmation(struct lapb_cb *lapb, int reason)
{
if (lapb->callbacks->disconnect_confirmation)
lapb->callbacks->disconnect_confirmation(lapb->dev, reason);
}
void lapb_disconnect_indication(struct lapb_cb *lapb, int reason)
{
if (lapb->callbacks->disconnect_indication)
lapb->callbacks->disconnect_indication(lapb->dev, reason);
}
int lapb_data_indication(struct lapb_cb *lapb, struct sk_buff *skb)
{
if (lapb->callbacks->data_indication)
return lapb->callbacks->data_indication(lapb->dev, skb);
kfree_skb(skb);
return NET_RX_SUCCESS; /* For now; must be != NET_RX_DROP */
}
int lapb_data_transmit(struct lapb_cb *lapb, struct sk_buff *skb)
{
int used = 0;
if (lapb->callbacks->data_transmit) {
lapb->callbacks->data_transmit(lapb->dev, skb);
used = 1;
}
return used;
}
EXPORT_SYMBOL(lapb_register);
EXPORT_SYMBOL(lapb_unregister);
EXPORT_SYMBOL(lapb_getparms);
EXPORT_SYMBOL(lapb_setparms);
EXPORT_SYMBOL(lapb_connect_request);
EXPORT_SYMBOL(lapb_disconnect_request);
EXPORT_SYMBOL(lapb_data_request);
EXPORT_SYMBOL(lapb_data_received);
static int __init lapb_init(void)
{
return 0;
}
static void __exit lapb_exit(void)
{
WARN_ON(!list_empty(&lapb_list));
}
MODULE_AUTHOR("Jonathan Naylor <g4klx@g4klx.demon.co.uk>");
MODULE_DESCRIPTION("The X.25 Link Access Procedure B link layer protocol");
MODULE_LICENSE("GPL");
module_init(lapb_init);
module_exit(lapb_exit);
| gpl-2.0 |
Linaro/test-kernel-public | arch/mips/kernel/cpufreq/loongson2_clock.c | 4701 | 3856 | /*
* Copyright (C) 2006 - 2008 Lemote Inc. & Insititute of Computing Technology
* Author: Yanhua, yanh@lemote.com
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/module.h>
#include <linux/cpufreq.h>
#include <linux/platform_device.h>
#include <asm/clock.h>
#include <loongson.h>
static LIST_HEAD(clock_list);
static DEFINE_SPINLOCK(clock_lock);
static DEFINE_MUTEX(clock_list_sem);
/* Minimum CLK support */
enum {
DC_ZERO, DC_25PT = 2, DC_37PT, DC_50PT, DC_62PT, DC_75PT,
DC_87PT, DC_DISABLE, DC_RESV
};
struct cpufreq_frequency_table loongson2_clockmod_table[] = {
{DC_RESV, CPUFREQ_ENTRY_INVALID},
{DC_ZERO, CPUFREQ_ENTRY_INVALID},
{DC_25PT, 0},
{DC_37PT, 0},
{DC_50PT, 0},
{DC_62PT, 0},
{DC_75PT, 0},
{DC_87PT, 0},
{DC_DISABLE, 0},
{DC_RESV, CPUFREQ_TABLE_END},
};
EXPORT_SYMBOL_GPL(loongson2_clockmod_table);
static struct clk cpu_clk = {
.name = "cpu_clk",
.flags = CLK_ALWAYS_ENABLED | CLK_RATE_PROPAGATES,
.rate = 800000000,
};
struct clk *clk_get(struct device *dev, const char *id)
{
return &cpu_clk;
}
EXPORT_SYMBOL(clk_get);
static void propagate_rate(struct clk *clk)
{
struct clk *clkp;
list_for_each_entry(clkp, &clock_list, node) {
if (likely(clkp->parent != clk))
continue;
if (likely(clkp->ops && clkp->ops->recalc))
clkp->ops->recalc(clkp);
if (unlikely(clkp->flags & CLK_RATE_PROPAGATES))
propagate_rate(clkp);
}
}
int clk_enable(struct clk *clk)
{
return 0;
}
EXPORT_SYMBOL(clk_enable);
void clk_disable(struct clk *clk)
{
}
EXPORT_SYMBOL(clk_disable);
unsigned long clk_get_rate(struct clk *clk)
{
return (unsigned long)clk->rate;
}
EXPORT_SYMBOL(clk_get_rate);
void clk_put(struct clk *clk)
{
}
EXPORT_SYMBOL(clk_put);
int clk_set_rate(struct clk *clk, unsigned long rate)
{
return clk_set_rate_ex(clk, rate, 0);
}
EXPORT_SYMBOL_GPL(clk_set_rate);
int clk_set_rate_ex(struct clk *clk, unsigned long rate, int algo_id)
{
int ret = 0;
int regval;
int i;
if (likely(clk->ops && clk->ops->set_rate)) {
unsigned long flags;
spin_lock_irqsave(&clock_lock, flags);
ret = clk->ops->set_rate(clk, rate, algo_id);
spin_unlock_irqrestore(&clock_lock, flags);
}
if (unlikely(clk->flags & CLK_RATE_PROPAGATES))
propagate_rate(clk);
for (i = 0; loongson2_clockmod_table[i].frequency != CPUFREQ_TABLE_END;
i++) {
if (loongson2_clockmod_table[i].frequency ==
CPUFREQ_ENTRY_INVALID)
continue;
if (rate == loongson2_clockmod_table[i].frequency)
break;
}
if (rate != loongson2_clockmod_table[i].frequency)
return -ENOTSUPP;
clk->rate = rate;
regval = LOONGSON_CHIPCFG0;
regval = (regval & ~0x7) | (loongson2_clockmod_table[i].index - 1);
LOONGSON_CHIPCFG0 = regval;
return ret;
}
EXPORT_SYMBOL_GPL(clk_set_rate_ex);
long clk_round_rate(struct clk *clk, unsigned long rate)
{
if (likely(clk->ops && clk->ops->round_rate)) {
unsigned long flags, rounded;
spin_lock_irqsave(&clock_lock, flags);
rounded = clk->ops->round_rate(clk, rate);
spin_unlock_irqrestore(&clock_lock, flags);
return rounded;
}
return rate;
}
EXPORT_SYMBOL_GPL(clk_round_rate);
/*
* This is the simple version of Loongson-2 wait, Maybe we need do this in
* interrupt disabled content
*/
DEFINE_SPINLOCK(loongson2_wait_lock);
void loongson2_cpu_wait(void)
{
u32 cpu_freq;
unsigned long flags;
spin_lock_irqsave(&loongson2_wait_lock, flags);
cpu_freq = LOONGSON_CHIPCFG0;
LOONGSON_CHIPCFG0 &= ~0x7; /* Put CPU into wait mode */
LOONGSON_CHIPCFG0 = cpu_freq; /* Restore CPU state */
spin_unlock_irqrestore(&loongson2_wait_lock, flags);
}
EXPORT_SYMBOL_GPL(loongson2_cpu_wait);
MODULE_AUTHOR("Yanhua <yanh@lemote.com>");
MODULE_DESCRIPTION("cpufreq driver for Loongson 2F");
MODULE_LICENSE("GPL");
| gpl-2.0 |
go2ev-devteam/Yoda-Kernel-ICS | arch/um/kernel/physmem.c | 4701 | 5397 | /*
* Copyright (C) 2000 - 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com)
* Licensed under the GPL
*/
#include "linux/bootmem.h"
#include "linux/mm.h"
#include "linux/pfn.h"
#include "asm/page.h"
#include "as-layout.h"
#include "init.h"
#include "kern.h"
#include "mem_user.h"
#include "os.h"
static int physmem_fd = -1;
/* Changed during early boot */
unsigned long high_physmem;
extern unsigned long long physmem_size;
int __init init_maps(unsigned long physmem, unsigned long iomem,
unsigned long highmem)
{
struct page *p, *map;
unsigned long phys_len, phys_pages, highmem_len, highmem_pages;
unsigned long iomem_len, iomem_pages, total_len, total_pages;
int i;
phys_pages = physmem >> PAGE_SHIFT;
phys_len = phys_pages * sizeof(struct page);
iomem_pages = iomem >> PAGE_SHIFT;
iomem_len = iomem_pages * sizeof(struct page);
highmem_pages = highmem >> PAGE_SHIFT;
highmem_len = highmem_pages * sizeof(struct page);
total_pages = phys_pages + iomem_pages + highmem_pages;
total_len = phys_len + iomem_len + highmem_len;
map = alloc_bootmem_low_pages(total_len);
if (map == NULL)
return -ENOMEM;
for (i = 0; i < total_pages; i++) {
p = &map[i];
memset(p, 0, sizeof(struct page));
SetPageReserved(p);
INIT_LIST_HEAD(&p->lru);
}
max_mapnr = total_pages;
return 0;
}
void map_memory(unsigned long virt, unsigned long phys, unsigned long len,
int r, int w, int x)
{
__u64 offset;
int fd, err;
fd = phys_mapping(phys, &offset);
err = os_map_memory((void *) virt, fd, offset, len, r, w, x);
if (err) {
if (err == -ENOMEM)
printk(KERN_ERR "try increasing the host's "
"/proc/sys/vm/max_map_count to <physical "
"memory size>/4096\n");
panic("map_memory(0x%lx, %d, 0x%llx, %ld, %d, %d, %d) failed, "
"err = %d\n", virt, fd, offset, len, r, w, x, err);
}
}
extern int __syscall_stub_start;
void __init setup_physmem(unsigned long start, unsigned long reserve_end,
unsigned long len, unsigned long long highmem)
{
unsigned long reserve = reserve_end - start;
int pfn = PFN_UP(__pa(reserve_end));
int delta = (len - reserve) >> PAGE_SHIFT;
int err, offset, bootmap_size;
physmem_fd = create_mem_file(len + highmem);
offset = uml_reserved - uml_physmem;
err = os_map_memory((void *) uml_reserved, physmem_fd, offset,
len - offset, 1, 1, 1);
if (err < 0) {
printf("setup_physmem - mapping %ld bytes of memory at 0x%p "
"failed - errno = %d\n", len - offset,
(void *) uml_reserved, err);
exit(1);
}
/*
* Special kludge - This page will be mapped in to userspace processes
* from physmem_fd, so it needs to be written out there.
*/
os_seek_file(physmem_fd, __pa(&__syscall_stub_start));
os_write_file(physmem_fd, &__syscall_stub_start, PAGE_SIZE);
bootmap_size = init_bootmem(pfn, pfn + delta);
free_bootmem(__pa(reserve_end) + bootmap_size,
len - bootmap_size - reserve);
}
int phys_mapping(unsigned long phys, unsigned long long *offset_out)
{
int fd = -1;
if (phys < physmem_size) {
fd = physmem_fd;
*offset_out = phys;
}
else if (phys < __pa(end_iomem)) {
struct iomem_region *region = iomem_regions;
while (region != NULL) {
if ((phys >= region->phys) &&
(phys < region->phys + region->size)) {
fd = region->fd;
*offset_out = phys - region->phys;
break;
}
region = region->next;
}
}
else if (phys < __pa(end_iomem) + highmem) {
fd = physmem_fd;
*offset_out = phys - iomem_size;
}
return fd;
}
static int __init uml_mem_setup(char *line, int *add)
{
char *retptr;
physmem_size = memparse(line,&retptr);
return 0;
}
__uml_setup("mem=", uml_mem_setup,
"mem=<Amount of desired ram>\n"
" This controls how much \"physical\" memory the kernel allocates\n"
" for the system. The size is specified as a number followed by\n"
" one of 'k', 'K', 'm', 'M', which have the obvious meanings.\n"
" This is not related to the amount of memory in the host. It can\n"
" be more, and the excess, if it's ever used, will just be swapped out.\n"
" Example: mem=64M\n\n"
);
extern int __init parse_iomem(char *str, int *add);
__uml_setup("iomem=", parse_iomem,
"iomem=<name>,<file>\n"
" Configure <file> as an IO memory region named <name>.\n\n"
);
/*
* This list is constructed in parse_iomem and addresses filled in in
* setup_iomem, both of which run during early boot. Afterwards, it's
* unchanged.
*/
struct iomem_region *iomem_regions;
/* Initialized in parse_iomem and unchanged thereafter */
int iomem_size;
unsigned long find_iomem(char *driver, unsigned long *len_out)
{
struct iomem_region *region = iomem_regions;
while (region != NULL) {
if (!strcmp(region->driver, driver)) {
*len_out = region->size;
return region->virt;
}
region = region->next;
}
return 0;
}
static int setup_iomem(void)
{
struct iomem_region *region = iomem_regions;
unsigned long iomem_start = high_physmem + PAGE_SIZE;
int err;
while (region != NULL) {
err = os_map_memory((void *) iomem_start, region->fd, 0,
region->size, 1, 1, 0);
if (err)
printk(KERN_ERR "Mapping iomem region for driver '%s' "
"failed, errno = %d\n", region->driver, -err);
else {
region->virt = iomem_start;
region->phys = __pa(region->virt);
}
iomem_start += region->size + PAGE_SIZE;
region = region->next;
}
return 0;
}
__initcall(setup_iomem);
| gpl-2.0 |
bgly/ibmvscsi_tgt | drivers/dma/bestcomm/gen_bd.c | 4701 | 9572 | /*
* Driver for MPC52xx processor BestComm General Buffer Descriptor
*
* Copyright (C) 2007 Sylvain Munaut <tnt@246tNt.com>
* Copyright (C) 2006 AppSpec Computer Technologies Corp.
* Jeff Gibbons <jeff.gibbons@appspec.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/string.h>
#include <linux/types.h>
#include <asm/errno.h>
#include <asm/io.h>
#include <asm/mpc52xx.h>
#include <asm/mpc52xx_psc.h>
#include <linux/fsl/bestcomm/bestcomm.h>
#include <linux/fsl/bestcomm/bestcomm_priv.h>
#include <linux/fsl/bestcomm/gen_bd.h>
/* ======================================================================== */
/* Task image/var/inc */
/* ======================================================================== */
/* gen_bd tasks images */
extern u32 bcom_gen_bd_rx_task[];
extern u32 bcom_gen_bd_tx_task[];
/* rx task vars that need to be set before enabling the task */
struct bcom_gen_bd_rx_var {
u32 enable; /* (u16*) address of task's control register */
u32 fifo; /* (u32*) address of gen_bd's fifo */
u32 bd_base; /* (struct bcom_bd*) beginning of ring buffer */
u32 bd_last; /* (struct bcom_bd*) end of ring buffer */
u32 bd_start; /* (struct bcom_bd*) current bd */
u32 buffer_size; /* size of receive buffer */
};
/* rx task incs that need to be set before enabling the task */
struct bcom_gen_bd_rx_inc {
u16 pad0;
s16 incr_bytes;
u16 pad1;
s16 incr_dst;
};
/* tx task vars that need to be set before enabling the task */
struct bcom_gen_bd_tx_var {
u32 fifo; /* (u32*) address of gen_bd's fifo */
u32 enable; /* (u16*) address of task's control register */
u32 bd_base; /* (struct bcom_bd*) beginning of ring buffer */
u32 bd_last; /* (struct bcom_bd*) end of ring buffer */
u32 bd_start; /* (struct bcom_bd*) current bd */
u32 buffer_size; /* set by uCode for each packet */
};
/* tx task incs that need to be set before enabling the task */
struct bcom_gen_bd_tx_inc {
u16 pad0;
s16 incr_bytes;
u16 pad1;
s16 incr_src;
u16 pad2;
s16 incr_src_ma;
};
/* private structure */
struct bcom_gen_bd_priv {
phys_addr_t fifo;
int initiator;
int ipr;
int maxbufsize;
};
/* ======================================================================== */
/* Task support code */
/* ======================================================================== */
struct bcom_task *
bcom_gen_bd_rx_init(int queue_len, phys_addr_t fifo,
int initiator, int ipr, int maxbufsize)
{
struct bcom_task *tsk;
struct bcom_gen_bd_priv *priv;
tsk = bcom_task_alloc(queue_len, sizeof(struct bcom_gen_bd),
sizeof(struct bcom_gen_bd_priv));
if (!tsk)
return NULL;
tsk->flags = BCOM_FLAGS_NONE;
priv = tsk->priv;
priv->fifo = fifo;
priv->initiator = initiator;
priv->ipr = ipr;
priv->maxbufsize = maxbufsize;
if (bcom_gen_bd_rx_reset(tsk)) {
bcom_task_free(tsk);
return NULL;
}
return tsk;
}
EXPORT_SYMBOL_GPL(bcom_gen_bd_rx_init);
int
bcom_gen_bd_rx_reset(struct bcom_task *tsk)
{
struct bcom_gen_bd_priv *priv = tsk->priv;
struct bcom_gen_bd_rx_var *var;
struct bcom_gen_bd_rx_inc *inc;
/* Shutdown the task */
bcom_disable_task(tsk->tasknum);
/* Reset the microcode */
var = (struct bcom_gen_bd_rx_var *) bcom_task_var(tsk->tasknum);
inc = (struct bcom_gen_bd_rx_inc *) bcom_task_inc(tsk->tasknum);
if (bcom_load_image(tsk->tasknum, bcom_gen_bd_rx_task))
return -1;
var->enable = bcom_eng->regs_base +
offsetof(struct mpc52xx_sdma, tcr[tsk->tasknum]);
var->fifo = (u32) priv->fifo;
var->bd_base = tsk->bd_pa;
var->bd_last = tsk->bd_pa + ((tsk->num_bd-1) * tsk->bd_size);
var->bd_start = tsk->bd_pa;
var->buffer_size = priv->maxbufsize;
inc->incr_bytes = -(s16)sizeof(u32);
inc->incr_dst = sizeof(u32);
/* Reset the BDs */
tsk->index = 0;
tsk->outdex = 0;
memset(tsk->bd, 0x00, tsk->num_bd * tsk->bd_size);
/* Configure some stuff */
bcom_set_task_pragma(tsk->tasknum, BCOM_GEN_RX_BD_PRAGMA);
bcom_set_task_auto_start(tsk->tasknum, tsk->tasknum);
out_8(&bcom_eng->regs->ipr[priv->initiator], priv->ipr);
bcom_set_initiator(tsk->tasknum, priv->initiator);
out_be32(&bcom_eng->regs->IntPend, 1<<tsk->tasknum); /* Clear ints */
return 0;
}
EXPORT_SYMBOL_GPL(bcom_gen_bd_rx_reset);
void
bcom_gen_bd_rx_release(struct bcom_task *tsk)
{
/* Nothing special for the GenBD tasks */
bcom_task_free(tsk);
}
EXPORT_SYMBOL_GPL(bcom_gen_bd_rx_release);
extern struct bcom_task *
bcom_gen_bd_tx_init(int queue_len, phys_addr_t fifo,
int initiator, int ipr)
{
struct bcom_task *tsk;
struct bcom_gen_bd_priv *priv;
tsk = bcom_task_alloc(queue_len, sizeof(struct bcom_gen_bd),
sizeof(struct bcom_gen_bd_priv));
if (!tsk)
return NULL;
tsk->flags = BCOM_FLAGS_NONE;
priv = tsk->priv;
priv->fifo = fifo;
priv->initiator = initiator;
priv->ipr = ipr;
if (bcom_gen_bd_tx_reset(tsk)) {
bcom_task_free(tsk);
return NULL;
}
return tsk;
}
EXPORT_SYMBOL_GPL(bcom_gen_bd_tx_init);
int
bcom_gen_bd_tx_reset(struct bcom_task *tsk)
{
struct bcom_gen_bd_priv *priv = tsk->priv;
struct bcom_gen_bd_tx_var *var;
struct bcom_gen_bd_tx_inc *inc;
/* Shutdown the task */
bcom_disable_task(tsk->tasknum);
/* Reset the microcode */
var = (struct bcom_gen_bd_tx_var *) bcom_task_var(tsk->tasknum);
inc = (struct bcom_gen_bd_tx_inc *) bcom_task_inc(tsk->tasknum);
if (bcom_load_image(tsk->tasknum, bcom_gen_bd_tx_task))
return -1;
var->enable = bcom_eng->regs_base +
offsetof(struct mpc52xx_sdma, tcr[tsk->tasknum]);
var->fifo = (u32) priv->fifo;
var->bd_base = tsk->bd_pa;
var->bd_last = tsk->bd_pa + ((tsk->num_bd-1) * tsk->bd_size);
var->bd_start = tsk->bd_pa;
inc->incr_bytes = -(s16)sizeof(u32);
inc->incr_src = sizeof(u32);
inc->incr_src_ma = sizeof(u8);
/* Reset the BDs */
tsk->index = 0;
tsk->outdex = 0;
memset(tsk->bd, 0x00, tsk->num_bd * tsk->bd_size);
/* Configure some stuff */
bcom_set_task_pragma(tsk->tasknum, BCOM_GEN_TX_BD_PRAGMA);
bcom_set_task_auto_start(tsk->tasknum, tsk->tasknum);
out_8(&bcom_eng->regs->ipr[priv->initiator], priv->ipr);
bcom_set_initiator(tsk->tasknum, priv->initiator);
out_be32(&bcom_eng->regs->IntPend, 1<<tsk->tasknum); /* Clear ints */
return 0;
}
EXPORT_SYMBOL_GPL(bcom_gen_bd_tx_reset);
void
bcom_gen_bd_tx_release(struct bcom_task *tsk)
{
/* Nothing special for the GenBD tasks */
bcom_task_free(tsk);
}
EXPORT_SYMBOL_GPL(bcom_gen_bd_tx_release);
/* ---------------------------------------------------------------------
* PSC support code
*/
/**
* bcom_psc_parameters - Bestcomm initialization value table for PSC devices
*
* This structure is only used internally. It is a lookup table for PSC
* specific parameters to bestcomm tasks.
*/
static struct bcom_psc_params {
int rx_initiator;
int rx_ipr;
int tx_initiator;
int tx_ipr;
} bcom_psc_params[] = {
[0] = {
.rx_initiator = BCOM_INITIATOR_PSC1_RX,
.rx_ipr = BCOM_IPR_PSC1_RX,
.tx_initiator = BCOM_INITIATOR_PSC1_TX,
.tx_ipr = BCOM_IPR_PSC1_TX,
},
[1] = {
.rx_initiator = BCOM_INITIATOR_PSC2_RX,
.rx_ipr = BCOM_IPR_PSC2_RX,
.tx_initiator = BCOM_INITIATOR_PSC2_TX,
.tx_ipr = BCOM_IPR_PSC2_TX,
},
[2] = {
.rx_initiator = BCOM_INITIATOR_PSC3_RX,
.rx_ipr = BCOM_IPR_PSC3_RX,
.tx_initiator = BCOM_INITIATOR_PSC3_TX,
.tx_ipr = BCOM_IPR_PSC3_TX,
},
[3] = {
.rx_initiator = BCOM_INITIATOR_PSC4_RX,
.rx_ipr = BCOM_IPR_PSC4_RX,
.tx_initiator = BCOM_INITIATOR_PSC4_TX,
.tx_ipr = BCOM_IPR_PSC4_TX,
},
[4] = {
.rx_initiator = BCOM_INITIATOR_PSC5_RX,
.rx_ipr = BCOM_IPR_PSC5_RX,
.tx_initiator = BCOM_INITIATOR_PSC5_TX,
.tx_ipr = BCOM_IPR_PSC5_TX,
},
[5] = {
.rx_initiator = BCOM_INITIATOR_PSC6_RX,
.rx_ipr = BCOM_IPR_PSC6_RX,
.tx_initiator = BCOM_INITIATOR_PSC6_TX,
.tx_ipr = BCOM_IPR_PSC6_TX,
},
};
/**
* bcom_psc_gen_bd_rx_init - Allocate a receive bcom_task for a PSC port
* @psc_num: Number of the PSC to allocate a task for
* @queue_len: number of buffer descriptors to allocate for the task
* @fifo: physical address of FIFO register
* @maxbufsize: Maximum receive data size in bytes.
*
* Allocate a bestcomm task structure for receiving data from a PSC.
*/
struct bcom_task * bcom_psc_gen_bd_rx_init(unsigned psc_num, int queue_len,
phys_addr_t fifo, int maxbufsize)
{
if (psc_num >= MPC52xx_PSC_MAXNUM)
return NULL;
return bcom_gen_bd_rx_init(queue_len, fifo,
bcom_psc_params[psc_num].rx_initiator,
bcom_psc_params[psc_num].rx_ipr,
maxbufsize);
}
EXPORT_SYMBOL_GPL(bcom_psc_gen_bd_rx_init);
/**
* bcom_psc_gen_bd_tx_init - Allocate a transmit bcom_task for a PSC port
* @psc_num: Number of the PSC to allocate a task for
* @queue_len: number of buffer descriptors to allocate for the task
* @fifo: physical address of FIFO register
*
* Allocate a bestcomm task structure for transmitting data to a PSC.
*/
struct bcom_task *
bcom_psc_gen_bd_tx_init(unsigned psc_num, int queue_len, phys_addr_t fifo)
{
struct psc;
return bcom_gen_bd_tx_init(queue_len, fifo,
bcom_psc_params[psc_num].tx_initiator,
bcom_psc_params[psc_num].tx_ipr);
}
EXPORT_SYMBOL_GPL(bcom_psc_gen_bd_tx_init);
MODULE_DESCRIPTION("BestComm General Buffer Descriptor tasks driver");
MODULE_AUTHOR("Jeff Gibbons <jeff.gibbons@appspec.com>");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
slz/arco-samsung-kernel-msm7x30 | arch/arm/mach-pxa/am300epd.c | 4957 | 6586 | /*
* am300epd.c -- Platform device for AM300 EPD kit
*
* Copyright (C) 2008, Jaya Kumar
*
* 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.
*
* This work was made possible by help and equipment support from E-Ink
* Corporation. http://support.eink.com/community
*
* This driver is written to be used with the Broadsheet display controller.
* on the AM300 EPD prototype kit/development kit with an E-Ink 800x600
* Vizplex EPD on a Gumstix board using the Broadsheet interface board.
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/fb.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/irq.h>
#include <linux/gpio.h>
#include <mach/gumstix.h>
#include <mach/mfp-pxa25x.h>
#include <mach/pxafb.h>
#include "generic.h"
#include <video/broadsheetfb.h>
static unsigned int panel_type = 6;
static struct platform_device *am300_device;
static struct broadsheet_board am300_board;
static unsigned long am300_pin_config[] __initdata = {
GPIO16_GPIO,
GPIO17_GPIO,
GPIO32_GPIO,
GPIO48_GPIO,
GPIO49_GPIO,
GPIO51_GPIO,
GPIO74_GPIO,
GPIO75_GPIO,
GPIO76_GPIO,
GPIO77_GPIO,
/* this is the 16-bit hdb bus 58-73 */
GPIO58_GPIO,
GPIO59_GPIO,
GPIO60_GPIO,
GPIO61_GPIO,
GPIO62_GPIO,
GPIO63_GPIO,
GPIO64_GPIO,
GPIO65_GPIO,
GPIO66_GPIO,
GPIO67_GPIO,
GPIO68_GPIO,
GPIO69_GPIO,
GPIO70_GPIO,
GPIO71_GPIO,
GPIO72_GPIO,
GPIO73_GPIO,
};
/* register offsets for gpio control */
#define PWR_GPIO_PIN 16
#define CFG_GPIO_PIN 17
#define RDY_GPIO_PIN 32
#define DC_GPIO_PIN 48
#define RST_GPIO_PIN 49
#define LED_GPIO_PIN 51
#define RD_GPIO_PIN 74
#define WR_GPIO_PIN 75
#define CS_GPIO_PIN 76
#define IRQ_GPIO_PIN 77
/* hdb bus */
#define DB0_GPIO_PIN 58
#define DB15_GPIO_PIN 73
static int gpios[] = { PWR_GPIO_PIN, CFG_GPIO_PIN, RDY_GPIO_PIN, DC_GPIO_PIN,
RST_GPIO_PIN, RD_GPIO_PIN, WR_GPIO_PIN, CS_GPIO_PIN,
IRQ_GPIO_PIN, LED_GPIO_PIN };
static char *gpio_names[] = { "PWR", "CFG", "RDY", "DC", "RST", "RD", "WR",
"CS", "IRQ", "LED" };
static int am300_wait_event(struct broadsheetfb_par *par)
{
/* todo: improve err recovery */
wait_event(par->waitq, gpio_get_value(RDY_GPIO_PIN));
return 0;
}
static int am300_init_gpio_regs(struct broadsheetfb_par *par)
{
int i;
int err;
char dbname[8];
for (i = 0; i < ARRAY_SIZE(gpios); i++) {
err = gpio_request(gpios[i], gpio_names[i]);
if (err) {
dev_err(&am300_device->dev, "failed requesting "
"gpio %s, err=%d\n", gpio_names[i], err);
goto err_req_gpio;
}
}
/* we also need to take care of the hdb bus */
for (i = DB0_GPIO_PIN; i <= DB15_GPIO_PIN; i++) {
sprintf(dbname, "DB%d", i);
err = gpio_request(i, dbname);
if (err) {
dev_err(&am300_device->dev, "failed requesting "
"gpio %d, err=%d\n", i, err);
goto err_req_gpio2;
}
}
/* setup the outputs and init values */
gpio_direction_output(PWR_GPIO_PIN, 0);
gpio_direction_output(CFG_GPIO_PIN, 1);
gpio_direction_output(DC_GPIO_PIN, 0);
gpio_direction_output(RD_GPIO_PIN, 1);
gpio_direction_output(WR_GPIO_PIN, 1);
gpio_direction_output(CS_GPIO_PIN, 1);
gpio_direction_output(RST_GPIO_PIN, 0);
/* setup the inputs */
gpio_direction_input(RDY_GPIO_PIN);
gpio_direction_input(IRQ_GPIO_PIN);
/* start the hdb bus as an input */
for (i = DB0_GPIO_PIN; i <= DB15_GPIO_PIN; i++)
gpio_direction_output(i, 0);
/* go into command mode */
gpio_set_value(CFG_GPIO_PIN, 1);
gpio_set_value(RST_GPIO_PIN, 0);
msleep(10);
gpio_set_value(RST_GPIO_PIN, 1);
msleep(10);
am300_wait_event(par);
return 0;
err_req_gpio2:
while (--i >= DB0_GPIO_PIN)
gpio_free(i);
i = ARRAY_SIZE(gpios);
err_req_gpio:
while (--i >= 0)
gpio_free(gpios[i]);
return err;
}
static int am300_init_board(struct broadsheetfb_par *par)
{
return am300_init_gpio_regs(par);
}
static void am300_cleanup(struct broadsheetfb_par *par)
{
int i;
free_irq(PXA_GPIO_TO_IRQ(RDY_GPIO_PIN), par);
for (i = 0; i < ARRAY_SIZE(gpios); i++)
gpio_free(gpios[i]);
for (i = DB0_GPIO_PIN; i <= DB15_GPIO_PIN; i++)
gpio_free(i);
}
static u16 am300_get_hdb(struct broadsheetfb_par *par)
{
u16 res = 0;
int i;
for (i = 0; i <= (DB15_GPIO_PIN - DB0_GPIO_PIN) ; i++)
res |= (gpio_get_value(DB0_GPIO_PIN + i)) ? (1 << i) : 0;
return res;
}
static void am300_set_hdb(struct broadsheetfb_par *par, u16 data)
{
int i;
for (i = 0; i <= (DB15_GPIO_PIN - DB0_GPIO_PIN) ; i++)
gpio_set_value(DB0_GPIO_PIN + i, (data >> i) & 0x01);
}
static void am300_set_ctl(struct broadsheetfb_par *par, unsigned char bit,
u8 state)
{
switch (bit) {
case BS_CS:
gpio_set_value(CS_GPIO_PIN, state);
break;
case BS_DC:
gpio_set_value(DC_GPIO_PIN, state);
break;
case BS_WR:
gpio_set_value(WR_GPIO_PIN, state);
break;
}
}
static int am300_get_panel_type(void)
{
return panel_type;
}
static irqreturn_t am300_handle_irq(int irq, void *dev_id)
{
struct broadsheetfb_par *par = dev_id;
wake_up(&par->waitq);
return IRQ_HANDLED;
}
static int am300_setup_irq(struct fb_info *info)
{
int ret;
struct broadsheetfb_par *par = info->par;
ret = request_irq(PXA_GPIO_TO_IRQ(RDY_GPIO_PIN), am300_handle_irq,
IRQF_DISABLED|IRQF_TRIGGER_RISING,
"AM300", par);
if (ret)
dev_err(&am300_device->dev, "request_irq failed: %d\n", ret);
return ret;
}
static struct broadsheet_board am300_board = {
.owner = THIS_MODULE,
.init = am300_init_board,
.cleanup = am300_cleanup,
.set_hdb = am300_set_hdb,
.get_hdb = am300_get_hdb,
.set_ctl = am300_set_ctl,
.wait_for_rdy = am300_wait_event,
.get_panel_type = am300_get_panel_type,
.setup_irq = am300_setup_irq,
};
int __init am300_init(void)
{
int ret;
pxa2xx_mfp_config(ARRAY_AND_SIZE(am300_pin_config));
/* request our platform independent driver */
request_module("broadsheetfb");
am300_device = platform_device_alloc("broadsheetfb", -1);
if (!am300_device)
return -ENOMEM;
/* the am300_board that will be seen by broadsheetfb is a copy */
platform_device_add_data(am300_device, &am300_board,
sizeof(am300_board));
ret = platform_device_add(am300_device);
if (ret) {
platform_device_put(am300_device);
return ret;
}
return 0;
}
module_param(panel_type, uint, 0);
MODULE_PARM_DESC(panel_type, "Select the panel type: 37, 6, 97");
MODULE_DESCRIPTION("board driver for am300 epd kit");
MODULE_AUTHOR("Jaya Kumar");
MODULE_LICENSE("GPL");
| gpl-2.0 |
myjang0507/Polaris | drivers/dca/dca-core.c | 5725 | 11284 | /*
* Copyright(c) 2007 - 2009 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59
* Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* The full GNU General Public License is included in this distribution in the
* file called COPYING.
*/
/*
* This driver supports an interface for DCA clients and providers to meet.
*/
#include <linux/kernel.h>
#include <linux/notifier.h>
#include <linux/device.h>
#include <linux/dca.h>
#include <linux/slab.h>
#include <linux/module.h>
#define DCA_VERSION "1.12.1"
MODULE_VERSION(DCA_VERSION);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Intel Corporation");
static DEFINE_RAW_SPINLOCK(dca_lock);
static LIST_HEAD(dca_domains);
static BLOCKING_NOTIFIER_HEAD(dca_provider_chain);
static int dca_providers_blocked;
static struct pci_bus *dca_pci_rc_from_dev(struct device *dev)
{
struct pci_dev *pdev = to_pci_dev(dev);
struct pci_bus *bus = pdev->bus;
while (bus->parent)
bus = bus->parent;
return bus;
}
static struct dca_domain *dca_allocate_domain(struct pci_bus *rc)
{
struct dca_domain *domain;
domain = kzalloc(sizeof(*domain), GFP_NOWAIT);
if (!domain)
return NULL;
INIT_LIST_HEAD(&domain->dca_providers);
domain->pci_rc = rc;
return domain;
}
static void dca_free_domain(struct dca_domain *domain)
{
list_del(&domain->node);
kfree(domain);
}
static int dca_provider_ioat_ver_3_0(struct device *dev)
{
struct pci_dev *pdev = to_pci_dev(dev);
return ((pdev->vendor == PCI_VENDOR_ID_INTEL) &&
((pdev->device == PCI_DEVICE_ID_INTEL_IOAT_TBG0) ||
(pdev->device == PCI_DEVICE_ID_INTEL_IOAT_TBG1) ||
(pdev->device == PCI_DEVICE_ID_INTEL_IOAT_TBG2) ||
(pdev->device == PCI_DEVICE_ID_INTEL_IOAT_TBG3) ||
(pdev->device == PCI_DEVICE_ID_INTEL_IOAT_TBG4) ||
(pdev->device == PCI_DEVICE_ID_INTEL_IOAT_TBG5) ||
(pdev->device == PCI_DEVICE_ID_INTEL_IOAT_TBG6) ||
(pdev->device == PCI_DEVICE_ID_INTEL_IOAT_TBG7)));
}
static void unregister_dca_providers(void)
{
struct dca_provider *dca, *_dca;
struct list_head unregistered_providers;
struct dca_domain *domain;
unsigned long flags;
blocking_notifier_call_chain(&dca_provider_chain,
DCA_PROVIDER_REMOVE, NULL);
INIT_LIST_HEAD(&unregistered_providers);
raw_spin_lock_irqsave(&dca_lock, flags);
if (list_empty(&dca_domains)) {
raw_spin_unlock_irqrestore(&dca_lock, flags);
return;
}
/* at this point only one domain in the list is expected */
domain = list_first_entry(&dca_domains, struct dca_domain, node);
list_for_each_entry_safe(dca, _dca, &domain->dca_providers, node)
list_move(&dca->node, &unregistered_providers);
dca_free_domain(domain);
raw_spin_unlock_irqrestore(&dca_lock, flags);
list_for_each_entry_safe(dca, _dca, &unregistered_providers, node) {
dca_sysfs_remove_provider(dca);
list_del(&dca->node);
}
}
static struct dca_domain *dca_find_domain(struct pci_bus *rc)
{
struct dca_domain *domain;
list_for_each_entry(domain, &dca_domains, node)
if (domain->pci_rc == rc)
return domain;
return NULL;
}
static struct dca_domain *dca_get_domain(struct device *dev)
{
struct pci_bus *rc;
struct dca_domain *domain;
rc = dca_pci_rc_from_dev(dev);
domain = dca_find_domain(rc);
if (!domain) {
if (dca_provider_ioat_ver_3_0(dev) && !list_empty(&dca_domains))
dca_providers_blocked = 1;
}
return domain;
}
static struct dca_provider *dca_find_provider_by_dev(struct device *dev)
{
struct dca_provider *dca;
struct pci_bus *rc;
struct dca_domain *domain;
if (dev) {
rc = dca_pci_rc_from_dev(dev);
domain = dca_find_domain(rc);
if (!domain)
return NULL;
} else {
if (!list_empty(&dca_domains))
domain = list_first_entry(&dca_domains,
struct dca_domain,
node);
else
return NULL;
}
list_for_each_entry(dca, &domain->dca_providers, node)
if ((!dev) || (dca->ops->dev_managed(dca, dev)))
return dca;
return NULL;
}
/**
* dca_add_requester - add a dca client to the list
* @dev - the device that wants dca service
*/
int dca_add_requester(struct device *dev)
{
struct dca_provider *dca;
int err, slot = -ENODEV;
unsigned long flags;
struct pci_bus *pci_rc;
struct dca_domain *domain;
if (!dev)
return -EFAULT;
raw_spin_lock_irqsave(&dca_lock, flags);
/* check if the requester has not been added already */
dca = dca_find_provider_by_dev(dev);
if (dca) {
raw_spin_unlock_irqrestore(&dca_lock, flags);
return -EEXIST;
}
pci_rc = dca_pci_rc_from_dev(dev);
domain = dca_find_domain(pci_rc);
if (!domain) {
raw_spin_unlock_irqrestore(&dca_lock, flags);
return -ENODEV;
}
list_for_each_entry(dca, &domain->dca_providers, node) {
slot = dca->ops->add_requester(dca, dev);
if (slot >= 0)
break;
}
raw_spin_unlock_irqrestore(&dca_lock, flags);
if (slot < 0)
return slot;
err = dca_sysfs_add_req(dca, dev, slot);
if (err) {
raw_spin_lock_irqsave(&dca_lock, flags);
if (dca == dca_find_provider_by_dev(dev))
dca->ops->remove_requester(dca, dev);
raw_spin_unlock_irqrestore(&dca_lock, flags);
return err;
}
return 0;
}
EXPORT_SYMBOL_GPL(dca_add_requester);
/**
* dca_remove_requester - remove a dca client from the list
* @dev - the device that wants dca service
*/
int dca_remove_requester(struct device *dev)
{
struct dca_provider *dca;
int slot;
unsigned long flags;
if (!dev)
return -EFAULT;
raw_spin_lock_irqsave(&dca_lock, flags);
dca = dca_find_provider_by_dev(dev);
if (!dca) {
raw_spin_unlock_irqrestore(&dca_lock, flags);
return -ENODEV;
}
slot = dca->ops->remove_requester(dca, dev);
raw_spin_unlock_irqrestore(&dca_lock, flags);
if (slot < 0)
return slot;
dca_sysfs_remove_req(dca, slot);
return 0;
}
EXPORT_SYMBOL_GPL(dca_remove_requester);
/**
* dca_common_get_tag - return the dca tag (serves both new and old api)
* @dev - the device that wants dca service
* @cpu - the cpuid as returned by get_cpu()
*/
u8 dca_common_get_tag(struct device *dev, int cpu)
{
struct dca_provider *dca;
u8 tag;
unsigned long flags;
raw_spin_lock_irqsave(&dca_lock, flags);
dca = dca_find_provider_by_dev(dev);
if (!dca) {
raw_spin_unlock_irqrestore(&dca_lock, flags);
return -ENODEV;
}
tag = dca->ops->get_tag(dca, dev, cpu);
raw_spin_unlock_irqrestore(&dca_lock, flags);
return tag;
}
/**
* dca3_get_tag - return the dca tag to the requester device
* for the given cpu (new api)
* @dev - the device that wants dca service
* @cpu - the cpuid as returned by get_cpu()
*/
u8 dca3_get_tag(struct device *dev, int cpu)
{
if (!dev)
return -EFAULT;
return dca_common_get_tag(dev, cpu);
}
EXPORT_SYMBOL_GPL(dca3_get_tag);
/**
* dca_get_tag - return the dca tag for the given cpu (old api)
* @cpu - the cpuid as returned by get_cpu()
*/
u8 dca_get_tag(int cpu)
{
struct device *dev = NULL;
return dca_common_get_tag(dev, cpu);
}
EXPORT_SYMBOL_GPL(dca_get_tag);
/**
* alloc_dca_provider - get data struct for describing a dca provider
* @ops - pointer to struct of dca operation function pointers
* @priv_size - size of extra mem to be added for provider's needs
*/
struct dca_provider *alloc_dca_provider(struct dca_ops *ops, int priv_size)
{
struct dca_provider *dca;
int alloc_size;
alloc_size = (sizeof(*dca) + priv_size);
dca = kzalloc(alloc_size, GFP_KERNEL);
if (!dca)
return NULL;
dca->ops = ops;
return dca;
}
EXPORT_SYMBOL_GPL(alloc_dca_provider);
/**
* free_dca_provider - release the dca provider data struct
* @ops - pointer to struct of dca operation function pointers
* @priv_size - size of extra mem to be added for provider's needs
*/
void free_dca_provider(struct dca_provider *dca)
{
kfree(dca);
}
EXPORT_SYMBOL_GPL(free_dca_provider);
/**
* register_dca_provider - register a dca provider
* @dca - struct created by alloc_dca_provider()
* @dev - device providing dca services
*/
int register_dca_provider(struct dca_provider *dca, struct device *dev)
{
int err;
unsigned long flags;
struct dca_domain *domain, *newdomain = NULL;
raw_spin_lock_irqsave(&dca_lock, flags);
if (dca_providers_blocked) {
raw_spin_unlock_irqrestore(&dca_lock, flags);
return -ENODEV;
}
raw_spin_unlock_irqrestore(&dca_lock, flags);
err = dca_sysfs_add_provider(dca, dev);
if (err)
return err;
raw_spin_lock_irqsave(&dca_lock, flags);
domain = dca_get_domain(dev);
if (!domain) {
struct pci_bus *rc;
if (dca_providers_blocked) {
raw_spin_unlock_irqrestore(&dca_lock, flags);
dca_sysfs_remove_provider(dca);
unregister_dca_providers();
return -ENODEV;
}
raw_spin_unlock_irqrestore(&dca_lock, flags);
rc = dca_pci_rc_from_dev(dev);
newdomain = dca_allocate_domain(rc);
if (!newdomain)
return -ENODEV;
raw_spin_lock_irqsave(&dca_lock, flags);
/* Recheck, we might have raced after dropping the lock */
domain = dca_get_domain(dev);
if (!domain) {
domain = newdomain;
newdomain = NULL;
list_add(&domain->node, &dca_domains);
}
}
list_add(&dca->node, &domain->dca_providers);
raw_spin_unlock_irqrestore(&dca_lock, flags);
blocking_notifier_call_chain(&dca_provider_chain,
DCA_PROVIDER_ADD, NULL);
kfree(newdomain);
return 0;
}
EXPORT_SYMBOL_GPL(register_dca_provider);
/**
* unregister_dca_provider - remove a dca provider
* @dca - struct created by alloc_dca_provider()
*/
void unregister_dca_provider(struct dca_provider *dca, struct device *dev)
{
unsigned long flags;
struct pci_bus *pci_rc;
struct dca_domain *domain;
blocking_notifier_call_chain(&dca_provider_chain,
DCA_PROVIDER_REMOVE, NULL);
raw_spin_lock_irqsave(&dca_lock, flags);
if (list_empty(&dca_domains)) {
raw_spin_unlock_irqrestore(&dca_lock, flags);
return;
}
list_del(&dca->node);
pci_rc = dca_pci_rc_from_dev(dev);
domain = dca_find_domain(pci_rc);
if (list_empty(&domain->dca_providers))
dca_free_domain(domain);
raw_spin_unlock_irqrestore(&dca_lock, flags);
dca_sysfs_remove_provider(dca);
}
EXPORT_SYMBOL_GPL(unregister_dca_provider);
/**
* dca_register_notify - register a client's notifier callback
*/
void dca_register_notify(struct notifier_block *nb)
{
blocking_notifier_chain_register(&dca_provider_chain, nb);
}
EXPORT_SYMBOL_GPL(dca_register_notify);
/**
* dca_unregister_notify - remove a client's notifier callback
*/
void dca_unregister_notify(struct notifier_block *nb)
{
blocking_notifier_chain_unregister(&dca_provider_chain, nb);
}
EXPORT_SYMBOL_GPL(dca_unregister_notify);
static int __init dca_init(void)
{
pr_info("dca service started, version %s\n", DCA_VERSION);
return dca_sysfs_init();
}
static void __exit dca_exit(void)
{
dca_sysfs_exit();
}
arch_initcall(dca_init);
module_exit(dca_exit);
| gpl-2.0 |
ThinkingBridge/platform_kernel_lge_hammerhead | arch/sh/kernel/cpu/irq/imask.c | 9053 | 1938 | /*
* arch/sh/kernel/cpu/irq/imask.c
*
* Copyright (C) 1999, 2000 Niibe Yutaka
*
* Simple interrupt handling using IMASK of SR register.
*
*/
/* NOTE: Will not work on level 15 */
#include <linux/ptrace.h>
#include <linux/errno.h>
#include <linux/kernel_stat.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/bitops.h>
#include <linux/spinlock.h>
#include <linux/cache.h>
#include <linux/irq.h>
#include <linux/bitmap.h>
#include <asm/irq.h>
/* Bitmap of IRQ masked */
#define IMASK_PRIORITY 15
static DECLARE_BITMAP(imask_mask, IMASK_PRIORITY);
static int interrupt_priority;
static inline void set_interrupt_registers(int ip)
{
unsigned long __dummy;
asm volatile(
#ifdef CONFIG_CPU_HAS_SR_RB
"ldc %2, r6_bank\n\t"
#endif
"stc sr, %0\n\t"
"and #0xf0, %0\n\t"
"shlr2 %0\n\t"
"cmp/eq #0x3c, %0\n\t"
"bt/s 1f ! CLI-ed\n\t"
" stc sr, %0\n\t"
"and %1, %0\n\t"
"or %2, %0\n\t"
"ldc %0, sr\n"
"1:"
: "=&z" (__dummy)
: "r" (~0xf0), "r" (ip << 4)
: "t");
}
static void mask_imask_irq(struct irq_data *data)
{
unsigned int irq = data->irq;
clear_bit(irq, imask_mask);
if (interrupt_priority < IMASK_PRIORITY - irq)
interrupt_priority = IMASK_PRIORITY - irq;
set_interrupt_registers(interrupt_priority);
}
static void unmask_imask_irq(struct irq_data *data)
{
unsigned int irq = data->irq;
set_bit(irq, imask_mask);
interrupt_priority = IMASK_PRIORITY -
find_first_zero_bit(imask_mask, IMASK_PRIORITY);
set_interrupt_registers(interrupt_priority);
}
static struct irq_chip imask_irq_chip = {
.name = "SR.IMASK",
.irq_mask = mask_imask_irq,
.irq_unmask = unmask_imask_irq,
.irq_mask_ack = mask_imask_irq,
};
void make_imask_irq(unsigned int irq)
{
irq_set_chip_and_handler_name(irq, &imask_irq_chip, handle_level_irq,
"level");
}
| gpl-2.0 |
ztc1997/android_kernel_sony_msm8974ac | arch/sh/kernel/reboot.c | 9053 | 1781 | #include <linux/pm.h>
#include <linux/kexec.h>
#include <linux/kernel.h>
#include <linux/reboot.h>
#include <linux/module.h>
#ifdef CONFIG_SUPERH32
#include <asm/watchdog.h>
#endif
#include <asm/addrspace.h>
#include <asm/reboot.h>
#include <asm/tlbflush.h>
#include <asm/traps.h>
void (*pm_power_off)(void);
EXPORT_SYMBOL(pm_power_off);
#ifdef CONFIG_SUPERH32
static void watchdog_trigger_immediate(void)
{
sh_wdt_write_cnt(0xFF);
sh_wdt_write_csr(0xC2);
}
#endif
static void native_machine_restart(char * __unused)
{
local_irq_disable();
/* Destroy all of the TLBs in preparation for reset by MMU */
__flush_tlb_global();
/* Address error with SR.BL=1 first. */
trigger_address_error();
#ifdef CONFIG_SUPERH32
/* If that fails or is unsupported, go for the watchdog next. */
watchdog_trigger_immediate();
#endif
/*
* Give up and sleep.
*/
while (1)
cpu_sleep();
}
static void native_machine_shutdown(void)
{
smp_send_stop();
}
static void native_machine_power_off(void)
{
if (pm_power_off)
pm_power_off();
}
static void native_machine_halt(void)
{
/* stop other cpus */
machine_shutdown();
/* stop this cpu */
stop_this_cpu(NULL);
}
struct machine_ops machine_ops = {
.power_off = native_machine_power_off,
.shutdown = native_machine_shutdown,
.restart = native_machine_restart,
.halt = native_machine_halt,
#ifdef CONFIG_KEXEC
.crash_shutdown = native_machine_crash_shutdown,
#endif
};
void machine_power_off(void)
{
machine_ops.power_off();
}
void machine_shutdown(void)
{
machine_ops.shutdown();
}
void machine_restart(char *cmd)
{
machine_ops.restart(cmd);
}
void machine_halt(void)
{
machine_ops.halt();
}
#ifdef CONFIG_KEXEC
void machine_crash_shutdown(struct pt_regs *regs)
{
machine_ops.crash_shutdown(regs);
}
#endif
| gpl-2.0 |
TeskeVirtualSystem/odroid_mptcp | arch/mips/pnx8550/jbs/irqmap.c | 9565 | 1583 | /*
* NXP JBS board irqmap.
*
* Copyright 2005 Embedded Alley Solutions, Inc
* source@embeddealley.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 SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/init.h>
#include <int.h>
char pnx8550_irq_tab[][5] __initdata = {
[8] = { -1, PNX8550_INT_PCI_INTA, 0xff, 0xff, 0xff},
[9] = { -1, PNX8550_INT_PCI_INTA, 0xff, 0xff, 0xff},
[17] = { -1, PNX8550_INT_PCI_INTA, 0xff, 0xff, 0xff},
};
| gpl-2.0 |
crimeofheart/android_kernel_samsung_smdk4210 | arch/arm/mach-s3c64xx/setup-sdhci-gpio.c | 10589 | 1830 | /* linux/arch/arm/plat-s3c64xx/setup-sdhci-gpio.c
*
* Copyright 2008 Simtec Electronics
* Ben Dooks <ben@simtec.co.uk>
* http://armlinux.simtec.co.uk/
*
* S3C64XX - Helper functions for setting up SDHCI device(s) GPIO (HSMMC)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/gpio.h>
#include <plat/gpio-cfg.h>
#include <plat/sdhci.h>
void s3c64xx_setup_sdhci0_cfg_gpio(struct platform_device *dev, int width)
{
struct s3c_sdhci_platdata *pdata = dev->dev.platform_data;
/* Set all the necessary GPG pins to special-function 2 */
s3c_gpio_cfgrange_nopull(S3C64XX_GPG(0), 2 + width, S3C_GPIO_SFN(2));
if (pdata->cd_type == S3C_SDHCI_CD_INTERNAL) {
s3c_gpio_setpull(S3C64XX_GPG(6), S3C_GPIO_PULL_UP);
s3c_gpio_cfgpin(S3C64XX_GPG(6), S3C_GPIO_SFN(2));
}
}
void s3c64xx_setup_sdhci1_cfg_gpio(struct platform_device *dev, int width)
{
struct s3c_sdhci_platdata *pdata = dev->dev.platform_data;
/* Set all the necessary GPH pins to special-function 2 */
s3c_gpio_cfgrange_nopull(S3C64XX_GPH(0), 2 + width, S3C_GPIO_SFN(2));
if (pdata->cd_type == S3C_SDHCI_CD_INTERNAL) {
s3c_gpio_setpull(S3C64XX_GPG(6), S3C_GPIO_PULL_UP);
s3c_gpio_cfgpin(S3C64XX_GPG(6), S3C_GPIO_SFN(3));
}
}
void s3c64xx_setup_sdhci2_cfg_gpio(struct platform_device *dev, int width)
{
/* Set all the necessary GPH pins to special-function 3 */
s3c_gpio_cfgrange_nopull(S3C64XX_GPH(6), width, S3C_GPIO_SFN(3));
/* Set all the necessary GPC pins to special-function 3 */
s3c_gpio_cfgrange_nopull(S3C64XX_GPC(4), 2, S3C_GPIO_SFN(3));
}
| gpl-2.0 |
Rox-/android_kernel_samsung_s3ve3g | arch/powerpc/platforms/pasemi/misc.c | 13661 | 2282 | /*
* Copyright (C) 2007 PA Semi, Inc
*
* Parts based on arch/powerpc/sysdev/fsl_soc.c:
*
* 2006 (c) MontaVista Software, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License 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/kernel.h>
#include <linux/pci.h>
#include <linux/of.h>
#include <linux/i2c.h>
#ifdef CONFIG_I2C_BOARDINFO
/* The below is from fsl_soc.c. It's copied because since there are no
* official bus bindings at this time it doesn't make sense to share across
* the platforms, even though they happen to be common.
*/
struct i2c_driver_device {
char *of_device;
char *i2c_type;
};
static struct i2c_driver_device i2c_devices[] __initdata = {
{"dallas,ds1338", "ds1338"},
};
static int __init find_i2c_driver(struct device_node *node,
struct i2c_board_info *info)
{
int i;
for (i = 0; i < ARRAY_SIZE(i2c_devices); i++) {
if (!of_device_is_compatible(node, i2c_devices[i].of_device))
continue;
if (strlcpy(info->type, i2c_devices[i].i2c_type,
I2C_NAME_SIZE) >= I2C_NAME_SIZE)
return -ENOMEM;
return 0;
}
return -ENODEV;
}
static int __init pasemi_register_i2c_devices(void)
{
struct pci_dev *pdev;
struct device_node *adap_node;
struct device_node *node;
pdev = NULL;
while ((pdev = pci_get_device(PCI_VENDOR_ID_PASEMI, 0xa003, pdev))) {
adap_node = pci_device_to_OF_node(pdev);
if (!adap_node)
continue;
node = NULL;
while ((node = of_get_next_child(adap_node, node))) {
struct i2c_board_info info = {};
const u32 *addr;
int len;
addr = of_get_property(node, "reg", &len);
if (!addr || len < sizeof(int) ||
*addr > (1 << 10) - 1) {
printk(KERN_WARNING
"pasemi_register_i2c_devices: "
"invalid i2c device entry\n");
continue;
}
info.irq = irq_of_parse_and_map(node, 0);
if (info.irq == NO_IRQ)
info.irq = -1;
if (find_i2c_driver(node, &info) < 0)
continue;
info.addr = *addr;
i2c_register_board_info(PCI_FUNC(pdev->devfn), &info,
1);
}
}
return 0;
}
device_initcall(pasemi_register_i2c_devices);
#endif
| gpl-2.0 |
faux123/msm8660-aosp-ics | drivers/video/mb862xx/mb862xxfb_accel.c | 13917 | 8449 | /*
* drivers/mb862xx/mb862xxfb_accel.c
*
* Fujitsu Carmine/Coral-P(A)/Lime framebuffer driver acceleration support
*
* (C) 2007 Alexander Shishkin <virtuoso@slind.org>
* (C) 2009 Valentin Sitdikov <v.sitdikov@gmail.com>
* (C) 2009 Siemens AG
*
* 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/fb.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/slab.h>
#if defined(CONFIG_OF)
#include <linux/of_platform.h>
#endif
#include "mb862xxfb.h"
#include "mb862xx_reg.h"
#include "mb862xxfb_accel.h"
static void mb862xxfb_write_fifo(u32 count, u32 *data, struct fb_info *info)
{
struct mb862xxfb_par *par = info->par;
static u32 free;
u32 total = 0;
while (total < count) {
if (free) {
outreg(geo, GDC_GEO_REG_INPUT_FIFO, data[total]);
total++;
free--;
} else {
free = (u32) inreg(draw, GDC_REG_FIFO_COUNT);
}
}
}
static void mb86290fb_copyarea(struct fb_info *info,
const struct fb_copyarea *area)
{
__u32 cmd[6];
cmd[0] = (GDC_TYPE_SETREGISTER << 24) | (1 << 16) | GDC_REG_MODE_BITMAP;
/* Set raster operation */
cmd[1] = (2 << 7) | (GDC_ROP_COPY << 9);
cmd[2] = GDC_TYPE_BLTCOPYP << 24;
if (area->sx >= area->dx && area->sy >= area->dy)
cmd[2] |= GDC_CMD_BLTCOPY_TOP_LEFT << 16;
else if (area->sx >= area->dx && area->sy <= area->dy)
cmd[2] |= GDC_CMD_BLTCOPY_BOTTOM_LEFT << 16;
else if (area->sx <= area->dx && area->sy >= area->dy)
cmd[2] |= GDC_CMD_BLTCOPY_TOP_RIGHT << 16;
else
cmd[2] |= GDC_CMD_BLTCOPY_BOTTOM_RIGHT << 16;
cmd[3] = (area->sy << 16) | area->sx;
cmd[4] = (area->dy << 16) | area->dx;
cmd[5] = (area->height << 16) | area->width;
mb862xxfb_write_fifo(6, cmd, info);
}
/*
* Fill in the cmd array /GDC FIFO commands/ to draw a 1bit image.
* Make sure cmd has enough room!
*/
static void mb86290fb_imageblit1(u32 *cmd, u16 step, u16 dx, u16 dy,
u16 width, u16 height, u32 fgcolor,
u32 bgcolor, const struct fb_image *image,
struct fb_info *info)
{
int i;
unsigned const char *line;
u16 bytes;
/* set colors and raster operation regs */
cmd[0] = (GDC_TYPE_SETREGISTER << 24) | (1 << 16) | GDC_REG_MODE_BITMAP;
/* Set raster operation */
cmd[1] = (2 << 7) | (GDC_ROP_COPY << 9);
cmd[2] =
(GDC_TYPE_SETCOLORREGISTER << 24) | (GDC_CMD_BODY_FORE_COLOR << 16);
cmd[3] = fgcolor;
cmd[4] =
(GDC_TYPE_SETCOLORREGISTER << 24) | (GDC_CMD_BODY_BACK_COLOR << 16);
cmd[5] = bgcolor;
i = 0;
line = image->data;
bytes = (image->width + 7) >> 3;
/* and the image */
cmd[6] = (GDC_TYPE_DRAWBITMAPP << 24) |
(GDC_CMD_BITMAP << 16) | (2 + (step * height));
cmd[7] = (dy << 16) | dx;
cmd[8] = (height << 16) | width;
while (i < height) {
memcpy(&cmd[9 + i * step], line, step << 2);
#ifdef __LITTLE_ENDIAN
{
int k = 0;
for (k = 0; k < step; k++)
cmd[9 + i * step + k] =
cpu_to_be32(cmd[9 + i * step + k]);
}
#endif
line += bytes;
i++;
}
}
/*
* Fill in the cmd array /GDC FIFO commands/ to draw a 8bit image.
* Make sure cmd has enough room!
*/
static void mb86290fb_imageblit8(u32 *cmd, u16 step, u16 dx, u16 dy,
u16 width, u16 height, u32 fgcolor,
u32 bgcolor, const struct fb_image *image,
struct fb_info *info)
{
int i, j;
unsigned const char *line, *ptr;
u16 bytes;
cmd[0] = (GDC_TYPE_DRAWBITMAPP << 24) |
(GDC_CMD_BLT_DRAW << 16) | (2 + (height * step));
cmd[1] = (dy << 16) | dx;
cmd[2] = (height << 16) | width;
i = 0;
line = ptr = image->data;
bytes = image->width;
while (i < height) {
ptr = line;
for (j = 0; j < step; j++) {
cmd[3 + i * step + j] =
(((u32 *) (info->pseudo_palette))[*ptr]) & 0xffff;
ptr++;
cmd[3 + i * step + j] |=
((((u32 *) (info->
pseudo_palette))[*ptr]) & 0xffff) << 16;
ptr++;
}
line += bytes;
i++;
}
}
/*
* Fill in the cmd array /GDC FIFO commands/ to draw a 16bit image.
* Make sure cmd has enough room!
*/
static void mb86290fb_imageblit16(u32 *cmd, u16 step, u16 dx, u16 dy,
u16 width, u16 height, u32 fgcolor,
u32 bgcolor, const struct fb_image *image,
struct fb_info *info)
{
int i;
unsigned const char *line;
u16 bytes;
i = 0;
line = image->data;
bytes = image->width << 1;
cmd[0] = (GDC_TYPE_DRAWBITMAPP << 24) |
(GDC_CMD_BLT_DRAW << 16) | (2 + step * height);
cmd[1] = (dy << 16) | dx;
cmd[2] = (height << 16) | width;
while (i < height) {
memcpy(&cmd[3 + i * step], line, step);
line += bytes;
i++;
}
}
static void mb86290fb_imageblit(struct fb_info *info,
const struct fb_image *image)
{
int mdr;
u32 *cmd = NULL;
void (*cmdfn) (u32 *, u16, u16, u16, u16, u16, u32, u32,
const struct fb_image *, struct fb_info *) = NULL;
u32 cmdlen;
u32 fgcolor = 0, bgcolor = 0;
u16 step;
u16 width = image->width, height = image->height;
u16 dx = image->dx, dy = image->dy;
int x2, y2, vxres, vyres;
mdr = (GDC_ROP_COPY << 9);
x2 = image->dx + image->width;
y2 = image->dy + image->height;
vxres = info->var.xres_virtual;
vyres = info->var.yres_virtual;
x2 = min(x2, vxres);
y2 = min(y2, vyres);
width = x2 - dx;
height = y2 - dy;
switch (image->depth) {
case 1:
step = (width + 31) >> 5;
cmdlen = 9 + height * step;
cmdfn = mb86290fb_imageblit1;
if (info->fix.visual == FB_VISUAL_TRUECOLOR ||
info->fix.visual == FB_VISUAL_DIRECTCOLOR) {
fgcolor =
((u32 *) (info->pseudo_palette))[image->fg_color];
bgcolor =
((u32 *) (info->pseudo_palette))[image->bg_color];
} else {
fgcolor = image->fg_color;
bgcolor = image->bg_color;
}
break;
case 8:
step = (width + 1) >> 1;
cmdlen = 3 + height * step;
cmdfn = mb86290fb_imageblit8;
break;
case 16:
step = (width + 1) >> 1;
cmdlen = 3 + height * step;
cmdfn = mb86290fb_imageblit16;
break;
default:
cfb_imageblit(info, image);
return;
}
cmd = kmalloc(cmdlen * 4, GFP_DMA);
if (!cmd)
return cfb_imageblit(info, image);
cmdfn(cmd, step, dx, dy, width, height, fgcolor, bgcolor, image, info);
mb862xxfb_write_fifo(cmdlen, cmd, info);
kfree(cmd);
}
static void mb86290fb_fillrect(struct fb_info *info,
const struct fb_fillrect *rect)
{
u32 x2, y2, vxres, vyres, height, width, fg;
u32 cmd[7];
vxres = info->var.xres_virtual;
vyres = info->var.yres_virtual;
if (!rect->width || !rect->height || rect->dx > vxres
|| rect->dy > vyres)
return;
/* We could use hardware clipping but on many cards you get around
* hardware clipping by writing to framebuffer directly. */
x2 = rect->dx + rect->width;
y2 = rect->dy + rect->height;
x2 = min(x2, vxres);
y2 = min(y2, vyres);
width = x2 - rect->dx;
height = y2 - rect->dy;
if (info->fix.visual == FB_VISUAL_TRUECOLOR ||
info->fix.visual == FB_VISUAL_DIRECTCOLOR)
fg = ((u32 *) (info->pseudo_palette))[rect->color];
else
fg = rect->color;
switch (rect->rop) {
case ROP_XOR:
/* Set raster operation */
cmd[1] = (2 << 7) | (GDC_ROP_XOR << 9);
break;
case ROP_COPY:
/* Set raster operation */
cmd[1] = (2 << 7) | (GDC_ROP_COPY << 9);
break;
}
cmd[0] = (GDC_TYPE_SETREGISTER << 24) | (1 << 16) | GDC_REG_MODE_BITMAP;
/* cmd[1] set earlier */
cmd[2] =
(GDC_TYPE_SETCOLORREGISTER << 24) | (GDC_CMD_BODY_FORE_COLOR << 16);
cmd[3] = fg;
cmd[4] = (GDC_TYPE_DRAWRECTP << 24) | (GDC_CMD_BLT_FILL << 16);
cmd[5] = (rect->dy << 16) | (rect->dx);
cmd[6] = (height << 16) | width;
mb862xxfb_write_fifo(7, cmd, info);
}
void mb862xxfb_init_accel(struct fb_info *info, int xres)
{
struct mb862xxfb_par *par = info->par;
if (info->var.bits_per_pixel == 32) {
info->fbops->fb_fillrect = cfb_fillrect;
info->fbops->fb_copyarea = cfb_copyarea;
info->fbops->fb_imageblit = cfb_imageblit;
} else {
outreg(disp, GC_L0EM, 3);
info->fbops->fb_fillrect = mb86290fb_fillrect;
info->fbops->fb_copyarea = mb86290fb_copyarea;
info->fbops->fb_imageblit = mb86290fb_imageblit;
}
outreg(draw, GDC_REG_DRAW_BASE, 0);
outreg(draw, GDC_REG_MODE_MISC, 0x8000);
outreg(draw, GDC_REG_X_RESOLUTION, xres);
info->flags |=
FBINFO_HWACCEL_COPYAREA | FBINFO_HWACCEL_FILLRECT |
FBINFO_HWACCEL_IMAGEBLIT;
info->fix.accel = 0xff; /*FIXME: add right define */
}
EXPORT_SYMBOL(mb862xxfb_init_accel);
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
binkybear/flounder | arch/arm/mach-highbank/hotplug.c | 94 | 1046 | /*
* Copyright 2011 Calxeda, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/kernel.h>
#include <asm/cacheflush.h>
#include <asm/cacheflush.h>
#include "core.h"
#include "sysregs.h"
extern void secondary_startup(void);
/*
* platform-specific code to shutdown a CPU
*
*/
void __ref highbank_cpu_die(unsigned int cpu)
{
flush_cache_all();
highbank_set_cpu_jump(cpu, phys_to_virt(0));
flush_cache_louis();
highbank_set_core_pwr();
while (1)
cpu_do_idle();
}
| gpl-2.0 |
dpuyosa/android_kernel_wiko_l5460 | drivers/net/wireless/rtlwifi/usb.c | 94 | 31558 | /******************************************************************************
*
* Copyright(c) 2009-2012 Realtek Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* wlanfae <wlanfae@realtek.com>
* Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park,
* Hsinchu 300, Taiwan.
*
*****************************************************************************/
#include "wifi.h"
#include "core.h"
#include "usb.h"
#include "base.h"
#include "ps.h"
#include "rtl8192c/fw_common.h"
#include <linux/export.h>
#include <linux/module.h>
MODULE_AUTHOR("lizhaoming <chaoming_li@realsil.com.cn>");
MODULE_AUTHOR("Realtek WlanFAE <wlanfae@realtek.com>");
MODULE_AUTHOR("Larry Finger <Larry.FInger@lwfinger.net>");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("USB basic driver for rtlwifi");
#define REALTEK_USB_VENQT_READ 0xC0
#define REALTEK_USB_VENQT_WRITE 0x40
#define REALTEK_USB_VENQT_CMD_REQ 0x05
#define REALTEK_USB_VENQT_CMD_IDX 0x00
#define MAX_USBCTRL_VENDORREQ_TIMES 10
static void usbctrl_async_callback(struct urb *urb)
{
if (urb) {
/* free dr */
kfree(urb->setup_packet);
/* free databuf */
kfree(urb->transfer_buffer);
}
}
static int _usbctrl_vendorreq_async_write(struct usb_device *udev, u8 request,
u16 value, u16 index, void *pdata,
u16 len)
{
int rc;
unsigned int pipe;
u8 reqtype;
struct usb_ctrlrequest *dr;
struct urb *urb;
const u16 databuf_maxlen = REALTEK_USB_VENQT_MAX_BUF_SIZE;
u8 *databuf;
if (WARN_ON_ONCE(len > databuf_maxlen))
len = databuf_maxlen;
pipe = usb_sndctrlpipe(udev, 0); /* write_out */
reqtype = REALTEK_USB_VENQT_WRITE;
dr = kzalloc(sizeof(*dr), GFP_ATOMIC);
if (!dr)
return -ENOMEM;
databuf = kzalloc(databuf_maxlen, GFP_ATOMIC);
if (!databuf) {
kfree(dr);
return -ENOMEM;
}
urb = usb_alloc_urb(0, GFP_ATOMIC);
if (!urb) {
kfree(databuf);
kfree(dr);
return -ENOMEM;
}
dr->bRequestType = reqtype;
dr->bRequest = request;
dr->wValue = cpu_to_le16(value);
dr->wIndex = cpu_to_le16(index);
dr->wLength = cpu_to_le16(len);
/* data are already in little-endian order */
memcpy(databuf, pdata, len);
usb_fill_control_urb(urb, udev, pipe,
(unsigned char *)dr, databuf, len,
usbctrl_async_callback, NULL);
rc = usb_submit_urb(urb, GFP_ATOMIC);
if (rc < 0) {
kfree(databuf);
kfree(dr);
}
usb_free_urb(urb);
return rc;
}
static int _usbctrl_vendorreq_sync_read(struct usb_device *udev, u8 request,
u16 value, u16 index, void *pdata,
u16 len)
{
unsigned int pipe;
int status;
u8 reqtype;
int vendorreq_times = 0;
static int count;
pipe = usb_rcvctrlpipe(udev, 0); /* read_in */
reqtype = REALTEK_USB_VENQT_READ;
do {
status = usb_control_msg(udev, pipe, request, reqtype, value,
index, pdata, len, 1000);
if (status < 0) {
/* firmware download is checksumed, don't retry */
if ((value >= FW_8192C_START_ADDRESS &&
value <= FW_8192C_END_ADDRESS))
break;
} else {
break;
}
} while (++vendorreq_times < MAX_USBCTRL_VENDORREQ_TIMES);
if (status < 0 && count++ < 4)
pr_err("reg 0x%x, usbctrl_vendorreq TimeOut! status:0x%x value=0x%x\n",
value, status, *(u32 *)pdata);
return status;
}
static u32 _usb_read_sync(struct rtl_priv *rtlpriv, u32 addr, u16 len)
{
struct device *dev = rtlpriv->io.dev;
struct usb_device *udev = to_usb_device(dev);
u8 request;
u16 wvalue;
u16 index;
__le32 *data;
unsigned long flags;
spin_lock_irqsave(&rtlpriv->locks.usb_lock, flags);
if (++rtlpriv->usb_data_index >= RTL_USB_MAX_RX_COUNT)
rtlpriv->usb_data_index = 0;
data = &rtlpriv->usb_data[rtlpriv->usb_data_index];
spin_unlock_irqrestore(&rtlpriv->locks.usb_lock, flags);
request = REALTEK_USB_VENQT_CMD_REQ;
index = REALTEK_USB_VENQT_CMD_IDX; /* n/a */
wvalue = (u16)addr;
_usbctrl_vendorreq_sync_read(udev, request, wvalue, index, data, len);
return le32_to_cpu(*data);
}
static u8 _usb_read8_sync(struct rtl_priv *rtlpriv, u32 addr)
{
return (u8)_usb_read_sync(rtlpriv, addr, 1);
}
static u16 _usb_read16_sync(struct rtl_priv *rtlpriv, u32 addr)
{
return (u16)_usb_read_sync(rtlpriv, addr, 2);
}
static u32 _usb_read32_sync(struct rtl_priv *rtlpriv, u32 addr)
{
return _usb_read_sync(rtlpriv, addr, 4);
}
static void _usb_write_async(struct usb_device *udev, u32 addr, u32 val,
u16 len)
{
u8 request;
u16 wvalue;
u16 index;
__le32 data;
request = REALTEK_USB_VENQT_CMD_REQ;
index = REALTEK_USB_VENQT_CMD_IDX; /* n/a */
wvalue = (u16)(addr&0x0000ffff);
data = cpu_to_le32(val);
_usbctrl_vendorreq_async_write(udev, request, wvalue, index, &data,
len);
}
static void _usb_write8_async(struct rtl_priv *rtlpriv, u32 addr, u8 val)
{
struct device *dev = rtlpriv->io.dev;
_usb_write_async(to_usb_device(dev), addr, val, 1);
}
static void _usb_write16_async(struct rtl_priv *rtlpriv, u32 addr, u16 val)
{
struct device *dev = rtlpriv->io.dev;
_usb_write_async(to_usb_device(dev), addr, val, 2);
}
static void _usb_write32_async(struct rtl_priv *rtlpriv, u32 addr, u32 val)
{
struct device *dev = rtlpriv->io.dev;
_usb_write_async(to_usb_device(dev), addr, val, 4);
}
static void _usb_writeN_sync(struct rtl_priv *rtlpriv, u32 addr, void *data,
u16 len)
{
struct device *dev = rtlpriv->io.dev;
struct usb_device *udev = to_usb_device(dev);
u8 request = REALTEK_USB_VENQT_CMD_REQ;
u8 reqtype = REALTEK_USB_VENQT_WRITE;
u16 wvalue;
u16 index = REALTEK_USB_VENQT_CMD_IDX;
int pipe = usb_sndctrlpipe(udev, 0); /* write_out */
u8 *buffer;
wvalue = (u16)(addr & 0x0000ffff);
buffer = kmemdup(data, len, GFP_ATOMIC);
if (!buffer)
return;
usb_control_msg(udev, pipe, request, reqtype, wvalue,
index, buffer, len, 50);
kfree(buffer);
}
static void _rtl_usb_io_handler_init(struct device *dev,
struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtlpriv->io.dev = dev;
mutex_init(&rtlpriv->io.bb_mutex);
rtlpriv->io.write8_async = _usb_write8_async;
rtlpriv->io.write16_async = _usb_write16_async;
rtlpriv->io.write32_async = _usb_write32_async;
rtlpriv->io.read8_sync = _usb_read8_sync;
rtlpriv->io.read16_sync = _usb_read16_sync;
rtlpriv->io.read32_sync = _usb_read32_sync;
rtlpriv->io.writeN_sync = _usb_writeN_sync;
}
static void _rtl_usb_io_handler_release(struct ieee80211_hw *hw)
{
struct rtl_priv __maybe_unused *rtlpriv = rtl_priv(hw);
mutex_destroy(&rtlpriv->io.bb_mutex);
}
/**
*
* Default aggregation handler. Do nothing and just return the oldest skb.
*/
static struct sk_buff *_none_usb_tx_aggregate_hdl(struct ieee80211_hw *hw,
struct sk_buff_head *list)
{
return skb_dequeue(list);
}
#define IS_HIGH_SPEED_USB(udev) \
((USB_SPEED_HIGH == (udev)->speed) ? true : false)
static int _rtl_usb_init_tx(struct ieee80211_hw *hw)
{
u32 i;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
rtlusb->max_bulk_out_size = IS_HIGH_SPEED_USB(rtlusb->udev)
? USB_HIGH_SPEED_BULK_SIZE
: USB_FULL_SPEED_BULK_SIZE;
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG, "USB Max Bulk-out Size=%d\n",
rtlusb->max_bulk_out_size);
for (i = 0; i < __RTL_TXQ_NUM; i++) {
u32 ep_num = rtlusb->ep_map.ep_mapping[i];
if (!ep_num) {
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG,
"Invalid endpoint map setting!\n");
return -EINVAL;
}
}
rtlusb->usb_tx_post_hdl =
rtlpriv->cfg->usb_interface_cfg->usb_tx_post_hdl;
rtlusb->usb_tx_cleanup =
rtlpriv->cfg->usb_interface_cfg->usb_tx_cleanup;
rtlusb->usb_tx_aggregate_hdl =
(rtlpriv->cfg->usb_interface_cfg->usb_tx_aggregate_hdl)
? rtlpriv->cfg->usb_interface_cfg->usb_tx_aggregate_hdl
: &_none_usb_tx_aggregate_hdl;
init_usb_anchor(&rtlusb->tx_submitted);
for (i = 0; i < RTL_USB_MAX_EP_NUM; i++) {
skb_queue_head_init(&rtlusb->tx_skb_queue[i]);
init_usb_anchor(&rtlusb->tx_pending[i]);
}
return 0;
}
static void _rtl_rx_work(unsigned long param);
static int _rtl_usb_init_rx(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_usb_priv *usb_priv = rtl_usbpriv(hw);
struct rtl_usb *rtlusb = rtl_usbdev(usb_priv);
rtlusb->rx_max_size = rtlpriv->cfg->usb_interface_cfg->rx_max_size;
rtlusb->rx_urb_num = rtlpriv->cfg->usb_interface_cfg->rx_urb_num;
rtlusb->in_ep = rtlpriv->cfg->usb_interface_cfg->in_ep_num;
rtlusb->usb_rx_hdl = rtlpriv->cfg->usb_interface_cfg->usb_rx_hdl;
rtlusb->usb_rx_segregate_hdl =
rtlpriv->cfg->usb_interface_cfg->usb_rx_segregate_hdl;
pr_info("rx_max_size %d, rx_urb_num %d, in_ep %d\n",
rtlusb->rx_max_size, rtlusb->rx_urb_num, rtlusb->in_ep);
init_usb_anchor(&rtlusb->rx_submitted);
init_usb_anchor(&rtlusb->rx_cleanup_urbs);
skb_queue_head_init(&rtlusb->rx_queue);
rtlusb->rx_work_tasklet.func = _rtl_rx_work;
rtlusb->rx_work_tasklet.data = (unsigned long)rtlusb;
return 0;
}
static int _rtl_usb_init(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_usb_priv *usb_priv = rtl_usbpriv(hw);
struct rtl_usb *rtlusb = rtl_usbdev(usb_priv);
int err;
u8 epidx;
struct usb_interface *usb_intf = rtlusb->intf;
u8 epnums = usb_intf->cur_altsetting->desc.bNumEndpoints;
rtlusb->out_ep_nums = rtlusb->in_ep_nums = 0;
for (epidx = 0; epidx < epnums; epidx++) {
struct usb_endpoint_descriptor *pep_desc;
pep_desc = &usb_intf->cur_altsetting->endpoint[epidx].desc;
if (usb_endpoint_dir_in(pep_desc))
rtlusb->in_ep_nums++;
else if (usb_endpoint_dir_out(pep_desc))
rtlusb->out_ep_nums++;
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG,
"USB EP(0x%02x), MaxPacketSize=%d, Interval=%d\n",
pep_desc->bEndpointAddress, pep_desc->wMaxPacketSize,
pep_desc->bInterval);
}
if (rtlusb->in_ep_nums < rtlpriv->cfg->usb_interface_cfg->in_ep_num) {
pr_err("Too few input end points found\n");
return -EINVAL;
}
if (rtlusb->out_ep_nums == 0) {
pr_err("No output end points found\n");
return -EINVAL;
}
/* usb endpoint mapping */
err = rtlpriv->cfg->usb_interface_cfg->usb_endpoint_mapping(hw);
rtlusb->usb_mq_to_hwq = rtlpriv->cfg->usb_interface_cfg->usb_mq_to_hwq;
_rtl_usb_init_tx(hw);
_rtl_usb_init_rx(hw);
return err;
}
static void rtl_usb_init_sw(struct ieee80211_hw *hw)
{
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
rtlhal->hw = hw;
ppsc->inactiveps = false;
ppsc->leisure_ps = false;
ppsc->fwctrl_lps = false;
ppsc->reg_fwctrl_lps = 3;
ppsc->reg_max_lps_awakeintvl = 5;
ppsc->fwctrl_psmode = FW_PS_DTIM_MODE;
/* IBSS */
mac->beacon_interval = 100;
/* AMPDU */
mac->min_space_cfg = 0;
mac->max_mss_density = 0;
/* set sane AMPDU defaults */
mac->current_ampdu_density = 7;
mac->current_ampdu_factor = 3;
/* QOS */
rtlusb->acm_method = EACMWAY2_SW;
/* IRQ */
/* HIMR - turn all on */
rtlusb->irq_mask[0] = 0xFFFFFFFF;
/* HIMR_EX - turn all on */
rtlusb->irq_mask[1] = 0xFFFFFFFF;
rtlusb->disableHWSM = true;
}
static void _rtl_rx_completed(struct urb *urb);
static int _rtl_prep_rx_urb(struct ieee80211_hw *hw, struct rtl_usb *rtlusb,
struct urb *urb, gfp_t gfp_mask)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
void *buf;
buf = usb_alloc_coherent(rtlusb->udev, rtlusb->rx_max_size, gfp_mask,
&urb->transfer_dma);
if (!buf) {
RT_TRACE(rtlpriv, COMP_USB, DBG_EMERG,
"Failed to usb_alloc_coherent!!\n");
return -ENOMEM;
}
usb_fill_bulk_urb(urb, rtlusb->udev,
usb_rcvbulkpipe(rtlusb->udev, rtlusb->in_ep),
buf, rtlusb->rx_max_size, _rtl_rx_completed, rtlusb);
urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
return 0;
}
static void _rtl_usb_rx_process_agg(struct ieee80211_hw *hw,
struct sk_buff *skb)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u8 *rxdesc = skb->data;
struct ieee80211_hdr *hdr;
bool unicast = false;
__le16 fc;
struct ieee80211_rx_status rx_status = {0};
struct rtl_stats stats = {
.signal = 0,
.rate = 0,
};
skb_pull(skb, RTL_RX_DESC_SIZE);
rtlpriv->cfg->ops->query_rx_desc(hw, &stats, &rx_status, rxdesc, skb);
skb_pull(skb, (stats.rx_drvinfo_size + stats.rx_bufshift));
hdr = (struct ieee80211_hdr *)(skb->data);
fc = hdr->frame_control;
if (!stats.crc) {
memcpy(IEEE80211_SKB_RXCB(skb), &rx_status, sizeof(rx_status));
if (is_broadcast_ether_addr(hdr->addr1)) {
/*TODO*/;
} else if (is_multicast_ether_addr(hdr->addr1)) {
/*TODO*/
} else {
unicast = true;
rtlpriv->stats.rxbytesunicast += skb->len;
}
if (ieee80211_is_data(fc)) {
rtlpriv->cfg->ops->led_control(hw, LED_CTL_RX);
if (unicast)
rtlpriv->link_info.num_rx_inperiod++;
}
/* static bcn for roaming */
rtl_beacon_statistic(hw, skb);
}
}
static void _rtl_usb_rx_process_noagg(struct ieee80211_hw *hw,
struct sk_buff *skb)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u8 *rxdesc = skb->data;
struct ieee80211_hdr *hdr;
bool unicast = false;
__le16 fc;
struct ieee80211_rx_status rx_status = {0};
struct rtl_stats stats = {
.signal = 0,
.rate = 0,
};
skb_pull(skb, RTL_RX_DESC_SIZE);
rtlpriv->cfg->ops->query_rx_desc(hw, &stats, &rx_status, rxdesc, skb);
skb_pull(skb, (stats.rx_drvinfo_size + stats.rx_bufshift));
hdr = (struct ieee80211_hdr *)(skb->data);
fc = hdr->frame_control;
if (!stats.crc) {
memcpy(IEEE80211_SKB_RXCB(skb), &rx_status, sizeof(rx_status));
if (is_broadcast_ether_addr(hdr->addr1)) {
/*TODO*/;
} else if (is_multicast_ether_addr(hdr->addr1)) {
/*TODO*/
} else {
unicast = true;
rtlpriv->stats.rxbytesunicast += skb->len;
}
if (ieee80211_is_data(fc)) {
rtlpriv->cfg->ops->led_control(hw, LED_CTL_RX);
if (unicast)
rtlpriv->link_info.num_rx_inperiod++;
}
/* static bcn for roaming */
rtl_beacon_statistic(hw, skb);
if (likely(rtl_action_proc(hw, skb, false)))
ieee80211_rx(hw, skb);
else
dev_kfree_skb_any(skb);
}
}
static void _rtl_rx_pre_process(struct ieee80211_hw *hw, struct sk_buff *skb)
{
struct sk_buff *_skb;
struct sk_buff_head rx_queue;
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
skb_queue_head_init(&rx_queue);
if (rtlusb->usb_rx_segregate_hdl)
rtlusb->usb_rx_segregate_hdl(hw, skb, &rx_queue);
WARN_ON(skb_queue_empty(&rx_queue));
while (!skb_queue_empty(&rx_queue)) {
_skb = skb_dequeue(&rx_queue);
_rtl_usb_rx_process_agg(hw, _skb);
ieee80211_rx(hw, _skb);
}
}
#define __RX_SKB_MAX_QUEUED 64
static void _rtl_rx_work(unsigned long param)
{
struct rtl_usb *rtlusb = (struct rtl_usb *)param;
struct ieee80211_hw *hw = usb_get_intfdata(rtlusb->intf);
struct sk_buff *skb;
while ((skb = skb_dequeue(&rtlusb->rx_queue))) {
if (unlikely(IS_USB_STOP(rtlusb))) {
dev_kfree_skb_any(skb);
continue;
}
if (likely(!rtlusb->usb_rx_segregate_hdl)) {
_rtl_usb_rx_process_noagg(hw, skb);
} else {
/* TO DO */
_rtl_rx_pre_process(hw, skb);
pr_err("rx agg not supported\n");
}
}
}
static unsigned int _rtl_rx_get_padding(struct ieee80211_hdr *hdr,
unsigned int len)
{
#if NET_IP_ALIGN != 0
unsigned int padding = 0;
#endif
/* make function no-op when possible */
if (NET_IP_ALIGN == 0 || len < sizeof(*hdr))
return 0;
#if NET_IP_ALIGN != 0
/* alignment calculation as in lbtf_rx() / carl9170_rx_copy_data() */
/* TODO: deduplicate common code, define helper function instead? */
if (ieee80211_is_data_qos(hdr->frame_control)) {
u8 *qc = ieee80211_get_qos_ctl(hdr);
padding ^= NET_IP_ALIGN;
/* Input might be invalid, avoid accessing memory outside
* the buffer.
*/
if ((unsigned long)qc - (unsigned long)hdr < len &&
*qc & IEEE80211_QOS_CTL_A_MSDU_PRESENT)
padding ^= NET_IP_ALIGN;
}
if (ieee80211_has_a4(hdr->frame_control))
padding ^= NET_IP_ALIGN;
return padding;
#endif
}
#define __RADIO_TAP_SIZE_RSV 32
static void _rtl_rx_completed(struct urb *_urb)
{
struct rtl_usb *rtlusb = (struct rtl_usb *)_urb->context;
struct ieee80211_hw *hw = usb_get_intfdata(rtlusb->intf);
struct rtl_priv *rtlpriv = rtl_priv(hw);
int err = 0;
if (unlikely(IS_USB_STOP(rtlusb)))
goto free;
if (likely(0 == _urb->status)) {
unsigned int padding;
struct sk_buff *skb;
unsigned int qlen;
unsigned int size = _urb->actual_length;
struct ieee80211_hdr *hdr;
if (size < RTL_RX_DESC_SIZE + sizeof(struct ieee80211_hdr)) {
RT_TRACE(rtlpriv, COMP_USB, DBG_EMERG,
"Too short packet from bulk IN! (len: %d)\n",
size);
goto resubmit;
}
qlen = skb_queue_len(&rtlusb->rx_queue);
if (qlen >= __RX_SKB_MAX_QUEUED) {
RT_TRACE(rtlpriv, COMP_USB, DBG_EMERG,
"Pending RX skbuff queue full! (qlen: %d)\n",
qlen);
goto resubmit;
}
hdr = (void *)(_urb->transfer_buffer + RTL_RX_DESC_SIZE);
padding = _rtl_rx_get_padding(hdr, size - RTL_RX_DESC_SIZE);
skb = dev_alloc_skb(size + __RADIO_TAP_SIZE_RSV + padding);
if (!skb) {
RT_TRACE(rtlpriv, COMP_USB, DBG_EMERG,
"Can't allocate skb for bulk IN!\n");
goto resubmit;
}
_rtl_install_trx_info(rtlusb, skb, rtlusb->in_ep);
/* Make sure the payload data is 4 byte aligned. */
skb_reserve(skb, padding);
/* reserve some space for mac80211's radiotap */
skb_reserve(skb, __RADIO_TAP_SIZE_RSV);
memcpy(skb_put(skb, size), _urb->transfer_buffer, size);
skb_queue_tail(&rtlusb->rx_queue, skb);
tasklet_schedule(&rtlusb->rx_work_tasklet);
goto resubmit;
}
switch (_urb->status) {
/* disconnect */
case -ENOENT:
case -ECONNRESET:
case -ENODEV:
case -ESHUTDOWN:
goto free;
default:
break;
}
resubmit:
usb_anchor_urb(_urb, &rtlusb->rx_submitted);
err = usb_submit_urb(_urb, GFP_ATOMIC);
if (unlikely(err)) {
usb_unanchor_urb(_urb);
goto free;
}
return;
free:
/* On some architectures, usb_free_coherent must not be called from
* hardirq context. Queue urb to cleanup list.
*/
usb_anchor_urb(_urb, &rtlusb->rx_cleanup_urbs);
}
#undef __RADIO_TAP_SIZE_RSV
static void _rtl_usb_cleanup_rx(struct ieee80211_hw *hw)
{
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
struct urb *urb;
usb_kill_anchored_urbs(&rtlusb->rx_submitted);
tasklet_kill(&rtlusb->rx_work_tasklet);
skb_queue_purge(&rtlusb->rx_queue);
while ((urb = usb_get_from_anchor(&rtlusb->rx_cleanup_urbs))) {
usb_free_coherent(urb->dev, urb->transfer_buffer_length,
urb->transfer_buffer, urb->transfer_dma);
usb_free_urb(urb);
}
}
static int _rtl_usb_receive(struct ieee80211_hw *hw)
{
struct urb *urb;
int err;
int i;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
WARN_ON(0 == rtlusb->rx_urb_num);
/* 1600 == 1514 + max WLAN header + rtk info */
WARN_ON(rtlusb->rx_max_size < 1600);
for (i = 0; i < rtlusb->rx_urb_num; i++) {
err = -ENOMEM;
urb = usb_alloc_urb(0, GFP_KERNEL);
if (!urb) {
RT_TRACE(rtlpriv, COMP_USB, DBG_EMERG,
"Failed to alloc URB!!\n");
goto err_out;
}
err = _rtl_prep_rx_urb(hw, rtlusb, urb, GFP_KERNEL);
if (err < 0) {
RT_TRACE(rtlpriv, COMP_USB, DBG_EMERG,
"Failed to prep_rx_urb!!\n");
usb_free_urb(urb);
goto err_out;
}
usb_anchor_urb(urb, &rtlusb->rx_submitted);
err = usb_submit_urb(urb, GFP_KERNEL);
if (err)
goto err_out;
usb_free_urb(urb);
}
return 0;
err_out:
usb_kill_anchored_urbs(&rtlusb->rx_submitted);
_rtl_usb_cleanup_rx(hw);
return err;
}
static int rtl_usb_start(struct ieee80211_hw *hw)
{
int err;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
err = rtlpriv->cfg->ops->hw_init(hw);
if (!err) {
rtl_init_rx_config(hw);
/* Enable software */
SET_USB_START(rtlusb);
/* should after adapter start and interrupt enable. */
set_hal_start(rtlhal);
/* Start bulk IN */
err = _rtl_usb_receive(hw);
}
return err;
}
/**
*
*
*/
/*======================= tx =========================================*/
static void rtl_usb_cleanup(struct ieee80211_hw *hw)
{
u32 i;
struct sk_buff *_skb;
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
struct ieee80211_tx_info *txinfo;
SET_USB_STOP(rtlusb);
/* clean up rx stuff. */
_rtl_usb_cleanup_rx(hw);
/* clean up tx stuff */
for (i = 0; i < RTL_USB_MAX_EP_NUM; i++) {
while ((_skb = skb_dequeue(&rtlusb->tx_skb_queue[i]))) {
rtlusb->usb_tx_cleanup(hw, _skb);
txinfo = IEEE80211_SKB_CB(_skb);
ieee80211_tx_info_clear_status(txinfo);
txinfo->flags |= IEEE80211_TX_STAT_ACK;
ieee80211_tx_status_irqsafe(hw, _skb);
}
usb_kill_anchored_urbs(&rtlusb->tx_pending[i]);
}
usb_kill_anchored_urbs(&rtlusb->tx_submitted);
}
/**
*
* We may add some struct into struct rtl_usb later. Do deinit here.
*
*/
static void rtl_usb_deinit(struct ieee80211_hw *hw)
{
rtl_usb_cleanup(hw);
}
static void rtl_usb_stop(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
/* should after adapter start and interrupt enable. */
set_hal_stop(rtlhal);
cancel_work_sync(&rtlpriv->works.fill_h2c_cmd);
/* Enable software */
SET_USB_STOP(rtlusb);
rtl_usb_deinit(hw);
rtlpriv->cfg->ops->hw_disable(hw);
}
static void _rtl_submit_tx_urb(struct ieee80211_hw *hw, struct urb *_urb)
{
int err;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
usb_anchor_urb(_urb, &rtlusb->tx_submitted);
err = usb_submit_urb(_urb, GFP_ATOMIC);
if (err < 0) {
struct sk_buff *skb;
RT_TRACE(rtlpriv, COMP_USB, DBG_EMERG,
"Failed to submit urb\n");
usb_unanchor_urb(_urb);
skb = (struct sk_buff *)_urb->context;
kfree_skb(skb);
}
usb_free_urb(_urb);
}
static int _usb_tx_post(struct ieee80211_hw *hw, struct urb *urb,
struct sk_buff *skb)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
struct ieee80211_tx_info *txinfo;
rtlusb->usb_tx_post_hdl(hw, urb, skb);
skb_pull(skb, RTL_TX_HEADER_SIZE);
txinfo = IEEE80211_SKB_CB(skb);
ieee80211_tx_info_clear_status(txinfo);
txinfo->flags |= IEEE80211_TX_STAT_ACK;
if (urb->status) {
RT_TRACE(rtlpriv, COMP_USB, DBG_EMERG,
"Urb has error status 0x%X\n", urb->status);
goto out;
}
/* TODO: statistics */
out:
ieee80211_tx_status_irqsafe(hw, skb);
return urb->status;
}
static void _rtl_tx_complete(struct urb *urb)
{
struct sk_buff *skb = (struct sk_buff *)urb->context;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
struct rtl_usb *rtlusb = (struct rtl_usb *)info->rate_driver_data[0];
struct ieee80211_hw *hw = usb_get_intfdata(rtlusb->intf);
int err;
if (unlikely(IS_USB_STOP(rtlusb)))
return;
err = _usb_tx_post(hw, urb, skb);
if (err) {
/* Ignore error and keep issuiing other urbs */
return;
}
}
static struct urb *_rtl_usb_tx_urb_setup(struct ieee80211_hw *hw,
struct sk_buff *skb, u32 ep_num)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
struct urb *_urb;
WARN_ON(NULL == skb);
_urb = usb_alloc_urb(0, GFP_ATOMIC);
if (!_urb) {
RT_TRACE(rtlpriv, COMP_USB, DBG_EMERG,
"Can't allocate URB for bulk out!\n");
kfree_skb(skb);
return NULL;
}
_rtl_install_trx_info(rtlusb, skb, ep_num);
usb_fill_bulk_urb(_urb, rtlusb->udev, usb_sndbulkpipe(rtlusb->udev,
ep_num), skb->data, skb->len, _rtl_tx_complete, skb);
_urb->transfer_flags |= URB_ZERO_PACKET;
return _urb;
}
static void _rtl_usb_transmit(struct ieee80211_hw *hw, struct sk_buff *skb,
enum rtl_txq qnum)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
u32 ep_num;
struct urb *_urb = NULL;
struct sk_buff *_skb = NULL;
WARN_ON(NULL == rtlusb->usb_tx_aggregate_hdl);
if (unlikely(IS_USB_STOP(rtlusb))) {
RT_TRACE(rtlpriv, COMP_USB, DBG_EMERG,
"USB device is stopping...\n");
kfree_skb(skb);
return;
}
ep_num = rtlusb->ep_map.ep_mapping[qnum];
_skb = skb;
_urb = _rtl_usb_tx_urb_setup(hw, _skb, ep_num);
if (unlikely(!_urb)) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"Can't allocate urb. Drop skb!\n");
kfree_skb(skb);
return;
}
_rtl_submit_tx_urb(hw, _urb);
}
static void _rtl_usb_tx_preprocess(struct ieee80211_hw *hw,
struct ieee80211_sta *sta,
struct sk_buff *skb,
u16 hw_queue)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
struct rtl_tx_desc *pdesc = NULL;
struct rtl_tcb_desc tcb_desc;
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)(skb->data);
__le16 fc = hdr->frame_control;
u8 *pda_addr = hdr->addr1;
/* ssn */
u8 *qc = NULL;
u8 tid = 0;
u16 seq_number = 0;
memset(&tcb_desc, 0, sizeof(struct rtl_tcb_desc));
if (ieee80211_is_auth(fc)) {
RT_TRACE(rtlpriv, COMP_SEND, DBG_DMESG, "MAC80211_LINKING\n");
rtl_ips_nic_on(hw);
}
if (rtlpriv->psc.sw_ps_enabled) {
if (ieee80211_is_data(fc) && !ieee80211_is_nullfunc(fc) &&
!ieee80211_has_pm(fc))
hdr->frame_control |= cpu_to_le16(IEEE80211_FCTL_PM);
}
rtl_action_proc(hw, skb, true);
if (is_multicast_ether_addr(pda_addr))
rtlpriv->stats.txbytesmulticast += skb->len;
else if (is_broadcast_ether_addr(pda_addr))
rtlpriv->stats.txbytesbroadcast += skb->len;
else
rtlpriv->stats.txbytesunicast += skb->len;
if (ieee80211_is_data_qos(fc)) {
qc = ieee80211_get_qos_ctl(hdr);
tid = qc[0] & IEEE80211_QOS_CTL_TID_MASK;
seq_number = (le16_to_cpu(hdr->seq_ctrl) &
IEEE80211_SCTL_SEQ) >> 4;
seq_number += 1;
seq_number <<= 4;
}
rtlpriv->cfg->ops->fill_tx_desc(hw, hdr, (u8 *)pdesc, NULL, info, sta, skb,
hw_queue, &tcb_desc);
if (!ieee80211_has_morefrags(hdr->frame_control)) {
if (qc)
mac->tids[tid].seq_number = seq_number;
}
if (ieee80211_is_data(fc))
rtlpriv->cfg->ops->led_control(hw, LED_CTL_TX);
}
static int rtl_usb_tx(struct ieee80211_hw *hw,
struct ieee80211_sta *sta,
struct sk_buff *skb,
struct rtl_tcb_desc *dummy)
{
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)(skb->data);
__le16 fc = hdr->frame_control;
u16 hw_queue;
if (unlikely(is_hal_stop(rtlhal)))
goto err_free;
hw_queue = rtlusb->usb_mq_to_hwq(fc, skb_get_queue_mapping(skb));
_rtl_usb_tx_preprocess(hw, sta, skb, hw_queue);
_rtl_usb_transmit(hw, skb, hw_queue);
return NETDEV_TX_OK;
err_free:
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
static bool rtl_usb_tx_chk_waitq_insert(struct ieee80211_hw *hw,
struct ieee80211_sta *sta,
struct sk_buff *skb)
{
return false;
}
static void rtl_fill_h2c_cmd_work_callback(struct work_struct *work)
{
struct rtl_works *rtlworks =
container_of(work, struct rtl_works, fill_h2c_cmd);
struct ieee80211_hw *hw = rtlworks->hw;
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtlpriv->cfg->ops->fill_h2c_cmd(hw, H2C_RA_MASK, 5, rtlpriv->rate_mask);
}
static struct rtl_intf_ops rtl_usb_ops = {
.adapter_start = rtl_usb_start,
.adapter_stop = rtl_usb_stop,
.adapter_tx = rtl_usb_tx,
.waitq_insert = rtl_usb_tx_chk_waitq_insert,
};
int rtl_usb_probe(struct usb_interface *intf,
const struct usb_device_id *id,
struct rtl_hal_cfg *rtl_hal_cfg)
{
int err;
struct ieee80211_hw *hw = NULL;
struct rtl_priv *rtlpriv = NULL;
struct usb_device *udev;
struct rtl_usb_priv *usb_priv;
hw = ieee80211_alloc_hw(sizeof(struct rtl_priv) +
sizeof(struct rtl_usb_priv), &rtl_ops);
if (!hw) {
RT_ASSERT(false, "ieee80211 alloc failed\n");
return -ENOMEM;
}
rtlpriv = hw->priv;
rtlpriv->usb_data = kzalloc(RTL_USB_MAX_RX_COUNT * sizeof(u32),
GFP_KERNEL);
if (!rtlpriv->usb_data)
return -ENOMEM;
/* this spin lock must be initialized early */
spin_lock_init(&rtlpriv->locks.usb_lock);
INIT_WORK(&rtlpriv->works.fill_h2c_cmd,
rtl_fill_h2c_cmd_work_callback);
INIT_WORK(&rtlpriv->works.lps_change_work,
rtl_lps_change_work_callback);
rtlpriv->usb_data_index = 0;
init_completion(&rtlpriv->firmware_loading_complete);
SET_IEEE80211_DEV(hw, &intf->dev);
udev = interface_to_usbdev(intf);
usb_get_dev(udev);
usb_priv = rtl_usbpriv(hw);
memset(usb_priv, 0, sizeof(*usb_priv));
usb_priv->dev.intf = intf;
usb_priv->dev.udev = udev;
usb_set_intfdata(intf, hw);
/* init cfg & intf_ops */
rtlpriv->rtlhal.interface = INTF_USB;
rtlpriv->cfg = rtl_hal_cfg;
rtlpriv->intf_ops = &rtl_usb_ops;
rtl_dbgp_flag_init(hw);
/* Init IO handler */
_rtl_usb_io_handler_init(&udev->dev, hw);
rtlpriv->cfg->ops->read_chip_version(hw);
/*like read eeprom and so on */
rtlpriv->cfg->ops->read_eeprom_info(hw);
err = _rtl_usb_init(hw);
if (err)
goto error_out;
rtl_usb_init_sw(hw);
/* Init mac80211 sw */
err = rtl_init_core(hw);
if (err) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"Can't allocate sw for mac80211\n");
goto error_out;
}
if (rtlpriv->cfg->ops->init_sw_vars(hw)) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG, "Can't init_sw_vars\n");
goto error_out;
}
rtlpriv->cfg->ops->init_sw_leds(hw);
err = ieee80211_register_hw(hw);
if (err) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"Can't register mac80211 hw.\n");
err = -ENODEV;
goto error_out;
}
rtlpriv->mac80211.mac80211_registered = 1;
set_bit(RTL_STATUS_INTERFACE_START, &rtlpriv->status);
return 0;
error_out:
rtl_deinit_core(hw);
_rtl_usb_io_handler_release(hw);
usb_put_dev(udev);
complete(&rtlpriv->firmware_loading_complete);
return -ENODEV;
}
EXPORT_SYMBOL(rtl_usb_probe);
void rtl_usb_disconnect(struct usb_interface *intf)
{
struct ieee80211_hw *hw = usb_get_intfdata(intf);
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *rtlmac = rtl_mac(rtl_priv(hw));
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
if (unlikely(!rtlpriv))
return;
/* just in case driver is removed before firmware callback */
wait_for_completion(&rtlpriv->firmware_loading_complete);
/*ieee80211_unregister_hw will call ops_stop */
if (rtlmac->mac80211_registered == 1) {
ieee80211_unregister_hw(hw);
rtlmac->mac80211_registered = 0;
} else {
rtl_deinit_deferred_work(hw);
rtlpriv->intf_ops->adapter_stop(hw);
}
/*deinit rfkill */
/* rtl_deinit_rfkill(hw); */
rtl_usb_deinit(hw);
rtl_deinit_core(hw);
kfree(rtlpriv->usb_data);
rtlpriv->cfg->ops->deinit_sw_leds(hw);
rtlpriv->cfg->ops->deinit_sw_vars(hw);
_rtl_usb_io_handler_release(hw);
usb_put_dev(rtlusb->udev);
usb_set_intfdata(intf, NULL);
ieee80211_free_hw(hw);
}
EXPORT_SYMBOL(rtl_usb_disconnect);
int rtl_usb_suspend(struct usb_interface *pusb_intf, pm_message_t message)
{
return 0;
}
EXPORT_SYMBOL(rtl_usb_suspend);
int rtl_usb_resume(struct usb_interface *pusb_intf)
{
return 0;
}
EXPORT_SYMBOL(rtl_usb_resume);
| gpl-2.0 |
Scorpio92/htc_desire_600_kernel | scripts/dtc/checks.c | 350 | 17435 | /*
* (C) Copyright David Gibson <dwg@au1.ibm.com>, IBM Corporation. 2007.
*
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
#include "dtc.h"
#ifdef TRACE_CHECKS
#define TRACE(c, ...) \
do { \
fprintf(stderr, "=== %s: ", (c)->name); \
fprintf(stderr, __VA_ARGS__); \
fprintf(stderr, "\n"); \
} while (0)
#else
#define TRACE(c, fmt, ...) do { } while (0)
#endif
enum checklevel {
IGNORE = 0,
WARN = 1,
ERROR = 2,
};
enum checkstatus {
UNCHECKED = 0,
PREREQ,
PASSED,
FAILED,
};
struct check;
typedef void (*tree_check_fn)(struct check *c, struct node *dt);
typedef void (*node_check_fn)(struct check *c, struct node *dt, struct node *node);
typedef void (*prop_check_fn)(struct check *c, struct node *dt,
struct node *node, struct property *prop);
struct check {
const char *name;
tree_check_fn tree_fn;
node_check_fn node_fn;
prop_check_fn prop_fn;
void *data;
enum checklevel level;
enum checkstatus status;
int inprogress;
int num_prereqs;
struct check **prereq;
};
#define CHECK(nm, tfn, nfn, pfn, d, lvl, ...) \
static struct check *nm##_prereqs[] = { __VA_ARGS__ }; \
static struct check nm = { \
.name = #nm, \
.tree_fn = (tfn), \
.node_fn = (nfn), \
.prop_fn = (pfn), \
.data = (d), \
.level = (lvl), \
.status = UNCHECKED, \
.num_prereqs = ARRAY_SIZE(nm##_prereqs), \
.prereq = nm##_prereqs, \
};
#define TREE_CHECK(nm, d, lvl, ...) \
CHECK(nm, check_##nm, NULL, NULL, d, lvl, __VA_ARGS__)
#define NODE_CHECK(nm, d, lvl, ...) \
CHECK(nm, NULL, check_##nm, NULL, d, lvl, __VA_ARGS__)
#define PROP_CHECK(nm, d, lvl, ...) \
CHECK(nm, NULL, NULL, check_##nm, d, lvl, __VA_ARGS__)
#define BATCH_CHECK(nm, lvl, ...) \
CHECK(nm, NULL, NULL, NULL, NULL, lvl, __VA_ARGS__)
#ifdef __GNUC__
static inline void check_msg(struct check *c, const char *fmt, ...) __attribute__((format (printf, 2, 3)));
#endif
static inline void check_msg(struct check *c, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
if ((c->level < WARN) || (c->level <= quiet))
return;
fprintf(stderr, "%s (%s): ",
(c->level == ERROR) ? "ERROR" : "Warning", c->name);
vfprintf(stderr, fmt, ap);
fprintf(stderr, "\n");
}
#define FAIL(c, ...) \
do { \
TRACE((c), "\t\tFAILED at %s:%d", __FILE__, __LINE__); \
(c)->status = FAILED; \
check_msg((c), __VA_ARGS__); \
} while (0)
static void check_nodes_props(struct check *c, struct node *dt, struct node *node)
{
struct node *child;
struct property *prop;
TRACE(c, "%s", node->fullpath);
if (c->node_fn)
c->node_fn(c, dt, node);
if (c->prop_fn)
for_each_property(node, prop) {
TRACE(c, "%s\t'%s'", node->fullpath, prop->name);
c->prop_fn(c, dt, node, prop);
}
for_each_child(node, child)
check_nodes_props(c, dt, child);
}
static int run_check(struct check *c, struct node *dt)
{
int error = 0;
int i;
assert(!c->inprogress);
if (c->status != UNCHECKED)
goto out;
c->inprogress = 1;
for (i = 0; i < c->num_prereqs; i++) {
struct check *prq = c->prereq[i];
error |= run_check(prq, dt);
if (prq->status != PASSED) {
c->status = PREREQ;
check_msg(c, "Failed prerequisite '%s'",
c->prereq[i]->name);
}
}
if (c->status != UNCHECKED)
goto out;
if (c->node_fn || c->prop_fn)
check_nodes_props(c, dt, dt);
if (c->tree_fn)
c->tree_fn(c, dt);
if (c->status == UNCHECKED)
c->status = PASSED;
TRACE(c, "\tCompleted, status %d", c->status);
out:
c->inprogress = 0;
if ((c->status != PASSED) && (c->level == ERROR))
error = 1;
return error;
}
static void check_is_string(struct check *c, struct node *root,
struct node *node)
{
struct property *prop;
char *propname = c->data;
prop = get_property(node, propname);
if (!prop)
return;
if (!data_is_one_string(prop->val))
FAIL(c, "\"%s\" property in %s is not a string",
propname, node->fullpath);
}
#define CHECK_IS_STRING(nm, propname, lvl) \
CHECK(nm, NULL, check_is_string, NULL, (propname), (lvl))
static void check_is_cell(struct check *c, struct node *root,
struct node *node)
{
struct property *prop;
char *propname = c->data;
prop = get_property(node, propname);
if (!prop)
return;
if (prop->val.len != sizeof(cell_t))
FAIL(c, "\"%s\" property in %s is not a single cell",
propname, node->fullpath);
}
#define CHECK_IS_CELL(nm, propname, lvl) \
CHECK(nm, NULL, check_is_cell, NULL, (propname), (lvl))
static void check_duplicate_node_names(struct check *c, struct node *dt,
struct node *node)
{
struct node *child, *child2;
for_each_child(node, child)
for (child2 = child->next_sibling;
child2;
child2 = child2->next_sibling)
if (streq(child->name, child2->name))
FAIL(c, "Duplicate node name %s",
child->fullpath);
}
NODE_CHECK(duplicate_node_names, NULL, ERROR);
static void check_duplicate_property_names(struct check *c, struct node *dt,
struct node *node)
{
struct property *prop, *prop2;
for_each_property(node, prop)
for (prop2 = prop->next; prop2; prop2 = prop2->next)
if (streq(prop->name, prop2->name))
FAIL(c, "Duplicate property name %s in %s",
prop->name, node->fullpath);
}
NODE_CHECK(duplicate_property_names, NULL, ERROR);
#define LOWERCASE "abcdefghijklmnopqrstuvwxyz"
#define UPPERCASE "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
#define DIGITS "0123456789"
#define PROPNODECHARS LOWERCASE UPPERCASE DIGITS ",._+*#?-"
static void check_node_name_chars(struct check *c, struct node *dt,
struct node *node)
{
int n = strspn(node->name, c->data);
if (n < strlen(node->name))
FAIL(c, "Bad character '%c' in node %s",
node->name[n], node->fullpath);
}
NODE_CHECK(node_name_chars, PROPNODECHARS "@", ERROR);
static void check_node_name_format(struct check *c, struct node *dt,
struct node *node)
{
if (strchr(get_unitname(node), '@'))
FAIL(c, "Node %s has multiple '@' characters in name",
node->fullpath);
}
NODE_CHECK(node_name_format, NULL, ERROR, &node_name_chars);
static void check_property_name_chars(struct check *c, struct node *dt,
struct node *node, struct property *prop)
{
int n = strspn(prop->name, c->data);
if (n < strlen(prop->name))
FAIL(c, "Bad character '%c' in property name \"%s\", node %s",
prop->name[n], prop->name, node->fullpath);
}
PROP_CHECK(property_name_chars, PROPNODECHARS, ERROR);
#define DESCLABEL_FMT "%s%s%s%s%s"
#define DESCLABEL_ARGS(node,prop,mark) \
((mark) ? "value of " : ""), \
((prop) ? "'" : ""), \
((prop) ? (prop)->name : ""), \
((prop) ? "' in " : ""), (node)->fullpath
static void check_duplicate_label(struct check *c, struct node *dt,
const char *label, struct node *node,
struct property *prop, struct marker *mark)
{
struct node *othernode = NULL;
struct property *otherprop = NULL;
struct marker *othermark = NULL;
othernode = get_node_by_label(dt, label);
if (!othernode)
otherprop = get_property_by_label(dt, label, &othernode);
if (!othernode)
othermark = get_marker_label(dt, label, &othernode,
&otherprop);
if (!othernode)
return;
if ((othernode != node) || (otherprop != prop) || (othermark != mark))
FAIL(c, "Duplicate label '%s' on " DESCLABEL_FMT
" and " DESCLABEL_FMT,
label, DESCLABEL_ARGS(node, prop, mark),
DESCLABEL_ARGS(othernode, otherprop, othermark));
}
static void check_duplicate_label_node(struct check *c, struct node *dt,
struct node *node)
{
struct label *l;
for_each_label(node->labels, l)
check_duplicate_label(c, dt, l->label, node, NULL, NULL);
}
static void check_duplicate_label_prop(struct check *c, struct node *dt,
struct node *node, struct property *prop)
{
struct marker *m = prop->val.markers;
struct label *l;
for_each_label(prop->labels, l)
check_duplicate_label(c, dt, l->label, node, prop, NULL);
for_each_marker_of_type(m, LABEL)
check_duplicate_label(c, dt, m->ref, node, prop, m);
}
CHECK(duplicate_label, NULL, check_duplicate_label_node,
check_duplicate_label_prop, NULL, ERROR);
static void check_explicit_phandles(struct check *c, struct node *root,
struct node *node, struct property *prop)
{
struct marker *m;
struct node *other;
cell_t phandle;
if (!streq(prop->name, "phandle")
&& !streq(prop->name, "linux,phandle"))
return;
if (prop->val.len != sizeof(cell_t)) {
FAIL(c, "%s has bad length (%d) %s property",
node->fullpath, prop->val.len, prop->name);
return;
}
m = prop->val.markers;
for_each_marker_of_type(m, REF_PHANDLE) {
assert(m->offset == 0);
if (node != get_node_by_ref(root, m->ref))
{
FAIL(c, "%s in %s is a reference to another node",
prop->name, node->fullpath);
return;
}
return;
}
phandle = propval_cell(prop);
if ((phandle == 0) || (phandle == -1)) {
FAIL(c, "%s has bad value (0x%x) in %s property",
node->fullpath, phandle, prop->name);
return;
}
if (node->phandle && (node->phandle != phandle))
FAIL(c, "%s has %s property which replaces existing phandle information",
node->fullpath, prop->name);
other = get_node_by_phandle(root, phandle);
if (other && (other != node)) {
FAIL(c, "%s has duplicated phandle 0x%x (seen before at %s)",
node->fullpath, phandle, other->fullpath);
return;
}
node->phandle = phandle;
}
PROP_CHECK(explicit_phandles, NULL, ERROR);
static void check_name_properties(struct check *c, struct node *root,
struct node *node)
{
struct property **pp, *prop = NULL;
for (pp = &node->proplist; *pp; pp = &((*pp)->next))
if (streq((*pp)->name, "name")) {
prop = *pp;
break;
}
if (!prop)
return;
if ((prop->val.len != node->basenamelen+1)
|| (memcmp(prop->val.val, node->name, node->basenamelen) != 0)) {
FAIL(c, "\"name\" property in %s is incorrect (\"%s\" instead"
" of base node name)", node->fullpath, prop->val.val);
} else {
*pp = prop->next;
free(prop->name);
data_free(prop->val);
free(prop);
}
}
CHECK_IS_STRING(name_is_string, "name", ERROR);
NODE_CHECK(name_properties, NULL, ERROR, &name_is_string);
static void fixup_phandle_references(struct check *c, struct node *dt,
struct node *node, struct property *prop)
{
struct marker *m = prop->val.markers;
struct node *refnode;
cell_t phandle;
for_each_marker_of_type(m, REF_PHANDLE) {
assert(m->offset + sizeof(cell_t) <= prop->val.len);
refnode = get_node_by_ref(dt, m->ref);
if (! refnode) {
FAIL(c, "Reference to non-existent node or label \"%s\"\n",
m->ref);
continue;
}
phandle = get_node_phandle(dt, refnode);
*((cell_t *)(prop->val.val + m->offset)) = cpu_to_fdt32(phandle);
}
}
CHECK(phandle_references, NULL, NULL, fixup_phandle_references, NULL, ERROR,
&duplicate_node_names, &explicit_phandles);
static void fixup_path_references(struct check *c, struct node *dt,
struct node *node, struct property *prop)
{
struct marker *m = prop->val.markers;
struct node *refnode;
char *path;
for_each_marker_of_type(m, REF_PATH) {
assert(m->offset <= prop->val.len);
refnode = get_node_by_ref(dt, m->ref);
if (!refnode) {
FAIL(c, "Reference to non-existent node or label \"%s\"\n",
m->ref);
continue;
}
path = refnode->fullpath;
prop->val = data_insert_at_marker(prop->val, m, path,
strlen(path) + 1);
}
}
CHECK(path_references, NULL, NULL, fixup_path_references, NULL, ERROR,
&duplicate_node_names);
CHECK_IS_CELL(address_cells_is_cell, "#address-cells", WARN);
CHECK_IS_CELL(size_cells_is_cell, "#size-cells", WARN);
CHECK_IS_CELL(interrupt_cells_is_cell, "#interrupt-cells", WARN);
CHECK_IS_STRING(device_type_is_string, "device_type", WARN);
CHECK_IS_STRING(model_is_string, "model", WARN);
CHECK_IS_STRING(status_is_string, "status", WARN);
static void fixup_addr_size_cells(struct check *c, struct node *dt,
struct node *node)
{
struct property *prop;
node->addr_cells = -1;
node->size_cells = -1;
prop = get_property(node, "#address-cells");
if (prop)
node->addr_cells = propval_cell(prop);
prop = get_property(node, "#size-cells");
if (prop)
node->size_cells = propval_cell(prop);
}
CHECK(addr_size_cells, NULL, fixup_addr_size_cells, NULL, NULL, WARN,
&address_cells_is_cell, &size_cells_is_cell);
#define node_addr_cells(n) \
(((n)->addr_cells == -1) ? 2 : (n)->addr_cells)
#define node_size_cells(n) \
(((n)->size_cells == -1) ? 1 : (n)->size_cells)
static void check_reg_format(struct check *c, struct node *dt,
struct node *node)
{
struct property *prop;
int addr_cells, size_cells, entrylen;
prop = get_property(node, "reg");
if (!prop)
return;
if (!node->parent) {
FAIL(c, "Root node has a \"reg\" property");
return;
}
if (prop->val.len == 0)
FAIL(c, "\"reg\" property in %s is empty", node->fullpath);
addr_cells = node_addr_cells(node->parent);
size_cells = node_size_cells(node->parent);
entrylen = (addr_cells + size_cells) * sizeof(cell_t);
if ((prop->val.len % entrylen) != 0)
FAIL(c, "\"reg\" property in %s has invalid length (%d bytes) "
"(#address-cells == %d, #size-cells == %d)",
node->fullpath, prop->val.len, addr_cells, size_cells);
}
NODE_CHECK(reg_format, NULL, WARN, &addr_size_cells);
static void check_ranges_format(struct check *c, struct node *dt,
struct node *node)
{
struct property *prop;
int c_addr_cells, p_addr_cells, c_size_cells, p_size_cells, entrylen;
prop = get_property(node, "ranges");
if (!prop)
return;
if (!node->parent) {
FAIL(c, "Root node has a \"ranges\" property");
return;
}
p_addr_cells = node_addr_cells(node->parent);
p_size_cells = node_size_cells(node->parent);
c_addr_cells = node_addr_cells(node);
c_size_cells = node_size_cells(node);
entrylen = (p_addr_cells + c_addr_cells + c_size_cells) * sizeof(cell_t);
if (prop->val.len == 0) {
if (p_addr_cells != c_addr_cells)
FAIL(c, "%s has empty \"ranges\" property but its "
"#address-cells (%d) differs from %s (%d)",
node->fullpath, c_addr_cells, node->parent->fullpath,
p_addr_cells);
if (p_size_cells != c_size_cells)
FAIL(c, "%s has empty \"ranges\" property but its "
"#size-cells (%d) differs from %s (%d)",
node->fullpath, c_size_cells, node->parent->fullpath,
p_size_cells);
} else if ((prop->val.len % entrylen) != 0) {
FAIL(c, "\"ranges\" property in %s has invalid length (%d bytes) "
"(parent #address-cells == %d, child #address-cells == %d, "
"#size-cells == %d)", node->fullpath, prop->val.len,
p_addr_cells, c_addr_cells, c_size_cells);
}
}
NODE_CHECK(ranges_format, NULL, WARN, &addr_size_cells);
static void check_avoid_default_addr_size(struct check *c, struct node *dt,
struct node *node)
{
struct property *reg, *ranges;
if (!node->parent)
return;
reg = get_property(node, "reg");
ranges = get_property(node, "ranges");
if (!reg && !ranges)
return;
if ((node->parent->addr_cells == -1))
FAIL(c, "Relying on default #address-cells value for %s",
node->fullpath);
if ((node->parent->size_cells == -1))
FAIL(c, "Relying on default #size-cells value for %s",
node->fullpath);
}
NODE_CHECK(avoid_default_addr_size, NULL, WARN, &addr_size_cells);
static void check_obsolete_chosen_interrupt_controller(struct check *c,
struct node *dt)
{
struct node *chosen;
struct property *prop;
chosen = get_node_by_path(dt, "/chosen");
if (!chosen)
return;
prop = get_property(chosen, "interrupt-controller");
if (prop)
FAIL(c, "/chosen has obsolete \"interrupt-controller\" "
"property");
}
TREE_CHECK(obsolete_chosen_interrupt_controller, NULL, WARN);
static struct check *check_table[] = {
&duplicate_node_names, &duplicate_property_names,
&node_name_chars, &node_name_format, &property_name_chars,
&name_is_string, &name_properties,
&duplicate_label,
&explicit_phandles,
&phandle_references, &path_references,
&address_cells_is_cell, &size_cells_is_cell, &interrupt_cells_is_cell,
&device_type_is_string, &model_is_string, &status_is_string,
&addr_size_cells, ®_format, &ranges_format,
&avoid_default_addr_size,
&obsolete_chosen_interrupt_controller,
};
void process_checks(int force, struct boot_info *bi)
{
struct node *dt = bi->dt;
int i;
int error = 0;
for (i = 0; i < ARRAY_SIZE(check_table); i++) {
struct check *c = check_table[i];
if (c->level != IGNORE)
error = error || run_check(c, dt);
}
if (error) {
if (!force) {
fprintf(stderr, "ERROR: Input tree has errors, aborting "
"(use -f to force output)\n");
exit(2);
} else if (quiet < 3) {
fprintf(stderr, "Warning: Input tree has errors, "
"output forced\n");
}
}
}
| gpl-2.0 |
loli10K/linux-hardkernel | arch/mips/kernel/irq.c | 606 | 2089 | /*
* 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.
*
* Code to handle x86 style IRQs plus some generic interrupt stuff.
*
* Copyright (C) 1992 Linus Torvalds
* Copyright (C) 1994 - 2000 Ralf Baechle
*/
#include <linux/kernel.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/kernel_stat.h>
#include <linux/proc_fs.h>
#include <linux/mm.h>
#include <linux/random.h>
#include <linux/sched.h>
#include <linux/seq_file.h>
#include <linux/kallsyms.h>
#include <linux/kgdb.h>
#include <linux/ftrace.h>
#include <linux/atomic.h>
#include <asm/uaccess.h>
/*
* 'what should we do if we get a hw irq event on an illegal vector'.
* each architecture has to answer this themselves.
*/
void ack_bad_irq(unsigned int irq)
{
printk("unexpected IRQ # %d\n", irq);
}
atomic_t irq_err_count;
int arch_show_interrupts(struct seq_file *p, int prec)
{
seq_printf(p, "%*s: %10u\n", prec, "ERR", atomic_read(&irq_err_count));
return 0;
}
asmlinkage void spurious_interrupt(void)
{
atomic_inc(&irq_err_count);
}
void __init init_IRQ(void)
{
int i;
for (i = 0; i < NR_IRQS; i++)
irq_set_noprobe(i);
arch_init_irq();
}
#ifdef CONFIG_DEBUG_STACKOVERFLOW
static inline void check_stack_overflow(void)
{
unsigned long sp;
__asm__ __volatile__("move %0, $sp" : "=r" (sp));
sp &= THREAD_MASK;
/*
* Check for stack overflow: is there less than STACK_WARN free?
* STACK_WARN is defined as 1/8 of THREAD_SIZE by default.
*/
if (unlikely(sp < (sizeof(struct thread_info) + STACK_WARN))) {
printk("do_IRQ: stack overflow: %ld\n",
sp - sizeof(struct thread_info));
dump_stack();
}
}
#else
static inline void check_stack_overflow(void) {}
#endif
/*
* do_IRQ handles all normal device IRQ's (the special
* SMP cross-CPU interrupts have their own specific
* handlers).
*/
void __irq_entry do_IRQ(unsigned int irq)
{
irq_enter();
check_stack_overflow();
generic_handle_irq(irq);
irq_exit();
}
| gpl-2.0 |
AOKP/lge-kernel-star | drivers/ide/aec62xx.c | 606 | 9392 | /*
* Copyright (C) 1999-2002 Andre Hedrick <andre@linux-ide.org>
* Copyright (C) 2007 MontaVista Software, Inc. <source@mvista.com>
*
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/ide.h>
#include <linux/init.h>
#include <asm/io.h>
#define DRV_NAME "aec62xx"
struct chipset_bus_clock_list_entry {
u8 xfer_speed;
u8 chipset_settings;
u8 ultra_settings;
};
static const struct chipset_bus_clock_list_entry aec6xxx_33_base [] = {
{ XFER_UDMA_6, 0x31, 0x07 },
{ XFER_UDMA_5, 0x31, 0x06 },
{ XFER_UDMA_4, 0x31, 0x05 },
{ XFER_UDMA_3, 0x31, 0x04 },
{ XFER_UDMA_2, 0x31, 0x03 },
{ XFER_UDMA_1, 0x31, 0x02 },
{ XFER_UDMA_0, 0x31, 0x01 },
{ XFER_MW_DMA_2, 0x31, 0x00 },
{ XFER_MW_DMA_1, 0x31, 0x00 },
{ XFER_MW_DMA_0, 0x0a, 0x00 },
{ XFER_PIO_4, 0x31, 0x00 },
{ XFER_PIO_3, 0x33, 0x00 },
{ XFER_PIO_2, 0x08, 0x00 },
{ XFER_PIO_1, 0x0a, 0x00 },
{ XFER_PIO_0, 0x00, 0x00 },
{ 0, 0x00, 0x00 }
};
static const struct chipset_bus_clock_list_entry aec6xxx_34_base [] = {
{ XFER_UDMA_6, 0x41, 0x06 },
{ XFER_UDMA_5, 0x41, 0x05 },
{ XFER_UDMA_4, 0x41, 0x04 },
{ XFER_UDMA_3, 0x41, 0x03 },
{ XFER_UDMA_2, 0x41, 0x02 },
{ XFER_UDMA_1, 0x41, 0x01 },
{ XFER_UDMA_0, 0x41, 0x01 },
{ XFER_MW_DMA_2, 0x41, 0x00 },
{ XFER_MW_DMA_1, 0x42, 0x00 },
{ XFER_MW_DMA_0, 0x7a, 0x00 },
{ XFER_PIO_4, 0x41, 0x00 },
{ XFER_PIO_3, 0x43, 0x00 },
{ XFER_PIO_2, 0x78, 0x00 },
{ XFER_PIO_1, 0x7a, 0x00 },
{ XFER_PIO_0, 0x70, 0x00 },
{ 0, 0x00, 0x00 }
};
/*
* TO DO: active tuning and correction of cards without a bios.
*/
static u8 pci_bus_clock_list (u8 speed, struct chipset_bus_clock_list_entry * chipset_table)
{
for ( ; chipset_table->xfer_speed ; chipset_table++)
if (chipset_table->xfer_speed == speed) {
return chipset_table->chipset_settings;
}
return chipset_table->chipset_settings;
}
static u8 pci_bus_clock_list_ultra (u8 speed, struct chipset_bus_clock_list_entry * chipset_table)
{
for ( ; chipset_table->xfer_speed ; chipset_table++)
if (chipset_table->xfer_speed == speed) {
return chipset_table->ultra_settings;
}
return chipset_table->ultra_settings;
}
static void aec6210_set_mode(ide_drive_t *drive, const u8 speed)
{
ide_hwif_t *hwif = drive->hwif;
struct pci_dev *dev = to_pci_dev(hwif->dev);
struct ide_host *host = pci_get_drvdata(dev);
struct chipset_bus_clock_list_entry *bus_clock = host->host_priv;
u16 d_conf = 0;
u8 ultra = 0, ultra_conf = 0;
u8 tmp0 = 0, tmp1 = 0, tmp2 = 0;
unsigned long flags;
local_irq_save(flags);
/* 0x40|(2*drive->dn): Active, 0x41|(2*drive->dn): Recovery */
pci_read_config_word(dev, 0x40|(2*drive->dn), &d_conf);
tmp0 = pci_bus_clock_list(speed, bus_clock);
d_conf = ((tmp0 & 0xf0) << 4) | (tmp0 & 0xf);
pci_write_config_word(dev, 0x40|(2*drive->dn), d_conf);
tmp1 = 0x00;
tmp2 = 0x00;
pci_read_config_byte(dev, 0x54, &ultra);
tmp1 = ((0x00 << (2*drive->dn)) | (ultra & ~(3 << (2*drive->dn))));
ultra_conf = pci_bus_clock_list_ultra(speed, bus_clock);
tmp2 = ((ultra_conf << (2*drive->dn)) | (tmp1 & ~(3 << (2*drive->dn))));
pci_write_config_byte(dev, 0x54, tmp2);
local_irq_restore(flags);
}
static void aec6260_set_mode(ide_drive_t *drive, const u8 speed)
{
ide_hwif_t *hwif = drive->hwif;
struct pci_dev *dev = to_pci_dev(hwif->dev);
struct ide_host *host = pci_get_drvdata(dev);
struct chipset_bus_clock_list_entry *bus_clock = host->host_priv;
u8 unit = drive->dn & 1;
u8 tmp1 = 0, tmp2 = 0;
u8 ultra = 0, drive_conf = 0, ultra_conf = 0;
unsigned long flags;
local_irq_save(flags);
/* high 4-bits: Active, low 4-bits: Recovery */
pci_read_config_byte(dev, 0x40|drive->dn, &drive_conf);
drive_conf = pci_bus_clock_list(speed, bus_clock);
pci_write_config_byte(dev, 0x40|drive->dn, drive_conf);
pci_read_config_byte(dev, (0x44|hwif->channel), &ultra);
tmp1 = ((0x00 << (4*unit)) | (ultra & ~(7 << (4*unit))));
ultra_conf = pci_bus_clock_list_ultra(speed, bus_clock);
tmp2 = ((ultra_conf << (4*unit)) | (tmp1 & ~(7 << (4*unit))));
pci_write_config_byte(dev, (0x44|hwif->channel), tmp2);
local_irq_restore(flags);
}
static void aec_set_pio_mode(ide_drive_t *drive, const u8 pio)
{
drive->hwif->port_ops->set_dma_mode(drive, pio + XFER_PIO_0);
}
static int init_chipset_aec62xx(struct pci_dev *dev)
{
/* These are necessary to get AEC6280 Macintosh cards to work */
if ((dev->device == PCI_DEVICE_ID_ARTOP_ATP865) ||
(dev->device == PCI_DEVICE_ID_ARTOP_ATP865R)) {
u8 reg49h = 0, reg4ah = 0;
/* Clear reset and test bits. */
pci_read_config_byte(dev, 0x49, ®49h);
pci_write_config_byte(dev, 0x49, reg49h & ~0x30);
/* Enable chip interrupt output. */
pci_read_config_byte(dev, 0x4a, ®4ah);
pci_write_config_byte(dev, 0x4a, reg4ah & ~0x01);
/* Enable burst mode. */
pci_read_config_byte(dev, 0x4a, ®4ah);
pci_write_config_byte(dev, 0x4a, reg4ah | 0x80);
}
return 0;
}
static u8 atp86x_cable_detect(ide_hwif_t *hwif)
{
struct pci_dev *dev = to_pci_dev(hwif->dev);
u8 ata66 = 0, mask = hwif->channel ? 0x02 : 0x01;
pci_read_config_byte(dev, 0x49, &ata66);
return (ata66 & mask) ? ATA_CBL_PATA40 : ATA_CBL_PATA80;
}
static const struct ide_port_ops atp850_port_ops = {
.set_pio_mode = aec_set_pio_mode,
.set_dma_mode = aec6210_set_mode,
};
static const struct ide_port_ops atp86x_port_ops = {
.set_pio_mode = aec_set_pio_mode,
.set_dma_mode = aec6260_set_mode,
.cable_detect = atp86x_cable_detect,
};
static const struct ide_port_info aec62xx_chipsets[] __devinitdata = {
{ /* 0: AEC6210 */
.name = DRV_NAME,
.init_chipset = init_chipset_aec62xx,
.enablebits = {{0x4a,0x02,0x02}, {0x4a,0x04,0x04}},
.port_ops = &atp850_port_ops,
.host_flags = IDE_HFLAG_SERIALIZE |
IDE_HFLAG_NO_ATAPI_DMA |
IDE_HFLAG_NO_DSC |
IDE_HFLAG_OFF_BOARD,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA2,
},
{ /* 1: AEC6260 */
.name = DRV_NAME,
.init_chipset = init_chipset_aec62xx,
.port_ops = &atp86x_port_ops,
.host_flags = IDE_HFLAG_NO_ATAPI_DMA | IDE_HFLAG_NO_AUTODMA |
IDE_HFLAG_OFF_BOARD,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA4,
},
{ /* 2: AEC6260R */
.name = DRV_NAME,
.init_chipset = init_chipset_aec62xx,
.enablebits = {{0x4a,0x02,0x02}, {0x4a,0x04,0x04}},
.port_ops = &atp86x_port_ops,
.host_flags = IDE_HFLAG_NO_ATAPI_DMA |
IDE_HFLAG_NON_BOOTABLE,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA4,
},
{ /* 3: AEC6280 */
.name = DRV_NAME,
.init_chipset = init_chipset_aec62xx,
.port_ops = &atp86x_port_ops,
.host_flags = IDE_HFLAG_NO_ATAPI_DMA |
IDE_HFLAG_OFF_BOARD,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA5,
},
{ /* 4: AEC6280R */
.name = DRV_NAME,
.init_chipset = init_chipset_aec62xx,
.enablebits = {{0x4a,0x02,0x02}, {0x4a,0x04,0x04}},
.port_ops = &atp86x_port_ops,
.host_flags = IDE_HFLAG_NO_ATAPI_DMA |
IDE_HFLAG_OFF_BOARD,
.pio_mask = ATA_PIO4,
.mwdma_mask = ATA_MWDMA2,
.udma_mask = ATA_UDMA5,
}
};
/**
* aec62xx_init_one - called when a AEC is found
* @dev: the aec62xx device
* @id: the matching pci id
*
* Called when the PCI registration layer (or the IDE initialization)
* finds a device matching our IDE device tables.
*
* NOTE: since we're going to modify the 'name' field for AEC-6[26]80[R]
* chips, pass a local copy of 'struct ide_port_info' down the call chain.
*/
static int __devinit aec62xx_init_one(struct pci_dev *dev, const struct pci_device_id *id)
{
const struct chipset_bus_clock_list_entry *bus_clock;
struct ide_port_info d;
u8 idx = id->driver_data;
int bus_speed = ide_pci_clk ? ide_pci_clk : 33;
int err;
if (bus_speed <= 33)
bus_clock = aec6xxx_33_base;
else
bus_clock = aec6xxx_34_base;
err = pci_enable_device(dev);
if (err)
return err;
d = aec62xx_chipsets[idx];
if (idx == 3 || idx == 4) {
unsigned long dma_base = pci_resource_start(dev, 4);
if (inb(dma_base + 2) & 0x10) {
printk(KERN_INFO DRV_NAME " %s: AEC6880%s card detected"
"\n", pci_name(dev), (idx == 4) ? "R" : "");
d.udma_mask = ATA_UDMA6;
}
}
err = ide_pci_init_one(dev, &d, (void *)bus_clock);
if (err)
pci_disable_device(dev);
return err;
}
static void __devexit aec62xx_remove(struct pci_dev *dev)
{
ide_pci_remove(dev);
pci_disable_device(dev);
}
static const struct pci_device_id aec62xx_pci_tbl[] = {
{ PCI_VDEVICE(ARTOP, PCI_DEVICE_ID_ARTOP_ATP850UF), 0 },
{ PCI_VDEVICE(ARTOP, PCI_DEVICE_ID_ARTOP_ATP860), 1 },
{ PCI_VDEVICE(ARTOP, PCI_DEVICE_ID_ARTOP_ATP860R), 2 },
{ PCI_VDEVICE(ARTOP, PCI_DEVICE_ID_ARTOP_ATP865), 3 },
{ PCI_VDEVICE(ARTOP, PCI_DEVICE_ID_ARTOP_ATP865R), 4 },
{ 0, },
};
MODULE_DEVICE_TABLE(pci, aec62xx_pci_tbl);
static struct pci_driver aec62xx_pci_driver = {
.name = "AEC62xx_IDE",
.id_table = aec62xx_pci_tbl,
.probe = aec62xx_init_one,
.remove = __devexit_p(aec62xx_remove),
.suspend = ide_pci_suspend,
.resume = ide_pci_resume,
};
static int __init aec62xx_ide_init(void)
{
return ide_pci_register_driver(&aec62xx_pci_driver);
}
static void __exit aec62xx_ide_exit(void)
{
pci_unregister_driver(&aec62xx_pci_driver);
}
module_init(aec62xx_ide_init);
module_exit(aec62xx_ide_exit);
MODULE_AUTHOR("Andre Hedrick");
MODULE_DESCRIPTION("PCI driver module for ARTOP AEC62xx IDE");
MODULE_LICENSE("GPL");
| gpl-2.0 |
sunnyden/ubuntu_kernel | drivers/clk/hisilicon/clkgate-separated.c | 1374 | 3680 | /*
* Hisilicon clock separated gate driver
*
* Copyright (c) 2012-2013 Hisilicon Limited.
* Copyright (c) 2012-2013 Linaro Limited.
*
* Author: Haojian Zhuang <haojian.zhuang@linaro.org>
* Xin Li <li.xin@linaro.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
#include <linux/kernel.h>
#include <linux/clk-provider.h>
#include <linux/clkdev.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <linux/clk.h>
#include "clk.h"
/* clock separated gate register offset */
#define CLKGATE_SEPERATED_ENABLE 0x0
#define CLKGATE_SEPERATED_DISABLE 0x4
#define CLKGATE_SEPERATED_STATUS 0x8
struct clkgate_separated {
struct clk_hw hw;
void __iomem *enable; /* enable register */
u8 bit_idx; /* bits in enable/disable register */
u8 flags;
spinlock_t *lock;
};
static int clkgate_separated_enable(struct clk_hw *hw)
{
struct clkgate_separated *sclk;
unsigned long flags = 0;
u32 reg;
sclk = container_of(hw, struct clkgate_separated, hw);
if (sclk->lock)
spin_lock_irqsave(sclk->lock, flags);
reg = BIT(sclk->bit_idx);
writel_relaxed(reg, sclk->enable);
readl_relaxed(sclk->enable + CLKGATE_SEPERATED_STATUS);
if (sclk->lock)
spin_unlock_irqrestore(sclk->lock, flags);
return 0;
}
static void clkgate_separated_disable(struct clk_hw *hw)
{
struct clkgate_separated *sclk;
unsigned long flags = 0;
u32 reg;
sclk = container_of(hw, struct clkgate_separated, hw);
if (sclk->lock)
spin_lock_irqsave(sclk->lock, flags);
reg = BIT(sclk->bit_idx);
writel_relaxed(reg, sclk->enable + CLKGATE_SEPERATED_DISABLE);
readl_relaxed(sclk->enable + CLKGATE_SEPERATED_STATUS);
if (sclk->lock)
spin_unlock_irqrestore(sclk->lock, flags);
}
static int clkgate_separated_is_enabled(struct clk_hw *hw)
{
struct clkgate_separated *sclk;
u32 reg;
sclk = container_of(hw, struct clkgate_separated, hw);
reg = readl_relaxed(sclk->enable + CLKGATE_SEPERATED_STATUS);
reg &= BIT(sclk->bit_idx);
return reg ? 1 : 0;
}
static struct clk_ops clkgate_separated_ops = {
.enable = clkgate_separated_enable,
.disable = clkgate_separated_disable,
.is_enabled = clkgate_separated_is_enabled,
};
struct clk *hisi_register_clkgate_sep(struct device *dev, const char *name,
const char *parent_name,
unsigned long flags,
void __iomem *reg, u8 bit_idx,
u8 clk_gate_flags, spinlock_t *lock)
{
struct clkgate_separated *sclk;
struct clk *clk;
struct clk_init_data init;
sclk = kzalloc(sizeof(*sclk), GFP_KERNEL);
if (!sclk) {
pr_err("%s: fail to allocate separated gated clk\n", __func__);
return ERR_PTR(-ENOMEM);
}
init.name = name;
init.ops = &clkgate_separated_ops;
init.flags = flags | CLK_IS_BASIC;
init.parent_names = (parent_name ? &parent_name : NULL);
init.num_parents = (parent_name ? 1 : 0);
sclk->enable = reg + CLKGATE_SEPERATED_ENABLE;
sclk->bit_idx = bit_idx;
sclk->flags = clk_gate_flags;
sclk->hw.init = &init;
clk = clk_register(dev, &sclk->hw);
if (IS_ERR(clk))
kfree(sclk);
return clk;
}
| gpl-2.0 |
7420dev/android_kernel_samsung_zero | drivers/watchdog/orion_wdt.c | 2142 | 5397 | /*
* drivers/watchdog/orion_wdt.c
*
* Watchdog driver for Orion/Kirkwood processors
*
* Author: Sylver Bruneau <sylver.bruneau@googlemail.com>
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/miscdevice.h>
#include <linux/platform_device.h>
#include <linux/watchdog.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/spinlock.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/of.h>
#include <mach/bridge-regs.h>
/*
* Watchdog timer block registers.
*/
#define TIMER_CTRL 0x0000
#define WDT_EN 0x0010
#define WDT_VAL 0x0024
#define WDT_MAX_CYCLE_COUNT 0xffffffff
#define WDT_IN_USE 0
#define WDT_OK_TO_CLOSE 1
static bool nowayout = WATCHDOG_NOWAYOUT;
static int heartbeat = -1; /* module parameter (seconds) */
static unsigned int wdt_max_duration; /* (seconds) */
static struct clk *clk;
static unsigned int wdt_tclk;
static void __iomem *wdt_reg;
static DEFINE_SPINLOCK(wdt_lock);
static int orion_wdt_ping(struct watchdog_device *wdt_dev)
{
spin_lock(&wdt_lock);
/* Reload watchdog duration */
writel(wdt_tclk * wdt_dev->timeout, wdt_reg + WDT_VAL);
spin_unlock(&wdt_lock);
return 0;
}
static int orion_wdt_start(struct watchdog_device *wdt_dev)
{
u32 reg;
spin_lock(&wdt_lock);
/* Set watchdog duration */
writel(wdt_tclk * wdt_dev->timeout, wdt_reg + WDT_VAL);
/* Clear watchdog timer interrupt */
reg = readl(BRIDGE_CAUSE);
reg &= ~WDT_INT_REQ;
writel(reg, BRIDGE_CAUSE);
/* Enable watchdog timer */
reg = readl(wdt_reg + TIMER_CTRL);
reg |= WDT_EN;
writel(reg, wdt_reg + TIMER_CTRL);
/* Enable reset on watchdog */
reg = readl(RSTOUTn_MASK);
reg |= WDT_RESET_OUT_EN;
writel(reg, RSTOUTn_MASK);
spin_unlock(&wdt_lock);
return 0;
}
static int orion_wdt_stop(struct watchdog_device *wdt_dev)
{
u32 reg;
spin_lock(&wdt_lock);
/* Disable reset on watchdog */
reg = readl(RSTOUTn_MASK);
reg &= ~WDT_RESET_OUT_EN;
writel(reg, RSTOUTn_MASK);
/* Disable watchdog timer */
reg = readl(wdt_reg + TIMER_CTRL);
reg &= ~WDT_EN;
writel(reg, wdt_reg + TIMER_CTRL);
spin_unlock(&wdt_lock);
return 0;
}
static unsigned int orion_wdt_get_timeleft(struct watchdog_device *wdt_dev)
{
unsigned int time_left;
spin_lock(&wdt_lock);
time_left = readl(wdt_reg + WDT_VAL) / wdt_tclk;
spin_unlock(&wdt_lock);
return time_left;
}
static int orion_wdt_set_timeout(struct watchdog_device *wdt_dev,
unsigned int timeout)
{
wdt_dev->timeout = timeout;
return 0;
}
static const struct watchdog_info orion_wdt_info = {
.options = WDIOF_SETTIMEOUT | WDIOF_KEEPALIVEPING | WDIOF_MAGICCLOSE,
.identity = "Orion Watchdog",
};
static const struct watchdog_ops orion_wdt_ops = {
.owner = THIS_MODULE,
.start = orion_wdt_start,
.stop = orion_wdt_stop,
.ping = orion_wdt_ping,
.set_timeout = orion_wdt_set_timeout,
.get_timeleft = orion_wdt_get_timeleft,
};
static struct watchdog_device orion_wdt = {
.info = &orion_wdt_info,
.ops = &orion_wdt_ops,
.min_timeout = 1,
};
static int orion_wdt_probe(struct platform_device *pdev)
{
struct resource *res;
int ret;
clk = devm_clk_get(&pdev->dev, NULL);
if (IS_ERR(clk)) {
dev_err(&pdev->dev, "Orion Watchdog missing clock\n");
return -ENODEV;
}
clk_prepare_enable(clk);
wdt_tclk = clk_get_rate(clk);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res)
return -ENODEV;
wdt_reg = devm_ioremap(&pdev->dev, res->start, resource_size(res));
if (!wdt_reg)
return -ENOMEM;
wdt_max_duration = WDT_MAX_CYCLE_COUNT / wdt_tclk;
orion_wdt.timeout = wdt_max_duration;
orion_wdt.max_timeout = wdt_max_duration;
watchdog_init_timeout(&orion_wdt, heartbeat, &pdev->dev);
watchdog_set_nowayout(&orion_wdt, nowayout);
ret = watchdog_register_device(&orion_wdt);
if (ret) {
clk_disable_unprepare(clk);
return ret;
}
pr_info("Initial timeout %d sec%s\n",
orion_wdt.timeout, nowayout ? ", nowayout" : "");
return 0;
}
static int orion_wdt_remove(struct platform_device *pdev)
{
watchdog_unregister_device(&orion_wdt);
clk_disable_unprepare(clk);
return 0;
}
static void orion_wdt_shutdown(struct platform_device *pdev)
{
orion_wdt_stop(&orion_wdt);
}
static const struct of_device_id orion_wdt_of_match_table[] = {
{ .compatible = "marvell,orion-wdt", },
{},
};
MODULE_DEVICE_TABLE(of, orion_wdt_of_match_table);
static struct platform_driver orion_wdt_driver = {
.probe = orion_wdt_probe,
.remove = orion_wdt_remove,
.shutdown = orion_wdt_shutdown,
.driver = {
.owner = THIS_MODULE,
.name = "orion_wdt",
.of_match_table = of_match_ptr(orion_wdt_of_match_table),
},
};
module_platform_driver(orion_wdt_driver);
MODULE_AUTHOR("Sylver Bruneau <sylver.bruneau@googlemail.com>");
MODULE_DESCRIPTION("Orion Processor Watchdog");
module_param(heartbeat, int, 0);
MODULE_PARM_DESC(heartbeat, "Initial watchdog heartbeat in seconds");
module_param(nowayout, bool, 0);
MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started (default="
__MODULE_STRING(WATCHDOG_NOWAYOUT) ")");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:orion_wdt");
MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR);
| gpl-2.0 |
miuihu/android_kernel_xiaomi_redmi2 | drivers/video/aty/radeon_base.c | 2398 | 76767 | /*
* drivers/video/aty/radeon_base.c
*
* framebuffer driver for ATI Radeon chipset video boards
*
* Copyright 2003 Ben. Herrenschmidt <benh@kernel.crashing.org>
* Copyright 2000 Ani Joshi <ajoshi@kernel.crashing.org>
*
* i2c bits from Luca Tettamanti <kronos@kronoz.cjb.net>
*
* Special thanks to ATI DevRel team for their hardware donations.
*
* ...Insert GPL boilerplate here...
*
* Significant portions of this driver apdated from XFree86 Radeon
* driver which has the following copyright notice:
*
* Copyright 2000 ATI Technologies Inc., Markham, Ontario, and
* VA Linux Systems Inc., Fremont, California.
*
* 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 on the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NON-INFRINGEMENT. IN NO EVENT SHALL ATI, VA LINUX SYSTEMS AND/OR
* THEIR 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.
*
* XFree86 driver authors:
*
* Kevin E. Martin <martin@xfree86.org>
* Rickard E. Faith <faith@valinux.com>
* Alan Hourihane <alanh@fairlite.demon.co.uk>
*
*/
#define RADEON_VERSION "0.2.0"
#include "radeonfb.h"
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/ctype.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/time.h>
#include <linux/fb.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/vmalloc.h>
#include <linux/device.h>
#include <asm/io.h>
#include <linux/uaccess.h>
#ifdef CONFIG_PPC_OF
#include <asm/pci-bridge.h>
#include "../macmodes.h"
#ifdef CONFIG_BOOTX_TEXT
#include <asm/btext.h>
#endif
#endif /* CONFIG_PPC_OF */
#ifdef CONFIG_MTRR
#include <asm/mtrr.h>
#endif
#include <video/radeon.h>
#include <linux/radeonfb.h>
#include "../edid.h" // MOVE THAT TO include/video
#include "ati_ids.h"
#define MAX_MAPPED_VRAM (2048*2048*4)
#define MIN_MAPPED_VRAM (1024*768*1)
#define CHIP_DEF(id, family, flags) \
{ PCI_VENDOR_ID_ATI, id, PCI_ANY_ID, PCI_ANY_ID, 0, 0, (flags) | (CHIP_FAMILY_##family) }
static struct pci_device_id radeonfb_pci_table[] = {
/* Radeon Xpress 200m */
CHIP_DEF(PCI_CHIP_RS480_5955, RS480, CHIP_HAS_CRTC2 | CHIP_IS_IGP | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RS482_5975, RS480, CHIP_HAS_CRTC2 | CHIP_IS_IGP | CHIP_IS_MOBILITY),
/* Mobility M6 */
CHIP_DEF(PCI_CHIP_RADEON_LY, RV100, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RADEON_LZ, RV100, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
/* Radeon VE/7000 */
CHIP_DEF(PCI_CHIP_RV100_QY, RV100, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV100_QZ, RV100, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RN50, RV100, CHIP_HAS_CRTC2),
/* Radeon IGP320M (U1) */
CHIP_DEF(PCI_CHIP_RS100_4336, RS100, CHIP_HAS_CRTC2 | CHIP_IS_IGP | CHIP_IS_MOBILITY),
/* Radeon IGP320 (A3) */
CHIP_DEF(PCI_CHIP_RS100_4136, RS100, CHIP_HAS_CRTC2 | CHIP_IS_IGP),
/* IGP330M/340M/350M (U2) */
CHIP_DEF(PCI_CHIP_RS200_4337, RS200, CHIP_HAS_CRTC2 | CHIP_IS_IGP | CHIP_IS_MOBILITY),
/* IGP330/340/350 (A4) */
CHIP_DEF(PCI_CHIP_RS200_4137, RS200, CHIP_HAS_CRTC2 | CHIP_IS_IGP),
/* Mobility 7000 IGP */
CHIP_DEF(PCI_CHIP_RS250_4437, RS200, CHIP_HAS_CRTC2 | CHIP_IS_IGP | CHIP_IS_MOBILITY),
/* 7000 IGP (A4+) */
CHIP_DEF(PCI_CHIP_RS250_4237, RS200, CHIP_HAS_CRTC2 | CHIP_IS_IGP),
/* 8500 AIW */
CHIP_DEF(PCI_CHIP_R200_BB, R200, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R200_BC, R200, CHIP_HAS_CRTC2),
/* 8700/8800 */
CHIP_DEF(PCI_CHIP_R200_QH, R200, CHIP_HAS_CRTC2),
/* 8500 */
CHIP_DEF(PCI_CHIP_R200_QL, R200, CHIP_HAS_CRTC2),
/* 9100 */
CHIP_DEF(PCI_CHIP_R200_QM, R200, CHIP_HAS_CRTC2),
/* Mobility M7 */
CHIP_DEF(PCI_CHIP_RADEON_LW, RV200, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RADEON_LX, RV200, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
/* 7500 */
CHIP_DEF(PCI_CHIP_RV200_QW, RV200, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV200_QX, RV200, CHIP_HAS_CRTC2),
/* Mobility M9 */
CHIP_DEF(PCI_CHIP_RV250_Ld, RV250, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV250_Le, RV250, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV250_Lf, RV250, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV250_Lg, RV250, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
/* 9000/Pro */
CHIP_DEF(PCI_CHIP_RV250_If, RV250, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV250_Ig, RV250, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RC410_5A62, RC410, CHIP_HAS_CRTC2 | CHIP_IS_IGP | CHIP_IS_MOBILITY),
/* Mobility 9100 IGP (U3) */
CHIP_DEF(PCI_CHIP_RS300_5835, RS300, CHIP_HAS_CRTC2 | CHIP_IS_IGP | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RS350_7835, RS300, CHIP_HAS_CRTC2 | CHIP_IS_IGP | CHIP_IS_MOBILITY),
/* 9100 IGP (A5) */
CHIP_DEF(PCI_CHIP_RS300_5834, RS300, CHIP_HAS_CRTC2 | CHIP_IS_IGP),
CHIP_DEF(PCI_CHIP_RS350_7834, RS300, CHIP_HAS_CRTC2 | CHIP_IS_IGP),
/* Mobility 9200 (M9+) */
CHIP_DEF(PCI_CHIP_RV280_5C61, RV280, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV280_5C63, RV280, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
/* 9200 */
CHIP_DEF(PCI_CHIP_RV280_5960, RV280, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV280_5961, RV280, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV280_5962, RV280, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV280_5964, RV280, CHIP_HAS_CRTC2),
/* 9500 */
CHIP_DEF(PCI_CHIP_R300_AD, R300, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R300_AE, R300, CHIP_HAS_CRTC2),
/* 9600TX / FireGL Z1 */
CHIP_DEF(PCI_CHIP_R300_AF, R300, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R300_AG, R300, CHIP_HAS_CRTC2),
/* 9700/9500/Pro/FireGL X1 */
CHIP_DEF(PCI_CHIP_R300_ND, R300, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R300_NE, R300, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R300_NF, R300, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R300_NG, R300, CHIP_HAS_CRTC2),
/* Mobility M10/M11 */
CHIP_DEF(PCI_CHIP_RV350_NP, RV350, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV350_NQ, RV350, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV350_NR, RV350, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV350_NS, RV350, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV350_NT, RV350, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV350_NV, RV350, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
/* 9600/FireGL T2 */
CHIP_DEF(PCI_CHIP_RV350_AP, RV350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV350_AQ, RV350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV360_AR, RV350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV350_AS, RV350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV350_AT, RV350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV350_AV, RV350, CHIP_HAS_CRTC2),
/* 9800/Pro/FileGL X2 */
CHIP_DEF(PCI_CHIP_R350_AH, R350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R350_AI, R350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R350_AJ, R350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R350_AK, R350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R350_NH, R350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R350_NI, R350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R360_NJ, R350, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R350_NK, R350, CHIP_HAS_CRTC2),
/* Newer stuff */
CHIP_DEF(PCI_CHIP_RV380_3E50, RV380, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV380_3E54, RV380, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV380_3150, RV380, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV380_3154, RV380, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV370_5B60, RV380, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV370_5B62, RV380, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV370_5B63, RV380, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV370_5B64, RV380, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV370_5B65, RV380, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_RV370_5460, RV380, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_RV370_5464, RV380, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_R420_JH, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R420_JI, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R420_JJ, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R420_JK, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R420_JL, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R420_JM, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R420_JN, R420, CHIP_HAS_CRTC2 | CHIP_IS_MOBILITY),
CHIP_DEF(PCI_CHIP_R420_JP, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R423_UH, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R423_UI, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R423_UJ, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R423_UK, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R423_UQ, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R423_UR, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R423_UT, R420, CHIP_HAS_CRTC2),
CHIP_DEF(PCI_CHIP_R423_5D57, R420, CHIP_HAS_CRTC2),
/* Original Radeon/7200 */
CHIP_DEF(PCI_CHIP_RADEON_QD, RADEON, 0),
CHIP_DEF(PCI_CHIP_RADEON_QE, RADEON, 0),
CHIP_DEF(PCI_CHIP_RADEON_QF, RADEON, 0),
CHIP_DEF(PCI_CHIP_RADEON_QG, RADEON, 0),
{ 0, }
};
MODULE_DEVICE_TABLE(pci, radeonfb_pci_table);
typedef struct {
u16 reg;
u32 val;
} reg_val;
/* these common regs are cleared before mode setting so they do not
* interfere with anything
*/
static reg_val common_regs[] = {
{ OVR_CLR, 0 },
{ OVR_WID_LEFT_RIGHT, 0 },
{ OVR_WID_TOP_BOTTOM, 0 },
{ OV0_SCALE_CNTL, 0 },
{ SUBPIC_CNTL, 0 },
{ VIPH_CONTROL, 0 },
{ I2C_CNTL_1, 0 },
{ GEN_INT_CNTL, 0 },
{ CAP0_TRIG_CNTL, 0 },
{ CAP1_TRIG_CNTL, 0 },
};
/*
* globals
*/
static char *mode_option;
static char *monitor_layout;
static bool noaccel = 0;
static int default_dynclk = -2;
static bool nomodeset = 0;
static bool ignore_edid = 0;
static bool mirror = 0;
static int panel_yres = 0;
static bool force_dfp = 0;
static bool force_measure_pll = 0;
#ifdef CONFIG_MTRR
static bool nomtrr = 0;
#endif
static bool force_sleep;
static bool ignore_devlist;
#ifdef CONFIG_PMAC_BACKLIGHT
static int backlight = 1;
#else
static int backlight = 0;
#endif
/*
* prototypes
*/
static void radeon_unmap_ROM(struct radeonfb_info *rinfo, struct pci_dev *dev)
{
if (!rinfo->bios_seg)
return;
pci_unmap_rom(dev, rinfo->bios_seg);
}
static int radeon_map_ROM(struct radeonfb_info *rinfo, struct pci_dev *dev)
{
void __iomem *rom;
u16 dptr;
u8 rom_type;
size_t rom_size;
/* If this is a primary card, there is a shadow copy of the
* ROM somewhere in the first meg. We will just ignore the copy
* and use the ROM directly.
*/
/* Fix from ATI for problem with Radeon hardware not leaving ROM enabled */
unsigned int temp;
temp = INREG(MPP_TB_CONFIG);
temp &= 0x00ffffffu;
temp |= 0x04 << 24;
OUTREG(MPP_TB_CONFIG, temp);
temp = INREG(MPP_TB_CONFIG);
rom = pci_map_rom(dev, &rom_size);
if (!rom) {
printk(KERN_ERR "radeonfb (%s): ROM failed to map\n",
pci_name(rinfo->pdev));
return -ENOMEM;
}
rinfo->bios_seg = rom;
/* Very simple test to make sure it appeared */
if (BIOS_IN16(0) != 0xaa55) {
printk(KERN_DEBUG "radeonfb (%s): Invalid ROM signature %x "
"should be 0xaa55\n",
pci_name(rinfo->pdev), BIOS_IN16(0));
goto failed;
}
/* Look for the PCI data to check the ROM type */
dptr = BIOS_IN16(0x18);
/* Check the PCI data signature. If it's wrong, we still assume a normal x86 ROM
* for now, until I've verified this works everywhere. The goal here is more
* to phase out Open Firmware images.
*
* Currently, we only look at the first PCI data, we could iteratre and deal with
* them all, and we should use fb_bios_start relative to start of image and not
* relative start of ROM, but so far, I never found a dual-image ATI card
*
* typedef struct {
* u32 signature; + 0x00
* u16 vendor; + 0x04
* u16 device; + 0x06
* u16 reserved_1; + 0x08
* u16 dlen; + 0x0a
* u8 drevision; + 0x0c
* u8 class_hi; + 0x0d
* u16 class_lo; + 0x0e
* u16 ilen; + 0x10
* u16 irevision; + 0x12
* u8 type; + 0x14
* u8 indicator; + 0x15
* u16 reserved_2; + 0x16
* } pci_data_t;
*/
if (BIOS_IN32(dptr) != (('R' << 24) | ('I' << 16) | ('C' << 8) | 'P')) {
printk(KERN_WARNING "radeonfb (%s): PCI DATA signature in ROM"
"incorrect: %08x\n", pci_name(rinfo->pdev), BIOS_IN32(dptr));
goto anyway;
}
rom_type = BIOS_IN8(dptr + 0x14);
switch(rom_type) {
case 0:
printk(KERN_INFO "radeonfb: Found Intel x86 BIOS ROM Image\n");
break;
case 1:
printk(KERN_INFO "radeonfb: Found Open Firmware ROM Image\n");
goto failed;
case 2:
printk(KERN_INFO "radeonfb: Found HP PA-RISC ROM Image\n");
goto failed;
default:
printk(KERN_INFO "radeonfb: Found unknown type %d ROM Image\n", rom_type);
goto failed;
}
anyway:
/* Locate the flat panel infos, do some sanity checking !!! */
rinfo->fp_bios_start = BIOS_IN16(0x48);
return 0;
failed:
rinfo->bios_seg = NULL;
radeon_unmap_ROM(rinfo, dev);
return -ENXIO;
}
#ifdef CONFIG_X86
static int radeon_find_mem_vbios(struct radeonfb_info *rinfo)
{
/* I simplified this code as we used to miss the signatures in
* a lot of case. It's now closer to XFree, we just don't check
* for signatures at all... Something better will have to be done
* if we end up having conflicts
*/
u32 segstart;
void __iomem *rom_base = NULL;
for(segstart=0x000c0000; segstart<0x000f0000; segstart+=0x00001000) {
rom_base = ioremap(segstart, 0x10000);
if (rom_base == NULL)
return -ENOMEM;
if (readb(rom_base) == 0x55 && readb(rom_base + 1) == 0xaa)
break;
iounmap(rom_base);
rom_base = NULL;
}
if (rom_base == NULL)
return -ENXIO;
/* Locate the flat panel infos, do some sanity checking !!! */
rinfo->bios_seg = rom_base;
rinfo->fp_bios_start = BIOS_IN16(0x48);
return 0;
}
#endif
#if defined(CONFIG_PPC_OF) || defined(CONFIG_SPARC)
/*
* Read XTAL (ref clock), SCLK and MCLK from Open Firmware device
* tree. Hopefully, ATI OF driver is kind enough to fill these
*/
static int radeon_read_xtal_OF(struct radeonfb_info *rinfo)
{
struct device_node *dp = rinfo->of_node;
const u32 *val;
if (dp == NULL)
return -ENODEV;
val = of_get_property(dp, "ATY,RefCLK", NULL);
if (!val || !*val) {
printk(KERN_WARNING "radeonfb: No ATY,RefCLK property !\n");
return -EINVAL;
}
rinfo->pll.ref_clk = (*val) / 10;
val = of_get_property(dp, "ATY,SCLK", NULL);
if (val && *val)
rinfo->pll.sclk = (*val) / 10;
val = of_get_property(dp, "ATY,MCLK", NULL);
if (val && *val)
rinfo->pll.mclk = (*val) / 10;
return 0;
}
#endif /* CONFIG_PPC_OF || CONFIG_SPARC */
/*
* Read PLL infos from chip registers
*/
static int radeon_probe_pll_params(struct radeonfb_info *rinfo)
{
unsigned char ppll_div_sel;
unsigned Ns, Nm, M;
unsigned sclk, mclk, tmp, ref_div;
int hTotal, vTotal, num, denom, m, n;
unsigned long long hz, vclk;
long xtal;
struct timeval start_tv, stop_tv;
long total_secs, total_usecs;
int i;
/* Ugh, we cut interrupts, bad bad bad, but we want some precision
* here, so... --BenH
*/
/* Flush PCI buffers ? */
tmp = INREG16(DEVICE_ID);
local_irq_disable();
for(i=0; i<1000000; i++)
if (((INREG(CRTC_VLINE_CRNT_VLINE) >> 16) & 0x3ff) == 0)
break;
do_gettimeofday(&start_tv);
for(i=0; i<1000000; i++)
if (((INREG(CRTC_VLINE_CRNT_VLINE) >> 16) & 0x3ff) != 0)
break;
for(i=0; i<1000000; i++)
if (((INREG(CRTC_VLINE_CRNT_VLINE) >> 16) & 0x3ff) == 0)
break;
do_gettimeofday(&stop_tv);
local_irq_enable();
total_secs = stop_tv.tv_sec - start_tv.tv_sec;
if (total_secs > 10)
return -1;
total_usecs = stop_tv.tv_usec - start_tv.tv_usec;
total_usecs += total_secs * 1000000;
if (total_usecs < 0)
total_usecs = -total_usecs;
hz = 1000000/total_usecs;
hTotal = ((INREG(CRTC_H_TOTAL_DISP) & 0x1ff) + 1) * 8;
vTotal = ((INREG(CRTC_V_TOTAL_DISP) & 0x3ff) + 1);
vclk = (long long)hTotal * (long long)vTotal * hz;
switch((INPLL(PPLL_REF_DIV) & 0x30000) >> 16) {
case 0:
default:
num = 1;
denom = 1;
break;
case 1:
n = ((INPLL(M_SPLL_REF_FB_DIV) >> 16) & 0xff);
m = (INPLL(M_SPLL_REF_FB_DIV) & 0xff);
num = 2*n;
denom = 2*m;
break;
case 2:
n = ((INPLL(M_SPLL_REF_FB_DIV) >> 8) & 0xff);
m = (INPLL(M_SPLL_REF_FB_DIV) & 0xff);
num = 2*n;
denom = 2*m;
break;
}
ppll_div_sel = INREG8(CLOCK_CNTL_INDEX + 1) & 0x3;
radeon_pll_errata_after_index(rinfo);
n = (INPLL(PPLL_DIV_0 + ppll_div_sel) & 0x7ff);
m = (INPLL(PPLL_REF_DIV) & 0x3ff);
num *= n;
denom *= m;
switch ((INPLL(PPLL_DIV_0 + ppll_div_sel) >> 16) & 0x7) {
case 1:
denom *= 2;
break;
case 2:
denom *= 4;
break;
case 3:
denom *= 8;
break;
case 4:
denom *= 3;
break;
case 6:
denom *= 6;
break;
case 7:
denom *= 12;
break;
}
vclk *= denom;
do_div(vclk, 1000 * num);
xtal = vclk;
if ((xtal > 26900) && (xtal < 27100))
xtal = 2700;
else if ((xtal > 14200) && (xtal < 14400))
xtal = 1432;
else if ((xtal > 29400) && (xtal < 29600))
xtal = 2950;
else {
printk(KERN_WARNING "xtal calculation failed: %ld\n", xtal);
return -1;
}
tmp = INPLL(M_SPLL_REF_FB_DIV);
ref_div = INPLL(PPLL_REF_DIV) & 0x3ff;
Ns = (tmp & 0xff0000) >> 16;
Nm = (tmp & 0xff00) >> 8;
M = (tmp & 0xff);
sclk = round_div((2 * Ns * xtal), (2 * M));
mclk = round_div((2 * Nm * xtal), (2 * M));
/* we're done, hopefully these are sane values */
rinfo->pll.ref_clk = xtal;
rinfo->pll.ref_div = ref_div;
rinfo->pll.sclk = sclk;
rinfo->pll.mclk = mclk;
return 0;
}
/*
* Retrieve PLL infos by different means (BIOS, Open Firmware, register probing...)
*/
static void radeon_get_pllinfo(struct radeonfb_info *rinfo)
{
/*
* In the case nothing works, these are defaults; they are mostly
* incomplete, however. It does provide ppll_max and _min values
* even for most other methods, however.
*/
switch (rinfo->chipset) {
case PCI_DEVICE_ID_ATI_RADEON_QW:
case PCI_DEVICE_ID_ATI_RADEON_QX:
rinfo->pll.ppll_max = 35000;
rinfo->pll.ppll_min = 12000;
rinfo->pll.mclk = 23000;
rinfo->pll.sclk = 23000;
rinfo->pll.ref_clk = 2700;
break;
case PCI_DEVICE_ID_ATI_RADEON_QL:
case PCI_DEVICE_ID_ATI_RADEON_QN:
case PCI_DEVICE_ID_ATI_RADEON_QO:
case PCI_DEVICE_ID_ATI_RADEON_Ql:
case PCI_DEVICE_ID_ATI_RADEON_BB:
rinfo->pll.ppll_max = 35000;
rinfo->pll.ppll_min = 12000;
rinfo->pll.mclk = 27500;
rinfo->pll.sclk = 27500;
rinfo->pll.ref_clk = 2700;
break;
case PCI_DEVICE_ID_ATI_RADEON_Id:
case PCI_DEVICE_ID_ATI_RADEON_Ie:
case PCI_DEVICE_ID_ATI_RADEON_If:
case PCI_DEVICE_ID_ATI_RADEON_Ig:
rinfo->pll.ppll_max = 35000;
rinfo->pll.ppll_min = 12000;
rinfo->pll.mclk = 25000;
rinfo->pll.sclk = 25000;
rinfo->pll.ref_clk = 2700;
break;
case PCI_DEVICE_ID_ATI_RADEON_ND:
case PCI_DEVICE_ID_ATI_RADEON_NE:
case PCI_DEVICE_ID_ATI_RADEON_NF:
case PCI_DEVICE_ID_ATI_RADEON_NG:
rinfo->pll.ppll_max = 40000;
rinfo->pll.ppll_min = 20000;
rinfo->pll.mclk = 27000;
rinfo->pll.sclk = 27000;
rinfo->pll.ref_clk = 2700;
break;
case PCI_DEVICE_ID_ATI_RADEON_QD:
case PCI_DEVICE_ID_ATI_RADEON_QE:
case PCI_DEVICE_ID_ATI_RADEON_QF:
case PCI_DEVICE_ID_ATI_RADEON_QG:
default:
rinfo->pll.ppll_max = 35000;
rinfo->pll.ppll_min = 12000;
rinfo->pll.mclk = 16600;
rinfo->pll.sclk = 16600;
rinfo->pll.ref_clk = 2700;
break;
}
rinfo->pll.ref_div = INPLL(PPLL_REF_DIV) & PPLL_REF_DIV_MASK;
#if defined(CONFIG_PPC_OF) || defined(CONFIG_SPARC)
/*
* Retrieve PLL infos from Open Firmware first
*/
if (!force_measure_pll && radeon_read_xtal_OF(rinfo) == 0) {
printk(KERN_INFO "radeonfb: Retrieved PLL infos from Open Firmware\n");
goto found;
}
#endif /* CONFIG_PPC_OF || CONFIG_SPARC */
/*
* Check out if we have an X86 which gave us some PLL informations
* and if yes, retrieve them
*/
if (!force_measure_pll && rinfo->bios_seg) {
u16 pll_info_block = BIOS_IN16(rinfo->fp_bios_start + 0x30);
rinfo->pll.sclk = BIOS_IN16(pll_info_block + 0x08);
rinfo->pll.mclk = BIOS_IN16(pll_info_block + 0x0a);
rinfo->pll.ref_clk = BIOS_IN16(pll_info_block + 0x0e);
rinfo->pll.ref_div = BIOS_IN16(pll_info_block + 0x10);
rinfo->pll.ppll_min = BIOS_IN32(pll_info_block + 0x12);
rinfo->pll.ppll_max = BIOS_IN32(pll_info_block + 0x16);
printk(KERN_INFO "radeonfb: Retrieved PLL infos from BIOS\n");
goto found;
}
/*
* We didn't get PLL parameters from either OF or BIOS, we try to
* probe them
*/
if (radeon_probe_pll_params(rinfo) == 0) {
printk(KERN_INFO "radeonfb: Retrieved PLL infos from registers\n");
goto found;
}
/*
* Fall back to already-set defaults...
*/
printk(KERN_INFO "radeonfb: Used default PLL infos\n");
found:
/*
* Some methods fail to retrieve SCLK and MCLK values, we apply default
* settings in this case (200Mhz). If that really happens often, we
* could fetch from registers instead...
*/
if (rinfo->pll.mclk == 0)
rinfo->pll.mclk = 20000;
if (rinfo->pll.sclk == 0)
rinfo->pll.sclk = 20000;
printk("radeonfb: Reference=%d.%02d MHz (RefDiv=%d) Memory=%d.%02d Mhz, System=%d.%02d MHz\n",
rinfo->pll.ref_clk / 100, rinfo->pll.ref_clk % 100,
rinfo->pll.ref_div,
rinfo->pll.mclk / 100, rinfo->pll.mclk % 100,
rinfo->pll.sclk / 100, rinfo->pll.sclk % 100);
printk("radeonfb: PLL min %d max %d\n", rinfo->pll.ppll_min, rinfo->pll.ppll_max);
}
static int radeonfb_check_var (struct fb_var_screeninfo *var, struct fb_info *info)
{
struct radeonfb_info *rinfo = info->par;
struct fb_var_screeninfo v;
int nom, den;
unsigned int pitch;
if (radeon_match_mode(rinfo, &v, var))
return -EINVAL;
switch (v.bits_per_pixel) {
case 0 ... 8:
v.bits_per_pixel = 8;
break;
case 9 ... 16:
v.bits_per_pixel = 16;
break;
case 17 ... 24:
#if 0 /* Doesn't seem to work */
v.bits_per_pixel = 24;
break;
#endif
return -EINVAL;
case 25 ... 32:
v.bits_per_pixel = 32;
break;
default:
return -EINVAL;
}
switch (var_to_depth(&v)) {
case 8:
nom = den = 1;
v.red.offset = v.green.offset = v.blue.offset = 0;
v.red.length = v.green.length = v.blue.length = 8;
v.transp.offset = v.transp.length = 0;
break;
case 15:
nom = 2;
den = 1;
v.red.offset = 10;
v.green.offset = 5;
v.blue.offset = 0;
v.red.length = v.green.length = v.blue.length = 5;
v.transp.offset = v.transp.length = 0;
break;
case 16:
nom = 2;
den = 1;
v.red.offset = 11;
v.green.offset = 5;
v.blue.offset = 0;
v.red.length = 5;
v.green.length = 6;
v.blue.length = 5;
v.transp.offset = v.transp.length = 0;
break;
case 24:
nom = 4;
den = 1;
v.red.offset = 16;
v.green.offset = 8;
v.blue.offset = 0;
v.red.length = v.blue.length = v.green.length = 8;
v.transp.offset = v.transp.length = 0;
break;
case 32:
nom = 4;
den = 1;
v.red.offset = 16;
v.green.offset = 8;
v.blue.offset = 0;
v.red.length = v.blue.length = v.green.length = 8;
v.transp.offset = 24;
v.transp.length = 8;
break;
default:
printk ("radeonfb: mode %dx%dx%d rejected, color depth invalid\n",
var->xres, var->yres, var->bits_per_pixel);
return -EINVAL;
}
if (v.yres_virtual < v.yres)
v.yres_virtual = v.yres;
if (v.xres_virtual < v.xres)
v.xres_virtual = v.xres;
/* XXX I'm adjusting xres_virtual to the pitch, that may help XFree
* with some panels, though I don't quite like this solution
*/
if (rinfo->info->flags & FBINFO_HWACCEL_DISABLED) {
v.xres_virtual = v.xres_virtual & ~7ul;
} else {
pitch = ((v.xres_virtual * ((v.bits_per_pixel + 1) / 8) + 0x3f)
& ~(0x3f)) >> 6;
v.xres_virtual = (pitch << 6) / ((v.bits_per_pixel + 1) / 8);
}
if (((v.xres_virtual * v.yres_virtual * nom) / den) > rinfo->mapped_vram)
return -EINVAL;
if (v.xres_virtual < v.xres)
v.xres = v.xres_virtual;
if (v.xoffset < 0)
v.xoffset = 0;
if (v.yoffset < 0)
v.yoffset = 0;
if (v.xoffset > v.xres_virtual - v.xres)
v.xoffset = v.xres_virtual - v.xres - 1;
if (v.yoffset > v.yres_virtual - v.yres)
v.yoffset = v.yres_virtual - v.yres - 1;
v.red.msb_right = v.green.msb_right = v.blue.msb_right =
v.transp.offset = v.transp.length =
v.transp.msb_right = 0;
memcpy(var, &v, sizeof(v));
return 0;
}
static int radeonfb_pan_display (struct fb_var_screeninfo *var,
struct fb_info *info)
{
struct radeonfb_info *rinfo = info->par;
if ((var->xoffset + info->var.xres > info->var.xres_virtual)
|| (var->yoffset + info->var.yres > info->var.yres_virtual))
return -EINVAL;
if (rinfo->asleep)
return 0;
radeon_fifo_wait(2);
OUTREG(CRTC_OFFSET, (var->yoffset * info->fix.line_length +
var->xoffset * info->var.bits_per_pixel / 8) & ~7);
return 0;
}
static int radeonfb_ioctl (struct fb_info *info, unsigned int cmd,
unsigned long arg)
{
struct radeonfb_info *rinfo = info->par;
unsigned int tmp;
u32 value = 0;
int rc;
switch (cmd) {
/*
* TODO: set mirror accordingly for non-Mobility chipsets with 2 CRTC's
* and do something better using 2nd CRTC instead of just hackish
* routing to second output
*/
case FBIO_RADEON_SET_MIRROR:
if (!rinfo->is_mobility)
return -EINVAL;
rc = get_user(value, (__u32 __user *)arg);
if (rc)
return rc;
radeon_fifo_wait(2);
if (value & 0x01) {
tmp = INREG(LVDS_GEN_CNTL);
tmp |= (LVDS_ON | LVDS_BLON);
} else {
tmp = INREG(LVDS_GEN_CNTL);
tmp &= ~(LVDS_ON | LVDS_BLON);
}
OUTREG(LVDS_GEN_CNTL, tmp);
if (value & 0x02) {
tmp = INREG(CRTC_EXT_CNTL);
tmp |= CRTC_CRT_ON;
mirror = 1;
} else {
tmp = INREG(CRTC_EXT_CNTL);
tmp &= ~CRTC_CRT_ON;
mirror = 0;
}
OUTREG(CRTC_EXT_CNTL, tmp);
return 0;
case FBIO_RADEON_GET_MIRROR:
if (!rinfo->is_mobility)
return -EINVAL;
tmp = INREG(LVDS_GEN_CNTL);
if ((LVDS_ON | LVDS_BLON) & tmp)
value |= 0x01;
tmp = INREG(CRTC_EXT_CNTL);
if (CRTC_CRT_ON & tmp)
value |= 0x02;
return put_user(value, (__u32 __user *)arg);
default:
return -EINVAL;
}
return -EINVAL;
}
int radeon_screen_blank(struct radeonfb_info *rinfo, int blank, int mode_switch)
{
u32 val;
u32 tmp_pix_clks;
int unblank = 0;
if (rinfo->lock_blank)
return 0;
radeon_engine_idle();
val = INREG(CRTC_EXT_CNTL);
val &= ~(CRTC_DISPLAY_DIS | CRTC_HSYNC_DIS |
CRTC_VSYNC_DIS);
switch (blank) {
case FB_BLANK_VSYNC_SUSPEND:
val |= (CRTC_DISPLAY_DIS | CRTC_VSYNC_DIS);
break;
case FB_BLANK_HSYNC_SUSPEND:
val |= (CRTC_DISPLAY_DIS | CRTC_HSYNC_DIS);
break;
case FB_BLANK_POWERDOWN:
val |= (CRTC_DISPLAY_DIS | CRTC_VSYNC_DIS |
CRTC_HSYNC_DIS);
break;
case FB_BLANK_NORMAL:
val |= CRTC_DISPLAY_DIS;
break;
case FB_BLANK_UNBLANK:
default:
unblank = 1;
}
OUTREG(CRTC_EXT_CNTL, val);
switch (rinfo->mon1_type) {
case MT_DFP:
if (unblank)
OUTREGP(FP_GEN_CNTL, (FP_FPON | FP_TMDS_EN),
~(FP_FPON | FP_TMDS_EN));
else {
if (mode_switch || blank == FB_BLANK_NORMAL)
break;
OUTREGP(FP_GEN_CNTL, 0, ~(FP_FPON | FP_TMDS_EN));
}
break;
case MT_LCD:
del_timer_sync(&rinfo->lvds_timer);
val = INREG(LVDS_GEN_CNTL);
if (unblank) {
u32 target_val = (val & ~LVDS_DISPLAY_DIS) | LVDS_BLON | LVDS_ON
| LVDS_EN | (rinfo->init_state.lvds_gen_cntl
& (LVDS_DIGON | LVDS_BL_MOD_EN));
if ((val ^ target_val) == LVDS_DISPLAY_DIS)
OUTREG(LVDS_GEN_CNTL, target_val);
else if ((val ^ target_val) != 0) {
OUTREG(LVDS_GEN_CNTL, target_val
& ~(LVDS_ON | LVDS_BL_MOD_EN));
rinfo->init_state.lvds_gen_cntl &= ~LVDS_STATE_MASK;
rinfo->init_state.lvds_gen_cntl |=
target_val & LVDS_STATE_MASK;
if (mode_switch) {
radeon_msleep(rinfo->panel_info.pwr_delay);
OUTREG(LVDS_GEN_CNTL, target_val);
}
else {
rinfo->pending_lvds_gen_cntl = target_val;
mod_timer(&rinfo->lvds_timer,
jiffies +
msecs_to_jiffies(rinfo->panel_info.pwr_delay));
}
}
} else {
val |= LVDS_DISPLAY_DIS;
OUTREG(LVDS_GEN_CNTL, val);
/* We don't do a full switch-off on a simple mode switch */
if (mode_switch || blank == FB_BLANK_NORMAL)
break;
/* Asic bug, when turning off LVDS_ON, we have to make sure
* RADEON_PIXCLK_LVDS_ALWAYS_ON bit is off
*/
tmp_pix_clks = INPLL(PIXCLKS_CNTL);
if (rinfo->is_mobility || rinfo->is_IGP)
OUTPLLP(PIXCLKS_CNTL, 0, ~PIXCLK_LVDS_ALWAYS_ONb);
val &= ~(LVDS_BL_MOD_EN);
OUTREG(LVDS_GEN_CNTL, val);
udelay(100);
val &= ~(LVDS_ON | LVDS_EN);
OUTREG(LVDS_GEN_CNTL, val);
val &= ~LVDS_DIGON;
rinfo->pending_lvds_gen_cntl = val;
mod_timer(&rinfo->lvds_timer,
jiffies +
msecs_to_jiffies(rinfo->panel_info.pwr_delay));
rinfo->init_state.lvds_gen_cntl &= ~LVDS_STATE_MASK;
rinfo->init_state.lvds_gen_cntl |= val & LVDS_STATE_MASK;
if (rinfo->is_mobility || rinfo->is_IGP)
OUTPLL(PIXCLKS_CNTL, tmp_pix_clks);
}
break;
case MT_CRT:
// todo: powerdown DAC
default:
break;
}
return 0;
}
static int radeonfb_blank (int blank, struct fb_info *info)
{
struct radeonfb_info *rinfo = info->par;
if (rinfo->asleep)
return 0;
return radeon_screen_blank(rinfo, blank, 0);
}
static int radeon_setcolreg (unsigned regno, unsigned red, unsigned green,
unsigned blue, unsigned transp,
struct radeonfb_info *rinfo)
{
u32 pindex;
unsigned int i;
if (regno > 255)
return -EINVAL;
red >>= 8;
green >>= 8;
blue >>= 8;
rinfo->palette[regno].red = red;
rinfo->palette[regno].green = green;
rinfo->palette[regno].blue = blue;
/* default */
pindex = regno;
if (!rinfo->asleep) {
radeon_fifo_wait(9);
if (rinfo->bpp == 16) {
pindex = regno * 8;
if (rinfo->depth == 16 && regno > 63)
return -EINVAL;
if (rinfo->depth == 15 && regno > 31)
return -EINVAL;
/* For 565, the green component is mixed one order
* below
*/
if (rinfo->depth == 16) {
OUTREG(PALETTE_INDEX, pindex>>1);
OUTREG(PALETTE_DATA,
(rinfo->palette[regno>>1].red << 16) |
(green << 8) |
(rinfo->palette[regno>>1].blue));
green = rinfo->palette[regno<<1].green;
}
}
if (rinfo->depth != 16 || regno < 32) {
OUTREG(PALETTE_INDEX, pindex);
OUTREG(PALETTE_DATA, (red << 16) |
(green << 8) | blue);
}
}
if (regno < 16) {
u32 *pal = rinfo->info->pseudo_palette;
switch (rinfo->depth) {
case 15:
pal[regno] = (regno << 10) | (regno << 5) | regno;
break;
case 16:
pal[regno] = (regno << 11) | (regno << 5) | regno;
break;
case 24:
pal[regno] = (regno << 16) | (regno << 8) | regno;
break;
case 32:
i = (regno << 8) | regno;
pal[regno] = (i << 16) | i;
break;
}
}
return 0;
}
static int radeonfb_setcolreg (unsigned regno, unsigned red, unsigned green,
unsigned blue, unsigned transp,
struct fb_info *info)
{
struct radeonfb_info *rinfo = info->par;
u32 dac_cntl2, vclk_cntl = 0;
int rc;
if (!rinfo->asleep) {
if (rinfo->is_mobility) {
vclk_cntl = INPLL(VCLK_ECP_CNTL);
OUTPLL(VCLK_ECP_CNTL,
vclk_cntl & ~PIXCLK_DAC_ALWAYS_ONb);
}
/* Make sure we are on first palette */
if (rinfo->has_CRTC2) {
dac_cntl2 = INREG(DAC_CNTL2);
dac_cntl2 &= ~DAC2_PALETTE_ACCESS_CNTL;
OUTREG(DAC_CNTL2, dac_cntl2);
}
}
rc = radeon_setcolreg (regno, red, green, blue, transp, rinfo);
if (!rinfo->asleep && rinfo->is_mobility)
OUTPLL(VCLK_ECP_CNTL, vclk_cntl);
return rc;
}
static int radeonfb_setcmap(struct fb_cmap *cmap, struct fb_info *info)
{
struct radeonfb_info *rinfo = info->par;
u16 *red, *green, *blue, *transp;
u32 dac_cntl2, vclk_cntl = 0;
int i, start, rc = 0;
if (!rinfo->asleep) {
if (rinfo->is_mobility) {
vclk_cntl = INPLL(VCLK_ECP_CNTL);
OUTPLL(VCLK_ECP_CNTL,
vclk_cntl & ~PIXCLK_DAC_ALWAYS_ONb);
}
/* Make sure we are on first palette */
if (rinfo->has_CRTC2) {
dac_cntl2 = INREG(DAC_CNTL2);
dac_cntl2 &= ~DAC2_PALETTE_ACCESS_CNTL;
OUTREG(DAC_CNTL2, dac_cntl2);
}
}
red = cmap->red;
green = cmap->green;
blue = cmap->blue;
transp = cmap->transp;
start = cmap->start;
for (i = 0; i < cmap->len; i++) {
u_int hred, hgreen, hblue, htransp = 0xffff;
hred = *red++;
hgreen = *green++;
hblue = *blue++;
if (transp)
htransp = *transp++;
rc = radeon_setcolreg (start++, hred, hgreen, hblue, htransp,
rinfo);
if (rc)
break;
}
if (!rinfo->asleep && rinfo->is_mobility)
OUTPLL(VCLK_ECP_CNTL, vclk_cntl);
return rc;
}
static void radeon_save_state (struct radeonfb_info *rinfo,
struct radeon_regs *save)
{
/* CRTC regs */
save->crtc_gen_cntl = INREG(CRTC_GEN_CNTL);
save->crtc_ext_cntl = INREG(CRTC_EXT_CNTL);
save->crtc_more_cntl = INREG(CRTC_MORE_CNTL);
save->dac_cntl = INREG(DAC_CNTL);
save->crtc_h_total_disp = INREG(CRTC_H_TOTAL_DISP);
save->crtc_h_sync_strt_wid = INREG(CRTC_H_SYNC_STRT_WID);
save->crtc_v_total_disp = INREG(CRTC_V_TOTAL_DISP);
save->crtc_v_sync_strt_wid = INREG(CRTC_V_SYNC_STRT_WID);
save->crtc_pitch = INREG(CRTC_PITCH);
save->surface_cntl = INREG(SURFACE_CNTL);
/* FP regs */
save->fp_crtc_h_total_disp = INREG(FP_CRTC_H_TOTAL_DISP);
save->fp_crtc_v_total_disp = INREG(FP_CRTC_V_TOTAL_DISP);
save->fp_gen_cntl = INREG(FP_GEN_CNTL);
save->fp_h_sync_strt_wid = INREG(FP_H_SYNC_STRT_WID);
save->fp_horz_stretch = INREG(FP_HORZ_STRETCH);
save->fp_v_sync_strt_wid = INREG(FP_V_SYNC_STRT_WID);
save->fp_vert_stretch = INREG(FP_VERT_STRETCH);
save->lvds_gen_cntl = INREG(LVDS_GEN_CNTL);
save->lvds_pll_cntl = INREG(LVDS_PLL_CNTL);
save->tmds_crc = INREG(TMDS_CRC);
save->tmds_transmitter_cntl = INREG(TMDS_TRANSMITTER_CNTL);
save->vclk_ecp_cntl = INPLL(VCLK_ECP_CNTL);
/* PLL regs */
save->clk_cntl_index = INREG(CLOCK_CNTL_INDEX) & ~0x3f;
radeon_pll_errata_after_index(rinfo);
save->ppll_div_3 = INPLL(PPLL_DIV_3);
save->ppll_ref_div = INPLL(PPLL_REF_DIV);
}
static void radeon_write_pll_regs(struct radeonfb_info *rinfo, struct radeon_regs *mode)
{
int i;
radeon_fifo_wait(20);
/* Workaround from XFree */
if (rinfo->is_mobility) {
/* A temporal workaround for the occasional blanking on certain laptop
* panels. This appears to related to the PLL divider registers
* (fail to lock?). It occurs even when all dividers are the same
* with their old settings. In this case we really don't need to
* fiddle with PLL registers. By doing this we can avoid the blanking
* problem with some panels.
*/
if ((mode->ppll_ref_div == (INPLL(PPLL_REF_DIV) & PPLL_REF_DIV_MASK)) &&
(mode->ppll_div_3 == (INPLL(PPLL_DIV_3) &
(PPLL_POST3_DIV_MASK | PPLL_FB3_DIV_MASK)))) {
/* We still have to force a switch to selected PPLL div thanks to
* an XFree86 driver bug which will switch it away in some cases
* even when using UseFDev */
OUTREGP(CLOCK_CNTL_INDEX,
mode->clk_cntl_index & PPLL_DIV_SEL_MASK,
~PPLL_DIV_SEL_MASK);
radeon_pll_errata_after_index(rinfo);
radeon_pll_errata_after_data(rinfo);
return;
}
}
/* Swich VCKL clock input to CPUCLK so it stays fed while PPLL updates*/
OUTPLLP(VCLK_ECP_CNTL, VCLK_SRC_SEL_CPUCLK, ~VCLK_SRC_SEL_MASK);
/* Reset PPLL & enable atomic update */
OUTPLLP(PPLL_CNTL,
PPLL_RESET | PPLL_ATOMIC_UPDATE_EN | PPLL_VGA_ATOMIC_UPDATE_EN,
~(PPLL_RESET | PPLL_ATOMIC_UPDATE_EN | PPLL_VGA_ATOMIC_UPDATE_EN));
/* Switch to selected PPLL divider */
OUTREGP(CLOCK_CNTL_INDEX,
mode->clk_cntl_index & PPLL_DIV_SEL_MASK,
~PPLL_DIV_SEL_MASK);
radeon_pll_errata_after_index(rinfo);
radeon_pll_errata_after_data(rinfo);
/* Set PPLL ref. div */
if (IS_R300_VARIANT(rinfo) ||
rinfo->family == CHIP_FAMILY_RS300 ||
rinfo->family == CHIP_FAMILY_RS400 ||
rinfo->family == CHIP_FAMILY_RS480) {
if (mode->ppll_ref_div & R300_PPLL_REF_DIV_ACC_MASK) {
/* When restoring console mode, use saved PPLL_REF_DIV
* setting.
*/
OUTPLLP(PPLL_REF_DIV, mode->ppll_ref_div, 0);
} else {
/* R300 uses ref_div_acc field as real ref divider */
OUTPLLP(PPLL_REF_DIV,
(mode->ppll_ref_div << R300_PPLL_REF_DIV_ACC_SHIFT),
~R300_PPLL_REF_DIV_ACC_MASK);
}
} else
OUTPLLP(PPLL_REF_DIV, mode->ppll_ref_div, ~PPLL_REF_DIV_MASK);
/* Set PPLL divider 3 & post divider*/
OUTPLLP(PPLL_DIV_3, mode->ppll_div_3, ~PPLL_FB3_DIV_MASK);
OUTPLLP(PPLL_DIV_3, mode->ppll_div_3, ~PPLL_POST3_DIV_MASK);
/* Write update */
while (INPLL(PPLL_REF_DIV) & PPLL_ATOMIC_UPDATE_R)
;
OUTPLLP(PPLL_REF_DIV, PPLL_ATOMIC_UPDATE_W, ~PPLL_ATOMIC_UPDATE_W);
/* Wait read update complete */
/* FIXME: Certain revisions of R300 can't recover here. Not sure of
the cause yet, but this workaround will mask the problem for now.
Other chips usually will pass at the very first test, so the
workaround shouldn't have any effect on them. */
for (i = 0; (i < 10000 && INPLL(PPLL_REF_DIV) & PPLL_ATOMIC_UPDATE_R); i++)
;
OUTPLL(HTOTAL_CNTL, 0);
/* Clear reset & atomic update */
OUTPLLP(PPLL_CNTL, 0,
~(PPLL_RESET | PPLL_SLEEP | PPLL_ATOMIC_UPDATE_EN | PPLL_VGA_ATOMIC_UPDATE_EN));
/* We may want some locking ... oh well */
radeon_msleep(5);
/* Switch back VCLK source to PPLL */
OUTPLLP(VCLK_ECP_CNTL, VCLK_SRC_SEL_PPLLCLK, ~VCLK_SRC_SEL_MASK);
}
/*
* Timer function for delayed LVDS panel power up/down
*/
static void radeon_lvds_timer_func(unsigned long data)
{
struct radeonfb_info *rinfo = (struct radeonfb_info *)data;
radeon_engine_idle();
OUTREG(LVDS_GEN_CNTL, rinfo->pending_lvds_gen_cntl);
}
/*
* Apply a video mode. This will apply the whole register set, including
* the PLL registers, to the card
*/
void radeon_write_mode (struct radeonfb_info *rinfo, struct radeon_regs *mode,
int regs_only)
{
int i;
int primary_mon = PRIMARY_MONITOR(rinfo);
if (nomodeset)
return;
if (!regs_only)
radeon_screen_blank(rinfo, FB_BLANK_NORMAL, 0);
radeon_fifo_wait(31);
for (i=0; i<10; i++)
OUTREG(common_regs[i].reg, common_regs[i].val);
/* Apply surface registers */
for (i=0; i<8; i++) {
OUTREG(SURFACE0_LOWER_BOUND + 0x10*i, mode->surf_lower_bound[i]);
OUTREG(SURFACE0_UPPER_BOUND + 0x10*i, mode->surf_upper_bound[i]);
OUTREG(SURFACE0_INFO + 0x10*i, mode->surf_info[i]);
}
OUTREG(CRTC_GEN_CNTL, mode->crtc_gen_cntl);
OUTREGP(CRTC_EXT_CNTL, mode->crtc_ext_cntl,
~(CRTC_HSYNC_DIS | CRTC_VSYNC_DIS | CRTC_DISPLAY_DIS));
OUTREG(CRTC_MORE_CNTL, mode->crtc_more_cntl);
OUTREGP(DAC_CNTL, mode->dac_cntl, DAC_RANGE_CNTL | DAC_BLANKING);
OUTREG(CRTC_H_TOTAL_DISP, mode->crtc_h_total_disp);
OUTREG(CRTC_H_SYNC_STRT_WID, mode->crtc_h_sync_strt_wid);
OUTREG(CRTC_V_TOTAL_DISP, mode->crtc_v_total_disp);
OUTREG(CRTC_V_SYNC_STRT_WID, mode->crtc_v_sync_strt_wid);
OUTREG(CRTC_OFFSET, 0);
OUTREG(CRTC_OFFSET_CNTL, 0);
OUTREG(CRTC_PITCH, mode->crtc_pitch);
OUTREG(SURFACE_CNTL, mode->surface_cntl);
radeon_write_pll_regs(rinfo, mode);
if ((primary_mon == MT_DFP) || (primary_mon == MT_LCD)) {
radeon_fifo_wait(10);
OUTREG(FP_CRTC_H_TOTAL_DISP, mode->fp_crtc_h_total_disp);
OUTREG(FP_CRTC_V_TOTAL_DISP, mode->fp_crtc_v_total_disp);
OUTREG(FP_H_SYNC_STRT_WID, mode->fp_h_sync_strt_wid);
OUTREG(FP_V_SYNC_STRT_WID, mode->fp_v_sync_strt_wid);
OUTREG(FP_HORZ_STRETCH, mode->fp_horz_stretch);
OUTREG(FP_VERT_STRETCH, mode->fp_vert_stretch);
OUTREG(FP_GEN_CNTL, mode->fp_gen_cntl);
OUTREG(TMDS_CRC, mode->tmds_crc);
OUTREG(TMDS_TRANSMITTER_CNTL, mode->tmds_transmitter_cntl);
}
if (!regs_only)
radeon_screen_blank(rinfo, FB_BLANK_UNBLANK, 0);
radeon_fifo_wait(2);
OUTPLL(VCLK_ECP_CNTL, mode->vclk_ecp_cntl);
return;
}
/*
* Calculate the PLL values for a given mode
*/
static void radeon_calc_pll_regs(struct radeonfb_info *rinfo, struct radeon_regs *regs,
unsigned long freq)
{
const struct {
int divider;
int bitvalue;
} *post_div,
post_divs[] = {
{ 1, 0 },
{ 2, 1 },
{ 4, 2 },
{ 8, 3 },
{ 3, 4 },
{ 16, 5 },
{ 6, 6 },
{ 12, 7 },
{ 0, 0 },
};
int fb_div, pll_output_freq = 0;
int uses_dvo = 0;
/* Check if the DVO port is enabled and sourced from the primary CRTC. I'm
* not sure which model starts having FP2_GEN_CNTL, I assume anything more
* recent than an r(v)100...
*/
#if 1
/* XXX I had reports of flicker happening with the cinema display
* on TMDS1 that seem to be fixed if I also forbit odd dividers in
* this case. This could just be a bandwidth calculation issue, I
* haven't implemented the bandwidth code yet, but in the meantime,
* forcing uses_dvo to 1 fixes it and shouln't have bad side effects,
* I haven't seen a case were were absolutely needed an odd PLL
* divider. I'll find a better fix once I have more infos on the
* real cause of the problem.
*/
while (rinfo->has_CRTC2) {
u32 fp2_gen_cntl = INREG(FP2_GEN_CNTL);
u32 disp_output_cntl;
int source;
/* FP2 path not enabled */
if ((fp2_gen_cntl & FP2_ON) == 0)
break;
/* Not all chip revs have the same format for this register,
* extract the source selection
*/
if (rinfo->family == CHIP_FAMILY_R200 || IS_R300_VARIANT(rinfo)) {
source = (fp2_gen_cntl >> 10) & 0x3;
/* sourced from transform unit, check for transform unit
* own source
*/
if (source == 3) {
disp_output_cntl = INREG(DISP_OUTPUT_CNTL);
source = (disp_output_cntl >> 12) & 0x3;
}
} else
source = (fp2_gen_cntl >> 13) & 0x1;
/* sourced from CRTC2 -> exit */
if (source == 1)
break;
/* so we end up on CRTC1, let's set uses_dvo to 1 now */
uses_dvo = 1;
break;
}
#else
uses_dvo = 1;
#endif
if (freq > rinfo->pll.ppll_max)
freq = rinfo->pll.ppll_max;
if (freq*12 < rinfo->pll.ppll_min)
freq = rinfo->pll.ppll_min / 12;
pr_debug("freq = %lu, PLL min = %u, PLL max = %u\n",
freq, rinfo->pll.ppll_min, rinfo->pll.ppll_max);
for (post_div = &post_divs[0]; post_div->divider; ++post_div) {
pll_output_freq = post_div->divider * freq;
/* If we output to the DVO port (external TMDS), we don't allow an
* odd PLL divider as those aren't supported on this path
*/
if (uses_dvo && (post_div->divider & 1))
continue;
if (pll_output_freq >= rinfo->pll.ppll_min &&
pll_output_freq <= rinfo->pll.ppll_max)
break;
}
/* If we fall through the bottom, try the "default value"
given by the terminal post_div->bitvalue */
if ( !post_div->divider ) {
post_div = &post_divs[post_div->bitvalue];
pll_output_freq = post_div->divider * freq;
}
pr_debug("ref_div = %d, ref_clk = %d, output_freq = %d\n",
rinfo->pll.ref_div, rinfo->pll.ref_clk,
pll_output_freq);
/* If we fall through the bottom, try the "default value"
given by the terminal post_div->bitvalue */
if ( !post_div->divider ) {
post_div = &post_divs[post_div->bitvalue];
pll_output_freq = post_div->divider * freq;
}
pr_debug("ref_div = %d, ref_clk = %d, output_freq = %d\n",
rinfo->pll.ref_div, rinfo->pll.ref_clk,
pll_output_freq);
fb_div = round_div(rinfo->pll.ref_div*pll_output_freq,
rinfo->pll.ref_clk);
regs->ppll_ref_div = rinfo->pll.ref_div;
regs->ppll_div_3 = fb_div | (post_div->bitvalue << 16);
pr_debug("post div = 0x%x\n", post_div->bitvalue);
pr_debug("fb_div = 0x%x\n", fb_div);
pr_debug("ppll_div_3 = 0x%x\n", regs->ppll_div_3);
}
static int radeonfb_set_par(struct fb_info *info)
{
struct radeonfb_info *rinfo = info->par;
struct fb_var_screeninfo *mode = &info->var;
struct radeon_regs *newmode;
int hTotal, vTotal, hSyncStart, hSyncEnd,
hSyncPol, vSyncStart, vSyncEnd, vSyncPol, cSync;
u8 hsync_adj_tab[] = {0, 0x12, 9, 9, 6, 5};
u8 hsync_fudge_fp[] = {2, 2, 0, 0, 5, 5};
u32 sync, h_sync_pol, v_sync_pol, dotClock, pixClock;
int i, freq;
int format = 0;
int nopllcalc = 0;
int hsync_start, hsync_fudge, bytpp, hsync_wid, vsync_wid;
int primary_mon = PRIMARY_MONITOR(rinfo);
int depth = var_to_depth(mode);
int use_rmx = 0;
newmode = kmalloc(sizeof(struct radeon_regs), GFP_KERNEL);
if (!newmode)
return -ENOMEM;
/* We always want engine to be idle on a mode switch, even
* if we won't actually change the mode
*/
radeon_engine_idle();
hSyncStart = mode->xres + mode->right_margin;
hSyncEnd = hSyncStart + mode->hsync_len;
hTotal = hSyncEnd + mode->left_margin;
vSyncStart = mode->yres + mode->lower_margin;
vSyncEnd = vSyncStart + mode->vsync_len;
vTotal = vSyncEnd + mode->upper_margin;
pixClock = mode->pixclock;
sync = mode->sync;
h_sync_pol = sync & FB_SYNC_HOR_HIGH_ACT ? 0 : 1;
v_sync_pol = sync & FB_SYNC_VERT_HIGH_ACT ? 0 : 1;
if (primary_mon == MT_DFP || primary_mon == MT_LCD) {
if (rinfo->panel_info.xres < mode->xres)
mode->xres = rinfo->panel_info.xres;
if (rinfo->panel_info.yres < mode->yres)
mode->yres = rinfo->panel_info.yres;
hTotal = mode->xres + rinfo->panel_info.hblank;
hSyncStart = mode->xres + rinfo->panel_info.hOver_plus;
hSyncEnd = hSyncStart + rinfo->panel_info.hSync_width;
vTotal = mode->yres + rinfo->panel_info.vblank;
vSyncStart = mode->yres + rinfo->panel_info.vOver_plus;
vSyncEnd = vSyncStart + rinfo->panel_info.vSync_width;
h_sync_pol = !rinfo->panel_info.hAct_high;
v_sync_pol = !rinfo->panel_info.vAct_high;
pixClock = 100000000 / rinfo->panel_info.clock;
if (rinfo->panel_info.use_bios_dividers) {
nopllcalc = 1;
newmode->ppll_div_3 = rinfo->panel_info.fbk_divider |
(rinfo->panel_info.post_divider << 16);
newmode->ppll_ref_div = rinfo->panel_info.ref_divider;
}
}
dotClock = 1000000000 / pixClock;
freq = dotClock / 10; /* x100 */
pr_debug("hStart = %d, hEnd = %d, hTotal = %d\n",
hSyncStart, hSyncEnd, hTotal);
pr_debug("vStart = %d, vEnd = %d, vTotal = %d\n",
vSyncStart, vSyncEnd, vTotal);
hsync_wid = (hSyncEnd - hSyncStart) / 8;
vsync_wid = vSyncEnd - vSyncStart;
if (hsync_wid == 0)
hsync_wid = 1;
else if (hsync_wid > 0x3f) /* max */
hsync_wid = 0x3f;
if (vsync_wid == 0)
vsync_wid = 1;
else if (vsync_wid > 0x1f) /* max */
vsync_wid = 0x1f;
hSyncPol = mode->sync & FB_SYNC_HOR_HIGH_ACT ? 0 : 1;
vSyncPol = mode->sync & FB_SYNC_VERT_HIGH_ACT ? 0 : 1;
cSync = mode->sync & FB_SYNC_COMP_HIGH_ACT ? (1 << 4) : 0;
format = radeon_get_dstbpp(depth);
bytpp = mode->bits_per_pixel >> 3;
if ((primary_mon == MT_DFP) || (primary_mon == MT_LCD))
hsync_fudge = hsync_fudge_fp[format-1];
else
hsync_fudge = hsync_adj_tab[format-1];
hsync_start = hSyncStart - 8 + hsync_fudge;
newmode->crtc_gen_cntl = CRTC_EXT_DISP_EN | CRTC_EN |
(format << 8);
/* Clear auto-center etc... */
newmode->crtc_more_cntl = rinfo->init_state.crtc_more_cntl;
newmode->crtc_more_cntl &= 0xfffffff0;
if ((primary_mon == MT_DFP) || (primary_mon == MT_LCD)) {
newmode->crtc_ext_cntl = VGA_ATI_LINEAR | XCRT_CNT_EN;
if (mirror)
newmode->crtc_ext_cntl |= CRTC_CRT_ON;
newmode->crtc_gen_cntl &= ~(CRTC_DBL_SCAN_EN |
CRTC_INTERLACE_EN);
} else {
newmode->crtc_ext_cntl = VGA_ATI_LINEAR | XCRT_CNT_EN |
CRTC_CRT_ON;
}
newmode->dac_cntl = /* INREG(DAC_CNTL) | */ DAC_MASK_ALL | DAC_VGA_ADR_EN |
DAC_8BIT_EN;
newmode->crtc_h_total_disp = ((((hTotal / 8) - 1) & 0x3ff) |
(((mode->xres / 8) - 1) << 16));
newmode->crtc_h_sync_strt_wid = ((hsync_start & 0x1fff) |
(hsync_wid << 16) | (h_sync_pol << 23));
newmode->crtc_v_total_disp = ((vTotal - 1) & 0xffff) |
((mode->yres - 1) << 16);
newmode->crtc_v_sync_strt_wid = (((vSyncStart - 1) & 0xfff) |
(vsync_wid << 16) | (v_sync_pol << 23));
if (!(info->flags & FBINFO_HWACCEL_DISABLED)) {
/* We first calculate the engine pitch */
rinfo->pitch = ((mode->xres_virtual * ((mode->bits_per_pixel + 1) / 8) + 0x3f)
& ~(0x3f)) >> 6;
/* Then, re-multiply it to get the CRTC pitch */
newmode->crtc_pitch = (rinfo->pitch << 3) / ((mode->bits_per_pixel + 1) / 8);
} else
newmode->crtc_pitch = (mode->xres_virtual >> 3);
newmode->crtc_pitch |= (newmode->crtc_pitch << 16);
/*
* It looks like recent chips have a problem with SURFACE_CNTL,
* setting SURF_TRANSLATION_DIS completely disables the
* swapper as well, so we leave it unset now.
*/
newmode->surface_cntl = 0;
#if defined(__BIG_ENDIAN)
/* Setup swapping on both apertures, though we currently
* only use aperture 0, enabling swapper on aperture 1
* won't harm
*/
switch (mode->bits_per_pixel) {
case 16:
newmode->surface_cntl |= NONSURF_AP0_SWP_16BPP;
newmode->surface_cntl |= NONSURF_AP1_SWP_16BPP;
break;
case 24:
case 32:
newmode->surface_cntl |= NONSURF_AP0_SWP_32BPP;
newmode->surface_cntl |= NONSURF_AP1_SWP_32BPP;
break;
}
#endif
/* Clear surface registers */
for (i=0; i<8; i++) {
newmode->surf_lower_bound[i] = 0;
newmode->surf_upper_bound[i] = 0x1f;
newmode->surf_info[i] = 0;
}
pr_debug("h_total_disp = 0x%x\t hsync_strt_wid = 0x%x\n",
newmode->crtc_h_total_disp, newmode->crtc_h_sync_strt_wid);
pr_debug("v_total_disp = 0x%x\t vsync_strt_wid = 0x%x\n",
newmode->crtc_v_total_disp, newmode->crtc_v_sync_strt_wid);
rinfo->bpp = mode->bits_per_pixel;
rinfo->depth = depth;
pr_debug("pixclock = %lu\n", (unsigned long)pixClock);
pr_debug("freq = %lu\n", (unsigned long)freq);
/* We use PPLL_DIV_3 */
newmode->clk_cntl_index = 0x300;
/* Calculate PPLL value if necessary */
if (!nopllcalc)
radeon_calc_pll_regs(rinfo, newmode, freq);
newmode->vclk_ecp_cntl = rinfo->init_state.vclk_ecp_cntl;
if ((primary_mon == MT_DFP) || (primary_mon == MT_LCD)) {
unsigned int hRatio, vRatio;
if (mode->xres > rinfo->panel_info.xres)
mode->xres = rinfo->panel_info.xres;
if (mode->yres > rinfo->panel_info.yres)
mode->yres = rinfo->panel_info.yres;
newmode->fp_horz_stretch = (((rinfo->panel_info.xres / 8) - 1)
<< HORZ_PANEL_SHIFT);
newmode->fp_vert_stretch = ((rinfo->panel_info.yres - 1)
<< VERT_PANEL_SHIFT);
if (mode->xres != rinfo->panel_info.xres) {
hRatio = round_div(mode->xres * HORZ_STRETCH_RATIO_MAX,
rinfo->panel_info.xres);
newmode->fp_horz_stretch = (((((unsigned long)hRatio) & HORZ_STRETCH_RATIO_MASK)) |
(newmode->fp_horz_stretch &
(HORZ_PANEL_SIZE | HORZ_FP_LOOP_STRETCH |
HORZ_AUTO_RATIO_INC)));
newmode->fp_horz_stretch |= (HORZ_STRETCH_BLEND |
HORZ_STRETCH_ENABLE);
use_rmx = 1;
}
newmode->fp_horz_stretch &= ~HORZ_AUTO_RATIO;
if (mode->yres != rinfo->panel_info.yres) {
vRatio = round_div(mode->yres * VERT_STRETCH_RATIO_MAX,
rinfo->panel_info.yres);
newmode->fp_vert_stretch = (((((unsigned long)vRatio) & VERT_STRETCH_RATIO_MASK)) |
(newmode->fp_vert_stretch &
(VERT_PANEL_SIZE | VERT_STRETCH_RESERVED)));
newmode->fp_vert_stretch |= (VERT_STRETCH_BLEND |
VERT_STRETCH_ENABLE);
use_rmx = 1;
}
newmode->fp_vert_stretch &= ~VERT_AUTO_RATIO_EN;
newmode->fp_gen_cntl = (rinfo->init_state.fp_gen_cntl & (u32)
~(FP_SEL_CRTC2 |
FP_RMX_HVSYNC_CONTROL_EN |
FP_DFP_SYNC_SEL |
FP_CRT_SYNC_SEL |
FP_CRTC_LOCK_8DOT |
FP_USE_SHADOW_EN |
FP_CRTC_USE_SHADOW_VEND |
FP_CRT_SYNC_ALT));
newmode->fp_gen_cntl |= (FP_CRTC_DONT_SHADOW_VPAR |
FP_CRTC_DONT_SHADOW_HEND |
FP_PANEL_FORMAT);
if (IS_R300_VARIANT(rinfo) ||
(rinfo->family == CHIP_FAMILY_R200)) {
newmode->fp_gen_cntl &= ~R200_FP_SOURCE_SEL_MASK;
if (use_rmx)
newmode->fp_gen_cntl |= R200_FP_SOURCE_SEL_RMX;
else
newmode->fp_gen_cntl |= R200_FP_SOURCE_SEL_CRTC1;
} else
newmode->fp_gen_cntl |= FP_SEL_CRTC1;
newmode->lvds_gen_cntl = rinfo->init_state.lvds_gen_cntl;
newmode->lvds_pll_cntl = rinfo->init_state.lvds_pll_cntl;
newmode->tmds_crc = rinfo->init_state.tmds_crc;
newmode->tmds_transmitter_cntl = rinfo->init_state.tmds_transmitter_cntl;
if (primary_mon == MT_LCD) {
newmode->lvds_gen_cntl |= (LVDS_ON | LVDS_BLON);
newmode->fp_gen_cntl &= ~(FP_FPON | FP_TMDS_EN);
} else {
/* DFP */
newmode->fp_gen_cntl |= (FP_FPON | FP_TMDS_EN);
newmode->tmds_transmitter_cntl &= ~(TMDS_PLLRST);
/* TMDS_PLL_EN bit is reversed on RV (and mobility) chips */
if (IS_R300_VARIANT(rinfo) ||
(rinfo->family == CHIP_FAMILY_R200) || !rinfo->has_CRTC2)
newmode->tmds_transmitter_cntl &= ~TMDS_PLL_EN;
else
newmode->tmds_transmitter_cntl |= TMDS_PLL_EN;
newmode->crtc_ext_cntl &= ~CRTC_CRT_ON;
}
newmode->fp_crtc_h_total_disp = (((rinfo->panel_info.hblank / 8) & 0x3ff) |
(((mode->xres / 8) - 1) << 16));
newmode->fp_crtc_v_total_disp = (rinfo->panel_info.vblank & 0xffff) |
((mode->yres - 1) << 16);
newmode->fp_h_sync_strt_wid = ((rinfo->panel_info.hOver_plus & 0x1fff) |
(hsync_wid << 16) | (h_sync_pol << 23));
newmode->fp_v_sync_strt_wid = ((rinfo->panel_info.vOver_plus & 0xfff) |
(vsync_wid << 16) | (v_sync_pol << 23));
}
/* do it! */
if (!rinfo->asleep) {
memcpy(&rinfo->state, newmode, sizeof(*newmode));
radeon_write_mode (rinfo, newmode, 0);
/* (re)initialize the engine */
if (!(info->flags & FBINFO_HWACCEL_DISABLED))
radeonfb_engine_init (rinfo);
}
/* Update fix */
if (!(info->flags & FBINFO_HWACCEL_DISABLED))
info->fix.line_length = rinfo->pitch*64;
else
info->fix.line_length = mode->xres_virtual
* ((mode->bits_per_pixel + 1) / 8);
info->fix.visual = rinfo->depth == 8 ? FB_VISUAL_PSEUDOCOLOR
: FB_VISUAL_DIRECTCOLOR;
#ifdef CONFIG_BOOTX_TEXT
/* Update debug text engine */
btext_update_display(rinfo->fb_base_phys, mode->xres, mode->yres,
rinfo->depth, info->fix.line_length);
#endif
kfree(newmode);
return 0;
}
static struct fb_ops radeonfb_ops = {
.owner = THIS_MODULE,
.fb_check_var = radeonfb_check_var,
.fb_set_par = radeonfb_set_par,
.fb_setcolreg = radeonfb_setcolreg,
.fb_setcmap = radeonfb_setcmap,
.fb_pan_display = radeonfb_pan_display,
.fb_blank = radeonfb_blank,
.fb_ioctl = radeonfb_ioctl,
.fb_sync = radeonfb_sync,
.fb_fillrect = radeonfb_fillrect,
.fb_copyarea = radeonfb_copyarea,
.fb_imageblit = radeonfb_imageblit,
};
static int radeon_set_fbinfo(struct radeonfb_info *rinfo)
{
struct fb_info *info = rinfo->info;
info->par = rinfo;
info->pseudo_palette = rinfo->pseudo_palette;
info->flags = FBINFO_DEFAULT
| FBINFO_HWACCEL_COPYAREA
| FBINFO_HWACCEL_FILLRECT
| FBINFO_HWACCEL_XPAN
| FBINFO_HWACCEL_YPAN;
info->fbops = &radeonfb_ops;
info->screen_base = rinfo->fb_base;
info->screen_size = rinfo->mapped_vram;
/* Fill fix common fields */
strlcpy(info->fix.id, rinfo->name, sizeof(info->fix.id));
info->fix.smem_start = rinfo->fb_base_phys;
info->fix.smem_len = rinfo->video_ram;
info->fix.type = FB_TYPE_PACKED_PIXELS;
info->fix.visual = FB_VISUAL_PSEUDOCOLOR;
info->fix.xpanstep = 8;
info->fix.ypanstep = 1;
info->fix.ywrapstep = 0;
info->fix.type_aux = 0;
info->fix.mmio_start = rinfo->mmio_base_phys;
info->fix.mmio_len = RADEON_REGSIZE;
info->fix.accel = FB_ACCEL_ATI_RADEON;
fb_alloc_cmap(&info->cmap, 256, 0);
if (noaccel)
info->flags |= FBINFO_HWACCEL_DISABLED;
return 0;
}
/*
* This reconfigure the card's internal memory map. In theory, we'd like
* to setup the card's memory at the same address as it's PCI bus address,
* and the AGP aperture right after that so that system RAM on 32 bits
* machines at least, is directly accessible. However, doing so would
* conflict with the current XFree drivers...
* Ultimately, I hope XFree, GATOS and ATI binary drivers will all agree
* on the proper way to set this up and duplicate this here. In the meantime,
* I put the card's memory at 0 in card space and AGP at some random high
* local (0xe0000000 for now) that will be changed by XFree/DRI anyway
*/
#ifdef CONFIG_PPC_OF
#undef SET_MC_FB_FROM_APERTURE
static void fixup_memory_mappings(struct radeonfb_info *rinfo)
{
u32 save_crtc_gen_cntl, save_crtc2_gen_cntl = 0;
u32 save_crtc_ext_cntl;
u32 aper_base, aper_size;
u32 agp_base;
/* First, we disable display to avoid interfering */
if (rinfo->has_CRTC2) {
save_crtc2_gen_cntl = INREG(CRTC2_GEN_CNTL);
OUTREG(CRTC2_GEN_CNTL, save_crtc2_gen_cntl | CRTC2_DISP_REQ_EN_B);
}
save_crtc_gen_cntl = INREG(CRTC_GEN_CNTL);
save_crtc_ext_cntl = INREG(CRTC_EXT_CNTL);
OUTREG(CRTC_EXT_CNTL, save_crtc_ext_cntl | CRTC_DISPLAY_DIS);
OUTREG(CRTC_GEN_CNTL, save_crtc_gen_cntl | CRTC_DISP_REQ_EN_B);
mdelay(100);
aper_base = INREG(CNFG_APER_0_BASE);
aper_size = INREG(CNFG_APER_SIZE);
#ifdef SET_MC_FB_FROM_APERTURE
/* Set framebuffer to be at the same address as set in PCI BAR */
OUTREG(MC_FB_LOCATION,
((aper_base + aper_size - 1) & 0xffff0000) | (aper_base >> 16));
rinfo->fb_local_base = aper_base;
#else
OUTREG(MC_FB_LOCATION, 0x7fff0000);
rinfo->fb_local_base = 0;
#endif
agp_base = aper_base + aper_size;
if (agp_base & 0xf0000000)
agp_base = (aper_base | 0x0fffffff) + 1;
/* Set AGP to be just after the framebuffer on a 256Mb boundary. This
* assumes the FB isn't mapped to 0xf0000000 or above, but this is
* always the case on PPCs afaik.
*/
#ifdef SET_MC_FB_FROM_APERTURE
OUTREG(MC_AGP_LOCATION, 0xffff0000 | (agp_base >> 16));
#else
OUTREG(MC_AGP_LOCATION, 0xffffe000);
#endif
/* Fixup the display base addresses & engine offsets while we
* are at it as well
*/
#ifdef SET_MC_FB_FROM_APERTURE
OUTREG(DISPLAY_BASE_ADDR, aper_base);
if (rinfo->has_CRTC2)
OUTREG(CRTC2_DISPLAY_BASE_ADDR, aper_base);
OUTREG(OV0_BASE_ADDR, aper_base);
#else
OUTREG(DISPLAY_BASE_ADDR, 0);
if (rinfo->has_CRTC2)
OUTREG(CRTC2_DISPLAY_BASE_ADDR, 0);
OUTREG(OV0_BASE_ADDR, 0);
#endif
mdelay(100);
/* Restore display settings */
OUTREG(CRTC_GEN_CNTL, save_crtc_gen_cntl);
OUTREG(CRTC_EXT_CNTL, save_crtc_ext_cntl);
if (rinfo->has_CRTC2)
OUTREG(CRTC2_GEN_CNTL, save_crtc2_gen_cntl);
pr_debug("aper_base: %08x MC_FB_LOC to: %08x, MC_AGP_LOC to: %08x\n",
aper_base,
((aper_base + aper_size - 1) & 0xffff0000) | (aper_base >> 16),
0xffff0000 | (agp_base >> 16));
}
#endif /* CONFIG_PPC_OF */
static void radeon_identify_vram(struct radeonfb_info *rinfo)
{
u32 tmp;
/* framebuffer size */
if ((rinfo->family == CHIP_FAMILY_RS100) ||
(rinfo->family == CHIP_FAMILY_RS200) ||
(rinfo->family == CHIP_FAMILY_RS300) ||
(rinfo->family == CHIP_FAMILY_RC410) ||
(rinfo->family == CHIP_FAMILY_RS400) ||
(rinfo->family == CHIP_FAMILY_RS480) ) {
u32 tom = INREG(NB_TOM);
tmp = ((((tom >> 16) - (tom & 0xffff) + 1) << 6) * 1024);
radeon_fifo_wait(6);
OUTREG(MC_FB_LOCATION, tom);
OUTREG(DISPLAY_BASE_ADDR, (tom & 0xffff) << 16);
OUTREG(CRTC2_DISPLAY_BASE_ADDR, (tom & 0xffff) << 16);
OUTREG(OV0_BASE_ADDR, (tom & 0xffff) << 16);
/* This is supposed to fix the crtc2 noise problem. */
OUTREG(GRPH2_BUFFER_CNTL, INREG(GRPH2_BUFFER_CNTL) & ~0x7f0000);
if ((rinfo->family == CHIP_FAMILY_RS100) ||
(rinfo->family == CHIP_FAMILY_RS200)) {
/* This is to workaround the asic bug for RMX, some versions
of BIOS doesn't have this register initialized correctly.
*/
OUTREGP(CRTC_MORE_CNTL, CRTC_H_CUTOFF_ACTIVE_EN,
~CRTC_H_CUTOFF_ACTIVE_EN);
}
} else {
tmp = INREG(CNFG_MEMSIZE);
}
/* mem size is bits [28:0], mask off the rest */
rinfo->video_ram = tmp & CNFG_MEMSIZE_MASK;
/*
* Hack to get around some busted production M6's
* reporting no ram
*/
if (rinfo->video_ram == 0) {
switch (rinfo->pdev->device) {
case PCI_CHIP_RADEON_LY:
case PCI_CHIP_RADEON_LZ:
rinfo->video_ram = 8192 * 1024;
break;
default:
break;
}
}
/*
* Now try to identify VRAM type
*/
if (rinfo->is_IGP || (rinfo->family >= CHIP_FAMILY_R300) ||
(INREG(MEM_SDRAM_MODE_REG) & (1<<30)))
rinfo->vram_ddr = 1;
else
rinfo->vram_ddr = 0;
tmp = INREG(MEM_CNTL);
if (IS_R300_VARIANT(rinfo)) {
tmp &= R300_MEM_NUM_CHANNELS_MASK;
switch (tmp) {
case 0: rinfo->vram_width = 64; break;
case 1: rinfo->vram_width = 128; break;
case 2: rinfo->vram_width = 256; break;
default: rinfo->vram_width = 128; break;
}
} else if ((rinfo->family == CHIP_FAMILY_RV100) ||
(rinfo->family == CHIP_FAMILY_RS100) ||
(rinfo->family == CHIP_FAMILY_RS200)){
if (tmp & RV100_MEM_HALF_MODE)
rinfo->vram_width = 32;
else
rinfo->vram_width = 64;
} else {
if (tmp & MEM_NUM_CHANNELS_MASK)
rinfo->vram_width = 128;
else
rinfo->vram_width = 64;
}
/* This may not be correct, as some cards can have half of channel disabled
* ToDo: identify these cases
*/
pr_debug("radeonfb (%s): Found %ldk of %s %d bits wide videoram\n",
pci_name(rinfo->pdev),
rinfo->video_ram / 1024,
rinfo->vram_ddr ? "DDR" : "SDRAM",
rinfo->vram_width);
}
/*
* Sysfs
*/
static ssize_t radeon_show_one_edid(char *buf, loff_t off, size_t count, const u8 *edid)
{
return memory_read_from_buffer(buf, count, &off, edid, EDID_LENGTH);
}
static ssize_t radeon_show_edid1(struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct pci_dev *pdev = to_pci_dev(dev);
struct fb_info *info = pci_get_drvdata(pdev);
struct radeonfb_info *rinfo = info->par;
return radeon_show_one_edid(buf, off, count, rinfo->mon1_EDID);
}
static ssize_t radeon_show_edid2(struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct pci_dev *pdev = to_pci_dev(dev);
struct fb_info *info = pci_get_drvdata(pdev);
struct radeonfb_info *rinfo = info->par;
return radeon_show_one_edid(buf, off, count, rinfo->mon2_EDID);
}
static struct bin_attribute edid1_attr = {
.attr = {
.name = "edid1",
.mode = 0444,
},
.size = EDID_LENGTH,
.read = radeon_show_edid1,
};
static struct bin_attribute edid2_attr = {
.attr = {
.name = "edid2",
.mode = 0444,
},
.size = EDID_LENGTH,
.read = radeon_show_edid2,
};
static int radeonfb_pci_register(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct fb_info *info;
struct radeonfb_info *rinfo;
int ret;
unsigned char c1, c2;
int err = 0;
pr_debug("radeonfb_pci_register BEGIN\n");
/* Enable device in PCI config */
ret = pci_enable_device(pdev);
if (ret < 0) {
printk(KERN_ERR "radeonfb (%s): Cannot enable PCI device\n",
pci_name(pdev));
goto err_out;
}
info = framebuffer_alloc(sizeof(struct radeonfb_info), &pdev->dev);
if (!info) {
printk (KERN_ERR "radeonfb (%s): could not allocate memory\n",
pci_name(pdev));
ret = -ENOMEM;
goto err_disable;
}
rinfo = info->par;
rinfo->info = info;
rinfo->pdev = pdev;
spin_lock_init(&rinfo->reg_lock);
init_timer(&rinfo->lvds_timer);
rinfo->lvds_timer.function = radeon_lvds_timer_func;
rinfo->lvds_timer.data = (unsigned long)rinfo;
c1 = ent->device >> 8;
c2 = ent->device & 0xff;
if (isprint(c1) && isprint(c2))
snprintf(rinfo->name, sizeof(rinfo->name),
"ATI Radeon %x \"%c%c\"", ent->device & 0xffff, c1, c2);
else
snprintf(rinfo->name, sizeof(rinfo->name),
"ATI Radeon %x", ent->device & 0xffff);
rinfo->family = ent->driver_data & CHIP_FAMILY_MASK;
rinfo->chipset = pdev->device;
rinfo->has_CRTC2 = (ent->driver_data & CHIP_HAS_CRTC2) != 0;
rinfo->is_mobility = (ent->driver_data & CHIP_IS_MOBILITY) != 0;
rinfo->is_IGP = (ent->driver_data & CHIP_IS_IGP) != 0;
/* Set base addrs */
rinfo->fb_base_phys = pci_resource_start (pdev, 0);
rinfo->mmio_base_phys = pci_resource_start (pdev, 2);
/* request the mem regions */
ret = pci_request_region(pdev, 0, "radeonfb framebuffer");
if (ret < 0) {
printk( KERN_ERR "radeonfb (%s): cannot request region 0.\n",
pci_name(rinfo->pdev));
goto err_release_fb;
}
ret = pci_request_region(pdev, 2, "radeonfb mmio");
if (ret < 0) {
printk( KERN_ERR "radeonfb (%s): cannot request region 2.\n",
pci_name(rinfo->pdev));
goto err_release_pci0;
}
/* map the regions */
rinfo->mmio_base = ioremap(rinfo->mmio_base_phys, RADEON_REGSIZE);
if (!rinfo->mmio_base) {
printk(KERN_ERR "radeonfb (%s): cannot map MMIO\n",
pci_name(rinfo->pdev));
ret = -EIO;
goto err_release_pci2;
}
rinfo->fb_local_base = INREG(MC_FB_LOCATION) << 16;
/*
* Check for errata
*/
rinfo->errata = 0;
if (rinfo->family == CHIP_FAMILY_R300 &&
(INREG(CNFG_CNTL) & CFG_ATI_REV_ID_MASK)
== CFG_ATI_REV_A11)
rinfo->errata |= CHIP_ERRATA_R300_CG;
if (rinfo->family == CHIP_FAMILY_RV200 ||
rinfo->family == CHIP_FAMILY_RS200)
rinfo->errata |= CHIP_ERRATA_PLL_DUMMYREADS;
if (rinfo->family == CHIP_FAMILY_RV100 ||
rinfo->family == CHIP_FAMILY_RS100 ||
rinfo->family == CHIP_FAMILY_RS200)
rinfo->errata |= CHIP_ERRATA_PLL_DELAY;
#if defined(CONFIG_PPC_OF) || defined(CONFIG_SPARC)
/* On PPC, we obtain the OF device-node pointer to the firmware
* data for this chip
*/
rinfo->of_node = pci_device_to_OF_node(pdev);
if (rinfo->of_node == NULL)
printk(KERN_WARNING "radeonfb (%s): Cannot match card to OF node !\n",
pci_name(rinfo->pdev));
#endif /* CONFIG_PPC_OF || CONFIG_SPARC */
#ifdef CONFIG_PPC_OF
/* On PPC, the firmware sets up a memory mapping that tends
* to cause lockups when enabling the engine. We reconfigure
* the card internal memory mappings properly
*/
fixup_memory_mappings(rinfo);
#endif /* CONFIG_PPC_OF */
/* Get VRAM size and type */
radeon_identify_vram(rinfo);
rinfo->mapped_vram = min_t(unsigned long, MAX_MAPPED_VRAM, rinfo->video_ram);
do {
rinfo->fb_base = ioremap (rinfo->fb_base_phys,
rinfo->mapped_vram);
} while (rinfo->fb_base == NULL &&
((rinfo->mapped_vram /= 2) >= MIN_MAPPED_VRAM));
if (rinfo->fb_base == NULL) {
printk (KERN_ERR "radeonfb (%s): cannot map FB\n",
pci_name(rinfo->pdev));
ret = -EIO;
goto err_unmap_rom;
}
pr_debug("radeonfb (%s): mapped %ldk videoram\n", pci_name(rinfo->pdev),
rinfo->mapped_vram/1024);
/*
* Map the BIOS ROM if any and retrieve PLL parameters from
* the BIOS. We skip that on mobility chips as the real panel
* values we need aren't in the ROM but in the BIOS image in
* memory. This is definitely not the best meacnism though,
* we really need the arch code to tell us which is the "primary"
* video adapter to use the memory image (or better, the arch
* should provide us a copy of the BIOS image to shield us from
* archs who would store that elsewhere and/or could initialize
* more than one adapter during boot).
*/
if (!rinfo->is_mobility)
radeon_map_ROM(rinfo, pdev);
/*
* On x86, the primary display on laptop may have it's BIOS
* ROM elsewhere, try to locate it at the legacy memory hole.
* We probably need to make sure this is the primary display,
* but that is difficult without some arch support.
*/
#ifdef CONFIG_X86
if (rinfo->bios_seg == NULL)
radeon_find_mem_vbios(rinfo);
#endif
/* If both above failed, try the BIOS ROM again for mobility
* chips
*/
if (rinfo->bios_seg == NULL && rinfo->is_mobility)
radeon_map_ROM(rinfo, pdev);
/* Get informations about the board's PLL */
radeon_get_pllinfo(rinfo);
#ifdef CONFIG_FB_RADEON_I2C
/* Register I2C bus */
radeon_create_i2c_busses(rinfo);
#endif
/* set all the vital stuff */
radeon_set_fbinfo (rinfo);
/* Probe screen types */
radeon_probe_screens(rinfo, monitor_layout, ignore_edid);
/* Build mode list, check out panel native model */
radeon_check_modes(rinfo, mode_option);
/* Register some sysfs stuff (should be done better) */
if (rinfo->mon1_EDID)
err |= sysfs_create_bin_file(&rinfo->pdev->dev.kobj,
&edid1_attr);
if (rinfo->mon2_EDID)
err |= sysfs_create_bin_file(&rinfo->pdev->dev.kobj,
&edid2_attr);
if (err)
pr_warning("%s() Creating sysfs files failed, continuing\n",
__func__);
/* save current mode regs before we switch into the new one
* so we can restore this upon __exit
*/
radeon_save_state (rinfo, &rinfo->init_state);
memcpy(&rinfo->state, &rinfo->init_state, sizeof(struct radeon_regs));
/* Setup Power Management capabilities */
if (default_dynclk < -1) {
/* -2 is special: means ON on mobility chips and do not
* change on others
*/
radeonfb_pm_init(rinfo, rinfo->is_mobility ? 1 : -1, ignore_devlist, force_sleep);
} else
radeonfb_pm_init(rinfo, default_dynclk, ignore_devlist, force_sleep);
pci_set_drvdata(pdev, info);
/* Register with fbdev layer */
ret = register_framebuffer(info);
if (ret < 0) {
printk (KERN_ERR "radeonfb (%s): could not register framebuffer\n",
pci_name(rinfo->pdev));
goto err_unmap_fb;
}
#ifdef CONFIG_MTRR
rinfo->mtrr_hdl = nomtrr ? -1 : mtrr_add(rinfo->fb_base_phys,
rinfo->video_ram,
MTRR_TYPE_WRCOMB, 1);
#endif
if (backlight)
radeonfb_bl_init(rinfo);
printk ("radeonfb (%s): %s\n", pci_name(rinfo->pdev), rinfo->name);
if (rinfo->bios_seg)
radeon_unmap_ROM(rinfo, pdev);
pr_debug("radeonfb_pci_register END\n");
return 0;
err_unmap_fb:
iounmap(rinfo->fb_base);
err_unmap_rom:
kfree(rinfo->mon1_EDID);
kfree(rinfo->mon2_EDID);
if (rinfo->mon1_modedb)
fb_destroy_modedb(rinfo->mon1_modedb);
fb_dealloc_cmap(&info->cmap);
#ifdef CONFIG_FB_RADEON_I2C
radeon_delete_i2c_busses(rinfo);
#endif
if (rinfo->bios_seg)
radeon_unmap_ROM(rinfo, pdev);
iounmap(rinfo->mmio_base);
err_release_pci2:
pci_release_region(pdev, 2);
err_release_pci0:
pci_release_region(pdev, 0);
err_release_fb:
framebuffer_release(info);
err_disable:
err_out:
return ret;
}
static void radeonfb_pci_unregister(struct pci_dev *pdev)
{
struct fb_info *info = pci_get_drvdata(pdev);
struct radeonfb_info *rinfo = info->par;
if (!rinfo)
return;
radeonfb_pm_exit(rinfo);
if (rinfo->mon1_EDID)
sysfs_remove_bin_file(&rinfo->pdev->dev.kobj, &edid1_attr);
if (rinfo->mon2_EDID)
sysfs_remove_bin_file(&rinfo->pdev->dev.kobj, &edid2_attr);
#if 0
/* restore original state
*
* Doesn't quite work yet, I suspect if we come from a legacy
* VGA mode (or worse, text mode), we need to do some VGA black
* magic here that I know nothing about. --BenH
*/
radeon_write_mode (rinfo, &rinfo->init_state, 1);
#endif
del_timer_sync(&rinfo->lvds_timer);
#ifdef CONFIG_MTRR
if (rinfo->mtrr_hdl >= 0)
mtrr_del(rinfo->mtrr_hdl, 0, 0);
#endif
unregister_framebuffer(info);
radeonfb_bl_exit(rinfo);
iounmap(rinfo->mmio_base);
iounmap(rinfo->fb_base);
pci_release_region(pdev, 2);
pci_release_region(pdev, 0);
kfree(rinfo->mon1_EDID);
kfree(rinfo->mon2_EDID);
if (rinfo->mon1_modedb)
fb_destroy_modedb(rinfo->mon1_modedb);
#ifdef CONFIG_FB_RADEON_I2C
radeon_delete_i2c_busses(rinfo);
#endif
fb_dealloc_cmap(&info->cmap);
framebuffer_release(info);
}
static struct pci_driver radeonfb_driver = {
.name = "radeonfb",
.id_table = radeonfb_pci_table,
.probe = radeonfb_pci_register,
.remove = radeonfb_pci_unregister,
#ifdef CONFIG_PM
.suspend = radeonfb_pci_suspend,
.resume = radeonfb_pci_resume,
#endif /* CONFIG_PM */
};
#ifndef MODULE
static int __init radeonfb_setup (char *options)
{
char *this_opt;
if (!options || !*options)
return 0;
while ((this_opt = strsep (&options, ",")) != NULL) {
if (!*this_opt)
continue;
if (!strncmp(this_opt, "noaccel", 7)) {
noaccel = 1;
} else if (!strncmp(this_opt, "mirror", 6)) {
mirror = 1;
} else if (!strncmp(this_opt, "force_dfp", 9)) {
force_dfp = 1;
} else if (!strncmp(this_opt, "panel_yres:", 11)) {
panel_yres = simple_strtoul((this_opt+11), NULL, 0);
} else if (!strncmp(this_opt, "backlight:", 10)) {
backlight = simple_strtoul(this_opt+10, NULL, 0);
#ifdef CONFIG_MTRR
} else if (!strncmp(this_opt, "nomtrr", 6)) {
nomtrr = 1;
#endif
} else if (!strncmp(this_opt, "nomodeset", 9)) {
nomodeset = 1;
} else if (!strncmp(this_opt, "force_measure_pll", 17)) {
force_measure_pll = 1;
} else if (!strncmp(this_opt, "ignore_edid", 11)) {
ignore_edid = 1;
#if defined(CONFIG_PM) && defined(CONFIG_X86)
} else if (!strncmp(this_opt, "force_sleep", 11)) {
force_sleep = 1;
} else if (!strncmp(this_opt, "ignore_devlist", 14)) {
ignore_devlist = 1;
#endif
} else
mode_option = this_opt;
}
return 0;
}
#endif /* MODULE */
static int __init radeonfb_init (void)
{
#ifndef MODULE
char *option = NULL;
if (fb_get_options("radeonfb", &option))
return -ENODEV;
radeonfb_setup(option);
#endif
return pci_register_driver (&radeonfb_driver);
}
static void __exit radeonfb_exit (void)
{
pci_unregister_driver (&radeonfb_driver);
}
module_init(radeonfb_init);
module_exit(radeonfb_exit);
MODULE_AUTHOR("Ani Joshi");
MODULE_DESCRIPTION("framebuffer driver for ATI Radeon chipset");
MODULE_LICENSE("GPL");
module_param(noaccel, bool, 0);
module_param(default_dynclk, int, 0);
MODULE_PARM_DESC(default_dynclk, "int: -2=enable on mobility only,-1=do not change,0=off,1=on");
MODULE_PARM_DESC(noaccel, "bool: disable acceleration");
module_param(nomodeset, bool, 0);
MODULE_PARM_DESC(nomodeset, "bool: disable actual setting of video mode");
module_param(mirror, bool, 0);
MODULE_PARM_DESC(mirror, "bool: mirror the display to both monitors");
module_param(force_dfp, bool, 0);
MODULE_PARM_DESC(force_dfp, "bool: force display to dfp");
module_param(ignore_edid, bool, 0);
MODULE_PARM_DESC(ignore_edid, "bool: Ignore EDID data when doing DDC probe");
module_param(monitor_layout, charp, 0);
MODULE_PARM_DESC(monitor_layout, "Specify monitor mapping (like XFree86)");
module_param(force_measure_pll, bool, 0);
MODULE_PARM_DESC(force_measure_pll, "Force measurement of PLL (debug)");
#ifdef CONFIG_MTRR
module_param(nomtrr, bool, 0);
MODULE_PARM_DESC(nomtrr, "bool: disable use of MTRR registers");
#endif
module_param(panel_yres, int, 0);
MODULE_PARM_DESC(panel_yres, "int: set panel yres");
module_param(mode_option, charp, 0);
MODULE_PARM_DESC(mode_option, "Specify resolution as \"<xres>x<yres>[-<bpp>][@<refresh>]\" ");
#if defined(CONFIG_PM) && defined(CONFIG_X86)
module_param(force_sleep, bool, 0);
MODULE_PARM_DESC(force_sleep, "bool: force D2 sleep mode on all hardware");
module_param(ignore_devlist, bool, 0);
MODULE_PARM_DESC(ignore_devlist, "bool: ignore workarounds for bugs in specific laptops");
#endif
| gpl-2.0 |
xlfjn/kernel_msm-3.10 | drivers/video/tdfxfb.c | 2398 | 43659 | /*
*
* tdfxfb.c
*
* Author: Hannu Mallat <hmallat@cc.hut.fi>
*
* Copyright © 1999 Hannu Mallat
* All rights reserved
*
* Created : Thu Sep 23 18:17:43 1999, hmallat
* Last modified: Tue Nov 2 21:19:47 1999, hmallat
*
* I2C part copied from the i2c-voodoo3.c driver by:
* Frodo Looijaard <frodol@dds.nl>,
* Philip Edelbrock <phil@netroedge.com>,
* Ralph Metzler <rjkm@thp.uni-koeln.de>, and
* Mark D. Studebaker <mdsxyz123@yahoo.com>
*
* Lots of the information here comes from the Daryll Strauss' Banshee
* patches to the XF86 server, and the rest comes from the 3dfx
* Banshee specification. I'm very much indebted to Daryll for his
* work on the X server.
*
* Voodoo3 support was contributed Harold Oga. Lots of additions
* (proper acceleration, 24 bpp, hardware cursor) and bug fixes by Attila
* Kesmarki. Thanks guys!
*
* Voodoo1 and Voodoo2 support aren't relevant to this driver as they
* behave very differently from the Voodoo3/4/5. For anyone wanting to
* use frame buffer on the Voodoo1/2, see the sstfb driver (which is
* located at http://www.sourceforge.net/projects/sstfb).
*
* While I _am_ grateful to 3Dfx for releasing the specs for Banshee,
* I do wish the next version is a bit more complete. Without the XF86
* patches I couldn't have gotten even this far... for instance, the
* extensions to the VGA register set go completely unmentioned in the
* spec! Also, lots of references are made to the 'SST core', but no
* spec is publicly available, AFAIK.
*
* The structure of this driver comes pretty much from the Permedia
* driver by Ilario Nardinocchi, which in turn is based on skeletonfb.
*
* TODO:
* - multihead support (basically need to support an array of fb_infos)
* - support other architectures (PPC, Alpha); does the fact that the VGA
* core can be accessed only thru I/O (not memory mapped) complicate
* things?
*
* Version history:
*
* 0.1.4 (released 2002-05-28) ported over to new fbdev api by James Simmons
*
* 0.1.3 (released 1999-11-02) added Attila's panning support, code
* reorg, hwcursor address page size alignment
* (for mmapping both frame buffer and regs),
* and my changes to get rid of hardcoded
* VGA i/o register locations (uses PCI
* configuration info now)
* 0.1.2 (released 1999-10-19) added Attila Kesmarki's bug fixes and
* improvements
* 0.1.1 (released 1999-10-07) added Voodoo3 support by Harold Oga.
* 0.1.0 (released 1999-10-06) initial version
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/fb.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <asm/io.h>
#include <video/tdfx.h>
#define DPRINTK(a, b...) pr_debug("fb: %s: " a, __func__ , ## b)
#ifdef CONFIG_MTRR
#include <asm/mtrr.h>
#else
/* duplicate asm/mtrr.h defines to work on archs without mtrr */
#define MTRR_TYPE_WRCOMB 1
static inline int mtrr_add(unsigned long base, unsigned long size,
unsigned int type, char increment)
{
return -ENODEV;
}
static inline int mtrr_del(int reg, unsigned long base,
unsigned long size)
{
return -ENODEV;
}
#endif
#define BANSHEE_MAX_PIXCLOCK 270000
#define VOODOO3_MAX_PIXCLOCK 300000
#define VOODOO5_MAX_PIXCLOCK 350000
static struct fb_fix_screeninfo tdfx_fix = {
.type = FB_TYPE_PACKED_PIXELS,
.visual = FB_VISUAL_PSEUDOCOLOR,
.ypanstep = 1,
.ywrapstep = 1,
.accel = FB_ACCEL_3DFX_BANSHEE
};
static struct fb_var_screeninfo tdfx_var = {
/* "640x480, 8 bpp @ 60 Hz */
.xres = 640,
.yres = 480,
.xres_virtual = 640,
.yres_virtual = 1024,
.bits_per_pixel = 8,
.red = {0, 8, 0},
.blue = {0, 8, 0},
.green = {0, 8, 0},
.activate = FB_ACTIVATE_NOW,
.height = -1,
.width = -1,
.accel_flags = FB_ACCELF_TEXT,
.pixclock = 39722,
.left_margin = 40,
.right_margin = 24,
.upper_margin = 32,
.lower_margin = 11,
.hsync_len = 96,
.vsync_len = 2,
.vmode = FB_VMODE_NONINTERLACED
};
/*
* PCI driver prototypes
*/
static int tdfxfb_probe(struct pci_dev *pdev, const struct pci_device_id *id);
static void tdfxfb_remove(struct pci_dev *pdev);
static struct pci_device_id tdfxfb_id_table[] = {
{ PCI_VENDOR_ID_3DFX, PCI_DEVICE_ID_3DFX_BANSHEE,
PCI_ANY_ID, PCI_ANY_ID, PCI_BASE_CLASS_DISPLAY << 16,
0xff0000, 0 },
{ PCI_VENDOR_ID_3DFX, PCI_DEVICE_ID_3DFX_VOODOO3,
PCI_ANY_ID, PCI_ANY_ID, PCI_BASE_CLASS_DISPLAY << 16,
0xff0000, 0 },
{ PCI_VENDOR_ID_3DFX, PCI_DEVICE_ID_3DFX_VOODOO5,
PCI_ANY_ID, PCI_ANY_ID, PCI_BASE_CLASS_DISPLAY << 16,
0xff0000, 0 },
{ 0, }
};
static struct pci_driver tdfxfb_driver = {
.name = "tdfxfb",
.id_table = tdfxfb_id_table,
.probe = tdfxfb_probe,
.remove = tdfxfb_remove,
};
MODULE_DEVICE_TABLE(pci, tdfxfb_id_table);
/*
* Driver data
*/
static int nopan;
static int nowrap = 1; /* not implemented (yet) */
static int hwcursor = 1;
static char *mode_option;
/* mtrr option */
static bool nomtrr;
/* -------------------------------------------------------------------------
* Hardware-specific funcions
* ------------------------------------------------------------------------- */
static inline u8 vga_inb(struct tdfx_par *par, u32 reg)
{
return inb(par->iobase + reg - 0x300);
}
static inline void vga_outb(struct tdfx_par *par, u32 reg, u8 val)
{
outb(val, par->iobase + reg - 0x300);
}
static inline void gra_outb(struct tdfx_par *par, u32 idx, u8 val)
{
vga_outb(par, GRA_I, idx);
wmb();
vga_outb(par, GRA_D, val);
wmb();
}
static inline void seq_outb(struct tdfx_par *par, u32 idx, u8 val)
{
vga_outb(par, SEQ_I, idx);
wmb();
vga_outb(par, SEQ_D, val);
wmb();
}
static inline u8 seq_inb(struct tdfx_par *par, u32 idx)
{
vga_outb(par, SEQ_I, idx);
mb();
return vga_inb(par, SEQ_D);
}
static inline void crt_outb(struct tdfx_par *par, u32 idx, u8 val)
{
vga_outb(par, CRT_I, idx);
wmb();
vga_outb(par, CRT_D, val);
wmb();
}
static inline u8 crt_inb(struct tdfx_par *par, u32 idx)
{
vga_outb(par, CRT_I, idx);
mb();
return vga_inb(par, CRT_D);
}
static inline void att_outb(struct tdfx_par *par, u32 idx, u8 val)
{
unsigned char tmp;
tmp = vga_inb(par, IS1_R);
vga_outb(par, ATT_IW, idx);
vga_outb(par, ATT_IW, val);
}
static inline void vga_disable_video(struct tdfx_par *par)
{
unsigned char s;
s = seq_inb(par, 0x01) | 0x20;
seq_outb(par, 0x00, 0x01);
seq_outb(par, 0x01, s);
seq_outb(par, 0x00, 0x03);
}
static inline void vga_enable_video(struct tdfx_par *par)
{
unsigned char s;
s = seq_inb(par, 0x01) & 0xdf;
seq_outb(par, 0x00, 0x01);
seq_outb(par, 0x01, s);
seq_outb(par, 0x00, 0x03);
}
static inline void vga_enable_palette(struct tdfx_par *par)
{
vga_inb(par, IS1_R);
mb();
vga_outb(par, ATT_IW, 0x20);
}
static inline u32 tdfx_inl(struct tdfx_par *par, unsigned int reg)
{
return readl(par->regbase_virt + reg);
}
static inline void tdfx_outl(struct tdfx_par *par, unsigned int reg, u32 val)
{
writel(val, par->regbase_virt + reg);
}
static inline void banshee_make_room(struct tdfx_par *par, int size)
{
/* Note: The Voodoo3's onboard FIFO has 32 slots. This loop
* won't quit if you ask for more. */
while ((tdfx_inl(par, STATUS) & 0x1f) < size - 1)
cpu_relax();
}
static int banshee_wait_idle(struct fb_info *info)
{
struct tdfx_par *par = info->par;
int i = 0;
banshee_make_room(par, 1);
tdfx_outl(par, COMMAND_3D, COMMAND_3D_NOP);
do {
if ((tdfx_inl(par, STATUS) & STATUS_BUSY) == 0)
i++;
} while (i < 3);
return 0;
}
/*
* Set the color of a palette entry in 8bpp mode
*/
static inline void do_setpalentry(struct tdfx_par *par, unsigned regno, u32 c)
{
banshee_make_room(par, 2);
tdfx_outl(par, DACADDR, regno);
/* read after write makes it working */
tdfx_inl(par, DACADDR);
tdfx_outl(par, DACDATA, c);
}
static u32 do_calc_pll(int freq, int *freq_out)
{
int m, n, k, best_m, best_n, best_k, best_error;
int fref = 14318;
best_error = freq;
best_n = best_m = best_k = 0;
for (k = 3; k >= 0; k--) {
for (m = 63; m >= 0; m--) {
/*
* Estimate value of n that produces target frequency
* with current m and k
*/
int n_estimated = ((freq * (m + 2) << k) / fref) - 2;
/* Search neighborhood of estimated n */
for (n = max(0, n_estimated);
n <= min(255, n_estimated + 1);
n++) {
/*
* Calculate PLL freqency with current m, k and
* estimated n
*/
int f = (fref * (n + 2) / (m + 2)) >> k;
int error = abs(f - freq);
/*
* If this is the closest we've come to the
* target frequency then remember n, m and k
*/
if (error < best_error) {
best_error = error;
best_n = n;
best_m = m;
best_k = k;
}
}
}
}
n = best_n;
m = best_m;
k = best_k;
*freq_out = (fref * (n + 2) / (m + 2)) >> k;
return (n << 8) | (m << 2) | k;
}
static void do_write_regs(struct fb_info *info, struct banshee_reg *reg)
{
struct tdfx_par *par = info->par;
int i;
banshee_wait_idle(info);
tdfx_outl(par, MISCINIT1, tdfx_inl(par, MISCINIT1) | 0x01);
crt_outb(par, 0x11, crt_inb(par, 0x11) & 0x7f); /* CRT unprotect */
banshee_make_room(par, 3);
tdfx_outl(par, VGAINIT1, reg->vgainit1 & 0x001FFFFF);
tdfx_outl(par, VIDPROCCFG, reg->vidcfg & ~0x00000001);
#if 0
tdfx_outl(par, PLLCTRL1, reg->mempll);
tdfx_outl(par, PLLCTRL2, reg->gfxpll);
#endif
tdfx_outl(par, PLLCTRL0, reg->vidpll);
vga_outb(par, MISC_W, reg->misc[0x00] | 0x01);
for (i = 0; i < 5; i++)
seq_outb(par, i, reg->seq[i]);
for (i = 0; i < 25; i++)
crt_outb(par, i, reg->crt[i]);
for (i = 0; i < 9; i++)
gra_outb(par, i, reg->gra[i]);
for (i = 0; i < 21; i++)
att_outb(par, i, reg->att[i]);
crt_outb(par, 0x1a, reg->ext[0]);
crt_outb(par, 0x1b, reg->ext[1]);
vga_enable_palette(par);
vga_enable_video(par);
banshee_make_room(par, 9);
tdfx_outl(par, VGAINIT0, reg->vgainit0);
tdfx_outl(par, DACMODE, reg->dacmode);
tdfx_outl(par, VIDDESKSTRIDE, reg->stride);
tdfx_outl(par, HWCURPATADDR, reg->curspataddr);
tdfx_outl(par, VIDSCREENSIZE, reg->screensize);
tdfx_outl(par, VIDDESKSTART, reg->startaddr);
tdfx_outl(par, VIDPROCCFG, reg->vidcfg);
tdfx_outl(par, VGAINIT1, reg->vgainit1);
tdfx_outl(par, MISCINIT0, reg->miscinit0);
banshee_make_room(par, 8);
tdfx_outl(par, SRCBASE, reg->startaddr);
tdfx_outl(par, DSTBASE, reg->startaddr);
tdfx_outl(par, COMMANDEXTRA_2D, 0);
tdfx_outl(par, CLIP0MIN, 0);
tdfx_outl(par, CLIP0MAX, 0x0fff0fff);
tdfx_outl(par, CLIP1MIN, 0);
tdfx_outl(par, CLIP1MAX, 0x0fff0fff);
tdfx_outl(par, SRCXY, 0);
banshee_wait_idle(info);
}
static unsigned long do_lfb_size(struct tdfx_par *par, unsigned short dev_id)
{
u32 draminit0 = tdfx_inl(par, DRAMINIT0);
u32 draminit1 = tdfx_inl(par, DRAMINIT1);
u32 miscinit1;
int num_chips = (draminit0 & DRAMINIT0_SGRAM_NUM) ? 8 : 4;
int chip_size; /* in MB */
int has_sgram = draminit1 & DRAMINIT1_MEM_SDRAM;
if (dev_id < PCI_DEVICE_ID_3DFX_VOODOO5) {
/* Banshee/Voodoo3 */
chip_size = 2;
if (has_sgram && !(draminit0 & DRAMINIT0_SGRAM_TYPE))
chip_size = 1;
} else {
/* Voodoo4/5 */
has_sgram = 0;
chip_size = draminit0 & DRAMINIT0_SGRAM_TYPE_MASK;
chip_size = 1 << (chip_size >> DRAMINIT0_SGRAM_TYPE_SHIFT);
}
/* disable block writes for SDRAM */
miscinit1 = tdfx_inl(par, MISCINIT1);
miscinit1 |= has_sgram ? 0 : MISCINIT1_2DBLOCK_DIS;
miscinit1 |= MISCINIT1_CLUT_INV;
banshee_make_room(par, 1);
tdfx_outl(par, MISCINIT1, miscinit1);
return num_chips * chip_size * 1024l * 1024;
}
/* ------------------------------------------------------------------------- */
static int tdfxfb_check_var(struct fb_var_screeninfo *var, struct fb_info *info)
{
struct tdfx_par *par = info->par;
u32 lpitch;
if (var->bits_per_pixel != 8 && var->bits_per_pixel != 16 &&
var->bits_per_pixel != 24 && var->bits_per_pixel != 32) {
DPRINTK("depth not supported: %u\n", var->bits_per_pixel);
return -EINVAL;
}
if (var->xres != var->xres_virtual)
var->xres_virtual = var->xres;
if (var->yres > var->yres_virtual)
var->yres_virtual = var->yres;
if (var->xoffset) {
DPRINTK("xoffset not supported\n");
return -EINVAL;
}
var->yoffset = 0;
/*
* Banshee doesn't support interlace, but Voodoo4/5 and probably
* Voodoo3 do.
* no direct information about device id now?
* use max_pixclock for this...
*/
if (((var->vmode & FB_VMODE_MASK) == FB_VMODE_INTERLACED) &&
(par->max_pixclock < VOODOO3_MAX_PIXCLOCK)) {
DPRINTK("interlace not supported\n");
return -EINVAL;
}
if (info->monspecs.hfmax && info->monspecs.vfmax &&
info->monspecs.dclkmax && fb_validate_mode(var, info) < 0) {
DPRINTK("mode outside monitor's specs\n");
return -EINVAL;
}
var->xres = (var->xres + 15) & ~15; /* could sometimes be 8 */
lpitch = var->xres * ((var->bits_per_pixel + 7) >> 3);
if (var->xres < 320 || var->xres > 2048) {
DPRINTK("width not supported: %u\n", var->xres);
return -EINVAL;
}
if (var->yres < 200 || var->yres > 2048) {
DPRINTK("height not supported: %u\n", var->yres);
return -EINVAL;
}
if (lpitch * var->yres_virtual > info->fix.smem_len) {
var->yres_virtual = info->fix.smem_len / lpitch;
if (var->yres_virtual < var->yres) {
DPRINTK("no memory for screen (%ux%ux%u)\n",
var->xres, var->yres_virtual,
var->bits_per_pixel);
return -EINVAL;
}
}
if (PICOS2KHZ(var->pixclock) > par->max_pixclock) {
DPRINTK("pixclock too high (%ldKHz)\n",
PICOS2KHZ(var->pixclock));
return -EINVAL;
}
var->transp.offset = 0;
var->transp.length = 0;
switch (var->bits_per_pixel) {
case 8:
var->red.length = 8;
var->red.offset = 0;
var->green = var->red;
var->blue = var->red;
break;
case 16:
var->red.offset = 11;
var->red.length = 5;
var->green.offset = 5;
var->green.length = 6;
var->blue.offset = 0;
var->blue.length = 5;
break;
case 32:
var->transp.offset = 24;
var->transp.length = 8;
case 24:
var->red.offset = 16;
var->green.offset = 8;
var->blue.offset = 0;
var->red.length = var->green.length = var->blue.length = 8;
break;
}
var->width = -1;
var->height = -1;
var->accel_flags = FB_ACCELF_TEXT;
DPRINTK("Checking graphics mode at %dx%d depth %d\n",
var->xres, var->yres, var->bits_per_pixel);
return 0;
}
static int tdfxfb_set_par(struct fb_info *info)
{
struct tdfx_par *par = info->par;
u32 hdispend = info->var.xres;
u32 hsyncsta = hdispend + info->var.right_margin;
u32 hsyncend = hsyncsta + info->var.hsync_len;
u32 htotal = hsyncend + info->var.left_margin;
u32 hd, hs, he, ht, hbs, hbe;
u32 vd, vs, ve, vt, vbs, vbe;
struct banshee_reg reg;
int fout, freq;
u32 wd;
u32 cpp = (info->var.bits_per_pixel + 7) >> 3;
memset(®, 0, sizeof(reg));
reg.vidcfg = VIDCFG_VIDPROC_ENABLE | VIDCFG_DESK_ENABLE |
VIDCFG_CURS_X11 |
((cpp - 1) << VIDCFG_PIXFMT_SHIFT) |
(cpp != 1 ? VIDCFG_CLUT_BYPASS : 0);
/* PLL settings */
freq = PICOS2KHZ(info->var.pixclock);
reg.vidcfg &= ~VIDCFG_2X;
if (freq > par->max_pixclock / 2) {
freq = freq > par->max_pixclock ? par->max_pixclock : freq;
reg.dacmode |= DACMODE_2X;
reg.vidcfg |= VIDCFG_2X;
hdispend >>= 1;
hsyncsta >>= 1;
hsyncend >>= 1;
htotal >>= 1;
}
wd = (hdispend >> 3) - 1;
hd = wd;
hs = (hsyncsta >> 3) - 1;
he = (hsyncend >> 3) - 1;
ht = (htotal >> 3) - 1;
hbs = hd;
hbe = ht;
if ((info->var.vmode & FB_VMODE_MASK) == FB_VMODE_DOUBLE) {
vd = (info->var.yres << 1) - 1;
vs = vd + (info->var.lower_margin << 1);
ve = vs + (info->var.vsync_len << 1);
vt = ve + (info->var.upper_margin << 1) - 1;
reg.screensize = info->var.xres | (info->var.yres << 13);
reg.vidcfg |= VIDCFG_HALF_MODE;
reg.crt[0x09] = 0x80;
} else {
vd = info->var.yres - 1;
vs = vd + info->var.lower_margin;
ve = vs + info->var.vsync_len;
vt = ve + info->var.upper_margin - 1;
reg.screensize = info->var.xres | (info->var.yres << 12);
reg.vidcfg &= ~VIDCFG_HALF_MODE;
}
vbs = vd;
vbe = vt;
/* this is all pretty standard VGA register stuffing */
reg.misc[0x00] = 0x0f |
(info->var.xres < 400 ? 0xa0 :
info->var.xres < 480 ? 0x60 :
info->var.xres < 768 ? 0xe0 : 0x20);
reg.gra[0x05] = 0x40;
reg.gra[0x06] = 0x05;
reg.gra[0x07] = 0x0f;
reg.gra[0x08] = 0xff;
reg.att[0x00] = 0x00;
reg.att[0x01] = 0x01;
reg.att[0x02] = 0x02;
reg.att[0x03] = 0x03;
reg.att[0x04] = 0x04;
reg.att[0x05] = 0x05;
reg.att[0x06] = 0x06;
reg.att[0x07] = 0x07;
reg.att[0x08] = 0x08;
reg.att[0x09] = 0x09;
reg.att[0x0a] = 0x0a;
reg.att[0x0b] = 0x0b;
reg.att[0x0c] = 0x0c;
reg.att[0x0d] = 0x0d;
reg.att[0x0e] = 0x0e;
reg.att[0x0f] = 0x0f;
reg.att[0x10] = 0x41;
reg.att[0x12] = 0x0f;
reg.seq[0x00] = 0x03;
reg.seq[0x01] = 0x01; /* fixme: clkdiv2? */
reg.seq[0x02] = 0x0f;
reg.seq[0x03] = 0x00;
reg.seq[0x04] = 0x0e;
reg.crt[0x00] = ht - 4;
reg.crt[0x01] = hd;
reg.crt[0x02] = hbs;
reg.crt[0x03] = 0x80 | (hbe & 0x1f);
reg.crt[0x04] = hs;
reg.crt[0x05] = ((hbe & 0x20) << 2) | (he & 0x1f);
reg.crt[0x06] = vt;
reg.crt[0x07] = ((vs & 0x200) >> 2) |
((vd & 0x200) >> 3) |
((vt & 0x200) >> 4) | 0x10 |
((vbs & 0x100) >> 5) |
((vs & 0x100) >> 6) |
((vd & 0x100) >> 7) |
((vt & 0x100) >> 8);
reg.crt[0x09] |= 0x40 | ((vbs & 0x200) >> 4);
reg.crt[0x10] = vs;
reg.crt[0x11] = (ve & 0x0f) | 0x20;
reg.crt[0x12] = vd;
reg.crt[0x13] = wd;
reg.crt[0x15] = vbs;
reg.crt[0x16] = vbe + 1;
reg.crt[0x17] = 0xc3;
reg.crt[0x18] = 0xff;
/* Banshee's nonvga stuff */
reg.ext[0x00] = (((ht & 0x100) >> 8) |
((hd & 0x100) >> 6) |
((hbs & 0x100) >> 4) |
((hbe & 0x40) >> 1) |
((hs & 0x100) >> 2) |
((he & 0x20) << 2));
reg.ext[0x01] = (((vt & 0x400) >> 10) |
((vd & 0x400) >> 8) |
((vbs & 0x400) >> 6) |
((vbe & 0x400) >> 4));
reg.vgainit0 = VGAINIT0_8BIT_DAC |
VGAINIT0_EXT_ENABLE |
VGAINIT0_WAKEUP_3C3 |
VGAINIT0_ALT_READBACK |
VGAINIT0_EXTSHIFTOUT;
reg.vgainit1 = tdfx_inl(par, VGAINIT1) & 0x1fffff;
if (hwcursor)
reg.curspataddr = info->fix.smem_len;
reg.cursloc = 0;
reg.cursc0 = 0;
reg.cursc1 = 0xffffff;
reg.stride = info->var.xres * cpp;
reg.startaddr = info->var.yoffset * reg.stride
+ info->var.xoffset * cpp;
reg.vidpll = do_calc_pll(freq, &fout);
#if 0
reg.mempll = do_calc_pll(..., &fout);
reg.gfxpll = do_calc_pll(..., &fout);
#endif
if ((info->var.vmode & FB_VMODE_MASK) == FB_VMODE_INTERLACED)
reg.vidcfg |= VIDCFG_INTERLACE;
reg.miscinit0 = tdfx_inl(par, MISCINIT0);
#if defined(__BIG_ENDIAN)
switch (info->var.bits_per_pixel) {
case 8:
case 24:
reg.miscinit0 &= ~(1 << 30);
reg.miscinit0 &= ~(1 << 31);
break;
case 16:
reg.miscinit0 |= (1 << 30);
reg.miscinit0 |= (1 << 31);
break;
case 32:
reg.miscinit0 |= (1 << 30);
reg.miscinit0 &= ~(1 << 31);
break;
}
#endif
do_write_regs(info, ®);
/* Now change fb_fix_screeninfo according to changes in par */
info->fix.line_length = reg.stride;
info->fix.visual = (info->var.bits_per_pixel == 8)
? FB_VISUAL_PSEUDOCOLOR
: FB_VISUAL_TRUECOLOR;
DPRINTK("Graphics mode is now set at %dx%d depth %d\n",
info->var.xres, info->var.yres, info->var.bits_per_pixel);
return 0;
}
/* A handy macro shamelessly pinched from matroxfb */
#define CNVT_TOHW(val, width) ((((val) << (width)) + 0x7FFF - (val)) >> 16)
static int tdfxfb_setcolreg(unsigned regno, unsigned red, unsigned green,
unsigned blue, unsigned transp,
struct fb_info *info)
{
struct tdfx_par *par = info->par;
u32 rgbcol;
if (regno >= info->cmap.len || regno > 255)
return 1;
/* grayscale works only partially under directcolor */
if (info->var.grayscale) {
/* grayscale = 0.30*R + 0.59*G + 0.11*B */
blue = (red * 77 + green * 151 + blue * 28) >> 8;
green = blue;
red = blue;
}
switch (info->fix.visual) {
case FB_VISUAL_PSEUDOCOLOR:
rgbcol = (((u32)red & 0xff00) << 8) |
(((u32)green & 0xff00) << 0) |
(((u32)blue & 0xff00) >> 8);
do_setpalentry(par, regno, rgbcol);
break;
/* Truecolor has no hardware color palettes. */
case FB_VISUAL_TRUECOLOR:
if (regno < 16) {
rgbcol = (CNVT_TOHW(red, info->var.red.length) <<
info->var.red.offset) |
(CNVT_TOHW(green, info->var.green.length) <<
info->var.green.offset) |
(CNVT_TOHW(blue, info->var.blue.length) <<
info->var.blue.offset) |
(CNVT_TOHW(transp, info->var.transp.length) <<
info->var.transp.offset);
par->palette[regno] = rgbcol;
}
break;
default:
DPRINTK("bad depth %u\n", info->var.bits_per_pixel);
break;
}
return 0;
}
/* 0 unblank, 1 blank, 2 no vsync, 3 no hsync, 4 off */
static int tdfxfb_blank(int blank, struct fb_info *info)
{
struct tdfx_par *par = info->par;
int vgablank = 1;
u32 dacmode = tdfx_inl(par, DACMODE);
dacmode &= ~(BIT(1) | BIT(3));
switch (blank) {
case FB_BLANK_UNBLANK: /* Screen: On; HSync: On, VSync: On */
vgablank = 0;
break;
case FB_BLANK_NORMAL: /* Screen: Off; HSync: On, VSync: On */
break;
case FB_BLANK_VSYNC_SUSPEND: /* Screen: Off; HSync: On, VSync: Off */
dacmode |= BIT(3);
break;
case FB_BLANK_HSYNC_SUSPEND: /* Screen: Off; HSync: Off, VSync: On */
dacmode |= BIT(1);
break;
case FB_BLANK_POWERDOWN: /* Screen: Off; HSync: Off, VSync: Off */
dacmode |= BIT(1) | BIT(3);
break;
}
banshee_make_room(par, 1);
tdfx_outl(par, DACMODE, dacmode);
if (vgablank)
vga_disable_video(par);
else
vga_enable_video(par);
return 0;
}
/*
* Set the starting position of the visible screen to var->yoffset
*/
static int tdfxfb_pan_display(struct fb_var_screeninfo *var,
struct fb_info *info)
{
struct tdfx_par *par = info->par;
u32 addr = var->yoffset * info->fix.line_length;
if (nopan || var->xoffset)
return -EINVAL;
banshee_make_room(par, 1);
tdfx_outl(par, VIDDESKSTART, addr);
return 0;
}
#ifdef CONFIG_FB_3DFX_ACCEL
/*
* FillRect 2D command (solidfill or invert (via ROP_XOR))
*/
static void tdfxfb_fillrect(struct fb_info *info,
const struct fb_fillrect *rect)
{
struct tdfx_par *par = info->par;
u32 bpp = info->var.bits_per_pixel;
u32 stride = info->fix.line_length;
u32 fmt = stride | ((bpp + ((bpp == 8) ? 0 : 8)) << 13);
int tdfx_rop;
u32 dx = rect->dx;
u32 dy = rect->dy;
u32 dstbase = 0;
if (rect->rop == ROP_COPY)
tdfx_rop = TDFX_ROP_COPY;
else
tdfx_rop = TDFX_ROP_XOR;
/* assume always rect->height < 4096 */
if (dy + rect->height > 4095) {
dstbase = stride * dy;
dy = 0;
}
/* assume always rect->width < 4096 */
if (dx + rect->width > 4095) {
dstbase += dx * bpp >> 3;
dx = 0;
}
banshee_make_room(par, 6);
tdfx_outl(par, DSTFORMAT, fmt);
if (info->fix.visual == FB_VISUAL_PSEUDOCOLOR) {
tdfx_outl(par, COLORFORE, rect->color);
} else { /* FB_VISUAL_TRUECOLOR */
tdfx_outl(par, COLORFORE, par->palette[rect->color]);
}
tdfx_outl(par, COMMAND_2D, COMMAND_2D_FILLRECT | (tdfx_rop << 24));
tdfx_outl(par, DSTBASE, dstbase);
tdfx_outl(par, DSTSIZE, rect->width | (rect->height << 16));
tdfx_outl(par, LAUNCH_2D, dx | (dy << 16));
}
/*
* Screen-to-Screen BitBlt 2D command (for the bmove fb op.)
*/
static void tdfxfb_copyarea(struct fb_info *info,
const struct fb_copyarea *area)
{
struct tdfx_par *par = info->par;
u32 sx = area->sx, sy = area->sy, dx = area->dx, dy = area->dy;
u32 bpp = info->var.bits_per_pixel;
u32 stride = info->fix.line_length;
u32 blitcmd = COMMAND_2D_S2S_BITBLT | (TDFX_ROP_COPY << 24);
u32 fmt = stride | ((bpp + ((bpp == 8) ? 0 : 8)) << 13);
u32 dstbase = 0;
u32 srcbase = 0;
/* assume always area->height < 4096 */
if (sy + area->height > 4095) {
srcbase = stride * sy;
sy = 0;
}
/* assume always area->width < 4096 */
if (sx + area->width > 4095) {
srcbase += sx * bpp >> 3;
sx = 0;
}
/* assume always area->height < 4096 */
if (dy + area->height > 4095) {
dstbase = stride * dy;
dy = 0;
}
/* assume always area->width < 4096 */
if (dx + area->width > 4095) {
dstbase += dx * bpp >> 3;
dx = 0;
}
if (area->sx <= area->dx) {
/* -X */
blitcmd |= BIT(14);
sx += area->width - 1;
dx += area->width - 1;
}
if (area->sy <= area->dy) {
/* -Y */
blitcmd |= BIT(15);
sy += area->height - 1;
dy += area->height - 1;
}
banshee_make_room(par, 8);
tdfx_outl(par, SRCFORMAT, fmt);
tdfx_outl(par, DSTFORMAT, fmt);
tdfx_outl(par, COMMAND_2D, blitcmd);
tdfx_outl(par, DSTSIZE, area->width | (area->height << 16));
tdfx_outl(par, DSTXY, dx | (dy << 16));
tdfx_outl(par, SRCBASE, srcbase);
tdfx_outl(par, DSTBASE, dstbase);
tdfx_outl(par, LAUNCH_2D, sx | (sy << 16));
}
static void tdfxfb_imageblit(struct fb_info *info, const struct fb_image *image)
{
struct tdfx_par *par = info->par;
int size = image->height * ((image->width * image->depth + 7) >> 3);
int fifo_free;
int i, stride = info->fix.line_length;
u32 bpp = info->var.bits_per_pixel;
u32 dstfmt = stride | ((bpp + ((bpp == 8) ? 0 : 8)) << 13);
u8 *chardata = (u8 *) image->data;
u32 srcfmt;
u32 dx = image->dx;
u32 dy = image->dy;
u32 dstbase = 0;
if (image->depth != 1) {
#ifdef BROKEN_CODE
banshee_make_room(par, 6 + ((size + 3) >> 2));
srcfmt = stride | ((bpp + ((bpp == 8) ? 0 : 8)) << 13) |
0x400000;
#else
cfb_imageblit(info, image);
#endif
return;
}
banshee_make_room(par, 9);
switch (info->fix.visual) {
case FB_VISUAL_PSEUDOCOLOR:
tdfx_outl(par, COLORFORE, image->fg_color);
tdfx_outl(par, COLORBACK, image->bg_color);
break;
case FB_VISUAL_TRUECOLOR:
default:
tdfx_outl(par, COLORFORE,
par->palette[image->fg_color]);
tdfx_outl(par, COLORBACK,
par->palette[image->bg_color]);
}
#ifdef __BIG_ENDIAN
srcfmt = 0x400000 | BIT(20);
#else
srcfmt = 0x400000;
#endif
/* assume always image->height < 4096 */
if (dy + image->height > 4095) {
dstbase = stride * dy;
dy = 0;
}
/* assume always image->width < 4096 */
if (dx + image->width > 4095) {
dstbase += dx * bpp >> 3;
dx = 0;
}
tdfx_outl(par, DSTBASE, dstbase);
tdfx_outl(par, SRCXY, 0);
tdfx_outl(par, DSTXY, dx | (dy << 16));
tdfx_outl(par, COMMAND_2D,
COMMAND_2D_H2S_BITBLT | (TDFX_ROP_COPY << 24));
tdfx_outl(par, SRCFORMAT, srcfmt);
tdfx_outl(par, DSTFORMAT, dstfmt);
tdfx_outl(par, DSTSIZE, image->width | (image->height << 16));
/* A count of how many free FIFO entries we've requested.
* When this goes negative, we need to request more. */
fifo_free = 0;
/* Send four bytes at a time of data */
for (i = (size >> 2); i > 0; i--) {
if (--fifo_free < 0) {
fifo_free = 31;
banshee_make_room(par, fifo_free);
}
tdfx_outl(par, LAUNCH_2D, *(u32 *)chardata);
chardata += 4;
}
/* Send the leftovers now */
banshee_make_room(par, 3);
switch (size % 4) {
case 0:
break;
case 1:
tdfx_outl(par, LAUNCH_2D, *chardata);
break;
case 2:
tdfx_outl(par, LAUNCH_2D, *(u16 *)chardata);
break;
case 3:
tdfx_outl(par, LAUNCH_2D,
*(u16 *)chardata | (chardata[3] << 24));
break;
}
}
#endif /* CONFIG_FB_3DFX_ACCEL */
static int tdfxfb_cursor(struct fb_info *info, struct fb_cursor *cursor)
{
struct tdfx_par *par = info->par;
u32 vidcfg;
if (!hwcursor)
return -EINVAL; /* just to force soft_cursor() call */
/* Too large of a cursor or wrong bpp :-( */
if (cursor->image.width > 64 ||
cursor->image.height > 64 ||
cursor->image.depth > 1)
return -EINVAL;
vidcfg = tdfx_inl(par, VIDPROCCFG);
if (cursor->enable)
tdfx_outl(par, VIDPROCCFG, vidcfg | VIDCFG_HWCURSOR_ENABLE);
else
tdfx_outl(par, VIDPROCCFG, vidcfg & ~VIDCFG_HWCURSOR_ENABLE);
/*
* If the cursor is not be changed this means either we want the
* current cursor state (if enable is set) or we want to query what
* we can do with the cursor (if enable is not set)
*/
if (!cursor->set)
return 0;
/* fix cursor color - XFree86 forgets to restore it properly */
if (cursor->set & FB_CUR_SETCMAP) {
struct fb_cmap cmap = info->cmap;
u32 bg_idx = cursor->image.bg_color;
u32 fg_idx = cursor->image.fg_color;
unsigned long bg_color, fg_color;
fg_color = (((u32)cmap.red[fg_idx] & 0xff00) << 8) |
(((u32)cmap.green[fg_idx] & 0xff00) << 0) |
(((u32)cmap.blue[fg_idx] & 0xff00) >> 8);
bg_color = (((u32)cmap.red[bg_idx] & 0xff00) << 8) |
(((u32)cmap.green[bg_idx] & 0xff00) << 0) |
(((u32)cmap.blue[bg_idx] & 0xff00) >> 8);
banshee_make_room(par, 2);
tdfx_outl(par, HWCURC0, bg_color);
tdfx_outl(par, HWCURC1, fg_color);
}
if (cursor->set & FB_CUR_SETPOS) {
int x = cursor->image.dx;
int y = cursor->image.dy - info->var.yoffset;
x += 63;
y += 63;
banshee_make_room(par, 1);
tdfx_outl(par, HWCURLOC, (y << 16) + x);
}
if (cursor->set & (FB_CUR_SETIMAGE | FB_CUR_SETSHAPE)) {
/*
* Voodoo 3 and above cards use 2 monochrome cursor patterns.
* The reason is so the card can fetch 8 words at a time
* and are stored on chip for use for the next 8 scanlines.
* This reduces the number of times for access to draw the
* cursor for each screen refresh.
* Each pattern is a bitmap of 64 bit wide and 64 bit high
* (total of 8192 bits or 1024 bytes). The two patterns are
* stored in such a way that pattern 0 always resides in the
* lower half (least significant 64 bits) of a 128 bit word
* and pattern 1 the upper half. If you examine the data of
* the cursor image the graphics card uses then from the
* beginning you see line one of pattern 0, line one of
* pattern 1, line two of pattern 0, line two of pattern 1,
* etc etc. The linear stride for the cursor is always 16 bytes
* (128 bits) which is the maximum cursor width times two for
* the two monochrome patterns.
*/
u8 __iomem *cursorbase = info->screen_base + info->fix.smem_len;
u8 *bitmap = (u8 *)cursor->image.data;
u8 *mask = (u8 *)cursor->mask;
int i;
fb_memset(cursorbase, 0, 1024);
for (i = 0; i < cursor->image.height; i++) {
int h = 0;
int j = (cursor->image.width + 7) >> 3;
for (; j > 0; j--) {
u8 data = *mask ^ *bitmap;
if (cursor->rop == ROP_COPY)
data = *mask & *bitmap;
/* Pattern 0. Copy the cursor mask to it */
fb_writeb(*mask, cursorbase + h);
mask++;
/* Pattern 1. Copy the cursor bitmap to it */
fb_writeb(data, cursorbase + h + 8);
bitmap++;
h++;
}
cursorbase += 16;
}
}
return 0;
}
static struct fb_ops tdfxfb_ops = {
.owner = THIS_MODULE,
.fb_check_var = tdfxfb_check_var,
.fb_set_par = tdfxfb_set_par,
.fb_setcolreg = tdfxfb_setcolreg,
.fb_blank = tdfxfb_blank,
.fb_pan_display = tdfxfb_pan_display,
.fb_sync = banshee_wait_idle,
.fb_cursor = tdfxfb_cursor,
#ifdef CONFIG_FB_3DFX_ACCEL
.fb_fillrect = tdfxfb_fillrect,
.fb_copyarea = tdfxfb_copyarea,
.fb_imageblit = tdfxfb_imageblit,
#else
.fb_fillrect = cfb_fillrect,
.fb_copyarea = cfb_copyarea,
.fb_imageblit = cfb_imageblit,
#endif
};
#ifdef CONFIG_FB_3DFX_I2C
/* The voo GPIO registers don't have individual masks for each bit
so we always have to read before writing. */
static void tdfxfb_i2c_setscl(void *data, int val)
{
struct tdfxfb_i2c_chan *chan = data;
struct tdfx_par *par = chan->par;
unsigned int r;
r = tdfx_inl(par, VIDSERPARPORT);
if (val)
r |= I2C_SCL_OUT;
else
r &= ~I2C_SCL_OUT;
tdfx_outl(par, VIDSERPARPORT, r);
tdfx_inl(par, VIDSERPARPORT); /* flush posted write */
}
static void tdfxfb_i2c_setsda(void *data, int val)
{
struct tdfxfb_i2c_chan *chan = data;
struct tdfx_par *par = chan->par;
unsigned int r;
r = tdfx_inl(par, VIDSERPARPORT);
if (val)
r |= I2C_SDA_OUT;
else
r &= ~I2C_SDA_OUT;
tdfx_outl(par, VIDSERPARPORT, r);
tdfx_inl(par, VIDSERPARPORT); /* flush posted write */
}
/* The GPIO pins are open drain, so the pins always remain outputs.
We rely on the i2c-algo-bit routines to set the pins high before
reading the input from other chips. */
static int tdfxfb_i2c_getscl(void *data)
{
struct tdfxfb_i2c_chan *chan = data;
struct tdfx_par *par = chan->par;
return (0 != (tdfx_inl(par, VIDSERPARPORT) & I2C_SCL_IN));
}
static int tdfxfb_i2c_getsda(void *data)
{
struct tdfxfb_i2c_chan *chan = data;
struct tdfx_par *par = chan->par;
return (0 != (tdfx_inl(par, VIDSERPARPORT) & I2C_SDA_IN));
}
static void tdfxfb_ddc_setscl(void *data, int val)
{
struct tdfxfb_i2c_chan *chan = data;
struct tdfx_par *par = chan->par;
unsigned int r;
r = tdfx_inl(par, VIDSERPARPORT);
if (val)
r |= DDC_SCL_OUT;
else
r &= ~DDC_SCL_OUT;
tdfx_outl(par, VIDSERPARPORT, r);
tdfx_inl(par, VIDSERPARPORT); /* flush posted write */
}
static void tdfxfb_ddc_setsda(void *data, int val)
{
struct tdfxfb_i2c_chan *chan = data;
struct tdfx_par *par = chan->par;
unsigned int r;
r = tdfx_inl(par, VIDSERPARPORT);
if (val)
r |= DDC_SDA_OUT;
else
r &= ~DDC_SDA_OUT;
tdfx_outl(par, VIDSERPARPORT, r);
tdfx_inl(par, VIDSERPARPORT); /* flush posted write */
}
static int tdfxfb_ddc_getscl(void *data)
{
struct tdfxfb_i2c_chan *chan = data;
struct tdfx_par *par = chan->par;
return (0 != (tdfx_inl(par, VIDSERPARPORT) & DDC_SCL_IN));
}
static int tdfxfb_ddc_getsda(void *data)
{
struct tdfxfb_i2c_chan *chan = data;
struct tdfx_par *par = chan->par;
return (0 != (tdfx_inl(par, VIDSERPARPORT) & DDC_SDA_IN));
}
static int tdfxfb_setup_ddc_bus(struct tdfxfb_i2c_chan *chan, const char *name,
struct device *dev)
{
int rc;
strlcpy(chan->adapter.name, name, sizeof(chan->adapter.name));
chan->adapter.owner = THIS_MODULE;
chan->adapter.class = I2C_CLASS_DDC;
chan->adapter.algo_data = &chan->algo;
chan->adapter.dev.parent = dev;
chan->algo.setsda = tdfxfb_ddc_setsda;
chan->algo.setscl = tdfxfb_ddc_setscl;
chan->algo.getsda = tdfxfb_ddc_getsda;
chan->algo.getscl = tdfxfb_ddc_getscl;
chan->algo.udelay = 10;
chan->algo.timeout = msecs_to_jiffies(500);
chan->algo.data = chan;
i2c_set_adapdata(&chan->adapter, chan);
rc = i2c_bit_add_bus(&chan->adapter);
if (rc == 0)
DPRINTK("I2C bus %s registered.\n", name);
else
chan->par = NULL;
return rc;
}
static int tdfxfb_setup_i2c_bus(struct tdfxfb_i2c_chan *chan, const char *name,
struct device *dev)
{
int rc;
strlcpy(chan->adapter.name, name, sizeof(chan->adapter.name));
chan->adapter.owner = THIS_MODULE;
chan->adapter.algo_data = &chan->algo;
chan->adapter.dev.parent = dev;
chan->algo.setsda = tdfxfb_i2c_setsda;
chan->algo.setscl = tdfxfb_i2c_setscl;
chan->algo.getsda = tdfxfb_i2c_getsda;
chan->algo.getscl = tdfxfb_i2c_getscl;
chan->algo.udelay = 10;
chan->algo.timeout = msecs_to_jiffies(500);
chan->algo.data = chan;
i2c_set_adapdata(&chan->adapter, chan);
rc = i2c_bit_add_bus(&chan->adapter);
if (rc == 0)
DPRINTK("I2C bus %s registered.\n", name);
else
chan->par = NULL;
return rc;
}
static void tdfxfb_create_i2c_busses(struct fb_info *info)
{
struct tdfx_par *par = info->par;
tdfx_outl(par, VIDINFORMAT, 0x8160);
tdfx_outl(par, VIDSERPARPORT, 0xcffc0020);
par->chan[0].par = par;
par->chan[1].par = par;
tdfxfb_setup_ddc_bus(&par->chan[0], "Voodoo3-DDC", info->dev);
tdfxfb_setup_i2c_bus(&par->chan[1], "Voodoo3-I2C", info->dev);
}
static void tdfxfb_delete_i2c_busses(struct tdfx_par *par)
{
if (par->chan[0].par)
i2c_del_adapter(&par->chan[0].adapter);
par->chan[0].par = NULL;
if (par->chan[1].par)
i2c_del_adapter(&par->chan[1].adapter);
par->chan[1].par = NULL;
}
static int tdfxfb_probe_i2c_connector(struct tdfx_par *par,
struct fb_monspecs *specs)
{
u8 *edid = NULL;
DPRINTK("Probe DDC Bus\n");
if (par->chan[0].par)
edid = fb_ddc_read(&par->chan[0].adapter);
if (edid) {
fb_edid_to_monspecs(edid, specs);
kfree(edid);
return 0;
}
return 1;
}
#endif /* CONFIG_FB_3DFX_I2C */
/**
* tdfxfb_probe - Device Initializiation
*
* @pdev: PCI Device to initialize
* @id: PCI Device ID
*
* Initializes and allocates resources for PCI device @pdev.
*
*/
static int tdfxfb_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{
struct tdfx_par *default_par;
struct fb_info *info;
int err, lpitch;
struct fb_monspecs *specs;
bool found;
err = pci_enable_device(pdev);
if (err) {
printk(KERN_ERR "tdfxfb: Can't enable pdev: %d\n", err);
return err;
}
info = framebuffer_alloc(sizeof(struct tdfx_par), &pdev->dev);
if (!info)
return -ENOMEM;
default_par = info->par;
info->fix = tdfx_fix;
/* Configure the default fb_fix_screeninfo first */
switch (pdev->device) {
case PCI_DEVICE_ID_3DFX_BANSHEE:
strcpy(info->fix.id, "3Dfx Banshee");
default_par->max_pixclock = BANSHEE_MAX_PIXCLOCK;
break;
case PCI_DEVICE_ID_3DFX_VOODOO3:
strcpy(info->fix.id, "3Dfx Voodoo3");
default_par->max_pixclock = VOODOO3_MAX_PIXCLOCK;
break;
case PCI_DEVICE_ID_3DFX_VOODOO5:
strcpy(info->fix.id, "3Dfx Voodoo5");
default_par->max_pixclock = VOODOO5_MAX_PIXCLOCK;
break;
}
info->fix.mmio_start = pci_resource_start(pdev, 0);
info->fix.mmio_len = pci_resource_len(pdev, 0);
if (!request_mem_region(info->fix.mmio_start, info->fix.mmio_len,
"tdfx regbase")) {
printk(KERN_ERR "tdfxfb: Can't reserve regbase\n");
goto out_err;
}
default_par->regbase_virt =
ioremap_nocache(info->fix.mmio_start, info->fix.mmio_len);
if (!default_par->regbase_virt) {
printk(KERN_ERR "fb: Can't remap %s register area.\n",
info->fix.id);
goto out_err_regbase;
}
info->fix.smem_start = pci_resource_start(pdev, 1);
info->fix.smem_len = do_lfb_size(default_par, pdev->device);
if (!info->fix.smem_len) {
printk(KERN_ERR "fb: Can't count %s memory.\n", info->fix.id);
goto out_err_regbase;
}
if (!request_mem_region(info->fix.smem_start,
pci_resource_len(pdev, 1), "tdfx smem")) {
printk(KERN_ERR "tdfxfb: Can't reserve smem\n");
goto out_err_regbase;
}
info->screen_base = ioremap_nocache(info->fix.smem_start,
info->fix.smem_len);
if (!info->screen_base) {
printk(KERN_ERR "fb: Can't remap %s framebuffer.\n",
info->fix.id);
goto out_err_screenbase;
}
default_par->iobase = pci_resource_start(pdev, 2);
if (!request_region(pci_resource_start(pdev, 2),
pci_resource_len(pdev, 2), "tdfx iobase")) {
printk(KERN_ERR "tdfxfb: Can't reserve iobase\n");
goto out_err_screenbase;
}
printk(KERN_INFO "fb: %s memory = %dK\n", info->fix.id,
info->fix.smem_len >> 10);
default_par->mtrr_handle = -1;
if (!nomtrr)
default_par->mtrr_handle =
mtrr_add(info->fix.smem_start, info->fix.smem_len,
MTRR_TYPE_WRCOMB, 1);
info->fix.ypanstep = nopan ? 0 : 1;
info->fix.ywrapstep = nowrap ? 0 : 1;
info->fbops = &tdfxfb_ops;
info->pseudo_palette = default_par->palette;
info->flags = FBINFO_DEFAULT | FBINFO_HWACCEL_YPAN;
#ifdef CONFIG_FB_3DFX_ACCEL
info->flags |= FBINFO_HWACCEL_FILLRECT |
FBINFO_HWACCEL_COPYAREA |
FBINFO_HWACCEL_IMAGEBLIT |
FBINFO_READS_FAST;
#endif
/* reserve 8192 bits for cursor */
/* the 2.4 driver says PAGE_MASK boundary is not enough for Voodoo4 */
if (hwcursor)
info->fix.smem_len = (info->fix.smem_len - 1024) &
(PAGE_MASK << 1);
specs = &info->monspecs;
found = false;
info->var.bits_per_pixel = 8;
#ifdef CONFIG_FB_3DFX_I2C
tdfxfb_create_i2c_busses(info);
err = tdfxfb_probe_i2c_connector(default_par, specs);
if (!err) {
if (specs->modedb == NULL)
DPRINTK("Unable to get Mode Database\n");
else {
const struct fb_videomode *m;
fb_videomode_to_modelist(specs->modedb,
specs->modedb_len,
&info->modelist);
m = fb_find_best_display(specs, &info->modelist);
if (m) {
fb_videomode_to_var(&info->var, m);
/* fill all other info->var's fields */
if (tdfxfb_check_var(&info->var, info) < 0)
info->var = tdfx_var;
else
found = true;
}
}
}
#endif
if (!mode_option && !found)
mode_option = "640x480@60";
if (mode_option) {
err = fb_find_mode(&info->var, info, mode_option,
specs->modedb, specs->modedb_len,
NULL, info->var.bits_per_pixel);
if (!err || err == 4)
info->var = tdfx_var;
}
if (found) {
fb_destroy_modedb(specs->modedb);
specs->modedb = NULL;
}
/* maximize virtual vertical length */
lpitch = info->var.xres_virtual * ((info->var.bits_per_pixel + 7) >> 3);
info->var.yres_virtual = info->fix.smem_len / lpitch;
if (info->var.yres_virtual < info->var.yres)
goto out_err_iobase;
if (fb_alloc_cmap(&info->cmap, 256, 0) < 0) {
printk(KERN_ERR "tdfxfb: Can't allocate color map\n");
goto out_err_iobase;
}
if (register_framebuffer(info) < 0) {
printk(KERN_ERR "tdfxfb: can't register framebuffer\n");
fb_dealloc_cmap(&info->cmap);
goto out_err_iobase;
}
/*
* Our driver data
*/
pci_set_drvdata(pdev, info);
return 0;
out_err_iobase:
#ifdef CONFIG_FB_3DFX_I2C
tdfxfb_delete_i2c_busses(default_par);
#endif
if (default_par->mtrr_handle >= 0)
mtrr_del(default_par->mtrr_handle, info->fix.smem_start,
info->fix.smem_len);
release_region(pci_resource_start(pdev, 2),
pci_resource_len(pdev, 2));
out_err_screenbase:
if (info->screen_base)
iounmap(info->screen_base);
release_mem_region(info->fix.smem_start, pci_resource_len(pdev, 1));
out_err_regbase:
/*
* Cleanup after anything that was remapped/allocated.
*/
if (default_par->regbase_virt)
iounmap(default_par->regbase_virt);
release_mem_region(info->fix.mmio_start, info->fix.mmio_len);
out_err:
framebuffer_release(info);
return -ENXIO;
}
#ifndef MODULE
static void __init tdfxfb_setup(char *options)
{
char *this_opt;
if (!options || !*options)
return;
while ((this_opt = strsep(&options, ",")) != NULL) {
if (!*this_opt)
continue;
if (!strcmp(this_opt, "nopan")) {
nopan = 1;
} else if (!strcmp(this_opt, "nowrap")) {
nowrap = 1;
} else if (!strncmp(this_opt, "hwcursor=", 9)) {
hwcursor = simple_strtoul(this_opt + 9, NULL, 0);
#ifdef CONFIG_MTRR
} else if (!strncmp(this_opt, "nomtrr", 6)) {
nomtrr = 1;
#endif
} else {
mode_option = this_opt;
}
}
}
#endif
/**
* tdfxfb_remove - Device removal
*
* @pdev: PCI Device to cleanup
*
* Releases all resources allocated during the course of the driver's
* lifetime for the PCI device @pdev.
*
*/
static void tdfxfb_remove(struct pci_dev *pdev)
{
struct fb_info *info = pci_get_drvdata(pdev);
struct tdfx_par *par = info->par;
unregister_framebuffer(info);
#ifdef CONFIG_FB_3DFX_I2C
tdfxfb_delete_i2c_busses(par);
#endif
if (par->mtrr_handle >= 0)
mtrr_del(par->mtrr_handle, info->fix.smem_start,
info->fix.smem_len);
iounmap(par->regbase_virt);
iounmap(info->screen_base);
/* Clean up after reserved regions */
release_region(pci_resource_start(pdev, 2),
pci_resource_len(pdev, 2));
release_mem_region(pci_resource_start(pdev, 1),
pci_resource_len(pdev, 1));
release_mem_region(pci_resource_start(pdev, 0),
pci_resource_len(pdev, 0));
pci_set_drvdata(pdev, NULL);
fb_dealloc_cmap(&info->cmap);
framebuffer_release(info);
}
static int __init tdfxfb_init(void)
{
#ifndef MODULE
char *option = NULL;
if (fb_get_options("tdfxfb", &option))
return -ENODEV;
tdfxfb_setup(option);
#endif
return pci_register_driver(&tdfxfb_driver);
}
static void __exit tdfxfb_exit(void)
{
pci_unregister_driver(&tdfxfb_driver);
}
MODULE_AUTHOR("Hannu Mallat <hmallat@cc.hut.fi>");
MODULE_DESCRIPTION("3Dfx framebuffer device driver");
MODULE_LICENSE("GPL");
module_param(hwcursor, int, 0644);
MODULE_PARM_DESC(hwcursor, "Enable hardware cursor "
"(1=enable, 0=disable, default=1)");
module_param(mode_option, charp, 0);
MODULE_PARM_DESC(mode_option, "Initial video mode e.g. '648x480-8@60'");
#ifdef CONFIG_MTRR
module_param(nomtrr, bool, 0);
MODULE_PARM_DESC(nomtrr, "Disable MTRR support (default: enabled)");
#endif
module_init(tdfxfb_init);
module_exit(tdfxfb_exit);
| gpl-2.0 |
myjang0507/Polaris | drivers/net/usb/zaurus.c | 2654 | 12101 | /*
* Copyright (C) 2002 Pavel Machek <pavel@ucw.cz>
* Copyright (C) 2002-2005 by David Brownell
*
* 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 DEBUG // error path messages, extra info
// #define VERBOSE // more; success messages
#include <linux/module.h>
#include <linux/init.h>
#include <linux/netdevice.h>
#include <linux/ethtool.h>
#include <linux/workqueue.h>
#include <linux/mii.h>
#include <linux/crc32.h>
#include <linux/usb.h>
#include <linux/usb/cdc.h>
#include <linux/usb/usbnet.h>
/*
* All known Zaurii lie about their standards conformance. At least
* the earliest SA-1100 models lie by saying they support CDC Ethernet.
* Some later models (especially PXA-25x and PXA-27x based ones) lie
* and say they support CDC MDLM (for access to cell phone modems).
*
* There are non-Zaurus products that use these same protocols too.
*
* The annoying thing is that at the same time Sharp was developing
* that annoying standards-breaking software, the Linux community had
* a simple "CDC Subset" working reliably on the same SA-1100 hardware.
* That is, the same functionality but not violating standards.
*
* The CDC Ethernet nonconformance points are troublesome to hosts
* with a true CDC Ethernet implementation:
* - Framing appends a CRC, which the spec says drivers "must not" do;
* - Transfers data in altsetting zero, instead of altsetting 1;
* - All these peripherals use the same ethernet address.
*
* The CDC MDLM nonconformance is less immediately troublesome, since all
* MDLM implementations are quasi-proprietary anyway.
*/
static struct sk_buff *
zaurus_tx_fixup(struct usbnet *dev, struct sk_buff *skb, gfp_t flags)
{
int padlen;
struct sk_buff *skb2;
padlen = 2;
if (!skb_cloned(skb)) {
int tailroom = skb_tailroom(skb);
if ((padlen + 4) <= tailroom)
goto done;
}
skb2 = skb_copy_expand(skb, 0, 4 + padlen, flags);
dev_kfree_skb_any(skb);
skb = skb2;
if (skb) {
u32 fcs;
done:
fcs = crc32_le(~0, skb->data, skb->len);
fcs = ~fcs;
*skb_put (skb, 1) = fcs & 0xff;
*skb_put (skb, 1) = (fcs>> 8) & 0xff;
*skb_put (skb, 1) = (fcs>>16) & 0xff;
*skb_put (skb, 1) = (fcs>>24) & 0xff;
}
return skb;
}
static int zaurus_bind(struct usbnet *dev, struct usb_interface *intf)
{
/* Belcarra's funky framing has other options; mostly
* TRAILERS (!) with 4 bytes CRC, and maybe 2 pad bytes.
*/
dev->net->hard_header_len += 6;
dev->rx_urb_size = dev->net->hard_header_len + dev->net->mtu;
return usbnet_generic_cdc_bind(dev, intf);
}
/* PDA style devices are always connected if present */
static int always_connected (struct usbnet *dev)
{
return 0;
}
static const struct driver_info zaurus_sl5x00_info = {
.description = "Sharp Zaurus SL-5x00",
.flags = FLAG_POINTTOPOINT | FLAG_FRAMING_Z,
.check_connect = always_connected,
.bind = zaurus_bind,
.unbind = usbnet_cdc_unbind,
.tx_fixup = zaurus_tx_fixup,
};
#define ZAURUS_STRONGARM_INFO ((unsigned long)&zaurus_sl5x00_info)
static const struct driver_info zaurus_pxa_info = {
.description = "Sharp Zaurus, PXA-2xx based",
.flags = FLAG_POINTTOPOINT | FLAG_FRAMING_Z,
.check_connect = always_connected,
.bind = zaurus_bind,
.unbind = usbnet_cdc_unbind,
.tx_fixup = zaurus_tx_fixup,
};
#define ZAURUS_PXA_INFO ((unsigned long)&zaurus_pxa_info)
static const struct driver_info olympus_mxl_info = {
.description = "Olympus R1000",
.flags = FLAG_POINTTOPOINT | FLAG_FRAMING_Z,
.check_connect = always_connected,
.bind = zaurus_bind,
.unbind = usbnet_cdc_unbind,
.tx_fixup = zaurus_tx_fixup,
};
#define OLYMPUS_MXL_INFO ((unsigned long)&olympus_mxl_info)
/* Some more recent products using Lineo/Belcarra code will wrongly claim
* CDC MDLM conformance. They aren't conformant: data endpoints live
* in the control interface, there's no data interface, and it's not used
* to talk to a cell phone radio. But at least we can detect these two
* pseudo-classes, rather than growing this product list with entries for
* each new nonconformant product (sigh).
*/
static const u8 safe_guid[16] = {
0x5d, 0x34, 0xcf, 0x66, 0x11, 0x18, 0x11, 0xd6,
0xa2, 0x1a, 0x00, 0x01, 0x02, 0xca, 0x9a, 0x7f,
};
static const u8 blan_guid[16] = {
0x74, 0xf0, 0x3d, 0xbd, 0x1e, 0xc1, 0x44, 0x70,
0xa3, 0x67, 0x71, 0x34, 0xc9, 0xf5, 0x54, 0x37,
};
static int blan_mdlm_bind(struct usbnet *dev, struct usb_interface *intf)
{
u8 *buf = intf->cur_altsetting->extra;
int len = intf->cur_altsetting->extralen;
struct usb_cdc_mdlm_desc *desc = NULL;
struct usb_cdc_mdlm_detail_desc *detail = NULL;
while (len > 3) {
if (buf [1] != USB_DT_CS_INTERFACE)
goto next_desc;
/* use bDescriptorSubType, and just verify that we get a
* "BLAN" (or "SAFE") descriptor.
*/
switch (buf [2]) {
case USB_CDC_MDLM_TYPE:
if (desc) {
dev_dbg(&intf->dev, "extra MDLM\n");
goto bad_desc;
}
desc = (void *) buf;
if (desc->bLength != sizeof *desc) {
dev_dbg(&intf->dev, "MDLM len %u\n",
desc->bLength);
goto bad_desc;
}
/* expect bcdVersion 1.0, ignore */
if (memcmp(&desc->bGUID, blan_guid, 16) &&
memcmp(&desc->bGUID, safe_guid, 16)) {
/* hey, this one might _really_ be MDLM! */
dev_dbg(&intf->dev, "MDLM guid\n");
goto bad_desc;
}
break;
case USB_CDC_MDLM_DETAIL_TYPE:
if (detail) {
dev_dbg(&intf->dev, "extra MDLM detail\n");
goto bad_desc;
}
detail = (void *) buf;
switch (detail->bGuidDescriptorType) {
case 0: /* "SAFE" */
if (detail->bLength != (sizeof *detail + 2))
goto bad_detail;
break;
case 1: /* "BLAN" */
if (detail->bLength != (sizeof *detail + 3))
goto bad_detail;
break;
default:
goto bad_detail;
}
/* assuming we either noticed BLAN already, or will
* find it soon, there are some data bytes here:
* - bmNetworkCapabilities (unused)
* - bmDataCapabilities (bits, see below)
* - bPad (ignored, for PADAFTER -- BLAN-only)
* bits are:
* - 0x01 -- Zaurus framing (add CRC)
* - 0x02 -- PADBEFORE (CRC includes some padding)
* - 0x04 -- PADAFTER (some padding after CRC)
* - 0x08 -- "fermat" packet mangling (for hw bugs)
* the PADBEFORE appears not to matter; we interop
* with devices that use it and those that don't.
*/
if ((detail->bDetailData[1] & ~0x02) != 0x01) {
/* bmDataCapabilities == 0 would be fine too,
* but framing is minidriver-coupled for now.
*/
bad_detail:
dev_dbg(&intf->dev,
"bad MDLM detail, %d %d %d\n",
detail->bLength,
detail->bDetailData[0],
detail->bDetailData[2]);
goto bad_desc;
}
/* same extra framing as for non-BLAN mode */
dev->net->hard_header_len += 6;
dev->rx_urb_size = dev->net->hard_header_len
+ dev->net->mtu;
break;
}
next_desc:
len -= buf [0]; /* bLength */
buf += buf [0];
}
if (!desc || !detail) {
dev_dbg(&intf->dev, "missing cdc mdlm %s%sdescriptor\n",
desc ? "" : "func ",
detail ? "" : "detail ");
goto bad_desc;
}
/* There's probably a CDC Ethernet descriptor there, but we can't
* rely on the Ethernet address it provides since not all vendors
* bother to make it unique. Likewise there's no point in tracking
* of the CDC event notifications.
*/
return usbnet_get_endpoints(dev, intf);
bad_desc:
dev_info(&dev->udev->dev, "unsupported MDLM descriptors\n");
return -ENODEV;
}
static const struct driver_info bogus_mdlm_info = {
.description = "pseudo-MDLM (BLAN) device",
.flags = FLAG_POINTTOPOINT | FLAG_FRAMING_Z,
.check_connect = always_connected,
.tx_fixup = zaurus_tx_fixup,
.bind = blan_mdlm_bind,
};
static const struct usb_device_id products [] = {
#define ZAURUS_MASTER_INTERFACE \
.bInterfaceClass = USB_CLASS_COMM, \
.bInterfaceSubClass = USB_CDC_SUBCLASS_ETHERNET, \
.bInterfaceProtocol = USB_CDC_PROTO_NONE
/* SA-1100 based Sharp Zaurus ("collie"), or compatible. */
{
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x04DD,
.idProduct = 0x8004,
ZAURUS_MASTER_INTERFACE,
.driver_info = ZAURUS_STRONGARM_INFO,
},
/* PXA-2xx based models are also lying-about-cdc. If you add any
* more devices that claim to be CDC Ethernet, make sure they get
* added to the blacklist in cdc_ether too.
*
* NOTE: OpenZaurus versions with 2.6 kernels won't use these entries,
* unlike the older ones with 2.4 "embedix" kernels.
*/
{
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x04DD,
.idProduct = 0x8005, /* A-300 */
ZAURUS_MASTER_INTERFACE,
.driver_info = ZAURUS_PXA_INFO,
}, {
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x04DD,
.idProduct = 0x8006, /* B-500/SL-5600 */
ZAURUS_MASTER_INTERFACE,
.driver_info = ZAURUS_PXA_INFO,
}, {
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x04DD,
.idProduct = 0x8007, /* C-700 */
ZAURUS_MASTER_INTERFACE,
.driver_info = ZAURUS_PXA_INFO,
}, {
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x04DD,
.idProduct = 0x9031, /* C-750 C-760 */
ZAURUS_MASTER_INTERFACE,
.driver_info = ZAURUS_PXA_INFO,
}, {
/* C-750/C-760/C-860/SL-C3000 PDA in MDLM mode */
USB_DEVICE_AND_INTERFACE_INFO(0x04DD, 0x9031, USB_CLASS_COMM,
USB_CDC_SUBCLASS_MDLM, USB_CDC_PROTO_NONE),
.driver_info = (unsigned long) &bogus_mdlm_info,
}, {
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x04DD,
.idProduct = 0x9032, /* SL-6000 */
ZAURUS_MASTER_INTERFACE,
.driver_info = ZAURUS_PXA_INFO,
}, {
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x04DD,
/* reported with some C860 units */
.idProduct = 0x9050, /* C-860 */
ZAURUS_MASTER_INTERFACE,
.driver_info = ZAURUS_PXA_INFO,
},
{
/* Motorola Rokr E6 */
USB_DEVICE_AND_INTERFACE_INFO(0x22b8, 0x6027, USB_CLASS_COMM,
USB_CDC_SUBCLASS_MDLM, USB_CDC_PROTO_NONE),
.driver_info = (unsigned long) &bogus_mdlm_info,
}, {
/* Motorola MOTOMAGX phones */
USB_DEVICE_AND_INTERFACE_INFO(0x22b8, 0x6425, USB_CLASS_COMM,
USB_CDC_SUBCLASS_MDLM, USB_CDC_PROTO_NONE),
.driver_info = (unsigned long) &bogus_mdlm_info,
},
/* Olympus has some models with a Zaurus-compatible option.
* R-1000 uses a FreeScale i.MXL cpu (ARMv4T)
*/
{
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x07B4,
.idProduct = 0x0F02, /* R-1000 */
ZAURUS_MASTER_INTERFACE,
.driver_info = OLYMPUS_MXL_INFO,
},
/* Logitech Harmony 900 - uses the pseudo-MDLM (BLAN) driver */
{
USB_DEVICE_AND_INTERFACE_INFO(0x046d, 0xc11f, USB_CLASS_COMM,
USB_CDC_SUBCLASS_MDLM, USB_CDC_PROTO_NONE),
.driver_info = (unsigned long) &bogus_mdlm_info,
},
{ }, // END
};
MODULE_DEVICE_TABLE(usb, products);
static struct usb_driver zaurus_driver = {
.name = "zaurus",
.id_table = products,
.probe = usbnet_probe,
.disconnect = usbnet_disconnect,
.suspend = usbnet_suspend,
.resume = usbnet_resume,
.disable_hub_initiated_lpm = 1,
};
module_usb_driver(zaurus_driver);
MODULE_AUTHOR("Pavel Machek, David Brownell");
MODULE_DESCRIPTION("Sharp Zaurus PDA, and compatible products");
MODULE_LICENSE("GPL");
| gpl-2.0 |
TenchiMasaki/android_kernel_asus_moorefield | drivers/net/usb/zaurus.c | 2654 | 12101 | /*
* Copyright (C) 2002 Pavel Machek <pavel@ucw.cz>
* Copyright (C) 2002-2005 by David Brownell
*
* 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 DEBUG // error path messages, extra info
// #define VERBOSE // more; success messages
#include <linux/module.h>
#include <linux/init.h>
#include <linux/netdevice.h>
#include <linux/ethtool.h>
#include <linux/workqueue.h>
#include <linux/mii.h>
#include <linux/crc32.h>
#include <linux/usb.h>
#include <linux/usb/cdc.h>
#include <linux/usb/usbnet.h>
/*
* All known Zaurii lie about their standards conformance. At least
* the earliest SA-1100 models lie by saying they support CDC Ethernet.
* Some later models (especially PXA-25x and PXA-27x based ones) lie
* and say they support CDC MDLM (for access to cell phone modems).
*
* There are non-Zaurus products that use these same protocols too.
*
* The annoying thing is that at the same time Sharp was developing
* that annoying standards-breaking software, the Linux community had
* a simple "CDC Subset" working reliably on the same SA-1100 hardware.
* That is, the same functionality but not violating standards.
*
* The CDC Ethernet nonconformance points are troublesome to hosts
* with a true CDC Ethernet implementation:
* - Framing appends a CRC, which the spec says drivers "must not" do;
* - Transfers data in altsetting zero, instead of altsetting 1;
* - All these peripherals use the same ethernet address.
*
* The CDC MDLM nonconformance is less immediately troublesome, since all
* MDLM implementations are quasi-proprietary anyway.
*/
static struct sk_buff *
zaurus_tx_fixup(struct usbnet *dev, struct sk_buff *skb, gfp_t flags)
{
int padlen;
struct sk_buff *skb2;
padlen = 2;
if (!skb_cloned(skb)) {
int tailroom = skb_tailroom(skb);
if ((padlen + 4) <= tailroom)
goto done;
}
skb2 = skb_copy_expand(skb, 0, 4 + padlen, flags);
dev_kfree_skb_any(skb);
skb = skb2;
if (skb) {
u32 fcs;
done:
fcs = crc32_le(~0, skb->data, skb->len);
fcs = ~fcs;
*skb_put (skb, 1) = fcs & 0xff;
*skb_put (skb, 1) = (fcs>> 8) & 0xff;
*skb_put (skb, 1) = (fcs>>16) & 0xff;
*skb_put (skb, 1) = (fcs>>24) & 0xff;
}
return skb;
}
static int zaurus_bind(struct usbnet *dev, struct usb_interface *intf)
{
/* Belcarra's funky framing has other options; mostly
* TRAILERS (!) with 4 bytes CRC, and maybe 2 pad bytes.
*/
dev->net->hard_header_len += 6;
dev->rx_urb_size = dev->net->hard_header_len + dev->net->mtu;
return usbnet_generic_cdc_bind(dev, intf);
}
/* PDA style devices are always connected if present */
static int always_connected (struct usbnet *dev)
{
return 0;
}
static const struct driver_info zaurus_sl5x00_info = {
.description = "Sharp Zaurus SL-5x00",
.flags = FLAG_POINTTOPOINT | FLAG_FRAMING_Z,
.check_connect = always_connected,
.bind = zaurus_bind,
.unbind = usbnet_cdc_unbind,
.tx_fixup = zaurus_tx_fixup,
};
#define ZAURUS_STRONGARM_INFO ((unsigned long)&zaurus_sl5x00_info)
static const struct driver_info zaurus_pxa_info = {
.description = "Sharp Zaurus, PXA-2xx based",
.flags = FLAG_POINTTOPOINT | FLAG_FRAMING_Z,
.check_connect = always_connected,
.bind = zaurus_bind,
.unbind = usbnet_cdc_unbind,
.tx_fixup = zaurus_tx_fixup,
};
#define ZAURUS_PXA_INFO ((unsigned long)&zaurus_pxa_info)
static const struct driver_info olympus_mxl_info = {
.description = "Olympus R1000",
.flags = FLAG_POINTTOPOINT | FLAG_FRAMING_Z,
.check_connect = always_connected,
.bind = zaurus_bind,
.unbind = usbnet_cdc_unbind,
.tx_fixup = zaurus_tx_fixup,
};
#define OLYMPUS_MXL_INFO ((unsigned long)&olympus_mxl_info)
/* Some more recent products using Lineo/Belcarra code will wrongly claim
* CDC MDLM conformance. They aren't conformant: data endpoints live
* in the control interface, there's no data interface, and it's not used
* to talk to a cell phone radio. But at least we can detect these two
* pseudo-classes, rather than growing this product list with entries for
* each new nonconformant product (sigh).
*/
static const u8 safe_guid[16] = {
0x5d, 0x34, 0xcf, 0x66, 0x11, 0x18, 0x11, 0xd6,
0xa2, 0x1a, 0x00, 0x01, 0x02, 0xca, 0x9a, 0x7f,
};
static const u8 blan_guid[16] = {
0x74, 0xf0, 0x3d, 0xbd, 0x1e, 0xc1, 0x44, 0x70,
0xa3, 0x67, 0x71, 0x34, 0xc9, 0xf5, 0x54, 0x37,
};
static int blan_mdlm_bind(struct usbnet *dev, struct usb_interface *intf)
{
u8 *buf = intf->cur_altsetting->extra;
int len = intf->cur_altsetting->extralen;
struct usb_cdc_mdlm_desc *desc = NULL;
struct usb_cdc_mdlm_detail_desc *detail = NULL;
while (len > 3) {
if (buf [1] != USB_DT_CS_INTERFACE)
goto next_desc;
/* use bDescriptorSubType, and just verify that we get a
* "BLAN" (or "SAFE") descriptor.
*/
switch (buf [2]) {
case USB_CDC_MDLM_TYPE:
if (desc) {
dev_dbg(&intf->dev, "extra MDLM\n");
goto bad_desc;
}
desc = (void *) buf;
if (desc->bLength != sizeof *desc) {
dev_dbg(&intf->dev, "MDLM len %u\n",
desc->bLength);
goto bad_desc;
}
/* expect bcdVersion 1.0, ignore */
if (memcmp(&desc->bGUID, blan_guid, 16) &&
memcmp(&desc->bGUID, safe_guid, 16)) {
/* hey, this one might _really_ be MDLM! */
dev_dbg(&intf->dev, "MDLM guid\n");
goto bad_desc;
}
break;
case USB_CDC_MDLM_DETAIL_TYPE:
if (detail) {
dev_dbg(&intf->dev, "extra MDLM detail\n");
goto bad_desc;
}
detail = (void *) buf;
switch (detail->bGuidDescriptorType) {
case 0: /* "SAFE" */
if (detail->bLength != (sizeof *detail + 2))
goto bad_detail;
break;
case 1: /* "BLAN" */
if (detail->bLength != (sizeof *detail + 3))
goto bad_detail;
break;
default:
goto bad_detail;
}
/* assuming we either noticed BLAN already, or will
* find it soon, there are some data bytes here:
* - bmNetworkCapabilities (unused)
* - bmDataCapabilities (bits, see below)
* - bPad (ignored, for PADAFTER -- BLAN-only)
* bits are:
* - 0x01 -- Zaurus framing (add CRC)
* - 0x02 -- PADBEFORE (CRC includes some padding)
* - 0x04 -- PADAFTER (some padding after CRC)
* - 0x08 -- "fermat" packet mangling (for hw bugs)
* the PADBEFORE appears not to matter; we interop
* with devices that use it and those that don't.
*/
if ((detail->bDetailData[1] & ~0x02) != 0x01) {
/* bmDataCapabilities == 0 would be fine too,
* but framing is minidriver-coupled for now.
*/
bad_detail:
dev_dbg(&intf->dev,
"bad MDLM detail, %d %d %d\n",
detail->bLength,
detail->bDetailData[0],
detail->bDetailData[2]);
goto bad_desc;
}
/* same extra framing as for non-BLAN mode */
dev->net->hard_header_len += 6;
dev->rx_urb_size = dev->net->hard_header_len
+ dev->net->mtu;
break;
}
next_desc:
len -= buf [0]; /* bLength */
buf += buf [0];
}
if (!desc || !detail) {
dev_dbg(&intf->dev, "missing cdc mdlm %s%sdescriptor\n",
desc ? "" : "func ",
detail ? "" : "detail ");
goto bad_desc;
}
/* There's probably a CDC Ethernet descriptor there, but we can't
* rely on the Ethernet address it provides since not all vendors
* bother to make it unique. Likewise there's no point in tracking
* of the CDC event notifications.
*/
return usbnet_get_endpoints(dev, intf);
bad_desc:
dev_info(&dev->udev->dev, "unsupported MDLM descriptors\n");
return -ENODEV;
}
static const struct driver_info bogus_mdlm_info = {
.description = "pseudo-MDLM (BLAN) device",
.flags = FLAG_POINTTOPOINT | FLAG_FRAMING_Z,
.check_connect = always_connected,
.tx_fixup = zaurus_tx_fixup,
.bind = blan_mdlm_bind,
};
static const struct usb_device_id products [] = {
#define ZAURUS_MASTER_INTERFACE \
.bInterfaceClass = USB_CLASS_COMM, \
.bInterfaceSubClass = USB_CDC_SUBCLASS_ETHERNET, \
.bInterfaceProtocol = USB_CDC_PROTO_NONE
/* SA-1100 based Sharp Zaurus ("collie"), or compatible. */
{
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x04DD,
.idProduct = 0x8004,
ZAURUS_MASTER_INTERFACE,
.driver_info = ZAURUS_STRONGARM_INFO,
},
/* PXA-2xx based models are also lying-about-cdc. If you add any
* more devices that claim to be CDC Ethernet, make sure they get
* added to the blacklist in cdc_ether too.
*
* NOTE: OpenZaurus versions with 2.6 kernels won't use these entries,
* unlike the older ones with 2.4 "embedix" kernels.
*/
{
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x04DD,
.idProduct = 0x8005, /* A-300 */
ZAURUS_MASTER_INTERFACE,
.driver_info = ZAURUS_PXA_INFO,
}, {
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x04DD,
.idProduct = 0x8006, /* B-500/SL-5600 */
ZAURUS_MASTER_INTERFACE,
.driver_info = ZAURUS_PXA_INFO,
}, {
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x04DD,
.idProduct = 0x8007, /* C-700 */
ZAURUS_MASTER_INTERFACE,
.driver_info = ZAURUS_PXA_INFO,
}, {
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x04DD,
.idProduct = 0x9031, /* C-750 C-760 */
ZAURUS_MASTER_INTERFACE,
.driver_info = ZAURUS_PXA_INFO,
}, {
/* C-750/C-760/C-860/SL-C3000 PDA in MDLM mode */
USB_DEVICE_AND_INTERFACE_INFO(0x04DD, 0x9031, USB_CLASS_COMM,
USB_CDC_SUBCLASS_MDLM, USB_CDC_PROTO_NONE),
.driver_info = (unsigned long) &bogus_mdlm_info,
}, {
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x04DD,
.idProduct = 0x9032, /* SL-6000 */
ZAURUS_MASTER_INTERFACE,
.driver_info = ZAURUS_PXA_INFO,
}, {
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x04DD,
/* reported with some C860 units */
.idProduct = 0x9050, /* C-860 */
ZAURUS_MASTER_INTERFACE,
.driver_info = ZAURUS_PXA_INFO,
},
{
/* Motorola Rokr E6 */
USB_DEVICE_AND_INTERFACE_INFO(0x22b8, 0x6027, USB_CLASS_COMM,
USB_CDC_SUBCLASS_MDLM, USB_CDC_PROTO_NONE),
.driver_info = (unsigned long) &bogus_mdlm_info,
}, {
/* Motorola MOTOMAGX phones */
USB_DEVICE_AND_INTERFACE_INFO(0x22b8, 0x6425, USB_CLASS_COMM,
USB_CDC_SUBCLASS_MDLM, USB_CDC_PROTO_NONE),
.driver_info = (unsigned long) &bogus_mdlm_info,
},
/* Olympus has some models with a Zaurus-compatible option.
* R-1000 uses a FreeScale i.MXL cpu (ARMv4T)
*/
{
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x07B4,
.idProduct = 0x0F02, /* R-1000 */
ZAURUS_MASTER_INTERFACE,
.driver_info = OLYMPUS_MXL_INFO,
},
/* Logitech Harmony 900 - uses the pseudo-MDLM (BLAN) driver */
{
USB_DEVICE_AND_INTERFACE_INFO(0x046d, 0xc11f, USB_CLASS_COMM,
USB_CDC_SUBCLASS_MDLM, USB_CDC_PROTO_NONE),
.driver_info = (unsigned long) &bogus_mdlm_info,
},
{ }, // END
};
MODULE_DEVICE_TABLE(usb, products);
static struct usb_driver zaurus_driver = {
.name = "zaurus",
.id_table = products,
.probe = usbnet_probe,
.disconnect = usbnet_disconnect,
.suspend = usbnet_suspend,
.resume = usbnet_resume,
.disable_hub_initiated_lpm = 1,
};
module_usb_driver(zaurus_driver);
MODULE_AUTHOR("Pavel Machek, David Brownell");
MODULE_DESCRIPTION("Sharp Zaurus PDA, and compatible products");
MODULE_LICENSE("GPL");
| gpl-2.0 |
goodhanrry/N915S_goodHanrry_kernel_lollipop | drivers/net/usb/zaurus.c | 2654 | 12101 | /*
* Copyright (C) 2002 Pavel Machek <pavel@ucw.cz>
* Copyright (C) 2002-2005 by David Brownell
*
* 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 DEBUG // error path messages, extra info
// #define VERBOSE // more; success messages
#include <linux/module.h>
#include <linux/init.h>
#include <linux/netdevice.h>
#include <linux/ethtool.h>
#include <linux/workqueue.h>
#include <linux/mii.h>
#include <linux/crc32.h>
#include <linux/usb.h>
#include <linux/usb/cdc.h>
#include <linux/usb/usbnet.h>
/*
* All known Zaurii lie about their standards conformance. At least
* the earliest SA-1100 models lie by saying they support CDC Ethernet.
* Some later models (especially PXA-25x and PXA-27x based ones) lie
* and say they support CDC MDLM (for access to cell phone modems).
*
* There are non-Zaurus products that use these same protocols too.
*
* The annoying thing is that at the same time Sharp was developing
* that annoying standards-breaking software, the Linux community had
* a simple "CDC Subset" working reliably on the same SA-1100 hardware.
* That is, the same functionality but not violating standards.
*
* The CDC Ethernet nonconformance points are troublesome to hosts
* with a true CDC Ethernet implementation:
* - Framing appends a CRC, which the spec says drivers "must not" do;
* - Transfers data in altsetting zero, instead of altsetting 1;
* - All these peripherals use the same ethernet address.
*
* The CDC MDLM nonconformance is less immediately troublesome, since all
* MDLM implementations are quasi-proprietary anyway.
*/
static struct sk_buff *
zaurus_tx_fixup(struct usbnet *dev, struct sk_buff *skb, gfp_t flags)
{
int padlen;
struct sk_buff *skb2;
padlen = 2;
if (!skb_cloned(skb)) {
int tailroom = skb_tailroom(skb);
if ((padlen + 4) <= tailroom)
goto done;
}
skb2 = skb_copy_expand(skb, 0, 4 + padlen, flags);
dev_kfree_skb_any(skb);
skb = skb2;
if (skb) {
u32 fcs;
done:
fcs = crc32_le(~0, skb->data, skb->len);
fcs = ~fcs;
*skb_put (skb, 1) = fcs & 0xff;
*skb_put (skb, 1) = (fcs>> 8) & 0xff;
*skb_put (skb, 1) = (fcs>>16) & 0xff;
*skb_put (skb, 1) = (fcs>>24) & 0xff;
}
return skb;
}
static int zaurus_bind(struct usbnet *dev, struct usb_interface *intf)
{
/* Belcarra's funky framing has other options; mostly
* TRAILERS (!) with 4 bytes CRC, and maybe 2 pad bytes.
*/
dev->net->hard_header_len += 6;
dev->rx_urb_size = dev->net->hard_header_len + dev->net->mtu;
return usbnet_generic_cdc_bind(dev, intf);
}
/* PDA style devices are always connected if present */
static int always_connected (struct usbnet *dev)
{
return 0;
}
static const struct driver_info zaurus_sl5x00_info = {
.description = "Sharp Zaurus SL-5x00",
.flags = FLAG_POINTTOPOINT | FLAG_FRAMING_Z,
.check_connect = always_connected,
.bind = zaurus_bind,
.unbind = usbnet_cdc_unbind,
.tx_fixup = zaurus_tx_fixup,
};
#define ZAURUS_STRONGARM_INFO ((unsigned long)&zaurus_sl5x00_info)
static const struct driver_info zaurus_pxa_info = {
.description = "Sharp Zaurus, PXA-2xx based",
.flags = FLAG_POINTTOPOINT | FLAG_FRAMING_Z,
.check_connect = always_connected,
.bind = zaurus_bind,
.unbind = usbnet_cdc_unbind,
.tx_fixup = zaurus_tx_fixup,
};
#define ZAURUS_PXA_INFO ((unsigned long)&zaurus_pxa_info)
static const struct driver_info olympus_mxl_info = {
.description = "Olympus R1000",
.flags = FLAG_POINTTOPOINT | FLAG_FRAMING_Z,
.check_connect = always_connected,
.bind = zaurus_bind,
.unbind = usbnet_cdc_unbind,
.tx_fixup = zaurus_tx_fixup,
};
#define OLYMPUS_MXL_INFO ((unsigned long)&olympus_mxl_info)
/* Some more recent products using Lineo/Belcarra code will wrongly claim
* CDC MDLM conformance. They aren't conformant: data endpoints live
* in the control interface, there's no data interface, and it's not used
* to talk to a cell phone radio. But at least we can detect these two
* pseudo-classes, rather than growing this product list with entries for
* each new nonconformant product (sigh).
*/
static const u8 safe_guid[16] = {
0x5d, 0x34, 0xcf, 0x66, 0x11, 0x18, 0x11, 0xd6,
0xa2, 0x1a, 0x00, 0x01, 0x02, 0xca, 0x9a, 0x7f,
};
static const u8 blan_guid[16] = {
0x74, 0xf0, 0x3d, 0xbd, 0x1e, 0xc1, 0x44, 0x70,
0xa3, 0x67, 0x71, 0x34, 0xc9, 0xf5, 0x54, 0x37,
};
static int blan_mdlm_bind(struct usbnet *dev, struct usb_interface *intf)
{
u8 *buf = intf->cur_altsetting->extra;
int len = intf->cur_altsetting->extralen;
struct usb_cdc_mdlm_desc *desc = NULL;
struct usb_cdc_mdlm_detail_desc *detail = NULL;
while (len > 3) {
if (buf [1] != USB_DT_CS_INTERFACE)
goto next_desc;
/* use bDescriptorSubType, and just verify that we get a
* "BLAN" (or "SAFE") descriptor.
*/
switch (buf [2]) {
case USB_CDC_MDLM_TYPE:
if (desc) {
dev_dbg(&intf->dev, "extra MDLM\n");
goto bad_desc;
}
desc = (void *) buf;
if (desc->bLength != sizeof *desc) {
dev_dbg(&intf->dev, "MDLM len %u\n",
desc->bLength);
goto bad_desc;
}
/* expect bcdVersion 1.0, ignore */
if (memcmp(&desc->bGUID, blan_guid, 16) &&
memcmp(&desc->bGUID, safe_guid, 16)) {
/* hey, this one might _really_ be MDLM! */
dev_dbg(&intf->dev, "MDLM guid\n");
goto bad_desc;
}
break;
case USB_CDC_MDLM_DETAIL_TYPE:
if (detail) {
dev_dbg(&intf->dev, "extra MDLM detail\n");
goto bad_desc;
}
detail = (void *) buf;
switch (detail->bGuidDescriptorType) {
case 0: /* "SAFE" */
if (detail->bLength != (sizeof *detail + 2))
goto bad_detail;
break;
case 1: /* "BLAN" */
if (detail->bLength != (sizeof *detail + 3))
goto bad_detail;
break;
default:
goto bad_detail;
}
/* assuming we either noticed BLAN already, or will
* find it soon, there are some data bytes here:
* - bmNetworkCapabilities (unused)
* - bmDataCapabilities (bits, see below)
* - bPad (ignored, for PADAFTER -- BLAN-only)
* bits are:
* - 0x01 -- Zaurus framing (add CRC)
* - 0x02 -- PADBEFORE (CRC includes some padding)
* - 0x04 -- PADAFTER (some padding after CRC)
* - 0x08 -- "fermat" packet mangling (for hw bugs)
* the PADBEFORE appears not to matter; we interop
* with devices that use it and those that don't.
*/
if ((detail->bDetailData[1] & ~0x02) != 0x01) {
/* bmDataCapabilities == 0 would be fine too,
* but framing is minidriver-coupled for now.
*/
bad_detail:
dev_dbg(&intf->dev,
"bad MDLM detail, %d %d %d\n",
detail->bLength,
detail->bDetailData[0],
detail->bDetailData[2]);
goto bad_desc;
}
/* same extra framing as for non-BLAN mode */
dev->net->hard_header_len += 6;
dev->rx_urb_size = dev->net->hard_header_len
+ dev->net->mtu;
break;
}
next_desc:
len -= buf [0]; /* bLength */
buf += buf [0];
}
if (!desc || !detail) {
dev_dbg(&intf->dev, "missing cdc mdlm %s%sdescriptor\n",
desc ? "" : "func ",
detail ? "" : "detail ");
goto bad_desc;
}
/* There's probably a CDC Ethernet descriptor there, but we can't
* rely on the Ethernet address it provides since not all vendors
* bother to make it unique. Likewise there's no point in tracking
* of the CDC event notifications.
*/
return usbnet_get_endpoints(dev, intf);
bad_desc:
dev_info(&dev->udev->dev, "unsupported MDLM descriptors\n");
return -ENODEV;
}
static const struct driver_info bogus_mdlm_info = {
.description = "pseudo-MDLM (BLAN) device",
.flags = FLAG_POINTTOPOINT | FLAG_FRAMING_Z,
.check_connect = always_connected,
.tx_fixup = zaurus_tx_fixup,
.bind = blan_mdlm_bind,
};
static const struct usb_device_id products [] = {
#define ZAURUS_MASTER_INTERFACE \
.bInterfaceClass = USB_CLASS_COMM, \
.bInterfaceSubClass = USB_CDC_SUBCLASS_ETHERNET, \
.bInterfaceProtocol = USB_CDC_PROTO_NONE
/* SA-1100 based Sharp Zaurus ("collie"), or compatible. */
{
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x04DD,
.idProduct = 0x8004,
ZAURUS_MASTER_INTERFACE,
.driver_info = ZAURUS_STRONGARM_INFO,
},
/* PXA-2xx based models are also lying-about-cdc. If you add any
* more devices that claim to be CDC Ethernet, make sure they get
* added to the blacklist in cdc_ether too.
*
* NOTE: OpenZaurus versions with 2.6 kernels won't use these entries,
* unlike the older ones with 2.4 "embedix" kernels.
*/
{
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x04DD,
.idProduct = 0x8005, /* A-300 */
ZAURUS_MASTER_INTERFACE,
.driver_info = ZAURUS_PXA_INFO,
}, {
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x04DD,
.idProduct = 0x8006, /* B-500/SL-5600 */
ZAURUS_MASTER_INTERFACE,
.driver_info = ZAURUS_PXA_INFO,
}, {
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x04DD,
.idProduct = 0x8007, /* C-700 */
ZAURUS_MASTER_INTERFACE,
.driver_info = ZAURUS_PXA_INFO,
}, {
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x04DD,
.idProduct = 0x9031, /* C-750 C-760 */
ZAURUS_MASTER_INTERFACE,
.driver_info = ZAURUS_PXA_INFO,
}, {
/* C-750/C-760/C-860/SL-C3000 PDA in MDLM mode */
USB_DEVICE_AND_INTERFACE_INFO(0x04DD, 0x9031, USB_CLASS_COMM,
USB_CDC_SUBCLASS_MDLM, USB_CDC_PROTO_NONE),
.driver_info = (unsigned long) &bogus_mdlm_info,
}, {
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x04DD,
.idProduct = 0x9032, /* SL-6000 */
ZAURUS_MASTER_INTERFACE,
.driver_info = ZAURUS_PXA_INFO,
}, {
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x04DD,
/* reported with some C860 units */
.idProduct = 0x9050, /* C-860 */
ZAURUS_MASTER_INTERFACE,
.driver_info = ZAURUS_PXA_INFO,
},
{
/* Motorola Rokr E6 */
USB_DEVICE_AND_INTERFACE_INFO(0x22b8, 0x6027, USB_CLASS_COMM,
USB_CDC_SUBCLASS_MDLM, USB_CDC_PROTO_NONE),
.driver_info = (unsigned long) &bogus_mdlm_info,
}, {
/* Motorola MOTOMAGX phones */
USB_DEVICE_AND_INTERFACE_INFO(0x22b8, 0x6425, USB_CLASS_COMM,
USB_CDC_SUBCLASS_MDLM, USB_CDC_PROTO_NONE),
.driver_info = (unsigned long) &bogus_mdlm_info,
},
/* Olympus has some models with a Zaurus-compatible option.
* R-1000 uses a FreeScale i.MXL cpu (ARMv4T)
*/
{
.match_flags = USB_DEVICE_ID_MATCH_INT_INFO
| USB_DEVICE_ID_MATCH_DEVICE,
.idVendor = 0x07B4,
.idProduct = 0x0F02, /* R-1000 */
ZAURUS_MASTER_INTERFACE,
.driver_info = OLYMPUS_MXL_INFO,
},
/* Logitech Harmony 900 - uses the pseudo-MDLM (BLAN) driver */
{
USB_DEVICE_AND_INTERFACE_INFO(0x046d, 0xc11f, USB_CLASS_COMM,
USB_CDC_SUBCLASS_MDLM, USB_CDC_PROTO_NONE),
.driver_info = (unsigned long) &bogus_mdlm_info,
},
{ }, // END
};
MODULE_DEVICE_TABLE(usb, products);
static struct usb_driver zaurus_driver = {
.name = "zaurus",
.id_table = products,
.probe = usbnet_probe,
.disconnect = usbnet_disconnect,
.suspend = usbnet_suspend,
.resume = usbnet_resume,
.disable_hub_initiated_lpm = 1,
};
module_usb_driver(zaurus_driver);
MODULE_AUTHOR("Pavel Machek, David Brownell");
MODULE_DESCRIPTION("Sharp Zaurus PDA, and compatible products");
MODULE_LICENSE("GPL");
| gpl-2.0 |
mfd10000/Itab1011 | drivers/net/ni5010.c | 3934 | 22862 | /* ni5010.c: A network driver for the MiCom-Interlan NI5010 ethercard.
*
* Copyright 1996,1997,2006 Jan-Pascal van Best and Andreas Mohr.
*
* This software may be used and distributed according to the terms
* of the GNU General Public License, incorporated herein by reference.
*
* The authors may be reached as:
* janpascal@vanbest.org andi@lisas.de
*
* Sources:
* Donald Becker's "skeleton.c"
* Crynwr ni5010 packet driver
*
* Changes:
* v0.0: First test version
* v0.1: First working version
* v0.2:
* v0.3->v0.90: Now demand setting io and irq when loading as module
* 970430 v0.91: modified for Linux 2.1.14
* v0.92: Implemented Andreas' (better) NI5010 probe
* 970503 v0.93: Fixed auto-irq failure on warm reboot (JB)
* 970623 v1.00: First kernel version (AM)
* 970814 v1.01: Added detection of onboard receive buffer size (AM)
* 060611 v1.02: slight cleanup: email addresses, driver modernization.
* Bugs:
* - not SMP-safe (no locking of I/O accesses)
* - Note that you have to patch ifconfig for the new /proc/net/dev
* format. It gives incorrect stats otherwise.
*
* To do:
* Fix all bugs :-)
* Move some stuff to chipset_init()
* Handle xmt errors other than collisions
* Complete merge with Andreas' driver
* Implement ring buffers (Is this useful? You can't squeeze
* too many packet in a 2k buffer!)
* Implement DMA (Again, is this useful? Some docs say DMA is
* slower than programmed I/O)
*
* Compile with:
* gcc -O2 -fomit-frame-pointer -m486 -D__KERNEL__ \
* -DMODULE -c ni5010.c
*
* Insert with e.g.:
* insmod ni5010.ko io=0x300 irq=5
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/bitops.h>
#include <asm/io.h>
#include <asm/dma.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include "ni5010.h"
static const char boardname[] = "NI5010";
static char version[] __initdata =
"ni5010.c: v1.02 20060611 Jan-Pascal van Best and Andreas Mohr\n";
/* bufsize_rcv == 0 means autoprobing */
static unsigned int bufsize_rcv;
#define JUMPERED_INTERRUPTS /* IRQ line jumpered on board */
#undef JUMPERED_DMA /* No DMA used */
#undef FULL_IODETECT /* Only detect in portlist */
#ifndef FULL_IODETECT
/* A zero-terminated list of I/O addresses to be probed. */
static unsigned int ports[] __initdata =
{ 0x300, 0x320, 0x340, 0x360, 0x380, 0x3a0, 0 };
#endif
/* Use 0 for production, 1 for verification, >2 for debug */
#ifndef NI5010_DEBUG
#define NI5010_DEBUG 0
#endif
/* Information that needs to be kept for each board. */
struct ni5010_local {
int o_pkt_size;
spinlock_t lock;
};
/* Index to functions, as function prototypes. */
static int ni5010_probe1(struct net_device *dev, int ioaddr);
static int ni5010_open(struct net_device *dev);
static int ni5010_send_packet(struct sk_buff *skb, struct net_device *dev);
static irqreturn_t ni5010_interrupt(int irq, void *dev_id);
static void ni5010_rx(struct net_device *dev);
static void ni5010_timeout(struct net_device *dev);
static int ni5010_close(struct net_device *dev);
static void ni5010_set_multicast_list(struct net_device *dev);
static void reset_receiver(struct net_device *dev);
static int process_xmt_interrupt(struct net_device *dev);
#define tx_done(dev) 1
static void hardware_send_packet(struct net_device *dev, char *buf, int length, int pad);
static void chipset_init(struct net_device *dev, int startp);
static void dump_packet(void *buf, int len);
static void ni5010_show_registers(struct net_device *dev);
static int io;
static int irq;
struct net_device * __init ni5010_probe(int unit)
{
struct net_device *dev = alloc_etherdev(sizeof(struct ni5010_local));
int *port;
int err = 0;
if (!dev)
return ERR_PTR(-ENOMEM);
if (unit >= 0) {
sprintf(dev->name, "eth%d", unit);
netdev_boot_setup_check(dev);
io = dev->base_addr;
irq = dev->irq;
}
PRINTK2((KERN_DEBUG "%s: Entering ni5010_probe\n", dev->name));
if (io > 0x1ff) { /* Check a single specified location. */
err = ni5010_probe1(dev, io);
} else if (io != 0) { /* Don't probe at all. */
err = -ENXIO;
} else {
#ifdef FULL_IODETECT
for (io=0x200; io<0x400 && ni5010_probe1(dev, io) ; io+=0x20)
;
if (io == 0x400)
err = -ENODEV;
#else
for (port = ports; *port && ni5010_probe1(dev, *port); port++)
;
if (!*port)
err = -ENODEV;
#endif /* FULL_IODETECT */
}
if (err)
goto out;
err = register_netdev(dev);
if (err)
goto out1;
return dev;
out1:
release_region(dev->base_addr, NI5010_IO_EXTENT);
out:
free_netdev(dev);
return ERR_PTR(err);
}
static inline int rd_port(int ioaddr)
{
inb(IE_RBUF);
return inb(IE_SAPROM);
}
static void __init trigger_irq(int ioaddr)
{
outb(0x00, EDLC_RESET); /* Clear EDLC hold RESET state */
outb(0x00, IE_RESET); /* Board reset */
outb(0x00, EDLC_XMASK); /* Disable all Xmt interrupts */
outb(0x00, EDLC_RMASK); /* Disable all Rcv interrupt */
outb(0xff, EDLC_XCLR); /* Clear all pending Xmt interrupts */
outb(0xff, EDLC_RCLR); /* Clear all pending Rcv interrupts */
/*
* Transmit packet mode: Ignore parity, Power xcvr,
* Enable loopback
*/
outb(XMD_IG_PAR | XMD_T_MODE | XMD_LBC, EDLC_XMODE);
outb(RMD_BROADCAST, EDLC_RMODE); /* Receive normal&broadcast */
outb(XM_ALL, EDLC_XMASK); /* Enable all Xmt interrupts */
udelay(50); /* FIXME: Necessary? */
outb(MM_EN_XMT|MM_MUX, IE_MMODE); /* Start transmission */
}
static const struct net_device_ops ni5010_netdev_ops = {
.ndo_open = ni5010_open,
.ndo_stop = ni5010_close,
.ndo_start_xmit = ni5010_send_packet,
.ndo_set_multicast_list = ni5010_set_multicast_list,
.ndo_tx_timeout = ni5010_timeout,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = eth_mac_addr,
.ndo_change_mtu = eth_change_mtu,
};
/*
* This is the real probe routine. Linux has a history of friendly device
* probes on the ISA bus. A good device probes avoids doing writes, and
* verifies that the correct device exists and functions.
*/
static int __init ni5010_probe1(struct net_device *dev, int ioaddr)
{
static unsigned version_printed;
struct ni5010_local *lp;
int i;
unsigned int data = 0;
int boguscount = 40;
int err = -ENODEV;
dev->base_addr = ioaddr;
dev->irq = irq;
if (!request_region(ioaddr, NI5010_IO_EXTENT, boardname))
return -EBUSY;
/*
* This is no "official" probe method, I've rather tested which
* probe works best with my seven NI5010 cards
* (they have very different serial numbers)
* Suggestions or failure reports are very, very welcome !
* But I think it is a relatively good probe method
* since it doesn't use any "outb"
* It should be nearly 100% reliable !
* well-known WARNING: this probe method (like many others)
* will hang the system if a NE2000 card region is probed !
*
* - Andreas
*/
PRINTK2((KERN_DEBUG "%s: entering ni5010_probe1(%#3x)\n",
dev->name, ioaddr));
if (inb(ioaddr+0) == 0xff)
goto out;
while ( (rd_port(ioaddr) & rd_port(ioaddr) & rd_port(ioaddr) &
rd_port(ioaddr) & rd_port(ioaddr) & rd_port(ioaddr)) != 0xff)
{
if (boguscount-- == 0)
goto out;
}
PRINTK2((KERN_DEBUG "%s: I/O #1 passed!\n", dev->name));
for (i=0; i<32; i++)
if ( (data = rd_port(ioaddr)) != 0xff) break;
if (data==0xff)
goto out;
PRINTK2((KERN_DEBUG "%s: I/O #2 passed!\n", dev->name));
if ((data != SA_ADDR0) || (rd_port(ioaddr) != SA_ADDR1) ||
(rd_port(ioaddr) != SA_ADDR2))
goto out;
for (i=0; i<4; i++)
rd_port(ioaddr);
if ( (rd_port(ioaddr) != NI5010_MAGICVAL1) ||
(rd_port(ioaddr) != NI5010_MAGICVAL2) )
goto out;
PRINTK2((KERN_DEBUG "%s: I/O #3 passed!\n", dev->name));
if (NI5010_DEBUG && version_printed++ == 0)
printk(KERN_INFO "%s", version);
printk("NI5010 ethercard probe at 0x%x: ", ioaddr);
dev->base_addr = ioaddr;
for (i=0; i<6; i++) {
outw(i, IE_GP);
dev->dev_addr[i] = inb(IE_SAPROM);
}
printk("%pM ", dev->dev_addr);
PRINTK2((KERN_DEBUG "%s: I/O #4 passed!\n", dev->name));
#ifdef JUMPERED_INTERRUPTS
if (dev->irq == 0xff)
;
else if (dev->irq < 2) {
unsigned long irq_mask;
PRINTK2((KERN_DEBUG "%s: I/O #5 passed!\n", dev->name));
irq_mask = probe_irq_on();
trigger_irq(ioaddr);
mdelay(20);
dev->irq = probe_irq_off(irq_mask);
PRINTK2((KERN_DEBUG "%s: I/O #6 passed!\n", dev->name));
if (dev->irq == 0) {
err = -EAGAIN;
printk(KERN_WARNING "%s: no IRQ found!\n", dev->name);
goto out;
}
PRINTK2((KERN_DEBUG "%s: I/O #7 passed!\n", dev->name));
} else if (dev->irq == 2) {
dev->irq = 9;
}
#endif /* JUMPERED_INTERRUPTS */
PRINTK2((KERN_DEBUG "%s: I/O #9 passed!\n", dev->name));
/* DMA is not supported (yet?), so no use detecting it */
lp = netdev_priv(dev);
spin_lock_init(&lp->lock);
PRINTK2((KERN_DEBUG "%s: I/O #10 passed!\n", dev->name));
/* get the size of the onboard receive buffer
* higher addresses than bufsize are wrapped into real buffer
* i.e. data for offs. 0x801 is written to 0x1 with a 2K onboard buffer
*/
if (!bufsize_rcv) {
outb(1, IE_MMODE); /* Put Rcv buffer on system bus */
outw(0, IE_GP); /* Point GP at start of packet */
outb(0, IE_RBUF); /* set buffer byte 0 to 0 */
for (i = 1; i < 0xff; i++) {
outw(i << 8, IE_GP); /* Point GP at packet size to be tested */
outb(i, IE_RBUF);
outw(0x0, IE_GP); /* Point GP at start of packet */
data = inb(IE_RBUF);
if (data == i) break;
}
bufsize_rcv = i << 8;
outw(0, IE_GP); /* Point GP at start of packet */
outb(0, IE_RBUF); /* set buffer byte 0 to 0 again */
}
printk("-> bufsize rcv/xmt=%d/%d\n", bufsize_rcv, NI5010_BUFSIZE);
dev->netdev_ops = &ni5010_netdev_ops;
dev->watchdog_timeo = HZ/20;
dev->flags &= ~IFF_MULTICAST; /* Multicast doesn't work */
/* Shut up the ni5010 */
outb(0, EDLC_RMASK); /* Mask all receive interrupts */
outb(0, EDLC_XMASK); /* Mask all xmit interrupts */
outb(0xff, EDLC_RCLR); /* Kill all pending rcv interrupts */
outb(0xff, EDLC_XCLR); /* Kill all pending xmt interrupts */
printk(KERN_INFO "%s: NI5010 found at 0x%x, using IRQ %d", dev->name, ioaddr, dev->irq);
if (dev->dma)
printk(" & DMA %d", dev->dma);
printk(".\n");
return 0;
out:
release_region(dev->base_addr, NI5010_IO_EXTENT);
return err;
}
/*
* Open/initialize the board. This is called (in the current kernel)
* sometime after booting when the 'ifconfig' program is run.
*
* This routine should set everything up anew at each open, even
* registers that "should" only need to be set once at boot, so that
* there is a non-reboot way to recover if something goes wrong.
*/
static int ni5010_open(struct net_device *dev)
{
int ioaddr = dev->base_addr;
int i;
PRINTK2((KERN_DEBUG "%s: entering ni5010_open()\n", dev->name));
if (request_irq(dev->irq, ni5010_interrupt, 0, boardname, dev)) {
printk(KERN_WARNING "%s: Cannot get irq %#2x\n", dev->name, dev->irq);
return -EAGAIN;
}
PRINTK3((KERN_DEBUG "%s: passed open() #1\n", dev->name));
/*
* Always allocate the DMA channel after the IRQ,
* and clean up on failure.
*/
#ifdef JUMPERED_DMA
if (request_dma(dev->dma, cardname)) {
printk(KERN_WARNING "%s: Cannot get dma %#2x\n", dev->name, dev->dma);
free_irq(dev->irq, NULL);
return -EAGAIN;
}
#endif /* JUMPERED_DMA */
PRINTK3((KERN_DEBUG "%s: passed open() #2\n", dev->name));
/* Reset the hardware here. Don't forget to set the station address. */
outb(RS_RESET, EDLC_RESET); /* Hold up EDLC_RESET while configing board */
outb(0, IE_RESET); /* Hardware reset of ni5010 board */
outb(XMD_LBC, EDLC_XMODE); /* Only loopback xmits */
PRINTK3((KERN_DEBUG "%s: passed open() #3\n", dev->name));
/* Set the station address */
for(i = 0;i < 6; i++) {
outb(dev->dev_addr[i], EDLC_ADDR + i);
}
PRINTK3((KERN_DEBUG "%s: Initialising ni5010\n", dev->name));
outb(0, EDLC_XMASK); /* No xmit interrupts for now */
outb(XMD_IG_PAR | XMD_T_MODE | XMD_LBC, EDLC_XMODE);
/* Normal packet xmit mode */
outb(0xff, EDLC_XCLR); /* Clear all pending xmit interrupts */
outb(RMD_BROADCAST, EDLC_RMODE);
/* Receive broadcast and normal packets */
reset_receiver(dev); /* Ready ni5010 for receiving packets */
outb(0, EDLC_RESET); /* Un-reset the ni5010 */
netif_start_queue(dev);
if (NI5010_DEBUG) ni5010_show_registers(dev);
PRINTK((KERN_DEBUG "%s: open successful\n", dev->name));
return 0;
}
static void reset_receiver(struct net_device *dev)
{
int ioaddr = dev->base_addr;
PRINTK3((KERN_DEBUG "%s: resetting receiver\n", dev->name));
outw(0, IE_GP); /* Receive packet at start of buffer */
outb(0xff, EDLC_RCLR); /* Clear all pending rcv interrupts */
outb(0, IE_MMODE); /* Put EDLC to rcv buffer */
outb(MM_EN_RCV, IE_MMODE); /* Enable rcv */
outb(0xff, EDLC_RMASK); /* Enable all rcv interrupts */
}
static void ni5010_timeout(struct net_device *dev)
{
printk(KERN_WARNING "%s: transmit timed out, %s?\n", dev->name,
tx_done(dev) ? "IRQ conflict" : "network cable problem");
/* Try to restart the adaptor. */
/* FIXME: Give it a real kick here */
chipset_init(dev, 1);
dev->trans_start = jiffies; /* prevent tx timeout */
netif_wake_queue(dev);
}
static int ni5010_send_packet(struct sk_buff *skb, struct net_device *dev)
{
int length = ETH_ZLEN < skb->len ? skb->len : ETH_ZLEN;
PRINTK2((KERN_DEBUG "%s: entering ni5010_send_packet\n", dev->name));
/*
* Block sending
*/
netif_stop_queue(dev);
hardware_send_packet(dev, (unsigned char *)skb->data, skb->len, length-skb->len);
dev_kfree_skb (skb);
return NETDEV_TX_OK;
}
/*
* The typical workload of the driver:
* Handle the network interface interrupts.
*/
static irqreturn_t ni5010_interrupt(int irq, void *dev_id)
{
struct net_device *dev = dev_id;
struct ni5010_local *lp;
int ioaddr, status;
int xmit_was_error = 0;
PRINTK2((KERN_DEBUG "%s: entering ni5010_interrupt\n", dev->name));
ioaddr = dev->base_addr;
lp = netdev_priv(dev);
spin_lock(&lp->lock);
status = inb(IE_ISTAT);
PRINTK3((KERN_DEBUG "%s: IE_ISTAT = %#02x\n", dev->name, status));
if ((status & IS_R_INT) == 0) ni5010_rx(dev);
if ((status & IS_X_INT) == 0) {
xmit_was_error = process_xmt_interrupt(dev);
}
if ((status & IS_DMA_INT) == 0) {
PRINTK((KERN_DEBUG "%s: DMA complete (?)\n", dev->name));
outb(0, IE_DMA_RST); /* Reset DMA int */
}
if (!xmit_was_error)
reset_receiver(dev);
spin_unlock(&lp->lock);
return IRQ_HANDLED;
}
static void dump_packet(void *buf, int len)
{
int i;
printk(KERN_DEBUG "Packet length = %#4x\n", len);
for (i = 0; i < len; i++){
if (i % 16 == 0) printk(KERN_DEBUG "%#4.4x", i);
if (i % 2 == 0) printk(" ");
printk("%2.2x", ((unsigned char *)buf)[i]);
if (i % 16 == 15) printk("\n");
}
printk("\n");
}
/* We have a good packet, get it out of the buffer. */
static void ni5010_rx(struct net_device *dev)
{
int ioaddr = dev->base_addr;
unsigned char rcv_stat;
struct sk_buff *skb;
int i_pkt_size;
PRINTK2((KERN_DEBUG "%s: entering ni5010_rx()\n", dev->name));
rcv_stat = inb(EDLC_RSTAT);
PRINTK3((KERN_DEBUG "%s: EDLC_RSTAT = %#2x\n", dev->name, rcv_stat));
if ( (rcv_stat & RS_VALID_BITS) != RS_PKT_OK) {
PRINTK((KERN_INFO "%s: receive error.\n", dev->name));
dev->stats.rx_errors++;
if (rcv_stat & RS_RUNT) dev->stats.rx_length_errors++;
if (rcv_stat & RS_ALIGN) dev->stats.rx_frame_errors++;
if (rcv_stat & RS_CRC_ERR) dev->stats.rx_crc_errors++;
if (rcv_stat & RS_OFLW) dev->stats.rx_fifo_errors++;
outb(0xff, EDLC_RCLR); /* Clear the interrupt */
return;
}
outb(0xff, EDLC_RCLR); /* Clear the interrupt */
i_pkt_size = inw(IE_RCNT);
if (i_pkt_size > ETH_FRAME_LEN || i_pkt_size < 10 ) {
PRINTK((KERN_DEBUG "%s: Packet size error, packet size = %#4.4x\n",
dev->name, i_pkt_size));
dev->stats.rx_errors++;
dev->stats.rx_length_errors++;
return;
}
/* Malloc up new buffer. */
skb = dev_alloc_skb(i_pkt_size + 3);
if (skb == NULL) {
printk(KERN_WARNING "%s: Memory squeeze, dropping packet.\n", dev->name);
dev->stats.rx_dropped++;
return;
}
skb_reserve(skb, 2);
/* Read packet into buffer */
outb(MM_MUX, IE_MMODE); /* Rcv buffer to system bus */
outw(0, IE_GP); /* Seek to beginning of packet */
insb(IE_RBUF, skb_put(skb, i_pkt_size), i_pkt_size);
if (NI5010_DEBUG >= 4)
dump_packet(skb->data, skb->len);
skb->protocol = eth_type_trans(skb,dev);
netif_rx(skb);
dev->stats.rx_packets++;
dev->stats.rx_bytes += i_pkt_size;
PRINTK2((KERN_DEBUG "%s: Received packet, size=%#4.4x\n",
dev->name, i_pkt_size));
}
static int process_xmt_interrupt(struct net_device *dev)
{
struct ni5010_local *lp = netdev_priv(dev);
int ioaddr = dev->base_addr;
int xmit_stat;
PRINTK2((KERN_DEBUG "%s: entering process_xmt_interrupt\n", dev->name));
xmit_stat = inb(EDLC_XSTAT);
PRINTK3((KERN_DEBUG "%s: EDLC_XSTAT = %2.2x\n", dev->name, xmit_stat));
outb(0, EDLC_XMASK); /* Disable xmit IRQ's */
outb(0xff, EDLC_XCLR); /* Clear all pending xmit IRQ's */
if (xmit_stat & XS_COLL){
PRINTK((KERN_DEBUG "%s: collision detected, retransmitting\n",
dev->name));
outw(NI5010_BUFSIZE - lp->o_pkt_size, IE_GP);
/* outb(0, IE_MMODE); */ /* xmt buf on sysbus FIXME: needed ? */
outb(MM_EN_XMT | MM_MUX, IE_MMODE);
outb(XM_ALL, EDLC_XMASK); /* Enable xmt IRQ's */
dev->stats.collisions++;
return 1;
}
/* FIXME: handle other xmt error conditions */
dev->stats.tx_packets++;
dev->stats.tx_bytes += lp->o_pkt_size;
netif_wake_queue(dev);
PRINTK2((KERN_DEBUG "%s: sent packet, size=%#4.4x\n",
dev->name, lp->o_pkt_size));
return 0;
}
/* The inverse routine to ni5010_open(). */
static int ni5010_close(struct net_device *dev)
{
int ioaddr = dev->base_addr;
PRINTK2((KERN_DEBUG "%s: entering ni5010_close\n", dev->name));
#ifdef JUMPERED_INTERRUPTS
free_irq(dev->irq, NULL);
#endif
/* Put card in held-RESET state */
outb(0, IE_MMODE);
outb(RS_RESET, EDLC_RESET);
netif_stop_queue(dev);
PRINTK((KERN_DEBUG "%s: %s closed down\n", dev->name, boardname));
return 0;
}
/* Set or clear the multicast filter for this adaptor.
num_addrs == -1 Promiscuous mode, receive all packets
num_addrs == 0 Normal mode, clear multicast list
num_addrs > 0 Multicast mode, receive normal and MC packets, and do
best-effort filtering.
*/
static void ni5010_set_multicast_list(struct net_device *dev)
{
short ioaddr = dev->base_addr;
PRINTK2((KERN_DEBUG "%s: entering set_multicast_list\n", dev->name));
if (dev->flags & IFF_PROMISC || dev->flags & IFF_ALLMULTI ||
!netdev_mc_empty(dev)) {
outb(RMD_PROMISC, EDLC_RMODE); /* Enable promiscuous mode */
PRINTK((KERN_DEBUG "%s: Entering promiscuous mode\n", dev->name));
} else {
PRINTK((KERN_DEBUG "%s: Entering broadcast mode\n", dev->name));
outb(RMD_BROADCAST, EDLC_RMODE); /* Disable promiscuous mode, use normal mode */
}
}
static void hardware_send_packet(struct net_device *dev, char *buf, int length, int pad)
{
struct ni5010_local *lp = netdev_priv(dev);
int ioaddr = dev->base_addr;
unsigned long flags;
unsigned int buf_offs;
PRINTK2((KERN_DEBUG "%s: entering hardware_send_packet\n", dev->name));
if (length > ETH_FRAME_LEN) {
PRINTK((KERN_WARNING "%s: packet too large, not possible\n",
dev->name));
return;
}
if (NI5010_DEBUG) ni5010_show_registers(dev);
if (inb(IE_ISTAT) & IS_EN_XMT) {
PRINTK((KERN_WARNING "%s: sending packet while already transmitting, not possible\n",
dev->name));
return;
}
if (NI5010_DEBUG > 3) dump_packet(buf, length);
buf_offs = NI5010_BUFSIZE - length - pad;
spin_lock_irqsave(&lp->lock, flags);
lp->o_pkt_size = length + pad;
outb(0, EDLC_RMASK); /* Mask all receive interrupts */
outb(0, IE_MMODE); /* Put Xmit buffer on system bus */
outb(0xff, EDLC_RCLR); /* Clear out pending rcv interrupts */
outw(buf_offs, IE_GP); /* Point GP at start of packet */
outsb(IE_XBUF, buf, length); /* Put data in buffer */
while(pad--)
outb(0, IE_XBUF);
outw(buf_offs, IE_GP); /* Rewrite where packet starts */
/* should work without that outb() (Crynwr used it) */
/*outb(MM_MUX, IE_MMODE);*/ /* Xmt buffer to EDLC bus */
outb(MM_EN_XMT | MM_MUX, IE_MMODE); /* Begin transmission */
outb(XM_ALL, EDLC_XMASK); /* Cause interrupt after completion or fail */
spin_unlock_irqrestore(&lp->lock, flags);
netif_wake_queue(dev);
if (NI5010_DEBUG) ni5010_show_registers(dev);
}
static void chipset_init(struct net_device *dev, int startp)
{
/* FIXME: Move some stuff here */
PRINTK3((KERN_DEBUG "%s: doing NOTHING in chipset_init\n", dev->name));
}
static void ni5010_show_registers(struct net_device *dev)
{
int ioaddr = dev->base_addr;
PRINTK3((KERN_DEBUG "%s: XSTAT %#2.2x\n", dev->name, inb(EDLC_XSTAT)));
PRINTK3((KERN_DEBUG "%s: XMASK %#2.2x\n", dev->name, inb(EDLC_XMASK)));
PRINTK3((KERN_DEBUG "%s: RSTAT %#2.2x\n", dev->name, inb(EDLC_RSTAT)));
PRINTK3((KERN_DEBUG "%s: RMASK %#2.2x\n", dev->name, inb(EDLC_RMASK)));
PRINTK3((KERN_DEBUG "%s: RMODE %#2.2x\n", dev->name, inb(EDLC_RMODE)));
PRINTK3((KERN_DEBUG "%s: XMODE %#2.2x\n", dev->name, inb(EDLC_XMODE)));
PRINTK3((KERN_DEBUG "%s: ISTAT %#2.2x\n", dev->name, inb(IE_ISTAT)));
}
#ifdef MODULE
static struct net_device *dev_ni5010;
module_param(io, int, 0);
module_param(irq, int, 0);
MODULE_PARM_DESC(io, "ni5010 I/O base address");
MODULE_PARM_DESC(irq, "ni5010 IRQ number");
static int __init ni5010_init_module(void)
{
PRINTK2((KERN_DEBUG "%s: entering init_module\n", boardname));
/*
if(io <= 0 || irq == 0){
printk(KERN_WARNING "%s: Autoprobing not allowed for modules.\n", boardname);
printk(KERN_WARNING "%s: Set symbols 'io' and 'irq'\n", boardname);
return -EINVAL;
}
*/
if (io <= 0){
printk(KERN_WARNING "%s: Autoprobing for modules is hazardous, trying anyway..\n", boardname);
}
PRINTK2((KERN_DEBUG "%s: init_module irq=%#2x, io=%#3x\n", boardname, irq, io));
dev_ni5010 = ni5010_probe(-1);
if (IS_ERR(dev_ni5010))
return PTR_ERR(dev_ni5010);
return 0;
}
static void __exit ni5010_cleanup_module(void)
{
PRINTK2((KERN_DEBUG "%s: entering cleanup_module\n", boardname));
unregister_netdev(dev_ni5010);
release_region(dev_ni5010->base_addr, NI5010_IO_EXTENT);
free_netdev(dev_ni5010);
}
module_init(ni5010_init_module);
module_exit(ni5010_cleanup_module);
#endif /* MODULE */
MODULE_LICENSE("GPL");
| gpl-2.0 |
Digilent/linux-Digilent-Dev | arch/microblaze/kernel/traps.c | 4190 | 1918 | /*
* Copyright (C) 2007-2009 Michal Simek <monstr@monstr.eu>
* Copyright (C) 2007-2009 PetaLogix
* Copyright (C) 2006 Atmark Techno, Inc.
*
* 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/export.h>
#include <linux/kernel.h>
#include <linux/kallsyms.h>
#include <linux/sched.h>
#include <linux/debug_locks.h>
#include <asm/exceptions.h>
#include <asm/unwind.h>
void trap_init(void)
{
__enable_hw_exceptions();
}
static unsigned long kstack_depth_to_print; /* 0 == entire stack */
static int __init kstack_setup(char *s)
{
return !kstrtoul(s, 0, &kstack_depth_to_print);
}
__setup("kstack=", kstack_setup);
void show_stack(struct task_struct *task, unsigned long *sp)
{
unsigned long words_to_show;
u32 fp = (u32) sp;
if (fp == 0) {
if (task) {
fp = ((struct thread_info *)
(task->stack))->cpu_context.r1;
} else {
/* Pick up caller of dump_stack() */
fp = (u32)&sp - 8;
}
}
words_to_show = (THREAD_SIZE - (fp & (THREAD_SIZE - 1))) >> 2;
if (kstack_depth_to_print && (words_to_show > kstack_depth_to_print))
words_to_show = kstack_depth_to_print;
pr_info("Kernel Stack:\n");
/*
* Make the first line an 'odd' size if necessary to get
* remaining lines to start at an address multiple of 0x10
*/
if (fp & 0xF) {
unsigned long line1_words = (0x10 - (fp & 0xF)) >> 2;
if (line1_words < words_to_show) {
print_hex_dump(KERN_INFO, "", DUMP_PREFIX_ADDRESS, 32,
4, (void *)fp, line1_words << 2, 0);
fp += line1_words << 2;
words_to_show -= line1_words;
}
}
print_hex_dump(KERN_INFO, "", DUMP_PREFIX_ADDRESS, 32, 4, (void *)fp,
words_to_show << 2, 0);
pr_info("\n\nCall Trace:\n");
microblaze_unwind(task, NULL);
pr_info("\n");
if (!task)
task = current;
debug_show_held_locks(task);
}
| gpl-2.0 |
XxXPachaXxX/kernel_msm_3.0 | arch/um/os-Linux/umid.c | 4702 | 8252 | /*
* Copyright (C) 2002 - 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com)
* Licensed under the GPL
*/
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include "init.h"
#include "kern_constants.h"
#include "os.h"
#include "user.h"
#define UML_DIR "~/.uml/"
#define UMID_LEN 64
/* Changed by set_umid, which is run early in boot */
static char umid[UMID_LEN] = { 0 };
/* Changed by set_uml_dir and make_uml_dir, which are run early in boot */
static char *uml_dir = UML_DIR;
static int __init make_uml_dir(void)
{
char dir[512] = { '\0' };
int len, err;
if (*uml_dir == '~') {
char *home = getenv("HOME");
err = -ENOENT;
if (home == NULL) {
printk(UM_KERN_ERR "make_uml_dir : no value in "
"environment for $HOME\n");
goto err;
}
strlcpy(dir, home, sizeof(dir));
uml_dir++;
}
strlcat(dir, uml_dir, sizeof(dir));
len = strlen(dir);
if (len > 0 && dir[len - 1] != '/')
strlcat(dir, "/", sizeof(dir));
err = -ENOMEM;
uml_dir = malloc(strlen(dir) + 1);
if (uml_dir == NULL) {
printf("make_uml_dir : malloc failed, errno = %d\n", errno);
goto err;
}
strcpy(uml_dir, dir);
if ((mkdir(uml_dir, 0777) < 0) && (errno != EEXIST)) {
printf("Failed to mkdir '%s': %s\n", uml_dir, strerror(errno));
err = -errno;
goto err_free;
}
return 0;
err_free:
free(uml_dir);
err:
uml_dir = NULL;
return err;
}
/*
* Unlinks the files contained in @dir and then removes @dir.
* Doesn't handle directory trees, so it's not like rm -rf, but almost such. We
* ignore ENOENT errors for anything (they happen, strangely enough - possibly
* due to races between multiple dying UML threads).
*/
static int remove_files_and_dir(char *dir)
{
DIR *directory;
struct dirent *ent;
int len;
char file[256];
int ret;
directory = opendir(dir);
if (directory == NULL) {
if (errno != ENOENT)
return -errno;
else
return 0;
}
while ((ent = readdir(directory)) != NULL) {
if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, ".."))
continue;
len = strlen(dir) + sizeof("/") + strlen(ent->d_name) + 1;
if (len > sizeof(file)) {
ret = -E2BIG;
goto out;
}
sprintf(file, "%s/%s", dir, ent->d_name);
if (unlink(file) < 0 && errno != ENOENT) {
ret = -errno;
goto out;
}
}
if (rmdir(dir) < 0 && errno != ENOENT) {
ret = -errno;
goto out;
}
ret = 0;
out:
closedir(directory);
return ret;
}
/*
* This says that there isn't already a user of the specified directory even if
* there are errors during the checking. This is because if these errors
* happen, the directory is unusable by the pre-existing UML, so we might as
* well take it over. This could happen either by
* the existing UML somehow corrupting its umid directory
* something other than UML sticking stuff in the directory
* this boot racing with a shutdown of the other UML
* In any of these cases, the directory isn't useful for anything else.
*
* Boolean return: 1 if in use, 0 otherwise.
*/
static inline int is_umdir_used(char *dir)
{
char file[strlen(uml_dir) + UMID_LEN + sizeof("/pid\0")];
char pid[sizeof("nnnnn\0")], *end;
int dead, fd, p, n, err;
n = snprintf(file, sizeof(file), "%s/pid", dir);
if (n >= sizeof(file)) {
printk(UM_KERN_ERR "is_umdir_used - pid filename too long\n");
err = -E2BIG;
goto out;
}
dead = 0;
fd = open(file, O_RDONLY);
if (fd < 0) {
fd = -errno;
if (fd != -ENOENT) {
printk(UM_KERN_ERR "is_umdir_used : couldn't open pid "
"file '%s', err = %d\n", file, -fd);
}
goto out;
}
err = 0;
n = read(fd, pid, sizeof(pid));
if (n < 0) {
printk(UM_KERN_ERR "is_umdir_used : couldn't read pid file "
"'%s', err = %d\n", file, errno);
goto out_close;
} else if (n == 0) {
printk(UM_KERN_ERR "is_umdir_used : couldn't read pid file "
"'%s', 0-byte read\n", file);
goto out_close;
}
p = strtoul(pid, &end, 0);
if (end == pid) {
printk(UM_KERN_ERR "is_umdir_used : couldn't parse pid file "
"'%s', errno = %d\n", file, errno);
goto out_close;
}
if ((kill(p, 0) == 0) || (errno != ESRCH)) {
printk(UM_KERN_ERR "umid \"%s\" is already in use by pid %d\n",
umid, p);
return 1;
}
out_close:
close(fd);
out:
return 0;
}
/*
* Try to remove the directory @dir unless it's in use.
* Precondition: @dir exists.
* Returns 0 for success, < 0 for failure in removal or if the directory is in
* use.
*/
static int umdir_take_if_dead(char *dir)
{
int ret;
if (is_umdir_used(dir))
return -EEXIST;
ret = remove_files_and_dir(dir);
if (ret) {
printk(UM_KERN_ERR "is_umdir_used - remove_files_and_dir "
"failed with err = %d\n", ret);
}
return ret;
}
static void __init create_pid_file(void)
{
char file[strlen(uml_dir) + UMID_LEN + sizeof("/pid\0")];
char pid[sizeof("nnnnn\0")];
int fd, n;
if (umid_file_name("pid", file, sizeof(file)))
return;
fd = open(file, O_RDWR | O_CREAT | O_EXCL, 0644);
if (fd < 0) {
printk(UM_KERN_ERR "Open of machine pid file \"%s\" failed: "
"%s\n", file, strerror(errno));
return;
}
snprintf(pid, sizeof(pid), "%d\n", getpid());
n = write(fd, pid, strlen(pid));
if (n != strlen(pid))
printk(UM_KERN_ERR "Write of pid file failed - err = %d\n",
errno);
close(fd);
}
int __init set_umid(char *name)
{
if (strlen(name) > UMID_LEN - 1)
return -E2BIG;
strlcpy(umid, name, sizeof(umid));
return 0;
}
/* Changed in make_umid, which is called during early boot */
static int umid_setup = 0;
static int __init make_umid(void)
{
int fd, err;
char tmp[256];
if (umid_setup)
return 0;
make_uml_dir();
if (*umid == '\0') {
strlcpy(tmp, uml_dir, sizeof(tmp));
strlcat(tmp, "XXXXXX", sizeof(tmp));
fd = mkstemp(tmp);
if (fd < 0) {
printk(UM_KERN_ERR "make_umid - mkstemp(%s) failed: "
"%s\n", tmp, strerror(errno));
err = -errno;
goto err;
}
close(fd);
set_umid(&tmp[strlen(uml_dir)]);
/*
* There's a nice tiny little race between this unlink and
* the mkdir below. It'd be nice if there were a mkstemp
* for directories.
*/
if (unlink(tmp)) {
err = -errno;
goto err;
}
}
snprintf(tmp, sizeof(tmp), "%s%s", uml_dir, umid);
err = mkdir(tmp, 0777);
if (err < 0) {
err = -errno;
if (err != -EEXIST)
goto err;
if (umdir_take_if_dead(tmp) < 0)
goto err;
err = mkdir(tmp, 0777);
}
if (err) {
err = -errno;
printk(UM_KERN_ERR "Failed to create '%s' - err = %d\n", umid,
errno);
goto err;
}
umid_setup = 1;
create_pid_file();
err = 0;
err:
return err;
}
static int __init make_umid_init(void)
{
if (!make_umid())
return 0;
/*
* If initializing with the given umid failed, then try again with
* a random one.
*/
printk(UM_KERN_ERR "Failed to initialize umid \"%s\", trying with a "
"random umid\n", umid);
*umid = '\0';
make_umid();
return 0;
}
__initcall(make_umid_init);
int __init umid_file_name(char *name, char *buf, int len)
{
int n, err;
err = make_umid();
if (err)
return err;
n = snprintf(buf, len, "%s%s/%s", uml_dir, umid, name);
if (n >= len) {
printk(UM_KERN_ERR "umid_file_name : buffer too short\n");
return -E2BIG;
}
return 0;
}
char *get_umid(void)
{
return umid;
}
static int __init set_uml_dir(char *name, int *add)
{
if (*name == '\0') {
printf("uml_dir can't be an empty string\n");
return 0;
}
if (name[strlen(name) - 1] == '/') {
uml_dir = name;
return 0;
}
uml_dir = malloc(strlen(name) + 2);
if (uml_dir == NULL) {
printf("Failed to malloc uml_dir - error = %d\n", errno);
/*
* Return 0 here because do_initcalls doesn't look at
* the return value.
*/
return 0;
}
sprintf(uml_dir, "%s/", name);
return 0;
}
__uml_setup("uml_dir=", set_uml_dir,
"uml_dir=<directory>\n"
" The location to place the pid and umid files.\n\n"
);
static void remove_umid_dir(void)
{
char dir[strlen(uml_dir) + UMID_LEN + 1], err;
sprintf(dir, "%s%s", uml_dir, umid);
err = remove_files_and_dir(dir);
if (err)
printf("remove_umid_dir - remove_files_and_dir failed with "
"err = %d\n", err);
}
__uml_exitcall(remove_umid_dir);
| gpl-2.0 |
invisiblek/android_kernel_oppo_n3 | arch/arm/mach-omap2/pm.c | 4702 | 7166 | /*
* pm.c - Common OMAP2+ power management-related code
*
* Copyright (C) 2010 Texas Instruments, Inc.
* Copyright (C) 2010 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.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/err.h>
#include <linux/opp.h>
#include <linux/export.h>
#include <linux/suspend.h>
#include <asm/system_misc.h>
#include <plat/omap-pm.h>
#include <plat/omap_device.h>
#include "common.h"
#include "prcm-common.h"
#include "voltage.h"
#include "powerdomain.h"
#include "clockdomain.h"
#include "pm.h"
#include "twl-common.h"
static struct omap_device_pm_latency *pm_lats;
/*
* omap_pm_suspend: points to a function that does the SoC-specific
* suspend work
*/
int (*omap_pm_suspend)(void);
static int __init _init_omap_device(char *name)
{
struct omap_hwmod *oh;
struct platform_device *pdev;
oh = omap_hwmod_lookup(name);
if (WARN(!oh, "%s: could not find omap_hwmod for %s\n",
__func__, name))
return -ENODEV;
pdev = omap_device_build(oh->name, 0, oh, NULL, 0, pm_lats, 0, false);
if (WARN(IS_ERR(pdev), "%s: could not build omap_device for %s\n",
__func__, name))
return -ENODEV;
return 0;
}
/*
* Build omap_devices for processors and bus.
*/
static void __init omap2_init_processor_devices(void)
{
_init_omap_device("mpu");
if (omap3_has_iva())
_init_omap_device("iva");
if (cpu_is_omap44xx()) {
_init_omap_device("l3_main_1");
_init_omap_device("dsp");
_init_omap_device("iva");
} else {
_init_omap_device("l3_main");
}
}
/* Types of sleep_switch used in omap_set_pwrdm_state */
#define FORCEWAKEUP_SWITCH 0
#define LOWPOWERSTATE_SWITCH 1
int __init omap_pm_clkdms_setup(struct clockdomain *clkdm, void *unused)
{
if (clkdm->flags & CLKDM_CAN_ENABLE_AUTO)
clkdm_allow_idle(clkdm);
else if (clkdm->flags & CLKDM_CAN_FORCE_SLEEP &&
atomic_read(&clkdm->usecount) == 0)
clkdm_sleep(clkdm);
return 0;
}
/*
* This sets pwrdm state (other than mpu & core. Currently only ON &
* RET are supported.
*/
int omap_set_pwrdm_state(struct powerdomain *pwrdm, u32 pwrst)
{
u8 curr_pwrst, next_pwrst;
int sleep_switch = -1, ret = 0, hwsup = 0;
if (!pwrdm || IS_ERR(pwrdm))
return -EINVAL;
while (!(pwrdm->pwrsts & (1 << pwrst))) {
if (pwrst == PWRDM_POWER_OFF)
return ret;
pwrst--;
}
next_pwrst = pwrdm_read_next_pwrst(pwrdm);
if (next_pwrst == pwrst)
return ret;
curr_pwrst = pwrdm_read_pwrst(pwrdm);
if (curr_pwrst < PWRDM_POWER_ON) {
if ((curr_pwrst > pwrst) &&
(pwrdm->flags & PWRDM_HAS_LOWPOWERSTATECHANGE)) {
sleep_switch = LOWPOWERSTATE_SWITCH;
} else {
hwsup = clkdm_in_hwsup(pwrdm->pwrdm_clkdms[0]);
clkdm_wakeup(pwrdm->pwrdm_clkdms[0]);
sleep_switch = FORCEWAKEUP_SWITCH;
}
}
ret = pwrdm_set_next_pwrst(pwrdm, pwrst);
if (ret)
pr_err("%s: unable to set power state of powerdomain: %s\n",
__func__, pwrdm->name);
switch (sleep_switch) {
case FORCEWAKEUP_SWITCH:
if (hwsup)
clkdm_allow_idle(pwrdm->pwrdm_clkdms[0]);
else
clkdm_sleep(pwrdm->pwrdm_clkdms[0]);
break;
case LOWPOWERSTATE_SWITCH:
pwrdm_set_lowpwrstchange(pwrdm);
pwrdm_wait_transition(pwrdm);
pwrdm_state_switch(pwrdm);
break;
}
return ret;
}
/*
* This API is to be called during init to set the various voltage
* domains to the voltage as per the opp table. Typically we boot up
* at the nominal voltage. So this function finds out the rate of
* the clock associated with the voltage domain, finds out the correct
* opp entry and sets the voltage domain to the voltage specified
* in the opp entry
*/
static int __init omap2_set_init_voltage(char *vdd_name, char *clk_name,
const char *oh_name)
{
struct voltagedomain *voltdm;
struct clk *clk;
struct opp *opp;
unsigned long freq, bootup_volt;
struct device *dev;
if (!vdd_name || !clk_name || !oh_name) {
pr_err("%s: invalid parameters\n", __func__);
goto exit;
}
dev = omap_device_get_by_hwmod_name(oh_name);
if (IS_ERR(dev)) {
pr_err("%s: Unable to get dev pointer for hwmod %s\n",
__func__, oh_name);
goto exit;
}
voltdm = voltdm_lookup(vdd_name);
if (IS_ERR(voltdm)) {
pr_err("%s: unable to get vdd pointer for vdd_%s\n",
__func__, vdd_name);
goto exit;
}
clk = clk_get(NULL, clk_name);
if (IS_ERR(clk)) {
pr_err("%s: unable to get clk %s\n", __func__, clk_name);
goto exit;
}
freq = clk->rate;
clk_put(clk);
rcu_read_lock();
opp = opp_find_freq_ceil(dev, &freq);
if (IS_ERR(opp)) {
rcu_read_unlock();
pr_err("%s: unable to find boot up OPP for vdd_%s\n",
__func__, vdd_name);
goto exit;
}
bootup_volt = opp_get_voltage(opp);
rcu_read_unlock();
if (!bootup_volt) {
pr_err("%s: unable to find voltage corresponding "
"to the bootup OPP for vdd_%s\n", __func__, vdd_name);
goto exit;
}
voltdm_scale(voltdm, bootup_volt);
return 0;
exit:
pr_err("%s: unable to set vdd_%s\n", __func__, vdd_name);
return -EINVAL;
}
#ifdef CONFIG_SUSPEND
static int omap_pm_enter(suspend_state_t suspend_state)
{
int ret = 0;
if (!omap_pm_suspend)
return -ENOENT; /* XXX doublecheck */
switch (suspend_state) {
case PM_SUSPEND_STANDBY:
case PM_SUSPEND_MEM:
ret = omap_pm_suspend();
break;
default:
ret = -EINVAL;
}
return ret;
}
static int omap_pm_begin(suspend_state_t state)
{
disable_hlt();
if (cpu_is_omap34xx())
omap_prcm_irq_prepare();
return 0;
}
static void omap_pm_end(void)
{
enable_hlt();
return;
}
static void omap_pm_finish(void)
{
if (cpu_is_omap34xx())
omap_prcm_irq_complete();
}
static const struct platform_suspend_ops omap_pm_ops = {
.begin = omap_pm_begin,
.end = omap_pm_end,
.enter = omap_pm_enter,
.finish = omap_pm_finish,
.valid = suspend_valid_only_mem,
};
#endif /* CONFIG_SUSPEND */
static void __init omap3_init_voltages(void)
{
if (!cpu_is_omap34xx())
return;
omap2_set_init_voltage("mpu_iva", "dpll1_ck", "mpu");
omap2_set_init_voltage("core", "l3_ick", "l3_main");
}
static void __init omap4_init_voltages(void)
{
if (!cpu_is_omap44xx())
return;
omap2_set_init_voltage("mpu", "dpll_mpu_ck", "mpu");
omap2_set_init_voltage("core", "l3_div_ck", "l3_main_1");
omap2_set_init_voltage("iva", "dpll_iva_m5x2_ck", "iva");
}
static int __init omap2_common_pm_init(void)
{
if (!of_have_populated_dt())
omap2_init_processor_devices();
omap_pm_if_init();
return 0;
}
postcore_initcall(omap2_common_pm_init);
static int __init omap2_common_pm_late_init(void)
{
/*
* In the case of DT, the PMIC and SR initialization will be done using
* a completely different mechanism.
* Disable this part if a DT blob is available.
*/
if (of_have_populated_dt())
return 0;
/* Init the voltage layer */
omap_pmic_late_init();
omap_voltage_late_init();
/* Initialize the voltages */
omap3_init_voltages();
omap4_init_voltages();
/* Smartreflex device init */
omap_devinit_smartreflex();
#ifdef CONFIG_SUSPEND
suspend_set_ops(&omap_pm_ops);
#endif
return 0;
}
late_initcall(omap2_common_pm_late_init);
| gpl-2.0 |
hagar006/android_kernel_sony_apq8064 | arch/arm/mach-sa1100/generic.c | 4702 | 10504 | /*
* linux/arch/arm/mach-sa1100/generic.c
*
* Author: Nicolas Pitre
*
* Code common to all SA11x0 machines.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/gpio.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/dma-mapping.h>
#include <linux/pm.h>
#include <linux/cpufreq.h>
#include <linux/ioport.h>
#include <linux/platform_device.h>
#include <video/sa1100fb.h>
#include <asm/div64.h>
#include <asm/mach/map.h>
#include <asm/mach/flash.h>
#include <asm/irq.h>
#include <asm/system_misc.h>
#include <mach/hardware.h>
#include <mach/irqs.h>
#include "generic.h"
unsigned int reset_status;
EXPORT_SYMBOL(reset_status);
#define NR_FREQS 16
/*
* This table is setup for a 3.6864MHz Crystal.
*/
static const unsigned short cclk_frequency_100khz[NR_FREQS] = {
590, /* 59.0 MHz */
737, /* 73.7 MHz */
885, /* 88.5 MHz */
1032, /* 103.2 MHz */
1180, /* 118.0 MHz */
1327, /* 132.7 MHz */
1475, /* 147.5 MHz */
1622, /* 162.2 MHz */
1769, /* 176.9 MHz */
1917, /* 191.7 MHz */
2064, /* 206.4 MHz */
2212, /* 221.2 MHz */
2359, /* 235.9 MHz */
2507, /* 250.7 MHz */
2654, /* 265.4 MHz */
2802 /* 280.2 MHz */
};
/* rounds up(!) */
unsigned int sa11x0_freq_to_ppcr(unsigned int khz)
{
int i;
khz /= 100;
for (i = 0; i < NR_FREQS; i++)
if (cclk_frequency_100khz[i] >= khz)
break;
return i;
}
unsigned int sa11x0_ppcr_to_freq(unsigned int idx)
{
unsigned int freq = 0;
if (idx < NR_FREQS)
freq = cclk_frequency_100khz[idx] * 100;
return freq;
}
/* make sure that only the "userspace" governor is run -- anything else wouldn't make sense on
* this platform, anyway.
*/
int sa11x0_verify_speed(struct cpufreq_policy *policy)
{
unsigned int tmp;
if (policy->cpu)
return -EINVAL;
cpufreq_verify_within_limits(policy, policy->cpuinfo.min_freq, policy->cpuinfo.max_freq);
/* make sure that at least one frequency is within the policy */
tmp = cclk_frequency_100khz[sa11x0_freq_to_ppcr(policy->min)] * 100;
if (tmp > policy->max)
policy->max = tmp;
cpufreq_verify_within_limits(policy, policy->cpuinfo.min_freq, policy->cpuinfo.max_freq);
return 0;
}
unsigned int sa11x0_getspeed(unsigned int cpu)
{
if (cpu)
return 0;
return cclk_frequency_100khz[PPCR & 0xf] * 100;
}
/*
* Default power-off for SA1100
*/
static void sa1100_power_off(void)
{
mdelay(100);
local_irq_disable();
/* disable internal oscillator, float CS lines */
PCFR = (PCFR_OPDE | PCFR_FP | PCFR_FS);
/* enable wake-up on GPIO0 (Assabet...) */
PWER = GFER = GRER = 1;
/*
* set scratchpad to zero, just in case it is used as a
* restart address by the bootloader.
*/
PSPR = 0;
/* enter sleep mode */
PMCR = PMCR_SF;
}
void sa11x0_restart(char mode, const char *cmd)
{
if (mode == 's') {
/* Jump into ROM at address 0 */
soft_restart(0);
} else {
/* Use on-chip reset capability */
RSRR = RSRR_SWR;
}
}
static void sa11x0_register_device(struct platform_device *dev, void *data)
{
int err;
dev->dev.platform_data = data;
err = platform_device_register(dev);
if (err)
printk(KERN_ERR "Unable to register device %s: %d\n",
dev->name, err);
}
static struct resource sa11x0udc_resources[] = {
[0] = DEFINE_RES_MEM(__PREG(Ser0UDCCR), SZ_64K),
[1] = DEFINE_RES_IRQ(IRQ_Ser0UDC),
};
static u64 sa11x0udc_dma_mask = 0xffffffffUL;
static struct platform_device sa11x0udc_device = {
.name = "sa11x0-udc",
.id = -1,
.dev = {
.dma_mask = &sa11x0udc_dma_mask,
.coherent_dma_mask = 0xffffffff,
},
.num_resources = ARRAY_SIZE(sa11x0udc_resources),
.resource = sa11x0udc_resources,
};
static struct resource sa11x0uart1_resources[] = {
[0] = DEFINE_RES_MEM(__PREG(Ser1UTCR0), SZ_64K),
[1] = DEFINE_RES_IRQ(IRQ_Ser1UART),
};
static struct platform_device sa11x0uart1_device = {
.name = "sa11x0-uart",
.id = 1,
.num_resources = ARRAY_SIZE(sa11x0uart1_resources),
.resource = sa11x0uart1_resources,
};
static struct resource sa11x0uart3_resources[] = {
[0] = DEFINE_RES_MEM(__PREG(Ser3UTCR0), SZ_64K),
[1] = DEFINE_RES_IRQ(IRQ_Ser3UART),
};
static struct platform_device sa11x0uart3_device = {
.name = "sa11x0-uart",
.id = 3,
.num_resources = ARRAY_SIZE(sa11x0uart3_resources),
.resource = sa11x0uart3_resources,
};
static struct resource sa11x0mcp_resources[] = {
[0] = DEFINE_RES_MEM(__PREG(Ser4MCCR0), SZ_64K),
[1] = DEFINE_RES_MEM(__PREG(Ser4MCCR1), 4),
[2] = DEFINE_RES_IRQ(IRQ_Ser4MCP),
};
static u64 sa11x0mcp_dma_mask = 0xffffffffUL;
static struct platform_device sa11x0mcp_device = {
.name = "sa11x0-mcp",
.id = -1,
.dev = {
.dma_mask = &sa11x0mcp_dma_mask,
.coherent_dma_mask = 0xffffffff,
},
.num_resources = ARRAY_SIZE(sa11x0mcp_resources),
.resource = sa11x0mcp_resources,
};
void __init sa11x0_ppc_configure_mcp(void)
{
/* Setup the PPC unit for the MCP */
PPDR &= ~PPC_RXD4;
PPDR |= PPC_TXD4 | PPC_SCLK | PPC_SFRM;
PSDR |= PPC_RXD4;
PSDR &= ~(PPC_TXD4 | PPC_SCLK | PPC_SFRM);
PPSR &= ~(PPC_TXD4 | PPC_SCLK | PPC_SFRM);
}
void sa11x0_register_mcp(struct mcp_plat_data *data)
{
sa11x0_register_device(&sa11x0mcp_device, data);
}
static struct resource sa11x0ssp_resources[] = {
[0] = DEFINE_RES_MEM(0x80070000, SZ_64K),
[1] = DEFINE_RES_IRQ(IRQ_Ser4SSP),
};
static u64 sa11x0ssp_dma_mask = 0xffffffffUL;
static struct platform_device sa11x0ssp_device = {
.name = "sa11x0-ssp",
.id = -1,
.dev = {
.dma_mask = &sa11x0ssp_dma_mask,
.coherent_dma_mask = 0xffffffff,
},
.num_resources = ARRAY_SIZE(sa11x0ssp_resources),
.resource = sa11x0ssp_resources,
};
static struct resource sa11x0fb_resources[] = {
[0] = DEFINE_RES_MEM(0xb0100000, SZ_64K),
[1] = DEFINE_RES_IRQ(IRQ_LCD),
};
static struct platform_device sa11x0fb_device = {
.name = "sa11x0-fb",
.id = -1,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
.num_resources = ARRAY_SIZE(sa11x0fb_resources),
.resource = sa11x0fb_resources,
};
void sa11x0_register_lcd(struct sa1100fb_mach_info *inf)
{
sa11x0_register_device(&sa11x0fb_device, inf);
}
static struct platform_device sa11x0pcmcia_device = {
.name = "sa11x0-pcmcia",
.id = -1,
};
static struct platform_device sa11x0mtd_device = {
.name = "sa1100-mtd",
.id = -1,
};
void sa11x0_register_mtd(struct flash_platform_data *flash,
struct resource *res, int nr)
{
flash->name = "sa1100";
sa11x0mtd_device.resource = res;
sa11x0mtd_device.num_resources = nr;
sa11x0_register_device(&sa11x0mtd_device, flash);
}
static struct resource sa11x0ir_resources[] = {
DEFINE_RES_MEM(__PREG(Ser2UTCR0), 0x24),
DEFINE_RES_MEM(__PREG(Ser2HSCR0), 0x1c),
DEFINE_RES_MEM(__PREG(Ser2HSCR2), 0x04),
DEFINE_RES_IRQ(IRQ_Ser2ICP),
};
static struct platform_device sa11x0ir_device = {
.name = "sa11x0-ir",
.id = -1,
.num_resources = ARRAY_SIZE(sa11x0ir_resources),
.resource = sa11x0ir_resources,
};
void sa11x0_register_irda(struct irda_platform_data *irda)
{
sa11x0_register_device(&sa11x0ir_device, irda);
}
static struct resource sa1100_rtc_resources[] = {
DEFINE_RES_MEM(0x90010000, 0x40),
DEFINE_RES_IRQ_NAMED(IRQ_RTC1Hz, "rtc 1Hz"),
DEFINE_RES_IRQ_NAMED(IRQ_RTCAlrm, "rtc alarm"),
};
static struct platform_device sa11x0rtc_device = {
.name = "sa1100-rtc",
.id = -1,
.num_resources = ARRAY_SIZE(sa1100_rtc_resources),
.resource = sa1100_rtc_resources,
};
static struct resource sa11x0dma_resources[] = {
DEFINE_RES_MEM(DMA_PHYS, DMA_SIZE),
DEFINE_RES_IRQ(IRQ_DMA0),
DEFINE_RES_IRQ(IRQ_DMA1),
DEFINE_RES_IRQ(IRQ_DMA2),
DEFINE_RES_IRQ(IRQ_DMA3),
DEFINE_RES_IRQ(IRQ_DMA4),
DEFINE_RES_IRQ(IRQ_DMA5),
};
static u64 sa11x0dma_dma_mask = DMA_BIT_MASK(32);
static struct platform_device sa11x0dma_device = {
.name = "sa11x0-dma",
.id = -1,
.dev = {
.dma_mask = &sa11x0dma_dma_mask,
.coherent_dma_mask = 0xffffffff,
},
.num_resources = ARRAY_SIZE(sa11x0dma_resources),
.resource = sa11x0dma_resources,
};
static struct platform_device *sa11x0_devices[] __initdata = {
&sa11x0udc_device,
&sa11x0uart1_device,
&sa11x0uart3_device,
&sa11x0ssp_device,
&sa11x0pcmcia_device,
&sa11x0rtc_device,
&sa11x0dma_device,
};
static int __init sa1100_init(void)
{
pm_power_off = sa1100_power_off;
return platform_add_devices(sa11x0_devices, ARRAY_SIZE(sa11x0_devices));
}
arch_initcall(sa1100_init);
/*
* Common I/O mapping:
*
* Typically, static virtual address mappings are as follow:
*
* 0xf0000000-0xf3ffffff: miscellaneous stuff (CPLDs, etc.)
* 0xf4000000-0xf4ffffff: SA-1111
* 0xf5000000-0xf5ffffff: reserved (used by cache flushing area)
* 0xf6000000-0xfffeffff: reserved (internal SA1100 IO defined above)
* 0xffff0000-0xffff0fff: SA1100 exception vectors
* 0xffff2000-0xffff2fff: Minicache copy_user_page area
*
* Below 0xe8000000 is reserved for vm allocation.
*
* The machine specific code must provide the extra mapping beside the
* default mapping provided here.
*/
static struct map_desc standard_io_desc[] __initdata = {
{ /* PCM */
.virtual = 0xf8000000,
.pfn = __phys_to_pfn(0x80000000),
.length = 0x00100000,
.type = MT_DEVICE
}, { /* SCM */
.virtual = 0xfa000000,
.pfn = __phys_to_pfn(0x90000000),
.length = 0x00100000,
.type = MT_DEVICE
}, { /* MER */
.virtual = 0xfc000000,
.pfn = __phys_to_pfn(0xa0000000),
.length = 0x00100000,
.type = MT_DEVICE
}, { /* LCD + DMA */
.virtual = 0xfe000000,
.pfn = __phys_to_pfn(0xb0000000),
.length = 0x00200000,
.type = MT_DEVICE
},
};
void __init sa1100_map_io(void)
{
iotable_init(standard_io_desc, ARRAY_SIZE(standard_io_desc));
}
/*
* Disable the memory bus request/grant signals on the SA1110 to
* ensure that we don't receive spurious memory requests. We set
* the MBGNT signal false to ensure the SA1111 doesn't own the
* SDRAM bus.
*/
void sa1110_mb_disable(void)
{
unsigned long flags;
local_irq_save(flags);
PGSR &= ~GPIO_MBGNT;
GPCR = GPIO_MBGNT;
GPDR = (GPDR & ~GPIO_MBREQ) | GPIO_MBGNT;
GAFR &= ~(GPIO_MBGNT | GPIO_MBREQ);
local_irq_restore(flags);
}
/*
* If the system is going to use the SA-1111 DMA engines, set up
* the memory bus request/grant pins.
*/
void sa1110_mb_enable(void)
{
unsigned long flags;
local_irq_save(flags);
PGSR &= ~GPIO_MBGNT;
GPCR = GPIO_MBGNT;
GPDR = (GPDR & ~GPIO_MBREQ) | GPIO_MBGNT;
GAFR |= (GPIO_MBGNT | GPIO_MBREQ);
TUCR |= TUCR_MR;
local_irq_restore(flags);
}
| gpl-2.0 |
chacox/s4mini_9195_cm12_kernel | fs/binfmt_som.c | 4958 | 7318 | /*
* linux/fs/binfmt_som.c
*
* These are the functions used to load SOM format executables as used
* by HP-UX.
*
* Copyright 1999 Matthew Wilcox <willy@bofh.ai>
* based on binfmt_elf which is
* Copyright 1993, 1994: Eric Youngdale (ericy@cais.com).
*/
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/stat.h>
#include <linux/sched.h>
#include <linux/mm.h>
#include <linux/mman.h>
#include <linux/errno.h>
#include <linux/signal.h>
#include <linux/binfmts.h>
#include <linux/som.h>
#include <linux/string.h>
#include <linux/file.h>
#include <linux/fcntl.h>
#include <linux/ptrace.h>
#include <linux/slab.h>
#include <linux/shm.h>
#include <linux/personality.h>
#include <linux/init.h>
#include <asm/uaccess.h>
#include <asm/pgtable.h>
#include <linux/elf.h>
static int load_som_binary(struct linux_binprm * bprm, struct pt_regs * regs);
static int load_som_library(struct file *);
/*
* If we don't support core dumping, then supply a NULL so we
* don't even try.
*/
#if 0
static int som_core_dump(struct coredump_params *cprm);
#else
#define som_core_dump NULL
#endif
#define SOM_PAGESTART(_v) ((_v) & ~(unsigned long)(SOM_PAGESIZE-1))
#define SOM_PAGEOFFSET(_v) ((_v) & (SOM_PAGESIZE-1))
#define SOM_PAGEALIGN(_v) (((_v) + SOM_PAGESIZE - 1) & ~(SOM_PAGESIZE - 1))
static struct linux_binfmt som_format = {
.module = THIS_MODULE,
.load_binary = load_som_binary,
.load_shlib = load_som_library,
.core_dump = som_core_dump,
.min_coredump = SOM_PAGESIZE
};
/*
* create_som_tables() parses the env- and arg-strings in new user
* memory and creates the pointer tables from them, and puts their
* addresses on the "stack", returning the new stack pointer value.
*/
static void create_som_tables(struct linux_binprm *bprm)
{
char **argv, **envp;
int argc = bprm->argc;
int envc = bprm->envc;
unsigned long p;
unsigned long *sp;
/* Word-align the stack pointer */
sp = (unsigned long *)((bprm->p + 3) & ~3);
envp = (char **) sp;
sp += envc + 1;
argv = (char **) sp;
sp += argc + 1;
__put_user((unsigned long) envp,++sp);
__put_user((unsigned long) argv,++sp);
__put_user(argc, ++sp);
bprm->p = (unsigned long) sp;
p = current->mm->arg_start;
while (argc-- > 0) {
__put_user((char *)p,argv++);
p += strlen_user((char *)p);
}
__put_user(NULL, argv);
current->mm->arg_end = current->mm->env_start = p;
while (envc-- > 0) {
__put_user((char *)p,envp++);
p += strlen_user((char *)p);
}
__put_user(NULL, envp);
current->mm->env_end = p;
}
static int check_som_header(struct som_hdr *som_ex)
{
int *buf = (int *)som_ex;
int i, ck;
if (som_ex->system_id != SOM_SID_PARISC_1_0 &&
som_ex->system_id != SOM_SID_PARISC_1_1 &&
som_ex->system_id != SOM_SID_PARISC_2_0)
return -ENOEXEC;
if (som_ex->a_magic != SOM_EXEC_NONSHARE &&
som_ex->a_magic != SOM_EXEC_SHARE &&
som_ex->a_magic != SOM_EXEC_DEMAND)
return -ENOEXEC;
if (som_ex->version_id != SOM_ID_OLD &&
som_ex->version_id != SOM_ID_NEW)
return -ENOEXEC;
ck = 0;
for (i=0; i<32; i++)
ck ^= buf[i];
if (ck != 0)
return -ENOEXEC;
return 0;
}
static int map_som_binary(struct file *file,
const struct som_exec_auxhdr *hpuxhdr)
{
unsigned long code_start, code_size, data_start, data_size;
unsigned long bss_start, som_brk;
int retval;
int prot = PROT_READ | PROT_EXEC;
int flags = MAP_FIXED|MAP_PRIVATE|MAP_DENYWRITE|MAP_EXECUTABLE;
mm_segment_t old_fs = get_fs();
set_fs(get_ds());
code_start = SOM_PAGESTART(hpuxhdr->exec_tmem);
code_size = SOM_PAGEALIGN(hpuxhdr->exec_tsize);
current->mm->start_code = code_start;
current->mm->end_code = code_start + code_size;
retval = vm_mmap(file, code_start, code_size, prot,
flags, SOM_PAGESTART(hpuxhdr->exec_tfile));
if (retval < 0 && retval > -1024)
goto out;
data_start = SOM_PAGESTART(hpuxhdr->exec_dmem);
data_size = SOM_PAGEALIGN(hpuxhdr->exec_dsize);
current->mm->start_data = data_start;
current->mm->end_data = bss_start = data_start + data_size;
retval = vm_mmap(file, data_start, data_size,
prot | PROT_WRITE, flags,
SOM_PAGESTART(hpuxhdr->exec_dfile));
if (retval < 0 && retval > -1024)
goto out;
som_brk = bss_start + SOM_PAGEALIGN(hpuxhdr->exec_bsize);
current->mm->start_brk = current->mm->brk = som_brk;
retval = vm_mmap(NULL, bss_start, som_brk - bss_start,
prot | PROT_WRITE, MAP_FIXED | MAP_PRIVATE, 0);
if (retval > 0 || retval < -1024)
retval = 0;
out:
set_fs(old_fs);
return retval;
}
/*
* These are the functions used to load SOM executables and shared
* libraries. There is no binary dependent code anywhere else.
*/
static int
load_som_binary(struct linux_binprm * bprm, struct pt_regs * regs)
{
int retval;
unsigned int size;
unsigned long som_entry;
struct som_hdr *som_ex;
struct som_exec_auxhdr *hpuxhdr;
/* Get the exec-header */
som_ex = (struct som_hdr *) bprm->buf;
retval = check_som_header(som_ex);
if (retval != 0)
goto out;
/* Now read in the auxiliary header information */
retval = -ENOMEM;
size = som_ex->aux_header_size;
if (size > SOM_PAGESIZE)
goto out;
hpuxhdr = kmalloc(size, GFP_KERNEL);
if (!hpuxhdr)
goto out;
retval = kernel_read(bprm->file, som_ex->aux_header_location,
(char *) hpuxhdr, size);
if (retval != size) {
if (retval >= 0)
retval = -EIO;
goto out_free;
}
/* Flush all traces of the currently running executable */
retval = flush_old_exec(bprm);
if (retval)
goto out_free;
/* OK, This is the point of no return */
current->personality = PER_HPUX;
setup_new_exec(bprm);
/* Set the task size for HP-UX processes such that
* the gateway page is outside the address space.
* This can be fixed later, but for now, this is much
* easier.
*/
current->thread.task_size = 0xc0000000;
/* Set map base to allow enough room for hp-ux heap growth */
current->thread.map_base = 0x80000000;
retval = map_som_binary(bprm->file, hpuxhdr);
if (retval < 0)
goto out_free;
som_entry = hpuxhdr->exec_entry;
kfree(hpuxhdr);
set_binfmt(&som_format);
install_exec_creds(bprm);
setup_arg_pages(bprm, STACK_TOP, EXSTACK_DEFAULT);
create_som_tables(bprm);
current->mm->start_stack = bprm->p;
#if 0
printk("(start_brk) %08lx\n" , (unsigned long) current->mm->start_brk);
printk("(end_code) %08lx\n" , (unsigned long) current->mm->end_code);
printk("(start_code) %08lx\n" , (unsigned long) current->mm->start_code);
printk("(end_data) %08lx\n" , (unsigned long) current->mm->end_data);
printk("(start_stack) %08lx\n" , (unsigned long) current->mm->start_stack);
printk("(brk) %08lx\n" , (unsigned long) current->mm->brk);
#endif
map_hpux_gateway_page(current,current->mm);
start_thread_som(regs, som_entry, bprm->p);
return 0;
/* error cleanup */
out_free:
kfree(hpuxhdr);
out:
return retval;
}
static int load_som_library(struct file *f)
{
/* No lib support in SOM yet. gizza chance.. */
return -ENOEXEC;
}
/* Install the SOM loader.
* N.B. We *rely* on the table being the right size with the
* right number of free slots...
*/
static int __init init_som_binfmt(void)
{
register_binfmt(&som_format);
return 0;
}
static void __exit exit_som_binfmt(void)
{
/* Remove the SOM loader. */
unregister_binfmt(&som_format);
}
core_initcall(init_som_binfmt);
module_exit(exit_som_binfmt);
MODULE_LICENSE("GPL");
| gpl-2.0 |
cphelps76/kernel_google_msm | drivers/infiniband/hw/cxgb4/mem.c | 5470 | 20512 | /*
* Copyright (c) 2009-2010 Chelsio, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <rdma/ib_umem.h>
#include <linux/atomic.h>
#include "iw_cxgb4.h"
#define T4_ULPTX_MIN_IO 32
#define C4IW_MAX_INLINE_SIZE 96
static int write_adapter_mem(struct c4iw_rdev *rdev, u32 addr, u32 len,
void *data)
{
struct sk_buff *skb;
struct ulp_mem_io *req;
struct ulptx_idata *sc;
u8 wr_len, *to_dp, *from_dp;
int copy_len, num_wqe, i, ret = 0;
struct c4iw_wr_wait wr_wait;
addr &= 0x7FFFFFF;
PDBG("%s addr 0x%x len %u\n", __func__, addr, len);
num_wqe = DIV_ROUND_UP(len, C4IW_MAX_INLINE_SIZE);
c4iw_init_wr_wait(&wr_wait);
for (i = 0; i < num_wqe; i++) {
copy_len = len > C4IW_MAX_INLINE_SIZE ? C4IW_MAX_INLINE_SIZE :
len;
wr_len = roundup(sizeof *req + sizeof *sc +
roundup(copy_len, T4_ULPTX_MIN_IO), 16);
skb = alloc_skb(wr_len, GFP_KERNEL);
if (!skb)
return -ENOMEM;
set_wr_txq(skb, CPL_PRIORITY_CONTROL, 0);
req = (struct ulp_mem_io *)__skb_put(skb, wr_len);
memset(req, 0, wr_len);
INIT_ULPTX_WR(req, wr_len, 0, 0);
if (i == (num_wqe-1)) {
req->wr.wr_hi = cpu_to_be32(FW_WR_OP(FW_ULPTX_WR) |
FW_WR_COMPL(1));
req->wr.wr_lo = (__force __be64)(unsigned long) &wr_wait;
} else
req->wr.wr_hi = cpu_to_be32(FW_WR_OP(FW_ULPTX_WR));
req->wr.wr_mid = cpu_to_be32(
FW_WR_LEN16(DIV_ROUND_UP(wr_len, 16)));
req->cmd = cpu_to_be32(ULPTX_CMD(ULP_TX_MEM_WRITE) | (1<<23));
req->dlen = cpu_to_be32(ULP_MEMIO_DATA_LEN(
DIV_ROUND_UP(copy_len, T4_ULPTX_MIN_IO)));
req->len16 = cpu_to_be32(DIV_ROUND_UP(wr_len-sizeof(req->wr),
16));
req->lock_addr = cpu_to_be32(ULP_MEMIO_ADDR(addr + i * 3));
sc = (struct ulptx_idata *)(req + 1);
sc->cmd_more = cpu_to_be32(ULPTX_CMD(ULP_TX_SC_IMM));
sc->len = cpu_to_be32(roundup(copy_len, T4_ULPTX_MIN_IO));
to_dp = (u8 *)(sc + 1);
from_dp = (u8 *)data + i * C4IW_MAX_INLINE_SIZE;
if (data)
memcpy(to_dp, from_dp, copy_len);
else
memset(to_dp, 0, copy_len);
if (copy_len % T4_ULPTX_MIN_IO)
memset(to_dp + copy_len, 0, T4_ULPTX_MIN_IO -
(copy_len % T4_ULPTX_MIN_IO));
ret = c4iw_ofld_send(rdev, skb);
if (ret)
return ret;
len -= C4IW_MAX_INLINE_SIZE;
}
ret = c4iw_wait_for_reply(rdev, &wr_wait, 0, 0, __func__);
return ret;
}
/*
* Build and write a TPT entry.
* IN: stag key, pdid, perm, bind_enabled, zbva, to, len, page_size,
* pbl_size and pbl_addr
* OUT: stag index
*/
static int write_tpt_entry(struct c4iw_rdev *rdev, u32 reset_tpt_entry,
u32 *stag, u8 stag_state, u32 pdid,
enum fw_ri_stag_type type, enum fw_ri_mem_perms perm,
int bind_enabled, u32 zbva, u64 to,
u64 len, u8 page_size, u32 pbl_size, u32 pbl_addr)
{
int err;
struct fw_ri_tpte tpt;
u32 stag_idx;
static atomic_t key;
if (c4iw_fatal_error(rdev))
return -EIO;
stag_state = stag_state > 0;
stag_idx = (*stag) >> 8;
if ((!reset_tpt_entry) && (*stag == T4_STAG_UNSET)) {
stag_idx = c4iw_get_resource(&rdev->resource.tpt_fifo,
&rdev->resource.tpt_fifo_lock);
if (!stag_idx)
return -ENOMEM;
*stag = (stag_idx << 8) | (atomic_inc_return(&key) & 0xff);
}
PDBG("%s stag_state 0x%0x type 0x%0x pdid 0x%0x, stag_idx 0x%x\n",
__func__, stag_state, type, pdid, stag_idx);
/* write TPT entry */
if (reset_tpt_entry)
memset(&tpt, 0, sizeof(tpt));
else {
tpt.valid_to_pdid = cpu_to_be32(F_FW_RI_TPTE_VALID |
V_FW_RI_TPTE_STAGKEY((*stag & M_FW_RI_TPTE_STAGKEY)) |
V_FW_RI_TPTE_STAGSTATE(stag_state) |
V_FW_RI_TPTE_STAGTYPE(type) | V_FW_RI_TPTE_PDID(pdid));
tpt.locread_to_qpid = cpu_to_be32(V_FW_RI_TPTE_PERM(perm) |
(bind_enabled ? F_FW_RI_TPTE_MWBINDEN : 0) |
V_FW_RI_TPTE_ADDRTYPE((zbva ? FW_RI_ZERO_BASED_TO :
FW_RI_VA_BASED_TO))|
V_FW_RI_TPTE_PS(page_size));
tpt.nosnoop_pbladdr = !pbl_size ? 0 : cpu_to_be32(
V_FW_RI_TPTE_PBLADDR(PBL_OFF(rdev, pbl_addr)>>3));
tpt.len_lo = cpu_to_be32((u32)(len & 0xffffffffUL));
tpt.va_hi = cpu_to_be32((u32)(to >> 32));
tpt.va_lo_fbo = cpu_to_be32((u32)(to & 0xffffffffUL));
tpt.dca_mwbcnt_pstag = cpu_to_be32(0);
tpt.len_hi = cpu_to_be32((u32)(len >> 32));
}
err = write_adapter_mem(rdev, stag_idx +
(rdev->lldi.vr->stag.start >> 5),
sizeof(tpt), &tpt);
if (reset_tpt_entry)
c4iw_put_resource(&rdev->resource.tpt_fifo, stag_idx,
&rdev->resource.tpt_fifo_lock);
return err;
}
static int write_pbl(struct c4iw_rdev *rdev, __be64 *pbl,
u32 pbl_addr, u32 pbl_size)
{
int err;
PDBG("%s *pdb_addr 0x%x, pbl_base 0x%x, pbl_size %d\n",
__func__, pbl_addr, rdev->lldi.vr->pbl.start,
pbl_size);
err = write_adapter_mem(rdev, pbl_addr >> 5, pbl_size << 3, pbl);
return err;
}
static int dereg_mem(struct c4iw_rdev *rdev, u32 stag, u32 pbl_size,
u32 pbl_addr)
{
return write_tpt_entry(rdev, 1, &stag, 0, 0, 0, 0, 0, 0, 0UL, 0, 0,
pbl_size, pbl_addr);
}
static int allocate_window(struct c4iw_rdev *rdev, u32 * stag, u32 pdid)
{
*stag = T4_STAG_UNSET;
return write_tpt_entry(rdev, 0, stag, 0, pdid, FW_RI_STAG_MW, 0, 0, 0,
0UL, 0, 0, 0, 0);
}
static int deallocate_window(struct c4iw_rdev *rdev, u32 stag)
{
return write_tpt_entry(rdev, 1, &stag, 0, 0, 0, 0, 0, 0, 0UL, 0, 0, 0,
0);
}
static int allocate_stag(struct c4iw_rdev *rdev, u32 *stag, u32 pdid,
u32 pbl_size, u32 pbl_addr)
{
*stag = T4_STAG_UNSET;
return write_tpt_entry(rdev, 0, stag, 0, pdid, FW_RI_STAG_NSMR, 0, 0, 0,
0UL, 0, 0, pbl_size, pbl_addr);
}
static int finish_mem_reg(struct c4iw_mr *mhp, u32 stag)
{
u32 mmid;
mhp->attr.state = 1;
mhp->attr.stag = stag;
mmid = stag >> 8;
mhp->ibmr.rkey = mhp->ibmr.lkey = stag;
PDBG("%s mmid 0x%x mhp %p\n", __func__, mmid, mhp);
return insert_handle(mhp->rhp, &mhp->rhp->mmidr, mhp, mmid);
}
static int register_mem(struct c4iw_dev *rhp, struct c4iw_pd *php,
struct c4iw_mr *mhp, int shift)
{
u32 stag = T4_STAG_UNSET;
int ret;
ret = write_tpt_entry(&rhp->rdev, 0, &stag, 1, mhp->attr.pdid,
FW_RI_STAG_NSMR, mhp->attr.perms,
mhp->attr.mw_bind_enable, mhp->attr.zbva,
mhp->attr.va_fbo, mhp->attr.len, shift - 12,
mhp->attr.pbl_size, mhp->attr.pbl_addr);
if (ret)
return ret;
ret = finish_mem_reg(mhp, stag);
if (ret)
dereg_mem(&rhp->rdev, mhp->attr.stag, mhp->attr.pbl_size,
mhp->attr.pbl_addr);
return ret;
}
static int reregister_mem(struct c4iw_dev *rhp, struct c4iw_pd *php,
struct c4iw_mr *mhp, int shift, int npages)
{
u32 stag;
int ret;
if (npages > mhp->attr.pbl_size)
return -ENOMEM;
stag = mhp->attr.stag;
ret = write_tpt_entry(&rhp->rdev, 0, &stag, 1, mhp->attr.pdid,
FW_RI_STAG_NSMR, mhp->attr.perms,
mhp->attr.mw_bind_enable, mhp->attr.zbva,
mhp->attr.va_fbo, mhp->attr.len, shift - 12,
mhp->attr.pbl_size, mhp->attr.pbl_addr);
if (ret)
return ret;
ret = finish_mem_reg(mhp, stag);
if (ret)
dereg_mem(&rhp->rdev, mhp->attr.stag, mhp->attr.pbl_size,
mhp->attr.pbl_addr);
return ret;
}
static int alloc_pbl(struct c4iw_mr *mhp, int npages)
{
mhp->attr.pbl_addr = c4iw_pblpool_alloc(&mhp->rhp->rdev,
npages << 3);
if (!mhp->attr.pbl_addr)
return -ENOMEM;
mhp->attr.pbl_size = npages;
return 0;
}
static int build_phys_page_list(struct ib_phys_buf *buffer_list,
int num_phys_buf, u64 *iova_start,
u64 *total_size, int *npages,
int *shift, __be64 **page_list)
{
u64 mask;
int i, j, n;
mask = 0;
*total_size = 0;
for (i = 0; i < num_phys_buf; ++i) {
if (i != 0 && buffer_list[i].addr & ~PAGE_MASK)
return -EINVAL;
if (i != 0 && i != num_phys_buf - 1 &&
(buffer_list[i].size & ~PAGE_MASK))
return -EINVAL;
*total_size += buffer_list[i].size;
if (i > 0)
mask |= buffer_list[i].addr;
else
mask |= buffer_list[i].addr & PAGE_MASK;
if (i != num_phys_buf - 1)
mask |= buffer_list[i].addr + buffer_list[i].size;
else
mask |= (buffer_list[i].addr + buffer_list[i].size +
PAGE_SIZE - 1) & PAGE_MASK;
}
if (*total_size > 0xFFFFFFFFULL)
return -ENOMEM;
/* Find largest page shift we can use to cover buffers */
for (*shift = PAGE_SHIFT; *shift < 27; ++(*shift))
if ((1ULL << *shift) & mask)
break;
buffer_list[0].size += buffer_list[0].addr & ((1ULL << *shift) - 1);
buffer_list[0].addr &= ~0ull << *shift;
*npages = 0;
for (i = 0; i < num_phys_buf; ++i)
*npages += (buffer_list[i].size +
(1ULL << *shift) - 1) >> *shift;
if (!*npages)
return -EINVAL;
*page_list = kmalloc(sizeof(u64) * *npages, GFP_KERNEL);
if (!*page_list)
return -ENOMEM;
n = 0;
for (i = 0; i < num_phys_buf; ++i)
for (j = 0;
j < (buffer_list[i].size + (1ULL << *shift) - 1) >> *shift;
++j)
(*page_list)[n++] = cpu_to_be64(buffer_list[i].addr +
((u64) j << *shift));
PDBG("%s va 0x%llx mask 0x%llx shift %d len %lld pbl_size %d\n",
__func__, (unsigned long long)*iova_start,
(unsigned long long)mask, *shift, (unsigned long long)*total_size,
*npages);
return 0;
}
int c4iw_reregister_phys_mem(struct ib_mr *mr, int mr_rereg_mask,
struct ib_pd *pd, struct ib_phys_buf *buffer_list,
int num_phys_buf, int acc, u64 *iova_start)
{
struct c4iw_mr mh, *mhp;
struct c4iw_pd *php;
struct c4iw_dev *rhp;
__be64 *page_list = NULL;
int shift = 0;
u64 total_size;
int npages;
int ret;
PDBG("%s ib_mr %p ib_pd %p\n", __func__, mr, pd);
/* There can be no memory windows */
if (atomic_read(&mr->usecnt))
return -EINVAL;
mhp = to_c4iw_mr(mr);
rhp = mhp->rhp;
php = to_c4iw_pd(mr->pd);
/* make sure we are on the same adapter */
if (rhp != php->rhp)
return -EINVAL;
memcpy(&mh, mhp, sizeof *mhp);
if (mr_rereg_mask & IB_MR_REREG_PD)
php = to_c4iw_pd(pd);
if (mr_rereg_mask & IB_MR_REREG_ACCESS) {
mh.attr.perms = c4iw_ib_to_tpt_access(acc);
mh.attr.mw_bind_enable = (acc & IB_ACCESS_MW_BIND) ==
IB_ACCESS_MW_BIND;
}
if (mr_rereg_mask & IB_MR_REREG_TRANS) {
ret = build_phys_page_list(buffer_list, num_phys_buf,
iova_start,
&total_size, &npages,
&shift, &page_list);
if (ret)
return ret;
}
ret = reregister_mem(rhp, php, &mh, shift, npages);
kfree(page_list);
if (ret)
return ret;
if (mr_rereg_mask & IB_MR_REREG_PD)
mhp->attr.pdid = php->pdid;
if (mr_rereg_mask & IB_MR_REREG_ACCESS)
mhp->attr.perms = c4iw_ib_to_tpt_access(acc);
if (mr_rereg_mask & IB_MR_REREG_TRANS) {
mhp->attr.zbva = 0;
mhp->attr.va_fbo = *iova_start;
mhp->attr.page_size = shift - 12;
mhp->attr.len = (u32) total_size;
mhp->attr.pbl_size = npages;
}
return 0;
}
struct ib_mr *c4iw_register_phys_mem(struct ib_pd *pd,
struct ib_phys_buf *buffer_list,
int num_phys_buf, int acc, u64 *iova_start)
{
__be64 *page_list;
int shift;
u64 total_size;
int npages;
struct c4iw_dev *rhp;
struct c4iw_pd *php;
struct c4iw_mr *mhp;
int ret;
PDBG("%s ib_pd %p\n", __func__, pd);
php = to_c4iw_pd(pd);
rhp = php->rhp;
mhp = kzalloc(sizeof(*mhp), GFP_KERNEL);
if (!mhp)
return ERR_PTR(-ENOMEM);
mhp->rhp = rhp;
/* First check that we have enough alignment */
if ((*iova_start & ~PAGE_MASK) != (buffer_list[0].addr & ~PAGE_MASK)) {
ret = -EINVAL;
goto err;
}
if (num_phys_buf > 1 &&
((buffer_list[0].addr + buffer_list[0].size) & ~PAGE_MASK)) {
ret = -EINVAL;
goto err;
}
ret = build_phys_page_list(buffer_list, num_phys_buf, iova_start,
&total_size, &npages, &shift,
&page_list);
if (ret)
goto err;
ret = alloc_pbl(mhp, npages);
if (ret) {
kfree(page_list);
goto err_pbl;
}
ret = write_pbl(&mhp->rhp->rdev, page_list, mhp->attr.pbl_addr,
npages);
kfree(page_list);
if (ret)
goto err_pbl;
mhp->attr.pdid = php->pdid;
mhp->attr.zbva = 0;
mhp->attr.perms = c4iw_ib_to_tpt_access(acc);
mhp->attr.va_fbo = *iova_start;
mhp->attr.page_size = shift - 12;
mhp->attr.len = (u32) total_size;
mhp->attr.pbl_size = npages;
ret = register_mem(rhp, php, mhp, shift);
if (ret)
goto err_pbl;
return &mhp->ibmr;
err_pbl:
c4iw_pblpool_free(&mhp->rhp->rdev, mhp->attr.pbl_addr,
mhp->attr.pbl_size << 3);
err:
kfree(mhp);
return ERR_PTR(ret);
}
struct ib_mr *c4iw_get_dma_mr(struct ib_pd *pd, int acc)
{
struct c4iw_dev *rhp;
struct c4iw_pd *php;
struct c4iw_mr *mhp;
int ret;
u32 stag = T4_STAG_UNSET;
PDBG("%s ib_pd %p\n", __func__, pd);
php = to_c4iw_pd(pd);
rhp = php->rhp;
mhp = kzalloc(sizeof(*mhp), GFP_KERNEL);
if (!mhp)
return ERR_PTR(-ENOMEM);
mhp->rhp = rhp;
mhp->attr.pdid = php->pdid;
mhp->attr.perms = c4iw_ib_to_tpt_access(acc);
mhp->attr.mw_bind_enable = (acc&IB_ACCESS_MW_BIND) == IB_ACCESS_MW_BIND;
mhp->attr.zbva = 0;
mhp->attr.va_fbo = 0;
mhp->attr.page_size = 0;
mhp->attr.len = ~0UL;
mhp->attr.pbl_size = 0;
ret = write_tpt_entry(&rhp->rdev, 0, &stag, 1, php->pdid,
FW_RI_STAG_NSMR, mhp->attr.perms,
mhp->attr.mw_bind_enable, 0, 0, ~0UL, 0, 0, 0);
if (ret)
goto err1;
ret = finish_mem_reg(mhp, stag);
if (ret)
goto err2;
return &mhp->ibmr;
err2:
dereg_mem(&rhp->rdev, mhp->attr.stag, mhp->attr.pbl_size,
mhp->attr.pbl_addr);
err1:
kfree(mhp);
return ERR_PTR(ret);
}
struct ib_mr *c4iw_reg_user_mr(struct ib_pd *pd, u64 start, u64 length,
u64 virt, int acc, struct ib_udata *udata)
{
__be64 *pages;
int shift, n, len;
int i, j, k;
int err = 0;
struct ib_umem_chunk *chunk;
struct c4iw_dev *rhp;
struct c4iw_pd *php;
struct c4iw_mr *mhp;
PDBG("%s ib_pd %p\n", __func__, pd);
if (length == ~0ULL)
return ERR_PTR(-EINVAL);
if ((length + start) < start)
return ERR_PTR(-EINVAL);
php = to_c4iw_pd(pd);
rhp = php->rhp;
mhp = kzalloc(sizeof(*mhp), GFP_KERNEL);
if (!mhp)
return ERR_PTR(-ENOMEM);
mhp->rhp = rhp;
mhp->umem = ib_umem_get(pd->uobject->context, start, length, acc, 0);
if (IS_ERR(mhp->umem)) {
err = PTR_ERR(mhp->umem);
kfree(mhp);
return ERR_PTR(err);
}
shift = ffs(mhp->umem->page_size) - 1;
n = 0;
list_for_each_entry(chunk, &mhp->umem->chunk_list, list)
n += chunk->nents;
err = alloc_pbl(mhp, n);
if (err)
goto err;
pages = (__be64 *) __get_free_page(GFP_KERNEL);
if (!pages) {
err = -ENOMEM;
goto err_pbl;
}
i = n = 0;
list_for_each_entry(chunk, &mhp->umem->chunk_list, list)
for (j = 0; j < chunk->nmap; ++j) {
len = sg_dma_len(&chunk->page_list[j]) >> shift;
for (k = 0; k < len; ++k) {
pages[i++] = cpu_to_be64(sg_dma_address(
&chunk->page_list[j]) +
mhp->umem->page_size * k);
if (i == PAGE_SIZE / sizeof *pages) {
err = write_pbl(&mhp->rhp->rdev,
pages,
mhp->attr.pbl_addr + (n << 3), i);
if (err)
goto pbl_done;
n += i;
i = 0;
}
}
}
if (i)
err = write_pbl(&mhp->rhp->rdev, pages,
mhp->attr.pbl_addr + (n << 3), i);
pbl_done:
free_page((unsigned long) pages);
if (err)
goto err_pbl;
mhp->attr.pdid = php->pdid;
mhp->attr.zbva = 0;
mhp->attr.perms = c4iw_ib_to_tpt_access(acc);
mhp->attr.va_fbo = virt;
mhp->attr.page_size = shift - 12;
mhp->attr.len = length;
err = register_mem(rhp, php, mhp, shift);
if (err)
goto err_pbl;
return &mhp->ibmr;
err_pbl:
c4iw_pblpool_free(&mhp->rhp->rdev, mhp->attr.pbl_addr,
mhp->attr.pbl_size << 3);
err:
ib_umem_release(mhp->umem);
kfree(mhp);
return ERR_PTR(err);
}
struct ib_mw *c4iw_alloc_mw(struct ib_pd *pd)
{
struct c4iw_dev *rhp;
struct c4iw_pd *php;
struct c4iw_mw *mhp;
u32 mmid;
u32 stag = 0;
int ret;
php = to_c4iw_pd(pd);
rhp = php->rhp;
mhp = kzalloc(sizeof(*mhp), GFP_KERNEL);
if (!mhp)
return ERR_PTR(-ENOMEM);
ret = allocate_window(&rhp->rdev, &stag, php->pdid);
if (ret) {
kfree(mhp);
return ERR_PTR(ret);
}
mhp->rhp = rhp;
mhp->attr.pdid = php->pdid;
mhp->attr.type = FW_RI_STAG_MW;
mhp->attr.stag = stag;
mmid = (stag) >> 8;
mhp->ibmw.rkey = stag;
if (insert_handle(rhp, &rhp->mmidr, mhp, mmid)) {
deallocate_window(&rhp->rdev, mhp->attr.stag);
kfree(mhp);
return ERR_PTR(-ENOMEM);
}
PDBG("%s mmid 0x%x mhp %p stag 0x%x\n", __func__, mmid, mhp, stag);
return &(mhp->ibmw);
}
int c4iw_dealloc_mw(struct ib_mw *mw)
{
struct c4iw_dev *rhp;
struct c4iw_mw *mhp;
u32 mmid;
mhp = to_c4iw_mw(mw);
rhp = mhp->rhp;
mmid = (mw->rkey) >> 8;
deallocate_window(&rhp->rdev, mhp->attr.stag);
remove_handle(rhp, &rhp->mmidr, mmid);
kfree(mhp);
PDBG("%s ib_mw %p mmid 0x%x ptr %p\n", __func__, mw, mmid, mhp);
return 0;
}
struct ib_mr *c4iw_alloc_fast_reg_mr(struct ib_pd *pd, int pbl_depth)
{
struct c4iw_dev *rhp;
struct c4iw_pd *php;
struct c4iw_mr *mhp;
u32 mmid;
u32 stag = 0;
int ret = 0;
php = to_c4iw_pd(pd);
rhp = php->rhp;
mhp = kzalloc(sizeof(*mhp), GFP_KERNEL);
if (!mhp) {
ret = -ENOMEM;
goto err;
}
mhp->rhp = rhp;
ret = alloc_pbl(mhp, pbl_depth);
if (ret)
goto err1;
mhp->attr.pbl_size = pbl_depth;
ret = allocate_stag(&rhp->rdev, &stag, php->pdid,
mhp->attr.pbl_size, mhp->attr.pbl_addr);
if (ret)
goto err2;
mhp->attr.pdid = php->pdid;
mhp->attr.type = FW_RI_STAG_NSMR;
mhp->attr.stag = stag;
mhp->attr.state = 1;
mmid = (stag) >> 8;
mhp->ibmr.rkey = mhp->ibmr.lkey = stag;
if (insert_handle(rhp, &rhp->mmidr, mhp, mmid)) {
ret = -ENOMEM;
goto err3;
}
PDBG("%s mmid 0x%x mhp %p stag 0x%x\n", __func__, mmid, mhp, stag);
return &(mhp->ibmr);
err3:
dereg_mem(&rhp->rdev, stag, mhp->attr.pbl_size,
mhp->attr.pbl_addr);
err2:
c4iw_pblpool_free(&mhp->rhp->rdev, mhp->attr.pbl_addr,
mhp->attr.pbl_size << 3);
err1:
kfree(mhp);
err:
return ERR_PTR(ret);
}
struct ib_fast_reg_page_list *c4iw_alloc_fastreg_pbl(struct ib_device *device,
int page_list_len)
{
struct c4iw_fr_page_list *c4pl;
struct c4iw_dev *dev = to_c4iw_dev(device);
dma_addr_t dma_addr;
int size = sizeof *c4pl + page_list_len * sizeof(u64);
c4pl = dma_alloc_coherent(&dev->rdev.lldi.pdev->dev, size,
&dma_addr, GFP_KERNEL);
if (!c4pl)
return ERR_PTR(-ENOMEM);
dma_unmap_addr_set(c4pl, mapping, dma_addr);
c4pl->dma_addr = dma_addr;
c4pl->dev = dev;
c4pl->size = size;
c4pl->ibpl.page_list = (u64 *)(c4pl + 1);
c4pl->ibpl.max_page_list_len = page_list_len;
return &c4pl->ibpl;
}
void c4iw_free_fastreg_pbl(struct ib_fast_reg_page_list *ibpl)
{
struct c4iw_fr_page_list *c4pl = to_c4iw_fr_page_list(ibpl);
dma_free_coherent(&c4pl->dev->rdev.lldi.pdev->dev, c4pl->size,
c4pl, dma_unmap_addr(c4pl, mapping));
}
int c4iw_dereg_mr(struct ib_mr *ib_mr)
{
struct c4iw_dev *rhp;
struct c4iw_mr *mhp;
u32 mmid;
PDBG("%s ib_mr %p\n", __func__, ib_mr);
/* There can be no memory windows */
if (atomic_read(&ib_mr->usecnt))
return -EINVAL;
mhp = to_c4iw_mr(ib_mr);
rhp = mhp->rhp;
mmid = mhp->attr.stag >> 8;
dereg_mem(&rhp->rdev, mhp->attr.stag, mhp->attr.pbl_size,
mhp->attr.pbl_addr);
if (mhp->attr.pbl_size)
c4iw_pblpool_free(&mhp->rhp->rdev, mhp->attr.pbl_addr,
mhp->attr.pbl_size << 3);
remove_handle(rhp, &rhp->mmidr, mmid);
if (mhp->kva)
kfree((void *) (unsigned long) mhp->kva);
if (mhp->umem)
ib_umem_release(mhp->umem);
PDBG("%s mmid 0x%x ptr %p\n", __func__, mmid, mhp);
kfree(mhp);
return 0;
}
| gpl-2.0 |
utkanos/android_tuna_omap_kernel | arch/xtensa/variants/s6000/gpio.c | 7518 | 5627 | /*
* s6000 gpio driver
*
* Copyright (c) 2009 emlix GmbH
* Authors: Oskar Schirmer <os@emlix.com>
* Johannes Weiner <jw@emlix.com>
* Daniel Gloeckner <dg@emlix.com>
*/
#include <linux/bitops.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/gpio.h>
#include <variant/hardware.h>
#define IRQ_BASE XTENSA_NR_IRQS
#define S6_GPIO_DATA 0x000
#define S6_GPIO_IS 0x404
#define S6_GPIO_IBE 0x408
#define S6_GPIO_IEV 0x40C
#define S6_GPIO_IE 0x410
#define S6_GPIO_RIS 0x414
#define S6_GPIO_MIS 0x418
#define S6_GPIO_IC 0x41C
#define S6_GPIO_AFSEL 0x420
#define S6_GPIO_DIR 0x800
#define S6_GPIO_BANK(nr) ((nr) * 0x1000)
#define S6_GPIO_MASK(nr) (4 << (nr))
#define S6_GPIO_OFFSET(nr) \
(S6_GPIO_BANK((nr) >> 3) + S6_GPIO_MASK((nr) & 7))
static int direction_input(struct gpio_chip *chip, unsigned int off)
{
writeb(0, S6_REG_GPIO + S6_GPIO_DIR + S6_GPIO_OFFSET(off));
return 0;
}
static int get(struct gpio_chip *chip, unsigned int off)
{
return readb(S6_REG_GPIO + S6_GPIO_DATA + S6_GPIO_OFFSET(off));
}
static int direction_output(struct gpio_chip *chip, unsigned int off, int val)
{
unsigned rel = S6_GPIO_OFFSET(off);
writeb(~0, S6_REG_GPIO + S6_GPIO_DIR + rel);
writeb(val ? ~0 : 0, S6_REG_GPIO + S6_GPIO_DATA + rel);
return 0;
}
static void set(struct gpio_chip *chip, unsigned int off, int val)
{
writeb(val ? ~0 : 0, S6_REG_GPIO + S6_GPIO_DATA + S6_GPIO_OFFSET(off));
}
static int to_irq(struct gpio_chip *chip, unsigned offset)
{
if (offset < 8)
return offset + IRQ_BASE;
return -EINVAL;
}
static struct gpio_chip gpiochip = {
.owner = THIS_MODULE,
.direction_input = direction_input,
.get = get,
.direction_output = direction_output,
.set = set,
.to_irq = to_irq,
.base = 0,
.ngpio = 24,
.can_sleep = 0, /* no blocking io needed */
.exported = 0, /* no exporting to userspace */
};
int s6_gpio_init(u32 afsel)
{
writeb(afsel, S6_REG_GPIO + S6_GPIO_BANK(0) + S6_GPIO_AFSEL);
writeb(afsel >> 8, S6_REG_GPIO + S6_GPIO_BANK(1) + S6_GPIO_AFSEL);
writeb(afsel >> 16, S6_REG_GPIO + S6_GPIO_BANK(2) + S6_GPIO_AFSEL);
return gpiochip_add(&gpiochip);
}
static void ack(struct irq_data *d)
{
writeb(1 << (d->irq - IRQ_BASE), S6_REG_GPIO + S6_GPIO_IC);
}
static void mask(struct irq_data *d)
{
u8 r = readb(S6_REG_GPIO + S6_GPIO_IE);
r &= ~(1 << (d->irq - IRQ_BASE));
writeb(r, S6_REG_GPIO + S6_GPIO_IE);
}
static void unmask(struct irq_data *d)
{
u8 m = readb(S6_REG_GPIO + S6_GPIO_IE);
m |= 1 << (d->irq - IRQ_BASE);
writeb(m, S6_REG_GPIO + S6_GPIO_IE);
}
static int set_type(struct irq_data *d, unsigned int type)
{
const u8 m = 1 << (d->irq - IRQ_BASE);
irq_flow_handler_t handler;
u8 reg;
if (type == IRQ_TYPE_PROBE) {
if ((readb(S6_REG_GPIO + S6_GPIO_BANK(0) + S6_GPIO_AFSEL) & m)
|| (readb(S6_REG_GPIO + S6_GPIO_BANK(0) + S6_GPIO_IE) & m)
|| readb(S6_REG_GPIO + S6_GPIO_BANK(0) + S6_GPIO_DIR
+ S6_GPIO_MASK(irq - IRQ_BASE)))
return 0;
type = IRQ_TYPE_EDGE_BOTH;
}
reg = readb(S6_REG_GPIO + S6_GPIO_BANK(0) + S6_GPIO_IS);
if (type & (IRQ_TYPE_LEVEL_LOW | IRQ_TYPE_LEVEL_HIGH)) {
reg |= m;
handler = handle_level_irq;
} else {
reg &= ~m;
handler = handle_edge_irq;
}
writeb(reg, S6_REG_GPIO + S6_GPIO_BANK(0) + S6_GPIO_IS);
__irq_set_handler_locked(irq, handler);
reg = readb(S6_REG_GPIO + S6_GPIO_BANK(0) + S6_GPIO_IEV);
if (type & (IRQ_TYPE_LEVEL_HIGH | IRQ_TYPE_EDGE_RISING))
reg |= m;
else
reg &= ~m;
writeb(reg, S6_REG_GPIO + S6_GPIO_BANK(0) + S6_GPIO_IEV);
reg = readb(S6_REG_GPIO + S6_GPIO_BANK(0) + S6_GPIO_IBE);
if ((type & IRQ_TYPE_EDGE_BOTH) == IRQ_TYPE_EDGE_BOTH)
reg |= m;
else
reg &= ~m;
writeb(reg, S6_REG_GPIO + S6_GPIO_BANK(0) + S6_GPIO_IBE);
return 0;
}
static struct irq_chip gpioirqs = {
.name = "GPIO",
.irq_ack = ack,
.irq_mask = mask,
.irq_unmask = unmask,
.irq_set_type = set_type,
};
static u8 demux_masks[4];
static void demux_irqs(unsigned int irq, struct irq_desc *desc)
{
struct irq_chip *chip = irq_desc_get_chip(desc);
u8 *mask = irq_desc_get_handler_data(desc);
u8 pending;
int cirq;
chip->irq_mask(&desc->irq_data);
chip->irq_ack(&desc->irq_data));
pending = readb(S6_REG_GPIO + S6_GPIO_BANK(0) + S6_GPIO_MIS) & *mask;
cirq = IRQ_BASE - 1;
while (pending) {
int n = ffs(pending);
cirq += n;
pending >>= n;
generic_handle_irq(cirq);
}
chip->irq_unmask(&desc->irq_data));
}
extern const signed char *platform_irq_mappings[XTENSA_NR_IRQS];
void __init variant_init_irq(void)
{
int irq, n;
writeb(0, S6_REG_GPIO + S6_GPIO_BANK(0) + S6_GPIO_IE);
for (irq = n = 0; irq < XTENSA_NR_IRQS; irq++) {
const signed char *mapping = platform_irq_mappings[irq];
int alone = 1;
u8 mask;
if (!mapping)
continue;
for(mask = 0; *mapping != -1; mapping++)
switch (*mapping) {
case S6_INTC_GPIO(0):
mask |= 1 << 0;
break;
case S6_INTC_GPIO(1):
mask |= 1 << 1;
break;
case S6_INTC_GPIO(2):
mask |= 1 << 2;
break;
case S6_INTC_GPIO(3):
mask |= 0x1f << 3;
break;
default:
alone = 0;
}
if (mask) {
int cirq, i;
if (!alone) {
printk(KERN_ERR "chained irq chips can't share"
" parent irq %i\n", irq);
continue;
}
demux_masks[n] = mask;
cirq = IRQ_BASE - 1;
do {
i = ffs(mask);
cirq += i;
mask >>= i;
irq_set_chip(cirq, &gpioirqs);
irq_set_irq_type(irq, IRQ_TYPE_LEVEL_LOW);
} while (mask);
irq_set_handler_data(irq, demux_masks + n);
irq_set_chained_handler(irq, demux_irqs);
if (++n == ARRAY_SIZE(demux_masks))
break;
}
}
}
| gpl-2.0 |
CyanogenMod/android_kernel_asus_tf701t | crypto/ctr.c | 8542 | 11063 | /*
* CTR: Counter mode
*
* (C) Copyright IBM Corp. 2007 - Joy Latten <latten@us.ibm.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
*/
#include <crypto/algapi.h>
#include <crypto/ctr.h>
#include <linux/err.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/random.h>
#include <linux/scatterlist.h>
#include <linux/slab.h>
struct crypto_ctr_ctx {
struct crypto_cipher *child;
};
struct crypto_rfc3686_ctx {
struct crypto_blkcipher *child;
u8 nonce[CTR_RFC3686_NONCE_SIZE];
};
static int crypto_ctr_setkey(struct crypto_tfm *parent, const u8 *key,
unsigned int keylen)
{
struct crypto_ctr_ctx *ctx = crypto_tfm_ctx(parent);
struct crypto_cipher *child = ctx->child;
int err;
crypto_cipher_clear_flags(child, CRYPTO_TFM_REQ_MASK);
crypto_cipher_set_flags(child, crypto_tfm_get_flags(parent) &
CRYPTO_TFM_REQ_MASK);
err = crypto_cipher_setkey(child, key, keylen);
crypto_tfm_set_flags(parent, crypto_cipher_get_flags(child) &
CRYPTO_TFM_RES_MASK);
return err;
}
static void crypto_ctr_crypt_final(struct blkcipher_walk *walk,
struct crypto_cipher *tfm)
{
unsigned int bsize = crypto_cipher_blocksize(tfm);
unsigned long alignmask = crypto_cipher_alignmask(tfm);
u8 *ctrblk = walk->iv;
u8 tmp[bsize + alignmask];
u8 *keystream = PTR_ALIGN(tmp + 0, alignmask + 1);
u8 *src = walk->src.virt.addr;
u8 *dst = walk->dst.virt.addr;
unsigned int nbytes = walk->nbytes;
crypto_cipher_encrypt_one(tfm, keystream, ctrblk);
crypto_xor(keystream, src, nbytes);
memcpy(dst, keystream, nbytes);
crypto_inc(ctrblk, bsize);
}
static int crypto_ctr_crypt_segment(struct blkcipher_walk *walk,
struct crypto_cipher *tfm)
{
void (*fn)(struct crypto_tfm *, u8 *, const u8 *) =
crypto_cipher_alg(tfm)->cia_encrypt;
unsigned int bsize = crypto_cipher_blocksize(tfm);
u8 *ctrblk = walk->iv;
u8 *src = walk->src.virt.addr;
u8 *dst = walk->dst.virt.addr;
unsigned int nbytes = walk->nbytes;
do {
/* create keystream */
fn(crypto_cipher_tfm(tfm), dst, ctrblk);
crypto_xor(dst, src, bsize);
/* increment counter in counterblock */
crypto_inc(ctrblk, bsize);
src += bsize;
dst += bsize;
} while ((nbytes -= bsize) >= bsize);
return nbytes;
}
static int crypto_ctr_crypt_inplace(struct blkcipher_walk *walk,
struct crypto_cipher *tfm)
{
void (*fn)(struct crypto_tfm *, u8 *, const u8 *) =
crypto_cipher_alg(tfm)->cia_encrypt;
unsigned int bsize = crypto_cipher_blocksize(tfm);
unsigned long alignmask = crypto_cipher_alignmask(tfm);
unsigned int nbytes = walk->nbytes;
u8 *ctrblk = walk->iv;
u8 *src = walk->src.virt.addr;
u8 tmp[bsize + alignmask];
u8 *keystream = PTR_ALIGN(tmp + 0, alignmask + 1);
do {
/* create keystream */
fn(crypto_cipher_tfm(tfm), keystream, ctrblk);
crypto_xor(src, keystream, bsize);
/* increment counter in counterblock */
crypto_inc(ctrblk, bsize);
src += bsize;
} while ((nbytes -= bsize) >= bsize);
return nbytes;
}
static int crypto_ctr_crypt(struct blkcipher_desc *desc,
struct scatterlist *dst, struct scatterlist *src,
unsigned int nbytes)
{
struct blkcipher_walk walk;
struct crypto_blkcipher *tfm = desc->tfm;
struct crypto_ctr_ctx *ctx = crypto_blkcipher_ctx(tfm);
struct crypto_cipher *child = ctx->child;
unsigned int bsize = crypto_cipher_blocksize(child);
int err;
blkcipher_walk_init(&walk, dst, src, nbytes);
err = blkcipher_walk_virt_block(desc, &walk, bsize);
while (walk.nbytes >= bsize) {
if (walk.src.virt.addr == walk.dst.virt.addr)
nbytes = crypto_ctr_crypt_inplace(&walk, child);
else
nbytes = crypto_ctr_crypt_segment(&walk, child);
err = blkcipher_walk_done(desc, &walk, nbytes);
}
if (walk.nbytes) {
crypto_ctr_crypt_final(&walk, child);
err = blkcipher_walk_done(desc, &walk, 0);
}
return err;
}
static int crypto_ctr_init_tfm(struct crypto_tfm *tfm)
{
struct crypto_instance *inst = (void *)tfm->__crt_alg;
struct crypto_spawn *spawn = crypto_instance_ctx(inst);
struct crypto_ctr_ctx *ctx = crypto_tfm_ctx(tfm);
struct crypto_cipher *cipher;
cipher = crypto_spawn_cipher(spawn);
if (IS_ERR(cipher))
return PTR_ERR(cipher);
ctx->child = cipher;
return 0;
}
static void crypto_ctr_exit_tfm(struct crypto_tfm *tfm)
{
struct crypto_ctr_ctx *ctx = crypto_tfm_ctx(tfm);
crypto_free_cipher(ctx->child);
}
static struct crypto_instance *crypto_ctr_alloc(struct rtattr **tb)
{
struct crypto_instance *inst;
struct crypto_alg *alg;
int err;
err = crypto_check_attr_type(tb, CRYPTO_ALG_TYPE_BLKCIPHER);
if (err)
return ERR_PTR(err);
alg = crypto_attr_alg(tb[1], CRYPTO_ALG_TYPE_CIPHER,
CRYPTO_ALG_TYPE_MASK);
if (IS_ERR(alg))
return ERR_CAST(alg);
/* Block size must be >= 4 bytes. */
err = -EINVAL;
if (alg->cra_blocksize < 4)
goto out_put_alg;
/* If this is false we'd fail the alignment of crypto_inc. */
if (alg->cra_blocksize % 4)
goto out_put_alg;
inst = crypto_alloc_instance("ctr", alg);
if (IS_ERR(inst))
goto out;
inst->alg.cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER;
inst->alg.cra_priority = alg->cra_priority;
inst->alg.cra_blocksize = 1;
inst->alg.cra_alignmask = alg->cra_alignmask | (__alignof__(u32) - 1);
inst->alg.cra_type = &crypto_blkcipher_type;
inst->alg.cra_blkcipher.ivsize = alg->cra_blocksize;
inst->alg.cra_blkcipher.min_keysize = alg->cra_cipher.cia_min_keysize;
inst->alg.cra_blkcipher.max_keysize = alg->cra_cipher.cia_max_keysize;
inst->alg.cra_ctxsize = sizeof(struct crypto_ctr_ctx);
inst->alg.cra_init = crypto_ctr_init_tfm;
inst->alg.cra_exit = crypto_ctr_exit_tfm;
inst->alg.cra_blkcipher.setkey = crypto_ctr_setkey;
inst->alg.cra_blkcipher.encrypt = crypto_ctr_crypt;
inst->alg.cra_blkcipher.decrypt = crypto_ctr_crypt;
inst->alg.cra_blkcipher.geniv = "chainiv";
out:
crypto_mod_put(alg);
return inst;
out_put_alg:
inst = ERR_PTR(err);
goto out;
}
static void crypto_ctr_free(struct crypto_instance *inst)
{
crypto_drop_spawn(crypto_instance_ctx(inst));
kfree(inst);
}
static struct crypto_template crypto_ctr_tmpl = {
.name = "ctr",
.alloc = crypto_ctr_alloc,
.free = crypto_ctr_free,
.module = THIS_MODULE,
};
static int crypto_rfc3686_setkey(struct crypto_tfm *parent, const u8 *key,
unsigned int keylen)
{
struct crypto_rfc3686_ctx *ctx = crypto_tfm_ctx(parent);
struct crypto_blkcipher *child = ctx->child;
int err;
/* the nonce is stored in bytes at end of key */
if (keylen < CTR_RFC3686_NONCE_SIZE)
return -EINVAL;
memcpy(ctx->nonce, key + (keylen - CTR_RFC3686_NONCE_SIZE),
CTR_RFC3686_NONCE_SIZE);
keylen -= CTR_RFC3686_NONCE_SIZE;
crypto_blkcipher_clear_flags(child, CRYPTO_TFM_REQ_MASK);
crypto_blkcipher_set_flags(child, crypto_tfm_get_flags(parent) &
CRYPTO_TFM_REQ_MASK);
err = crypto_blkcipher_setkey(child, key, keylen);
crypto_tfm_set_flags(parent, crypto_blkcipher_get_flags(child) &
CRYPTO_TFM_RES_MASK);
return err;
}
static int crypto_rfc3686_crypt(struct blkcipher_desc *desc,
struct scatterlist *dst,
struct scatterlist *src, unsigned int nbytes)
{
struct crypto_blkcipher *tfm = desc->tfm;
struct crypto_rfc3686_ctx *ctx = crypto_blkcipher_ctx(tfm);
struct crypto_blkcipher *child = ctx->child;
unsigned long alignmask = crypto_blkcipher_alignmask(tfm);
u8 ivblk[CTR_RFC3686_BLOCK_SIZE + alignmask];
u8 *iv = PTR_ALIGN(ivblk + 0, alignmask + 1);
u8 *info = desc->info;
int err;
/* set up counter block */
memcpy(iv, ctx->nonce, CTR_RFC3686_NONCE_SIZE);
memcpy(iv + CTR_RFC3686_NONCE_SIZE, info, CTR_RFC3686_IV_SIZE);
/* initialize counter portion of counter block */
*(__be32 *)(iv + CTR_RFC3686_NONCE_SIZE + CTR_RFC3686_IV_SIZE) =
cpu_to_be32(1);
desc->tfm = child;
desc->info = iv;
err = crypto_blkcipher_encrypt_iv(desc, dst, src, nbytes);
desc->tfm = tfm;
desc->info = info;
return err;
}
static int crypto_rfc3686_init_tfm(struct crypto_tfm *tfm)
{
struct crypto_instance *inst = (void *)tfm->__crt_alg;
struct crypto_spawn *spawn = crypto_instance_ctx(inst);
struct crypto_rfc3686_ctx *ctx = crypto_tfm_ctx(tfm);
struct crypto_blkcipher *cipher;
cipher = crypto_spawn_blkcipher(spawn);
if (IS_ERR(cipher))
return PTR_ERR(cipher);
ctx->child = cipher;
return 0;
}
static void crypto_rfc3686_exit_tfm(struct crypto_tfm *tfm)
{
struct crypto_rfc3686_ctx *ctx = crypto_tfm_ctx(tfm);
crypto_free_blkcipher(ctx->child);
}
static struct crypto_instance *crypto_rfc3686_alloc(struct rtattr **tb)
{
struct crypto_instance *inst;
struct crypto_alg *alg;
int err;
err = crypto_check_attr_type(tb, CRYPTO_ALG_TYPE_BLKCIPHER);
if (err)
return ERR_PTR(err);
alg = crypto_attr_alg(tb[1], CRYPTO_ALG_TYPE_BLKCIPHER,
CRYPTO_ALG_TYPE_MASK);
err = PTR_ERR(alg);
if (IS_ERR(alg))
return ERR_PTR(err);
/* We only support 16-byte blocks. */
err = -EINVAL;
if (alg->cra_blkcipher.ivsize != CTR_RFC3686_BLOCK_SIZE)
goto out_put_alg;
/* Not a stream cipher? */
if (alg->cra_blocksize != 1)
goto out_put_alg;
inst = crypto_alloc_instance("rfc3686", alg);
if (IS_ERR(inst))
goto out;
inst->alg.cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER;
inst->alg.cra_priority = alg->cra_priority;
inst->alg.cra_blocksize = 1;
inst->alg.cra_alignmask = alg->cra_alignmask;
inst->alg.cra_type = &crypto_blkcipher_type;
inst->alg.cra_blkcipher.ivsize = CTR_RFC3686_IV_SIZE;
inst->alg.cra_blkcipher.min_keysize = alg->cra_blkcipher.min_keysize
+ CTR_RFC3686_NONCE_SIZE;
inst->alg.cra_blkcipher.max_keysize = alg->cra_blkcipher.max_keysize
+ CTR_RFC3686_NONCE_SIZE;
inst->alg.cra_blkcipher.geniv = "seqiv";
inst->alg.cra_ctxsize = sizeof(struct crypto_rfc3686_ctx);
inst->alg.cra_init = crypto_rfc3686_init_tfm;
inst->alg.cra_exit = crypto_rfc3686_exit_tfm;
inst->alg.cra_blkcipher.setkey = crypto_rfc3686_setkey;
inst->alg.cra_blkcipher.encrypt = crypto_rfc3686_crypt;
inst->alg.cra_blkcipher.decrypt = crypto_rfc3686_crypt;
out:
crypto_mod_put(alg);
return inst;
out_put_alg:
inst = ERR_PTR(err);
goto out;
}
static struct crypto_template crypto_rfc3686_tmpl = {
.name = "rfc3686",
.alloc = crypto_rfc3686_alloc,
.free = crypto_ctr_free,
.module = THIS_MODULE,
};
static int __init crypto_ctr_module_init(void)
{
int err;
err = crypto_register_template(&crypto_ctr_tmpl);
if (err)
goto out;
err = crypto_register_template(&crypto_rfc3686_tmpl);
if (err)
goto out_drop_ctr;
out:
return err;
out_drop_ctr:
crypto_unregister_template(&crypto_ctr_tmpl);
goto out;
}
static void __exit crypto_ctr_module_exit(void)
{
crypto_unregister_template(&crypto_rfc3686_tmpl);
crypto_unregister_template(&crypto_ctr_tmpl);
}
module_init(crypto_ctr_module_init);
module_exit(crypto_ctr_module_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("CTR Counter block mode");
MODULE_ALIAS("rfc3686");
| gpl-2.0 |
perillamint/garlickernel-lgog | drivers/misc/enclosure.c | 8798 | 15821 | /*
* Enclosure Services
*
* Copyright (C) 2008 James Bottomley <James.Bottomley@HansenPartnership.com>
*
**-----------------------------------------------------------------------------
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the GNU General Public License
** 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., 675 Mass Ave, Cambridge, MA 02139, USA.
**
**-----------------------------------------------------------------------------
*/
#include <linux/device.h>
#include <linux/enclosure.h>
#include <linux/err.h>
#include <linux/list.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/slab.h>
static LIST_HEAD(container_list);
static DEFINE_MUTEX(container_list_lock);
static struct class enclosure_class;
/**
* enclosure_find - find an enclosure given a parent device
* @dev: the parent to match against
* @start: Optional enclosure device to start from (NULL if none)
*
* Looks through the list of registered enclosures to find all those
* with @dev as a parent. Returns NULL if no enclosure is
* found. @start can be used as a starting point to obtain multiple
* enclosures per parent (should begin with NULL and then be set to
* each returned enclosure device). Obtains a reference to the
* enclosure class device which must be released with device_put().
* If @start is not NULL, a reference must be taken on it which is
* released before returning (this allows a loop through all
* enclosures to exit with only the reference on the enclosure of
* interest held). Note that the @dev may correspond to the actual
* device housing the enclosure, in which case no iteration via @start
* is required.
*/
struct enclosure_device *enclosure_find(struct device *dev,
struct enclosure_device *start)
{
struct enclosure_device *edev;
mutex_lock(&container_list_lock);
edev = list_prepare_entry(start, &container_list, node);
if (start)
put_device(&start->edev);
list_for_each_entry_continue(edev, &container_list, node) {
struct device *parent = edev->edev.parent;
/* parent might not be immediate, so iterate up to
* the root of the tree if necessary */
while (parent) {
if (parent == dev) {
get_device(&edev->edev);
mutex_unlock(&container_list_lock);
return edev;
}
parent = parent->parent;
}
}
mutex_unlock(&container_list_lock);
return NULL;
}
EXPORT_SYMBOL_GPL(enclosure_find);
/**
* enclosure_for_each_device - calls a function for each enclosure
* @fn: the function to call
* @data: the data to pass to each call
*
* Loops over all the enclosures calling the function.
*
* Note, this function uses a mutex which will be held across calls to
* @fn, so it must have non atomic context, and @fn may (although it
* should not) sleep or otherwise cause the mutex to be held for
* indefinite periods
*/
int enclosure_for_each_device(int (*fn)(struct enclosure_device *, void *),
void *data)
{
int error = 0;
struct enclosure_device *edev;
mutex_lock(&container_list_lock);
list_for_each_entry(edev, &container_list, node) {
error = fn(edev, data);
if (error)
break;
}
mutex_unlock(&container_list_lock);
return error;
}
EXPORT_SYMBOL_GPL(enclosure_for_each_device);
/**
* enclosure_register - register device as an enclosure
*
* @dev: device containing the enclosure
* @components: number of components in the enclosure
*
* This sets up the device for being an enclosure. Note that @dev does
* not have to be a dedicated enclosure device. It may be some other type
* of device that additionally responds to enclosure services
*/
struct enclosure_device *
enclosure_register(struct device *dev, const char *name, int components,
struct enclosure_component_callbacks *cb)
{
struct enclosure_device *edev =
kzalloc(sizeof(struct enclosure_device) +
sizeof(struct enclosure_component)*components,
GFP_KERNEL);
int err, i;
BUG_ON(!cb);
if (!edev)
return ERR_PTR(-ENOMEM);
edev->components = components;
edev->edev.class = &enclosure_class;
edev->edev.parent = get_device(dev);
edev->cb = cb;
dev_set_name(&edev->edev, "%s", name);
err = device_register(&edev->edev);
if (err)
goto err;
for (i = 0; i < components; i++)
edev->component[i].number = -1;
mutex_lock(&container_list_lock);
list_add_tail(&edev->node, &container_list);
mutex_unlock(&container_list_lock);
return edev;
err:
put_device(edev->edev.parent);
kfree(edev);
return ERR_PTR(err);
}
EXPORT_SYMBOL_GPL(enclosure_register);
static struct enclosure_component_callbacks enclosure_null_callbacks;
/**
* enclosure_unregister - remove an enclosure
*
* @edev: the registered enclosure to remove;
*/
void enclosure_unregister(struct enclosure_device *edev)
{
int i;
mutex_lock(&container_list_lock);
list_del(&edev->node);
mutex_unlock(&container_list_lock);
for (i = 0; i < edev->components; i++)
if (edev->component[i].number != -1)
device_unregister(&edev->component[i].cdev);
/* prevent any callbacks into service user */
edev->cb = &enclosure_null_callbacks;
device_unregister(&edev->edev);
}
EXPORT_SYMBOL_GPL(enclosure_unregister);
#define ENCLOSURE_NAME_SIZE 64
static void enclosure_link_name(struct enclosure_component *cdev, char *name)
{
strcpy(name, "enclosure_device:");
strcat(name, dev_name(&cdev->cdev));
}
static void enclosure_remove_links(struct enclosure_component *cdev)
{
char name[ENCLOSURE_NAME_SIZE];
enclosure_link_name(cdev, name);
sysfs_remove_link(&cdev->dev->kobj, name);
sysfs_remove_link(&cdev->cdev.kobj, "device");
}
static int enclosure_add_links(struct enclosure_component *cdev)
{
int error;
char name[ENCLOSURE_NAME_SIZE];
error = sysfs_create_link(&cdev->cdev.kobj, &cdev->dev->kobj, "device");
if (error)
return error;
enclosure_link_name(cdev, name);
error = sysfs_create_link(&cdev->dev->kobj, &cdev->cdev.kobj, name);
if (error)
sysfs_remove_link(&cdev->cdev.kobj, "device");
return error;
}
static void enclosure_release(struct device *cdev)
{
struct enclosure_device *edev = to_enclosure_device(cdev);
put_device(cdev->parent);
kfree(edev);
}
static void enclosure_component_release(struct device *dev)
{
struct enclosure_component *cdev = to_enclosure_component(dev);
if (cdev->dev) {
enclosure_remove_links(cdev);
put_device(cdev->dev);
}
put_device(dev->parent);
}
static const struct attribute_group *enclosure_groups[];
/**
* enclosure_component_register - add a particular component to an enclosure
* @edev: the enclosure to add the component
* @num: the device number
* @type: the type of component being added
* @name: an optional name to appear in sysfs (leave NULL if none)
*
* Registers the component. The name is optional for enclosures that
* give their components a unique name. If not, leave the field NULL
* and a name will be assigned.
*
* Returns a pointer to the enclosure component or an error.
*/
struct enclosure_component *
enclosure_component_register(struct enclosure_device *edev,
unsigned int number,
enum enclosure_component_type type,
const char *name)
{
struct enclosure_component *ecomp;
struct device *cdev;
int err;
if (number >= edev->components)
return ERR_PTR(-EINVAL);
ecomp = &edev->component[number];
if (ecomp->number != -1)
return ERR_PTR(-EINVAL);
ecomp->type = type;
ecomp->number = number;
cdev = &ecomp->cdev;
cdev->parent = get_device(&edev->edev);
if (name && name[0])
dev_set_name(cdev, "%s", name);
else
dev_set_name(cdev, "%u", number);
cdev->release = enclosure_component_release;
cdev->groups = enclosure_groups;
err = device_register(cdev);
if (err) {
ecomp->number = -1;
put_device(cdev);
return ERR_PTR(err);
}
return ecomp;
}
EXPORT_SYMBOL_GPL(enclosure_component_register);
/**
* enclosure_add_device - add a device as being part of an enclosure
* @edev: the enclosure device being added to.
* @num: the number of the component
* @dev: the device being added
*
* Declares a real device to reside in slot (or identifier) @num of an
* enclosure. This will cause the relevant sysfs links to appear.
* This function may also be used to change a device associated with
* an enclosure without having to call enclosure_remove_device() in
* between.
*
* Returns zero on success or an error.
*/
int enclosure_add_device(struct enclosure_device *edev, int component,
struct device *dev)
{
struct enclosure_component *cdev;
if (!edev || component >= edev->components)
return -EINVAL;
cdev = &edev->component[component];
if (cdev->dev == dev)
return -EEXIST;
if (cdev->dev)
enclosure_remove_links(cdev);
put_device(cdev->dev);
cdev->dev = get_device(dev);
return enclosure_add_links(cdev);
}
EXPORT_SYMBOL_GPL(enclosure_add_device);
/**
* enclosure_remove_device - remove a device from an enclosure
* @edev: the enclosure device
* @num: the number of the component to remove
*
* Returns zero on success or an error.
*
*/
int enclosure_remove_device(struct enclosure_device *edev, struct device *dev)
{
struct enclosure_component *cdev;
int i;
if (!edev || !dev)
return -EINVAL;
for (i = 0; i < edev->components; i++) {
cdev = &edev->component[i];
if (cdev->dev == dev) {
enclosure_remove_links(cdev);
device_del(&cdev->cdev);
put_device(dev);
cdev->dev = NULL;
return device_add(&cdev->cdev);
}
}
return -ENODEV;
}
EXPORT_SYMBOL_GPL(enclosure_remove_device);
/*
* sysfs pieces below
*/
static ssize_t enclosure_show_components(struct device *cdev,
struct device_attribute *attr,
char *buf)
{
struct enclosure_device *edev = to_enclosure_device(cdev);
return snprintf(buf, 40, "%d\n", edev->components);
}
static struct device_attribute enclosure_attrs[] = {
__ATTR(components, S_IRUGO, enclosure_show_components, NULL),
__ATTR_NULL
};
static struct class enclosure_class = {
.name = "enclosure",
.owner = THIS_MODULE,
.dev_release = enclosure_release,
.dev_attrs = enclosure_attrs,
};
static const char *const enclosure_status [] = {
[ENCLOSURE_STATUS_UNSUPPORTED] = "unsupported",
[ENCLOSURE_STATUS_OK] = "OK",
[ENCLOSURE_STATUS_CRITICAL] = "critical",
[ENCLOSURE_STATUS_NON_CRITICAL] = "non-critical",
[ENCLOSURE_STATUS_UNRECOVERABLE] = "unrecoverable",
[ENCLOSURE_STATUS_NOT_INSTALLED] = "not installed",
[ENCLOSURE_STATUS_UNKNOWN] = "unknown",
[ENCLOSURE_STATUS_UNAVAILABLE] = "unavailable",
[ENCLOSURE_STATUS_MAX] = NULL,
};
static const char *const enclosure_type [] = {
[ENCLOSURE_COMPONENT_DEVICE] = "device",
[ENCLOSURE_COMPONENT_ARRAY_DEVICE] = "array device",
};
static ssize_t get_component_fault(struct device *cdev,
struct device_attribute *attr, char *buf)
{
struct enclosure_device *edev = to_enclosure_device(cdev->parent);
struct enclosure_component *ecomp = to_enclosure_component(cdev);
if (edev->cb->get_fault)
edev->cb->get_fault(edev, ecomp);
return snprintf(buf, 40, "%d\n", ecomp->fault);
}
static ssize_t set_component_fault(struct device *cdev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct enclosure_device *edev = to_enclosure_device(cdev->parent);
struct enclosure_component *ecomp = to_enclosure_component(cdev);
int val = simple_strtoul(buf, NULL, 0);
if (edev->cb->set_fault)
edev->cb->set_fault(edev, ecomp, val);
return count;
}
static ssize_t get_component_status(struct device *cdev,
struct device_attribute *attr,char *buf)
{
struct enclosure_device *edev = to_enclosure_device(cdev->parent);
struct enclosure_component *ecomp = to_enclosure_component(cdev);
if (edev->cb->get_status)
edev->cb->get_status(edev, ecomp);
return snprintf(buf, 40, "%s\n", enclosure_status[ecomp->status]);
}
static ssize_t set_component_status(struct device *cdev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct enclosure_device *edev = to_enclosure_device(cdev->parent);
struct enclosure_component *ecomp = to_enclosure_component(cdev);
int i;
for (i = 0; enclosure_status[i]; i++) {
if (strncmp(buf, enclosure_status[i],
strlen(enclosure_status[i])) == 0 &&
(buf[strlen(enclosure_status[i])] == '\n' ||
buf[strlen(enclosure_status[i])] == '\0'))
break;
}
if (enclosure_status[i] && edev->cb->set_status) {
edev->cb->set_status(edev, ecomp, i);
return count;
} else
return -EINVAL;
}
static ssize_t get_component_active(struct device *cdev,
struct device_attribute *attr, char *buf)
{
struct enclosure_device *edev = to_enclosure_device(cdev->parent);
struct enclosure_component *ecomp = to_enclosure_component(cdev);
if (edev->cb->get_active)
edev->cb->get_active(edev, ecomp);
return snprintf(buf, 40, "%d\n", ecomp->active);
}
static ssize_t set_component_active(struct device *cdev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct enclosure_device *edev = to_enclosure_device(cdev->parent);
struct enclosure_component *ecomp = to_enclosure_component(cdev);
int val = simple_strtoul(buf, NULL, 0);
if (edev->cb->set_active)
edev->cb->set_active(edev, ecomp, val);
return count;
}
static ssize_t get_component_locate(struct device *cdev,
struct device_attribute *attr, char *buf)
{
struct enclosure_device *edev = to_enclosure_device(cdev->parent);
struct enclosure_component *ecomp = to_enclosure_component(cdev);
if (edev->cb->get_locate)
edev->cb->get_locate(edev, ecomp);
return snprintf(buf, 40, "%d\n", ecomp->locate);
}
static ssize_t set_component_locate(struct device *cdev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct enclosure_device *edev = to_enclosure_device(cdev->parent);
struct enclosure_component *ecomp = to_enclosure_component(cdev);
int val = simple_strtoul(buf, NULL, 0);
if (edev->cb->set_locate)
edev->cb->set_locate(edev, ecomp, val);
return count;
}
static ssize_t get_component_type(struct device *cdev,
struct device_attribute *attr, char *buf)
{
struct enclosure_component *ecomp = to_enclosure_component(cdev);
return snprintf(buf, 40, "%s\n", enclosure_type[ecomp->type]);
}
static DEVICE_ATTR(fault, S_IRUGO | S_IWUSR, get_component_fault,
set_component_fault);
static DEVICE_ATTR(status, S_IRUGO | S_IWUSR, get_component_status,
set_component_status);
static DEVICE_ATTR(active, S_IRUGO | S_IWUSR, get_component_active,
set_component_active);
static DEVICE_ATTR(locate, S_IRUGO | S_IWUSR, get_component_locate,
set_component_locate);
static DEVICE_ATTR(type, S_IRUGO, get_component_type, NULL);
static struct attribute *enclosure_component_attrs[] = {
&dev_attr_fault.attr,
&dev_attr_status.attr,
&dev_attr_active.attr,
&dev_attr_locate.attr,
&dev_attr_type.attr,
NULL
};
static struct attribute_group enclosure_group = {
.attrs = enclosure_component_attrs,
};
static const struct attribute_group *enclosure_groups[] = {
&enclosure_group,
NULL
};
static int __init enclosure_init(void)
{
int err;
err = class_register(&enclosure_class);
if (err)
return err;
return 0;
}
static void __exit enclosure_exit(void)
{
class_unregister(&enclosure_class);
}
module_init(enclosure_init);
module_exit(enclosure_exit);
MODULE_AUTHOR("James Bottomley");
MODULE_DESCRIPTION("Enclosure Services");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
StarKissed/starkissed-kernel-ardbeg | sound/soc/codecs/dmic.c | 95 | 2633 | /*
* dmic.c -- SoC audio for Generic Digital MICs
*
* Author: Liam Girdwood <lrg@slimlogic.co.uk>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* 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/platform_device.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/soc.h>
#include <sound/soc-dapm.h>
static struct snd_soc_dai_driver dmic_dai = {
.name = "dmic-hifi",
.capture = {
.stream_name = "Capture",
.channels_min = 1,
.channels_max = 8,
.rates = SNDRV_PCM_RATE_CONTINUOUS
| SNDRV_PCM_RATE_8000
| SNDRV_PCM_RATE_16000
| SNDRV_PCM_RATE_44100
| SNDRV_PCM_RATE_48000,
.formats = SNDRV_PCM_FMTBIT_S32_LE
| SNDRV_PCM_FMTBIT_S24_LE
| SNDRV_PCM_FMTBIT_S16_LE
| SNDRV_PCM_FMTBIT_S20_3LE,
},
};
static const struct snd_soc_dapm_widget dmic_dapm_widgets[] = {
SND_SOC_DAPM_AIF_OUT("DMIC AIF", "Capture", 0,
SND_SOC_NOPM, 0, 0),
SND_SOC_DAPM_INPUT("DMic"),
};
static const struct snd_soc_dapm_route intercon[] = {
{"DMIC AIF", NULL, "DMic"},
};
static int dmic_probe(struct snd_soc_codec *codec)
{
struct snd_soc_dapm_context *dapm = &codec->dapm;
snd_soc_dapm_new_controls(dapm, dmic_dapm_widgets,
ARRAY_SIZE(dmic_dapm_widgets));
snd_soc_dapm_add_routes(dapm, intercon, ARRAY_SIZE(intercon));
snd_soc_dapm_new_widgets(dapm);
return 0;
}
static struct snd_soc_codec_driver soc_dmic = {
.probe = dmic_probe,
};
static int dmic_dev_probe(struct platform_device *pdev)
{
return snd_soc_register_codec(&pdev->dev,
&soc_dmic, &dmic_dai, 1);
}
static int dmic_dev_remove(struct platform_device *pdev)
{
snd_soc_unregister_codec(&pdev->dev);
return 0;
}
MODULE_ALIAS("platform:dmic-codec");
static struct platform_driver dmic_driver = {
.driver = {
.name = "dmic-codec",
.owner = THIS_MODULE,
},
.probe = dmic_dev_probe,
.remove = dmic_dev_remove,
};
module_platform_driver(dmic_driver);
MODULE_DESCRIPTION("Generic DMIC driver");
MODULE_AUTHOR("Liam Girdwood <lrg@slimlogic.co.uk>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
NewbyJE/android_kernel_samsung_msm8660-common | arch/arm/kernel/perf_event_msm_l2.c | 95 | 27134 | /*
* Copyright (c) 2011, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#ifdef CONFIG_ARCH_MSM8X60
#include <linux/irq.h>
#define MAX_BB_L2_PERIOD ((1ULL << 32) - 1)
#define MAX_BB_L2_CTRS 5
#define BB_L2CYCLE_CTR_BIT 31
#define BB_L2CYCLE_CTR_EVENT_IDX 4
#define BB_L2CYCLE_CTR_RAW_CODE 0xfe
#define SCORPIONL2_PMNC_E (1 << 0) /* Enable all counters */
#define SCORPION_L2_EVT_PREFIX 3
#define SCORPION_MAX_L2_REG 4
/*
* Lock to protect r/m/w sequences to the L2 PMU.
*/
DEFINE_RAW_SPINLOCK(bb_l2_pmu_lock);
static struct platform_device *bb_l2_pmu_device;
struct hw_bb_l2_pmu {
struct perf_event *events[MAX_BB_L2_CTRS];
unsigned long active_mask[BITS_TO_LONGS(MAX_BB_L2_CTRS)];
raw_spinlock_t lock;
};
struct hw_bb_l2_pmu hw_bb_l2_pmu;
struct bb_l2_scorp_evt {
u32 evt_type;
u32 val;
u8 grp;
u32 evt_type_act;
};
enum scorpion_perf_types {
SCORPIONL2_TOTAL_BANK_REQ = 0x90,
SCORPIONL2_DSIDE_READ = 0x91,
SCORPIONL2_DSIDE_WRITE = 0x92,
SCORPIONL2_ISIDE_READ = 0x93,
SCORPIONL2_L2CACHE_ISIDE_READ = 0x94,
SCORPIONL2_L2CACHE_BANK_REQ = 0x95,
SCORPIONL2_L2CACHE_DSIDE_READ = 0x96,
SCORPIONL2_L2CACHE_DSIDE_WRITE = 0x97,
SCORPIONL2_L2NOCACHE_DSIDE_WRITE = 0x98,
SCORPIONL2_L2NOCACHE_ISIDE_READ = 0x99,
SCORPIONL2_L2NOCACHE_TOTAL_REQ = 0x9a,
SCORPIONL2_L2NOCACHE_DSIDE_READ = 0x9b,
SCORPIONL2_DSIDE_READ_NOL1 = 0x9c,
SCORPIONL2_L2CACHE_WRITETHROUGH = 0x9d,
SCORPIONL2_BARRIERS = 0x9e,
SCORPIONL2_HARDWARE_TABLE_WALKS = 0x9f,
SCORPIONL2_MVA_POC = 0xa0,
SCORPIONL2_L2CACHE_HW_TABLE_WALKS = 0xa1,
SCORPIONL2_SETWAY_CACHE_OPS = 0xa2,
SCORPIONL2_DSIDE_WRITE_HITS = 0xa3,
SCORPIONL2_ISIDE_READ_HITS = 0xa4,
SCORPIONL2_CACHE_DSIDE_READ_NOL1 = 0xa5,
SCORPIONL2_TOTAL_CACHE_HITS = 0xa6,
SCORPIONL2_CACHE_MATCH_MISS = 0xa7,
SCORPIONL2_DREAD_HIT_L1_DATA = 0xa8,
SCORPIONL2_L2LINE_LOCKED = 0xa9,
SCORPIONL2_HW_TABLE_WALK_HIT = 0xaa,
SCORPIONL2_CACHE_MVA_POC = 0xab,
SCORPIONL2_L2ALLOC_DWRITE_MISS = 0xac,
SCORPIONL2_CORRECTED_TAG_ARRAY = 0xad,
SCORPIONL2_CORRECTED_DATA_ARRAY = 0xae,
SCORPIONL2_CORRECTED_REPLACEMENT_ARRAY = 0xaf,
SCORPIONL2_PMBUS_MPAAF = 0xb0,
SCORPIONL2_PMBUS_MPWDAF = 0xb1,
SCORPIONL2_PMBUS_MPBRT = 0xb2,
SCORPIONL2_CPU0_GRANT = 0xb3,
SCORPIONL2_CPU1_GRANT = 0xb4,
SCORPIONL2_CPU0_NOGRANT = 0xb5,
SCORPIONL2_CPU1_NOGRANT = 0xb6,
SCORPIONL2_CPU0_LOSING_ARB = 0xb7,
SCORPIONL2_CPU1_LOSING_ARB = 0xb8,
SCORPIONL2_SLAVEPORT_NOGRANT = 0xb9,
SCORPIONL2_SLAVEPORT_BPQ_FULL = 0xba,
SCORPIONL2_SLAVEPORT_LOSING_ARB = 0xbb,
SCORPIONL2_SLAVEPORT_GRANT = 0xbc,
SCORPIONL2_SLAVEPORT_GRANTLOCK = 0xbd,
SCORPIONL2_L2EM_STREX_PASS = 0xbe,
SCORPIONL2_L2EM_STREX_FAIL = 0xbf,
SCORPIONL2_LDREX_RESERVE_L2EM = 0xc0,
SCORPIONL2_SLAVEPORT_LDREX = 0xc1,
SCORPIONL2_CPU0_L2EM_CLEARED = 0xc2,
SCORPIONL2_CPU1_L2EM_CLEARED = 0xc3,
SCORPIONL2_SLAVEPORT_L2EM_CLEARED = 0xc4,
SCORPIONL2_CPU0_CLAMPED = 0xc5,
SCORPIONL2_CPU1_CLAMPED = 0xc6,
SCORPIONL2_CPU0_WAIT = 0xc7,
SCORPIONL2_CPU1_WAIT = 0xc8,
SCORPIONL2_CPU0_NONAMBAS_WAIT = 0xc9,
SCORPIONL2_CPU1_NONAMBAS_WAIT = 0xca,
SCORPIONL2_CPU0_DSB_WAIT = 0xcb,
SCORPIONL2_CPU1_DSB_WAIT = 0xcc,
SCORPIONL2_AXI_READ = 0xcd,
SCORPIONL2_AXI_WRITE = 0xce,
SCORPIONL2_1BEAT_WRITE = 0xcf,
SCORPIONL2_2BEAT_WRITE = 0xd0,
SCORPIONL2_4BEAT_WRITE = 0xd1,
SCORPIONL2_8BEAT_WRITE = 0xd2,
SCORPIONL2_12BEAT_WRITE = 0xd3,
SCORPIONL2_16BEAT_WRITE = 0xd4,
SCORPIONL2_1BEAT_DSIDE_READ = 0xd5,
SCORPIONL2_2BEAT_DSIDE_READ = 0xd6,
SCORPIONL2_4BEAT_DSIDE_READ = 0xd7,
SCORPIONL2_8BEAT_DSIDE_READ = 0xd8,
SCORPIONL2_CSYS_READ_1BEAT = 0xd9,
SCORPIONL2_CSYS_READ_2BEAT = 0xda,
SCORPIONL2_CSYS_READ_4BEAT = 0xdb,
SCORPIONL2_CSYS_READ_8BEAT = 0xdc,
SCORPIONL2_4BEAT_IFETCH_READ = 0xdd,
SCORPIONL2_8BEAT_IFETCH_READ = 0xde,
SCORPIONL2_CSYS_WRITE_1BEAT = 0xdf,
SCORPIONL2_CSYS_WRITE_2BEAT = 0xe0,
SCORPIONL2_AXI_READ_DATA_BEAT = 0xe1,
SCORPIONL2_AXI_WRITE_EVT1 = 0xe2,
SCORPIONL2_AXI_WRITE_EVT2 = 0xe3,
SCORPIONL2_LDREX_REQ = 0xe4,
SCORPIONL2_STREX_PASS = 0xe5,
SCORPIONL2_STREX_FAIL = 0xe6,
SCORPIONL2_CPREAD = 0xe7,
SCORPIONL2_CPWRITE = 0xe8,
SCORPIONL2_BARRIER_REQ = 0xe9,
SCORPIONL2_AXI_READ_SLVPORT = 0xea,
SCORPIONL2_AXI_WRITE_SLVPORT = 0xeb,
SCORPIONL2_AXI_READ_SLVPORT_DATABEAT = 0xec,
SCORPIONL2_AXI_WRITE_SLVPORT_DATABEAT = 0xed,
SCORPIONL2_SNOOPKILL_PREFILTER = 0xee,
SCORPIONL2_SNOOPKILL_FILTEROUT = 0xef,
SCORPIONL2_SNOOPED_IC = 0xf0,
SCORPIONL2_SNOOPED_BP = 0xf1,
SCORPIONL2_SNOOPED_BARRIERS = 0xf2,
SCORPIONL2_SNOOPED_TLB = 0xf3,
BB_L2_MAX_EVT,
};
static const struct bb_l2_scorp_evt sc_evt[] = {
{SCORPIONL2_TOTAL_BANK_REQ, 0x80000001, 0, 0x00},
{SCORPIONL2_DSIDE_READ, 0x80000100, 0, 0x01},
{SCORPIONL2_DSIDE_WRITE, 0x80010000, 0, 0x02},
{SCORPIONL2_ISIDE_READ, 0x81000000, 0, 0x03},
{SCORPIONL2_L2CACHE_ISIDE_READ, 0x80000002, 0, 0x00},
{SCORPIONL2_L2CACHE_BANK_REQ, 0x80000200, 0, 0x01},
{SCORPIONL2_L2CACHE_DSIDE_READ, 0x80020000, 0, 0x02},
{SCORPIONL2_L2CACHE_DSIDE_WRITE, 0x82000000, 0, 0x03},
{SCORPIONL2_L2NOCACHE_DSIDE_WRITE, 0x80000003, 0, 0x00},
{SCORPIONL2_L2NOCACHE_ISIDE_READ, 0x80000300, 0, 0x01},
{SCORPIONL2_L2NOCACHE_TOTAL_REQ, 0x80030000, 0, 0x02},
{SCORPIONL2_L2NOCACHE_DSIDE_READ, 0x83000000, 0, 0x03},
{SCORPIONL2_DSIDE_READ_NOL1, 0x80000004, 0, 0x00},
{SCORPIONL2_L2CACHE_WRITETHROUGH, 0x80000400, 0, 0x01},
{SCORPIONL2_BARRIERS, 0x84000000, 0, 0x03},
{SCORPIONL2_HARDWARE_TABLE_WALKS, 0x80000005, 0, 0x00},
{SCORPIONL2_MVA_POC, 0x80000500, 0, 0x01},
{SCORPIONL2_L2CACHE_HW_TABLE_WALKS, 0x80050000, 0, 0x02},
{SCORPIONL2_SETWAY_CACHE_OPS, 0x85000000, 0, 0x03},
{SCORPIONL2_DSIDE_WRITE_HITS, 0x80000006, 0, 0x00},
{SCORPIONL2_ISIDE_READ_HITS, 0x80000600, 0, 0x01},
{SCORPIONL2_CACHE_DSIDE_READ_NOL1, 0x80060000, 0, 0x02},
{SCORPIONL2_TOTAL_CACHE_HITS, 0x86000000, 0, 0x03},
{SCORPIONL2_CACHE_MATCH_MISS, 0x80000007, 0, 0x00},
{SCORPIONL2_DREAD_HIT_L1_DATA, 0x87000000, 0, 0x03},
{SCORPIONL2_L2LINE_LOCKED, 0x80000008, 0, 0x00},
{SCORPIONL2_HW_TABLE_WALK_HIT, 0x80000800, 0, 0x01},
{SCORPIONL2_CACHE_MVA_POC, 0x80080000, 0, 0x02},
{SCORPIONL2_L2ALLOC_DWRITE_MISS, 0x88000000, 0, 0x03},
{SCORPIONL2_CORRECTED_TAG_ARRAY, 0x80001A00, 0, 0x01},
{SCORPIONL2_CORRECTED_DATA_ARRAY, 0x801A0000, 0, 0x02},
{SCORPIONL2_CORRECTED_REPLACEMENT_ARRAY, 0x9A000000, 0, 0x03},
{SCORPIONL2_PMBUS_MPAAF, 0x80001C00, 0, 0x01},
{SCORPIONL2_PMBUS_MPWDAF, 0x801C0000, 0, 0x02},
{SCORPIONL2_PMBUS_MPBRT, 0x9C000000, 0, 0x03},
{SCORPIONL2_CPU0_GRANT, 0x80000001, 1, 0x04},
{SCORPIONL2_CPU1_GRANT, 0x80000100, 1, 0x05},
{SCORPIONL2_CPU0_NOGRANT, 0x80020000, 1, 0x06},
{SCORPIONL2_CPU1_NOGRANT, 0x82000000, 1, 0x07},
{SCORPIONL2_CPU0_LOSING_ARB, 0x80040000, 1, 0x06},
{SCORPIONL2_CPU1_LOSING_ARB, 0x84000000, 1, 0x07},
{SCORPIONL2_SLAVEPORT_NOGRANT, 0x80000007, 1, 0x04},
{SCORPIONL2_SLAVEPORT_BPQ_FULL, 0x80000700, 1, 0x05},
{SCORPIONL2_SLAVEPORT_LOSING_ARB, 0x80070000, 1, 0x06},
{SCORPIONL2_SLAVEPORT_GRANT, 0x87000000, 1, 0x07},
{SCORPIONL2_SLAVEPORT_GRANTLOCK, 0x80000008, 1, 0x04},
{SCORPIONL2_L2EM_STREX_PASS, 0x80000009, 1, 0x04},
{SCORPIONL2_L2EM_STREX_FAIL, 0x80000900, 1, 0x05},
{SCORPIONL2_LDREX_RESERVE_L2EM, 0x80090000, 1, 0x06},
{SCORPIONL2_SLAVEPORT_LDREX, 0x89000000, 1, 0x07},
{SCORPIONL2_CPU0_L2EM_CLEARED, 0x800A0000, 1, 0x06},
{SCORPIONL2_CPU1_L2EM_CLEARED, 0x8A000000, 1, 0x07},
{SCORPIONL2_SLAVEPORT_L2EM_CLEARED, 0x80000B00, 1, 0x05},
{SCORPIONL2_CPU0_CLAMPED, 0x8000000E, 1, 0x04},
{SCORPIONL2_CPU1_CLAMPED, 0x80000E00, 1, 0x05},
{SCORPIONL2_CPU0_WAIT, 0x800F0000, 1, 0x06},
{SCORPIONL2_CPU1_WAIT, 0x8F000000, 1, 0x07},
{SCORPIONL2_CPU0_NONAMBAS_WAIT, 0x80000010, 1, 0x04},
{SCORPIONL2_CPU1_NONAMBAS_WAIT, 0x80001000, 1, 0x05},
{SCORPIONL2_CPU0_DSB_WAIT, 0x80000014, 1, 0x04},
{SCORPIONL2_CPU1_DSB_WAIT, 0x80001400, 1, 0x05},
{SCORPIONL2_AXI_READ, 0x80000001, 2, 0x08},
{SCORPIONL2_AXI_WRITE, 0x80000100, 2, 0x09},
{SCORPIONL2_1BEAT_WRITE, 0x80010000, 2, 0x0a},
{SCORPIONL2_2BEAT_WRITE, 0x80010000, 2, 0x0b},
{SCORPIONL2_4BEAT_WRITE, 0x80000002, 2, 0x08},
{SCORPIONL2_8BEAT_WRITE, 0x80000200, 2, 0x09},
{SCORPIONL2_12BEAT_WRITE, 0x80020000, 2, 0x0a},
{SCORPIONL2_16BEAT_WRITE, 0x82000000, 2, 0x0b},
{SCORPIONL2_1BEAT_DSIDE_READ, 0x80000003, 2, 0x08},
{SCORPIONL2_2BEAT_DSIDE_READ, 0x80000300, 2, 0x09},
{SCORPIONL2_4BEAT_DSIDE_READ, 0x80030000, 2, 0x0a},
{SCORPIONL2_8BEAT_DSIDE_READ, 0x83000000, 2, 0x0b},
{SCORPIONL2_CSYS_READ_1BEAT, 0x80000004, 2, 0x08},
{SCORPIONL2_CSYS_READ_2BEAT, 0x80000400, 2, 0x09},
{SCORPIONL2_CSYS_READ_4BEAT, 0x80040000, 2, 0x0a},
{SCORPIONL2_CSYS_READ_8BEAT, 0x84000000, 2, 0x0b},
{SCORPIONL2_4BEAT_IFETCH_READ, 0x80000005, 2, 0x08},
{SCORPIONL2_8BEAT_IFETCH_READ, 0x80000500, 2, 0x09},
{SCORPIONL2_CSYS_WRITE_1BEAT, 0x80050000, 2, 0x0a},
{SCORPIONL2_CSYS_WRITE_2BEAT, 0x85000000, 2, 0x0b},
{SCORPIONL2_AXI_READ_DATA_BEAT, 0x80000600, 2, 0x09},
{SCORPIONL2_AXI_WRITE_EVT1, 0x80060000, 2, 0x0a},
{SCORPIONL2_AXI_WRITE_EVT2, 0x86000000, 2, 0x0b},
{SCORPIONL2_LDREX_REQ, 0x80000007, 2, 0x08},
{SCORPIONL2_STREX_PASS, 0x80000700, 2, 0x09},
{SCORPIONL2_STREX_FAIL, 0x80070000, 2, 0x0a},
{SCORPIONL2_CPREAD, 0x80000008, 2, 0x08},
{SCORPIONL2_CPWRITE, 0x80000800, 2, 0x09},
{SCORPIONL2_BARRIER_REQ, 0x88000000, 2, 0x0b},
{SCORPIONL2_AXI_READ_SLVPORT, 0x80000001, 3, 0x0c},
{SCORPIONL2_AXI_WRITE_SLVPORT, 0x80000100, 3, 0x0d},
{SCORPIONL2_AXI_READ_SLVPORT_DATABEAT, 0x80010000, 3, 0x0e},
{SCORPIONL2_AXI_WRITE_SLVPORT_DATABEAT, 0x81000000, 3, 0x0f},
{SCORPIONL2_SNOOPKILL_PREFILTER, 0x80000001, 4, 0x10},
{SCORPIONL2_SNOOPKILL_FILTEROUT, 0x80000100, 4, 0x11},
{SCORPIONL2_SNOOPED_IC, 0x80000002, 4, 0x10},
{SCORPIONL2_SNOOPED_BP, 0x80000200, 4, 0x11},
{SCORPIONL2_SNOOPED_BARRIERS, 0x80020000, 4, 0x12},
{SCORPIONL2_SNOOPED_TLB, 0x82000000, 4, 0x13},
};
static u32 bb_l2_read_l2pm0(void)
{
u32 val;
asm volatile ("mrc p15, 3, %0, c15, c7, 0" : "=r" (val));
return val;
}
static void bb_l2_write_l2pm0(u32 val)
{
asm volatile ("mcr p15, 3, %0, c15, c7, 0" : : "r" (val));
}
static u32 bb_l2_read_l2pm1(void)
{
u32 val;
asm volatile ("mrc p15, 3, %0, c15, c7, 1" : "=r" (val));
return val;
}
static void bb_l2_write_l2pm1(u32 val)
{
asm volatile ("mcr p15, 3, %0, c15, c7, 1" : : "r" (val));
}
static u32 bb_l2_read_l2pm2(void)
{
u32 val;
asm volatile ("mrc p15, 3, %0, c15, c7, 2" : "=r" (val));
return val;
}
static void bb_l2_write_l2pm2(u32 val)
{
asm volatile ("mcr p15, 3, %0, c15, c7, 2" : : "r" (val));
}
static u32 bb_l2_read_l2pm3(void)
{
u32 val;
asm volatile ("mrc p15, 3, %0, c15, c7, 3" : "=r" (val));
return val;
}
static void bb_l2_write_l2pm3(u32 val)
{
asm volatile ("mcr p15, 3, %0, c15, c7, 3" : : "r" (val));
}
static u32 bb_l2_read_l2pm4(void)
{
u32 val;
asm volatile ("mrc p15, 3, %0, c15, c7, 4" : "=r" (val));
return val;
}
static void bb_l2_write_l2pm4(u32 val)
{
asm volatile ("mcr p15, 3, %0, c15, c7, 4" : : "r" (val));
}
struct bb_scorpion_access_funcs {
u32(*read) (void);
void (*write) (u32);
void (*pre) (void);
void (*post) (void);
};
struct bb_scorpion_access_funcs bb_l2_func[] = {
{bb_l2_read_l2pm0, bb_l2_write_l2pm0, NULL, NULL},
{bb_l2_read_l2pm1, bb_l2_write_l2pm1, NULL, NULL},
{bb_l2_read_l2pm2, bb_l2_write_l2pm2, NULL, NULL},
{bb_l2_read_l2pm3, bb_l2_write_l2pm3, NULL, NULL},
{bb_l2_read_l2pm4, bb_l2_write_l2pm4, NULL, NULL},
};
#define COLMN0MASK 0x000000ff
#define COLMN1MASK 0x0000ff00
#define COLMN2MASK 0x00ff0000
static u32 bb_l2_get_columnmask(u32 setval)
{
if (setval & COLMN0MASK)
return 0xffffff00;
else if (setval & COLMN1MASK)
return 0xffff00ff;
else if (setval & COLMN2MASK)
return 0xff00ffff;
else
return 0x80ffffff;
}
static void bb_l2_evt_setup(u32 gr, u32 setval)
{
u32 val;
if (bb_l2_func[gr].pre)
bb_l2_func[gr].pre();
val = bb_l2_get_columnmask(setval) & bb_l2_func[gr].read();
val = val | setval;
bb_l2_func[gr].write(val);
if (bb_l2_func[gr].post)
bb_l2_func[gr].post();
}
#define BB_L2_EVT_START_IDX 0x90
#define BB_L2_INV_EVTYPE 0
static unsigned int get_bb_l2_evtinfo(unsigned int evt_type,
struct bb_l2_scorp_evt *evtinfo)
{
u32 idx;
u8 prefix;
u8 reg;
u8 code;
u8 group;
prefix = (evt_type & 0xF0000) >> 16;
if (prefix == SCORPION_L2_EVT_PREFIX) {
reg = (evt_type & 0x0F000) >> 12;
code = (evt_type & 0x00FF0) >> 4;
group = evt_type & 0x0000F;
if ((group > 3) || (reg > SCORPION_MAX_L2_REG))
return BB_L2_INV_EVTYPE;
evtinfo->val = 0x80000000 | (code << (group * 8));
evtinfo->grp = reg;
evtinfo->evt_type_act = group | (reg << 2);
return evtinfo->evt_type_act;
}
if (evt_type < BB_L2_EVT_START_IDX || evt_type >= BB_L2_MAX_EVT)
return BB_L2_INV_EVTYPE;
idx = evt_type - BB_L2_EVT_START_IDX;
if (sc_evt[idx].evt_type == evt_type) {
evtinfo->val = sc_evt[idx].val;
evtinfo->grp = sc_evt[idx].grp;
evtinfo->evt_type_act = sc_evt[idx].evt_type_act;
return sc_evt[idx].evt_type_act;
}
return BB_L2_INV_EVTYPE;
}
static inline void bb_l2_pmnc_write(unsigned long val)
{
val &= 0xff;
asm volatile ("mcr p15, 3, %0, c15, c4, 0" : : "r" (val));
}
static inline unsigned long bb_l2_pmnc_read(void)
{
u32 val;
asm volatile ("mrc p15, 3, %0, c15, c4, 0" : "=r" (val));
return val;
}
static void bb_l2_set_evcntcr(void)
{
u32 val = 0x0;
asm volatile ("mcr p15, 3, %0, c15, c6, 4" : : "r" (val));
}
static inline void bb_l2_set_evtyper(int ctr, int val)
{
/* select ctr */
asm volatile ("mcr p15, 3, %0, c15, c6, 0" : : "r" (ctr));
/* write into EVTYPER */
asm volatile ("mcr p15, 3, %0, c15, c6, 7" : : "r" (val));
}
static void bb_l2_set_evfilter_task_mode(void)
{
u32 filter_val = 0x000f0030 | 1 << smp_processor_id();
asm volatile ("mcr p15, 3, %0, c15, c6, 3" : : "r" (filter_val));
}
static void bb_l2_set_evfilter_sys_mode(void)
{
u32 filter_val = 0x000f003f;
asm volatile ("mcr p15, 3, %0, c15, c6, 3" : : "r" (filter_val));
}
static void bb_l2_enable_intenset(u32 idx)
{
if (idx == BB_L2CYCLE_CTR_EVENT_IDX) {
asm volatile ("mcr p15, 3, %0, c15, c5, 1" : : "r"
(1 << BB_L2CYCLE_CTR_BIT));
} else {
asm volatile ("mcr p15, 3, %0, c15, c5, 1" : : "r" (1 << idx));
}
}
static void bb_l2_disable_intenclr(u32 idx)
{
if (idx == BB_L2CYCLE_CTR_EVENT_IDX) {
asm volatile ("mcr p15, 3, %0, c15, c5, 0" : : "r"
(1 << BB_L2CYCLE_CTR_BIT));
} else {
asm volatile ("mcr p15, 3, %0, c15, c5, 0" : : "r" (1 << idx));
}
}
static void bb_l2_enable_counter(u32 idx)
{
if (idx == BB_L2CYCLE_CTR_EVENT_IDX) {
asm volatile ("mcr p15, 3, %0, c15, c4, 3" : : "r"
(1 << BB_L2CYCLE_CTR_BIT));
} else {
asm volatile ("mcr p15, 3, %0, c15, c4, 3" : : "r" (1 << idx));
}
}
static void bb_l2_disable_counter(u32 idx)
{
if (idx == BB_L2CYCLE_CTR_EVENT_IDX) {
asm volatile ("mcr p15, 3, %0, c15, c4, 2" : : "r"
(1 << BB_L2CYCLE_CTR_BIT));
} else {
asm volatile ("mcr p15, 3, %0, c15, c4, 2" : : "r" (1 << idx));
}
}
static u64 bb_l2_read_counter(u32 idx)
{
u32 val;
unsigned long flags;
if (idx == BB_L2CYCLE_CTR_EVENT_IDX) {
asm volatile ("mrc p15, 3, %0, c15, c4, 5" : "=r" (val));
} else {
raw_spin_lock_irqsave(&bb_l2_pmu_lock, flags);
asm volatile ("mcr p15, 3, %0, c15, c6, 0" : : "r" (idx));
/* read val from counter */
asm volatile ("mrc p15, 3, %0, c15, c6, 5" : "=r" (val));
raw_spin_unlock_irqrestore(&bb_l2_pmu_lock, flags);
}
return val;
}
static void bb_l2_write_counter(u32 idx, u32 val)
{
unsigned long flags;
if (idx == BB_L2CYCLE_CTR_EVENT_IDX) {
asm volatile ("mcr p15, 3, %0, c15, c4, 5" : : "r" (val));
} else {
raw_spin_lock_irqsave(&bb_l2_pmu_lock, flags);
/* select counter */
asm volatile ("mcr p15, 3, %0, c15, c6, 0" : : "r" (idx));
/* write val into counter */
asm volatile ("mcr p15, 3, %0, c15, c6, 5" : : "r" (val));
raw_spin_unlock_irqrestore(&bb_l2_pmu_lock, flags);
}
}
static int
bb_pmu_event_set_period(struct perf_event *event,
struct hw_perf_event *hwc, int idx)
{
s64 left = local64_read(&hwc->period_left);
s64 period = hwc->sample_period;
int ret = 0;
if (unlikely(left <= -period)) {
left = period;
local64_set(&hwc->period_left, left);
hwc->last_period = period;
ret = 1;
}
if (unlikely(left <= 0)) {
left += period;
local64_set(&hwc->period_left, left);
hwc->last_period = period;
ret = 1;
}
if (left > (s64) MAX_BB_L2_PERIOD)
left = MAX_BB_L2_PERIOD;
local64_set(&hwc->prev_count, (u64)-left);
bb_l2_write_counter(idx, (u64) (-left) & 0xffffffff);
perf_event_update_userpage(event);
return ret;
}
static u64
bb_pmu_event_update(struct perf_event *event, struct hw_perf_event *hwc,
int idx, int overflow)
{
u64 prev_raw_count, new_raw_count;
u64 delta;
again:
prev_raw_count = local64_read(&hwc->prev_count);
new_raw_count = bb_l2_read_counter(idx);
if (local64_cmpxchg(&hwc->prev_count, prev_raw_count,
new_raw_count) != prev_raw_count)
goto again;
new_raw_count &= MAX_BB_L2_PERIOD;
prev_raw_count &= MAX_BB_L2_PERIOD;
if (overflow) {
delta = MAX_BB_L2_PERIOD - prev_raw_count + new_raw_count;
pr_err("%s: delta: %lld\n", __func__, delta);
} else
delta = new_raw_count - prev_raw_count;
local64_add(delta, &event->count);
local64_sub(delta, &hwc->period_left);
pr_debug("%s: new: %lld, prev: %lld, event: %ld count: %lld\n",
__func__, new_raw_count, prev_raw_count,
hwc->config_base, local64_read(&event->count));
return new_raw_count;
}
static void bb_l2_read(struct perf_event *event)
{
struct hw_perf_event *hwc = &event->hw;
bb_pmu_event_update(event, hwc, hwc->idx, 0);
}
static void bb_l2_stop_counter(struct perf_event *event, int flags)
{
struct hw_perf_event *hwc = &event->hw;
int idx = hwc->idx;
if (!(hwc->state & PERF_HES_STOPPED)) {
bb_l2_disable_intenclr(idx);
bb_l2_disable_counter(idx);
bb_pmu_event_update(event, hwc, idx, 0);
hwc->state |= PERF_HES_STOPPED | PERF_HES_UPTODATE;
}
pr_debug("%s: event: %ld ctr: %d stopped\n", __func__, hwc->config_base,
idx);
}
static void bb_l2_start_counter(struct perf_event *event, int flags)
{
struct hw_perf_event *hwc = &event->hw;
int idx = hwc->idx;
struct bb_l2_scorp_evt evtinfo;
int evtype = hwc->config_base;
int ev_typer;
unsigned long iflags;
int cpu_id = smp_processor_id();
if (flags & PERF_EF_RELOAD)
WARN_ON_ONCE(!(hwc->state & PERF_HES_UPTODATE));
hwc->state = 0;
bb_pmu_event_set_period(event, hwc, idx);
if (hwc->config_base == BB_L2CYCLE_CTR_RAW_CODE)
goto out;
memset(&evtinfo, 0, sizeof(evtinfo));
ev_typer = get_bb_l2_evtinfo(evtype, &evtinfo);
raw_spin_lock_irqsave(&bb_l2_pmu_lock, iflags);
bb_l2_set_evtyper(idx, ev_typer);
bb_l2_set_evcntcr();
if (event->cpu < 0)
bb_l2_set_evfilter_task_mode();
else
bb_l2_set_evfilter_sys_mode();
bb_l2_evt_setup(evtinfo.grp, evtinfo.val);
raw_spin_unlock_irqrestore(&bb_l2_pmu_lock, iflags);
out:
bb_l2_enable_intenset(idx);
bb_l2_enable_counter(idx);
pr_debug("%s: idx: %d, event: %d, val: %x, cpu: %d\n",
__func__, idx, evtype, evtinfo.val, cpu_id);
}
static void bb_l2_del_event(struct perf_event *event, int flags)
{
struct hw_perf_event *hwc = &event->hw;
int idx = hwc->idx;
unsigned long iflags;
raw_spin_lock_irqsave(&hw_bb_l2_pmu.lock, iflags);
clear_bit(idx, (long unsigned int *)(&hw_bb_l2_pmu.active_mask));
bb_l2_stop_counter(event, PERF_EF_UPDATE);
hw_bb_l2_pmu.events[idx] = NULL;
hwc->idx = -1;
raw_spin_unlock_irqrestore(&hw_bb_l2_pmu.lock, iflags);
pr_debug("%s: event: %ld deleted\n", __func__, hwc->config_base);
perf_event_update_userpage(event);
}
static int bb_l2_add_event(struct perf_event *event, int flags)
{
int ctr = 0;
struct hw_perf_event *hwc = &event->hw;
unsigned long iflags;
int err = 0;
perf_pmu_disable(event->pmu);
raw_spin_lock_irqsave(&hw_bb_l2_pmu.lock, iflags);
/* Cycle counter has a resrvd index */
if (hwc->config_base == BB_L2CYCLE_CTR_RAW_CODE) {
if (hw_bb_l2_pmu.events[BB_L2CYCLE_CTR_EVENT_IDX]) {
pr_err("%s: Stale cycle ctr event ptr !\n", __func__);
err = -EINVAL;
goto out;
}
hwc->idx = BB_L2CYCLE_CTR_EVENT_IDX;
hw_bb_l2_pmu.events[BB_L2CYCLE_CTR_EVENT_IDX] = event;
set_bit(BB_L2CYCLE_CTR_EVENT_IDX,
(long unsigned int *)&hw_bb_l2_pmu.active_mask);
goto skip_ctr_loop;
}
for (ctr = 0; ctr < MAX_BB_L2_CTRS - 1; ctr++) {
if (!hw_bb_l2_pmu.events[ctr]) {
hwc->idx = ctr;
hw_bb_l2_pmu.events[ctr] = event;
set_bit(ctr, (long unsigned int *)
&hw_bb_l2_pmu.active_mask);
break;
}
}
if (hwc->idx < 0) {
err = -ENOSPC;
pr_err("%s: No space for event: %llx!!\n", __func__,
event->attr.config);
goto out;
}
skip_ctr_loop:
bb_l2_disable_counter(hwc->idx);
hwc->state = PERF_HES_STOPPED | PERF_HES_UPTODATE;
if (flags & PERF_EF_START)
bb_l2_start_counter(event, PERF_EF_RELOAD);
perf_event_update_userpage(event);
pr_debug("%s: event: %ld, ctr: %d added from cpu:%d\n",
__func__, hwc->config_base, hwc->idx, smp_processor_id());
out:
raw_spin_unlock_irqrestore(&hw_bb_l2_pmu.lock, iflags);
/* Resume the PMU even if this event could not be added */
perf_pmu_enable(event->pmu);
return err;
}
static void bb_l2_pmu_enable(struct pmu *pmu)
{
unsigned long flags;
isb();
raw_spin_lock_irqsave(&bb_l2_pmu_lock, flags);
/* Enable all counters */
bb_l2_pmnc_write(bb_l2_pmnc_read() | SCORPIONL2_PMNC_E);
raw_spin_unlock_irqrestore(&bb_l2_pmu_lock, flags);
}
static void bb_l2_pmu_disable(struct pmu *pmu)
{
unsigned long flags;
raw_spin_lock_irqsave(&bb_l2_pmu_lock, flags);
/* Disable all counters */
bb_l2_pmnc_write(bb_l2_pmnc_read() & ~SCORPIONL2_PMNC_E);
raw_spin_unlock_irqrestore(&bb_l2_pmu_lock, flags);
isb();
}
static inline u32 bb_l2_get_reset_pmovsr(void)
{
u32 val;
/* Read */
asm volatile ("mrc p15, 3, %0, c15, c4, 1" : "=r" (val));
/* Write to clear flags */
val &= 0xffffffff;
asm volatile ("mcr p15, 3, %0, c15, c4, 1" : : "r" (val));
return val;
}
static irqreturn_t bb_l2_handle_irq(int irq_num, void *dev)
{
unsigned long pmovsr;
struct perf_sample_data data;
struct pt_regs *regs;
struct perf_event *event;
struct hw_perf_event *hwc;
int bitp;
int idx = 0;
pmovsr = bb_l2_get_reset_pmovsr();
if (!(pmovsr & 0xffffffff))
return IRQ_NONE;
regs = get_irq_regs();
perf_sample_data_init(&data, 0);
raw_spin_lock(&hw_bb_l2_pmu.lock);
while (pmovsr) {
bitp = __ffs(pmovsr);
if (bitp == BB_L2CYCLE_CTR_BIT)
idx = BB_L2CYCLE_CTR_EVENT_IDX;
else
idx = bitp;
event = hw_bb_l2_pmu.events[idx];
if (!event)
goto next;
if (!test_bit(idx, hw_bb_l2_pmu.active_mask))
goto next;
hwc = &event->hw;
bb_pmu_event_update(event, hwc, idx, 1);
data.period = event->hw.last_period;
if (!bb_pmu_event_set_period(event, hwc, idx))
goto next;
if (perf_event_overflow(event, 0, &data, regs))
bb_l2_disable_counter(hwc->idx);
next:
pmovsr &= (pmovsr - 1);
}
raw_spin_unlock(&hw_bb_l2_pmu.lock);
irq_work_run();
return IRQ_HANDLED;
}
static atomic_t active_bb_l2_events = ATOMIC_INIT(0);
static DEFINE_MUTEX(bb_pmu_reserve_mutex);
static int bb_pmu_reserve_hardware(void)
{
int i, err = -ENODEV, irq;
bb_l2_pmu_device = reserve_pmu(ARM_PMU_DEVICE_L2);
if (IS_ERR(bb_l2_pmu_device)) {
pr_warning("unable to reserve pmu\n");
return PTR_ERR(bb_l2_pmu_device);
}
if (bb_l2_pmu_device->num_resources < 1) {
pr_err("no irqs for PMUs defined\n");
return -ENODEV;
}
if (strncmp(bb_l2_pmu_device->name, "l2-arm-pmu", 6)) {
pr_err("Incorrect pdev reserved !\n");
return -EINVAL;
}
for (i = 0; i < bb_l2_pmu_device->num_resources; ++i) {
irq = platform_get_irq(bb_l2_pmu_device, i);
if (irq < 0)
continue;
err = request_irq(irq, bb_l2_handle_irq,
IRQF_DISABLED | IRQF_NOBALANCING,
"bb-l2-pmu", NULL);
if (err) {
pr_warning("unable to request IRQ%d for Krait L2 perf "
"counters\n", irq);
break;
}
irq_get_chip(irq)->irq_unmask(irq_get_irq_data(irq));
}
if (err) {
for (i = i - 1; i >= 0; --i) {
irq = platform_get_irq(bb_l2_pmu_device, i);
if (irq >= 0)
free_irq(irq, NULL);
}
release_pmu(bb_l2_pmu_device);
bb_l2_pmu_device = NULL;
}
return err;
}
static void bb_pmu_release_hardware(void)
{
int i, irq;
for (i = bb_l2_pmu_device->num_resources - 1; i >= 0; --i) {
irq = platform_get_irq(bb_l2_pmu_device, i);
if (irq >= 0)
free_irq(irq, NULL);
}
bb_l2_pmu_disable(NULL);
release_pmu(bb_l2_pmu_device);
bb_l2_pmu_device = NULL;
}
static void bb_pmu_perf_event_destroy(struct perf_event *event)
{
if (atomic_dec_and_mutex_lock
(&active_bb_l2_events, &bb_pmu_reserve_mutex)) {
bb_pmu_release_hardware();
mutex_unlock(&bb_pmu_reserve_mutex);
}
}
static int bb_l2_event_init(struct perf_event *event)
{
int err = 0;
struct hw_perf_event *hwc = &event->hw;
int status = 0;
switch (event->attr.type) {
case PERF_TYPE_SHARED:
break;
default:
return -ENOENT;
}
hwc->idx = -1;
event->destroy = bb_pmu_perf_event_destroy;
if (!atomic_inc_not_zero(&active_bb_l2_events)) {
/* 0 active events */
mutex_lock(&bb_pmu_reserve_mutex);
err = bb_pmu_reserve_hardware();
mutex_unlock(&bb_pmu_reserve_mutex);
if (!err)
atomic_inc(&active_bb_l2_events);
else
return err;
}
hwc->config = 0;
hwc->event_base = 0;
/* Check if we came via perf default syms */
if (event->attr.config == PERF_COUNT_HW_L2_CYCLES)
hwc->config_base = BB_L2CYCLE_CTR_RAW_CODE;
else
hwc->config_base = event->attr.config;
/* Only one CPU can control the cycle counter */
if (hwc->config_base == BB_L2CYCLE_CTR_RAW_CODE) {
/* Check if its already running */
asm volatile ("mrc p15, 3, %0, c15, c4, 6" : "=r" (status));
if (status == 0x2) {
err = -ENOSPC;
goto out;
}
}
if (!hwc->sample_period) {
hwc->sample_period = MAX_BB_L2_PERIOD;
hwc->last_period = hwc->sample_period;
local64_set(&hwc->period_left, hwc->sample_period);
}
pr_debug("%s: event: %lld init'd\n", __func__, event->attr.config);
out:
if (err < 0)
bb_pmu_perf_event_destroy(event);
return err;
}
static struct pmu bb_l2_pmu = {
.pmu_enable = bb_l2_pmu_enable,
.pmu_disable = bb_l2_pmu_disable,
.event_init = bb_l2_event_init,
.add = bb_l2_add_event,
.del = bb_l2_del_event,
.start = bb_l2_start_counter,
.stop = bb_l2_stop_counter,
.read = bb_l2_read,
};
static const struct arm_pmu *__init scorpionmp_l2_pmu_init(void)
{
/* Register our own PMU here */
perf_pmu_register(&bb_l2_pmu, "BB L2", PERF_TYPE_SHARED);
memset(&hw_bb_l2_pmu, 0, sizeof(hw_bb_l2_pmu));
/* Avoid spurious interrupts at startup */
bb_l2_get_reset_pmovsr();
/* Don't return an arm_pmu here */
return NULL;
}
#else
static const struct arm_pmu *__init scorpionmp_l2_pmu_init(void)
{
return NULL;
}
#endif
| gpl-2.0 |
explora26/kernel-hikey-linaro | drivers/net/wireless/rsi/rsi_91x_main.c | 1887 | 7448 | /**
* Copyright (c) 2014 Redpine Signals Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/firmware.h>
#include "rsi_mgmt.h"
#include "rsi_common.h"
u32 rsi_zone_enabled = /* INFO_ZONE |
INIT_ZONE |
MGMT_TX_ZONE |
MGMT_RX_ZONE |
DATA_TX_ZONE |
DATA_RX_ZONE |
FSM_ZONE |
ISR_ZONE | */
ERR_ZONE |
0;
EXPORT_SYMBOL_GPL(rsi_zone_enabled);
/**
* rsi_dbg() - This function outputs informational messages.
* @zone: Zone of interest for output message.
* @fmt: printf-style format for output message.
*
* Return: none
*/
void rsi_dbg(u32 zone, const char *fmt, ...)
{
struct va_format vaf;
va_list args;
va_start(args, fmt);
vaf.fmt = fmt;
vaf.va = &args;
if (zone & rsi_zone_enabled)
pr_info("%pV", &vaf);
va_end(args);
}
EXPORT_SYMBOL_GPL(rsi_dbg);
/**
* rsi_prepare_skb() - This function prepares the skb.
* @common: Pointer to the driver private structure.
* @buffer: Pointer to the packet data.
* @pkt_len: Length of the packet.
* @extended_desc: Extended descriptor.
*
* Return: Successfully skb.
*/
static struct sk_buff *rsi_prepare_skb(struct rsi_common *common,
u8 *buffer,
u32 pkt_len,
u8 extended_desc)
{
struct ieee80211_tx_info *info;
struct skb_info *rx_params;
struct sk_buff *skb = NULL;
u8 payload_offset;
if (WARN(!pkt_len, "%s: Dummy pkt received", __func__))
return NULL;
if (pkt_len > (RSI_RCV_BUFFER_LEN * 4)) {
rsi_dbg(ERR_ZONE, "%s: Pkt size > max rx buf size %d\n",
__func__, pkt_len);
pkt_len = RSI_RCV_BUFFER_LEN * 4;
}
pkt_len -= extended_desc;
skb = dev_alloc_skb(pkt_len + FRAME_DESC_SZ);
if (skb == NULL)
return NULL;
payload_offset = (extended_desc + FRAME_DESC_SZ);
skb_put(skb, pkt_len);
memcpy((skb->data), (buffer + payload_offset), skb->len);
info = IEEE80211_SKB_CB(skb);
rx_params = (struct skb_info *)info->driver_data;
rx_params->rssi = rsi_get_rssi(buffer);
rx_params->channel = rsi_get_connected_channel(common->priv);
return skb;
}
/**
* rsi_read_pkt() - This function reads frames from the card.
* @common: Pointer to the driver private structure.
* @rcv_pkt_len: Received pkt length. In case of USB it is 0.
*
* Return: 0 on success, -1 on failure.
*/
int rsi_read_pkt(struct rsi_common *common, s32 rcv_pkt_len)
{
u8 *frame_desc = NULL, extended_desc = 0;
u32 index, length = 0, queueno = 0;
u16 actual_length = 0, offset;
struct sk_buff *skb = NULL;
index = 0;
do {
frame_desc = &common->rx_data_pkt[index];
actual_length = *(u16 *)&frame_desc[0];
offset = *(u16 *)&frame_desc[2];
queueno = rsi_get_queueno(frame_desc, offset);
length = rsi_get_length(frame_desc, offset);
extended_desc = rsi_get_extended_desc(frame_desc, offset);
switch (queueno) {
case RSI_WIFI_DATA_Q:
skb = rsi_prepare_skb(common,
(frame_desc + offset),
length,
extended_desc);
if (skb == NULL)
goto fail;
rsi_indicate_pkt_to_os(common, skb);
break;
case RSI_WIFI_MGMT_Q:
rsi_mgmt_pkt_recv(common, (frame_desc + offset));
break;
default:
rsi_dbg(ERR_ZONE, "%s: pkt from invalid queue: %d\n",
__func__, queueno);
goto fail;
}
index += actual_length;
rcv_pkt_len -= actual_length;
} while (rcv_pkt_len > 0);
return 0;
fail:
return -EINVAL;
}
EXPORT_SYMBOL_GPL(rsi_read_pkt);
/**
* rsi_tx_scheduler_thread() - This function is a kernel thread to send the
* packets to the device.
* @common: Pointer to the driver private structure.
*
* Return: None.
*/
static void rsi_tx_scheduler_thread(struct rsi_common *common)
{
struct rsi_hw *adapter = common->priv;
u32 timeout = EVENT_WAIT_FOREVER;
do {
if (adapter->determine_event_timeout)
timeout = adapter->determine_event_timeout(adapter);
rsi_wait_event(&common->tx_thread.event, timeout);
rsi_reset_event(&common->tx_thread.event);
if (common->init_done)
rsi_core_qos_processor(common);
} while (atomic_read(&common->tx_thread.thread_done) == 0);
complete_and_exit(&common->tx_thread.completion, 0);
}
/**
* rsi_91x_init() - This function initializes os interface operations.
* @void: Void.
*
* Return: Pointer to the adapter structure on success, NULL on failure .
*/
struct rsi_hw *rsi_91x_init(void)
{
struct rsi_hw *adapter = NULL;
struct rsi_common *common = NULL;
u8 ii = 0;
adapter = kzalloc(sizeof(*adapter), GFP_KERNEL);
if (!adapter)
return NULL;
adapter->priv = kzalloc(sizeof(*common), GFP_KERNEL);
if (adapter->priv == NULL) {
rsi_dbg(ERR_ZONE, "%s: Failed in allocation of memory\n",
__func__);
kfree(adapter);
return NULL;
} else {
common = adapter->priv;
common->priv = adapter;
}
for (ii = 0; ii < NUM_SOFT_QUEUES; ii++)
skb_queue_head_init(&common->tx_queue[ii]);
rsi_init_event(&common->tx_thread.event);
mutex_init(&common->mutex);
mutex_init(&common->tx_rxlock);
if (rsi_create_kthread(common,
&common->tx_thread,
rsi_tx_scheduler_thread,
"Tx-Thread")) {
rsi_dbg(ERR_ZONE, "%s: Unable to init tx thrd\n", __func__);
goto err;
}
common->init_done = true;
return adapter;
err:
kfree(common);
kfree(adapter);
return NULL;
}
EXPORT_SYMBOL_GPL(rsi_91x_init);
/**
* rsi_91x_deinit() - This function de-intializes os intf operations.
* @adapter: Pointer to the adapter structure.
*
* Return: None.
*/
void rsi_91x_deinit(struct rsi_hw *adapter)
{
struct rsi_common *common = adapter->priv;
u8 ii;
rsi_dbg(INFO_ZONE, "%s: Performing deinit os ops\n", __func__);
rsi_kill_thread(&common->tx_thread);
for (ii = 0; ii < NUM_SOFT_QUEUES; ii++)
skb_queue_purge(&common->tx_queue[ii]);
common->init_done = false;
kfree(common);
kfree(adapter->rsi_dev);
kfree(adapter);
}
EXPORT_SYMBOL_GPL(rsi_91x_deinit);
/**
* rsi_91x_hal_module_init() - This function is invoked when the module is
* loaded into the kernel.
* It registers the client driver.
* @void: Void.
*
* Return: 0 on success, -1 on failure.
*/
static int rsi_91x_hal_module_init(void)
{
rsi_dbg(INIT_ZONE, "%s: Module init called\n", __func__);
return 0;
}
/**
* rsi_91x_hal_module_exit() - This function is called at the time of
* removing/unloading the module.
* It unregisters the client driver.
* @void: Void.
*
* Return: None.
*/
static void rsi_91x_hal_module_exit(void)
{
rsi_dbg(INIT_ZONE, "%s: Module exit called\n", __func__);
}
module_init(rsi_91x_hal_module_init);
module_exit(rsi_91x_hal_module_exit);
MODULE_AUTHOR("Redpine Signals Inc");
MODULE_DESCRIPTION("Station driver for RSI 91x devices");
MODULE_SUPPORTED_DEVICE("RSI-91x");
MODULE_VERSION("0.1");
MODULE_LICENSE("Dual BSD/GPL");
| gpl-2.0 |
playfulgod/kernel-LGMS910 | drivers/input/mouse/logips2pp.c | 3935 | 11699 | /*
* Logitech PS/2++ mouse driver
*
* Copyright (c) 1999-2003 Vojtech Pavlik <vojtech@suse.cz>
* Copyright (c) 2003 Eric Wong <eric@yhbt.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.
*/
#include <linux/input.h>
#include <linux/serio.h>
#include <linux/libps2.h>
#include "psmouse.h"
#include "logips2pp.h"
/* Logitech mouse types */
#define PS2PP_KIND_WHEEL 1
#define PS2PP_KIND_MX 2
#define PS2PP_KIND_TP3 3
#define PS2PP_KIND_TRACKMAN 4
/* Logitech mouse features */
#define PS2PP_WHEEL 0x01
#define PS2PP_HWHEEL 0x02
#define PS2PP_SIDE_BTN 0x04
#define PS2PP_EXTRA_BTN 0x08
#define PS2PP_TASK_BTN 0x10
#define PS2PP_NAV_BTN 0x20
struct ps2pp_info {
u8 model;
u8 kind;
u16 features;
};
/*
* Process a PS2++ or PS2T++ packet.
*/
static psmouse_ret_t ps2pp_process_byte(struct psmouse *psmouse)
{
struct input_dev *dev = psmouse->dev;
unsigned char *packet = psmouse->packet;
if (psmouse->pktcnt < 3)
return PSMOUSE_GOOD_DATA;
/*
* Full packet accumulated, process it
*/
if ((packet[0] & 0x48) == 0x48 && (packet[1] & 0x02) == 0x02) {
/* Logitech extended packet */
switch ((packet[1] >> 4) | (packet[0] & 0x30)) {
case 0x0d: /* Mouse extra info */
input_report_rel(dev, packet[2] & 0x80 ? REL_HWHEEL : REL_WHEEL,
(int) (packet[2] & 8) - (int) (packet[2] & 7));
input_report_key(dev, BTN_SIDE, (packet[2] >> 4) & 1);
input_report_key(dev, BTN_EXTRA, (packet[2] >> 5) & 1);
break;
case 0x0e: /* buttons 4, 5, 6, 7, 8, 9, 10 info */
input_report_key(dev, BTN_SIDE, (packet[2]) & 1);
input_report_key(dev, BTN_EXTRA, (packet[2] >> 1) & 1);
input_report_key(dev, BTN_BACK, (packet[2] >> 3) & 1);
input_report_key(dev, BTN_FORWARD, (packet[2] >> 4) & 1);
input_report_key(dev, BTN_TASK, (packet[2] >> 2) & 1);
break;
case 0x0f: /* TouchPad extra info */
input_report_rel(dev, packet[2] & 0x08 ? REL_HWHEEL : REL_WHEEL,
(int) ((packet[2] >> 4) & 8) - (int) ((packet[2] >> 4) & 7));
packet[0] = packet[2] | 0x08;
break;
#ifdef DEBUG
default:
printk(KERN_WARNING "psmouse.c: Received PS2++ packet #%x, but don't know how to handle.\n",
(packet[1] >> 4) | (packet[0] & 0x30));
#endif
}
} else {
/* Standard PS/2 motion data */
input_report_rel(dev, REL_X, packet[1] ? (int) packet[1] - (int) ((packet[0] << 4) & 0x100) : 0);
input_report_rel(dev, REL_Y, packet[2] ? (int) ((packet[0] << 3) & 0x100) - (int) packet[2] : 0);
}
input_report_key(dev, BTN_LEFT, packet[0] & 1);
input_report_key(dev, BTN_MIDDLE, (packet[0] >> 2) & 1);
input_report_key(dev, BTN_RIGHT, (packet[0] >> 1) & 1);
input_sync(dev);
return PSMOUSE_FULL_PACKET;
}
/*
* ps2pp_cmd() sends a PS2++ command, sliced into two bit
* pieces through the SETRES command. This is needed to send extended
* commands to mice on notebooks that try to understand the PS/2 protocol
* Ugly.
*/
static int ps2pp_cmd(struct psmouse *psmouse, unsigned char *param, unsigned char command)
{
if (psmouse_sliced_command(psmouse, command))
return -1;
if (ps2_command(&psmouse->ps2dev, param, PSMOUSE_CMD_POLL | 0x0300))
return -1;
return 0;
}
/*
* SmartScroll / CruiseControl for some newer Logitech mice Defaults to
* enabled if we do nothing to it. Of course I put this in because I want it
* disabled :P
* 1 - enabled (if previously disabled, also default)
* 0 - disabled
*/
static void ps2pp_set_smartscroll(struct psmouse *psmouse, bool smartscroll)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
unsigned char param[4];
ps2pp_cmd(psmouse, param, 0x32);
param[0] = 0;
ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES);
ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES);
ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES);
param[0] = smartscroll;
ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES);
}
static ssize_t ps2pp_attr_show_smartscroll(struct psmouse *psmouse,
void *data, char *buf)
{
return sprintf(buf, "%d\n", psmouse->smartscroll);
}
static ssize_t ps2pp_attr_set_smartscroll(struct psmouse *psmouse, void *data,
const char *buf, size_t count)
{
unsigned long value;
if (strict_strtoul(buf, 10, &value) || value > 1)
return -EINVAL;
ps2pp_set_smartscroll(psmouse, value);
psmouse->smartscroll = value;
return count;
}
PSMOUSE_DEFINE_ATTR(smartscroll, S_IWUSR | S_IRUGO, NULL,
ps2pp_attr_show_smartscroll, ps2pp_attr_set_smartscroll);
/*
* Support 800 dpi resolution _only_ if the user wants it (there are good
* reasons to not use it even if the mouse supports it, and of course there are
* also good reasons to use it, let the user decide).
*/
static void ps2pp_set_resolution(struct psmouse *psmouse, unsigned int resolution)
{
if (resolution > 400) {
struct ps2dev *ps2dev = &psmouse->ps2dev;
unsigned char param = 3;
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11);
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11);
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11);
ps2_command(ps2dev, ¶m, PSMOUSE_CMD_SETRES);
psmouse->resolution = 800;
} else
psmouse_set_resolution(psmouse, resolution);
}
static void ps2pp_disconnect(struct psmouse *psmouse)
{
device_remove_file(&psmouse->ps2dev.serio->dev, &psmouse_attr_smartscroll.dattr);
}
static const struct ps2pp_info *get_model_info(unsigned char model)
{
static const struct ps2pp_info ps2pp_list[] = {
{ 1, 0, 0 }, /* Simple 2-button mouse */
{ 12, 0, PS2PP_SIDE_BTN},
{ 13, 0, 0 },
{ 15, PS2PP_KIND_MX, /* MX1000 */
PS2PP_WHEEL | PS2PP_SIDE_BTN | PS2PP_TASK_BTN |
PS2PP_EXTRA_BTN | PS2PP_NAV_BTN | PS2PP_HWHEEL },
{ 40, 0, PS2PP_SIDE_BTN },
{ 41, 0, PS2PP_SIDE_BTN },
{ 42, 0, PS2PP_SIDE_BTN },
{ 43, 0, PS2PP_SIDE_BTN },
{ 50, 0, 0 },
{ 51, 0, 0 },
{ 52, PS2PP_KIND_WHEEL, PS2PP_SIDE_BTN | PS2PP_WHEEL },
{ 53, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 56, PS2PP_KIND_WHEEL, PS2PP_SIDE_BTN | PS2PP_WHEEL }, /* Cordless MouseMan Wheel */
{ 61, PS2PP_KIND_MX, /* MX700 */
PS2PP_WHEEL | PS2PP_SIDE_BTN | PS2PP_TASK_BTN |
PS2PP_EXTRA_BTN | PS2PP_NAV_BTN },
{ 66, PS2PP_KIND_MX, /* MX3100 reciver */
PS2PP_WHEEL | PS2PP_SIDE_BTN | PS2PP_TASK_BTN |
PS2PP_EXTRA_BTN | PS2PP_NAV_BTN | PS2PP_HWHEEL },
{ 72, PS2PP_KIND_TRACKMAN, 0 }, /* T-CH11: TrackMan Marble */
{ 73, PS2PP_KIND_TRACKMAN, PS2PP_SIDE_BTN }, /* TrackMan FX */
{ 75, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 76, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 79, PS2PP_KIND_TRACKMAN, PS2PP_WHEEL }, /* TrackMan with wheel */
{ 80, PS2PP_KIND_WHEEL, PS2PP_SIDE_BTN | PS2PP_WHEEL },
{ 81, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 83, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 85, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 86, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 87, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 88, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 96, 0, 0 },
{ 97, PS2PP_KIND_TP3, PS2PP_WHEEL | PS2PP_HWHEEL },
{ 99, PS2PP_KIND_WHEEL, PS2PP_WHEEL },
{ 100, PS2PP_KIND_MX, /* MX510 */
PS2PP_WHEEL | PS2PP_SIDE_BTN | PS2PP_TASK_BTN |
PS2PP_EXTRA_BTN | PS2PP_NAV_BTN },
{ 111, PS2PP_KIND_MX, PS2PP_WHEEL | PS2PP_SIDE_BTN }, /* MX300 reports task button as side */
{ 112, PS2PP_KIND_MX, /* MX500 */
PS2PP_WHEEL | PS2PP_SIDE_BTN | PS2PP_TASK_BTN |
PS2PP_EXTRA_BTN | PS2PP_NAV_BTN },
{ 114, PS2PP_KIND_MX, /* MX310 */
PS2PP_WHEEL | PS2PP_SIDE_BTN |
PS2PP_TASK_BTN | PS2PP_EXTRA_BTN }
};
int i;
for (i = 0; i < ARRAY_SIZE(ps2pp_list); i++)
if (model == ps2pp_list[i].model)
return &ps2pp_list[i];
return NULL;
}
/*
* Set up input device's properties based on the detected mouse model.
*/
static void ps2pp_set_model_properties(struct psmouse *psmouse,
const struct ps2pp_info *model_info,
bool using_ps2pp)
{
struct input_dev *input_dev = psmouse->dev;
if (model_info->features & PS2PP_SIDE_BTN)
__set_bit(BTN_SIDE, input_dev->keybit);
if (model_info->features & PS2PP_EXTRA_BTN)
__set_bit(BTN_EXTRA, input_dev->keybit);
if (model_info->features & PS2PP_TASK_BTN)
__set_bit(BTN_TASK, input_dev->keybit);
if (model_info->features & PS2PP_NAV_BTN) {
__set_bit(BTN_FORWARD, input_dev->keybit);
__set_bit(BTN_BACK, input_dev->keybit);
}
if (model_info->features & PS2PP_WHEEL)
__set_bit(REL_WHEEL, input_dev->relbit);
if (model_info->features & PS2PP_HWHEEL)
__set_bit(REL_HWHEEL, input_dev->relbit);
switch (model_info->kind) {
case PS2PP_KIND_WHEEL:
psmouse->name = "Wheel Mouse";
break;
case PS2PP_KIND_MX:
psmouse->name = "MX Mouse";
break;
case PS2PP_KIND_TP3:
psmouse->name = "TouchPad 3";
break;
case PS2PP_KIND_TRACKMAN:
psmouse->name = "TrackMan";
break;
default:
/*
* Set name to "Mouse" only when using PS2++,
* otherwise let other protocols define suitable
* name
*/
if (using_ps2pp)
psmouse->name = "Mouse";
break;
}
}
/*
* Logitech magic init. Detect whether the mouse is a Logitech one
* and its exact model and try turning on extended protocol for ones
* that support it.
*/
int ps2pp_init(struct psmouse *psmouse, bool set_properties)
{
struct ps2dev *ps2dev = &psmouse->ps2dev;
unsigned char param[4];
unsigned char model, buttons;
const struct ps2pp_info *model_info;
bool use_ps2pp = false;
int error;
param[0] = 0;
ps2_command(ps2dev, param, PSMOUSE_CMD_SETRES);
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11);
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11);
ps2_command(ps2dev, NULL, PSMOUSE_CMD_SETSCALE11);
param[1] = 0;
ps2_command(ps2dev, param, PSMOUSE_CMD_GETINFO);
model = ((param[0] >> 4) & 0x07) | ((param[0] << 3) & 0x78);
buttons = param[1];
if (!model || !buttons)
return -1;
model_info = get_model_info(model);
if (model_info) {
/*
* Do Logitech PS2++ / PS2T++ magic init.
*/
if (model_info->kind == PS2PP_KIND_TP3) { /* Touch Pad 3 */
/* Unprotect RAM */
param[0] = 0x11; param[1] = 0x04; param[2] = 0x68;
ps2_command(ps2dev, param, 0x30d1);
/* Enable features */
param[0] = 0x11; param[1] = 0x05; param[2] = 0x0b;
ps2_command(ps2dev, param, 0x30d1);
/* Enable PS2++ */
param[0] = 0x11; param[1] = 0x09; param[2] = 0xc3;
ps2_command(ps2dev, param, 0x30d1);
param[0] = 0;
if (!ps2_command(ps2dev, param, 0x13d1) &&
param[0] == 0x06 && param[1] == 0x00 && param[2] == 0x14) {
use_ps2pp = true;
}
} else {
param[0] = param[1] = param[2] = 0;
ps2pp_cmd(psmouse, param, 0x39); /* Magic knock */
ps2pp_cmd(psmouse, param, 0xDB);
if ((param[0] & 0x78) == 0x48 &&
(param[1] & 0xf3) == 0xc2 &&
(param[2] & 0x03) == ((param[1] >> 2) & 3)) {
ps2pp_set_smartscroll(psmouse, false);
use_ps2pp = true;
}
}
} else {
printk(KERN_WARNING "logips2pp: Detected unknown logitech mouse model %d\n", model);
}
if (set_properties) {
psmouse->vendor = "Logitech";
psmouse->model = model;
if (use_ps2pp) {
psmouse->protocol_handler = ps2pp_process_byte;
psmouse->pktsize = 3;
if (model_info->kind != PS2PP_KIND_TP3) {
psmouse->set_resolution = ps2pp_set_resolution;
psmouse->disconnect = ps2pp_disconnect;
error = device_create_file(&psmouse->ps2dev.serio->dev,
&psmouse_attr_smartscroll.dattr);
if (error) {
printk(KERN_ERR
"logips2pp.c: failed to create smartscroll "
"sysfs attribute, error: %d\n", error);
return -1;
}
}
}
if (buttons >= 3)
__set_bit(BTN_MIDDLE, psmouse->dev->keybit);
if (model_info)
ps2pp_set_model_properties(psmouse, model_info, use_ps2pp);
}
return use_ps2pp ? 0 : -1;
}
| gpl-2.0 |
compudj/linux-libringbuffer | net/dsa/tag_edsa.c | 4191 | 5424 | /*
* net/dsa/tag_edsa.c - Ethertype DSA tagging
* Copyright (c) 2008-2009 Marvell Semiconductor
*
* 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/etherdevice.h>
#include <linux/list.h>
#include <linux/netdevice.h>
#include <linux/slab.h>
#include "dsa_priv.h"
#define DSA_HLEN 4
#define EDSA_HLEN 8
netdev_tx_t edsa_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct dsa_slave_priv *p = netdev_priv(dev);
u8 *edsa_header;
dev->stats.tx_packets++;
dev->stats.tx_bytes += skb->len;
/*
* Convert the outermost 802.1q tag to a DSA tag and prepend
* a DSA ethertype field is the packet is tagged, or insert
* a DSA ethertype plus DSA tag between the addresses and the
* current ethertype field if the packet is untagged.
*/
if (skb->protocol == htons(ETH_P_8021Q)) {
if (skb_cow_head(skb, DSA_HLEN) < 0)
goto out_free;
skb_push(skb, DSA_HLEN);
memmove(skb->data, skb->data + DSA_HLEN, 2 * ETH_ALEN);
/*
* Construct tagged FROM_CPU DSA tag from 802.1q tag.
*/
edsa_header = skb->data + 2 * ETH_ALEN;
edsa_header[0] = (ETH_P_EDSA >> 8) & 0xff;
edsa_header[1] = ETH_P_EDSA & 0xff;
edsa_header[2] = 0x00;
edsa_header[3] = 0x00;
edsa_header[4] = 0x60 | p->parent->index;
edsa_header[5] = p->port << 3;
/*
* Move CFI field from byte 6 to byte 5.
*/
if (edsa_header[6] & 0x10) {
edsa_header[5] |= 0x01;
edsa_header[6] &= ~0x10;
}
} else {
if (skb_cow_head(skb, EDSA_HLEN) < 0)
goto out_free;
skb_push(skb, EDSA_HLEN);
memmove(skb->data, skb->data + EDSA_HLEN, 2 * ETH_ALEN);
/*
* Construct untagged FROM_CPU DSA tag.
*/
edsa_header = skb->data + 2 * ETH_ALEN;
edsa_header[0] = (ETH_P_EDSA >> 8) & 0xff;
edsa_header[1] = ETH_P_EDSA & 0xff;
edsa_header[2] = 0x00;
edsa_header[3] = 0x00;
edsa_header[4] = 0x40 | p->parent->index;
edsa_header[5] = p->port << 3;
edsa_header[6] = 0x00;
edsa_header[7] = 0x00;
}
skb->protocol = htons(ETH_P_EDSA);
skb->dev = p->parent->dst->master_netdev;
dev_queue_xmit(skb);
return NETDEV_TX_OK;
out_free:
kfree_skb(skb);
return NETDEV_TX_OK;
}
static int edsa_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct dsa_switch_tree *dst = dev->dsa_ptr;
struct dsa_switch *ds;
u8 *edsa_header;
int source_device;
int source_port;
if (unlikely(dst == NULL))
goto out_drop;
skb = skb_unshare(skb, GFP_ATOMIC);
if (skb == NULL)
goto out;
if (unlikely(!pskb_may_pull(skb, EDSA_HLEN)))
goto out_drop;
/*
* Skip the two null bytes after the ethertype.
*/
edsa_header = skb->data + 2;
/*
* Check that frame type is either TO_CPU or FORWARD.
*/
if ((edsa_header[0] & 0xc0) != 0x00 && (edsa_header[0] & 0xc0) != 0xc0)
goto out_drop;
/*
* Determine source device and port.
*/
source_device = edsa_header[0] & 0x1f;
source_port = (edsa_header[1] >> 3) & 0x1f;
/*
* Check that the source device exists and that the source
* port is a registered DSA port.
*/
if (source_device >= dst->pd->nr_chips)
goto out_drop;
ds = dst->ds[source_device];
if (source_port >= DSA_MAX_PORTS || ds->ports[source_port] == NULL)
goto out_drop;
/*
* If the 'tagged' bit is set, convert the DSA tag to a 802.1q
* tag and delete the ethertype part. If the 'tagged' bit is
* clear, delete the ethertype and the DSA tag parts.
*/
if (edsa_header[0] & 0x20) {
u8 new_header[4];
/*
* Insert 802.1q ethertype and copy the VLAN-related
* fields, but clear the bit that will hold CFI (since
* DSA uses that bit location for another purpose).
*/
new_header[0] = (ETH_P_8021Q >> 8) & 0xff;
new_header[1] = ETH_P_8021Q & 0xff;
new_header[2] = edsa_header[2] & ~0x10;
new_header[3] = edsa_header[3];
/*
* Move CFI bit from its place in the DSA header to
* its 802.1q-designated place.
*/
if (edsa_header[1] & 0x01)
new_header[2] |= 0x10;
skb_pull_rcsum(skb, DSA_HLEN);
/*
* Update packet checksum if skb is CHECKSUM_COMPLETE.
*/
if (skb->ip_summed == CHECKSUM_COMPLETE) {
__wsum c = skb->csum;
c = csum_add(c, csum_partial(new_header + 2, 2, 0));
c = csum_sub(c, csum_partial(edsa_header + 2, 2, 0));
skb->csum = c;
}
memcpy(edsa_header, new_header, DSA_HLEN);
memmove(skb->data - ETH_HLEN,
skb->data - ETH_HLEN - DSA_HLEN,
2 * ETH_ALEN);
} else {
/*
* Remove DSA tag and update checksum.
*/
skb_pull_rcsum(skb, EDSA_HLEN);
memmove(skb->data - ETH_HLEN,
skb->data - ETH_HLEN - EDSA_HLEN,
2 * ETH_ALEN);
}
skb->dev = ds->ports[source_port];
skb_push(skb, ETH_HLEN);
skb->pkt_type = PACKET_HOST;
skb->protocol = eth_type_trans(skb, skb->dev);
skb->dev->stats.rx_packets++;
skb->dev->stats.rx_bytes += skb->len;
netif_receive_skb(skb);
return 0;
out_drop:
kfree_skb(skb);
out:
return 0;
}
static struct packet_type edsa_packet_type __read_mostly = {
.type = cpu_to_be16(ETH_P_EDSA),
.func = edsa_rcv,
};
static int __init edsa_init_module(void)
{
dev_add_pack(&edsa_packet_type);
return 0;
}
module_init(edsa_init_module);
static void __exit edsa_cleanup_module(void)
{
dev_remove_pack(&edsa_packet_type);
}
module_exit(edsa_cleanup_module);
| gpl-2.0 |
Koloses/kernel_i8200 | drivers/block/drbd/drbd_receiver.c | 5983 | 131391 | /*
drbd_receiver.c
This file is part of DRBD by Philipp Reisner and Lars Ellenberg.
Copyright (C) 2001-2008, LINBIT Information Technologies GmbH.
Copyright (C) 1999-2008, Philipp Reisner <philipp.reisner@linbit.com>.
Copyright (C) 2002-2008, Lars Ellenberg <lars.ellenberg@linbit.com>.
drbd 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.
drbd 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 drbd; see the file COPYING. If not, write to
the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/module.h>
#include <asm/uaccess.h>
#include <net/sock.h>
#include <linux/drbd.h>
#include <linux/fs.h>
#include <linux/file.h>
#include <linux/in.h>
#include <linux/mm.h>
#include <linux/memcontrol.h>
#include <linux/mm_inline.h>
#include <linux/slab.h>
#include <linux/pkt_sched.h>
#define __KERNEL_SYSCALLS__
#include <linux/unistd.h>
#include <linux/vmalloc.h>
#include <linux/random.h>
#include <linux/string.h>
#include <linux/scatterlist.h>
#include "drbd_int.h"
#include "drbd_req.h"
#include "drbd_vli.h"
enum finish_epoch {
FE_STILL_LIVE,
FE_DESTROYED,
FE_RECYCLED,
};
static int drbd_do_handshake(struct drbd_conf *mdev);
static int drbd_do_auth(struct drbd_conf *mdev);
static enum finish_epoch drbd_may_finish_epoch(struct drbd_conf *, struct drbd_epoch *, enum epoch_event);
static int e_end_block(struct drbd_conf *, struct drbd_work *, int);
#define GFP_TRY (__GFP_HIGHMEM | __GFP_NOWARN)
/*
* some helper functions to deal with single linked page lists,
* page->private being our "next" pointer.
*/
/* If at least n pages are linked at head, get n pages off.
* Otherwise, don't modify head, and return NULL.
* Locking is the responsibility of the caller.
*/
static struct page *page_chain_del(struct page **head, int n)
{
struct page *page;
struct page *tmp;
BUG_ON(!n);
BUG_ON(!head);
page = *head;
if (!page)
return NULL;
while (page) {
tmp = page_chain_next(page);
if (--n == 0)
break; /* found sufficient pages */
if (tmp == NULL)
/* insufficient pages, don't use any of them. */
return NULL;
page = tmp;
}
/* add end of list marker for the returned list */
set_page_private(page, 0);
/* actual return value, and adjustment of head */
page = *head;
*head = tmp;
return page;
}
/* may be used outside of locks to find the tail of a (usually short)
* "private" page chain, before adding it back to a global chain head
* with page_chain_add() under a spinlock. */
static struct page *page_chain_tail(struct page *page, int *len)
{
struct page *tmp;
int i = 1;
while ((tmp = page_chain_next(page)))
++i, page = tmp;
if (len)
*len = i;
return page;
}
static int page_chain_free(struct page *page)
{
struct page *tmp;
int i = 0;
page_chain_for_each_safe(page, tmp) {
put_page(page);
++i;
}
return i;
}
static void page_chain_add(struct page **head,
struct page *chain_first, struct page *chain_last)
{
#if 1
struct page *tmp;
tmp = page_chain_tail(chain_first, NULL);
BUG_ON(tmp != chain_last);
#endif
/* add chain to head */
set_page_private(chain_last, (unsigned long)*head);
*head = chain_first;
}
static struct page *drbd_pp_first_pages_or_try_alloc(struct drbd_conf *mdev, int number)
{
struct page *page = NULL;
struct page *tmp = NULL;
int i = 0;
/* Yes, testing drbd_pp_vacant outside the lock is racy.
* So what. It saves a spin_lock. */
if (drbd_pp_vacant >= number) {
spin_lock(&drbd_pp_lock);
page = page_chain_del(&drbd_pp_pool, number);
if (page)
drbd_pp_vacant -= number;
spin_unlock(&drbd_pp_lock);
if (page)
return page;
}
/* GFP_TRY, because we must not cause arbitrary write-out: in a DRBD
* "criss-cross" setup, that might cause write-out on some other DRBD,
* which in turn might block on the other node at this very place. */
for (i = 0; i < number; i++) {
tmp = alloc_page(GFP_TRY);
if (!tmp)
break;
set_page_private(tmp, (unsigned long)page);
page = tmp;
}
if (i == number)
return page;
/* Not enough pages immediately available this time.
* No need to jump around here, drbd_pp_alloc will retry this
* function "soon". */
if (page) {
tmp = page_chain_tail(page, NULL);
spin_lock(&drbd_pp_lock);
page_chain_add(&drbd_pp_pool, page, tmp);
drbd_pp_vacant += i;
spin_unlock(&drbd_pp_lock);
}
return NULL;
}
static void reclaim_net_ee(struct drbd_conf *mdev, struct list_head *to_be_freed)
{
struct drbd_epoch_entry *e;
struct list_head *le, *tle;
/* The EEs are always appended to the end of the list. Since
they are sent in order over the wire, they have to finish
in order. As soon as we see the first not finished we can
stop to examine the list... */
list_for_each_safe(le, tle, &mdev->net_ee) {
e = list_entry(le, struct drbd_epoch_entry, w.list);
if (drbd_ee_has_active_page(e))
break;
list_move(le, to_be_freed);
}
}
static void drbd_kick_lo_and_reclaim_net(struct drbd_conf *mdev)
{
LIST_HEAD(reclaimed);
struct drbd_epoch_entry *e, *t;
spin_lock_irq(&mdev->req_lock);
reclaim_net_ee(mdev, &reclaimed);
spin_unlock_irq(&mdev->req_lock);
list_for_each_entry_safe(e, t, &reclaimed, w.list)
drbd_free_net_ee(mdev, e);
}
/**
* drbd_pp_alloc() - Returns @number pages, retries forever (or until signalled)
* @mdev: DRBD device.
* @number: number of pages requested
* @retry: whether to retry, if not enough pages are available right now
*
* Tries to allocate number pages, first from our own page pool, then from
* the kernel, unless this allocation would exceed the max_buffers setting.
* Possibly retry until DRBD frees sufficient pages somewhere else.
*
* Returns a page chain linked via page->private.
*/
static struct page *drbd_pp_alloc(struct drbd_conf *mdev, unsigned number, bool retry)
{
struct page *page = NULL;
DEFINE_WAIT(wait);
/* Yes, we may run up to @number over max_buffers. If we
* follow it strictly, the admin will get it wrong anyways. */
if (atomic_read(&mdev->pp_in_use) < mdev->net_conf->max_buffers)
page = drbd_pp_first_pages_or_try_alloc(mdev, number);
while (page == NULL) {
prepare_to_wait(&drbd_pp_wait, &wait, TASK_INTERRUPTIBLE);
drbd_kick_lo_and_reclaim_net(mdev);
if (atomic_read(&mdev->pp_in_use) < mdev->net_conf->max_buffers) {
page = drbd_pp_first_pages_or_try_alloc(mdev, number);
if (page)
break;
}
if (!retry)
break;
if (signal_pending(current)) {
dev_warn(DEV, "drbd_pp_alloc interrupted!\n");
break;
}
schedule();
}
finish_wait(&drbd_pp_wait, &wait);
if (page)
atomic_add(number, &mdev->pp_in_use);
return page;
}
/* Must not be used from irq, as that may deadlock: see drbd_pp_alloc.
* Is also used from inside an other spin_lock_irq(&mdev->req_lock);
* Either links the page chain back to the global pool,
* or returns all pages to the system. */
static void drbd_pp_free(struct drbd_conf *mdev, struct page *page, int is_net)
{
atomic_t *a = is_net ? &mdev->pp_in_use_by_net : &mdev->pp_in_use;
int i;
if (drbd_pp_vacant > (DRBD_MAX_BIO_SIZE/PAGE_SIZE)*minor_count)
i = page_chain_free(page);
else {
struct page *tmp;
tmp = page_chain_tail(page, &i);
spin_lock(&drbd_pp_lock);
page_chain_add(&drbd_pp_pool, page, tmp);
drbd_pp_vacant += i;
spin_unlock(&drbd_pp_lock);
}
i = atomic_sub_return(i, a);
if (i < 0)
dev_warn(DEV, "ASSERTION FAILED: %s: %d < 0\n",
is_net ? "pp_in_use_by_net" : "pp_in_use", i);
wake_up(&drbd_pp_wait);
}
/*
You need to hold the req_lock:
_drbd_wait_ee_list_empty()
You must not have the req_lock:
drbd_free_ee()
drbd_alloc_ee()
drbd_init_ee()
drbd_release_ee()
drbd_ee_fix_bhs()
drbd_process_done_ee()
drbd_clear_done_ee()
drbd_wait_ee_list_empty()
*/
struct drbd_epoch_entry *drbd_alloc_ee(struct drbd_conf *mdev,
u64 id,
sector_t sector,
unsigned int data_size,
gfp_t gfp_mask) __must_hold(local)
{
struct drbd_epoch_entry *e;
struct page *page;
unsigned nr_pages = (data_size + PAGE_SIZE -1) >> PAGE_SHIFT;
if (drbd_insert_fault(mdev, DRBD_FAULT_AL_EE))
return NULL;
e = mempool_alloc(drbd_ee_mempool, gfp_mask & ~__GFP_HIGHMEM);
if (!e) {
if (!(gfp_mask & __GFP_NOWARN))
dev_err(DEV, "alloc_ee: Allocation of an EE failed\n");
return NULL;
}
page = drbd_pp_alloc(mdev, nr_pages, (gfp_mask & __GFP_WAIT));
if (!page)
goto fail;
INIT_HLIST_NODE(&e->collision);
e->epoch = NULL;
e->mdev = mdev;
e->pages = page;
atomic_set(&e->pending_bios, 0);
e->size = data_size;
e->flags = 0;
e->sector = sector;
e->block_id = id;
return e;
fail:
mempool_free(e, drbd_ee_mempool);
return NULL;
}
void drbd_free_some_ee(struct drbd_conf *mdev, struct drbd_epoch_entry *e, int is_net)
{
if (e->flags & EE_HAS_DIGEST)
kfree(e->digest);
drbd_pp_free(mdev, e->pages, is_net);
D_ASSERT(atomic_read(&e->pending_bios) == 0);
D_ASSERT(hlist_unhashed(&e->collision));
mempool_free(e, drbd_ee_mempool);
}
int drbd_release_ee(struct drbd_conf *mdev, struct list_head *list)
{
LIST_HEAD(work_list);
struct drbd_epoch_entry *e, *t;
int count = 0;
int is_net = list == &mdev->net_ee;
spin_lock_irq(&mdev->req_lock);
list_splice_init(list, &work_list);
spin_unlock_irq(&mdev->req_lock);
list_for_each_entry_safe(e, t, &work_list, w.list) {
drbd_free_some_ee(mdev, e, is_net);
count++;
}
return count;
}
/*
* This function is called from _asender only_
* but see also comments in _req_mod(,barrier_acked)
* and receive_Barrier.
*
* Move entries from net_ee to done_ee, if ready.
* Grab done_ee, call all callbacks, free the entries.
* The callbacks typically send out ACKs.
*/
static int drbd_process_done_ee(struct drbd_conf *mdev)
{
LIST_HEAD(work_list);
LIST_HEAD(reclaimed);
struct drbd_epoch_entry *e, *t;
int ok = (mdev->state.conn >= C_WF_REPORT_PARAMS);
spin_lock_irq(&mdev->req_lock);
reclaim_net_ee(mdev, &reclaimed);
list_splice_init(&mdev->done_ee, &work_list);
spin_unlock_irq(&mdev->req_lock);
list_for_each_entry_safe(e, t, &reclaimed, w.list)
drbd_free_net_ee(mdev, e);
/* possible callbacks here:
* e_end_block, and e_end_resync_block, e_send_discard_ack.
* all ignore the last argument.
*/
list_for_each_entry_safe(e, t, &work_list, w.list) {
/* list_del not necessary, next/prev members not touched */
ok = e->w.cb(mdev, &e->w, !ok) && ok;
drbd_free_ee(mdev, e);
}
wake_up(&mdev->ee_wait);
return ok;
}
void _drbd_wait_ee_list_empty(struct drbd_conf *mdev, struct list_head *head)
{
DEFINE_WAIT(wait);
/* avoids spin_lock/unlock
* and calling prepare_to_wait in the fast path */
while (!list_empty(head)) {
prepare_to_wait(&mdev->ee_wait, &wait, TASK_UNINTERRUPTIBLE);
spin_unlock_irq(&mdev->req_lock);
io_schedule();
finish_wait(&mdev->ee_wait, &wait);
spin_lock_irq(&mdev->req_lock);
}
}
void drbd_wait_ee_list_empty(struct drbd_conf *mdev, struct list_head *head)
{
spin_lock_irq(&mdev->req_lock);
_drbd_wait_ee_list_empty(mdev, head);
spin_unlock_irq(&mdev->req_lock);
}
/* see also kernel_accept; which is only present since 2.6.18.
* also we want to log which part of it failed, exactly */
static int drbd_accept(struct drbd_conf *mdev, const char **what,
struct socket *sock, struct socket **newsock)
{
struct sock *sk = sock->sk;
int err = 0;
*what = "listen";
err = sock->ops->listen(sock, 5);
if (err < 0)
goto out;
*what = "sock_create_lite";
err = sock_create_lite(sk->sk_family, sk->sk_type, sk->sk_protocol,
newsock);
if (err < 0)
goto out;
*what = "accept";
err = sock->ops->accept(sock, *newsock, 0);
if (err < 0) {
sock_release(*newsock);
*newsock = NULL;
goto out;
}
(*newsock)->ops = sock->ops;
out:
return err;
}
static int drbd_recv_short(struct drbd_conf *mdev, struct socket *sock,
void *buf, size_t size, int flags)
{
mm_segment_t oldfs;
struct kvec iov = {
.iov_base = buf,
.iov_len = size,
};
struct msghdr msg = {
.msg_iovlen = 1,
.msg_iov = (struct iovec *)&iov,
.msg_flags = (flags ? flags : MSG_WAITALL | MSG_NOSIGNAL)
};
int rv;
oldfs = get_fs();
set_fs(KERNEL_DS);
rv = sock_recvmsg(sock, &msg, size, msg.msg_flags);
set_fs(oldfs);
return rv;
}
static int drbd_recv(struct drbd_conf *mdev, void *buf, size_t size)
{
mm_segment_t oldfs;
struct kvec iov = {
.iov_base = buf,
.iov_len = size,
};
struct msghdr msg = {
.msg_iovlen = 1,
.msg_iov = (struct iovec *)&iov,
.msg_flags = MSG_WAITALL | MSG_NOSIGNAL
};
int rv;
oldfs = get_fs();
set_fs(KERNEL_DS);
for (;;) {
rv = sock_recvmsg(mdev->data.socket, &msg, size, msg.msg_flags);
if (rv == size)
break;
/* Note:
* ECONNRESET other side closed the connection
* ERESTARTSYS (on sock) we got a signal
*/
if (rv < 0) {
if (rv == -ECONNRESET)
dev_info(DEV, "sock was reset by peer\n");
else if (rv != -ERESTARTSYS)
dev_err(DEV, "sock_recvmsg returned %d\n", rv);
break;
} else if (rv == 0) {
dev_info(DEV, "sock was shut down by peer\n");
break;
} else {
/* signal came in, or peer/link went down,
* after we read a partial message
*/
/* D_ASSERT(signal_pending(current)); */
break;
}
};
set_fs(oldfs);
if (rv != size)
drbd_force_state(mdev, NS(conn, C_BROKEN_PIPE));
return rv;
}
/* quoting tcp(7):
* On individual connections, the socket buffer size must be set prior to the
* listen(2) or connect(2) calls in order to have it take effect.
* This is our wrapper to do so.
*/
static void drbd_setbufsize(struct socket *sock, unsigned int snd,
unsigned int rcv)
{
/* open coded SO_SNDBUF, SO_RCVBUF */
if (snd) {
sock->sk->sk_sndbuf = snd;
sock->sk->sk_userlocks |= SOCK_SNDBUF_LOCK;
}
if (rcv) {
sock->sk->sk_rcvbuf = rcv;
sock->sk->sk_userlocks |= SOCK_RCVBUF_LOCK;
}
}
static struct socket *drbd_try_connect(struct drbd_conf *mdev)
{
const char *what;
struct socket *sock;
struct sockaddr_in6 src_in6;
int err;
int disconnect_on_error = 1;
if (!get_net_conf(mdev))
return NULL;
what = "sock_create_kern";
err = sock_create_kern(((struct sockaddr *)mdev->net_conf->my_addr)->sa_family,
SOCK_STREAM, IPPROTO_TCP, &sock);
if (err < 0) {
sock = NULL;
goto out;
}
sock->sk->sk_rcvtimeo =
sock->sk->sk_sndtimeo = mdev->net_conf->try_connect_int*HZ;
drbd_setbufsize(sock, mdev->net_conf->sndbuf_size,
mdev->net_conf->rcvbuf_size);
/* explicitly bind to the configured IP as source IP
* for the outgoing connections.
* This is needed for multihomed hosts and to be
* able to use lo: interfaces for drbd.
* Make sure to use 0 as port number, so linux selects
* a free one dynamically.
*/
memcpy(&src_in6, mdev->net_conf->my_addr,
min_t(int, mdev->net_conf->my_addr_len, sizeof(src_in6)));
if (((struct sockaddr *)mdev->net_conf->my_addr)->sa_family == AF_INET6)
src_in6.sin6_port = 0;
else
((struct sockaddr_in *)&src_in6)->sin_port = 0; /* AF_INET & AF_SCI */
what = "bind before connect";
err = sock->ops->bind(sock,
(struct sockaddr *) &src_in6,
mdev->net_conf->my_addr_len);
if (err < 0)
goto out;
/* connect may fail, peer not yet available.
* stay C_WF_CONNECTION, don't go Disconnecting! */
disconnect_on_error = 0;
what = "connect";
err = sock->ops->connect(sock,
(struct sockaddr *)mdev->net_conf->peer_addr,
mdev->net_conf->peer_addr_len, 0);
out:
if (err < 0) {
if (sock) {
sock_release(sock);
sock = NULL;
}
switch (-err) {
/* timeout, busy, signal pending */
case ETIMEDOUT: case EAGAIN: case EINPROGRESS:
case EINTR: case ERESTARTSYS:
/* peer not (yet) available, network problem */
case ECONNREFUSED: case ENETUNREACH:
case EHOSTDOWN: case EHOSTUNREACH:
disconnect_on_error = 0;
break;
default:
dev_err(DEV, "%s failed, err = %d\n", what, err);
}
if (disconnect_on_error)
drbd_force_state(mdev, NS(conn, C_DISCONNECTING));
}
put_net_conf(mdev);
return sock;
}
static struct socket *drbd_wait_for_connect(struct drbd_conf *mdev)
{
int timeo, err;
struct socket *s_estab = NULL, *s_listen;
const char *what;
if (!get_net_conf(mdev))
return NULL;
what = "sock_create_kern";
err = sock_create_kern(((struct sockaddr *)mdev->net_conf->my_addr)->sa_family,
SOCK_STREAM, IPPROTO_TCP, &s_listen);
if (err) {
s_listen = NULL;
goto out;
}
timeo = mdev->net_conf->try_connect_int * HZ;
timeo += (random32() & 1) ? timeo / 7 : -timeo / 7; /* 28.5% random jitter */
s_listen->sk->sk_reuse = 1; /* SO_REUSEADDR */
s_listen->sk->sk_rcvtimeo = timeo;
s_listen->sk->sk_sndtimeo = timeo;
drbd_setbufsize(s_listen, mdev->net_conf->sndbuf_size,
mdev->net_conf->rcvbuf_size);
what = "bind before listen";
err = s_listen->ops->bind(s_listen,
(struct sockaddr *) mdev->net_conf->my_addr,
mdev->net_conf->my_addr_len);
if (err < 0)
goto out;
err = drbd_accept(mdev, &what, s_listen, &s_estab);
out:
if (s_listen)
sock_release(s_listen);
if (err < 0) {
if (err != -EAGAIN && err != -EINTR && err != -ERESTARTSYS) {
dev_err(DEV, "%s failed, err = %d\n", what, err);
drbd_force_state(mdev, NS(conn, C_DISCONNECTING));
}
}
put_net_conf(mdev);
return s_estab;
}
static int drbd_send_fp(struct drbd_conf *mdev,
struct socket *sock, enum drbd_packets cmd)
{
struct p_header80 *h = &mdev->data.sbuf.header.h80;
return _drbd_send_cmd(mdev, sock, cmd, h, sizeof(*h), 0);
}
static enum drbd_packets drbd_recv_fp(struct drbd_conf *mdev, struct socket *sock)
{
struct p_header80 *h = &mdev->data.rbuf.header.h80;
int rr;
rr = drbd_recv_short(mdev, sock, h, sizeof(*h), 0);
if (rr == sizeof(*h) && h->magic == BE_DRBD_MAGIC)
return be16_to_cpu(h->command);
return 0xffff;
}
/**
* drbd_socket_okay() - Free the socket if its connection is not okay
* @mdev: DRBD device.
* @sock: pointer to the pointer to the socket.
*/
static int drbd_socket_okay(struct drbd_conf *mdev, struct socket **sock)
{
int rr;
char tb[4];
if (!*sock)
return false;
rr = drbd_recv_short(mdev, *sock, tb, 4, MSG_DONTWAIT | MSG_PEEK);
if (rr > 0 || rr == -EAGAIN) {
return true;
} else {
sock_release(*sock);
*sock = NULL;
return false;
}
}
/*
* return values:
* 1 yes, we have a valid connection
* 0 oops, did not work out, please try again
* -1 peer talks different language,
* no point in trying again, please go standalone.
* -2 We do not have a network config...
*/
static int drbd_connect(struct drbd_conf *mdev)
{
struct socket *s, *sock, *msock;
int try, h, ok;
D_ASSERT(!mdev->data.socket);
if (drbd_request_state(mdev, NS(conn, C_WF_CONNECTION)) < SS_SUCCESS)
return -2;
clear_bit(DISCARD_CONCURRENT, &mdev->flags);
sock = NULL;
msock = NULL;
do {
for (try = 0;;) {
/* 3 tries, this should take less than a second! */
s = drbd_try_connect(mdev);
if (s || ++try >= 3)
break;
/* give the other side time to call bind() & listen() */
schedule_timeout_interruptible(HZ / 10);
}
if (s) {
if (!sock) {
drbd_send_fp(mdev, s, P_HAND_SHAKE_S);
sock = s;
s = NULL;
} else if (!msock) {
drbd_send_fp(mdev, s, P_HAND_SHAKE_M);
msock = s;
s = NULL;
} else {
dev_err(DEV, "Logic error in drbd_connect()\n");
goto out_release_sockets;
}
}
if (sock && msock) {
schedule_timeout_interruptible(mdev->net_conf->ping_timeo*HZ/10);
ok = drbd_socket_okay(mdev, &sock);
ok = drbd_socket_okay(mdev, &msock) && ok;
if (ok)
break;
}
retry:
s = drbd_wait_for_connect(mdev);
if (s) {
try = drbd_recv_fp(mdev, s);
drbd_socket_okay(mdev, &sock);
drbd_socket_okay(mdev, &msock);
switch (try) {
case P_HAND_SHAKE_S:
if (sock) {
dev_warn(DEV, "initial packet S crossed\n");
sock_release(sock);
}
sock = s;
break;
case P_HAND_SHAKE_M:
if (msock) {
dev_warn(DEV, "initial packet M crossed\n");
sock_release(msock);
}
msock = s;
set_bit(DISCARD_CONCURRENT, &mdev->flags);
break;
default:
dev_warn(DEV, "Error receiving initial packet\n");
sock_release(s);
if (random32() & 1)
goto retry;
}
}
if (mdev->state.conn <= C_DISCONNECTING)
goto out_release_sockets;
if (signal_pending(current)) {
flush_signals(current);
smp_rmb();
if (get_t_state(&mdev->receiver) == Exiting)
goto out_release_sockets;
}
if (sock && msock) {
ok = drbd_socket_okay(mdev, &sock);
ok = drbd_socket_okay(mdev, &msock) && ok;
if (ok)
break;
}
} while (1);
msock->sk->sk_reuse = 1; /* SO_REUSEADDR */
sock->sk->sk_reuse = 1; /* SO_REUSEADDR */
sock->sk->sk_allocation = GFP_NOIO;
msock->sk->sk_allocation = GFP_NOIO;
sock->sk->sk_priority = TC_PRIO_INTERACTIVE_BULK;
msock->sk->sk_priority = TC_PRIO_INTERACTIVE;
/* NOT YET ...
* sock->sk->sk_sndtimeo = mdev->net_conf->timeout*HZ/10;
* sock->sk->sk_rcvtimeo = MAX_SCHEDULE_TIMEOUT;
* first set it to the P_HAND_SHAKE timeout,
* which we set to 4x the configured ping_timeout. */
sock->sk->sk_sndtimeo =
sock->sk->sk_rcvtimeo = mdev->net_conf->ping_timeo*4*HZ/10;
msock->sk->sk_sndtimeo = mdev->net_conf->timeout*HZ/10;
msock->sk->sk_rcvtimeo = mdev->net_conf->ping_int*HZ;
/* we don't want delays.
* we use TCP_CORK where appropriate, though */
drbd_tcp_nodelay(sock);
drbd_tcp_nodelay(msock);
mdev->data.socket = sock;
mdev->meta.socket = msock;
mdev->last_received = jiffies;
D_ASSERT(mdev->asender.task == NULL);
h = drbd_do_handshake(mdev);
if (h <= 0)
return h;
if (mdev->cram_hmac_tfm) {
/* drbd_request_state(mdev, NS(conn, WFAuth)); */
switch (drbd_do_auth(mdev)) {
case -1:
dev_err(DEV, "Authentication of peer failed\n");
return -1;
case 0:
dev_err(DEV, "Authentication of peer failed, trying again.\n");
return 0;
}
}
if (drbd_request_state(mdev, NS(conn, C_WF_REPORT_PARAMS)) < SS_SUCCESS)
return 0;
sock->sk->sk_sndtimeo = mdev->net_conf->timeout*HZ/10;
sock->sk->sk_rcvtimeo = MAX_SCHEDULE_TIMEOUT;
atomic_set(&mdev->packet_seq, 0);
mdev->peer_seq = 0;
drbd_thread_start(&mdev->asender);
if (drbd_send_protocol(mdev) == -1)
return -1;
drbd_send_sync_param(mdev, &mdev->sync_conf);
drbd_send_sizes(mdev, 0, 0);
drbd_send_uuids(mdev);
drbd_send_state(mdev);
clear_bit(USE_DEGR_WFC_T, &mdev->flags);
clear_bit(RESIZE_PENDING, &mdev->flags);
mod_timer(&mdev->request_timer, jiffies + HZ); /* just start it here. */
return 1;
out_release_sockets:
if (sock)
sock_release(sock);
if (msock)
sock_release(msock);
return -1;
}
static int drbd_recv_header(struct drbd_conf *mdev, enum drbd_packets *cmd, unsigned int *packet_size)
{
union p_header *h = &mdev->data.rbuf.header;
int r;
r = drbd_recv(mdev, h, sizeof(*h));
if (unlikely(r != sizeof(*h))) {
if (!signal_pending(current))
dev_warn(DEV, "short read expecting header on sock: r=%d\n", r);
return false;
}
if (likely(h->h80.magic == BE_DRBD_MAGIC)) {
*cmd = be16_to_cpu(h->h80.command);
*packet_size = be16_to_cpu(h->h80.length);
} else if (h->h95.magic == BE_DRBD_MAGIC_BIG) {
*cmd = be16_to_cpu(h->h95.command);
*packet_size = be32_to_cpu(h->h95.length);
} else {
dev_err(DEV, "magic?? on data m: 0x%08x c: %d l: %d\n",
be32_to_cpu(h->h80.magic),
be16_to_cpu(h->h80.command),
be16_to_cpu(h->h80.length));
return false;
}
mdev->last_received = jiffies;
return true;
}
static void drbd_flush(struct drbd_conf *mdev)
{
int rv;
if (mdev->write_ordering >= WO_bdev_flush && get_ldev(mdev)) {
rv = blkdev_issue_flush(mdev->ldev->backing_bdev, GFP_KERNEL,
NULL);
if (rv) {
dev_err(DEV, "local disk flush failed with status %d\n", rv);
/* would rather check on EOPNOTSUPP, but that is not reliable.
* don't try again for ANY return value != 0
* if (rv == -EOPNOTSUPP) */
drbd_bump_write_ordering(mdev, WO_drain_io);
}
put_ldev(mdev);
}
}
/**
* drbd_may_finish_epoch() - Applies an epoch_event to the epoch's state, eventually finishes it.
* @mdev: DRBD device.
* @epoch: Epoch object.
* @ev: Epoch event.
*/
static enum finish_epoch drbd_may_finish_epoch(struct drbd_conf *mdev,
struct drbd_epoch *epoch,
enum epoch_event ev)
{
int epoch_size;
struct drbd_epoch *next_epoch;
enum finish_epoch rv = FE_STILL_LIVE;
spin_lock(&mdev->epoch_lock);
do {
next_epoch = NULL;
epoch_size = atomic_read(&epoch->epoch_size);
switch (ev & ~EV_CLEANUP) {
case EV_PUT:
atomic_dec(&epoch->active);
break;
case EV_GOT_BARRIER_NR:
set_bit(DE_HAVE_BARRIER_NUMBER, &epoch->flags);
break;
case EV_BECAME_LAST:
/* nothing to do*/
break;
}
if (epoch_size != 0 &&
atomic_read(&epoch->active) == 0 &&
test_bit(DE_HAVE_BARRIER_NUMBER, &epoch->flags)) {
if (!(ev & EV_CLEANUP)) {
spin_unlock(&mdev->epoch_lock);
drbd_send_b_ack(mdev, epoch->barrier_nr, epoch_size);
spin_lock(&mdev->epoch_lock);
}
dec_unacked(mdev);
if (mdev->current_epoch != epoch) {
next_epoch = list_entry(epoch->list.next, struct drbd_epoch, list);
list_del(&epoch->list);
ev = EV_BECAME_LAST | (ev & EV_CLEANUP);
mdev->epochs--;
kfree(epoch);
if (rv == FE_STILL_LIVE)
rv = FE_DESTROYED;
} else {
epoch->flags = 0;
atomic_set(&epoch->epoch_size, 0);
/* atomic_set(&epoch->active, 0); is already zero */
if (rv == FE_STILL_LIVE)
rv = FE_RECYCLED;
wake_up(&mdev->ee_wait);
}
}
if (!next_epoch)
break;
epoch = next_epoch;
} while (1);
spin_unlock(&mdev->epoch_lock);
return rv;
}
/**
* drbd_bump_write_ordering() - Fall back to an other write ordering method
* @mdev: DRBD device.
* @wo: Write ordering method to try.
*/
void drbd_bump_write_ordering(struct drbd_conf *mdev, enum write_ordering_e wo) __must_hold(local)
{
enum write_ordering_e pwo;
static char *write_ordering_str[] = {
[WO_none] = "none",
[WO_drain_io] = "drain",
[WO_bdev_flush] = "flush",
};
pwo = mdev->write_ordering;
wo = min(pwo, wo);
if (wo == WO_bdev_flush && mdev->ldev->dc.no_disk_flush)
wo = WO_drain_io;
if (wo == WO_drain_io && mdev->ldev->dc.no_disk_drain)
wo = WO_none;
mdev->write_ordering = wo;
if (pwo != mdev->write_ordering || wo == WO_bdev_flush)
dev_info(DEV, "Method to ensure write ordering: %s\n", write_ordering_str[mdev->write_ordering]);
}
/**
* drbd_submit_ee()
* @mdev: DRBD device.
* @e: epoch entry
* @rw: flag field, see bio->bi_rw
*
* May spread the pages to multiple bios,
* depending on bio_add_page restrictions.
*
* Returns 0 if all bios have been submitted,
* -ENOMEM if we could not allocate enough bios,
* -ENOSPC (any better suggestion?) if we have not been able to bio_add_page a
* single page to an empty bio (which should never happen and likely indicates
* that the lower level IO stack is in some way broken). This has been observed
* on certain Xen deployments.
*/
/* TODO allocate from our own bio_set. */
int drbd_submit_ee(struct drbd_conf *mdev, struct drbd_epoch_entry *e,
const unsigned rw, const int fault_type)
{
struct bio *bios = NULL;
struct bio *bio;
struct page *page = e->pages;
sector_t sector = e->sector;
unsigned ds = e->size;
unsigned n_bios = 0;
unsigned nr_pages = (ds + PAGE_SIZE -1) >> PAGE_SHIFT;
int err = -ENOMEM;
/* In most cases, we will only need one bio. But in case the lower
* level restrictions happen to be different at this offset on this
* side than those of the sending peer, we may need to submit the
* request in more than one bio. */
next_bio:
bio = bio_alloc(GFP_NOIO, nr_pages);
if (!bio) {
dev_err(DEV, "submit_ee: Allocation of a bio failed\n");
goto fail;
}
/* > e->sector, unless this is the first bio */
bio->bi_sector = sector;
bio->bi_bdev = mdev->ldev->backing_bdev;
bio->bi_rw = rw;
bio->bi_private = e;
bio->bi_end_io = drbd_endio_sec;
bio->bi_next = bios;
bios = bio;
++n_bios;
page_chain_for_each(page) {
unsigned len = min_t(unsigned, ds, PAGE_SIZE);
if (!bio_add_page(bio, page, len, 0)) {
/* A single page must always be possible!
* But in case it fails anyways,
* we deal with it, and complain (below). */
if (bio->bi_vcnt == 0) {
dev_err(DEV,
"bio_add_page failed for len=%u, "
"bi_vcnt=0 (bi_sector=%llu)\n",
len, (unsigned long long)bio->bi_sector);
err = -ENOSPC;
goto fail;
}
goto next_bio;
}
ds -= len;
sector += len >> 9;
--nr_pages;
}
D_ASSERT(page == NULL);
D_ASSERT(ds == 0);
atomic_set(&e->pending_bios, n_bios);
do {
bio = bios;
bios = bios->bi_next;
bio->bi_next = NULL;
drbd_generic_make_request(mdev, fault_type, bio);
} while (bios);
return 0;
fail:
while (bios) {
bio = bios;
bios = bios->bi_next;
bio_put(bio);
}
return err;
}
static int receive_Barrier(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
int rv;
struct p_barrier *p = &mdev->data.rbuf.barrier;
struct drbd_epoch *epoch;
inc_unacked(mdev);
mdev->current_epoch->barrier_nr = p->barrier;
rv = drbd_may_finish_epoch(mdev, mdev->current_epoch, EV_GOT_BARRIER_NR);
/* P_BARRIER_ACK may imply that the corresponding extent is dropped from
* the activity log, which means it would not be resynced in case the
* R_PRIMARY crashes now.
* Therefore we must send the barrier_ack after the barrier request was
* completed. */
switch (mdev->write_ordering) {
case WO_none:
if (rv == FE_RECYCLED)
return true;
/* receiver context, in the writeout path of the other node.
* avoid potential distributed deadlock */
epoch = kmalloc(sizeof(struct drbd_epoch), GFP_NOIO);
if (epoch)
break;
else
dev_warn(DEV, "Allocation of an epoch failed, slowing down\n");
/* Fall through */
case WO_bdev_flush:
case WO_drain_io:
drbd_wait_ee_list_empty(mdev, &mdev->active_ee);
drbd_flush(mdev);
if (atomic_read(&mdev->current_epoch->epoch_size)) {
epoch = kmalloc(sizeof(struct drbd_epoch), GFP_NOIO);
if (epoch)
break;
}
epoch = mdev->current_epoch;
wait_event(mdev->ee_wait, atomic_read(&epoch->epoch_size) == 0);
D_ASSERT(atomic_read(&epoch->active) == 0);
D_ASSERT(epoch->flags == 0);
return true;
default:
dev_err(DEV, "Strangeness in mdev->write_ordering %d\n", mdev->write_ordering);
return false;
}
epoch->flags = 0;
atomic_set(&epoch->epoch_size, 0);
atomic_set(&epoch->active, 0);
spin_lock(&mdev->epoch_lock);
if (atomic_read(&mdev->current_epoch->epoch_size)) {
list_add(&epoch->list, &mdev->current_epoch->list);
mdev->current_epoch = epoch;
mdev->epochs++;
} else {
/* The current_epoch got recycled while we allocated this one... */
kfree(epoch);
}
spin_unlock(&mdev->epoch_lock);
return true;
}
/* used from receive_RSDataReply (recv_resync_read)
* and from receive_Data */
static struct drbd_epoch_entry *
read_in_block(struct drbd_conf *mdev, u64 id, sector_t sector, int data_size) __must_hold(local)
{
const sector_t capacity = drbd_get_capacity(mdev->this_bdev);
struct drbd_epoch_entry *e;
struct page *page;
int dgs, ds, rr;
void *dig_in = mdev->int_dig_in;
void *dig_vv = mdev->int_dig_vv;
unsigned long *data;
dgs = (mdev->agreed_pro_version >= 87 && mdev->integrity_r_tfm) ?
crypto_hash_digestsize(mdev->integrity_r_tfm) : 0;
if (dgs) {
rr = drbd_recv(mdev, dig_in, dgs);
if (rr != dgs) {
if (!signal_pending(current))
dev_warn(DEV,
"short read receiving data digest: read %d expected %d\n",
rr, dgs);
return NULL;
}
}
data_size -= dgs;
ERR_IF(data_size == 0) return NULL;
ERR_IF(data_size & 0x1ff) return NULL;
ERR_IF(data_size > DRBD_MAX_BIO_SIZE) return NULL;
/* even though we trust out peer,
* we sometimes have to double check. */
if (sector + (data_size>>9) > capacity) {
dev_err(DEV, "request from peer beyond end of local disk: "
"capacity: %llus < sector: %llus + size: %u\n",
(unsigned long long)capacity,
(unsigned long long)sector, data_size);
return NULL;
}
/* GFP_NOIO, because we must not cause arbitrary write-out: in a DRBD
* "criss-cross" setup, that might cause write-out on some other DRBD,
* which in turn might block on the other node at this very place. */
e = drbd_alloc_ee(mdev, id, sector, data_size, GFP_NOIO);
if (!e)
return NULL;
ds = data_size;
page = e->pages;
page_chain_for_each(page) {
unsigned len = min_t(int, ds, PAGE_SIZE);
data = kmap(page);
rr = drbd_recv(mdev, data, len);
if (drbd_insert_fault(mdev, DRBD_FAULT_RECEIVE)) {
dev_err(DEV, "Fault injection: Corrupting data on receive\n");
data[0] = data[0] ^ (unsigned long)-1;
}
kunmap(page);
if (rr != len) {
drbd_free_ee(mdev, e);
if (!signal_pending(current))
dev_warn(DEV, "short read receiving data: read %d expected %d\n",
rr, len);
return NULL;
}
ds -= rr;
}
if (dgs) {
drbd_csum_ee(mdev, mdev->integrity_r_tfm, e, dig_vv);
if (memcmp(dig_in, dig_vv, dgs)) {
dev_err(DEV, "Digest integrity check FAILED: %llus +%u\n",
(unsigned long long)sector, data_size);
drbd_bcast_ee(mdev, "digest failed",
dgs, dig_in, dig_vv, e);
drbd_free_ee(mdev, e);
return NULL;
}
}
mdev->recv_cnt += data_size>>9;
return e;
}
/* drbd_drain_block() just takes a data block
* out of the socket input buffer, and discards it.
*/
static int drbd_drain_block(struct drbd_conf *mdev, int data_size)
{
struct page *page;
int rr, rv = 1;
void *data;
if (!data_size)
return true;
page = drbd_pp_alloc(mdev, 1, 1);
data = kmap(page);
while (data_size) {
rr = drbd_recv(mdev, data, min_t(int, data_size, PAGE_SIZE));
if (rr != min_t(int, data_size, PAGE_SIZE)) {
rv = 0;
if (!signal_pending(current))
dev_warn(DEV,
"short read receiving data: read %d expected %d\n",
rr, min_t(int, data_size, PAGE_SIZE));
break;
}
data_size -= rr;
}
kunmap(page);
drbd_pp_free(mdev, page, 0);
return rv;
}
static int recv_dless_read(struct drbd_conf *mdev, struct drbd_request *req,
sector_t sector, int data_size)
{
struct bio_vec *bvec;
struct bio *bio;
int dgs, rr, i, expect;
void *dig_in = mdev->int_dig_in;
void *dig_vv = mdev->int_dig_vv;
dgs = (mdev->agreed_pro_version >= 87 && mdev->integrity_r_tfm) ?
crypto_hash_digestsize(mdev->integrity_r_tfm) : 0;
if (dgs) {
rr = drbd_recv(mdev, dig_in, dgs);
if (rr != dgs) {
if (!signal_pending(current))
dev_warn(DEV,
"short read receiving data reply digest: read %d expected %d\n",
rr, dgs);
return 0;
}
}
data_size -= dgs;
/* optimistically update recv_cnt. if receiving fails below,
* we disconnect anyways, and counters will be reset. */
mdev->recv_cnt += data_size>>9;
bio = req->master_bio;
D_ASSERT(sector == bio->bi_sector);
bio_for_each_segment(bvec, bio, i) {
expect = min_t(int, data_size, bvec->bv_len);
rr = drbd_recv(mdev,
kmap(bvec->bv_page)+bvec->bv_offset,
expect);
kunmap(bvec->bv_page);
if (rr != expect) {
if (!signal_pending(current))
dev_warn(DEV, "short read receiving data reply: "
"read %d expected %d\n",
rr, expect);
return 0;
}
data_size -= rr;
}
if (dgs) {
drbd_csum_bio(mdev, mdev->integrity_r_tfm, bio, dig_vv);
if (memcmp(dig_in, dig_vv, dgs)) {
dev_err(DEV, "Digest integrity check FAILED. Broken NICs?\n");
return 0;
}
}
D_ASSERT(data_size == 0);
return 1;
}
/* e_end_resync_block() is called via
* drbd_process_done_ee() by asender only */
static int e_end_resync_block(struct drbd_conf *mdev, struct drbd_work *w, int unused)
{
struct drbd_epoch_entry *e = (struct drbd_epoch_entry *)w;
sector_t sector = e->sector;
int ok;
D_ASSERT(hlist_unhashed(&e->collision));
if (likely((e->flags & EE_WAS_ERROR) == 0)) {
drbd_set_in_sync(mdev, sector, e->size);
ok = drbd_send_ack(mdev, P_RS_WRITE_ACK, e);
} else {
/* Record failure to sync */
drbd_rs_failed_io(mdev, sector, e->size);
ok = drbd_send_ack(mdev, P_NEG_ACK, e);
}
dec_unacked(mdev);
return ok;
}
static int recv_resync_read(struct drbd_conf *mdev, sector_t sector, int data_size) __releases(local)
{
struct drbd_epoch_entry *e;
e = read_in_block(mdev, ID_SYNCER, sector, data_size);
if (!e)
goto fail;
dec_rs_pending(mdev);
inc_unacked(mdev);
/* corresponding dec_unacked() in e_end_resync_block()
* respective _drbd_clear_done_ee */
e->w.cb = e_end_resync_block;
spin_lock_irq(&mdev->req_lock);
list_add(&e->w.list, &mdev->sync_ee);
spin_unlock_irq(&mdev->req_lock);
atomic_add(data_size >> 9, &mdev->rs_sect_ev);
if (drbd_submit_ee(mdev, e, WRITE, DRBD_FAULT_RS_WR) == 0)
return true;
/* don't care for the reason here */
dev_err(DEV, "submit failed, triggering re-connect\n");
spin_lock_irq(&mdev->req_lock);
list_del(&e->w.list);
spin_unlock_irq(&mdev->req_lock);
drbd_free_ee(mdev, e);
fail:
put_ldev(mdev);
return false;
}
static int receive_DataReply(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
struct drbd_request *req;
sector_t sector;
int ok;
struct p_data *p = &mdev->data.rbuf.data;
sector = be64_to_cpu(p->sector);
spin_lock_irq(&mdev->req_lock);
req = _ar_id_to_req(mdev, p->block_id, sector);
spin_unlock_irq(&mdev->req_lock);
if (unlikely(!req)) {
dev_err(DEV, "Got a corrupt block_id/sector pair(1).\n");
return false;
}
/* hlist_del(&req->collision) is done in _req_may_be_done, to avoid
* special casing it there for the various failure cases.
* still no race with drbd_fail_pending_reads */
ok = recv_dless_read(mdev, req, sector, data_size);
if (ok)
req_mod(req, data_received);
/* else: nothing. handled from drbd_disconnect...
* I don't think we may complete this just yet
* in case we are "on-disconnect: freeze" */
return ok;
}
static int receive_RSDataReply(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
sector_t sector;
int ok;
struct p_data *p = &mdev->data.rbuf.data;
sector = be64_to_cpu(p->sector);
D_ASSERT(p->block_id == ID_SYNCER);
if (get_ldev(mdev)) {
/* data is submitted to disk within recv_resync_read.
* corresponding put_ldev done below on error,
* or in drbd_endio_write_sec. */
ok = recv_resync_read(mdev, sector, data_size);
} else {
if (__ratelimit(&drbd_ratelimit_state))
dev_err(DEV, "Can not write resync data to local disk.\n");
ok = drbd_drain_block(mdev, data_size);
drbd_send_ack_dp(mdev, P_NEG_ACK, p, data_size);
}
atomic_add(data_size >> 9, &mdev->rs_sect_in);
return ok;
}
/* e_end_block() is called via drbd_process_done_ee().
* this means this function only runs in the asender thread
*/
static int e_end_block(struct drbd_conf *mdev, struct drbd_work *w, int cancel)
{
struct drbd_epoch_entry *e = (struct drbd_epoch_entry *)w;
sector_t sector = e->sector;
int ok = 1, pcmd;
if (mdev->net_conf->wire_protocol == DRBD_PROT_C) {
if (likely((e->flags & EE_WAS_ERROR) == 0)) {
pcmd = (mdev->state.conn >= C_SYNC_SOURCE &&
mdev->state.conn <= C_PAUSED_SYNC_T &&
e->flags & EE_MAY_SET_IN_SYNC) ?
P_RS_WRITE_ACK : P_WRITE_ACK;
ok &= drbd_send_ack(mdev, pcmd, e);
if (pcmd == P_RS_WRITE_ACK)
drbd_set_in_sync(mdev, sector, e->size);
} else {
ok = drbd_send_ack(mdev, P_NEG_ACK, e);
/* we expect it to be marked out of sync anyways...
* maybe assert this? */
}
dec_unacked(mdev);
}
/* we delete from the conflict detection hash _after_ we sent out the
* P_WRITE_ACK / P_NEG_ACK, to get the sequence number right. */
if (mdev->net_conf->two_primaries) {
spin_lock_irq(&mdev->req_lock);
D_ASSERT(!hlist_unhashed(&e->collision));
hlist_del_init(&e->collision);
spin_unlock_irq(&mdev->req_lock);
} else {
D_ASSERT(hlist_unhashed(&e->collision));
}
drbd_may_finish_epoch(mdev, e->epoch, EV_PUT + (cancel ? EV_CLEANUP : 0));
return ok;
}
static int e_send_discard_ack(struct drbd_conf *mdev, struct drbd_work *w, int unused)
{
struct drbd_epoch_entry *e = (struct drbd_epoch_entry *)w;
int ok = 1;
D_ASSERT(mdev->net_conf->wire_protocol == DRBD_PROT_C);
ok = drbd_send_ack(mdev, P_DISCARD_ACK, e);
spin_lock_irq(&mdev->req_lock);
D_ASSERT(!hlist_unhashed(&e->collision));
hlist_del_init(&e->collision);
spin_unlock_irq(&mdev->req_lock);
dec_unacked(mdev);
return ok;
}
/* Called from receive_Data.
* Synchronize packets on sock with packets on msock.
*
* This is here so even when a P_DATA packet traveling via sock overtook an Ack
* packet traveling on msock, they are still processed in the order they have
* been sent.
*
* Note: we don't care for Ack packets overtaking P_DATA packets.
*
* In case packet_seq is larger than mdev->peer_seq number, there are
* outstanding packets on the msock. We wait for them to arrive.
* In case we are the logically next packet, we update mdev->peer_seq
* ourselves. Correctly handles 32bit wrap around.
*
* Assume we have a 10 GBit connection, that is about 1<<30 byte per second,
* about 1<<21 sectors per second. So "worst" case, we have 1<<3 == 8 seconds
* for the 24bit wrap (historical atomic_t guarantee on some archs), and we have
* 1<<9 == 512 seconds aka ages for the 32bit wrap around...
*
* returns 0 if we may process the packet,
* -ERESTARTSYS if we were interrupted (by disconnect signal). */
static int drbd_wait_peer_seq(struct drbd_conf *mdev, const u32 packet_seq)
{
DEFINE_WAIT(wait);
unsigned int p_seq;
long timeout;
int ret = 0;
spin_lock(&mdev->peer_seq_lock);
for (;;) {
prepare_to_wait(&mdev->seq_wait, &wait, TASK_INTERRUPTIBLE);
if (seq_le(packet_seq, mdev->peer_seq+1))
break;
if (signal_pending(current)) {
ret = -ERESTARTSYS;
break;
}
p_seq = mdev->peer_seq;
spin_unlock(&mdev->peer_seq_lock);
timeout = schedule_timeout(30*HZ);
spin_lock(&mdev->peer_seq_lock);
if (timeout == 0 && p_seq == mdev->peer_seq) {
ret = -ETIMEDOUT;
dev_err(DEV, "ASSERT FAILED waited 30 seconds for sequence update, forcing reconnect\n");
break;
}
}
finish_wait(&mdev->seq_wait, &wait);
if (mdev->peer_seq+1 == packet_seq)
mdev->peer_seq++;
spin_unlock(&mdev->peer_seq_lock);
return ret;
}
/* see also bio_flags_to_wire()
* DRBD_REQ_*, because we need to semantically map the flags to data packet
* flags and back. We may replicate to other kernel versions. */
static unsigned long wire_flags_to_bio(struct drbd_conf *mdev, u32 dpf)
{
return (dpf & DP_RW_SYNC ? REQ_SYNC : 0) |
(dpf & DP_FUA ? REQ_FUA : 0) |
(dpf & DP_FLUSH ? REQ_FLUSH : 0) |
(dpf & DP_DISCARD ? REQ_DISCARD : 0);
}
/* mirrored write */
static int receive_Data(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
sector_t sector;
struct drbd_epoch_entry *e;
struct p_data *p = &mdev->data.rbuf.data;
int rw = WRITE;
u32 dp_flags;
if (!get_ldev(mdev)) {
spin_lock(&mdev->peer_seq_lock);
if (mdev->peer_seq+1 == be32_to_cpu(p->seq_num))
mdev->peer_seq++;
spin_unlock(&mdev->peer_seq_lock);
drbd_send_ack_dp(mdev, P_NEG_ACK, p, data_size);
atomic_inc(&mdev->current_epoch->epoch_size);
return drbd_drain_block(mdev, data_size);
}
/* get_ldev(mdev) successful.
* Corresponding put_ldev done either below (on various errors),
* or in drbd_endio_write_sec, if we successfully submit the data at
* the end of this function. */
sector = be64_to_cpu(p->sector);
e = read_in_block(mdev, p->block_id, sector, data_size);
if (!e) {
put_ldev(mdev);
return false;
}
e->w.cb = e_end_block;
dp_flags = be32_to_cpu(p->dp_flags);
rw |= wire_flags_to_bio(mdev, dp_flags);
if (dp_flags & DP_MAY_SET_IN_SYNC)
e->flags |= EE_MAY_SET_IN_SYNC;
spin_lock(&mdev->epoch_lock);
e->epoch = mdev->current_epoch;
atomic_inc(&e->epoch->epoch_size);
atomic_inc(&e->epoch->active);
spin_unlock(&mdev->epoch_lock);
/* I'm the receiver, I do hold a net_cnt reference. */
if (!mdev->net_conf->two_primaries) {
spin_lock_irq(&mdev->req_lock);
} else {
/* don't get the req_lock yet,
* we may sleep in drbd_wait_peer_seq */
const int size = e->size;
const int discard = test_bit(DISCARD_CONCURRENT, &mdev->flags);
DEFINE_WAIT(wait);
struct drbd_request *i;
struct hlist_node *n;
struct hlist_head *slot;
int first;
D_ASSERT(mdev->net_conf->wire_protocol == DRBD_PROT_C);
BUG_ON(mdev->ee_hash == NULL);
BUG_ON(mdev->tl_hash == NULL);
/* conflict detection and handling:
* 1. wait on the sequence number,
* in case this data packet overtook ACK packets.
* 2. check our hash tables for conflicting requests.
* we only need to walk the tl_hash, since an ee can not
* have a conflict with an other ee: on the submitting
* node, the corresponding req had already been conflicting,
* and a conflicting req is never sent.
*
* Note: for two_primaries, we are protocol C,
* so there cannot be any request that is DONE
* but still on the transfer log.
*
* unconditionally add to the ee_hash.
*
* if no conflicting request is found:
* submit.
*
* if any conflicting request is found
* that has not yet been acked,
* AND I have the "discard concurrent writes" flag:
* queue (via done_ee) the P_DISCARD_ACK; OUT.
*
* if any conflicting request is found:
* block the receiver, waiting on misc_wait
* until no more conflicting requests are there,
* or we get interrupted (disconnect).
*
* we do not just write after local io completion of those
* requests, but only after req is done completely, i.e.
* we wait for the P_DISCARD_ACK to arrive!
*
* then proceed normally, i.e. submit.
*/
if (drbd_wait_peer_seq(mdev, be32_to_cpu(p->seq_num)))
goto out_interrupted;
spin_lock_irq(&mdev->req_lock);
hlist_add_head(&e->collision, ee_hash_slot(mdev, sector));
#define OVERLAPS overlaps(i->sector, i->size, sector, size)
slot = tl_hash_slot(mdev, sector);
first = 1;
for (;;) {
int have_unacked = 0;
int have_conflict = 0;
prepare_to_wait(&mdev->misc_wait, &wait,
TASK_INTERRUPTIBLE);
hlist_for_each_entry(i, n, slot, collision) {
if (OVERLAPS) {
/* only ALERT on first iteration,
* we may be woken up early... */
if (first)
dev_alert(DEV, "%s[%u] Concurrent local write detected!"
" new: %llus +%u; pending: %llus +%u\n",
current->comm, current->pid,
(unsigned long long)sector, size,
(unsigned long long)i->sector, i->size);
if (i->rq_state & RQ_NET_PENDING)
++have_unacked;
++have_conflict;
}
}
#undef OVERLAPS
if (!have_conflict)
break;
/* Discard Ack only for the _first_ iteration */
if (first && discard && have_unacked) {
dev_alert(DEV, "Concurrent write! [DISCARD BY FLAG] sec=%llus\n",
(unsigned long long)sector);
inc_unacked(mdev);
e->w.cb = e_send_discard_ack;
list_add_tail(&e->w.list, &mdev->done_ee);
spin_unlock_irq(&mdev->req_lock);
/* we could probably send that P_DISCARD_ACK ourselves,
* but I don't like the receiver using the msock */
put_ldev(mdev);
wake_asender(mdev);
finish_wait(&mdev->misc_wait, &wait);
return true;
}
if (signal_pending(current)) {
hlist_del_init(&e->collision);
spin_unlock_irq(&mdev->req_lock);
finish_wait(&mdev->misc_wait, &wait);
goto out_interrupted;
}
spin_unlock_irq(&mdev->req_lock);
if (first) {
first = 0;
dev_alert(DEV, "Concurrent write! [W AFTERWARDS] "
"sec=%llus\n", (unsigned long long)sector);
} else if (discard) {
/* we had none on the first iteration.
* there must be none now. */
D_ASSERT(have_unacked == 0);
}
schedule();
spin_lock_irq(&mdev->req_lock);
}
finish_wait(&mdev->misc_wait, &wait);
}
list_add(&e->w.list, &mdev->active_ee);
spin_unlock_irq(&mdev->req_lock);
switch (mdev->net_conf->wire_protocol) {
case DRBD_PROT_C:
inc_unacked(mdev);
/* corresponding dec_unacked() in e_end_block()
* respective _drbd_clear_done_ee */
break;
case DRBD_PROT_B:
/* I really don't like it that the receiver thread
* sends on the msock, but anyways */
drbd_send_ack(mdev, P_RECV_ACK, e);
break;
case DRBD_PROT_A:
/* nothing to do */
break;
}
if (mdev->state.pdsk < D_INCONSISTENT) {
/* In case we have the only disk of the cluster, */
drbd_set_out_of_sync(mdev, e->sector, e->size);
e->flags |= EE_CALL_AL_COMPLETE_IO;
e->flags &= ~EE_MAY_SET_IN_SYNC;
drbd_al_begin_io(mdev, e->sector);
}
if (drbd_submit_ee(mdev, e, rw, DRBD_FAULT_DT_WR) == 0)
return true;
/* don't care for the reason here */
dev_err(DEV, "submit failed, triggering re-connect\n");
spin_lock_irq(&mdev->req_lock);
list_del(&e->w.list);
hlist_del_init(&e->collision);
spin_unlock_irq(&mdev->req_lock);
if (e->flags & EE_CALL_AL_COMPLETE_IO)
drbd_al_complete_io(mdev, e->sector);
out_interrupted:
drbd_may_finish_epoch(mdev, e->epoch, EV_PUT + EV_CLEANUP);
put_ldev(mdev);
drbd_free_ee(mdev, e);
return false;
}
/* We may throttle resync, if the lower device seems to be busy,
* and current sync rate is above c_min_rate.
*
* To decide whether or not the lower device is busy, we use a scheme similar
* to MD RAID is_mddev_idle(): if the partition stats reveal "significant"
* (more than 64 sectors) of activity we cannot account for with our own resync
* activity, it obviously is "busy".
*
* The current sync rate used here uses only the most recent two step marks,
* to have a short time average so we can react faster.
*/
int drbd_rs_should_slow_down(struct drbd_conf *mdev, sector_t sector)
{
struct gendisk *disk = mdev->ldev->backing_bdev->bd_contains->bd_disk;
unsigned long db, dt, dbdt;
struct lc_element *tmp;
int curr_events;
int throttle = 0;
/* feature disabled? */
if (mdev->sync_conf.c_min_rate == 0)
return 0;
spin_lock_irq(&mdev->al_lock);
tmp = lc_find(mdev->resync, BM_SECT_TO_EXT(sector));
if (tmp) {
struct bm_extent *bm_ext = lc_entry(tmp, struct bm_extent, lce);
if (test_bit(BME_PRIORITY, &bm_ext->flags)) {
spin_unlock_irq(&mdev->al_lock);
return 0;
}
/* Do not slow down if app IO is already waiting for this extent */
}
spin_unlock_irq(&mdev->al_lock);
curr_events = (int)part_stat_read(&disk->part0, sectors[0]) +
(int)part_stat_read(&disk->part0, sectors[1]) -
atomic_read(&mdev->rs_sect_ev);
if (!mdev->rs_last_events || curr_events - mdev->rs_last_events > 64) {
unsigned long rs_left;
int i;
mdev->rs_last_events = curr_events;
/* sync speed average over the last 2*DRBD_SYNC_MARK_STEP,
* approx. */
i = (mdev->rs_last_mark + DRBD_SYNC_MARKS-1) % DRBD_SYNC_MARKS;
if (mdev->state.conn == C_VERIFY_S || mdev->state.conn == C_VERIFY_T)
rs_left = mdev->ov_left;
else
rs_left = drbd_bm_total_weight(mdev) - mdev->rs_failed;
dt = ((long)jiffies - (long)mdev->rs_mark_time[i]) / HZ;
if (!dt)
dt++;
db = mdev->rs_mark_left[i] - rs_left;
dbdt = Bit2KB(db/dt);
if (dbdt > mdev->sync_conf.c_min_rate)
throttle = 1;
}
return throttle;
}
static int receive_DataRequest(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int digest_size)
{
sector_t sector;
const sector_t capacity = drbd_get_capacity(mdev->this_bdev);
struct drbd_epoch_entry *e;
struct digest_info *di = NULL;
int size, verb;
unsigned int fault_type;
struct p_block_req *p = &mdev->data.rbuf.block_req;
sector = be64_to_cpu(p->sector);
size = be32_to_cpu(p->blksize);
if (size <= 0 || (size & 0x1ff) != 0 || size > DRBD_MAX_BIO_SIZE) {
dev_err(DEV, "%s:%d: sector: %llus, size: %u\n", __FILE__, __LINE__,
(unsigned long long)sector, size);
return false;
}
if (sector + (size>>9) > capacity) {
dev_err(DEV, "%s:%d: sector: %llus, size: %u\n", __FILE__, __LINE__,
(unsigned long long)sector, size);
return false;
}
if (!get_ldev_if_state(mdev, D_UP_TO_DATE)) {
verb = 1;
switch (cmd) {
case P_DATA_REQUEST:
drbd_send_ack_rp(mdev, P_NEG_DREPLY, p);
break;
case P_RS_DATA_REQUEST:
case P_CSUM_RS_REQUEST:
case P_OV_REQUEST:
drbd_send_ack_rp(mdev, P_NEG_RS_DREPLY , p);
break;
case P_OV_REPLY:
verb = 0;
dec_rs_pending(mdev);
drbd_send_ack_ex(mdev, P_OV_RESULT, sector, size, ID_IN_SYNC);
break;
default:
dev_err(DEV, "unexpected command (%s) in receive_DataRequest\n",
cmdname(cmd));
}
if (verb && __ratelimit(&drbd_ratelimit_state))
dev_err(DEV, "Can not satisfy peer's read request, "
"no local data.\n");
/* drain possibly payload */
return drbd_drain_block(mdev, digest_size);
}
/* GFP_NOIO, because we must not cause arbitrary write-out: in a DRBD
* "criss-cross" setup, that might cause write-out on some other DRBD,
* which in turn might block on the other node at this very place. */
e = drbd_alloc_ee(mdev, p->block_id, sector, size, GFP_NOIO);
if (!e) {
put_ldev(mdev);
return false;
}
switch (cmd) {
case P_DATA_REQUEST:
e->w.cb = w_e_end_data_req;
fault_type = DRBD_FAULT_DT_RD;
/* application IO, don't drbd_rs_begin_io */
goto submit;
case P_RS_DATA_REQUEST:
e->w.cb = w_e_end_rsdata_req;
fault_type = DRBD_FAULT_RS_RD;
/* used in the sector offset progress display */
mdev->bm_resync_fo = BM_SECT_TO_BIT(sector);
break;
case P_OV_REPLY:
case P_CSUM_RS_REQUEST:
fault_type = DRBD_FAULT_RS_RD;
di = kmalloc(sizeof(*di) + digest_size, GFP_NOIO);
if (!di)
goto out_free_e;
di->digest_size = digest_size;
di->digest = (((char *)di)+sizeof(struct digest_info));
e->digest = di;
e->flags |= EE_HAS_DIGEST;
if (drbd_recv(mdev, di->digest, digest_size) != digest_size)
goto out_free_e;
if (cmd == P_CSUM_RS_REQUEST) {
D_ASSERT(mdev->agreed_pro_version >= 89);
e->w.cb = w_e_end_csum_rs_req;
/* used in the sector offset progress display */
mdev->bm_resync_fo = BM_SECT_TO_BIT(sector);
} else if (cmd == P_OV_REPLY) {
/* track progress, we may need to throttle */
atomic_add(size >> 9, &mdev->rs_sect_in);
e->w.cb = w_e_end_ov_reply;
dec_rs_pending(mdev);
/* drbd_rs_begin_io done when we sent this request,
* but accounting still needs to be done. */
goto submit_for_resync;
}
break;
case P_OV_REQUEST:
if (mdev->ov_start_sector == ~(sector_t)0 &&
mdev->agreed_pro_version >= 90) {
unsigned long now = jiffies;
int i;
mdev->ov_start_sector = sector;
mdev->ov_position = sector;
mdev->ov_left = drbd_bm_bits(mdev) - BM_SECT_TO_BIT(sector);
mdev->rs_total = mdev->ov_left;
for (i = 0; i < DRBD_SYNC_MARKS; i++) {
mdev->rs_mark_left[i] = mdev->ov_left;
mdev->rs_mark_time[i] = now;
}
dev_info(DEV, "Online Verify start sector: %llu\n",
(unsigned long long)sector);
}
e->w.cb = w_e_end_ov_req;
fault_type = DRBD_FAULT_RS_RD;
break;
default:
dev_err(DEV, "unexpected command (%s) in receive_DataRequest\n",
cmdname(cmd));
fault_type = DRBD_FAULT_MAX;
goto out_free_e;
}
/* Throttle, drbd_rs_begin_io and submit should become asynchronous
* wrt the receiver, but it is not as straightforward as it may seem.
* Various places in the resync start and stop logic assume resync
* requests are processed in order, requeuing this on the worker thread
* introduces a bunch of new code for synchronization between threads.
*
* Unlimited throttling before drbd_rs_begin_io may stall the resync
* "forever", throttling after drbd_rs_begin_io will lock that extent
* for application writes for the same time. For now, just throttle
* here, where the rest of the code expects the receiver to sleep for
* a while, anyways.
*/
/* Throttle before drbd_rs_begin_io, as that locks out application IO;
* this defers syncer requests for some time, before letting at least
* on request through. The resync controller on the receiving side
* will adapt to the incoming rate accordingly.
*
* We cannot throttle here if remote is Primary/SyncTarget:
* we would also throttle its application reads.
* In that case, throttling is done on the SyncTarget only.
*/
if (mdev->state.peer != R_PRIMARY && drbd_rs_should_slow_down(mdev, sector))
schedule_timeout_uninterruptible(HZ/10);
if (drbd_rs_begin_io(mdev, sector))
goto out_free_e;
submit_for_resync:
atomic_add(size >> 9, &mdev->rs_sect_ev);
submit:
inc_unacked(mdev);
spin_lock_irq(&mdev->req_lock);
list_add_tail(&e->w.list, &mdev->read_ee);
spin_unlock_irq(&mdev->req_lock);
if (drbd_submit_ee(mdev, e, READ, fault_type) == 0)
return true;
/* don't care for the reason here */
dev_err(DEV, "submit failed, triggering re-connect\n");
spin_lock_irq(&mdev->req_lock);
list_del(&e->w.list);
spin_unlock_irq(&mdev->req_lock);
/* no drbd_rs_complete_io(), we are dropping the connection anyways */
out_free_e:
put_ldev(mdev);
drbd_free_ee(mdev, e);
return false;
}
static int drbd_asb_recover_0p(struct drbd_conf *mdev) __must_hold(local)
{
int self, peer, rv = -100;
unsigned long ch_self, ch_peer;
self = mdev->ldev->md.uuid[UI_BITMAP] & 1;
peer = mdev->p_uuid[UI_BITMAP] & 1;
ch_peer = mdev->p_uuid[UI_SIZE];
ch_self = mdev->comm_bm_set;
switch (mdev->net_conf->after_sb_0p) {
case ASB_CONSENSUS:
case ASB_DISCARD_SECONDARY:
case ASB_CALL_HELPER:
dev_err(DEV, "Configuration error.\n");
break;
case ASB_DISCONNECT:
break;
case ASB_DISCARD_YOUNGER_PRI:
if (self == 0 && peer == 1) {
rv = -1;
break;
}
if (self == 1 && peer == 0) {
rv = 1;
break;
}
/* Else fall through to one of the other strategies... */
case ASB_DISCARD_OLDER_PRI:
if (self == 0 && peer == 1) {
rv = 1;
break;
}
if (self == 1 && peer == 0) {
rv = -1;
break;
}
/* Else fall through to one of the other strategies... */
dev_warn(DEV, "Discard younger/older primary did not find a decision\n"
"Using discard-least-changes instead\n");
case ASB_DISCARD_ZERO_CHG:
if (ch_peer == 0 && ch_self == 0) {
rv = test_bit(DISCARD_CONCURRENT, &mdev->flags)
? -1 : 1;
break;
} else {
if (ch_peer == 0) { rv = 1; break; }
if (ch_self == 0) { rv = -1; break; }
}
if (mdev->net_conf->after_sb_0p == ASB_DISCARD_ZERO_CHG)
break;
case ASB_DISCARD_LEAST_CHG:
if (ch_self < ch_peer)
rv = -1;
else if (ch_self > ch_peer)
rv = 1;
else /* ( ch_self == ch_peer ) */
/* Well, then use something else. */
rv = test_bit(DISCARD_CONCURRENT, &mdev->flags)
? -1 : 1;
break;
case ASB_DISCARD_LOCAL:
rv = -1;
break;
case ASB_DISCARD_REMOTE:
rv = 1;
}
return rv;
}
static int drbd_asb_recover_1p(struct drbd_conf *mdev) __must_hold(local)
{
int hg, rv = -100;
switch (mdev->net_conf->after_sb_1p) {
case ASB_DISCARD_YOUNGER_PRI:
case ASB_DISCARD_OLDER_PRI:
case ASB_DISCARD_LEAST_CHG:
case ASB_DISCARD_LOCAL:
case ASB_DISCARD_REMOTE:
dev_err(DEV, "Configuration error.\n");
break;
case ASB_DISCONNECT:
break;
case ASB_CONSENSUS:
hg = drbd_asb_recover_0p(mdev);
if (hg == -1 && mdev->state.role == R_SECONDARY)
rv = hg;
if (hg == 1 && mdev->state.role == R_PRIMARY)
rv = hg;
break;
case ASB_VIOLENTLY:
rv = drbd_asb_recover_0p(mdev);
break;
case ASB_DISCARD_SECONDARY:
return mdev->state.role == R_PRIMARY ? 1 : -1;
case ASB_CALL_HELPER:
hg = drbd_asb_recover_0p(mdev);
if (hg == -1 && mdev->state.role == R_PRIMARY) {
enum drbd_state_rv rv2;
drbd_set_role(mdev, R_SECONDARY, 0);
/* drbd_change_state() does not sleep while in SS_IN_TRANSIENT_STATE,
* we might be here in C_WF_REPORT_PARAMS which is transient.
* we do not need to wait for the after state change work either. */
rv2 = drbd_change_state(mdev, CS_VERBOSE, NS(role, R_SECONDARY));
if (rv2 != SS_SUCCESS) {
drbd_khelper(mdev, "pri-lost-after-sb");
} else {
dev_warn(DEV, "Successfully gave up primary role.\n");
rv = hg;
}
} else
rv = hg;
}
return rv;
}
static int drbd_asb_recover_2p(struct drbd_conf *mdev) __must_hold(local)
{
int hg, rv = -100;
switch (mdev->net_conf->after_sb_2p) {
case ASB_DISCARD_YOUNGER_PRI:
case ASB_DISCARD_OLDER_PRI:
case ASB_DISCARD_LEAST_CHG:
case ASB_DISCARD_LOCAL:
case ASB_DISCARD_REMOTE:
case ASB_CONSENSUS:
case ASB_DISCARD_SECONDARY:
dev_err(DEV, "Configuration error.\n");
break;
case ASB_VIOLENTLY:
rv = drbd_asb_recover_0p(mdev);
break;
case ASB_DISCONNECT:
break;
case ASB_CALL_HELPER:
hg = drbd_asb_recover_0p(mdev);
if (hg == -1) {
enum drbd_state_rv rv2;
/* drbd_change_state() does not sleep while in SS_IN_TRANSIENT_STATE,
* we might be here in C_WF_REPORT_PARAMS which is transient.
* we do not need to wait for the after state change work either. */
rv2 = drbd_change_state(mdev, CS_VERBOSE, NS(role, R_SECONDARY));
if (rv2 != SS_SUCCESS) {
drbd_khelper(mdev, "pri-lost-after-sb");
} else {
dev_warn(DEV, "Successfully gave up primary role.\n");
rv = hg;
}
} else
rv = hg;
}
return rv;
}
static void drbd_uuid_dump(struct drbd_conf *mdev, char *text, u64 *uuid,
u64 bits, u64 flags)
{
if (!uuid) {
dev_info(DEV, "%s uuid info vanished while I was looking!\n", text);
return;
}
dev_info(DEV, "%s %016llX:%016llX:%016llX:%016llX bits:%llu flags:%llX\n",
text,
(unsigned long long)uuid[UI_CURRENT],
(unsigned long long)uuid[UI_BITMAP],
(unsigned long long)uuid[UI_HISTORY_START],
(unsigned long long)uuid[UI_HISTORY_END],
(unsigned long long)bits,
(unsigned long long)flags);
}
/*
100 after split brain try auto recover
2 C_SYNC_SOURCE set BitMap
1 C_SYNC_SOURCE use BitMap
0 no Sync
-1 C_SYNC_TARGET use BitMap
-2 C_SYNC_TARGET set BitMap
-100 after split brain, disconnect
-1000 unrelated data
-1091 requires proto 91
-1096 requires proto 96
*/
static int drbd_uuid_compare(struct drbd_conf *mdev, int *rule_nr) __must_hold(local)
{
u64 self, peer;
int i, j;
self = mdev->ldev->md.uuid[UI_CURRENT] & ~((u64)1);
peer = mdev->p_uuid[UI_CURRENT] & ~((u64)1);
*rule_nr = 10;
if (self == UUID_JUST_CREATED && peer == UUID_JUST_CREATED)
return 0;
*rule_nr = 20;
if ((self == UUID_JUST_CREATED || self == (u64)0) &&
peer != UUID_JUST_CREATED)
return -2;
*rule_nr = 30;
if (self != UUID_JUST_CREATED &&
(peer == UUID_JUST_CREATED || peer == (u64)0))
return 2;
if (self == peer) {
int rct, dc; /* roles at crash time */
if (mdev->p_uuid[UI_BITMAP] == (u64)0 && mdev->ldev->md.uuid[UI_BITMAP] != (u64)0) {
if (mdev->agreed_pro_version < 91)
return -1091;
if ((mdev->ldev->md.uuid[UI_BITMAP] & ~((u64)1)) == (mdev->p_uuid[UI_HISTORY_START] & ~((u64)1)) &&
(mdev->ldev->md.uuid[UI_HISTORY_START] & ~((u64)1)) == (mdev->p_uuid[UI_HISTORY_START + 1] & ~((u64)1))) {
dev_info(DEV, "was SyncSource, missed the resync finished event, corrected myself:\n");
drbd_uuid_set_bm(mdev, 0UL);
drbd_uuid_dump(mdev, "self", mdev->ldev->md.uuid,
mdev->state.disk >= D_NEGOTIATING ? drbd_bm_total_weight(mdev) : 0, 0);
*rule_nr = 34;
} else {
dev_info(DEV, "was SyncSource (peer failed to write sync_uuid)\n");
*rule_nr = 36;
}
return 1;
}
if (mdev->ldev->md.uuid[UI_BITMAP] == (u64)0 && mdev->p_uuid[UI_BITMAP] != (u64)0) {
if (mdev->agreed_pro_version < 91)
return -1091;
if ((mdev->ldev->md.uuid[UI_HISTORY_START] & ~((u64)1)) == (mdev->p_uuid[UI_BITMAP] & ~((u64)1)) &&
(mdev->ldev->md.uuid[UI_HISTORY_START + 1] & ~((u64)1)) == (mdev->p_uuid[UI_HISTORY_START] & ~((u64)1))) {
dev_info(DEV, "was SyncTarget, peer missed the resync finished event, corrected peer:\n");
mdev->p_uuid[UI_HISTORY_START + 1] = mdev->p_uuid[UI_HISTORY_START];
mdev->p_uuid[UI_HISTORY_START] = mdev->p_uuid[UI_BITMAP];
mdev->p_uuid[UI_BITMAP] = 0UL;
drbd_uuid_dump(mdev, "peer", mdev->p_uuid, mdev->p_uuid[UI_SIZE], mdev->p_uuid[UI_FLAGS]);
*rule_nr = 35;
} else {
dev_info(DEV, "was SyncTarget (failed to write sync_uuid)\n");
*rule_nr = 37;
}
return -1;
}
/* Common power [off|failure] */
rct = (test_bit(CRASHED_PRIMARY, &mdev->flags) ? 1 : 0) +
(mdev->p_uuid[UI_FLAGS] & 2);
/* lowest bit is set when we were primary,
* next bit (weight 2) is set when peer was primary */
*rule_nr = 40;
switch (rct) {
case 0: /* !self_pri && !peer_pri */ return 0;
case 1: /* self_pri && !peer_pri */ return 1;
case 2: /* !self_pri && peer_pri */ return -1;
case 3: /* self_pri && peer_pri */
dc = test_bit(DISCARD_CONCURRENT, &mdev->flags);
return dc ? -1 : 1;
}
}
*rule_nr = 50;
peer = mdev->p_uuid[UI_BITMAP] & ~((u64)1);
if (self == peer)
return -1;
*rule_nr = 51;
peer = mdev->p_uuid[UI_HISTORY_START] & ~((u64)1);
if (self == peer) {
if (mdev->agreed_pro_version < 96 ?
(mdev->ldev->md.uuid[UI_HISTORY_START] & ~((u64)1)) ==
(mdev->p_uuid[UI_HISTORY_START + 1] & ~((u64)1)) :
peer + UUID_NEW_BM_OFFSET == (mdev->p_uuid[UI_BITMAP] & ~((u64)1))) {
/* The last P_SYNC_UUID did not get though. Undo the last start of
resync as sync source modifications of the peer's UUIDs. */
if (mdev->agreed_pro_version < 91)
return -1091;
mdev->p_uuid[UI_BITMAP] = mdev->p_uuid[UI_HISTORY_START];
mdev->p_uuid[UI_HISTORY_START] = mdev->p_uuid[UI_HISTORY_START + 1];
dev_info(DEV, "Did not got last syncUUID packet, corrected:\n");
drbd_uuid_dump(mdev, "peer", mdev->p_uuid, mdev->p_uuid[UI_SIZE], mdev->p_uuid[UI_FLAGS]);
return -1;
}
}
*rule_nr = 60;
self = mdev->ldev->md.uuid[UI_CURRENT] & ~((u64)1);
for (i = UI_HISTORY_START; i <= UI_HISTORY_END; i++) {
peer = mdev->p_uuid[i] & ~((u64)1);
if (self == peer)
return -2;
}
*rule_nr = 70;
self = mdev->ldev->md.uuid[UI_BITMAP] & ~((u64)1);
peer = mdev->p_uuid[UI_CURRENT] & ~((u64)1);
if (self == peer)
return 1;
*rule_nr = 71;
self = mdev->ldev->md.uuid[UI_HISTORY_START] & ~((u64)1);
if (self == peer) {
if (mdev->agreed_pro_version < 96 ?
(mdev->ldev->md.uuid[UI_HISTORY_START + 1] & ~((u64)1)) ==
(mdev->p_uuid[UI_HISTORY_START] & ~((u64)1)) :
self + UUID_NEW_BM_OFFSET == (mdev->ldev->md.uuid[UI_BITMAP] & ~((u64)1))) {
/* The last P_SYNC_UUID did not get though. Undo the last start of
resync as sync source modifications of our UUIDs. */
if (mdev->agreed_pro_version < 91)
return -1091;
_drbd_uuid_set(mdev, UI_BITMAP, mdev->ldev->md.uuid[UI_HISTORY_START]);
_drbd_uuid_set(mdev, UI_HISTORY_START, mdev->ldev->md.uuid[UI_HISTORY_START + 1]);
dev_info(DEV, "Last syncUUID did not get through, corrected:\n");
drbd_uuid_dump(mdev, "self", mdev->ldev->md.uuid,
mdev->state.disk >= D_NEGOTIATING ? drbd_bm_total_weight(mdev) : 0, 0);
return 1;
}
}
*rule_nr = 80;
peer = mdev->p_uuid[UI_CURRENT] & ~((u64)1);
for (i = UI_HISTORY_START; i <= UI_HISTORY_END; i++) {
self = mdev->ldev->md.uuid[i] & ~((u64)1);
if (self == peer)
return 2;
}
*rule_nr = 90;
self = mdev->ldev->md.uuid[UI_BITMAP] & ~((u64)1);
peer = mdev->p_uuid[UI_BITMAP] & ~((u64)1);
if (self == peer && self != ((u64)0))
return 100;
*rule_nr = 100;
for (i = UI_HISTORY_START; i <= UI_HISTORY_END; i++) {
self = mdev->ldev->md.uuid[i] & ~((u64)1);
for (j = UI_HISTORY_START; j <= UI_HISTORY_END; j++) {
peer = mdev->p_uuid[j] & ~((u64)1);
if (self == peer)
return -100;
}
}
return -1000;
}
/* drbd_sync_handshake() returns the new conn state on success, or
CONN_MASK (-1) on failure.
*/
static enum drbd_conns drbd_sync_handshake(struct drbd_conf *mdev, enum drbd_role peer_role,
enum drbd_disk_state peer_disk) __must_hold(local)
{
int hg, rule_nr;
enum drbd_conns rv = C_MASK;
enum drbd_disk_state mydisk;
mydisk = mdev->state.disk;
if (mydisk == D_NEGOTIATING)
mydisk = mdev->new_state_tmp.disk;
dev_info(DEV, "drbd_sync_handshake:\n");
drbd_uuid_dump(mdev, "self", mdev->ldev->md.uuid, mdev->comm_bm_set, 0);
drbd_uuid_dump(mdev, "peer", mdev->p_uuid,
mdev->p_uuid[UI_SIZE], mdev->p_uuid[UI_FLAGS]);
hg = drbd_uuid_compare(mdev, &rule_nr);
dev_info(DEV, "uuid_compare()=%d by rule %d\n", hg, rule_nr);
if (hg == -1000) {
dev_alert(DEV, "Unrelated data, aborting!\n");
return C_MASK;
}
if (hg < -1000) {
dev_alert(DEV, "To resolve this both sides have to support at least protocol %d\n", -hg - 1000);
return C_MASK;
}
if ((mydisk == D_INCONSISTENT && peer_disk > D_INCONSISTENT) ||
(peer_disk == D_INCONSISTENT && mydisk > D_INCONSISTENT)) {
int f = (hg == -100) || abs(hg) == 2;
hg = mydisk > D_INCONSISTENT ? 1 : -1;
if (f)
hg = hg*2;
dev_info(DEV, "Becoming sync %s due to disk states.\n",
hg > 0 ? "source" : "target");
}
if (abs(hg) == 100)
drbd_khelper(mdev, "initial-split-brain");
if (hg == 100 || (hg == -100 && mdev->net_conf->always_asbp)) {
int pcount = (mdev->state.role == R_PRIMARY)
+ (peer_role == R_PRIMARY);
int forced = (hg == -100);
switch (pcount) {
case 0:
hg = drbd_asb_recover_0p(mdev);
break;
case 1:
hg = drbd_asb_recover_1p(mdev);
break;
case 2:
hg = drbd_asb_recover_2p(mdev);
break;
}
if (abs(hg) < 100) {
dev_warn(DEV, "Split-Brain detected, %d primaries, "
"automatically solved. Sync from %s node\n",
pcount, (hg < 0) ? "peer" : "this");
if (forced) {
dev_warn(DEV, "Doing a full sync, since"
" UUIDs where ambiguous.\n");
hg = hg*2;
}
}
}
if (hg == -100) {
if (mdev->net_conf->want_lose && !(mdev->p_uuid[UI_FLAGS]&1))
hg = -1;
if (!mdev->net_conf->want_lose && (mdev->p_uuid[UI_FLAGS]&1))
hg = 1;
if (abs(hg) < 100)
dev_warn(DEV, "Split-Brain detected, manually solved. "
"Sync from %s node\n",
(hg < 0) ? "peer" : "this");
}
if (hg == -100) {
/* FIXME this log message is not correct if we end up here
* after an attempted attach on a diskless node.
* We just refuse to attach -- well, we drop the "connection"
* to that disk, in a way... */
dev_alert(DEV, "Split-Brain detected but unresolved, dropping connection!\n");
drbd_khelper(mdev, "split-brain");
return C_MASK;
}
if (hg > 0 && mydisk <= D_INCONSISTENT) {
dev_err(DEV, "I shall become SyncSource, but I am inconsistent!\n");
return C_MASK;
}
if (hg < 0 && /* by intention we do not use mydisk here. */
mdev->state.role == R_PRIMARY && mdev->state.disk >= D_CONSISTENT) {
switch (mdev->net_conf->rr_conflict) {
case ASB_CALL_HELPER:
drbd_khelper(mdev, "pri-lost");
/* fall through */
case ASB_DISCONNECT:
dev_err(DEV, "I shall become SyncTarget, but I am primary!\n");
return C_MASK;
case ASB_VIOLENTLY:
dev_warn(DEV, "Becoming SyncTarget, violating the stable-data"
"assumption\n");
}
}
if (mdev->net_conf->dry_run || test_bit(CONN_DRY_RUN, &mdev->flags)) {
if (hg == 0)
dev_info(DEV, "dry-run connect: No resync, would become Connected immediately.\n");
else
dev_info(DEV, "dry-run connect: Would become %s, doing a %s resync.",
drbd_conn_str(hg > 0 ? C_SYNC_SOURCE : C_SYNC_TARGET),
abs(hg) >= 2 ? "full" : "bit-map based");
return C_MASK;
}
if (abs(hg) >= 2) {
dev_info(DEV, "Writing the whole bitmap, full sync required after drbd_sync_handshake.\n");
if (drbd_bitmap_io(mdev, &drbd_bmio_set_n_write, "set_n_write from sync_handshake",
BM_LOCKED_SET_ALLOWED))
return C_MASK;
}
if (hg > 0) { /* become sync source. */
rv = C_WF_BITMAP_S;
} else if (hg < 0) { /* become sync target */
rv = C_WF_BITMAP_T;
} else {
rv = C_CONNECTED;
if (drbd_bm_total_weight(mdev)) {
dev_info(DEV, "No resync, but %lu bits in bitmap!\n",
drbd_bm_total_weight(mdev));
}
}
return rv;
}
/* returns 1 if invalid */
static int cmp_after_sb(enum drbd_after_sb_p peer, enum drbd_after_sb_p self)
{
/* ASB_DISCARD_REMOTE - ASB_DISCARD_LOCAL is valid */
if ((peer == ASB_DISCARD_REMOTE && self == ASB_DISCARD_LOCAL) ||
(self == ASB_DISCARD_REMOTE && peer == ASB_DISCARD_LOCAL))
return 0;
/* any other things with ASB_DISCARD_REMOTE or ASB_DISCARD_LOCAL are invalid */
if (peer == ASB_DISCARD_REMOTE || peer == ASB_DISCARD_LOCAL ||
self == ASB_DISCARD_REMOTE || self == ASB_DISCARD_LOCAL)
return 1;
/* everything else is valid if they are equal on both sides. */
if (peer == self)
return 0;
/* everything es is invalid. */
return 1;
}
static int receive_protocol(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
struct p_protocol *p = &mdev->data.rbuf.protocol;
int p_proto, p_after_sb_0p, p_after_sb_1p, p_after_sb_2p;
int p_want_lose, p_two_primaries, cf;
char p_integrity_alg[SHARED_SECRET_MAX] = "";
p_proto = be32_to_cpu(p->protocol);
p_after_sb_0p = be32_to_cpu(p->after_sb_0p);
p_after_sb_1p = be32_to_cpu(p->after_sb_1p);
p_after_sb_2p = be32_to_cpu(p->after_sb_2p);
p_two_primaries = be32_to_cpu(p->two_primaries);
cf = be32_to_cpu(p->conn_flags);
p_want_lose = cf & CF_WANT_LOSE;
clear_bit(CONN_DRY_RUN, &mdev->flags);
if (cf & CF_DRY_RUN)
set_bit(CONN_DRY_RUN, &mdev->flags);
if (p_proto != mdev->net_conf->wire_protocol) {
dev_err(DEV, "incompatible communication protocols\n");
goto disconnect;
}
if (cmp_after_sb(p_after_sb_0p, mdev->net_conf->after_sb_0p)) {
dev_err(DEV, "incompatible after-sb-0pri settings\n");
goto disconnect;
}
if (cmp_after_sb(p_after_sb_1p, mdev->net_conf->after_sb_1p)) {
dev_err(DEV, "incompatible after-sb-1pri settings\n");
goto disconnect;
}
if (cmp_after_sb(p_after_sb_2p, mdev->net_conf->after_sb_2p)) {
dev_err(DEV, "incompatible after-sb-2pri settings\n");
goto disconnect;
}
if (p_want_lose && mdev->net_conf->want_lose) {
dev_err(DEV, "both sides have the 'want_lose' flag set\n");
goto disconnect;
}
if (p_two_primaries != mdev->net_conf->two_primaries) {
dev_err(DEV, "incompatible setting of the two-primaries options\n");
goto disconnect;
}
if (mdev->agreed_pro_version >= 87) {
unsigned char *my_alg = mdev->net_conf->integrity_alg;
if (drbd_recv(mdev, p_integrity_alg, data_size) != data_size)
return false;
p_integrity_alg[SHARED_SECRET_MAX-1] = 0;
if (strcmp(p_integrity_alg, my_alg)) {
dev_err(DEV, "incompatible setting of the data-integrity-alg\n");
goto disconnect;
}
dev_info(DEV, "data-integrity-alg: %s\n",
my_alg[0] ? my_alg : (unsigned char *)"<not-used>");
}
return true;
disconnect:
drbd_force_state(mdev, NS(conn, C_DISCONNECTING));
return false;
}
/* helper function
* input: alg name, feature name
* return: NULL (alg name was "")
* ERR_PTR(error) if something goes wrong
* or the crypto hash ptr, if it worked out ok. */
struct crypto_hash *drbd_crypto_alloc_digest_safe(const struct drbd_conf *mdev,
const char *alg, const char *name)
{
struct crypto_hash *tfm;
if (!alg[0])
return NULL;
tfm = crypto_alloc_hash(alg, 0, CRYPTO_ALG_ASYNC);
if (IS_ERR(tfm)) {
dev_err(DEV, "Can not allocate \"%s\" as %s (reason: %ld)\n",
alg, name, PTR_ERR(tfm));
return tfm;
}
if (!drbd_crypto_is_hash(crypto_hash_tfm(tfm))) {
crypto_free_hash(tfm);
dev_err(DEV, "\"%s\" is not a digest (%s)\n", alg, name);
return ERR_PTR(-EINVAL);
}
return tfm;
}
static int receive_SyncParam(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int packet_size)
{
int ok = true;
struct p_rs_param_95 *p = &mdev->data.rbuf.rs_param_95;
unsigned int header_size, data_size, exp_max_sz;
struct crypto_hash *verify_tfm = NULL;
struct crypto_hash *csums_tfm = NULL;
const int apv = mdev->agreed_pro_version;
int *rs_plan_s = NULL;
int fifo_size = 0;
exp_max_sz = apv <= 87 ? sizeof(struct p_rs_param)
: apv == 88 ? sizeof(struct p_rs_param)
+ SHARED_SECRET_MAX
: apv <= 94 ? sizeof(struct p_rs_param_89)
: /* apv >= 95 */ sizeof(struct p_rs_param_95);
if (packet_size > exp_max_sz) {
dev_err(DEV, "SyncParam packet too long: received %u, expected <= %u bytes\n",
packet_size, exp_max_sz);
return false;
}
if (apv <= 88) {
header_size = sizeof(struct p_rs_param) - sizeof(struct p_header80);
data_size = packet_size - header_size;
} else if (apv <= 94) {
header_size = sizeof(struct p_rs_param_89) - sizeof(struct p_header80);
data_size = packet_size - header_size;
D_ASSERT(data_size == 0);
} else {
header_size = sizeof(struct p_rs_param_95) - sizeof(struct p_header80);
data_size = packet_size - header_size;
D_ASSERT(data_size == 0);
}
/* initialize verify_alg and csums_alg */
memset(p->verify_alg, 0, 2 * SHARED_SECRET_MAX);
if (drbd_recv(mdev, &p->head.payload, header_size) != header_size)
return false;
mdev->sync_conf.rate = be32_to_cpu(p->rate);
if (apv >= 88) {
if (apv == 88) {
if (data_size > SHARED_SECRET_MAX) {
dev_err(DEV, "verify-alg too long, "
"peer wants %u, accepting only %u byte\n",
data_size, SHARED_SECRET_MAX);
return false;
}
if (drbd_recv(mdev, p->verify_alg, data_size) != data_size)
return false;
/* we expect NUL terminated string */
/* but just in case someone tries to be evil */
D_ASSERT(p->verify_alg[data_size-1] == 0);
p->verify_alg[data_size-1] = 0;
} else /* apv >= 89 */ {
/* we still expect NUL terminated strings */
/* but just in case someone tries to be evil */
D_ASSERT(p->verify_alg[SHARED_SECRET_MAX-1] == 0);
D_ASSERT(p->csums_alg[SHARED_SECRET_MAX-1] == 0);
p->verify_alg[SHARED_SECRET_MAX-1] = 0;
p->csums_alg[SHARED_SECRET_MAX-1] = 0;
}
if (strcmp(mdev->sync_conf.verify_alg, p->verify_alg)) {
if (mdev->state.conn == C_WF_REPORT_PARAMS) {
dev_err(DEV, "Different verify-alg settings. me=\"%s\" peer=\"%s\"\n",
mdev->sync_conf.verify_alg, p->verify_alg);
goto disconnect;
}
verify_tfm = drbd_crypto_alloc_digest_safe(mdev,
p->verify_alg, "verify-alg");
if (IS_ERR(verify_tfm)) {
verify_tfm = NULL;
goto disconnect;
}
}
if (apv >= 89 && strcmp(mdev->sync_conf.csums_alg, p->csums_alg)) {
if (mdev->state.conn == C_WF_REPORT_PARAMS) {
dev_err(DEV, "Different csums-alg settings. me=\"%s\" peer=\"%s\"\n",
mdev->sync_conf.csums_alg, p->csums_alg);
goto disconnect;
}
csums_tfm = drbd_crypto_alloc_digest_safe(mdev,
p->csums_alg, "csums-alg");
if (IS_ERR(csums_tfm)) {
csums_tfm = NULL;
goto disconnect;
}
}
if (apv > 94) {
mdev->sync_conf.rate = be32_to_cpu(p->rate);
mdev->sync_conf.c_plan_ahead = be32_to_cpu(p->c_plan_ahead);
mdev->sync_conf.c_delay_target = be32_to_cpu(p->c_delay_target);
mdev->sync_conf.c_fill_target = be32_to_cpu(p->c_fill_target);
mdev->sync_conf.c_max_rate = be32_to_cpu(p->c_max_rate);
fifo_size = (mdev->sync_conf.c_plan_ahead * 10 * SLEEP_TIME) / HZ;
if (fifo_size != mdev->rs_plan_s.size && fifo_size > 0) {
rs_plan_s = kzalloc(sizeof(int) * fifo_size, GFP_KERNEL);
if (!rs_plan_s) {
dev_err(DEV, "kmalloc of fifo_buffer failed");
goto disconnect;
}
}
}
spin_lock(&mdev->peer_seq_lock);
/* lock against drbd_nl_syncer_conf() */
if (verify_tfm) {
strcpy(mdev->sync_conf.verify_alg, p->verify_alg);
mdev->sync_conf.verify_alg_len = strlen(p->verify_alg) + 1;
crypto_free_hash(mdev->verify_tfm);
mdev->verify_tfm = verify_tfm;
dev_info(DEV, "using verify-alg: \"%s\"\n", p->verify_alg);
}
if (csums_tfm) {
strcpy(mdev->sync_conf.csums_alg, p->csums_alg);
mdev->sync_conf.csums_alg_len = strlen(p->csums_alg) + 1;
crypto_free_hash(mdev->csums_tfm);
mdev->csums_tfm = csums_tfm;
dev_info(DEV, "using csums-alg: \"%s\"\n", p->csums_alg);
}
if (fifo_size != mdev->rs_plan_s.size) {
kfree(mdev->rs_plan_s.values);
mdev->rs_plan_s.values = rs_plan_s;
mdev->rs_plan_s.size = fifo_size;
mdev->rs_planed = 0;
}
spin_unlock(&mdev->peer_seq_lock);
}
return ok;
disconnect:
/* just for completeness: actually not needed,
* as this is not reached if csums_tfm was ok. */
crypto_free_hash(csums_tfm);
/* but free the verify_tfm again, if csums_tfm did not work out */
crypto_free_hash(verify_tfm);
drbd_force_state(mdev, NS(conn, C_DISCONNECTING));
return false;
}
/* warn if the arguments differ by more than 12.5% */
static void warn_if_differ_considerably(struct drbd_conf *mdev,
const char *s, sector_t a, sector_t b)
{
sector_t d;
if (a == 0 || b == 0)
return;
d = (a > b) ? (a - b) : (b - a);
if (d > (a>>3) || d > (b>>3))
dev_warn(DEV, "Considerable difference in %s: %llus vs. %llus\n", s,
(unsigned long long)a, (unsigned long long)b);
}
static int receive_sizes(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
struct p_sizes *p = &mdev->data.rbuf.sizes;
enum determine_dev_size dd = unchanged;
sector_t p_size, p_usize, my_usize;
int ldsc = 0; /* local disk size changed */
enum dds_flags ddsf;
p_size = be64_to_cpu(p->d_size);
p_usize = be64_to_cpu(p->u_size);
if (p_size == 0 && mdev->state.disk == D_DISKLESS) {
dev_err(DEV, "some backing storage is needed\n");
drbd_force_state(mdev, NS(conn, C_DISCONNECTING));
return false;
}
/* just store the peer's disk size for now.
* we still need to figure out whether we accept that. */
mdev->p_size = p_size;
if (get_ldev(mdev)) {
warn_if_differ_considerably(mdev, "lower level device sizes",
p_size, drbd_get_max_capacity(mdev->ldev));
warn_if_differ_considerably(mdev, "user requested size",
p_usize, mdev->ldev->dc.disk_size);
/* if this is the first connect, or an otherwise expected
* param exchange, choose the minimum */
if (mdev->state.conn == C_WF_REPORT_PARAMS)
p_usize = min_not_zero((sector_t)mdev->ldev->dc.disk_size,
p_usize);
my_usize = mdev->ldev->dc.disk_size;
if (mdev->ldev->dc.disk_size != p_usize) {
mdev->ldev->dc.disk_size = p_usize;
dev_info(DEV, "Peer sets u_size to %lu sectors\n",
(unsigned long)mdev->ldev->dc.disk_size);
}
/* Never shrink a device with usable data during connect.
But allow online shrinking if we are connected. */
if (drbd_new_dev_size(mdev, mdev->ldev, 0) <
drbd_get_capacity(mdev->this_bdev) &&
mdev->state.disk >= D_OUTDATED &&
mdev->state.conn < C_CONNECTED) {
dev_err(DEV, "The peer's disk size is too small!\n");
drbd_force_state(mdev, NS(conn, C_DISCONNECTING));
mdev->ldev->dc.disk_size = my_usize;
put_ldev(mdev);
return false;
}
put_ldev(mdev);
}
ddsf = be16_to_cpu(p->dds_flags);
if (get_ldev(mdev)) {
dd = drbd_determine_dev_size(mdev, ddsf);
put_ldev(mdev);
if (dd == dev_size_error)
return false;
drbd_md_sync(mdev);
} else {
/* I am diskless, need to accept the peer's size. */
drbd_set_my_capacity(mdev, p_size);
}
mdev->peer_max_bio_size = be32_to_cpu(p->max_bio_size);
drbd_reconsider_max_bio_size(mdev);
if (get_ldev(mdev)) {
if (mdev->ldev->known_size != drbd_get_capacity(mdev->ldev->backing_bdev)) {
mdev->ldev->known_size = drbd_get_capacity(mdev->ldev->backing_bdev);
ldsc = 1;
}
put_ldev(mdev);
}
if (mdev->state.conn > C_WF_REPORT_PARAMS) {
if (be64_to_cpu(p->c_size) !=
drbd_get_capacity(mdev->this_bdev) || ldsc) {
/* we have different sizes, probably peer
* needs to know my new size... */
drbd_send_sizes(mdev, 0, ddsf);
}
if (test_and_clear_bit(RESIZE_PENDING, &mdev->flags) ||
(dd == grew && mdev->state.conn == C_CONNECTED)) {
if (mdev->state.pdsk >= D_INCONSISTENT &&
mdev->state.disk >= D_INCONSISTENT) {
if (ddsf & DDSF_NO_RESYNC)
dev_info(DEV, "Resync of new storage suppressed with --assume-clean\n");
else
resync_after_online_grow(mdev);
} else
set_bit(RESYNC_AFTER_NEG, &mdev->flags);
}
}
return true;
}
static int receive_uuids(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
struct p_uuids *p = &mdev->data.rbuf.uuids;
u64 *p_uuid;
int i, updated_uuids = 0;
p_uuid = kmalloc(sizeof(u64)*UI_EXTENDED_SIZE, GFP_NOIO);
for (i = UI_CURRENT; i < UI_EXTENDED_SIZE; i++)
p_uuid[i] = be64_to_cpu(p->uuid[i]);
kfree(mdev->p_uuid);
mdev->p_uuid = p_uuid;
if (mdev->state.conn < C_CONNECTED &&
mdev->state.disk < D_INCONSISTENT &&
mdev->state.role == R_PRIMARY &&
(mdev->ed_uuid & ~((u64)1)) != (p_uuid[UI_CURRENT] & ~((u64)1))) {
dev_err(DEV, "Can only connect to data with current UUID=%016llX\n",
(unsigned long long)mdev->ed_uuid);
drbd_force_state(mdev, NS(conn, C_DISCONNECTING));
return false;
}
if (get_ldev(mdev)) {
int skip_initial_sync =
mdev->state.conn == C_CONNECTED &&
mdev->agreed_pro_version >= 90 &&
mdev->ldev->md.uuid[UI_CURRENT] == UUID_JUST_CREATED &&
(p_uuid[UI_FLAGS] & 8);
if (skip_initial_sync) {
dev_info(DEV, "Accepted new current UUID, preparing to skip initial sync\n");
drbd_bitmap_io(mdev, &drbd_bmio_clear_n_write,
"clear_n_write from receive_uuids",
BM_LOCKED_TEST_ALLOWED);
_drbd_uuid_set(mdev, UI_CURRENT, p_uuid[UI_CURRENT]);
_drbd_uuid_set(mdev, UI_BITMAP, 0);
_drbd_set_state(_NS2(mdev, disk, D_UP_TO_DATE, pdsk, D_UP_TO_DATE),
CS_VERBOSE, NULL);
drbd_md_sync(mdev);
updated_uuids = 1;
}
put_ldev(mdev);
} else if (mdev->state.disk < D_INCONSISTENT &&
mdev->state.role == R_PRIMARY) {
/* I am a diskless primary, the peer just created a new current UUID
for me. */
updated_uuids = drbd_set_ed_uuid(mdev, p_uuid[UI_CURRENT]);
}
/* Before we test for the disk state, we should wait until an eventually
ongoing cluster wide state change is finished. That is important if
we are primary and are detaching from our disk. We need to see the
new disk state... */
wait_event(mdev->misc_wait, !test_bit(CLUSTER_ST_CHANGE, &mdev->flags));
if (mdev->state.conn >= C_CONNECTED && mdev->state.disk < D_INCONSISTENT)
updated_uuids |= drbd_set_ed_uuid(mdev, p_uuid[UI_CURRENT]);
if (updated_uuids)
drbd_print_uuids(mdev, "receiver updated UUIDs to");
return true;
}
/**
* convert_state() - Converts the peer's view of the cluster state to our point of view
* @ps: The state as seen by the peer.
*/
static union drbd_state convert_state(union drbd_state ps)
{
union drbd_state ms;
static enum drbd_conns c_tab[] = {
[C_CONNECTED] = C_CONNECTED,
[C_STARTING_SYNC_S] = C_STARTING_SYNC_T,
[C_STARTING_SYNC_T] = C_STARTING_SYNC_S,
[C_DISCONNECTING] = C_TEAR_DOWN, /* C_NETWORK_FAILURE, */
[C_VERIFY_S] = C_VERIFY_T,
[C_MASK] = C_MASK,
};
ms.i = ps.i;
ms.conn = c_tab[ps.conn];
ms.peer = ps.role;
ms.role = ps.peer;
ms.pdsk = ps.disk;
ms.disk = ps.pdsk;
ms.peer_isp = (ps.aftr_isp | ps.user_isp);
return ms;
}
static int receive_req_state(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
struct p_req_state *p = &mdev->data.rbuf.req_state;
union drbd_state mask, val;
enum drbd_state_rv rv;
mask.i = be32_to_cpu(p->mask);
val.i = be32_to_cpu(p->val);
if (test_bit(DISCARD_CONCURRENT, &mdev->flags) &&
test_bit(CLUSTER_ST_CHANGE, &mdev->flags)) {
drbd_send_sr_reply(mdev, SS_CONCURRENT_ST_CHG);
return true;
}
mask = convert_state(mask);
val = convert_state(val);
rv = drbd_change_state(mdev, CS_VERBOSE, mask, val);
drbd_send_sr_reply(mdev, rv);
drbd_md_sync(mdev);
return true;
}
static int receive_state(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
struct p_state *p = &mdev->data.rbuf.state;
union drbd_state os, ns, peer_state;
enum drbd_disk_state real_peer_disk;
enum chg_state_flags cs_flags;
int rv;
peer_state.i = be32_to_cpu(p->state);
real_peer_disk = peer_state.disk;
if (peer_state.disk == D_NEGOTIATING) {
real_peer_disk = mdev->p_uuid[UI_FLAGS] & 4 ? D_INCONSISTENT : D_CONSISTENT;
dev_info(DEV, "real peer disk state = %s\n", drbd_disk_str(real_peer_disk));
}
spin_lock_irq(&mdev->req_lock);
retry:
os = ns = mdev->state;
spin_unlock_irq(&mdev->req_lock);
/* peer says his disk is uptodate, while we think it is inconsistent,
* and this happens while we think we have a sync going on. */
if (os.pdsk == D_INCONSISTENT && real_peer_disk == D_UP_TO_DATE &&
os.conn > C_CONNECTED && os.disk == D_UP_TO_DATE) {
/* If we are (becoming) SyncSource, but peer is still in sync
* preparation, ignore its uptodate-ness to avoid flapping, it
* will change to inconsistent once the peer reaches active
* syncing states.
* It may have changed syncer-paused flags, however, so we
* cannot ignore this completely. */
if (peer_state.conn > C_CONNECTED &&
peer_state.conn < C_SYNC_SOURCE)
real_peer_disk = D_INCONSISTENT;
/* if peer_state changes to connected at the same time,
* it explicitly notifies us that it finished resync.
* Maybe we should finish it up, too? */
else if (os.conn >= C_SYNC_SOURCE &&
peer_state.conn == C_CONNECTED) {
if (drbd_bm_total_weight(mdev) <= mdev->rs_failed)
drbd_resync_finished(mdev);
return true;
}
}
/* peer says his disk is inconsistent, while we think it is uptodate,
* and this happens while the peer still thinks we have a sync going on,
* but we think we are already done with the sync.
* We ignore this to avoid flapping pdsk.
* This should not happen, if the peer is a recent version of drbd. */
if (os.pdsk == D_UP_TO_DATE && real_peer_disk == D_INCONSISTENT &&
os.conn == C_CONNECTED && peer_state.conn > C_SYNC_SOURCE)
real_peer_disk = D_UP_TO_DATE;
if (ns.conn == C_WF_REPORT_PARAMS)
ns.conn = C_CONNECTED;
if (peer_state.conn == C_AHEAD)
ns.conn = C_BEHIND;
if (mdev->p_uuid && peer_state.disk >= D_NEGOTIATING &&
get_ldev_if_state(mdev, D_NEGOTIATING)) {
int cr; /* consider resync */
/* if we established a new connection */
cr = (os.conn < C_CONNECTED);
/* if we had an established connection
* and one of the nodes newly attaches a disk */
cr |= (os.conn == C_CONNECTED &&
(peer_state.disk == D_NEGOTIATING ||
os.disk == D_NEGOTIATING));
/* if we have both been inconsistent, and the peer has been
* forced to be UpToDate with --overwrite-data */
cr |= test_bit(CONSIDER_RESYNC, &mdev->flags);
/* if we had been plain connected, and the admin requested to
* start a sync by "invalidate" or "invalidate-remote" */
cr |= (os.conn == C_CONNECTED &&
(peer_state.conn >= C_STARTING_SYNC_S &&
peer_state.conn <= C_WF_BITMAP_T));
if (cr)
ns.conn = drbd_sync_handshake(mdev, peer_state.role, real_peer_disk);
put_ldev(mdev);
if (ns.conn == C_MASK) {
ns.conn = C_CONNECTED;
if (mdev->state.disk == D_NEGOTIATING) {
drbd_force_state(mdev, NS(disk, D_FAILED));
} else if (peer_state.disk == D_NEGOTIATING) {
dev_err(DEV, "Disk attach process on the peer node was aborted.\n");
peer_state.disk = D_DISKLESS;
real_peer_disk = D_DISKLESS;
} else {
if (test_and_clear_bit(CONN_DRY_RUN, &mdev->flags))
return false;
D_ASSERT(os.conn == C_WF_REPORT_PARAMS);
drbd_force_state(mdev, NS(conn, C_DISCONNECTING));
return false;
}
}
}
spin_lock_irq(&mdev->req_lock);
if (mdev->state.i != os.i)
goto retry;
clear_bit(CONSIDER_RESYNC, &mdev->flags);
ns.peer = peer_state.role;
ns.pdsk = real_peer_disk;
ns.peer_isp = (peer_state.aftr_isp | peer_state.user_isp);
if ((ns.conn == C_CONNECTED || ns.conn == C_WF_BITMAP_S) && ns.disk == D_NEGOTIATING)
ns.disk = mdev->new_state_tmp.disk;
cs_flags = CS_VERBOSE + (os.conn < C_CONNECTED && ns.conn >= C_CONNECTED ? 0 : CS_HARD);
if (ns.pdsk == D_CONSISTENT && is_susp(ns) && ns.conn == C_CONNECTED && os.conn < C_CONNECTED &&
test_bit(NEW_CUR_UUID, &mdev->flags)) {
/* Do not allow tl_restart(resend) for a rebooted peer. We can only allow this
for temporal network outages! */
spin_unlock_irq(&mdev->req_lock);
dev_err(DEV, "Aborting Connect, can not thaw IO with an only Consistent peer\n");
tl_clear(mdev);
drbd_uuid_new_current(mdev);
clear_bit(NEW_CUR_UUID, &mdev->flags);
drbd_force_state(mdev, NS2(conn, C_PROTOCOL_ERROR, susp, 0));
return false;
}
rv = _drbd_set_state(mdev, ns, cs_flags, NULL);
ns = mdev->state;
spin_unlock_irq(&mdev->req_lock);
if (rv < SS_SUCCESS) {
drbd_force_state(mdev, NS(conn, C_DISCONNECTING));
return false;
}
if (os.conn > C_WF_REPORT_PARAMS) {
if (ns.conn > C_CONNECTED && peer_state.conn <= C_CONNECTED &&
peer_state.disk != D_NEGOTIATING ) {
/* we want resync, peer has not yet decided to sync... */
/* Nowadays only used when forcing a node into primary role and
setting its disk to UpToDate with that */
drbd_send_uuids(mdev);
drbd_send_state(mdev);
}
}
mdev->net_conf->want_lose = 0;
drbd_md_sync(mdev); /* update connected indicator, la_size, ... */
return true;
}
static int receive_sync_uuid(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
struct p_rs_uuid *p = &mdev->data.rbuf.rs_uuid;
wait_event(mdev->misc_wait,
mdev->state.conn == C_WF_SYNC_UUID ||
mdev->state.conn == C_BEHIND ||
mdev->state.conn < C_CONNECTED ||
mdev->state.disk < D_NEGOTIATING);
/* D_ASSERT( mdev->state.conn == C_WF_SYNC_UUID ); */
/* Here the _drbd_uuid_ functions are right, current should
_not_ be rotated into the history */
if (get_ldev_if_state(mdev, D_NEGOTIATING)) {
_drbd_uuid_set(mdev, UI_CURRENT, be64_to_cpu(p->uuid));
_drbd_uuid_set(mdev, UI_BITMAP, 0UL);
drbd_print_uuids(mdev, "updated sync uuid");
drbd_start_resync(mdev, C_SYNC_TARGET);
put_ldev(mdev);
} else
dev_err(DEV, "Ignoring SyncUUID packet!\n");
return true;
}
/**
* receive_bitmap_plain
*
* Return 0 when done, 1 when another iteration is needed, and a negative error
* code upon failure.
*/
static int
receive_bitmap_plain(struct drbd_conf *mdev, unsigned int data_size,
unsigned long *buffer, struct bm_xfer_ctx *c)
{
unsigned num_words = min_t(size_t, BM_PACKET_WORDS, c->bm_words - c->word_offset);
unsigned want = num_words * sizeof(long);
int err;
if (want != data_size) {
dev_err(DEV, "%s:want (%u) != data_size (%u)\n", __func__, want, data_size);
return -EIO;
}
if (want == 0)
return 0;
err = drbd_recv(mdev, buffer, want);
if (err != want) {
if (err >= 0)
err = -EIO;
return err;
}
drbd_bm_merge_lel(mdev, c->word_offset, num_words, buffer);
c->word_offset += num_words;
c->bit_offset = c->word_offset * BITS_PER_LONG;
if (c->bit_offset > c->bm_bits)
c->bit_offset = c->bm_bits;
return 1;
}
/**
* recv_bm_rle_bits
*
* Return 0 when done, 1 when another iteration is needed, and a negative error
* code upon failure.
*/
static int
recv_bm_rle_bits(struct drbd_conf *mdev,
struct p_compressed_bm *p,
struct bm_xfer_ctx *c)
{
struct bitstream bs;
u64 look_ahead;
u64 rl;
u64 tmp;
unsigned long s = c->bit_offset;
unsigned long e;
int len = be16_to_cpu(p->head.length) - (sizeof(*p) - sizeof(p->head));
int toggle = DCBP_get_start(p);
int have;
int bits;
bitstream_init(&bs, p->code, len, DCBP_get_pad_bits(p));
bits = bitstream_get_bits(&bs, &look_ahead, 64);
if (bits < 0)
return -EIO;
for (have = bits; have > 0; s += rl, toggle = !toggle) {
bits = vli_decode_bits(&rl, look_ahead);
if (bits <= 0)
return -EIO;
if (toggle) {
e = s + rl -1;
if (e >= c->bm_bits) {
dev_err(DEV, "bitmap overflow (e:%lu) while decoding bm RLE packet\n", e);
return -EIO;
}
_drbd_bm_set_bits(mdev, s, e);
}
if (have < bits) {
dev_err(DEV, "bitmap decoding error: h:%d b:%d la:0x%08llx l:%u/%u\n",
have, bits, look_ahead,
(unsigned int)(bs.cur.b - p->code),
(unsigned int)bs.buf_len);
return -EIO;
}
look_ahead >>= bits;
have -= bits;
bits = bitstream_get_bits(&bs, &tmp, 64 - have);
if (bits < 0)
return -EIO;
look_ahead |= tmp << have;
have += bits;
}
c->bit_offset = s;
bm_xfer_ctx_bit_to_word_offset(c);
return (s != c->bm_bits);
}
/**
* decode_bitmap_c
*
* Return 0 when done, 1 when another iteration is needed, and a negative error
* code upon failure.
*/
static int
decode_bitmap_c(struct drbd_conf *mdev,
struct p_compressed_bm *p,
struct bm_xfer_ctx *c)
{
if (DCBP_get_code(p) == RLE_VLI_Bits)
return recv_bm_rle_bits(mdev, p, c);
/* other variants had been implemented for evaluation,
* but have been dropped as this one turned out to be "best"
* during all our tests. */
dev_err(DEV, "receive_bitmap_c: unknown encoding %u\n", p->encoding);
drbd_force_state(mdev, NS(conn, C_PROTOCOL_ERROR));
return -EIO;
}
void INFO_bm_xfer_stats(struct drbd_conf *mdev,
const char *direction, struct bm_xfer_ctx *c)
{
/* what would it take to transfer it "plaintext" */
unsigned plain = sizeof(struct p_header80) *
((c->bm_words+BM_PACKET_WORDS-1)/BM_PACKET_WORDS+1)
+ c->bm_words * sizeof(long);
unsigned total = c->bytes[0] + c->bytes[1];
unsigned r;
/* total can not be zero. but just in case: */
if (total == 0)
return;
/* don't report if not compressed */
if (total >= plain)
return;
/* total < plain. check for overflow, still */
r = (total > UINT_MAX/1000) ? (total / (plain/1000))
: (1000 * total / plain);
if (r > 1000)
r = 1000;
r = 1000 - r;
dev_info(DEV, "%s bitmap stats [Bytes(packets)]: plain %u(%u), RLE %u(%u), "
"total %u; compression: %u.%u%%\n",
direction,
c->bytes[1], c->packets[1],
c->bytes[0], c->packets[0],
total, r/10, r % 10);
}
/* Since we are processing the bitfield from lower addresses to higher,
it does not matter if the process it in 32 bit chunks or 64 bit
chunks as long as it is little endian. (Understand it as byte stream,
beginning with the lowest byte...) If we would use big endian
we would need to process it from the highest address to the lowest,
in order to be agnostic to the 32 vs 64 bits issue.
returns 0 on failure, 1 if we successfully received it. */
static int receive_bitmap(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
struct bm_xfer_ctx c;
void *buffer;
int err;
int ok = false;
struct p_header80 *h = &mdev->data.rbuf.header.h80;
drbd_bm_lock(mdev, "receive bitmap", BM_LOCKED_SET_ALLOWED);
/* you are supposed to send additional out-of-sync information
* if you actually set bits during this phase */
/* maybe we should use some per thread scratch page,
* and allocate that during initial device creation? */
buffer = (unsigned long *) __get_free_page(GFP_NOIO);
if (!buffer) {
dev_err(DEV, "failed to allocate one page buffer in %s\n", __func__);
goto out;
}
c = (struct bm_xfer_ctx) {
.bm_bits = drbd_bm_bits(mdev),
.bm_words = drbd_bm_words(mdev),
};
for(;;) {
if (cmd == P_BITMAP) {
err = receive_bitmap_plain(mdev, data_size, buffer, &c);
} else if (cmd == P_COMPRESSED_BITMAP) {
/* MAYBE: sanity check that we speak proto >= 90,
* and the feature is enabled! */
struct p_compressed_bm *p;
if (data_size > BM_PACKET_PAYLOAD_BYTES) {
dev_err(DEV, "ReportCBitmap packet too large\n");
goto out;
}
/* use the page buff */
p = buffer;
memcpy(p, h, sizeof(*h));
if (drbd_recv(mdev, p->head.payload, data_size) != data_size)
goto out;
if (data_size <= (sizeof(*p) - sizeof(p->head))) {
dev_err(DEV, "ReportCBitmap packet too small (l:%u)\n", data_size);
goto out;
}
err = decode_bitmap_c(mdev, p, &c);
} else {
dev_warn(DEV, "receive_bitmap: cmd neither ReportBitMap nor ReportCBitMap (is 0x%x)", cmd);
goto out;
}
c.packets[cmd == P_BITMAP]++;
c.bytes[cmd == P_BITMAP] += sizeof(struct p_header80) + data_size;
if (err <= 0) {
if (err < 0)
goto out;
break;
}
if (!drbd_recv_header(mdev, &cmd, &data_size))
goto out;
}
INFO_bm_xfer_stats(mdev, "receive", &c);
if (mdev->state.conn == C_WF_BITMAP_T) {
enum drbd_state_rv rv;
ok = !drbd_send_bitmap(mdev);
if (!ok)
goto out;
/* Omit CS_ORDERED with this state transition to avoid deadlocks. */
rv = _drbd_request_state(mdev, NS(conn, C_WF_SYNC_UUID), CS_VERBOSE);
D_ASSERT(rv == SS_SUCCESS);
} else if (mdev->state.conn != C_WF_BITMAP_S) {
/* admin may have requested C_DISCONNECTING,
* other threads may have noticed network errors */
dev_info(DEV, "unexpected cstate (%s) in receive_bitmap\n",
drbd_conn_str(mdev->state.conn));
}
ok = true;
out:
drbd_bm_unlock(mdev);
if (ok && mdev->state.conn == C_WF_BITMAP_S)
drbd_start_resync(mdev, C_SYNC_SOURCE);
free_page((unsigned long) buffer);
return ok;
}
static int receive_skip(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
/* TODO zero copy sink :) */
static char sink[128];
int size, want, r;
dev_warn(DEV, "skipping unknown optional packet type %d, l: %d!\n",
cmd, data_size);
size = data_size;
while (size > 0) {
want = min_t(int, size, sizeof(sink));
r = drbd_recv(mdev, sink, want);
ERR_IF(r <= 0) break;
size -= r;
}
return size == 0;
}
static int receive_UnplugRemote(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
/* Make sure we've acked all the TCP data associated
* with the data requests being unplugged */
drbd_tcp_quickack(mdev->data.socket);
return true;
}
static int receive_out_of_sync(struct drbd_conf *mdev, enum drbd_packets cmd, unsigned int data_size)
{
struct p_block_desc *p = &mdev->data.rbuf.block_desc;
switch (mdev->state.conn) {
case C_WF_SYNC_UUID:
case C_WF_BITMAP_T:
case C_BEHIND:
break;
default:
dev_err(DEV, "ASSERT FAILED cstate = %s, expected: WFSyncUUID|WFBitMapT|Behind\n",
drbd_conn_str(mdev->state.conn));
}
drbd_set_out_of_sync(mdev, be64_to_cpu(p->sector), be32_to_cpu(p->blksize));
return true;
}
typedef int (*drbd_cmd_handler_f)(struct drbd_conf *, enum drbd_packets cmd, unsigned int to_receive);
struct data_cmd {
int expect_payload;
size_t pkt_size;
drbd_cmd_handler_f function;
};
static struct data_cmd drbd_cmd_handler[] = {
[P_DATA] = { 1, sizeof(struct p_data), receive_Data },
[P_DATA_REPLY] = { 1, sizeof(struct p_data), receive_DataReply },
[P_RS_DATA_REPLY] = { 1, sizeof(struct p_data), receive_RSDataReply } ,
[P_BARRIER] = { 0, sizeof(struct p_barrier), receive_Barrier } ,
[P_BITMAP] = { 1, sizeof(struct p_header80), receive_bitmap } ,
[P_COMPRESSED_BITMAP] = { 1, sizeof(struct p_header80), receive_bitmap } ,
[P_UNPLUG_REMOTE] = { 0, sizeof(struct p_header80), receive_UnplugRemote },
[P_DATA_REQUEST] = { 0, sizeof(struct p_block_req), receive_DataRequest },
[P_RS_DATA_REQUEST] = { 0, sizeof(struct p_block_req), receive_DataRequest },
[P_SYNC_PARAM] = { 1, sizeof(struct p_header80), receive_SyncParam },
[P_SYNC_PARAM89] = { 1, sizeof(struct p_header80), receive_SyncParam },
[P_PROTOCOL] = { 1, sizeof(struct p_protocol), receive_protocol },
[P_UUIDS] = { 0, sizeof(struct p_uuids), receive_uuids },
[P_SIZES] = { 0, sizeof(struct p_sizes), receive_sizes },
[P_STATE] = { 0, sizeof(struct p_state), receive_state },
[P_STATE_CHG_REQ] = { 0, sizeof(struct p_req_state), receive_req_state },
[P_SYNC_UUID] = { 0, sizeof(struct p_rs_uuid), receive_sync_uuid },
[P_OV_REQUEST] = { 0, sizeof(struct p_block_req), receive_DataRequest },
[P_OV_REPLY] = { 1, sizeof(struct p_block_req), receive_DataRequest },
[P_CSUM_RS_REQUEST] = { 1, sizeof(struct p_block_req), receive_DataRequest },
[P_DELAY_PROBE] = { 0, sizeof(struct p_delay_probe93), receive_skip },
[P_OUT_OF_SYNC] = { 0, sizeof(struct p_block_desc), receive_out_of_sync },
/* anything missing from this table is in
* the asender_tbl, see get_asender_cmd */
[P_MAX_CMD] = { 0, 0, NULL },
};
/* All handler functions that expect a sub-header get that sub-heder in
mdev->data.rbuf.header.head.payload.
Usually in mdev->data.rbuf.header.head the callback can find the usual
p_header, but they may not rely on that. Since there is also p_header95 !
*/
static void drbdd(struct drbd_conf *mdev)
{
union p_header *header = &mdev->data.rbuf.header;
unsigned int packet_size;
enum drbd_packets cmd;
size_t shs; /* sub header size */
int rv;
while (get_t_state(&mdev->receiver) == Running) {
drbd_thread_current_set_cpu(mdev);
if (!drbd_recv_header(mdev, &cmd, &packet_size))
goto err_out;
if (unlikely(cmd >= P_MAX_CMD || !drbd_cmd_handler[cmd].function)) {
dev_err(DEV, "unknown packet type %d, l: %d!\n", cmd, packet_size);
goto err_out;
}
shs = drbd_cmd_handler[cmd].pkt_size - sizeof(union p_header);
if (packet_size - shs > 0 && !drbd_cmd_handler[cmd].expect_payload) {
dev_err(DEV, "No payload expected %s l:%d\n", cmdname(cmd), packet_size);
goto err_out;
}
if (shs) {
rv = drbd_recv(mdev, &header->h80.payload, shs);
if (unlikely(rv != shs)) {
if (!signal_pending(current))
dev_warn(DEV, "short read while reading sub header: rv=%d\n", rv);
goto err_out;
}
}
rv = drbd_cmd_handler[cmd].function(mdev, cmd, packet_size - shs);
if (unlikely(!rv)) {
dev_err(DEV, "error receiving %s, l: %d!\n",
cmdname(cmd), packet_size);
goto err_out;
}
}
if (0) {
err_out:
drbd_force_state(mdev, NS(conn, C_PROTOCOL_ERROR));
}
/* If we leave here, we probably want to update at least the
* "Connected" indicator on stable storage. Do so explicitly here. */
drbd_md_sync(mdev);
}
void drbd_flush_workqueue(struct drbd_conf *mdev)
{
struct drbd_wq_barrier barr;
barr.w.cb = w_prev_work_done;
init_completion(&barr.done);
drbd_queue_work(&mdev->data.work, &barr.w);
wait_for_completion(&barr.done);
}
void drbd_free_tl_hash(struct drbd_conf *mdev)
{
struct hlist_head *h;
spin_lock_irq(&mdev->req_lock);
if (!mdev->tl_hash || mdev->state.conn != C_STANDALONE) {
spin_unlock_irq(&mdev->req_lock);
return;
}
/* paranoia code */
for (h = mdev->ee_hash; h < mdev->ee_hash + mdev->ee_hash_s; h++)
if (h->first)
dev_err(DEV, "ASSERT FAILED ee_hash[%u].first == %p, expected NULL\n",
(int)(h - mdev->ee_hash), h->first);
kfree(mdev->ee_hash);
mdev->ee_hash = NULL;
mdev->ee_hash_s = 0;
/* paranoia code */
for (h = mdev->tl_hash; h < mdev->tl_hash + mdev->tl_hash_s; h++)
if (h->first)
dev_err(DEV, "ASSERT FAILED tl_hash[%u] == %p, expected NULL\n",
(int)(h - mdev->tl_hash), h->first);
kfree(mdev->tl_hash);
mdev->tl_hash = NULL;
mdev->tl_hash_s = 0;
spin_unlock_irq(&mdev->req_lock);
}
static void drbd_disconnect(struct drbd_conf *mdev)
{
enum drbd_fencing_p fp;
union drbd_state os, ns;
int rv = SS_UNKNOWN_ERROR;
unsigned int i;
if (mdev->state.conn == C_STANDALONE)
return;
/* asender does not clean up anything. it must not interfere, either */
drbd_thread_stop(&mdev->asender);
drbd_free_sock(mdev);
/* wait for current activity to cease. */
spin_lock_irq(&mdev->req_lock);
_drbd_wait_ee_list_empty(mdev, &mdev->active_ee);
_drbd_wait_ee_list_empty(mdev, &mdev->sync_ee);
_drbd_wait_ee_list_empty(mdev, &mdev->read_ee);
spin_unlock_irq(&mdev->req_lock);
/* We do not have data structures that would allow us to
* get the rs_pending_cnt down to 0 again.
* * On C_SYNC_TARGET we do not have any data structures describing
* the pending RSDataRequest's we have sent.
* * On C_SYNC_SOURCE there is no data structure that tracks
* the P_RS_DATA_REPLY blocks that we sent to the SyncTarget.
* And no, it is not the sum of the reference counts in the
* resync_LRU. The resync_LRU tracks the whole operation including
* the disk-IO, while the rs_pending_cnt only tracks the blocks
* on the fly. */
drbd_rs_cancel_all(mdev);
mdev->rs_total = 0;
mdev->rs_failed = 0;
atomic_set(&mdev->rs_pending_cnt, 0);
wake_up(&mdev->misc_wait);
del_timer(&mdev->request_timer);
/* make sure syncer is stopped and w_resume_next_sg queued */
del_timer_sync(&mdev->resync_timer);
resync_timer_fn((unsigned long)mdev);
/* wait for all w_e_end_data_req, w_e_end_rsdata_req, w_send_barrier,
* w_make_resync_request etc. which may still be on the worker queue
* to be "canceled" */
drbd_flush_workqueue(mdev);
/* This also does reclaim_net_ee(). If we do this too early, we might
* miss some resync ee and pages.*/
drbd_process_done_ee(mdev);
kfree(mdev->p_uuid);
mdev->p_uuid = NULL;
if (!is_susp(mdev->state))
tl_clear(mdev);
dev_info(DEV, "Connection closed\n");
drbd_md_sync(mdev);
fp = FP_DONT_CARE;
if (get_ldev(mdev)) {
fp = mdev->ldev->dc.fencing;
put_ldev(mdev);
}
if (mdev->state.role == R_PRIMARY && fp >= FP_RESOURCE && mdev->state.pdsk >= D_UNKNOWN)
drbd_try_outdate_peer_async(mdev);
spin_lock_irq(&mdev->req_lock);
os = mdev->state;
if (os.conn >= C_UNCONNECTED) {
/* Do not restart in case we are C_DISCONNECTING */
ns = os;
ns.conn = C_UNCONNECTED;
rv = _drbd_set_state(mdev, ns, CS_VERBOSE, NULL);
}
spin_unlock_irq(&mdev->req_lock);
if (os.conn == C_DISCONNECTING) {
wait_event(mdev->net_cnt_wait, atomic_read(&mdev->net_cnt) == 0);
crypto_free_hash(mdev->cram_hmac_tfm);
mdev->cram_hmac_tfm = NULL;
kfree(mdev->net_conf);
mdev->net_conf = NULL;
drbd_request_state(mdev, NS(conn, C_STANDALONE));
}
/* serialize with bitmap writeout triggered by the state change,
* if any. */
wait_event(mdev->misc_wait, !test_bit(BITMAP_IO, &mdev->flags));
/* tcp_close and release of sendpage pages can be deferred. I don't
* want to use SO_LINGER, because apparently it can be deferred for
* more than 20 seconds (longest time I checked).
*
* Actually we don't care for exactly when the network stack does its
* put_page(), but release our reference on these pages right here.
*/
i = drbd_release_ee(mdev, &mdev->net_ee);
if (i)
dev_info(DEV, "net_ee not empty, killed %u entries\n", i);
i = atomic_read(&mdev->pp_in_use_by_net);
if (i)
dev_info(DEV, "pp_in_use_by_net = %d, expected 0\n", i);
i = atomic_read(&mdev->pp_in_use);
if (i)
dev_info(DEV, "pp_in_use = %d, expected 0\n", i);
D_ASSERT(list_empty(&mdev->read_ee));
D_ASSERT(list_empty(&mdev->active_ee));
D_ASSERT(list_empty(&mdev->sync_ee));
D_ASSERT(list_empty(&mdev->done_ee));
/* ok, no more ee's on the fly, it is safe to reset the epoch_size */
atomic_set(&mdev->current_epoch->epoch_size, 0);
D_ASSERT(list_empty(&mdev->current_epoch->list));
}
/*
* We support PRO_VERSION_MIN to PRO_VERSION_MAX. The protocol version
* we can agree on is stored in agreed_pro_version.
*
* feature flags and the reserved array should be enough room for future
* enhancements of the handshake protocol, and possible plugins...
*
* for now, they are expected to be zero, but ignored.
*/
static int drbd_send_handshake(struct drbd_conf *mdev)
{
/* ASSERT current == mdev->receiver ... */
struct p_handshake *p = &mdev->data.sbuf.handshake;
int ok;
if (mutex_lock_interruptible(&mdev->data.mutex)) {
dev_err(DEV, "interrupted during initial handshake\n");
return 0; /* interrupted. not ok. */
}
if (mdev->data.socket == NULL) {
mutex_unlock(&mdev->data.mutex);
return 0;
}
memset(p, 0, sizeof(*p));
p->protocol_min = cpu_to_be32(PRO_VERSION_MIN);
p->protocol_max = cpu_to_be32(PRO_VERSION_MAX);
ok = _drbd_send_cmd( mdev, mdev->data.socket, P_HAND_SHAKE,
(struct p_header80 *)p, sizeof(*p), 0 );
mutex_unlock(&mdev->data.mutex);
return ok;
}
/*
* return values:
* 1 yes, we have a valid connection
* 0 oops, did not work out, please try again
* -1 peer talks different language,
* no point in trying again, please go standalone.
*/
static int drbd_do_handshake(struct drbd_conf *mdev)
{
/* ASSERT current == mdev->receiver ... */
struct p_handshake *p = &mdev->data.rbuf.handshake;
const int expect = sizeof(struct p_handshake) - sizeof(struct p_header80);
unsigned int length;
enum drbd_packets cmd;
int rv;
rv = drbd_send_handshake(mdev);
if (!rv)
return 0;
rv = drbd_recv_header(mdev, &cmd, &length);
if (!rv)
return 0;
if (cmd != P_HAND_SHAKE) {
dev_err(DEV, "expected HandShake packet, received: %s (0x%04x)\n",
cmdname(cmd), cmd);
return -1;
}
if (length != expect) {
dev_err(DEV, "expected HandShake length: %u, received: %u\n",
expect, length);
return -1;
}
rv = drbd_recv(mdev, &p->head.payload, expect);
if (rv != expect) {
if (!signal_pending(current))
dev_warn(DEV, "short read receiving handshake packet: l=%u\n", rv);
return 0;
}
p->protocol_min = be32_to_cpu(p->protocol_min);
p->protocol_max = be32_to_cpu(p->protocol_max);
if (p->protocol_max == 0)
p->protocol_max = p->protocol_min;
if (PRO_VERSION_MAX < p->protocol_min ||
PRO_VERSION_MIN > p->protocol_max)
goto incompat;
mdev->agreed_pro_version = min_t(int, PRO_VERSION_MAX, p->protocol_max);
dev_info(DEV, "Handshake successful: "
"Agreed network protocol version %d\n", mdev->agreed_pro_version);
return 1;
incompat:
dev_err(DEV, "incompatible DRBD dialects: "
"I support %d-%d, peer supports %d-%d\n",
PRO_VERSION_MIN, PRO_VERSION_MAX,
p->protocol_min, p->protocol_max);
return -1;
}
#if !defined(CONFIG_CRYPTO_HMAC) && !defined(CONFIG_CRYPTO_HMAC_MODULE)
static int drbd_do_auth(struct drbd_conf *mdev)
{
dev_err(DEV, "This kernel was build without CONFIG_CRYPTO_HMAC.\n");
dev_err(DEV, "You need to disable 'cram-hmac-alg' in drbd.conf.\n");
return -1;
}
#else
#define CHALLENGE_LEN 64
/* Return value:
1 - auth succeeded,
0 - failed, try again (network error),
-1 - auth failed, don't try again.
*/
static int drbd_do_auth(struct drbd_conf *mdev)
{
char my_challenge[CHALLENGE_LEN]; /* 64 Bytes... */
struct scatterlist sg;
char *response = NULL;
char *right_response = NULL;
char *peers_ch = NULL;
unsigned int key_len = strlen(mdev->net_conf->shared_secret);
unsigned int resp_size;
struct hash_desc desc;
enum drbd_packets cmd;
unsigned int length;
int rv;
desc.tfm = mdev->cram_hmac_tfm;
desc.flags = 0;
rv = crypto_hash_setkey(mdev->cram_hmac_tfm,
(u8 *)mdev->net_conf->shared_secret, key_len);
if (rv) {
dev_err(DEV, "crypto_hash_setkey() failed with %d\n", rv);
rv = -1;
goto fail;
}
get_random_bytes(my_challenge, CHALLENGE_LEN);
rv = drbd_send_cmd2(mdev, P_AUTH_CHALLENGE, my_challenge, CHALLENGE_LEN);
if (!rv)
goto fail;
rv = drbd_recv_header(mdev, &cmd, &length);
if (!rv)
goto fail;
if (cmd != P_AUTH_CHALLENGE) {
dev_err(DEV, "expected AuthChallenge packet, received: %s (0x%04x)\n",
cmdname(cmd), cmd);
rv = 0;
goto fail;
}
if (length > CHALLENGE_LEN * 2) {
dev_err(DEV, "expected AuthChallenge payload too big.\n");
rv = -1;
goto fail;
}
peers_ch = kmalloc(length, GFP_NOIO);
if (peers_ch == NULL) {
dev_err(DEV, "kmalloc of peers_ch failed\n");
rv = -1;
goto fail;
}
rv = drbd_recv(mdev, peers_ch, length);
if (rv != length) {
if (!signal_pending(current))
dev_warn(DEV, "short read AuthChallenge: l=%u\n", rv);
rv = 0;
goto fail;
}
resp_size = crypto_hash_digestsize(mdev->cram_hmac_tfm);
response = kmalloc(resp_size, GFP_NOIO);
if (response == NULL) {
dev_err(DEV, "kmalloc of response failed\n");
rv = -1;
goto fail;
}
sg_init_table(&sg, 1);
sg_set_buf(&sg, peers_ch, length);
rv = crypto_hash_digest(&desc, &sg, sg.length, response);
if (rv) {
dev_err(DEV, "crypto_hash_digest() failed with %d\n", rv);
rv = -1;
goto fail;
}
rv = drbd_send_cmd2(mdev, P_AUTH_RESPONSE, response, resp_size);
if (!rv)
goto fail;
rv = drbd_recv_header(mdev, &cmd, &length);
if (!rv)
goto fail;
if (cmd != P_AUTH_RESPONSE) {
dev_err(DEV, "expected AuthResponse packet, received: %s (0x%04x)\n",
cmdname(cmd), cmd);
rv = 0;
goto fail;
}
if (length != resp_size) {
dev_err(DEV, "expected AuthResponse payload of wrong size\n");
rv = 0;
goto fail;
}
rv = drbd_recv(mdev, response , resp_size);
if (rv != resp_size) {
if (!signal_pending(current))
dev_warn(DEV, "short read receiving AuthResponse: l=%u\n", rv);
rv = 0;
goto fail;
}
right_response = kmalloc(resp_size, GFP_NOIO);
if (right_response == NULL) {
dev_err(DEV, "kmalloc of right_response failed\n");
rv = -1;
goto fail;
}
sg_set_buf(&sg, my_challenge, CHALLENGE_LEN);
rv = crypto_hash_digest(&desc, &sg, sg.length, right_response);
if (rv) {
dev_err(DEV, "crypto_hash_digest() failed with %d\n", rv);
rv = -1;
goto fail;
}
rv = !memcmp(response, right_response, resp_size);
if (rv)
dev_info(DEV, "Peer authenticated using %d bytes of '%s' HMAC\n",
resp_size, mdev->net_conf->cram_hmac_alg);
else
rv = -1;
fail:
kfree(peers_ch);
kfree(response);
kfree(right_response);
return rv;
}
#endif
int drbdd_init(struct drbd_thread *thi)
{
struct drbd_conf *mdev = thi->mdev;
unsigned int minor = mdev_to_minor(mdev);
int h;
sprintf(current->comm, "drbd%d_receiver", minor);
dev_info(DEV, "receiver (re)started\n");
do {
h = drbd_connect(mdev);
if (h == 0) {
drbd_disconnect(mdev);
schedule_timeout_interruptible(HZ);
}
if (h == -1) {
dev_warn(DEV, "Discarding network configuration.\n");
drbd_force_state(mdev, NS(conn, C_DISCONNECTING));
}
} while (h == 0);
if (h > 0) {
if (get_net_conf(mdev)) {
drbdd(mdev);
put_net_conf(mdev);
}
}
drbd_disconnect(mdev);
dev_info(DEV, "receiver terminated\n");
return 0;
}
/* ********* acknowledge sender ******** */
static int got_RqSReply(struct drbd_conf *mdev, struct p_header80 *h)
{
struct p_req_state_reply *p = (struct p_req_state_reply *)h;
int retcode = be32_to_cpu(p->retcode);
if (retcode >= SS_SUCCESS) {
set_bit(CL_ST_CHG_SUCCESS, &mdev->flags);
} else {
set_bit(CL_ST_CHG_FAIL, &mdev->flags);
dev_err(DEV, "Requested state change failed by peer: %s (%d)\n",
drbd_set_st_err_str(retcode), retcode);
}
wake_up(&mdev->state_wait);
return true;
}
static int got_Ping(struct drbd_conf *mdev, struct p_header80 *h)
{
return drbd_send_ping_ack(mdev);
}
static int got_PingAck(struct drbd_conf *mdev, struct p_header80 *h)
{
/* restore idle timeout */
mdev->meta.socket->sk->sk_rcvtimeo = mdev->net_conf->ping_int*HZ;
if (!test_and_set_bit(GOT_PING_ACK, &mdev->flags))
wake_up(&mdev->misc_wait);
return true;
}
static int got_IsInSync(struct drbd_conf *mdev, struct p_header80 *h)
{
struct p_block_ack *p = (struct p_block_ack *)h;
sector_t sector = be64_to_cpu(p->sector);
int blksize = be32_to_cpu(p->blksize);
D_ASSERT(mdev->agreed_pro_version >= 89);
update_peer_seq(mdev, be32_to_cpu(p->seq_num));
if (get_ldev(mdev)) {
drbd_rs_complete_io(mdev, sector);
drbd_set_in_sync(mdev, sector, blksize);
/* rs_same_csums is supposed to count in units of BM_BLOCK_SIZE */
mdev->rs_same_csum += (blksize >> BM_BLOCK_SHIFT);
put_ldev(mdev);
}
dec_rs_pending(mdev);
atomic_add(blksize >> 9, &mdev->rs_sect_in);
return true;
}
/* when we receive the ACK for a write request,
* verify that we actually know about it */
static struct drbd_request *_ack_id_to_req(struct drbd_conf *mdev,
u64 id, sector_t sector)
{
struct hlist_head *slot = tl_hash_slot(mdev, sector);
struct hlist_node *n;
struct drbd_request *req;
hlist_for_each_entry(req, n, slot, collision) {
if ((unsigned long)req == (unsigned long)id) {
if (req->sector != sector) {
dev_err(DEV, "_ack_id_to_req: found req %p but it has "
"wrong sector (%llus versus %llus)\n", req,
(unsigned long long)req->sector,
(unsigned long long)sector);
break;
}
return req;
}
}
return NULL;
}
typedef struct drbd_request *(req_validator_fn)
(struct drbd_conf *mdev, u64 id, sector_t sector);
static int validate_req_change_req_state(struct drbd_conf *mdev,
u64 id, sector_t sector, req_validator_fn validator,
const char *func, enum drbd_req_event what)
{
struct drbd_request *req;
struct bio_and_error m;
spin_lock_irq(&mdev->req_lock);
req = validator(mdev, id, sector);
if (unlikely(!req)) {
spin_unlock_irq(&mdev->req_lock);
dev_err(DEV, "%s: failed to find req %p, sector %llus\n", func,
(void *)(unsigned long)id, (unsigned long long)sector);
return false;
}
__req_mod(req, what, &m);
spin_unlock_irq(&mdev->req_lock);
if (m.bio)
complete_master_bio(mdev, &m);
return true;
}
static int got_BlockAck(struct drbd_conf *mdev, struct p_header80 *h)
{
struct p_block_ack *p = (struct p_block_ack *)h;
sector_t sector = be64_to_cpu(p->sector);
int blksize = be32_to_cpu(p->blksize);
enum drbd_req_event what;
update_peer_seq(mdev, be32_to_cpu(p->seq_num));
if (is_syncer_block_id(p->block_id)) {
drbd_set_in_sync(mdev, sector, blksize);
dec_rs_pending(mdev);
return true;
}
switch (be16_to_cpu(h->command)) {
case P_RS_WRITE_ACK:
D_ASSERT(mdev->net_conf->wire_protocol == DRBD_PROT_C);
what = write_acked_by_peer_and_sis;
break;
case P_WRITE_ACK:
D_ASSERT(mdev->net_conf->wire_protocol == DRBD_PROT_C);
what = write_acked_by_peer;
break;
case P_RECV_ACK:
D_ASSERT(mdev->net_conf->wire_protocol == DRBD_PROT_B);
what = recv_acked_by_peer;
break;
case P_DISCARD_ACK:
D_ASSERT(mdev->net_conf->wire_protocol == DRBD_PROT_C);
what = conflict_discarded_by_peer;
break;
default:
D_ASSERT(0);
return false;
}
return validate_req_change_req_state(mdev, p->block_id, sector,
_ack_id_to_req, __func__ , what);
}
static int got_NegAck(struct drbd_conf *mdev, struct p_header80 *h)
{
struct p_block_ack *p = (struct p_block_ack *)h;
sector_t sector = be64_to_cpu(p->sector);
int size = be32_to_cpu(p->blksize);
struct drbd_request *req;
struct bio_and_error m;
update_peer_seq(mdev, be32_to_cpu(p->seq_num));
if (is_syncer_block_id(p->block_id)) {
dec_rs_pending(mdev);
drbd_rs_failed_io(mdev, sector, size);
return true;
}
spin_lock_irq(&mdev->req_lock);
req = _ack_id_to_req(mdev, p->block_id, sector);
if (!req) {
spin_unlock_irq(&mdev->req_lock);
if (mdev->net_conf->wire_protocol == DRBD_PROT_A ||
mdev->net_conf->wire_protocol == DRBD_PROT_B) {
/* Protocol A has no P_WRITE_ACKs, but has P_NEG_ACKs.
The master bio might already be completed, therefore the
request is no longer in the collision hash.
=> Do not try to validate block_id as request. */
/* In Protocol B we might already have got a P_RECV_ACK
but then get a P_NEG_ACK after wards. */
drbd_set_out_of_sync(mdev, sector, size);
return true;
} else {
dev_err(DEV, "%s: failed to find req %p, sector %llus\n", __func__,
(void *)(unsigned long)p->block_id, (unsigned long long)sector);
return false;
}
}
__req_mod(req, neg_acked, &m);
spin_unlock_irq(&mdev->req_lock);
if (m.bio)
complete_master_bio(mdev, &m);
return true;
}
static int got_NegDReply(struct drbd_conf *mdev, struct p_header80 *h)
{
struct p_block_ack *p = (struct p_block_ack *)h;
sector_t sector = be64_to_cpu(p->sector);
update_peer_seq(mdev, be32_to_cpu(p->seq_num));
dev_err(DEV, "Got NegDReply; Sector %llus, len %u; Fail original request.\n",
(unsigned long long)sector, be32_to_cpu(p->blksize));
return validate_req_change_req_state(mdev, p->block_id, sector,
_ar_id_to_req, __func__ , neg_acked);
}
static int got_NegRSDReply(struct drbd_conf *mdev, struct p_header80 *h)
{
sector_t sector;
int size;
struct p_block_ack *p = (struct p_block_ack *)h;
sector = be64_to_cpu(p->sector);
size = be32_to_cpu(p->blksize);
update_peer_seq(mdev, be32_to_cpu(p->seq_num));
dec_rs_pending(mdev);
if (get_ldev_if_state(mdev, D_FAILED)) {
drbd_rs_complete_io(mdev, sector);
switch (be16_to_cpu(h->command)) {
case P_NEG_RS_DREPLY:
drbd_rs_failed_io(mdev, sector, size);
case P_RS_CANCEL:
break;
default:
D_ASSERT(0);
put_ldev(mdev);
return false;
}
put_ldev(mdev);
}
return true;
}
static int got_BarrierAck(struct drbd_conf *mdev, struct p_header80 *h)
{
struct p_barrier_ack *p = (struct p_barrier_ack *)h;
tl_release(mdev, p->barrier, be32_to_cpu(p->set_size));
if (mdev->state.conn == C_AHEAD &&
atomic_read(&mdev->ap_in_flight) == 0 &&
!test_and_set_bit(AHEAD_TO_SYNC_SOURCE, &mdev->current_epoch->flags)) {
mdev->start_resync_timer.expires = jiffies + HZ;
add_timer(&mdev->start_resync_timer);
}
return true;
}
static int got_OVResult(struct drbd_conf *mdev, struct p_header80 *h)
{
struct p_block_ack *p = (struct p_block_ack *)h;
struct drbd_work *w;
sector_t sector;
int size;
sector = be64_to_cpu(p->sector);
size = be32_to_cpu(p->blksize);
update_peer_seq(mdev, be32_to_cpu(p->seq_num));
if (be64_to_cpu(p->block_id) == ID_OUT_OF_SYNC)
drbd_ov_oos_found(mdev, sector, size);
else
ov_oos_print(mdev);
if (!get_ldev(mdev))
return true;
drbd_rs_complete_io(mdev, sector);
dec_rs_pending(mdev);
--mdev->ov_left;
/* let's advance progress step marks only for every other megabyte */
if ((mdev->ov_left & 0x200) == 0x200)
drbd_advance_rs_marks(mdev, mdev->ov_left);
if (mdev->ov_left == 0) {
w = kmalloc(sizeof(*w), GFP_NOIO);
if (w) {
w->cb = w_ov_finished;
drbd_queue_work_front(&mdev->data.work, w);
} else {
dev_err(DEV, "kmalloc(w) failed.");
ov_oos_print(mdev);
drbd_resync_finished(mdev);
}
}
put_ldev(mdev);
return true;
}
static int got_skip(struct drbd_conf *mdev, struct p_header80 *h)
{
return true;
}
struct asender_cmd {
size_t pkt_size;
int (*process)(struct drbd_conf *mdev, struct p_header80 *h);
};
static struct asender_cmd *get_asender_cmd(int cmd)
{
static struct asender_cmd asender_tbl[] = {
/* anything missing from this table is in
* the drbd_cmd_handler (drbd_default_handler) table,
* see the beginning of drbdd() */
[P_PING] = { sizeof(struct p_header80), got_Ping },
[P_PING_ACK] = { sizeof(struct p_header80), got_PingAck },
[P_RECV_ACK] = { sizeof(struct p_block_ack), got_BlockAck },
[P_WRITE_ACK] = { sizeof(struct p_block_ack), got_BlockAck },
[P_RS_WRITE_ACK] = { sizeof(struct p_block_ack), got_BlockAck },
[P_DISCARD_ACK] = { sizeof(struct p_block_ack), got_BlockAck },
[P_NEG_ACK] = { sizeof(struct p_block_ack), got_NegAck },
[P_NEG_DREPLY] = { sizeof(struct p_block_ack), got_NegDReply },
[P_NEG_RS_DREPLY] = { sizeof(struct p_block_ack), got_NegRSDReply},
[P_OV_RESULT] = { sizeof(struct p_block_ack), got_OVResult },
[P_BARRIER_ACK] = { sizeof(struct p_barrier_ack), got_BarrierAck },
[P_STATE_CHG_REPLY] = { sizeof(struct p_req_state_reply), got_RqSReply },
[P_RS_IS_IN_SYNC] = { sizeof(struct p_block_ack), got_IsInSync },
[P_DELAY_PROBE] = { sizeof(struct p_delay_probe93), got_skip },
[P_RS_CANCEL] = { sizeof(struct p_block_ack), got_NegRSDReply},
[P_MAX_CMD] = { 0, NULL },
};
if (cmd > P_MAX_CMD || asender_tbl[cmd].process == NULL)
return NULL;
return &asender_tbl[cmd];
}
int drbd_asender(struct drbd_thread *thi)
{
struct drbd_conf *mdev = thi->mdev;
struct p_header80 *h = &mdev->meta.rbuf.header.h80;
struct asender_cmd *cmd = NULL;
int rv, len;
void *buf = h;
int received = 0;
int expect = sizeof(struct p_header80);
int empty;
int ping_timeout_active = 0;
sprintf(current->comm, "drbd%d_asender", mdev_to_minor(mdev));
current->policy = SCHED_RR; /* Make this a realtime task! */
current->rt_priority = 2; /* more important than all other tasks */
while (get_t_state(thi) == Running) {
drbd_thread_current_set_cpu(mdev);
if (test_and_clear_bit(SEND_PING, &mdev->flags)) {
ERR_IF(!drbd_send_ping(mdev)) goto reconnect;
mdev->meta.socket->sk->sk_rcvtimeo =
mdev->net_conf->ping_timeo*HZ/10;
ping_timeout_active = 1;
}
/* conditionally cork;
* it may hurt latency if we cork without much to send */
if (!mdev->net_conf->no_cork &&
3 < atomic_read(&mdev->unacked_cnt))
drbd_tcp_cork(mdev->meta.socket);
while (1) {
clear_bit(SIGNAL_ASENDER, &mdev->flags);
flush_signals(current);
if (!drbd_process_done_ee(mdev))
goto reconnect;
/* to avoid race with newly queued ACKs */
set_bit(SIGNAL_ASENDER, &mdev->flags);
spin_lock_irq(&mdev->req_lock);
empty = list_empty(&mdev->done_ee);
spin_unlock_irq(&mdev->req_lock);
/* new ack may have been queued right here,
* but then there is also a signal pending,
* and we start over... */
if (empty)
break;
}
/* but unconditionally uncork unless disabled */
if (!mdev->net_conf->no_cork)
drbd_tcp_uncork(mdev->meta.socket);
/* short circuit, recv_msg would return EINTR anyways. */
if (signal_pending(current))
continue;
rv = drbd_recv_short(mdev, mdev->meta.socket,
buf, expect-received, 0);
clear_bit(SIGNAL_ASENDER, &mdev->flags);
flush_signals(current);
/* Note:
* -EINTR (on meta) we got a signal
* -EAGAIN (on meta) rcvtimeo expired
* -ECONNRESET other side closed the connection
* -ERESTARTSYS (on data) we got a signal
* rv < 0 other than above: unexpected error!
* rv == expected: full header or command
* rv < expected: "woken" by signal during receive
* rv == 0 : "connection shut down by peer"
*/
if (likely(rv > 0)) {
received += rv;
buf += rv;
} else if (rv == 0) {
dev_err(DEV, "meta connection shut down by peer.\n");
goto reconnect;
} else if (rv == -EAGAIN) {
/* If the data socket received something meanwhile,
* that is good enough: peer is still alive. */
if (time_after(mdev->last_received,
jiffies - mdev->meta.socket->sk->sk_rcvtimeo))
continue;
if (ping_timeout_active) {
dev_err(DEV, "PingAck did not arrive in time.\n");
goto reconnect;
}
set_bit(SEND_PING, &mdev->flags);
continue;
} else if (rv == -EINTR) {
continue;
} else {
dev_err(DEV, "sock_recvmsg returned %d\n", rv);
goto reconnect;
}
if (received == expect && cmd == NULL) {
if (unlikely(h->magic != BE_DRBD_MAGIC)) {
dev_err(DEV, "magic?? on meta m: 0x%08x c: %d l: %d\n",
be32_to_cpu(h->magic),
be16_to_cpu(h->command),
be16_to_cpu(h->length));
goto reconnect;
}
cmd = get_asender_cmd(be16_to_cpu(h->command));
len = be16_to_cpu(h->length);
if (unlikely(cmd == NULL)) {
dev_err(DEV, "unknown command?? on meta m: 0x%08x c: %d l: %d\n",
be32_to_cpu(h->magic),
be16_to_cpu(h->command),
be16_to_cpu(h->length));
goto disconnect;
}
expect = cmd->pkt_size;
ERR_IF(len != expect-sizeof(struct p_header80))
goto reconnect;
}
if (received == expect) {
mdev->last_received = jiffies;
D_ASSERT(cmd != NULL);
if (!cmd->process(mdev, h))
goto reconnect;
/* the idle_timeout (ping-int)
* has been restored in got_PingAck() */
if (cmd == get_asender_cmd(P_PING_ACK))
ping_timeout_active = 0;
buf = h;
received = 0;
expect = sizeof(struct p_header80);
cmd = NULL;
}
}
if (0) {
reconnect:
drbd_force_state(mdev, NS(conn, C_NETWORK_FAILURE));
drbd_md_sync(mdev);
}
if (0) {
disconnect:
drbd_force_state(mdev, NS(conn, C_DISCONNECTING));
drbd_md_sync(mdev);
}
clear_bit(SIGNAL_ASENDER, &mdev->flags);
D_ASSERT(mdev->state.conn < C_CONNECTED);
dev_info(DEV, "asender terminated\n");
return 0;
}
| gpl-2.0 |
ivanmeler/android_kernel_htc_g3u | net/ipx/af_ipx.c | 7007 | 51483 | /*
* Implements an IPX socket layer.
*
* This code is derived from work by
* Ross Biro : Writing the original IP stack
* Fred Van Kempen : Tidying up the TCP/IP
*
* Many thanks go to Keith Baker, Institute For Industrial Information
* Technology Ltd, Swansea University for allowing me to work on this
* in my own time even though it was in some ways related to commercial
* work I am currently employed to do there.
*
* All the material in this file is subject to the Gnu license version 2.
* Neither Alan Cox nor the Swansea University Computer Society admit
* liability nor provide warranty for any of this software. This material
* is provided as is and at no charge.
*
* Portions Copyright (c) 2000-2003 Conectiva, Inc. <acme@conectiva.com.br>
* Neither Arnaldo Carvalho de Melo nor Conectiva, Inc. admit liability nor
* provide warranty for any of this software. This material is provided
* "AS-IS" and at no charge.
*
* Portions Copyright (c) 1995 Caldera, Inc. <greg@caldera.com>
* Neither Greg Page nor Caldera, Inc. admit liability nor provide
* warranty for any of this software. This material is provided
* "AS-IS" and at no charge.
*
* See net/ipx/ChangeLog.
*/
#include <linux/capability.h>
#include <linux/errno.h>
#include <linux/if_arp.h>
#include <linux/if_ether.h>
#include <linux/init.h>
#include <linux/ipx.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/net.h>
#include <linux/netdevice.h>
#include <linux/uio.h>
#include <linux/slab.h>
#include <linux/skbuff.h>
#include <linux/socket.h>
#include <linux/sockios.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/termios.h>
#include <net/ipx.h>
#include <net/p8022.h>
#include <net/psnap.h>
#include <net/sock.h>
#include <net/tcp_states.h>
#include <asm/uaccess.h>
#ifdef CONFIG_SYSCTL
extern void ipx_register_sysctl(void);
extern void ipx_unregister_sysctl(void);
#else
#define ipx_register_sysctl()
#define ipx_unregister_sysctl()
#endif
/* Configuration Variables */
static unsigned char ipxcfg_max_hops = 16;
static char ipxcfg_auto_select_primary;
static char ipxcfg_auto_create_interfaces;
int sysctl_ipx_pprop_broadcasting = 1;
/* Global Variables */
static struct datalink_proto *p8022_datalink;
static struct datalink_proto *pEII_datalink;
static struct datalink_proto *p8023_datalink;
static struct datalink_proto *pSNAP_datalink;
static const struct proto_ops ipx_dgram_ops;
LIST_HEAD(ipx_interfaces);
DEFINE_SPINLOCK(ipx_interfaces_lock);
struct ipx_interface *ipx_primary_net;
struct ipx_interface *ipx_internal_net;
extern int ipxrtr_add_route(__be32 network, struct ipx_interface *intrfc,
unsigned char *node);
extern void ipxrtr_del_routes(struct ipx_interface *intrfc);
extern int ipxrtr_route_packet(struct sock *sk, struct sockaddr_ipx *usipx,
struct iovec *iov, size_t len, int noblock);
extern int ipxrtr_route_skb(struct sk_buff *skb);
extern struct ipx_route *ipxrtr_lookup(__be32 net);
extern int ipxrtr_ioctl(unsigned int cmd, void __user *arg);
struct ipx_interface *ipx_interfaces_head(void)
{
struct ipx_interface *rc = NULL;
if (!list_empty(&ipx_interfaces))
rc = list_entry(ipx_interfaces.next,
struct ipx_interface, node);
return rc;
}
static void ipxcfg_set_auto_select(char val)
{
ipxcfg_auto_select_primary = val;
if (val && !ipx_primary_net)
ipx_primary_net = ipx_interfaces_head();
}
static int ipxcfg_get_config_data(struct ipx_config_data __user *arg)
{
struct ipx_config_data vals;
vals.ipxcfg_auto_create_interfaces = ipxcfg_auto_create_interfaces;
vals.ipxcfg_auto_select_primary = ipxcfg_auto_select_primary;
return copy_to_user(arg, &vals, sizeof(vals)) ? -EFAULT : 0;
}
/*
* Note: Sockets may not be removed _during_ an interrupt or inet_bh
* handler using this technique. They can be added although we do not
* use this facility.
*/
static void ipx_remove_socket(struct sock *sk)
{
/* Determine interface with which socket is associated */
struct ipx_interface *intrfc = ipx_sk(sk)->intrfc;
if (!intrfc)
goto out;
ipxitf_hold(intrfc);
spin_lock_bh(&intrfc->if_sklist_lock);
sk_del_node_init(sk);
spin_unlock_bh(&intrfc->if_sklist_lock);
ipxitf_put(intrfc);
out:
return;
}
static void ipx_destroy_socket(struct sock *sk)
{
ipx_remove_socket(sk);
skb_queue_purge(&sk->sk_receive_queue);
sk_refcnt_debug_dec(sk);
}
/*
* The following code is used to support IPX Interfaces (IPXITF). An
* IPX interface is defined by a physical device and a frame type.
*/
/* ipxitf_clear_primary_net has to be called with ipx_interfaces_lock held */
static void ipxitf_clear_primary_net(void)
{
ipx_primary_net = NULL;
if (ipxcfg_auto_select_primary)
ipx_primary_net = ipx_interfaces_head();
}
static struct ipx_interface *__ipxitf_find_using_phys(struct net_device *dev,
__be16 datalink)
{
struct ipx_interface *i;
list_for_each_entry(i, &ipx_interfaces, node)
if (i->if_dev == dev && i->if_dlink_type == datalink)
goto out;
i = NULL;
out:
return i;
}
static struct ipx_interface *ipxitf_find_using_phys(struct net_device *dev,
__be16 datalink)
{
struct ipx_interface *i;
spin_lock_bh(&ipx_interfaces_lock);
i = __ipxitf_find_using_phys(dev, datalink);
if (i)
ipxitf_hold(i);
spin_unlock_bh(&ipx_interfaces_lock);
return i;
}
struct ipx_interface *ipxitf_find_using_net(__be32 net)
{
struct ipx_interface *i;
spin_lock_bh(&ipx_interfaces_lock);
if (net) {
list_for_each_entry(i, &ipx_interfaces, node)
if (i->if_netnum == net)
goto hold;
i = NULL;
goto unlock;
}
i = ipx_primary_net;
if (i)
hold:
ipxitf_hold(i);
unlock:
spin_unlock_bh(&ipx_interfaces_lock);
return i;
}
/* Sockets are bound to a particular IPX interface. */
static void ipxitf_insert_socket(struct ipx_interface *intrfc, struct sock *sk)
{
ipxitf_hold(intrfc);
spin_lock_bh(&intrfc->if_sklist_lock);
ipx_sk(sk)->intrfc = intrfc;
sk_add_node(sk, &intrfc->if_sklist);
spin_unlock_bh(&intrfc->if_sklist_lock);
ipxitf_put(intrfc);
}
/* caller must hold intrfc->if_sklist_lock */
static struct sock *__ipxitf_find_socket(struct ipx_interface *intrfc,
__be16 port)
{
struct sock *s;
struct hlist_node *node;
sk_for_each(s, node, &intrfc->if_sklist)
if (ipx_sk(s)->port == port)
goto found;
s = NULL;
found:
return s;
}
/* caller must hold a reference to intrfc */
static struct sock *ipxitf_find_socket(struct ipx_interface *intrfc,
__be16 port)
{
struct sock *s;
spin_lock_bh(&intrfc->if_sklist_lock);
s = __ipxitf_find_socket(intrfc, port);
if (s)
sock_hold(s);
spin_unlock_bh(&intrfc->if_sklist_lock);
return s;
}
#ifdef CONFIG_IPX_INTERN
static struct sock *ipxitf_find_internal_socket(struct ipx_interface *intrfc,
unsigned char *ipx_node,
__be16 port)
{
struct sock *s;
struct hlist_node *node;
ipxitf_hold(intrfc);
spin_lock_bh(&intrfc->if_sklist_lock);
sk_for_each(s, node, &intrfc->if_sklist) {
struct ipx_sock *ipxs = ipx_sk(s);
if (ipxs->port == port &&
!memcmp(ipx_node, ipxs->node, IPX_NODE_LEN))
goto found;
}
s = NULL;
found:
spin_unlock_bh(&intrfc->if_sklist_lock);
ipxitf_put(intrfc);
return s;
}
#endif
static void __ipxitf_down(struct ipx_interface *intrfc)
{
struct sock *s;
struct hlist_node *node, *t;
/* Delete all routes associated with this interface */
ipxrtr_del_routes(intrfc);
spin_lock_bh(&intrfc->if_sklist_lock);
/* error sockets */
sk_for_each_safe(s, node, t, &intrfc->if_sklist) {
struct ipx_sock *ipxs = ipx_sk(s);
s->sk_err = ENOLINK;
s->sk_error_report(s);
ipxs->intrfc = NULL;
ipxs->port = 0;
sock_set_flag(s, SOCK_ZAPPED); /* Indicates it is no longer bound */
sk_del_node_init(s);
}
INIT_HLIST_HEAD(&intrfc->if_sklist);
spin_unlock_bh(&intrfc->if_sklist_lock);
/* remove this interface from list */
list_del(&intrfc->node);
/* remove this interface from *special* networks */
if (intrfc == ipx_primary_net)
ipxitf_clear_primary_net();
if (intrfc == ipx_internal_net)
ipx_internal_net = NULL;
if (intrfc->if_dev)
dev_put(intrfc->if_dev);
kfree(intrfc);
}
void ipxitf_down(struct ipx_interface *intrfc)
{
spin_lock_bh(&ipx_interfaces_lock);
__ipxitf_down(intrfc);
spin_unlock_bh(&ipx_interfaces_lock);
}
static __inline__ void __ipxitf_put(struct ipx_interface *intrfc)
{
if (atomic_dec_and_test(&intrfc->refcnt))
__ipxitf_down(intrfc);
}
static int ipxitf_device_event(struct notifier_block *notifier,
unsigned long event, void *ptr)
{
struct net_device *dev = ptr;
struct ipx_interface *i, *tmp;
if (!net_eq(dev_net(dev), &init_net))
return NOTIFY_DONE;
if (event != NETDEV_DOWN && event != NETDEV_UP)
goto out;
spin_lock_bh(&ipx_interfaces_lock);
list_for_each_entry_safe(i, tmp, &ipx_interfaces, node)
if (i->if_dev == dev) {
if (event == NETDEV_UP)
ipxitf_hold(i);
else
__ipxitf_put(i);
}
spin_unlock_bh(&ipx_interfaces_lock);
out:
return NOTIFY_DONE;
}
static __exit void ipxitf_cleanup(void)
{
struct ipx_interface *i, *tmp;
spin_lock_bh(&ipx_interfaces_lock);
list_for_each_entry_safe(i, tmp, &ipx_interfaces, node)
__ipxitf_put(i);
spin_unlock_bh(&ipx_interfaces_lock);
}
static void ipxitf_def_skb_handler(struct sock *sock, struct sk_buff *skb)
{
if (sock_queue_rcv_skb(sock, skb) < 0)
kfree_skb(skb);
}
/*
* On input skb->sk is NULL. Nobody is charged for the memory.
*/
/* caller must hold a reference to intrfc */
#ifdef CONFIG_IPX_INTERN
static int ipxitf_demux_socket(struct ipx_interface *intrfc,
struct sk_buff *skb, int copy)
{
struct ipxhdr *ipx = ipx_hdr(skb);
int is_broadcast = !memcmp(ipx->ipx_dest.node, ipx_broadcast_node,
IPX_NODE_LEN);
struct sock *s;
struct hlist_node *node;
int rc;
spin_lock_bh(&intrfc->if_sklist_lock);
sk_for_each(s, node, &intrfc->if_sklist) {
struct ipx_sock *ipxs = ipx_sk(s);
if (ipxs->port == ipx->ipx_dest.sock &&
(is_broadcast || !memcmp(ipx->ipx_dest.node,
ipxs->node, IPX_NODE_LEN))) {
/* We found a socket to which to send */
struct sk_buff *skb1;
if (copy) {
skb1 = skb_clone(skb, GFP_ATOMIC);
rc = -ENOMEM;
if (!skb1)
goto out;
} else {
skb1 = skb;
copy = 1; /* skb may only be used once */
}
ipxitf_def_skb_handler(s, skb1);
/* On an external interface, one socket can listen */
if (intrfc != ipx_internal_net)
break;
}
}
/* skb was solely for us, and we did not make a copy, so free it. */
if (!copy)
kfree_skb(skb);
rc = 0;
out:
spin_unlock_bh(&intrfc->if_sklist_lock);
return rc;
}
#else
static struct sock *ncp_connection_hack(struct ipx_interface *intrfc,
struct ipxhdr *ipx)
{
/* The packet's target is a NCP connection handler. We want to hand it
* to the correct socket directly within the kernel, so that the
* mars_nwe packet distribution process does not have to do it. Here we
* only care about NCP and BURST packets.
*
* You might call this a hack, but believe me, you do not want a
* complete NCP layer in the kernel, and this is VERY fast as well. */
struct sock *sk = NULL;
int connection = 0;
u8 *ncphdr = (u8 *)(ipx + 1);
if (*ncphdr == 0x22 && *(ncphdr + 1) == 0x22) /* NCP request */
connection = (((int) *(ncphdr + 5)) << 8) | (int) *(ncphdr + 3);
else if (*ncphdr == 0x77 && *(ncphdr + 1) == 0x77) /* BURST packet */
connection = (((int) *(ncphdr + 9)) << 8) | (int) *(ncphdr + 8);
if (connection) {
struct hlist_node *node;
/* Now we have to look for a special NCP connection handling
* socket. Only these sockets have ipx_ncp_conn != 0, set by
* SIOCIPXNCPCONN. */
spin_lock_bh(&intrfc->if_sklist_lock);
sk_for_each(sk, node, &intrfc->if_sklist)
if (ipx_sk(sk)->ipx_ncp_conn == connection) {
sock_hold(sk);
goto found;
}
sk = NULL;
found:
spin_unlock_bh(&intrfc->if_sklist_lock);
}
return sk;
}
static int ipxitf_demux_socket(struct ipx_interface *intrfc,
struct sk_buff *skb, int copy)
{
struct ipxhdr *ipx = ipx_hdr(skb);
struct sock *sock1 = NULL, *sock2 = NULL;
struct sk_buff *skb1 = NULL, *skb2 = NULL;
int rc;
if (intrfc == ipx_primary_net && ntohs(ipx->ipx_dest.sock) == 0x451)
sock1 = ncp_connection_hack(intrfc, ipx);
if (!sock1)
/* No special socket found, forward the packet the normal way */
sock1 = ipxitf_find_socket(intrfc, ipx->ipx_dest.sock);
/*
* We need to check if there is a primary net and if
* this is addressed to one of the *SPECIAL* sockets because
* these need to be propagated to the primary net.
* The *SPECIAL* socket list contains: 0x452(SAP), 0x453(RIP) and
* 0x456(Diagnostic).
*/
if (ipx_primary_net && intrfc != ipx_primary_net) {
const int dsock = ntohs(ipx->ipx_dest.sock);
if (dsock == 0x452 || dsock == 0x453 || dsock == 0x456)
/* The appropriate thing to do here is to dup the
* packet and route to the primary net interface via
* ipxitf_send; however, we'll cheat and just demux it
* here. */
sock2 = ipxitf_find_socket(ipx_primary_net,
ipx->ipx_dest.sock);
}
/*
* If there is nothing to do return. The kfree will cancel any charging.
*/
rc = 0;
if (!sock1 && !sock2) {
if (!copy)
kfree_skb(skb);
goto out;
}
/*
* This next segment of code is a little awkward, but it sets it up
* so that the appropriate number of copies of the SKB are made and
* that skb1 and skb2 point to it (them) so that it (they) can be
* demuxed to sock1 and/or sock2. If we are unable to make enough
* copies, we do as much as is possible.
*/
if (copy)
skb1 = skb_clone(skb, GFP_ATOMIC);
else
skb1 = skb;
rc = -ENOMEM;
if (!skb1)
goto out_put;
/* Do we need 2 SKBs? */
if (sock1 && sock2)
skb2 = skb_clone(skb1, GFP_ATOMIC);
else
skb2 = skb1;
if (sock1)
ipxitf_def_skb_handler(sock1, skb1);
if (!skb2)
goto out_put;
if (sock2)
ipxitf_def_skb_handler(sock2, skb2);
rc = 0;
out_put:
if (sock1)
sock_put(sock1);
if (sock2)
sock_put(sock2);
out:
return rc;
}
#endif /* CONFIG_IPX_INTERN */
static struct sk_buff *ipxitf_adjust_skbuff(struct ipx_interface *intrfc,
struct sk_buff *skb)
{
struct sk_buff *skb2;
int in_offset = (unsigned char *)ipx_hdr(skb) - skb->head;
int out_offset = intrfc->if_ipx_offset;
int len;
/* Hopefully, most cases */
if (in_offset >= out_offset)
return skb;
/* Need new SKB */
len = skb->len + out_offset;
skb2 = alloc_skb(len, GFP_ATOMIC);
if (skb2) {
skb_reserve(skb2, out_offset);
skb_reset_network_header(skb2);
skb_reset_transport_header(skb2);
skb_put(skb2, skb->len);
memcpy(ipx_hdr(skb2), ipx_hdr(skb), skb->len);
memcpy(skb2->cb, skb->cb, sizeof(skb->cb));
}
kfree_skb(skb);
return skb2;
}
/* caller must hold a reference to intrfc and the skb has to be unshared */
int ipxitf_send(struct ipx_interface *intrfc, struct sk_buff *skb, char *node)
{
struct ipxhdr *ipx = ipx_hdr(skb);
struct net_device *dev = intrfc->if_dev;
struct datalink_proto *dl = intrfc->if_dlink;
char dest_node[IPX_NODE_LEN];
int send_to_wire = 1;
int addr_len;
ipx->ipx_tctrl = IPX_SKB_CB(skb)->ipx_tctrl;
ipx->ipx_dest.net = IPX_SKB_CB(skb)->ipx_dest_net;
ipx->ipx_source.net = IPX_SKB_CB(skb)->ipx_source_net;
/* see if we need to include the netnum in the route list */
if (IPX_SKB_CB(skb)->last_hop.index >= 0) {
__be32 *last_hop = (__be32 *)(((u8 *) skb->data) +
sizeof(struct ipxhdr) +
IPX_SKB_CB(skb)->last_hop.index *
sizeof(__be32));
*last_hop = IPX_SKB_CB(skb)->last_hop.netnum;
IPX_SKB_CB(skb)->last_hop.index = -1;
}
/*
* We need to know how many skbuffs it will take to send out this
* packet to avoid unnecessary copies.
*/
if (!dl || !dev || dev->flags & IFF_LOOPBACK)
send_to_wire = 0; /* No non looped */
/*
* See if this should be demuxed to sockets on this interface
*
* We want to ensure the original was eaten or that we only use
* up clones.
*/
if (ipx->ipx_dest.net == intrfc->if_netnum) {
/*
* To our own node, loop and free the original.
* The internal net will receive on all node address.
*/
if (intrfc == ipx_internal_net ||
!memcmp(intrfc->if_node, node, IPX_NODE_LEN)) {
/* Don't charge sender */
skb_orphan(skb);
/* Will charge receiver */
return ipxitf_demux_socket(intrfc, skb, 0);
}
/* Broadcast, loop and possibly keep to send on. */
if (!memcmp(ipx_broadcast_node, node, IPX_NODE_LEN)) {
if (!send_to_wire)
skb_orphan(skb);
ipxitf_demux_socket(intrfc, skb, send_to_wire);
if (!send_to_wire)
goto out;
}
}
/*
* If the originating net is not equal to our net; this is routed
* We are still charging the sender. Which is right - the driver
* free will handle this fairly.
*/
if (ipx->ipx_source.net != intrfc->if_netnum) {
/*
* Unshare the buffer before modifying the count in
* case it's a flood or tcpdump
*/
skb = skb_unshare(skb, GFP_ATOMIC);
if (!skb)
goto out;
if (++ipx->ipx_tctrl > ipxcfg_max_hops)
send_to_wire = 0;
}
if (!send_to_wire) {
kfree_skb(skb);
goto out;
}
/* Determine the appropriate hardware address */
addr_len = dev->addr_len;
if (!memcmp(ipx_broadcast_node, node, IPX_NODE_LEN))
memcpy(dest_node, dev->broadcast, addr_len);
else
memcpy(dest_node, &(node[IPX_NODE_LEN-addr_len]), addr_len);
/* Make any compensation for differing physical/data link size */
skb = ipxitf_adjust_skbuff(intrfc, skb);
if (!skb)
goto out;
/* set up data link and physical headers */
skb->dev = dev;
skb->protocol = htons(ETH_P_IPX);
/* Send it out */
dl->request(dl, skb, dest_node);
out:
return 0;
}
static int ipxitf_add_local_route(struct ipx_interface *intrfc)
{
return ipxrtr_add_route(intrfc->if_netnum, intrfc, NULL);
}
static void ipxitf_discover_netnum(struct ipx_interface *intrfc,
struct sk_buff *skb);
static int ipxitf_pprop(struct ipx_interface *intrfc, struct sk_buff *skb);
static int ipxitf_rcv(struct ipx_interface *intrfc, struct sk_buff *skb)
{
struct ipxhdr *ipx = ipx_hdr(skb);
int rc = 0;
ipxitf_hold(intrfc);
/* See if we should update our network number */
if (!intrfc->if_netnum) /* net number of intrfc not known yet */
ipxitf_discover_netnum(intrfc, skb);
IPX_SKB_CB(skb)->last_hop.index = -1;
if (ipx->ipx_type == IPX_TYPE_PPROP) {
rc = ipxitf_pprop(intrfc, skb);
if (rc)
goto out_free_skb;
}
/* local processing follows */
if (!IPX_SKB_CB(skb)->ipx_dest_net)
IPX_SKB_CB(skb)->ipx_dest_net = intrfc->if_netnum;
if (!IPX_SKB_CB(skb)->ipx_source_net)
IPX_SKB_CB(skb)->ipx_source_net = intrfc->if_netnum;
/* it doesn't make sense to route a pprop packet, there's no meaning
* in the ipx_dest_net for such packets */
if (ipx->ipx_type != IPX_TYPE_PPROP &&
intrfc->if_netnum != IPX_SKB_CB(skb)->ipx_dest_net) {
/* We only route point-to-point packets. */
if (skb->pkt_type == PACKET_HOST) {
skb = skb_unshare(skb, GFP_ATOMIC);
if (skb)
rc = ipxrtr_route_skb(skb);
goto out_intrfc;
}
goto out_free_skb;
}
/* see if we should keep it */
if (!memcmp(ipx_broadcast_node, ipx->ipx_dest.node, IPX_NODE_LEN) ||
!memcmp(intrfc->if_node, ipx->ipx_dest.node, IPX_NODE_LEN)) {
rc = ipxitf_demux_socket(intrfc, skb, 0);
goto out_intrfc;
}
/* we couldn't pawn it off so unload it */
out_free_skb:
kfree_skb(skb);
out_intrfc:
ipxitf_put(intrfc);
return rc;
}
static void ipxitf_discover_netnum(struct ipx_interface *intrfc,
struct sk_buff *skb)
{
const struct ipx_cb *cb = IPX_SKB_CB(skb);
/* see if this is an intra packet: source_net == dest_net */
if (cb->ipx_source_net == cb->ipx_dest_net && cb->ipx_source_net) {
struct ipx_interface *i =
ipxitf_find_using_net(cb->ipx_source_net);
/* NB: NetWare servers lie about their hop count so we
* dropped the test based on it. This is the best way
* to determine this is a 0 hop count packet. */
if (!i) {
intrfc->if_netnum = cb->ipx_source_net;
ipxitf_add_local_route(intrfc);
} else {
printk(KERN_WARNING "IPX: Network number collision "
"%lx\n %s %s and %s %s\n",
(unsigned long) ntohl(cb->ipx_source_net),
ipx_device_name(i),
ipx_frame_name(i->if_dlink_type),
ipx_device_name(intrfc),
ipx_frame_name(intrfc->if_dlink_type));
ipxitf_put(i);
}
}
}
/**
* ipxitf_pprop - Process packet propagation IPX packet type 0x14, used for
* NetBIOS broadcasts
* @intrfc: IPX interface receiving this packet
* @skb: Received packet
*
* Checks if packet is valid: if its more than %IPX_MAX_PPROP_HOPS hops or if it
* is smaller than a IPX header + the room for %IPX_MAX_PPROP_HOPS hops we drop
* it, not even processing it locally, if it has exact %IPX_MAX_PPROP_HOPS we
* don't broadcast it, but process it locally. See chapter 5 of Novell's "IPX
* RIP and SAP Router Specification", Part Number 107-000029-001.
*
* If it is valid, check if we have pprop broadcasting enabled by the user,
* if not, just return zero for local processing.
*
* If it is enabled check the packet and don't broadcast it if we have already
* seen this packet.
*
* Broadcast: send it to the interfaces that aren't on the packet visited nets
* array, just after the IPX header.
*
* Returns -EINVAL for invalid packets, so that the calling function drops
* the packet without local processing. 0 if packet is to be locally processed.
*/
static int ipxitf_pprop(struct ipx_interface *intrfc, struct sk_buff *skb)
{
struct ipxhdr *ipx = ipx_hdr(skb);
int i, rc = -EINVAL;
struct ipx_interface *ifcs;
char *c;
__be32 *l;
/* Illegal packet - too many hops or too short */
/* We decide to throw it away: no broadcasting, no local processing.
* NetBIOS unaware implementations route them as normal packets -
* tctrl <= 15, any data payload... */
if (IPX_SKB_CB(skb)->ipx_tctrl > IPX_MAX_PPROP_HOPS ||
ntohs(ipx->ipx_pktsize) < sizeof(struct ipxhdr) +
IPX_MAX_PPROP_HOPS * sizeof(u32))
goto out;
/* are we broadcasting this damn thing? */
rc = 0;
if (!sysctl_ipx_pprop_broadcasting)
goto out;
/* We do broadcast packet on the IPX_MAX_PPROP_HOPS hop, but we
* process it locally. All previous hops broadcasted it, and process it
* locally. */
if (IPX_SKB_CB(skb)->ipx_tctrl == IPX_MAX_PPROP_HOPS)
goto out;
c = ((u8 *) ipx) + sizeof(struct ipxhdr);
l = (__be32 *) c;
/* Don't broadcast packet if already seen this net */
for (i = 0; i < IPX_SKB_CB(skb)->ipx_tctrl; i++)
if (*l++ == intrfc->if_netnum)
goto out;
/* < IPX_MAX_PPROP_HOPS hops && input interface not in list. Save the
* position where we will insert recvd netnum into list, later on,
* in ipxitf_send */
IPX_SKB_CB(skb)->last_hop.index = i;
IPX_SKB_CB(skb)->last_hop.netnum = intrfc->if_netnum;
/* xmit on all other interfaces... */
spin_lock_bh(&ipx_interfaces_lock);
list_for_each_entry(ifcs, &ipx_interfaces, node) {
/* Except unconfigured interfaces */
if (!ifcs->if_netnum)
continue;
/* That aren't in the list */
if (ifcs == intrfc)
continue;
l = (__be32 *) c;
/* don't consider the last entry in the packet list,
* it is our netnum, and it is not there yet */
for (i = 0; i < IPX_SKB_CB(skb)->ipx_tctrl; i++)
if (ifcs->if_netnum == *l++)
break;
if (i == IPX_SKB_CB(skb)->ipx_tctrl) {
struct sk_buff *s = skb_copy(skb, GFP_ATOMIC);
if (s) {
IPX_SKB_CB(s)->ipx_dest_net = ifcs->if_netnum;
ipxrtr_route_skb(s);
}
}
}
spin_unlock_bh(&ipx_interfaces_lock);
out:
return rc;
}
static void ipxitf_insert(struct ipx_interface *intrfc)
{
spin_lock_bh(&ipx_interfaces_lock);
list_add_tail(&intrfc->node, &ipx_interfaces);
spin_unlock_bh(&ipx_interfaces_lock);
if (ipxcfg_auto_select_primary && !ipx_primary_net)
ipx_primary_net = intrfc;
}
static struct ipx_interface *ipxitf_alloc(struct net_device *dev, __be32 netnum,
__be16 dlink_type,
struct datalink_proto *dlink,
unsigned char internal,
int ipx_offset)
{
struct ipx_interface *intrfc = kmalloc(sizeof(*intrfc), GFP_ATOMIC);
if (intrfc) {
intrfc->if_dev = dev;
intrfc->if_netnum = netnum;
intrfc->if_dlink_type = dlink_type;
intrfc->if_dlink = dlink;
intrfc->if_internal = internal;
intrfc->if_ipx_offset = ipx_offset;
intrfc->if_sknum = IPX_MIN_EPHEMERAL_SOCKET;
INIT_HLIST_HEAD(&intrfc->if_sklist);
atomic_set(&intrfc->refcnt, 1);
spin_lock_init(&intrfc->if_sklist_lock);
}
return intrfc;
}
static int ipxitf_create_internal(struct ipx_interface_definition *idef)
{
struct ipx_interface *intrfc;
int rc = -EEXIST;
/* Only one primary network allowed */
if (ipx_primary_net)
goto out;
/* Must have a valid network number */
rc = -EADDRNOTAVAIL;
if (!idef->ipx_network)
goto out;
intrfc = ipxitf_find_using_net(idef->ipx_network);
rc = -EADDRINUSE;
if (intrfc) {
ipxitf_put(intrfc);
goto out;
}
intrfc = ipxitf_alloc(NULL, idef->ipx_network, 0, NULL, 1, 0);
rc = -EAGAIN;
if (!intrfc)
goto out;
memcpy((char *)&(intrfc->if_node), idef->ipx_node, IPX_NODE_LEN);
ipx_internal_net = ipx_primary_net = intrfc;
ipxitf_hold(intrfc);
ipxitf_insert(intrfc);
rc = ipxitf_add_local_route(intrfc);
ipxitf_put(intrfc);
out:
return rc;
}
static __be16 ipx_map_frame_type(unsigned char type)
{
__be16 rc = 0;
switch (type) {
case IPX_FRAME_ETHERII: rc = htons(ETH_P_IPX); break;
case IPX_FRAME_8022: rc = htons(ETH_P_802_2); break;
case IPX_FRAME_SNAP: rc = htons(ETH_P_SNAP); break;
case IPX_FRAME_8023: rc = htons(ETH_P_802_3); break;
}
return rc;
}
static int ipxitf_create(struct ipx_interface_definition *idef)
{
struct net_device *dev;
__be16 dlink_type = 0;
struct datalink_proto *datalink = NULL;
struct ipx_interface *intrfc;
int rc;
if (idef->ipx_special == IPX_INTERNAL) {
rc = ipxitf_create_internal(idef);
goto out;
}
rc = -EEXIST;
if (idef->ipx_special == IPX_PRIMARY && ipx_primary_net)
goto out;
intrfc = ipxitf_find_using_net(idef->ipx_network);
rc = -EADDRINUSE;
if (idef->ipx_network && intrfc) {
ipxitf_put(intrfc);
goto out;
}
if (intrfc)
ipxitf_put(intrfc);
dev = dev_get_by_name(&init_net, idef->ipx_device);
rc = -ENODEV;
if (!dev)
goto out;
switch (idef->ipx_dlink_type) {
case IPX_FRAME_TR_8022:
printk(KERN_WARNING "IPX frame type 802.2TR is "
"obsolete Use 802.2 instead.\n");
/* fall through */
case IPX_FRAME_8022:
dlink_type = htons(ETH_P_802_2);
datalink = p8022_datalink;
break;
case IPX_FRAME_ETHERII:
if (dev->type != ARPHRD_IEEE802) {
dlink_type = htons(ETH_P_IPX);
datalink = pEII_datalink;
break;
} else
printk(KERN_WARNING "IPX frame type EtherII over "
"token-ring is obsolete. Use SNAP "
"instead.\n");
/* fall through */
case IPX_FRAME_SNAP:
dlink_type = htons(ETH_P_SNAP);
datalink = pSNAP_datalink;
break;
case IPX_FRAME_8023:
dlink_type = htons(ETH_P_802_3);
datalink = p8023_datalink;
break;
case IPX_FRAME_NONE:
default:
rc = -EPROTONOSUPPORT;
goto out_dev;
}
rc = -ENETDOWN;
if (!(dev->flags & IFF_UP))
goto out_dev;
/* Check addresses are suitable */
rc = -EINVAL;
if (dev->addr_len > IPX_NODE_LEN)
goto out_dev;
intrfc = ipxitf_find_using_phys(dev, dlink_type);
if (!intrfc) {
/* Ok now create */
intrfc = ipxitf_alloc(dev, idef->ipx_network, dlink_type,
datalink, 0, dev->hard_header_len +
datalink->header_length);
rc = -EAGAIN;
if (!intrfc)
goto out_dev;
/* Setup primary if necessary */
if (idef->ipx_special == IPX_PRIMARY)
ipx_primary_net = intrfc;
if (!memcmp(idef->ipx_node, "\000\000\000\000\000\000",
IPX_NODE_LEN)) {
memset(intrfc->if_node, 0, IPX_NODE_LEN);
memcpy(intrfc->if_node + IPX_NODE_LEN - dev->addr_len,
dev->dev_addr, dev->addr_len);
} else
memcpy(intrfc->if_node, idef->ipx_node, IPX_NODE_LEN);
ipxitf_hold(intrfc);
ipxitf_insert(intrfc);
}
/* If the network number is known, add a route */
rc = 0;
if (!intrfc->if_netnum)
goto out_intrfc;
rc = ipxitf_add_local_route(intrfc);
out_intrfc:
ipxitf_put(intrfc);
goto out;
out_dev:
dev_put(dev);
out:
return rc;
}
static int ipxitf_delete(struct ipx_interface_definition *idef)
{
struct net_device *dev = NULL;
__be16 dlink_type = 0;
struct ipx_interface *intrfc;
int rc = 0;
spin_lock_bh(&ipx_interfaces_lock);
if (idef->ipx_special == IPX_INTERNAL) {
if (ipx_internal_net) {
__ipxitf_put(ipx_internal_net);
goto out;
}
rc = -ENOENT;
goto out;
}
dlink_type = ipx_map_frame_type(idef->ipx_dlink_type);
rc = -EPROTONOSUPPORT;
if (!dlink_type)
goto out;
dev = __dev_get_by_name(&init_net, idef->ipx_device);
rc = -ENODEV;
if (!dev)
goto out;
intrfc = __ipxitf_find_using_phys(dev, dlink_type);
rc = -EINVAL;
if (!intrfc)
goto out;
__ipxitf_put(intrfc);
rc = 0;
out:
spin_unlock_bh(&ipx_interfaces_lock);
return rc;
}
static struct ipx_interface *ipxitf_auto_create(struct net_device *dev,
__be16 dlink_type)
{
struct ipx_interface *intrfc = NULL;
struct datalink_proto *datalink;
if (!dev)
goto out;
/* Check addresses are suitable */
if (dev->addr_len > IPX_NODE_LEN)
goto out;
switch (ntohs(dlink_type)) {
case ETH_P_IPX: datalink = pEII_datalink; break;
case ETH_P_802_2: datalink = p8022_datalink; break;
case ETH_P_SNAP: datalink = pSNAP_datalink; break;
case ETH_P_802_3: datalink = p8023_datalink; break;
default: goto out;
}
intrfc = ipxitf_alloc(dev, 0, dlink_type, datalink, 0,
dev->hard_header_len + datalink->header_length);
if (intrfc) {
memset(intrfc->if_node, 0, IPX_NODE_LEN);
memcpy((char *)&(intrfc->if_node[IPX_NODE_LEN-dev->addr_len]),
dev->dev_addr, dev->addr_len);
spin_lock_init(&intrfc->if_sklist_lock);
atomic_set(&intrfc->refcnt, 1);
ipxitf_insert(intrfc);
dev_hold(dev);
}
out:
return intrfc;
}
static int ipxitf_ioctl(unsigned int cmd, void __user *arg)
{
int rc = -EINVAL;
struct ifreq ifr;
int val;
switch (cmd) {
case SIOCSIFADDR: {
struct sockaddr_ipx *sipx;
struct ipx_interface_definition f;
rc = -EFAULT;
if (copy_from_user(&ifr, arg, sizeof(ifr)))
break;
sipx = (struct sockaddr_ipx *)&ifr.ifr_addr;
rc = -EINVAL;
if (sipx->sipx_family != AF_IPX)
break;
f.ipx_network = sipx->sipx_network;
memcpy(f.ipx_device, ifr.ifr_name,
sizeof(f.ipx_device));
memcpy(f.ipx_node, sipx->sipx_node, IPX_NODE_LEN);
f.ipx_dlink_type = sipx->sipx_type;
f.ipx_special = sipx->sipx_special;
if (sipx->sipx_action == IPX_DLTITF)
rc = ipxitf_delete(&f);
else
rc = ipxitf_create(&f);
break;
}
case SIOCGIFADDR: {
struct sockaddr_ipx *sipx;
struct ipx_interface *ipxif;
struct net_device *dev;
rc = -EFAULT;
if (copy_from_user(&ifr, arg, sizeof(ifr)))
break;
sipx = (struct sockaddr_ipx *)&ifr.ifr_addr;
dev = __dev_get_by_name(&init_net, ifr.ifr_name);
rc = -ENODEV;
if (!dev)
break;
ipxif = ipxitf_find_using_phys(dev,
ipx_map_frame_type(sipx->sipx_type));
rc = -EADDRNOTAVAIL;
if (!ipxif)
break;
sipx->sipx_family = AF_IPX;
sipx->sipx_network = ipxif->if_netnum;
memcpy(sipx->sipx_node, ipxif->if_node,
sizeof(sipx->sipx_node));
rc = -EFAULT;
if (copy_to_user(arg, &ifr, sizeof(ifr)))
break;
ipxitf_put(ipxif);
rc = 0;
break;
}
case SIOCAIPXITFCRT:
rc = -EFAULT;
if (get_user(val, (unsigned char __user *) arg))
break;
rc = 0;
ipxcfg_auto_create_interfaces = val;
break;
case SIOCAIPXPRISLT:
rc = -EFAULT;
if (get_user(val, (unsigned char __user *) arg))
break;
rc = 0;
ipxcfg_set_auto_select(val);
break;
}
return rc;
}
/*
* Checksum routine for IPX
*/
/* Note: We assume ipx_tctrl==0 and htons(length)==ipx_pktsize */
/* This functions should *not* mess with packet contents */
__be16 ipx_cksum(struct ipxhdr *packet, int length)
{
/*
* NOTE: sum is a net byte order quantity, which optimizes the
* loop. This only works on big and little endian machines. (I
* don't know of a machine that isn't.)
*/
/* handle the first 3 words separately; checksum should be skipped
* and ipx_tctrl masked out */
__u16 *p = (__u16 *)packet;
__u32 sum = p[1] + (p[2] & (__force u16)htons(0x00ff));
__u32 i = (length >> 1) - 3; /* Number of remaining complete words */
/* Loop through them */
p += 3;
while (i--)
sum += *p++;
/* Add on the last part word if it exists */
if (packet->ipx_pktsize & htons(1))
sum += (__force u16)htons(0xff00) & *p;
/* Do final fixup */
sum = (sum & 0xffff) + (sum >> 16);
/* It's a pity there's no concept of carry in C */
if (sum >= 0x10000)
sum++;
/*
* Leave 0 alone; we don't want 0xffff here. Note that we can't get
* here with 0x10000, so this check is the same as ((__u16)sum)
*/
if (sum)
sum = ~sum;
return (__force __be16)sum;
}
const char *ipx_frame_name(__be16 frame)
{
char* rc = "None";
switch (ntohs(frame)) {
case ETH_P_IPX: rc = "EtherII"; break;
case ETH_P_802_2: rc = "802.2"; break;
case ETH_P_SNAP: rc = "SNAP"; break;
case ETH_P_802_3: rc = "802.3"; break;
case ETH_P_TR_802_2: rc = "802.2TR"; break;
}
return rc;
}
const char *ipx_device_name(struct ipx_interface *intrfc)
{
return intrfc->if_internal ? "Internal" :
intrfc->if_dev ? intrfc->if_dev->name : "Unknown";
}
/* Handling for system calls applied via the various interfaces to an IPX
* socket object. */
static int ipx_setsockopt(struct socket *sock, int level, int optname,
char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
int opt;
int rc = -EINVAL;
lock_sock(sk);
if (optlen != sizeof(int))
goto out;
rc = -EFAULT;
if (get_user(opt, (unsigned int __user *)optval))
goto out;
rc = -ENOPROTOOPT;
if (!(level == SOL_IPX && optname == IPX_TYPE))
goto out;
ipx_sk(sk)->type = opt;
rc = 0;
out:
release_sock(sk);
return rc;
}
static int ipx_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
struct sock *sk = sock->sk;
int val = 0;
int len;
int rc = -ENOPROTOOPT;
lock_sock(sk);
if (!(level == SOL_IPX && optname == IPX_TYPE))
goto out;
val = ipx_sk(sk)->type;
rc = -EFAULT;
if (get_user(len, optlen))
goto out;
len = min_t(unsigned int, len, sizeof(int));
rc = -EINVAL;
if(len < 0)
goto out;
rc = -EFAULT;
if (put_user(len, optlen) || copy_to_user(optval, &val, len))
goto out;
rc = 0;
out:
release_sock(sk);
return rc;
}
static struct proto ipx_proto = {
.name = "IPX",
.owner = THIS_MODULE,
.obj_size = sizeof(struct ipx_sock),
};
static int ipx_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
int rc = -ESOCKTNOSUPPORT;
struct sock *sk;
if (!net_eq(net, &init_net))
return -EAFNOSUPPORT;
/*
* SPX support is not anymore in the kernel sources. If you want to
* ressurrect it, completing it and making it understand shared skbs,
* be fully multithreaded, etc, grab the sources in an early 2.5 kernel
* tree.
*/
if (sock->type != SOCK_DGRAM)
goto out;
rc = -ENOMEM;
sk = sk_alloc(net, PF_IPX, GFP_KERNEL, &ipx_proto);
if (!sk)
goto out;
sk_refcnt_debug_inc(sk);
sock_init_data(sock, sk);
sk->sk_no_check = 1; /* Checksum off by default */
sock->ops = &ipx_dgram_ops;
rc = 0;
out:
return rc;
}
static int ipx_release(struct socket *sock)
{
struct sock *sk = sock->sk;
if (!sk)
goto out;
lock_sock(sk);
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_state_change(sk);
sock_set_flag(sk, SOCK_DEAD);
sock->sk = NULL;
sk_refcnt_debug_release(sk);
ipx_destroy_socket(sk);
release_sock(sk);
sock_put(sk);
out:
return 0;
}
/* caller must hold a reference to intrfc */
static __be16 ipx_first_free_socketnum(struct ipx_interface *intrfc)
{
unsigned short socketNum = intrfc->if_sknum;
spin_lock_bh(&intrfc->if_sklist_lock);
if (socketNum < IPX_MIN_EPHEMERAL_SOCKET)
socketNum = IPX_MIN_EPHEMERAL_SOCKET;
while (__ipxitf_find_socket(intrfc, htons(socketNum)))
if (socketNum > IPX_MAX_EPHEMERAL_SOCKET)
socketNum = IPX_MIN_EPHEMERAL_SOCKET;
else
socketNum++;
spin_unlock_bh(&intrfc->if_sklist_lock);
intrfc->if_sknum = socketNum;
return htons(socketNum);
}
static int __ipx_bind(struct socket *sock,
struct sockaddr *uaddr, int addr_len)
{
struct sock *sk = sock->sk;
struct ipx_sock *ipxs = ipx_sk(sk);
struct ipx_interface *intrfc;
struct sockaddr_ipx *addr = (struct sockaddr_ipx *)uaddr;
int rc = -EINVAL;
if (!sock_flag(sk, SOCK_ZAPPED) || addr_len != sizeof(struct sockaddr_ipx))
goto out;
intrfc = ipxitf_find_using_net(addr->sipx_network);
rc = -EADDRNOTAVAIL;
if (!intrfc)
goto out;
if (!addr->sipx_port) {
addr->sipx_port = ipx_first_free_socketnum(intrfc);
rc = -EINVAL;
if (!addr->sipx_port)
goto out_put;
}
/* protect IPX system stuff like routing/sap */
rc = -EACCES;
if (ntohs(addr->sipx_port) < IPX_MIN_EPHEMERAL_SOCKET &&
!capable(CAP_NET_ADMIN))
goto out_put;
ipxs->port = addr->sipx_port;
#ifdef CONFIG_IPX_INTERN
if (intrfc == ipx_internal_net) {
/* The source address is to be set explicitly if the
* socket is to be bound on the internal network. If a
* node number 0 was specified, the default is used.
*/
rc = -EINVAL;
if (!memcmp(addr->sipx_node, ipx_broadcast_node, IPX_NODE_LEN))
goto out_put;
if (!memcmp(addr->sipx_node, ipx_this_node, IPX_NODE_LEN))
memcpy(ipxs->node, intrfc->if_node, IPX_NODE_LEN);
else
memcpy(ipxs->node, addr->sipx_node, IPX_NODE_LEN);
rc = -EADDRINUSE;
if (ipxitf_find_internal_socket(intrfc, ipxs->node,
ipxs->port)) {
SOCK_DEBUG(sk,
"IPX: bind failed because port %X in use.\n",
ntohs(addr->sipx_port));
goto out_put;
}
} else {
/* Source addresses are easy. It must be our
* network:node pair for an interface routed to IPX
* with the ipx routing ioctl()
*/
memcpy(ipxs->node, intrfc->if_node, IPX_NODE_LEN);
rc = -EADDRINUSE;
if (ipxitf_find_socket(intrfc, addr->sipx_port)) {
SOCK_DEBUG(sk,
"IPX: bind failed because port %X in use.\n",
ntohs(addr->sipx_port));
goto out_put;
}
}
#else /* !def CONFIG_IPX_INTERN */
/* Source addresses are easy. It must be our network:node pair for
an interface routed to IPX with the ipx routing ioctl() */
rc = -EADDRINUSE;
if (ipxitf_find_socket(intrfc, addr->sipx_port)) {
SOCK_DEBUG(sk, "IPX: bind failed because port %X in use.\n",
ntohs((int)addr->sipx_port));
goto out_put;
}
#endif /* CONFIG_IPX_INTERN */
ipxitf_insert_socket(intrfc, sk);
sock_reset_flag(sk, SOCK_ZAPPED);
rc = 0;
out_put:
ipxitf_put(intrfc);
out:
return rc;
}
static int ipx_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
{
struct sock *sk = sock->sk;
int rc;
lock_sock(sk);
rc = __ipx_bind(sock, uaddr, addr_len);
release_sock(sk);
return rc;
}
static int ipx_connect(struct socket *sock, struct sockaddr *uaddr,
int addr_len, int flags)
{
struct sock *sk = sock->sk;
struct ipx_sock *ipxs = ipx_sk(sk);
struct sockaddr_ipx *addr;
int rc = -EINVAL;
struct ipx_route *rt;
sk->sk_state = TCP_CLOSE;
sock->state = SS_UNCONNECTED;
lock_sock(sk);
if (addr_len != sizeof(*addr))
goto out;
addr = (struct sockaddr_ipx *)uaddr;
/* put the autobinding in */
if (!ipxs->port) {
struct sockaddr_ipx uaddr;
uaddr.sipx_port = 0;
uaddr.sipx_network = 0;
#ifdef CONFIG_IPX_INTERN
rc = -ENETDOWN;
if (!ipxs->intrfc)
goto out; /* Someone zonked the iface */
memcpy(uaddr.sipx_node, ipxs->intrfc->if_node,
IPX_NODE_LEN);
#endif /* CONFIG_IPX_INTERN */
rc = __ipx_bind(sock, (struct sockaddr *)&uaddr,
sizeof(struct sockaddr_ipx));
if (rc)
goto out;
}
/* We can either connect to primary network or somewhere
* we can route to */
rt = ipxrtr_lookup(addr->sipx_network);
rc = -ENETUNREACH;
if (!rt && !(!addr->sipx_network && ipx_primary_net))
goto out;
ipxs->dest_addr.net = addr->sipx_network;
ipxs->dest_addr.sock = addr->sipx_port;
memcpy(ipxs->dest_addr.node, addr->sipx_node, IPX_NODE_LEN);
ipxs->type = addr->sipx_type;
if (sock->type == SOCK_DGRAM) {
sock->state = SS_CONNECTED;
sk->sk_state = TCP_ESTABLISHED;
}
if (rt)
ipxrtr_put(rt);
rc = 0;
out:
release_sock(sk);
return rc;
}
static int ipx_getname(struct socket *sock, struct sockaddr *uaddr,
int *uaddr_len, int peer)
{
struct ipx_address *addr;
struct sockaddr_ipx sipx;
struct sock *sk = sock->sk;
struct ipx_sock *ipxs = ipx_sk(sk);
int rc;
*uaddr_len = sizeof(struct sockaddr_ipx);
lock_sock(sk);
if (peer) {
rc = -ENOTCONN;
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
addr = &ipxs->dest_addr;
sipx.sipx_network = addr->net;
sipx.sipx_port = addr->sock;
memcpy(sipx.sipx_node, addr->node, IPX_NODE_LEN);
} else {
if (ipxs->intrfc) {
sipx.sipx_network = ipxs->intrfc->if_netnum;
#ifdef CONFIG_IPX_INTERN
memcpy(sipx.sipx_node, ipxs->node, IPX_NODE_LEN);
#else
memcpy(sipx.sipx_node, ipxs->intrfc->if_node,
IPX_NODE_LEN);
#endif /* CONFIG_IPX_INTERN */
} else {
sipx.sipx_network = 0;
memset(sipx.sipx_node, '\0', IPX_NODE_LEN);
}
sipx.sipx_port = ipxs->port;
}
sipx.sipx_family = AF_IPX;
sipx.sipx_type = ipxs->type;
sipx.sipx_zero = 0;
memcpy(uaddr, &sipx, sizeof(sipx));
rc = 0;
out:
release_sock(sk);
return rc;
}
static int ipx_rcv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev)
{
/* NULL here for pt means the packet was looped back */
struct ipx_interface *intrfc;
struct ipxhdr *ipx;
u16 ipx_pktsize;
int rc = 0;
if (!net_eq(dev_net(dev), &init_net))
goto drop;
/* Not ours */
if (skb->pkt_type == PACKET_OTHERHOST)
goto drop;
if ((skb = skb_share_check(skb, GFP_ATOMIC)) == NULL)
goto out;
if (!pskb_may_pull(skb, sizeof(struct ipxhdr)))
goto drop;
ipx_pktsize = ntohs(ipx_hdr(skb)->ipx_pktsize);
/* Too small or invalid header? */
if (ipx_pktsize < sizeof(struct ipxhdr) ||
!pskb_may_pull(skb, ipx_pktsize))
goto drop;
ipx = ipx_hdr(skb);
if (ipx->ipx_checksum != IPX_NO_CHECKSUM &&
ipx->ipx_checksum != ipx_cksum(ipx, ipx_pktsize))
goto drop;
IPX_SKB_CB(skb)->ipx_tctrl = ipx->ipx_tctrl;
IPX_SKB_CB(skb)->ipx_dest_net = ipx->ipx_dest.net;
IPX_SKB_CB(skb)->ipx_source_net = ipx->ipx_source.net;
/* Determine what local ipx endpoint this is */
intrfc = ipxitf_find_using_phys(dev, pt->type);
if (!intrfc) {
if (ipxcfg_auto_create_interfaces &&
IPX_SKB_CB(skb)->ipx_dest_net) {
intrfc = ipxitf_auto_create(dev, pt->type);
if (intrfc)
ipxitf_hold(intrfc);
}
if (!intrfc) /* Not one of ours */
/* or invalid packet for auto creation */
goto drop;
}
rc = ipxitf_rcv(intrfc, skb);
ipxitf_put(intrfc);
goto out;
drop:
kfree_skb(skb);
out:
return rc;
}
static int ipx_sendmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct ipx_sock *ipxs = ipx_sk(sk);
struct sockaddr_ipx *usipx = (struct sockaddr_ipx *)msg->msg_name;
struct sockaddr_ipx local_sipx;
int rc = -EINVAL;
int flags = msg->msg_flags;
lock_sock(sk);
/* Socket gets bound below anyway */
/* if (sk->sk_zapped)
return -EIO; */ /* Socket not bound */
if (flags & ~(MSG_DONTWAIT|MSG_CMSG_COMPAT))
goto out;
/* Max possible packet size limited by 16 bit pktsize in header */
if (len >= 65535 - sizeof(struct ipxhdr))
goto out;
if (usipx) {
if (!ipxs->port) {
struct sockaddr_ipx uaddr;
uaddr.sipx_port = 0;
uaddr.sipx_network = 0;
#ifdef CONFIG_IPX_INTERN
rc = -ENETDOWN;
if (!ipxs->intrfc)
goto out; /* Someone zonked the iface */
memcpy(uaddr.sipx_node, ipxs->intrfc->if_node,
IPX_NODE_LEN);
#endif
rc = __ipx_bind(sock, (struct sockaddr *)&uaddr,
sizeof(struct sockaddr_ipx));
if (rc)
goto out;
}
rc = -EINVAL;
if (msg->msg_namelen < sizeof(*usipx) ||
usipx->sipx_family != AF_IPX)
goto out;
} else {
rc = -ENOTCONN;
if (sk->sk_state != TCP_ESTABLISHED)
goto out;
usipx = &local_sipx;
usipx->sipx_family = AF_IPX;
usipx->sipx_type = ipxs->type;
usipx->sipx_port = ipxs->dest_addr.sock;
usipx->sipx_network = ipxs->dest_addr.net;
memcpy(usipx->sipx_node, ipxs->dest_addr.node, IPX_NODE_LEN);
}
rc = ipxrtr_route_packet(sk, usipx, msg->msg_iov, len,
flags & MSG_DONTWAIT);
if (rc >= 0)
rc = len;
out:
release_sock(sk);
return rc;
}
static int ipx_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t size, int flags)
{
struct sock *sk = sock->sk;
struct ipx_sock *ipxs = ipx_sk(sk);
struct sockaddr_ipx *sipx = (struct sockaddr_ipx *)msg->msg_name;
struct ipxhdr *ipx = NULL;
struct sk_buff *skb;
int copied, rc;
lock_sock(sk);
/* put the autobinding in */
if (!ipxs->port) {
struct sockaddr_ipx uaddr;
uaddr.sipx_port = 0;
uaddr.sipx_network = 0;
#ifdef CONFIG_IPX_INTERN
rc = -ENETDOWN;
if (!ipxs->intrfc)
goto out; /* Someone zonked the iface */
memcpy(uaddr.sipx_node, ipxs->intrfc->if_node, IPX_NODE_LEN);
#endif /* CONFIG_IPX_INTERN */
rc = __ipx_bind(sock, (struct sockaddr *)&uaddr,
sizeof(struct sockaddr_ipx));
if (rc)
goto out;
}
rc = -ENOTCONN;
if (sock_flag(sk, SOCK_ZAPPED))
goto out;
skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT,
flags & MSG_DONTWAIT, &rc);
if (!skb)
goto out;
ipx = ipx_hdr(skb);
copied = ntohs(ipx->ipx_pktsize) - sizeof(struct ipxhdr);
if (copied > size) {
copied = size;
msg->msg_flags |= MSG_TRUNC;
}
rc = skb_copy_datagram_iovec(skb, sizeof(struct ipxhdr), msg->msg_iov,
copied);
if (rc)
goto out_free;
if (skb->tstamp.tv64)
sk->sk_stamp = skb->tstamp;
msg->msg_namelen = sizeof(*sipx);
if (sipx) {
sipx->sipx_family = AF_IPX;
sipx->sipx_port = ipx->ipx_source.sock;
memcpy(sipx->sipx_node, ipx->ipx_source.node, IPX_NODE_LEN);
sipx->sipx_network = IPX_SKB_CB(skb)->ipx_source_net;
sipx->sipx_type = ipx->ipx_type;
sipx->sipx_zero = 0;
}
rc = copied;
out_free:
skb_free_datagram(sk, skb);
out:
release_sock(sk);
return rc;
}
static int ipx_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
int rc = 0;
long amount = 0;
struct sock *sk = sock->sk;
void __user *argp = (void __user *)arg;
lock_sock(sk);
switch (cmd) {
case TIOCOUTQ:
amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk);
if (amount < 0)
amount = 0;
rc = put_user(amount, (int __user *)argp);
break;
case TIOCINQ: {
struct sk_buff *skb = skb_peek(&sk->sk_receive_queue);
/* These two are safe on a single CPU system as only
* user tasks fiddle here */
if (skb)
amount = skb->len - sizeof(struct ipxhdr);
rc = put_user(amount, (int __user *)argp);
break;
}
case SIOCADDRT:
case SIOCDELRT:
rc = -EPERM;
if (capable(CAP_NET_ADMIN))
rc = ipxrtr_ioctl(cmd, argp);
break;
case SIOCSIFADDR:
case SIOCAIPXITFCRT:
case SIOCAIPXPRISLT:
rc = -EPERM;
if (!capable(CAP_NET_ADMIN))
break;
case SIOCGIFADDR:
rc = ipxitf_ioctl(cmd, argp);
break;
case SIOCIPXCFGDATA:
rc = ipxcfg_get_config_data(argp);
break;
case SIOCIPXNCPCONN:
/*
* This socket wants to take care of the NCP connection
* handed to us in arg.
*/
rc = -EPERM;
if (!capable(CAP_NET_ADMIN))
break;
rc = get_user(ipx_sk(sk)->ipx_ncp_conn,
(const unsigned short __user *)argp);
break;
case SIOCGSTAMP:
rc = -EINVAL;
if (sk)
rc = sock_get_timestamp(sk, argp);
break;
case SIOCGIFDSTADDR:
case SIOCSIFDSTADDR:
case SIOCGIFBRDADDR:
case SIOCSIFBRDADDR:
case SIOCGIFNETMASK:
case SIOCSIFNETMASK:
rc = -EINVAL;
break;
default:
rc = -ENOIOCTLCMD;
break;
}
release_sock(sk);
return rc;
}
#ifdef CONFIG_COMPAT
static int ipx_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
{
/*
* These 4 commands use same structure on 32bit and 64bit. Rest of IPX
* commands is handled by generic ioctl code. As these commands are
* SIOCPROTOPRIVATE..SIOCPROTOPRIVATE+3, they cannot be handled by generic
* code.
*/
switch (cmd) {
case SIOCAIPXITFCRT:
case SIOCAIPXPRISLT:
case SIOCIPXCFGDATA:
case SIOCIPXNCPCONN:
return ipx_ioctl(sock, cmd, arg);
default:
return -ENOIOCTLCMD;
}
}
#endif
/*
* Socket family declarations
*/
static const struct net_proto_family ipx_family_ops = {
.family = PF_IPX,
.create = ipx_create,
.owner = THIS_MODULE,
};
static const struct proto_ops ipx_dgram_ops = {
.family = PF_IPX,
.owner = THIS_MODULE,
.release = ipx_release,
.bind = ipx_bind,
.connect = ipx_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = ipx_getname,
.poll = datagram_poll,
.ioctl = ipx_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = ipx_compat_ioctl,
#endif
.listen = sock_no_listen,
.shutdown = sock_no_shutdown, /* FIXME: support shutdown */
.setsockopt = ipx_setsockopt,
.getsockopt = ipx_getsockopt,
.sendmsg = ipx_sendmsg,
.recvmsg = ipx_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
};
static struct packet_type ipx_8023_packet_type __read_mostly = {
.type = cpu_to_be16(ETH_P_802_3),
.func = ipx_rcv,
};
static struct packet_type ipx_dix_packet_type __read_mostly = {
.type = cpu_to_be16(ETH_P_IPX),
.func = ipx_rcv,
};
static struct notifier_block ipx_dev_notifier = {
.notifier_call = ipxitf_device_event,
};
extern struct datalink_proto *make_EII_client(void);
extern void destroy_EII_client(struct datalink_proto *);
static const unsigned char ipx_8022_type = 0xE0;
static const unsigned char ipx_snap_id[5] = { 0x0, 0x0, 0x0, 0x81, 0x37 };
static const char ipx_EII_err_msg[] __initconst =
KERN_CRIT "IPX: Unable to register with Ethernet II\n";
static const char ipx_8023_err_msg[] __initconst =
KERN_CRIT "IPX: Unable to register with 802.3\n";
static const char ipx_llc_err_msg[] __initconst =
KERN_CRIT "IPX: Unable to register with 802.2\n";
static const char ipx_snap_err_msg[] __initconst =
KERN_CRIT "IPX: Unable to register with SNAP\n";
static int __init ipx_init(void)
{
int rc = proto_register(&ipx_proto, 1);
if (rc != 0)
goto out;
sock_register(&ipx_family_ops);
pEII_datalink = make_EII_client();
if (pEII_datalink)
dev_add_pack(&ipx_dix_packet_type);
else
printk(ipx_EII_err_msg);
p8023_datalink = make_8023_client();
if (p8023_datalink)
dev_add_pack(&ipx_8023_packet_type);
else
printk(ipx_8023_err_msg);
p8022_datalink = register_8022_client(ipx_8022_type, ipx_rcv);
if (!p8022_datalink)
printk(ipx_llc_err_msg);
pSNAP_datalink = register_snap_client(ipx_snap_id, ipx_rcv);
if (!pSNAP_datalink)
printk(ipx_snap_err_msg);
register_netdevice_notifier(&ipx_dev_notifier);
ipx_register_sysctl();
ipx_proc_init();
out:
return rc;
}
static void __exit ipx_proto_finito(void)
{
ipx_proc_exit();
ipx_unregister_sysctl();
unregister_netdevice_notifier(&ipx_dev_notifier);
ipxitf_cleanup();
if (pSNAP_datalink) {
unregister_snap_client(pSNAP_datalink);
pSNAP_datalink = NULL;
}
if (p8022_datalink) {
unregister_8022_client(p8022_datalink);
p8022_datalink = NULL;
}
dev_remove_pack(&ipx_8023_packet_type);
if (p8023_datalink) {
destroy_8023_client(p8023_datalink);
p8023_datalink = NULL;
}
dev_remove_pack(&ipx_dix_packet_type);
if (pEII_datalink) {
destroy_EII_client(pEII_datalink);
pEII_datalink = NULL;
}
proto_unregister(&ipx_proto);
sock_unregister(ipx_family_ops.family);
}
module_init(ipx_init);
module_exit(ipx_proto_finito);
MODULE_LICENSE("GPL");
MODULE_ALIAS_NETPROTO(PF_IPX);
| gpl-2.0 |
EPDCenter/android_kernel_bq_qc | drivers/staging/bcm/Qos.c | 8031 | 31006 | /**
@file Qos.C
This file contains the routines related to Quality of Service.
*/
#include "headers.h"
static void EThCSGetPktInfo(PMINI_ADAPTER Adapter,PVOID pvEthPayload,PS_ETHCS_PKT_INFO pstEthCsPktInfo);
static BOOLEAN EThCSClassifyPkt(PMINI_ADAPTER Adapter,struct sk_buff* skb,PS_ETHCS_PKT_INFO pstEthCsPktInfo,S_CLASSIFIER_RULE *pstClassifierRule, B_UINT8 EthCSCupport);
static USHORT IpVersion4(PMINI_ADAPTER Adapter, struct iphdr *iphd,
S_CLASSIFIER_RULE *pstClassifierRule );
static VOID PruneQueue(PMINI_ADAPTER Adapter, INT iIndex);
/*******************************************************************
* Function - MatchSrcIpAddress()
*
* Description - Checks whether the Source IP address from the packet
* matches with that of Queue.
*
* Parameters - pstClassifierRule: Pointer to the packet info structure.
* - ulSrcIP : Source IP address from the packet.
*
* Returns - TRUE(If address matches) else FAIL .
*********************************************************************/
BOOLEAN MatchSrcIpAddress(S_CLASSIFIER_RULE *pstClassifierRule,ULONG ulSrcIP)
{
UCHAR ucLoopIndex=0;
PMINI_ADAPTER Adapter = GET_BCM_ADAPTER(gblpnetdev);
ulSrcIP=ntohl(ulSrcIP);
if(0 == pstClassifierRule->ucIPSourceAddressLength)
return TRUE;
for(ucLoopIndex=0; ucLoopIndex < (pstClassifierRule->ucIPSourceAddressLength);ucLoopIndex++)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "Src Ip Address Mask:0x%x PacketIp:0x%x and Classification:0x%x", (UINT)pstClassifierRule->stSrcIpAddress.ulIpv4Mask[ucLoopIndex], (UINT)ulSrcIP, (UINT)pstClassifierRule->stSrcIpAddress.ulIpv6Addr[ucLoopIndex]);
if((pstClassifierRule->stSrcIpAddress.ulIpv4Mask[ucLoopIndex] & ulSrcIP)==
(pstClassifierRule->stSrcIpAddress.ulIpv4Addr[ucLoopIndex] & pstClassifierRule->stSrcIpAddress.ulIpv4Mask[ucLoopIndex] ))
{
return TRUE;
}
}
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "Src Ip Address Not Matched");
return FALSE;
}
/*******************************************************************
* Function - MatchDestIpAddress()
*
* Description - Checks whether the Destination IP address from the packet
* matches with that of Queue.
*
* Parameters - pstClassifierRule: Pointer to the packet info structure.
* - ulDestIP : Destination IP address from the packet.
*
* Returns - TRUE(If address matches) else FAIL .
*********************************************************************/
BOOLEAN MatchDestIpAddress(S_CLASSIFIER_RULE *pstClassifierRule,ULONG ulDestIP)
{
UCHAR ucLoopIndex=0;
PMINI_ADAPTER Adapter = GET_BCM_ADAPTER(gblpnetdev);
ulDestIP=ntohl(ulDestIP);
if(0 == pstClassifierRule->ucIPDestinationAddressLength)
return TRUE;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "Destination Ip Address 0x%x 0x%x 0x%x ", (UINT)ulDestIP, (UINT)pstClassifierRule->stDestIpAddress.ulIpv4Mask[ucLoopIndex], (UINT)pstClassifierRule->stDestIpAddress.ulIpv4Addr[ucLoopIndex]);
for(ucLoopIndex=0;ucLoopIndex<(pstClassifierRule->ucIPDestinationAddressLength);ucLoopIndex++)
{
if((pstClassifierRule->stDestIpAddress.ulIpv4Mask[ucLoopIndex] & ulDestIP)==
(pstClassifierRule->stDestIpAddress.ulIpv4Addr[ucLoopIndex] & pstClassifierRule->stDestIpAddress.ulIpv4Mask[ucLoopIndex]))
{
return TRUE;
}
}
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "Destination Ip Address Not Matched");
return FALSE;
}
/************************************************************************
* Function - MatchTos()
*
* Description - Checks the TOS from the packet matches with that of queue.
*
* Parameters - pstClassifierRule : Pointer to the packet info structure.
* - ucTypeOfService: TOS from the packet.
*
* Returns - TRUE(If address matches) else FAIL.
**************************************************************************/
BOOLEAN MatchTos(S_CLASSIFIER_RULE *pstClassifierRule,UCHAR ucTypeOfService)
{
PMINI_ADAPTER Adapter = GET_BCM_ADAPTER(gblpnetdev);
if( 3 != pstClassifierRule->ucIPTypeOfServiceLength )
return TRUE;
if(((pstClassifierRule->ucTosMask & ucTypeOfService)<=pstClassifierRule->ucTosHigh) && ((pstClassifierRule->ucTosMask & ucTypeOfService)>=pstClassifierRule->ucTosLow))
{
return TRUE;
}
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "Type Of Service Not Matched");
return FALSE;
}
/***************************************************************************
* Function - MatchProtocol()
*
* Description - Checks the protocol from the packet matches with that of queue.
*
* Parameters - pstClassifierRule: Pointer to the packet info structure.
* - ucProtocol : Protocol from the packet.
*
* Returns - TRUE(If address matches) else FAIL.
****************************************************************************/
BOOLEAN MatchProtocol(S_CLASSIFIER_RULE *pstClassifierRule,UCHAR ucProtocol)
{
UCHAR ucLoopIndex=0;
PMINI_ADAPTER Adapter = GET_BCM_ADAPTER(gblpnetdev);
if(0 == pstClassifierRule->ucProtocolLength)
return TRUE;
for(ucLoopIndex=0;ucLoopIndex<pstClassifierRule->ucProtocolLength;ucLoopIndex++)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "Protocol:0x%X Classification Protocol:0x%X",ucProtocol,pstClassifierRule->ucProtocol[ucLoopIndex]);
if(pstClassifierRule->ucProtocol[ucLoopIndex]==ucProtocol)
{
return TRUE;
}
}
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "Protocol Not Matched");
return FALSE;
}
/***********************************************************************
* Function - MatchSrcPort()
*
* Description - Checks, Source port from the packet matches with that of queue.
*
* Parameters - pstClassifierRule: Pointer to the packet info structure.
* - ushSrcPort : Source port from the packet.
*
* Returns - TRUE(If address matches) else FAIL.
***************************************************************************/
BOOLEAN MatchSrcPort(S_CLASSIFIER_RULE *pstClassifierRule,USHORT ushSrcPort)
{
UCHAR ucLoopIndex=0;
PMINI_ADAPTER Adapter = GET_BCM_ADAPTER(gblpnetdev);
if(0 == pstClassifierRule->ucSrcPortRangeLength)
return TRUE;
for(ucLoopIndex=0;ucLoopIndex<pstClassifierRule->ucSrcPortRangeLength;ucLoopIndex++)
{
if(ushSrcPort <= pstClassifierRule->usSrcPortRangeHi[ucLoopIndex] &&
ushSrcPort >= pstClassifierRule->usSrcPortRangeLo[ucLoopIndex])
{
return TRUE;
}
}
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "Src Port: %x Not Matched ",ushSrcPort);
return FALSE;
}
/***********************************************************************
* Function - MatchDestPort()
*
* Description - Checks, Destination port from packet matches with that of queue.
*
* Parameters - pstClassifierRule: Pointer to the packet info structure.
* - ushDestPort : Destination port from the packet.
*
* Returns - TRUE(If address matches) else FAIL.
***************************************************************************/
BOOLEAN MatchDestPort(S_CLASSIFIER_RULE *pstClassifierRule,USHORT ushDestPort)
{
UCHAR ucLoopIndex=0;
PMINI_ADAPTER Adapter = GET_BCM_ADAPTER(gblpnetdev);
if(0 == pstClassifierRule->ucDestPortRangeLength)
return TRUE;
for(ucLoopIndex=0;ucLoopIndex<pstClassifierRule->ucDestPortRangeLength;ucLoopIndex++)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "Matching Port:0x%X 0x%X 0x%X",ushDestPort,pstClassifierRule->usDestPortRangeLo[ucLoopIndex],pstClassifierRule->usDestPortRangeHi[ucLoopIndex]);
if(ushDestPort <= pstClassifierRule->usDestPortRangeHi[ucLoopIndex] &&
ushDestPort >= pstClassifierRule->usDestPortRangeLo[ucLoopIndex])
{
return TRUE;
}
}
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "Dest Port: %x Not Matched",ushDestPort);
return FALSE;
}
/**
@ingroup tx_functions
Compares IPV4 Ip address and port number
@return Queue Index.
*/
static USHORT IpVersion4(PMINI_ADAPTER Adapter,
struct iphdr *iphd,
S_CLASSIFIER_RULE *pstClassifierRule )
{
xporthdr *xprt_hdr=NULL;
BOOLEAN bClassificationSucceed=FALSE;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "========>");
xprt_hdr=(xporthdr *)((PUCHAR)iphd + sizeof(struct iphdr));
do {
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "Trying to see Direction = %d %d",
pstClassifierRule->ucDirection,
pstClassifierRule->usVCID_Value);
//Checking classifier validity
if(!pstClassifierRule->bUsed || pstClassifierRule->ucDirection == DOWNLINK_DIR)
{
bClassificationSucceed = FALSE;
break;
}
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "is IPv6 check!");
if(pstClassifierRule->bIpv6Protocol)
break;
//**************Checking IP header parameter**************************//
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "Trying to match Source IP Address");
if(FALSE == (bClassificationSucceed =
MatchSrcIpAddress(pstClassifierRule, iphd->saddr)))
break;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "Source IP Address Matched");
if(FALSE == (bClassificationSucceed =
MatchDestIpAddress(pstClassifierRule, iphd->daddr)))
break;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "Destination IP Address Matched");
if(FALSE == (bClassificationSucceed =
MatchTos(pstClassifierRule, iphd->tos)))
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "TOS Match failed\n");
break;
}
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "TOS Matched");
if(FALSE == (bClassificationSucceed =
MatchProtocol(pstClassifierRule,iphd->protocol)))
break;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "Protocol Matched");
//if protocol is not TCP or UDP then no need of comparing source port and destination port
if(iphd->protocol!=TCP && iphd->protocol!=UDP)
break;
//******************Checking Transport Layer Header field if present *****************//
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "Source Port %04x",
(iphd->protocol==UDP)?xprt_hdr->uhdr.source:xprt_hdr->thdr.source);
if(FALSE == (bClassificationSucceed =
MatchSrcPort(pstClassifierRule,
ntohs((iphd->protocol == UDP)?
xprt_hdr->uhdr.source:xprt_hdr->thdr.source))))
break;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "Src Port Matched");
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "Destination Port %04x",
(iphd->protocol==UDP)?xprt_hdr->uhdr.dest:
xprt_hdr->thdr.dest);
if(FALSE == (bClassificationSucceed =
MatchDestPort(pstClassifierRule,
ntohs((iphd->protocol == UDP)?
xprt_hdr->uhdr.dest:xprt_hdr->thdr.dest))))
break;
} while(0);
if(TRUE==bClassificationSucceed)
{
INT iMatchedSFQueueIndex = 0;
iMatchedSFQueueIndex = SearchSfid(Adapter,pstClassifierRule->ulSFID);
if(iMatchedSFQueueIndex >= NO_OF_QUEUES)
{
bClassificationSucceed = FALSE;
}
else
{
if(FALSE == Adapter->PackInfo[iMatchedSFQueueIndex].bActive)
{
bClassificationSucceed = FALSE;
}
}
}
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "IpVersion4 <==========");
return bClassificationSucceed;
}
VOID PruneQueueAllSF(PMINI_ADAPTER Adapter)
{
UINT iIndex = 0;
for(iIndex = 0; iIndex < HiPriority; iIndex++)
{
if(!Adapter->PackInfo[iIndex].bValid)
continue;
PruneQueue(Adapter, iIndex);
}
}
/**
@ingroup tx_functions
This function checks if the max queue size for a queue
is less than number of bytes in the queue. If so -
drops packets from the Head till the number of bytes is
less than or equal to max queue size for the queue.
*/
static VOID PruneQueue(PMINI_ADAPTER Adapter, INT iIndex)
{
struct sk_buff* PacketToDrop=NULL;
struct net_device_stats *netstats;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, PRUNE_QUEUE, DBG_LVL_ALL, "=====> Index %d",iIndex);
if(iIndex == HiPriority)
return;
if(!Adapter || (iIndex < 0) || (iIndex > HiPriority))
return;
/* To Store the netdevice statistic */
netstats = &Adapter->dev->stats;
spin_lock_bh(&Adapter->PackInfo[iIndex].SFQueueLock);
while(1)
// while((UINT)Adapter->PackInfo[iIndex].uiCurrentPacketsOnHost >
// SF_MAX_ALLOWED_PACKETS_TO_BACKUP)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, PRUNE_QUEUE, DBG_LVL_ALL, "uiCurrentBytesOnHost:%x uiMaxBucketSize :%x",
Adapter->PackInfo[iIndex].uiCurrentBytesOnHost,
Adapter->PackInfo[iIndex].uiMaxBucketSize);
PacketToDrop = Adapter->PackInfo[iIndex].FirstTxQueue;
if(PacketToDrop == NULL)
break;
if((Adapter->PackInfo[iIndex].uiCurrentPacketsOnHost < SF_MAX_ALLOWED_PACKETS_TO_BACKUP) &&
((1000*(jiffies - *((B_UINT32 *)(PacketToDrop->cb)+SKB_CB_LATENCY_OFFSET))/HZ) <= Adapter->PackInfo[iIndex].uiMaxLatency))
break;
if(PacketToDrop)
{
if (netif_msg_tx_err(Adapter))
pr_info(PFX "%s: tx queue %d overlimit\n",
Adapter->dev->name, iIndex);
netstats->tx_dropped++;
DEQUEUEPACKET(Adapter->PackInfo[iIndex].FirstTxQueue,
Adapter->PackInfo[iIndex].LastTxQueue);
/// update current bytes and packets count
Adapter->PackInfo[iIndex].uiCurrentBytesOnHost -=
PacketToDrop->len;
Adapter->PackInfo[iIndex].uiCurrentPacketsOnHost--;
/// update dropped bytes and packets counts
Adapter->PackInfo[iIndex].uiDroppedCountBytes += PacketToDrop->len;
Adapter->PackInfo[iIndex].uiDroppedCountPackets++;
dev_kfree_skb(PacketToDrop);
}
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, PRUNE_QUEUE, DBG_LVL_ALL, "Dropped Bytes:%x Dropped Packets:%x",
Adapter->PackInfo[iIndex].uiDroppedCountBytes,
Adapter->PackInfo[iIndex].uiDroppedCountPackets);
atomic_dec(&Adapter->TotalPacketCount);
}
spin_unlock_bh(&Adapter->PackInfo[iIndex].SFQueueLock);
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, PRUNE_QUEUE, DBG_LVL_ALL, "TotalPacketCount:%x",
atomic_read(&Adapter->TotalPacketCount));
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, PRUNE_QUEUE, DBG_LVL_ALL, "<=====");
}
VOID flush_all_queues(PMINI_ADAPTER Adapter)
{
INT iQIndex;
UINT uiTotalPacketLength;
struct sk_buff* PacketToDrop=NULL;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, DUMP_INFO, DBG_LVL_ALL, "=====>");
// down(&Adapter->data_packet_queue_lock);
for(iQIndex=LowPriority; iQIndex<HiPriority; iQIndex++)
{
struct net_device_stats *netstats = &Adapter->dev->stats;
spin_lock_bh(&Adapter->PackInfo[iQIndex].SFQueueLock);
while(Adapter->PackInfo[iQIndex].FirstTxQueue)
{
PacketToDrop = Adapter->PackInfo[iQIndex].FirstTxQueue;
if(PacketToDrop)
{
uiTotalPacketLength = PacketToDrop->len;
netstats->tx_dropped++;
}
else
uiTotalPacketLength = 0;
DEQUEUEPACKET(Adapter->PackInfo[iQIndex].FirstTxQueue,
Adapter->PackInfo[iQIndex].LastTxQueue);
/* Free the skb */
dev_kfree_skb(PacketToDrop);
/// update current bytes and packets count
Adapter->PackInfo[iQIndex].uiCurrentBytesOnHost -= uiTotalPacketLength;
Adapter->PackInfo[iQIndex].uiCurrentPacketsOnHost--;
/// update dropped bytes and packets counts
Adapter->PackInfo[iQIndex].uiDroppedCountBytes += uiTotalPacketLength;
Adapter->PackInfo[iQIndex].uiDroppedCountPackets++;
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, DUMP_INFO, DBG_LVL_ALL, "Dropped Bytes:%x Dropped Packets:%x",
Adapter->PackInfo[iQIndex].uiDroppedCountBytes,
Adapter->PackInfo[iQIndex].uiDroppedCountPackets);
atomic_dec(&Adapter->TotalPacketCount);
}
spin_unlock_bh(&Adapter->PackInfo[iQIndex].SFQueueLock);
}
// up(&Adapter->data_packet_queue_lock);
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_OTHERS, DUMP_INFO, DBG_LVL_ALL, "<=====");
}
USHORT ClassifyPacket(PMINI_ADAPTER Adapter,struct sk_buff* skb)
{
INT uiLoopIndex=0;
S_CLASSIFIER_RULE *pstClassifierRule = NULL;
S_ETHCS_PKT_INFO stEthCsPktInfo;
PVOID pvEThPayload = NULL;
struct iphdr *pIpHeader = NULL;
INT uiSfIndex=0;
USHORT usIndex=Adapter->usBestEffortQueueIndex;
BOOLEAN bFragmentedPkt=FALSE,bClassificationSucceed=FALSE;
USHORT usCurrFragment =0;
PTCP_HEADER pTcpHeader;
UCHAR IpHeaderLength;
UCHAR TcpHeaderLength;
pvEThPayload = skb->data;
*((UINT32*) (skb->cb) +SKB_CB_TCPACK_OFFSET ) = 0;
EThCSGetPktInfo(Adapter,pvEThPayload,&stEthCsPktInfo);
switch(stEthCsPktInfo.eNwpktEthFrameType)
{
case eEth802LLCFrame:
{
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "ClassifyPacket : 802LLCFrame\n");
pIpHeader = pvEThPayload + sizeof(ETH_CS_802_LLC_FRAME);
break;
}
case eEth802LLCSNAPFrame:
{
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "ClassifyPacket : 802LLC SNAP Frame\n");
pIpHeader = pvEThPayload + sizeof(ETH_CS_802_LLC_SNAP_FRAME);
break;
}
case eEth802QVLANFrame:
{
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "ClassifyPacket : 802.1Q VLANFrame\n");
pIpHeader = pvEThPayload + sizeof(ETH_CS_802_Q_FRAME);
break;
}
case eEthOtherFrame:
{
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "ClassifyPacket : ETH Other Frame\n");
pIpHeader = pvEThPayload + sizeof(ETH_CS_ETH2_FRAME);
break;
}
default:
{
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "ClassifyPacket : Unrecognized ETH Frame\n");
pIpHeader = pvEThPayload + sizeof(ETH_CS_ETH2_FRAME);
break;
}
}
if(stEthCsPktInfo.eNwpktIPFrameType == eIPv4Packet)
{
usCurrFragment = (ntohs(pIpHeader->frag_off) & IP_OFFSET);
if((ntohs(pIpHeader->frag_off) & IP_MF) || usCurrFragment)
bFragmentedPkt = TRUE;
if(bFragmentedPkt)
{
//Fragmented Packet. Get Frag Classifier Entry.
pstClassifierRule = GetFragIPClsEntry(Adapter,pIpHeader->id, pIpHeader->saddr);
if(pstClassifierRule)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL,"It is next Fragmented pkt");
bClassificationSucceed=TRUE;
}
if(!(ntohs(pIpHeader->frag_off) & IP_MF))
{
//Fragmented Last packet . Remove Frag Classifier Entry
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL,"This is the last fragmented Pkt");
DelFragIPClsEntry(Adapter,pIpHeader->id, pIpHeader->saddr);
}
}
}
for(uiLoopIndex = MAX_CLASSIFIERS - 1; uiLoopIndex >= 0; uiLoopIndex--)
{
if(bClassificationSucceed)
break;
//Iterate through all classifiers which are already in order of priority
//to classify the packet until match found
do
{
if(FALSE==Adapter->astClassifierTable[uiLoopIndex].bUsed)
{
bClassificationSucceed=FALSE;
break;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "Adapter->PackInfo[%d].bvalid=True\n",uiLoopIndex);
if(0 == Adapter->astClassifierTable[uiLoopIndex].ucDirection)
{
bClassificationSucceed=FALSE;//cannot be processed for classification.
break; // it is a down link connection
}
pstClassifierRule = &Adapter->astClassifierTable[uiLoopIndex];
uiSfIndex = SearchSfid(Adapter,pstClassifierRule->ulSFID);
if (uiSfIndex >= NO_OF_QUEUES) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "Queue Not Valid. SearchSfid for this classifier Failed\n");
break;
}
if(Adapter->PackInfo[uiSfIndex].bEthCSSupport)
{
if(eEthUnsupportedFrame==stEthCsPktInfo.eNwpktEthFrameType)
{
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, " ClassifyPacket : Packet Not a Valid Supported Ethernet Frame \n");
bClassificationSucceed = FALSE;
break;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "Performing ETH CS Classification on Classifier Rule ID : %x Service Flow ID : %lx\n",pstClassifierRule->uiClassifierRuleIndex,Adapter->PackInfo[uiSfIndex].ulSFID);
bClassificationSucceed = EThCSClassifyPkt(Adapter,skb,&stEthCsPktInfo,pstClassifierRule, Adapter->PackInfo[uiSfIndex].bEthCSSupport);
if(!bClassificationSucceed)
{
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "ClassifyPacket : Ethernet CS Classification Failed\n");
break;
}
}
else // No ETH Supported on this SF
{
if(eEthOtherFrame != stEthCsPktInfo.eNwpktEthFrameType)
{
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, " ClassifyPacket : Packet Not a 802.3 Ethernet Frame... hence not allowed over non-ETH CS SF \n");
bClassificationSucceed = FALSE;
break;
}
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "Proceeding to IP CS Clasification");
if(Adapter->PackInfo[uiSfIndex].bIPCSSupport)
{
if(stEthCsPktInfo.eNwpktIPFrameType == eNonIPPacket)
{
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, " ClassifyPacket : Packet is Not an IP Packet \n");
bClassificationSucceed = FALSE;
break;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "Dump IP Header : \n");
DumpFullPacket((PUCHAR)pIpHeader,20);
if(stEthCsPktInfo.eNwpktIPFrameType == eIPv4Packet)
bClassificationSucceed = IpVersion4(Adapter,pIpHeader,pstClassifierRule);
else if(stEthCsPktInfo.eNwpktIPFrameType == eIPv6Packet)
bClassificationSucceed = IpVersion6(Adapter,pIpHeader,pstClassifierRule);
}
}while(0);
}
if(bClassificationSucceed == TRUE)
{
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "CF id : %d, SF ID is =%lu",pstClassifierRule->uiClassifierRuleIndex, pstClassifierRule->ulSFID);
//Store The matched Classifier in SKB
*((UINT32*)(skb->cb)+SKB_CB_CLASSIFICATION_OFFSET) = pstClassifierRule->uiClassifierRuleIndex;
if((TCP == pIpHeader->protocol ) && !bFragmentedPkt && (ETH_AND_IP_HEADER_LEN + TCP_HEADER_LEN <= skb->len) )
{
IpHeaderLength = pIpHeader->ihl;
pTcpHeader = (PTCP_HEADER)(((PUCHAR)pIpHeader)+(IpHeaderLength*4));
TcpHeaderLength = GET_TCP_HEADER_LEN(pTcpHeader->HeaderLength);
if((pTcpHeader->ucFlags & TCP_ACK) &&
(ntohs(pIpHeader->tot_len) == (IpHeaderLength*4)+(TcpHeaderLength*4)))
{
*((UINT32*) (skb->cb) +SKB_CB_TCPACK_OFFSET ) = TCP_ACK;
}
}
usIndex = SearchSfid(Adapter, pstClassifierRule->ulSFID);
BCM_DEBUG_PRINT(Adapter,DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "index is =%d", usIndex);
//If this is the first fragment of a Fragmented pkt, add this CF. Only This CF should be used for all other fragment of this Pkt.
if(bFragmentedPkt && (usCurrFragment == 0))
{
//First Fragment of Fragmented Packet. Create Frag CLS Entry
S_FRAGMENTED_PACKET_INFO stFragPktInfo;
stFragPktInfo.bUsed = TRUE;
stFragPktInfo.ulSrcIpAddress = pIpHeader->saddr;
stFragPktInfo.usIpIdentification = pIpHeader->id;
stFragPktInfo.pstMatchedClassifierEntry = pstClassifierRule;
stFragPktInfo.bOutOfOrderFragment = FALSE;
AddFragIPClsEntry(Adapter,&stFragPktInfo);
}
}
if(bClassificationSucceed)
return usIndex;
else
return INVALID_QUEUE_INDEX;
}
static BOOLEAN EthCSMatchSrcMACAddress(S_CLASSIFIER_RULE *pstClassifierRule,PUCHAR Mac)
{
UINT i=0;
PMINI_ADAPTER Adapter = GET_BCM_ADAPTER(gblpnetdev);
if(pstClassifierRule->ucEthCSSrcMACLen==0)
return TRUE;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "%s \n",__FUNCTION__);
for(i=0;i<MAC_ADDRESS_SIZE;i++)
{
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "SRC MAC[%x] = %x ClassifierRuleSrcMAC = %x Mask : %x\n",i,Mac[i],pstClassifierRule->au8EThCSSrcMAC[i],pstClassifierRule->au8EThCSSrcMACMask[i]);
if((pstClassifierRule->au8EThCSSrcMAC[i] & pstClassifierRule->au8EThCSSrcMACMask[i])!=
(Mac[i] & pstClassifierRule->au8EThCSSrcMACMask[i]))
return FALSE;
}
return TRUE;
}
static BOOLEAN EthCSMatchDestMACAddress(S_CLASSIFIER_RULE *pstClassifierRule,PUCHAR Mac)
{
UINT i=0;
PMINI_ADAPTER Adapter = GET_BCM_ADAPTER(gblpnetdev);
if(pstClassifierRule->ucEthCSDestMACLen==0)
return TRUE;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "%s \n",__FUNCTION__);
for(i=0;i<MAC_ADDRESS_SIZE;i++)
{
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "SRC MAC[%x] = %x ClassifierRuleSrcMAC = %x Mask : %x\n",i,Mac[i],pstClassifierRule->au8EThCSDestMAC[i],pstClassifierRule->au8EThCSDestMACMask[i]);
if((pstClassifierRule->au8EThCSDestMAC[i] & pstClassifierRule->au8EThCSDestMACMask[i])!=
(Mac[i] & pstClassifierRule->au8EThCSDestMACMask[i]))
return FALSE;
}
return TRUE;
}
static BOOLEAN EthCSMatchEThTypeSAP(S_CLASSIFIER_RULE *pstClassifierRule,struct sk_buff* skb,PS_ETHCS_PKT_INFO pstEthCsPktInfo)
{
PMINI_ADAPTER Adapter = GET_BCM_ADAPTER(gblpnetdev);
if((pstClassifierRule->ucEtherTypeLen==0)||
(pstClassifierRule->au8EthCSEtherType[0] == 0))
return TRUE;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "%s SrcEtherType:%x CLS EtherType[0]:%x\n",__FUNCTION__,pstEthCsPktInfo->usEtherType,pstClassifierRule->au8EthCSEtherType[0]);
if(pstClassifierRule->au8EthCSEtherType[0] == 1)
{
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "%s CLS EtherType[1]:%x EtherType[2]:%x\n",__FUNCTION__,pstClassifierRule->au8EthCSEtherType[1],pstClassifierRule->au8EthCSEtherType[2]);
if(memcmp(&pstEthCsPktInfo->usEtherType,&pstClassifierRule->au8EthCSEtherType[1],2)==0)
return TRUE;
else
return FALSE;
}
if(pstClassifierRule->au8EthCSEtherType[0] == 2)
{
if(eEth802LLCFrame != pstEthCsPktInfo->eNwpktEthFrameType)
return FALSE;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "%s EthCS DSAP:%x EtherType[2]:%x\n",__FUNCTION__,pstEthCsPktInfo->ucDSAP,pstClassifierRule->au8EthCSEtherType[2]);
if(pstEthCsPktInfo->ucDSAP == pstClassifierRule->au8EthCSEtherType[2])
return TRUE;
else
return FALSE;
}
return FALSE;
}
static BOOLEAN EthCSMatchVLANRules(S_CLASSIFIER_RULE *pstClassifierRule,struct sk_buff* skb,PS_ETHCS_PKT_INFO pstEthCsPktInfo)
{
BOOLEAN bClassificationSucceed = FALSE;
USHORT usVLANID;
B_UINT8 uPriority = 0;
PMINI_ADAPTER Adapter = GET_BCM_ADAPTER(gblpnetdev);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "%s CLS UserPrio:%x CLS VLANID:%x\n",__FUNCTION__,ntohs(*((USHORT *)pstClassifierRule->usUserPriority)),pstClassifierRule->usVLANID);
/* In case FW didn't receive the TLV, the priority field should be ignored */
if(pstClassifierRule->usValidityBitMap & (1<<PKT_CLASSIFICATION_USER_PRIORITY_VALID))
{
if(pstEthCsPktInfo->eNwpktEthFrameType!=eEth802QVLANFrame)
return FALSE;
uPriority = (ntohs(*(USHORT *)(skb->data + sizeof(ETH_HEADER_STRUC))) & 0xF000) >> 13;
if((uPriority >= pstClassifierRule->usUserPriority[0]) && (uPriority <= pstClassifierRule->usUserPriority[1]))
bClassificationSucceed = TRUE;
if(!bClassificationSucceed)
return FALSE;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "ETH CS 802.1 D User Priority Rule Matched\n");
bClassificationSucceed = FALSE;
if(pstClassifierRule->usValidityBitMap & (1<<PKT_CLASSIFICATION_VLANID_VALID))
{
if(pstEthCsPktInfo->eNwpktEthFrameType!=eEth802QVLANFrame)
return FALSE;
usVLANID = ntohs(*(USHORT *)(skb->data + sizeof(ETH_HEADER_STRUC))) & 0xFFF;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "%s Pkt VLANID %x Priority: %d\n",__FUNCTION__,usVLANID, uPriority);
if(usVLANID == ((pstClassifierRule->usVLANID & 0xFFF0) >> 4))
bClassificationSucceed = TRUE;
if(!bClassificationSucceed)
return FALSE;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "ETH CS 802.1 Q VLAN ID Rule Matched\n");
return TRUE;
}
static BOOLEAN EThCSClassifyPkt(PMINI_ADAPTER Adapter,struct sk_buff* skb,
PS_ETHCS_PKT_INFO pstEthCsPktInfo,
S_CLASSIFIER_RULE *pstClassifierRule,
B_UINT8 EthCSCupport)
{
BOOLEAN bClassificationSucceed = FALSE;
bClassificationSucceed = EthCSMatchSrcMACAddress(pstClassifierRule,((ETH_HEADER_STRUC *)(skb->data))->au8SourceAddress);
if(!bClassificationSucceed)
return FALSE;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "ETH CS SrcMAC Matched\n");
bClassificationSucceed = EthCSMatchDestMACAddress(pstClassifierRule,((ETH_HEADER_STRUC*)(skb->data))->au8DestinationAddress);
if(!bClassificationSucceed)
return FALSE;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "ETH CS DestMAC Matched\n");
//classify on ETHType/802.2SAP TLV
bClassificationSucceed = EthCSMatchEThTypeSAP(pstClassifierRule,skb,pstEthCsPktInfo);
if(!bClassificationSucceed)
return FALSE;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "ETH CS EthType/802.2SAP Matched\n");
//classify on 802.1VLAN Header Parameters
bClassificationSucceed = EthCSMatchVLANRules(pstClassifierRule,skb,pstEthCsPktInfo);
if(!bClassificationSucceed)
return FALSE;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "ETH CS 802.1 VLAN Rules Matched\n");
return bClassificationSucceed;
}
static void EThCSGetPktInfo(PMINI_ADAPTER Adapter,PVOID pvEthPayload,
PS_ETHCS_PKT_INFO pstEthCsPktInfo)
{
USHORT u16Etype = ntohs(((ETH_HEADER_STRUC*)pvEthPayload)->u16Etype);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "EthCSGetPktInfo : Eth Hdr Type : %X\n",u16Etype);
if(u16Etype > 0x5dc)
{
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "EthCSGetPktInfo : ETH2 Frame \n");
//ETH2 Frame
if(u16Etype == ETHERNET_FRAMETYPE_802QVLAN)
{
//802.1Q VLAN Header
pstEthCsPktInfo->eNwpktEthFrameType = eEth802QVLANFrame;
u16Etype = ((ETH_CS_802_Q_FRAME*)pvEthPayload)->EthType;
//((ETH_CS_802_Q_FRAME*)pvEthPayload)->UserPriority
}
else
{
pstEthCsPktInfo->eNwpktEthFrameType = eEthOtherFrame;
u16Etype = ntohs(u16Etype);
}
}
else
{
//802.2 LLC
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "802.2 LLC Frame \n");
pstEthCsPktInfo->eNwpktEthFrameType = eEth802LLCFrame;
pstEthCsPktInfo->ucDSAP = ((ETH_CS_802_LLC_FRAME*)pvEthPayload)->DSAP;
if(pstEthCsPktInfo->ucDSAP == 0xAA && ((ETH_CS_802_LLC_FRAME*)pvEthPayload)->SSAP == 0xAA)
{
//SNAP Frame
pstEthCsPktInfo->eNwpktEthFrameType = eEth802LLCSNAPFrame;
u16Etype = ((ETH_CS_802_LLC_SNAP_FRAME*)pvEthPayload)->usEtherType;
}
}
if(u16Etype == ETHERNET_FRAMETYPE_IPV4)
pstEthCsPktInfo->eNwpktIPFrameType = eIPv4Packet;
else if(u16Etype == ETHERNET_FRAMETYPE_IPV6)
pstEthCsPktInfo->eNwpktIPFrameType = eIPv6Packet;
else
pstEthCsPktInfo->eNwpktIPFrameType = eNonIPPacket;
pstEthCsPktInfo->usEtherType = ((ETH_HEADER_STRUC*)pvEthPayload)->u16Etype;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "EthCsPktInfo->eNwpktIPFrameType : %x\n",pstEthCsPktInfo->eNwpktIPFrameType);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "EthCsPktInfo->eNwpktEthFrameType : %x\n",pstEthCsPktInfo->eNwpktEthFrameType);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_TX, IPV4_DBG, DBG_LVL_ALL, "EthCsPktInfo->usEtherType : %x\n",pstEthCsPktInfo->usEtherType);
}
| gpl-2.0 |
Eason91/kernel_lge_x3 | drivers/ide/ide.c | 10847 | 10698 | /*
* Copyright (C) 1994-1998 Linus Torvalds & authors (see below)
* Copyright (C) 2003-2005, 2007 Bartlomiej Zolnierkiewicz
*/
/*
* Mostly written by Mark Lord <mlord@pobox.com>
* and Gadi Oxman <gadio@netvision.net.il>
* and Andre Hedrick <andre@linux-ide.org>
*
* See linux/MAINTAINERS for address of current maintainer.
*
* This is the multiple IDE interface driver, as evolved from hd.c.
* It supports up to MAX_HWIFS IDE interfaces, on one or more IRQs
* (usually 14 & 15).
* There can be up to two drives per interface, as per the ATA-2 spec.
*
* ...
*
* From hd.c:
* |
* | It traverses the request-list, using interrupts to jump between functions.
* | As nearly all functions can be called within interrupts, we may not sleep.
* | Special care is recommended. Have Fun!
* |
* | modified by Drew Eckhardt to check nr of hd's from the CMOS.
* |
* | Thanks to Branko Lankester, lankeste@fwi.uva.nl, who found a bug
* | in the early extended-partition checks and added DM partitions.
* |
* | Early work on error handling by Mika Liljeberg (liljeber@cs.Helsinki.FI).
* |
* | IRQ-unmask, drive-id, multiple-mode, support for ">16 heads",
* | and general streamlining by Mark Lord (mlord@pobox.com).
*
* October, 1994 -- Complete line-by-line overhaul for linux 1.1.x, by:
*
* Mark Lord (mlord@pobox.com) (IDE Perf.Pkg)
* Delman Lee (delman@ieee.org) ("Mr. atdisk2")
* Scott Snyder (snyder@fnald0.fnal.gov) (ATAPI IDE cd-rom)
*
* This was a rewrite of just about everything from hd.c, though some original
* code is still sprinkled about. Think of it as a major evolution, with
* inspiration from lots of linux users, esp. hamish@zot.apana.org.au
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/interrupt.h>
#include <linux/major.h>
#include <linux/errno.h>
#include <linux/genhd.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/ide.h>
#include <linux/hdreg.h>
#include <linux/completion.h>
#include <linux/device.h>
struct class *ide_port_class;
/**
* ide_device_get - get an additional reference to a ide_drive_t
* @drive: device to get a reference to
*
* Gets a reference to the ide_drive_t and increments the use count of the
* underlying LLDD module.
*/
int ide_device_get(ide_drive_t *drive)
{
struct device *host_dev;
struct module *module;
if (!get_device(&drive->gendev))
return -ENXIO;
host_dev = drive->hwif->host->dev[0];
module = host_dev ? host_dev->driver->owner : NULL;
if (module && !try_module_get(module)) {
put_device(&drive->gendev);
return -ENXIO;
}
return 0;
}
EXPORT_SYMBOL_GPL(ide_device_get);
/**
* ide_device_put - release a reference to a ide_drive_t
* @drive: device to release a reference on
*
* Release a reference to the ide_drive_t and decrements the use count of
* the underlying LLDD module.
*/
void ide_device_put(ide_drive_t *drive)
{
#ifdef CONFIG_MODULE_UNLOAD
struct device *host_dev = drive->hwif->host->dev[0];
struct module *module = host_dev ? host_dev->driver->owner : NULL;
if (module)
module_put(module);
#endif
put_device(&drive->gendev);
}
EXPORT_SYMBOL_GPL(ide_device_put);
static int ide_bus_match(struct device *dev, struct device_driver *drv)
{
return 1;
}
static int ide_uevent(struct device *dev, struct kobj_uevent_env *env)
{
ide_drive_t *drive = to_ide_device(dev);
add_uevent_var(env, "MEDIA=%s", ide_media_string(drive));
add_uevent_var(env, "DRIVENAME=%s", drive->name);
add_uevent_var(env, "MODALIAS=ide:m-%s", ide_media_string(drive));
return 0;
}
static int generic_ide_probe(struct device *dev)
{
ide_drive_t *drive = to_ide_device(dev);
struct ide_driver *drv = to_ide_driver(dev->driver);
return drv->probe ? drv->probe(drive) : -ENODEV;
}
static int generic_ide_remove(struct device *dev)
{
ide_drive_t *drive = to_ide_device(dev);
struct ide_driver *drv = to_ide_driver(dev->driver);
if (drv->remove)
drv->remove(drive);
return 0;
}
static void generic_ide_shutdown(struct device *dev)
{
ide_drive_t *drive = to_ide_device(dev);
struct ide_driver *drv = to_ide_driver(dev->driver);
if (dev->driver && drv->shutdown)
drv->shutdown(drive);
}
struct bus_type ide_bus_type = {
.name = "ide",
.match = ide_bus_match,
.uevent = ide_uevent,
.probe = generic_ide_probe,
.remove = generic_ide_remove,
.shutdown = generic_ide_shutdown,
.dev_attrs = ide_dev_attrs,
.suspend = generic_ide_suspend,
.resume = generic_ide_resume,
};
EXPORT_SYMBOL_GPL(ide_bus_type);
int ide_vlb_clk;
EXPORT_SYMBOL_GPL(ide_vlb_clk);
module_param_named(vlb_clock, ide_vlb_clk, int, 0);
MODULE_PARM_DESC(vlb_clock, "VLB clock frequency (in MHz)");
int ide_pci_clk;
EXPORT_SYMBOL_GPL(ide_pci_clk);
module_param_named(pci_clock, ide_pci_clk, int, 0);
MODULE_PARM_DESC(pci_clock, "PCI bus clock frequency (in MHz)");
static int ide_set_dev_param_mask(const char *s, const struct kernel_param *kp)
{
int a, b, i, j = 1;
unsigned int *dev_param_mask = (unsigned int *)kp->arg;
/* controller . device (0 or 1) [ : 1 (set) | 0 (clear) ] */
if (sscanf(s, "%d.%d:%d", &a, &b, &j) != 3 &&
sscanf(s, "%d.%d", &a, &b) != 2)
return -EINVAL;
i = a * MAX_DRIVES + b;
if (i >= MAX_HWIFS * MAX_DRIVES || j < 0 || j > 1)
return -EINVAL;
if (j)
*dev_param_mask |= (1 << i);
else
*dev_param_mask &= ~(1 << i);
return 0;
}
static struct kernel_param_ops param_ops_ide_dev_mask = {
.set = ide_set_dev_param_mask
};
#define param_check_ide_dev_mask(name, p) param_check_uint(name, p)
static unsigned int ide_nodma;
module_param_named(nodma, ide_nodma, ide_dev_mask, 0);
MODULE_PARM_DESC(nodma, "disallow DMA for a device");
static unsigned int ide_noflush;
module_param_named(noflush, ide_noflush, ide_dev_mask, 0);
MODULE_PARM_DESC(noflush, "disable flush requests for a device");
static unsigned int ide_nohpa;
module_param_named(nohpa, ide_nohpa, ide_dev_mask, 0);
MODULE_PARM_DESC(nohpa, "disable Host Protected Area for a device");
static unsigned int ide_noprobe;
module_param_named(noprobe, ide_noprobe, ide_dev_mask, 0);
MODULE_PARM_DESC(noprobe, "skip probing for a device");
static unsigned int ide_nowerr;
module_param_named(nowerr, ide_nowerr, ide_dev_mask, 0);
MODULE_PARM_DESC(nowerr, "ignore the ATA_DF bit for a device");
static unsigned int ide_cdroms;
module_param_named(cdrom, ide_cdroms, ide_dev_mask, 0);
MODULE_PARM_DESC(cdrom, "force device as a CD-ROM");
struct chs_geom {
unsigned int cyl;
u8 head;
u8 sect;
};
static unsigned int ide_disks;
static struct chs_geom ide_disks_chs[MAX_HWIFS * MAX_DRIVES];
static int ide_set_disk_chs(const char *str, struct kernel_param *kp)
{
int a, b, c = 0, h = 0, s = 0, i, j = 1;
/* controller . device (0 or 1) : Cylinders , Heads , Sectors */
/* controller . device (0 or 1) : 1 (use CHS) | 0 (ignore CHS) */
if (sscanf(str, "%d.%d:%d,%d,%d", &a, &b, &c, &h, &s) != 5 &&
sscanf(str, "%d.%d:%d", &a, &b, &j) != 3)
return -EINVAL;
i = a * MAX_DRIVES + b;
if (i >= MAX_HWIFS * MAX_DRIVES || j < 0 || j > 1)
return -EINVAL;
if (c > INT_MAX || h > 255 || s > 255)
return -EINVAL;
if (j)
ide_disks |= (1 << i);
else
ide_disks &= ~(1 << i);
ide_disks_chs[i].cyl = c;
ide_disks_chs[i].head = h;
ide_disks_chs[i].sect = s;
return 0;
}
module_param_call(chs, ide_set_disk_chs, NULL, NULL, 0);
MODULE_PARM_DESC(chs, "force device as a disk (using CHS)");
static void ide_dev_apply_params(ide_drive_t *drive, u8 unit)
{
int i = drive->hwif->index * MAX_DRIVES + unit;
if (ide_nodma & (1 << i)) {
printk(KERN_INFO "ide: disallowing DMA for %s\n", drive->name);
drive->dev_flags |= IDE_DFLAG_NODMA;
}
if (ide_noflush & (1 << i)) {
printk(KERN_INFO "ide: disabling flush requests for %s\n",
drive->name);
drive->dev_flags |= IDE_DFLAG_NOFLUSH;
}
if (ide_nohpa & (1 << i)) {
printk(KERN_INFO "ide: disabling Host Protected Area for %s\n",
drive->name);
drive->dev_flags |= IDE_DFLAG_NOHPA;
}
if (ide_noprobe & (1 << i)) {
printk(KERN_INFO "ide: skipping probe for %s\n", drive->name);
drive->dev_flags |= IDE_DFLAG_NOPROBE;
}
if (ide_nowerr & (1 << i)) {
printk(KERN_INFO "ide: ignoring the ATA_DF bit for %s\n",
drive->name);
drive->bad_wstat = BAD_R_STAT;
}
if (ide_cdroms & (1 << i)) {
printk(KERN_INFO "ide: forcing %s as a CD-ROM\n", drive->name);
drive->dev_flags |= IDE_DFLAG_PRESENT;
drive->media = ide_cdrom;
/* an ATAPI device ignores DRDY */
drive->ready_stat = 0;
}
if (ide_disks & (1 << i)) {
drive->cyl = drive->bios_cyl = ide_disks_chs[i].cyl;
drive->head = drive->bios_head = ide_disks_chs[i].head;
drive->sect = drive->bios_sect = ide_disks_chs[i].sect;
printk(KERN_INFO "ide: forcing %s as a disk (%d/%d/%d)\n",
drive->name,
drive->cyl, drive->head, drive->sect);
drive->dev_flags |= IDE_DFLAG_FORCED_GEOM | IDE_DFLAG_PRESENT;
drive->media = ide_disk;
drive->ready_stat = ATA_DRDY;
}
}
static unsigned int ide_ignore_cable;
static int ide_set_ignore_cable(const char *s, struct kernel_param *kp)
{
int i, j = 1;
/* controller (ignore) */
/* controller : 1 (ignore) | 0 (use) */
if (sscanf(s, "%d:%d", &i, &j) != 2 && sscanf(s, "%d", &i) != 1)
return -EINVAL;
if (i >= MAX_HWIFS || j < 0 || j > 1)
return -EINVAL;
if (j)
ide_ignore_cable |= (1 << i);
else
ide_ignore_cable &= ~(1 << i);
return 0;
}
module_param_call(ignore_cable, ide_set_ignore_cable, NULL, NULL, 0);
MODULE_PARM_DESC(ignore_cable, "ignore cable detection");
void ide_port_apply_params(ide_hwif_t *hwif)
{
ide_drive_t *drive;
int i;
if (ide_ignore_cable & (1 << hwif->index)) {
printk(KERN_INFO "ide: ignoring cable detection for %s\n",
hwif->name);
hwif->cbl = ATA_CBL_PATA40_SHORT;
}
ide_port_for_each_dev(i, drive, hwif)
ide_dev_apply_params(drive, i);
}
/*
* This is gets invoked once during initialization, to set *everything* up
*/
static int __init ide_init(void)
{
int ret;
printk(KERN_INFO "Uniform Multi-Platform E-IDE driver\n");
ret = bus_register(&ide_bus_type);
if (ret < 0) {
printk(KERN_WARNING "IDE: bus_register error: %d\n", ret);
return ret;
}
ide_port_class = class_create(THIS_MODULE, "ide_port");
if (IS_ERR(ide_port_class)) {
ret = PTR_ERR(ide_port_class);
goto out_port_class;
}
ide_acpi_init();
proc_ide_create();
return 0;
out_port_class:
bus_unregister(&ide_bus_type);
return ret;
}
static void __exit ide_exit(void)
{
proc_ide_destroy();
class_destroy(ide_port_class);
bus_unregister(&ide_bus_type);
}
module_init(ide_init);
module_exit(ide_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
sktjdgns1189/android_kernel_pantech_ef63l-cm | drivers/ide/ide.c | 10847 | 10698 | /*
* Copyright (C) 1994-1998 Linus Torvalds & authors (see below)
* Copyright (C) 2003-2005, 2007 Bartlomiej Zolnierkiewicz
*/
/*
* Mostly written by Mark Lord <mlord@pobox.com>
* and Gadi Oxman <gadio@netvision.net.il>
* and Andre Hedrick <andre@linux-ide.org>
*
* See linux/MAINTAINERS for address of current maintainer.
*
* This is the multiple IDE interface driver, as evolved from hd.c.
* It supports up to MAX_HWIFS IDE interfaces, on one or more IRQs
* (usually 14 & 15).
* There can be up to two drives per interface, as per the ATA-2 spec.
*
* ...
*
* From hd.c:
* |
* | It traverses the request-list, using interrupts to jump between functions.
* | As nearly all functions can be called within interrupts, we may not sleep.
* | Special care is recommended. Have Fun!
* |
* | modified by Drew Eckhardt to check nr of hd's from the CMOS.
* |
* | Thanks to Branko Lankester, lankeste@fwi.uva.nl, who found a bug
* | in the early extended-partition checks and added DM partitions.
* |
* | Early work on error handling by Mika Liljeberg (liljeber@cs.Helsinki.FI).
* |
* | IRQ-unmask, drive-id, multiple-mode, support for ">16 heads",
* | and general streamlining by Mark Lord (mlord@pobox.com).
*
* October, 1994 -- Complete line-by-line overhaul for linux 1.1.x, by:
*
* Mark Lord (mlord@pobox.com) (IDE Perf.Pkg)
* Delman Lee (delman@ieee.org) ("Mr. atdisk2")
* Scott Snyder (snyder@fnald0.fnal.gov) (ATAPI IDE cd-rom)
*
* This was a rewrite of just about everything from hd.c, though some original
* code is still sprinkled about. Think of it as a major evolution, with
* inspiration from lots of linux users, esp. hamish@zot.apana.org.au
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/interrupt.h>
#include <linux/major.h>
#include <linux/errno.h>
#include <linux/genhd.h>
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/ide.h>
#include <linux/hdreg.h>
#include <linux/completion.h>
#include <linux/device.h>
struct class *ide_port_class;
/**
* ide_device_get - get an additional reference to a ide_drive_t
* @drive: device to get a reference to
*
* Gets a reference to the ide_drive_t and increments the use count of the
* underlying LLDD module.
*/
int ide_device_get(ide_drive_t *drive)
{
struct device *host_dev;
struct module *module;
if (!get_device(&drive->gendev))
return -ENXIO;
host_dev = drive->hwif->host->dev[0];
module = host_dev ? host_dev->driver->owner : NULL;
if (module && !try_module_get(module)) {
put_device(&drive->gendev);
return -ENXIO;
}
return 0;
}
EXPORT_SYMBOL_GPL(ide_device_get);
/**
* ide_device_put - release a reference to a ide_drive_t
* @drive: device to release a reference on
*
* Release a reference to the ide_drive_t and decrements the use count of
* the underlying LLDD module.
*/
void ide_device_put(ide_drive_t *drive)
{
#ifdef CONFIG_MODULE_UNLOAD
struct device *host_dev = drive->hwif->host->dev[0];
struct module *module = host_dev ? host_dev->driver->owner : NULL;
if (module)
module_put(module);
#endif
put_device(&drive->gendev);
}
EXPORT_SYMBOL_GPL(ide_device_put);
static int ide_bus_match(struct device *dev, struct device_driver *drv)
{
return 1;
}
static int ide_uevent(struct device *dev, struct kobj_uevent_env *env)
{
ide_drive_t *drive = to_ide_device(dev);
add_uevent_var(env, "MEDIA=%s", ide_media_string(drive));
add_uevent_var(env, "DRIVENAME=%s", drive->name);
add_uevent_var(env, "MODALIAS=ide:m-%s", ide_media_string(drive));
return 0;
}
static int generic_ide_probe(struct device *dev)
{
ide_drive_t *drive = to_ide_device(dev);
struct ide_driver *drv = to_ide_driver(dev->driver);
return drv->probe ? drv->probe(drive) : -ENODEV;
}
static int generic_ide_remove(struct device *dev)
{
ide_drive_t *drive = to_ide_device(dev);
struct ide_driver *drv = to_ide_driver(dev->driver);
if (drv->remove)
drv->remove(drive);
return 0;
}
static void generic_ide_shutdown(struct device *dev)
{
ide_drive_t *drive = to_ide_device(dev);
struct ide_driver *drv = to_ide_driver(dev->driver);
if (dev->driver && drv->shutdown)
drv->shutdown(drive);
}
struct bus_type ide_bus_type = {
.name = "ide",
.match = ide_bus_match,
.uevent = ide_uevent,
.probe = generic_ide_probe,
.remove = generic_ide_remove,
.shutdown = generic_ide_shutdown,
.dev_attrs = ide_dev_attrs,
.suspend = generic_ide_suspend,
.resume = generic_ide_resume,
};
EXPORT_SYMBOL_GPL(ide_bus_type);
int ide_vlb_clk;
EXPORT_SYMBOL_GPL(ide_vlb_clk);
module_param_named(vlb_clock, ide_vlb_clk, int, 0);
MODULE_PARM_DESC(vlb_clock, "VLB clock frequency (in MHz)");
int ide_pci_clk;
EXPORT_SYMBOL_GPL(ide_pci_clk);
module_param_named(pci_clock, ide_pci_clk, int, 0);
MODULE_PARM_DESC(pci_clock, "PCI bus clock frequency (in MHz)");
static int ide_set_dev_param_mask(const char *s, const struct kernel_param *kp)
{
int a, b, i, j = 1;
unsigned int *dev_param_mask = (unsigned int *)kp->arg;
/* controller . device (0 or 1) [ : 1 (set) | 0 (clear) ] */
if (sscanf(s, "%d.%d:%d", &a, &b, &j) != 3 &&
sscanf(s, "%d.%d", &a, &b) != 2)
return -EINVAL;
i = a * MAX_DRIVES + b;
if (i >= MAX_HWIFS * MAX_DRIVES || j < 0 || j > 1)
return -EINVAL;
if (j)
*dev_param_mask |= (1 << i);
else
*dev_param_mask &= ~(1 << i);
return 0;
}
static struct kernel_param_ops param_ops_ide_dev_mask = {
.set = ide_set_dev_param_mask
};
#define param_check_ide_dev_mask(name, p) param_check_uint(name, p)
static unsigned int ide_nodma;
module_param_named(nodma, ide_nodma, ide_dev_mask, 0);
MODULE_PARM_DESC(nodma, "disallow DMA for a device");
static unsigned int ide_noflush;
module_param_named(noflush, ide_noflush, ide_dev_mask, 0);
MODULE_PARM_DESC(noflush, "disable flush requests for a device");
static unsigned int ide_nohpa;
module_param_named(nohpa, ide_nohpa, ide_dev_mask, 0);
MODULE_PARM_DESC(nohpa, "disable Host Protected Area for a device");
static unsigned int ide_noprobe;
module_param_named(noprobe, ide_noprobe, ide_dev_mask, 0);
MODULE_PARM_DESC(noprobe, "skip probing for a device");
static unsigned int ide_nowerr;
module_param_named(nowerr, ide_nowerr, ide_dev_mask, 0);
MODULE_PARM_DESC(nowerr, "ignore the ATA_DF bit for a device");
static unsigned int ide_cdroms;
module_param_named(cdrom, ide_cdroms, ide_dev_mask, 0);
MODULE_PARM_DESC(cdrom, "force device as a CD-ROM");
struct chs_geom {
unsigned int cyl;
u8 head;
u8 sect;
};
static unsigned int ide_disks;
static struct chs_geom ide_disks_chs[MAX_HWIFS * MAX_DRIVES];
static int ide_set_disk_chs(const char *str, struct kernel_param *kp)
{
int a, b, c = 0, h = 0, s = 0, i, j = 1;
/* controller . device (0 or 1) : Cylinders , Heads , Sectors */
/* controller . device (0 or 1) : 1 (use CHS) | 0 (ignore CHS) */
if (sscanf(str, "%d.%d:%d,%d,%d", &a, &b, &c, &h, &s) != 5 &&
sscanf(str, "%d.%d:%d", &a, &b, &j) != 3)
return -EINVAL;
i = a * MAX_DRIVES + b;
if (i >= MAX_HWIFS * MAX_DRIVES || j < 0 || j > 1)
return -EINVAL;
if (c > INT_MAX || h > 255 || s > 255)
return -EINVAL;
if (j)
ide_disks |= (1 << i);
else
ide_disks &= ~(1 << i);
ide_disks_chs[i].cyl = c;
ide_disks_chs[i].head = h;
ide_disks_chs[i].sect = s;
return 0;
}
module_param_call(chs, ide_set_disk_chs, NULL, NULL, 0);
MODULE_PARM_DESC(chs, "force device as a disk (using CHS)");
static void ide_dev_apply_params(ide_drive_t *drive, u8 unit)
{
int i = drive->hwif->index * MAX_DRIVES + unit;
if (ide_nodma & (1 << i)) {
printk(KERN_INFO "ide: disallowing DMA for %s\n", drive->name);
drive->dev_flags |= IDE_DFLAG_NODMA;
}
if (ide_noflush & (1 << i)) {
printk(KERN_INFO "ide: disabling flush requests for %s\n",
drive->name);
drive->dev_flags |= IDE_DFLAG_NOFLUSH;
}
if (ide_nohpa & (1 << i)) {
printk(KERN_INFO "ide: disabling Host Protected Area for %s\n",
drive->name);
drive->dev_flags |= IDE_DFLAG_NOHPA;
}
if (ide_noprobe & (1 << i)) {
printk(KERN_INFO "ide: skipping probe for %s\n", drive->name);
drive->dev_flags |= IDE_DFLAG_NOPROBE;
}
if (ide_nowerr & (1 << i)) {
printk(KERN_INFO "ide: ignoring the ATA_DF bit for %s\n",
drive->name);
drive->bad_wstat = BAD_R_STAT;
}
if (ide_cdroms & (1 << i)) {
printk(KERN_INFO "ide: forcing %s as a CD-ROM\n", drive->name);
drive->dev_flags |= IDE_DFLAG_PRESENT;
drive->media = ide_cdrom;
/* an ATAPI device ignores DRDY */
drive->ready_stat = 0;
}
if (ide_disks & (1 << i)) {
drive->cyl = drive->bios_cyl = ide_disks_chs[i].cyl;
drive->head = drive->bios_head = ide_disks_chs[i].head;
drive->sect = drive->bios_sect = ide_disks_chs[i].sect;
printk(KERN_INFO "ide: forcing %s as a disk (%d/%d/%d)\n",
drive->name,
drive->cyl, drive->head, drive->sect);
drive->dev_flags |= IDE_DFLAG_FORCED_GEOM | IDE_DFLAG_PRESENT;
drive->media = ide_disk;
drive->ready_stat = ATA_DRDY;
}
}
static unsigned int ide_ignore_cable;
static int ide_set_ignore_cable(const char *s, struct kernel_param *kp)
{
int i, j = 1;
/* controller (ignore) */
/* controller : 1 (ignore) | 0 (use) */
if (sscanf(s, "%d:%d", &i, &j) != 2 && sscanf(s, "%d", &i) != 1)
return -EINVAL;
if (i >= MAX_HWIFS || j < 0 || j > 1)
return -EINVAL;
if (j)
ide_ignore_cable |= (1 << i);
else
ide_ignore_cable &= ~(1 << i);
return 0;
}
module_param_call(ignore_cable, ide_set_ignore_cable, NULL, NULL, 0);
MODULE_PARM_DESC(ignore_cable, "ignore cable detection");
void ide_port_apply_params(ide_hwif_t *hwif)
{
ide_drive_t *drive;
int i;
if (ide_ignore_cable & (1 << hwif->index)) {
printk(KERN_INFO "ide: ignoring cable detection for %s\n",
hwif->name);
hwif->cbl = ATA_CBL_PATA40_SHORT;
}
ide_port_for_each_dev(i, drive, hwif)
ide_dev_apply_params(drive, i);
}
/*
* This is gets invoked once during initialization, to set *everything* up
*/
static int __init ide_init(void)
{
int ret;
printk(KERN_INFO "Uniform Multi-Platform E-IDE driver\n");
ret = bus_register(&ide_bus_type);
if (ret < 0) {
printk(KERN_WARNING "IDE: bus_register error: %d\n", ret);
return ret;
}
ide_port_class = class_create(THIS_MODULE, "ide_port");
if (IS_ERR(ide_port_class)) {
ret = PTR_ERR(ide_port_class);
goto out_port_class;
}
ide_acpi_init();
proc_ide_create();
return 0;
out_port_class:
bus_unregister(&ide_bus_type);
return ret;
}
static void __exit ide_exit(void)
{
proc_ide_destroy();
class_destroy(ide_port_class);
bus_unregister(&ide_bus_type);
}
module_init(ide_init);
module_exit(ide_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
GAXUSXX/GalaxyS7edge_G935F_Kernel | drivers/gpu/arm/t8xx/r7p0/mali_kbase_mem_linux.c | 96 | 53269 | /*
*
* (C) COPYRIGHT 2010-2015 ARM Limited. All rights reserved.
*
* This program is free software and is provided to you under the terms of the
* GNU General Public License version 2 as published by the Free Software
* Foundation, and any use by you of this program is subject to the terms
* of such GNU licence.
*
* A copy of the licence is included with the program, and can also be obtained
* from Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
/**
* @file mali_kbase_mem_linux.c
* Base kernel memory APIs, Linux implementation.
*/
#include <linux/compat.h>
#include <linux/kernel.h>
#include <linux/bug.h>
#include <linux/mm.h>
#include <linux/fs.h>
#include <linux/version.h>
#include <linux/dma-mapping.h>
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(3, 5, 0))
#include <linux/dma-attrs.h>
#endif
#ifdef CONFIG_DMA_SHARED_BUFFER
#include <linux/dma-buf.h>
#endif /* defined(CONFIG_DMA_SHARED_BUFFER) */
#include <mali_kbase.h>
#include <mali_kbase_mem_linux.h>
#include <mali_kbase_config_defaults.h>
#include <mali_kbase_hwaccess_time.h>
static int kbase_tracking_page_setup(struct kbase_context *kctx, struct vm_area_struct *vma);
static const struct vm_operations_struct kbase_vm_ops;
struct kbase_va_region *kbase_mem_alloc(struct kbase_context *kctx, u64 va_pages, u64 commit_pages, u64 extent, u64 *flags, u64 *gpu_va, u16 *va_alignment)
{
int zone;
int gpu_pc_bits;
int cpu_va_bits;
struct kbase_va_region *reg;
struct device *dev;
KBASE_DEBUG_ASSERT(kctx);
KBASE_DEBUG_ASSERT(flags);
KBASE_DEBUG_ASSERT(gpu_va);
KBASE_DEBUG_ASSERT(va_alignment);
dev = kctx->kbdev->dev;
*va_alignment = 0; /* no alignment by default */
*gpu_va = 0; /* return 0 on failure */
gpu_pc_bits = kctx->kbdev->gpu_props.props.core_props.log2_program_counter_size;
cpu_va_bits = BITS_PER_LONG;
if (0 == va_pages) {
dev_warn(dev, "kbase_mem_alloc called with 0 va_pages!");
goto bad_size;
}
if (va_pages > (U64_MAX / PAGE_SIZE))
/* 64-bit address range is the max */
goto bad_size;
#if defined(CONFIG_64BIT)
if (kctx->is_compat)
cpu_va_bits = 32;
else
/* force SAME_VA if a 64-bit client */
*flags |= BASE_MEM_SAME_VA;
#endif
if (!kbase_check_alloc_flags(*flags)) {
dev_warn(dev,
"kbase_mem_alloc called with bad flags (%llx)",
(unsigned long long)*flags);
goto bad_flags;
}
if ((*flags & BASE_MEM_COHERENT_SYSTEM_REQUIRED) != 0 &&
kctx->kbdev->system_coherency != COHERENCY_ACE) {
dev_warn(dev, "kbase_mem_alloc call required coherent mem when unavailable");
goto bad_flags;
}
if ((*flags & BASE_MEM_COHERENT_SYSTEM) != 0 &&
kctx->kbdev->system_coherency != COHERENCY_ACE) {
/* Remove COHERENT_SYSTEM flag if coherent mem is unavailable */
*flags &= ~BASE_MEM_COHERENT_SYSTEM;
}
/* Limit GPU executable allocs to GPU PC size */
if ((*flags & BASE_MEM_PROT_GPU_EX) &&
(va_pages > (1ULL << gpu_pc_bits >> PAGE_SHIFT)))
goto bad_ex_size;
/* find out which VA zone to use */
if (*flags & BASE_MEM_SAME_VA)
zone = KBASE_REG_ZONE_SAME_VA;
else if (*flags & BASE_MEM_PROT_GPU_EX)
zone = KBASE_REG_ZONE_EXEC;
else
zone = KBASE_REG_ZONE_CUSTOM_VA;
reg = kbase_alloc_free_region(kctx, 0, va_pages, zone);
if (!reg) {
dev_err(dev, "Failed to allocate free region");
goto no_region;
}
kbase_update_region_flags(kctx, reg, *flags);
if (kbase_reg_prepare_native(reg, kctx) != 0) {
dev_err(dev, "Failed to prepare region");
goto prepare_failed;
}
if (*flags & BASE_MEM_GROW_ON_GPF)
reg->extent = extent;
else
reg->extent = 0;
if (kbase_alloc_phy_pages(reg, va_pages, commit_pages) != 0) {
dev_warn(dev, "Failed to allocate %lld pages (va_pages=%lld)",
(unsigned long long)commit_pages,
(unsigned long long)va_pages);
goto no_mem;
}
kbase_gpu_vm_lock(kctx);
/* mmap needed to setup VA? */
if (*flags & BASE_MEM_SAME_VA) {
/* Bind to a cookie */
if (!kctx->cookies) {
dev_err(dev, "No cookies available for allocation!");
goto no_cookie;
}
/* return a cookie */
*gpu_va = __ffs(kctx->cookies);
kctx->cookies &= ~(1UL << *gpu_va);
BUG_ON(kctx->pending_regions[*gpu_va]);
kctx->pending_regions[*gpu_va] = reg;
/* relocate to correct base */
*gpu_va += PFN_DOWN(BASE_MEM_COOKIE_BASE);
*gpu_va <<= PAGE_SHIFT;
/* See if we must align memory due to GPU PC bits vs CPU VA */
if ((*flags & BASE_MEM_PROT_GPU_EX) &&
(cpu_va_bits > gpu_pc_bits)) {
*va_alignment = gpu_pc_bits;
reg->flags |= KBASE_REG_ALIGNED;
}
} else /* we control the VA */ {
if (kbase_gpu_mmap(kctx, reg, 0, va_pages, 1) != 0) {
dev_warn(dev, "Failed to map memory on GPU");
goto no_mmap;
}
/* return real GPU VA */
*gpu_va = reg->start_pfn << PAGE_SHIFT;
}
kbase_gpu_vm_unlock(kctx);
return reg;
no_mmap:
no_cookie:
kbase_gpu_vm_unlock(kctx);
no_mem:
kbase_mem_phy_alloc_put(reg->cpu_alloc);
kbase_mem_phy_alloc_put(reg->gpu_alloc);
prepare_failed:
kfree(reg);
no_region:
bad_ex_size:
bad_flags:
bad_size:
return NULL;
}
KBASE_EXPORT_TEST_API(kbase_mem_alloc);
int kbase_mem_query(struct kbase_context *kctx, u64 gpu_addr, int query, u64 * const out)
{
struct kbase_va_region *reg;
int ret = -EINVAL;
KBASE_DEBUG_ASSERT(kctx);
KBASE_DEBUG_ASSERT(out);
kbase_gpu_vm_lock(kctx);
/* Validate the region */
reg = kbase_region_tracker_find_region_base_address(kctx, gpu_addr);
if (!reg || (reg->flags & KBASE_REG_FREE))
goto out_unlock;
switch (query) {
case KBASE_MEM_QUERY_COMMIT_SIZE:
if (reg->cpu_alloc->type != KBASE_MEM_TYPE_ALIAS) {
*out = kbase_reg_current_backed_size(reg);
} else {
size_t i;
struct kbase_aliased *aliased;
*out = 0;
aliased = reg->cpu_alloc->imported.alias.aliased;
for (i = 0; i < reg->cpu_alloc->imported.alias.nents; i++)
*out += aliased[i].length;
}
break;
case KBASE_MEM_QUERY_VA_SIZE:
*out = reg->nr_pages;
break;
case KBASE_MEM_QUERY_FLAGS:
{
*out = 0;
if (KBASE_REG_CPU_WR & reg->flags)
*out |= BASE_MEM_PROT_CPU_WR;
if (KBASE_REG_CPU_RD & reg->flags)
*out |= BASE_MEM_PROT_CPU_RD;
if (KBASE_REG_CPU_CACHED & reg->flags)
*out |= BASE_MEM_CACHED_CPU;
if (KBASE_REG_GPU_WR & reg->flags)
*out |= BASE_MEM_PROT_GPU_WR;
if (KBASE_REG_GPU_RD & reg->flags)
*out |= BASE_MEM_PROT_GPU_RD;
if (!(KBASE_REG_GPU_NX & reg->flags))
*out |= BASE_MEM_PROT_GPU_EX;
if (KBASE_REG_SHARE_BOTH & reg->flags)
*out |= BASE_MEM_COHERENT_SYSTEM;
if (KBASE_REG_SHARE_IN & reg->flags)
*out |= BASE_MEM_COHERENT_LOCAL;
break;
}
default:
*out = 0;
goto out_unlock;
}
ret = 0;
out_unlock:
kbase_gpu_vm_unlock(kctx);
return ret;
}
int kbase_mem_flags_change(struct kbase_context *kctx, u64 gpu_addr, unsigned int flags, unsigned int mask)
{
struct kbase_va_region *reg;
int ret = -EINVAL;
unsigned int real_flags = 0;
unsigned int prev_flags = 0;
KBASE_DEBUG_ASSERT(kctx);
if (!gpu_addr)
return -EINVAL;
/* nuke other bits */
flags &= mask;
/* check for only supported flags */
if (flags & ~(BASE_MEM_COHERENT_SYSTEM | BASE_MEM_COHERENT_LOCAL))
goto out;
/* mask covers bits we don't support? */
if (mask & ~(BASE_MEM_COHERENT_SYSTEM | BASE_MEM_COHERENT_LOCAL))
goto out;
/* convert flags */
if (BASE_MEM_COHERENT_SYSTEM & flags)
real_flags |= KBASE_REG_SHARE_BOTH;
else if (BASE_MEM_COHERENT_LOCAL & flags)
real_flags |= KBASE_REG_SHARE_IN;
/* now we can lock down the context, and find the region */
kbase_gpu_vm_lock(kctx);
/* Validate the region */
reg = kbase_region_tracker_find_region_base_address(kctx, gpu_addr);
if (!reg || (reg->flags & KBASE_REG_FREE))
goto out_unlock;
/* limit to imported memory */
if ((reg->gpu_alloc->type != KBASE_MEM_TYPE_IMPORTED_UMP) &&
(reg->gpu_alloc->type != KBASE_MEM_TYPE_IMPORTED_UMM))
goto out_unlock;
/* no change? */
if (real_flags == (reg->flags & (KBASE_REG_SHARE_IN | KBASE_REG_SHARE_BOTH))) {
ret = 0;
goto out_unlock;
}
/* save for roll back */
prev_flags = reg->flags;
reg->flags &= ~(KBASE_REG_SHARE_IN | KBASE_REG_SHARE_BOTH);
reg->flags |= real_flags;
/* Currently supporting only imported memory */
switch (reg->gpu_alloc->type) {
#ifdef CONFIG_UMP
case KBASE_MEM_TYPE_IMPORTED_UMP:
ret = kbase_mmu_update_pages(kctx, reg->start_pfn, kbase_get_cpu_phy_pages(reg), reg->gpu_alloc->nents, reg->flags);
break;
#endif
#ifdef CONFIG_DMA_SHARED_BUFFER
case KBASE_MEM_TYPE_IMPORTED_UMM:
/* Future use will use the new flags, existing mapping will NOT be updated
* as memory should not be in use by the GPU when updating the flags.
*/
ret = 0;
WARN_ON(reg->gpu_alloc->imported.umm.current_mapping_usage_count);
break;
#endif
default:
break;
}
/* roll back on error, i.e. not UMP */
if (ret)
reg->flags = prev_flags;
out_unlock:
kbase_gpu_vm_unlock(kctx);
out:
return ret;
}
#define KBASE_MEM_IMPORT_HAVE_PAGES (1UL << BASE_MEM_FLAGS_NR_BITS)
#ifdef CONFIG_UMP
static struct kbase_va_region *kbase_mem_from_ump(struct kbase_context *kctx, ump_secure_id id, u64 *va_pages, u64 *flags)
{
struct kbase_va_region *reg;
ump_dd_handle umph;
u64 block_count;
const ump_dd_physical_block_64 *block_array;
u64 i, j;
int page = 0;
ump_alloc_flags ump_flags;
ump_alloc_flags cpu_flags;
ump_alloc_flags gpu_flags;
KBASE_DEBUG_ASSERT(kctx);
KBASE_DEBUG_ASSERT(va_pages);
KBASE_DEBUG_ASSERT(flags);
if (*flags & BASE_MEM_SECURE)
goto bad_flags;
umph = ump_dd_from_secure_id(id);
if (UMP_DD_INVALID_MEMORY_HANDLE == umph)
goto bad_id;
ump_flags = ump_dd_allocation_flags_get(umph);
cpu_flags = (ump_flags >> UMP_DEVICE_CPU_SHIFT) & UMP_DEVICE_MASK;
gpu_flags = (ump_flags >> DEFAULT_UMP_GPU_DEVICE_SHIFT) &
UMP_DEVICE_MASK;
*va_pages = ump_dd_size_get_64(umph);
*va_pages >>= PAGE_SHIFT;
if (!*va_pages)
goto bad_size;
if (*va_pages > (U64_MAX / PAGE_SIZE))
/* 64-bit address range is the max */
goto bad_size;
if (*flags & BASE_MEM_SAME_VA)
reg = kbase_alloc_free_region(kctx, 0, *va_pages, KBASE_REG_ZONE_SAME_VA);
else
reg = kbase_alloc_free_region(kctx, 0, *va_pages, KBASE_REG_ZONE_CUSTOM_VA);
if (!reg)
goto no_region;
/* we've got pages to map now, and support SAME_VA */
*flags |= KBASE_MEM_IMPORT_HAVE_PAGES;
reg->gpu_alloc = kbase_alloc_create(*va_pages, KBASE_MEM_TYPE_IMPORTED_UMP);
if (IS_ERR_OR_NULL(reg->gpu_alloc))
goto no_alloc_obj;
reg->cpu_alloc = kbase_mem_phy_alloc_get(reg->gpu_alloc);
reg->gpu_alloc->imported.ump_handle = umph;
reg->flags &= ~KBASE_REG_FREE;
reg->flags |= KBASE_REG_GPU_NX; /* UMP is always No eXecute */
reg->flags &= ~KBASE_REG_GROWABLE; /* UMP cannot be grown */
/* Override import flags based on UMP flags */
*flags &= ~(BASE_MEM_CACHED_CPU);
*flags &= ~(BASE_MEM_PROT_CPU_RD | BASE_MEM_PROT_CPU_WR);
*flags &= ~(BASE_MEM_PROT_GPU_RD | BASE_MEM_PROT_GPU_WR);
if ((cpu_flags & (UMP_HINT_DEVICE_RD | UMP_HINT_DEVICE_WR)) ==
(UMP_HINT_DEVICE_RD | UMP_HINT_DEVICE_WR)) {
reg->flags |= KBASE_REG_CPU_CACHED;
*flags |= BASE_MEM_CACHED_CPU;
}
if (cpu_flags & UMP_PROT_CPU_WR) {
reg->flags |= KBASE_REG_CPU_WR;
*flags |= BASE_MEM_PROT_CPU_WR;
}
if (cpu_flags & UMP_PROT_CPU_RD) {
reg->flags |= KBASE_REG_CPU_RD;
*flags |= BASE_MEM_PROT_CPU_RD;
}
if ((gpu_flags & (UMP_HINT_DEVICE_RD | UMP_HINT_DEVICE_WR)) ==
(UMP_HINT_DEVICE_RD | UMP_HINT_DEVICE_WR))
reg->flags |= KBASE_REG_GPU_CACHED;
if (gpu_flags & UMP_PROT_DEVICE_WR) {
reg->flags |= KBASE_REG_GPU_WR;
*flags |= BASE_MEM_PROT_GPU_WR;
}
if (gpu_flags & UMP_PROT_DEVICE_RD) {
reg->flags |= KBASE_REG_GPU_RD;
*flags |= BASE_MEM_PROT_GPU_RD;
}
/* ump phys block query */
ump_dd_phys_blocks_get_64(umph, &block_count, &block_array);
for (i = 0; i < block_count; i++) {
for (j = 0; j < (block_array[i].size >> PAGE_SHIFT); j++) {
reg->gpu_alloc->pages[page] = block_array[i].addr + (j << PAGE_SHIFT);
page++;
}
}
reg->gpu_alloc->nents = *va_pages;
reg->extent = 0;
return reg;
no_alloc_obj:
kfree(reg);
no_region:
bad_size:
ump_dd_release(umph);
bad_id:
bad_flags:
return NULL;
}
#endif /* CONFIG_UMP */
#ifdef CONFIG_DMA_SHARED_BUFFER
static struct kbase_va_region *kbase_mem_from_umm(struct kbase_context *kctx, int fd, u64 *va_pages, u64 *flags)
{
struct kbase_va_region *reg;
struct dma_buf *dma_buf;
struct dma_buf_attachment *dma_attachment;
dma_buf = dma_buf_get(fd);
if (IS_ERR_OR_NULL(dma_buf))
goto no_buf;
dma_attachment = dma_buf_attach(dma_buf, kctx->kbdev->dev);
if (!dma_attachment)
goto no_attachment;
*va_pages = PAGE_ALIGN(dma_buf->size) >> PAGE_SHIFT;
if (!*va_pages)
goto bad_size;
if (*va_pages > (U64_MAX / PAGE_SIZE))
/* 64-bit address range is the max */
goto bad_size;
/* ignore SAME_VA */
*flags &= ~BASE_MEM_SAME_VA;
#ifdef CONFIG_64BIT
if (!kctx->is_compat) {
/* 64-bit tasks must MMAP anyway, but not expose this address to clients */
*flags |= BASE_MEM_NEED_MMAP;
reg = kbase_alloc_free_region(kctx, 0, *va_pages, KBASE_REG_ZONE_SAME_VA);
} else {
#else
if (1) {
#endif
reg = kbase_alloc_free_region(kctx, 0, *va_pages, KBASE_REG_ZONE_CUSTOM_VA);
}
if (!reg)
goto no_region;
reg->gpu_alloc = kbase_alloc_create(*va_pages, KBASE_MEM_TYPE_IMPORTED_UMM);
if (IS_ERR_OR_NULL(reg->gpu_alloc))
goto no_alloc_obj;
/* MALI_SEC_SECURE_RENDERING */
reg->phys_by_ion = 0;
reg->len_by_ion = 0;
reg->cpu_alloc = kbase_mem_phy_alloc_get(reg->gpu_alloc);
/* No pages to map yet */
reg->gpu_alloc->nents = 0;
reg->flags &= ~KBASE_REG_FREE;
reg->flags |= KBASE_REG_GPU_NX; /* UMM is always No eXecute */
reg->flags &= ~KBASE_REG_GROWABLE; /* UMM cannot be grown */
reg->flags |= KBASE_REG_GPU_CACHED;
if (*flags & BASE_MEM_PROT_CPU_WR)
reg->flags |= KBASE_REG_CPU_WR;
if (*flags & BASE_MEM_PROT_CPU_RD)
reg->flags |= KBASE_REG_CPU_RD;
if (*flags & BASE_MEM_PROT_GPU_WR)
reg->flags |= KBASE_REG_GPU_WR;
if (*flags & BASE_MEM_PROT_GPU_RD)
reg->flags |= KBASE_REG_GPU_RD;
if (*flags & BASE_MEM_SECURE) {
/* MALI_SEC_SECURE_RENDERING */
if (kctx->kbdev->secure_mode_support == true &&
kctx->kbdev->secure_ops != NULL) {
int err = -EINVAL;
err = kctx->kbdev->secure_ops->secure_mem_enable(kctx->kbdev, fd, *flags, reg);
if (err)
dev_warn(kctx->kbdev->dev, "Failed to enable secure memory : 0x%08x\n", err);
} else {
dev_warn(kctx->kbdev->dev, "%s: wrong operation! DDK cannot support Secure Rendering\n", __func__);
}
}
/* no read or write permission given on import, only on run do we give the right permissions */
reg->gpu_alloc->type = BASE_MEM_IMPORT_TYPE_UMM;
reg->gpu_alloc->imported.umm.sgt = NULL;
reg->gpu_alloc->imported.umm.dma_buf = dma_buf;
reg->gpu_alloc->imported.umm.dma_attachment = dma_attachment;
reg->gpu_alloc->imported.umm.current_mapping_usage_count = 0;
reg->extent = 0;
return reg;
no_alloc_obj:
kfree(reg);
no_region:
bad_size:
dma_buf_detach(dma_buf, dma_attachment);
no_attachment:
dma_buf_put(dma_buf);
no_buf:
return NULL;
}
#endif /* CONFIG_DMA_SHARED_BUFFER */
u64 kbase_mem_alias(struct kbase_context *kctx, u64 *flags, u64 stride,
u64 nents, struct base_mem_aliasing_info *ai,
u64 *num_pages)
{
struct kbase_va_region *reg;
u64 gpu_va;
size_t i;
bool coherent;
KBASE_DEBUG_ASSERT(kctx);
KBASE_DEBUG_ASSERT(flags);
KBASE_DEBUG_ASSERT(ai);
KBASE_DEBUG_ASSERT(num_pages);
/* mask to only allowed flags */
*flags &= (BASE_MEM_PROT_GPU_RD | BASE_MEM_PROT_GPU_WR |
BASE_MEM_COHERENT_SYSTEM | BASE_MEM_COHERENT_LOCAL |
BASE_MEM_COHERENT_SYSTEM_REQUIRED);
if (!(*flags & (BASE_MEM_PROT_GPU_RD | BASE_MEM_PROT_GPU_WR))) {
dev_warn(kctx->kbdev->dev,
"kbase_mem_alias called with bad flags (%llx)",
(unsigned long long)*flags);
goto bad_flags;
}
coherent = (*flags & BASE_MEM_COHERENT_SYSTEM) != 0 ||
(*flags & BASE_MEM_COHERENT_SYSTEM_REQUIRED) != 0;
if (!stride)
goto bad_stride;
if (!nents)
goto bad_nents;
if ((nents * stride) > (U64_MAX / PAGE_SIZE))
/* 64-bit address range is the max */
goto bad_size;
/* calculate the number of pages this alias will cover */
*num_pages = nents * stride;
#ifdef CONFIG_64BIT
if (!kctx->is_compat) {
/* 64-bit tasks must MMAP anyway, but not expose this address to
* clients */
*flags |= BASE_MEM_NEED_MMAP;
reg = kbase_alloc_free_region(kctx, 0, *num_pages,
KBASE_REG_ZONE_SAME_VA);
} else {
#else
if (1) {
#endif
reg = kbase_alloc_free_region(kctx, 0, *num_pages,
KBASE_REG_ZONE_CUSTOM_VA);
}
if (!reg)
goto no_reg;
/* zero-sized page array, as we don't need one/can support one */
reg->gpu_alloc = kbase_alloc_create(0, KBASE_MEM_TYPE_ALIAS);
if (IS_ERR_OR_NULL(reg->gpu_alloc))
goto no_alloc_obj;
reg->cpu_alloc = kbase_mem_phy_alloc_get(reg->gpu_alloc);
kbase_update_region_flags(kctx, reg, *flags);
reg->gpu_alloc->imported.alias.nents = nents;
reg->gpu_alloc->imported.alias.stride = stride;
reg->gpu_alloc->imported.alias.aliased = vzalloc(sizeof(*reg->gpu_alloc->imported.alias.aliased) * nents);
if (!reg->gpu_alloc->imported.alias.aliased)
goto no_aliased_array;
kbase_gpu_vm_lock(kctx);
/* validate and add src handles */
for (i = 0; i < nents; i++) {
if (ai[i].handle < BASE_MEM_FIRST_FREE_ADDRESS) {
if (ai[i].handle != BASE_MEM_WRITE_ALLOC_PAGES_HANDLE)
goto bad_handle; /* unsupported magic handle */
if (!ai[i].length)
goto bad_handle; /* must be > 0 */
if (ai[i].length > stride)
goto bad_handle; /* can't be larger than the
stride */
reg->gpu_alloc->imported.alias.aliased[i].length = ai[i].length;
} else {
struct kbase_va_region *aliasing_reg;
struct kbase_mem_phy_alloc *alloc;
aliasing_reg = kbase_region_tracker_find_region_base_address(kctx, (ai[i].handle >> PAGE_SHIFT) << PAGE_SHIFT);
/* validate found region */
if (!aliasing_reg)
goto bad_handle; /* Not found */
if (aliasing_reg->flags & KBASE_REG_FREE)
goto bad_handle; /* Free region */
if (!aliasing_reg->gpu_alloc)
goto bad_handle; /* No alloc */
if (aliasing_reg->gpu_alloc->type != KBASE_MEM_TYPE_NATIVE)
goto bad_handle; /* Not a native alloc */
if (coherent != ((aliasing_reg->flags & KBASE_REG_SHARE_BOTH) != 0))
goto bad_handle;
/* Non-coherent memory cannot alias
coherent memory, and vice versa.*/
/* check size against stride */
if (!ai[i].length)
goto bad_handle; /* must be > 0 */
if (ai[i].length > stride)
goto bad_handle; /* can't be larger than the
stride */
alloc = aliasing_reg->gpu_alloc;
/* check against the alloc's size */
if (ai[i].offset > alloc->nents)
goto bad_handle; /* beyond end */
if (ai[i].offset + ai[i].length > alloc->nents)
goto bad_handle; /* beyond end */
reg->gpu_alloc->imported.alias.aliased[i].alloc = kbase_mem_phy_alloc_get(alloc);
reg->gpu_alloc->imported.alias.aliased[i].length = ai[i].length;
reg->gpu_alloc->imported.alias.aliased[i].offset = ai[i].offset;
}
}
#ifdef CONFIG_64BIT
if (!kctx->is_compat) {
/* Bind to a cookie */
if (!kctx->cookies) {
dev_err(kctx->kbdev->dev, "No cookies available for allocation!");
goto no_cookie;
}
/* return a cookie */
gpu_va = __ffs(kctx->cookies);
kctx->cookies &= ~(1UL << gpu_va);
BUG_ON(kctx->pending_regions[gpu_va]);
kctx->pending_regions[gpu_va] = reg;
/* relocate to correct base */
gpu_va += PFN_DOWN(BASE_MEM_COOKIE_BASE);
gpu_va <<= PAGE_SHIFT;
} else /* we control the VA */ {
#else
if (1) {
#endif
if (kbase_gpu_mmap(kctx, reg, 0, *num_pages, 1) != 0) {
dev_warn(kctx->kbdev->dev, "Failed to map memory on GPU");
goto no_mmap;
}
/* return real GPU VA */
gpu_va = reg->start_pfn << PAGE_SHIFT;
}
reg->flags &= ~KBASE_REG_FREE;
reg->flags &= ~KBASE_REG_GROWABLE;
kbase_gpu_vm_unlock(kctx);
return gpu_va;
#ifdef CONFIG_64BIT
no_cookie:
#endif
no_mmap:
bad_handle:
kbase_gpu_vm_unlock(kctx);
no_aliased_array:
kbase_mem_phy_alloc_put(reg->cpu_alloc);
kbase_mem_phy_alloc_put(reg->gpu_alloc);
no_alloc_obj:
kfree(reg);
no_reg:
bad_size:
bad_nents:
bad_stride:
bad_flags:
return 0;
}
int kbase_mem_import(struct kbase_context *kctx, enum base_mem_import_type type, int handle, u64 *gpu_va, u64 *va_pages, u64 *flags)
{
struct kbase_va_region *reg;
KBASE_DEBUG_ASSERT(kctx);
KBASE_DEBUG_ASSERT(gpu_va);
KBASE_DEBUG_ASSERT(va_pages);
KBASE_DEBUG_ASSERT(flags);
#ifdef CONFIG_64BIT
if (!kctx->is_compat)
*flags |= BASE_MEM_SAME_VA;
#endif
if (!kbase_check_import_flags(*flags)) {
dev_warn(kctx->kbdev->dev,
"kbase_mem_import called with bad flags (%llx)",
(unsigned long long)*flags);
goto bad_flags;
}
switch (type) {
#ifdef CONFIG_UMP
case BASE_MEM_IMPORT_TYPE_UMP:
reg = kbase_mem_from_ump(kctx, (ump_secure_id)handle, va_pages, flags);
break;
#endif /* CONFIG_UMP */
#ifdef CONFIG_DMA_SHARED_BUFFER
case BASE_MEM_IMPORT_TYPE_UMM:
reg = kbase_mem_from_umm(kctx, handle, va_pages, flags);
break;
#endif /* CONFIG_DMA_SHARED_BUFFER */
default:
reg = NULL;
break;
}
if (!reg)
goto no_reg;
kbase_gpu_vm_lock(kctx);
/* mmap needed to setup VA? */
if (*flags & (BASE_MEM_SAME_VA | BASE_MEM_NEED_MMAP)) {
/* Bind to a cookie */
if (!kctx->cookies)
goto no_cookie;
/* return a cookie */
*gpu_va = __ffs(kctx->cookies);
kctx->cookies &= ~(1UL << *gpu_va);
BUG_ON(kctx->pending_regions[*gpu_va]);
kctx->pending_regions[*gpu_va] = reg;
/* relocate to correct base */
*gpu_va += PFN_DOWN(BASE_MEM_COOKIE_BASE);
*gpu_va <<= PAGE_SHIFT;
} else if (*flags & KBASE_MEM_IMPORT_HAVE_PAGES) {
/* we control the VA, mmap now to the GPU */
if (kbase_gpu_mmap(kctx, reg, 0, *va_pages, 1) != 0)
goto no_gpu_va;
/* return real GPU VA */
*gpu_va = reg->start_pfn << PAGE_SHIFT;
} else {
/* we control the VA, but nothing to mmap yet */
if (kbase_add_va_region(kctx, reg, 0, *va_pages, 1) != 0)
goto no_gpu_va;
/* return real GPU VA */
*gpu_va = reg->start_pfn << PAGE_SHIFT;
}
/* clear out private flags */
*flags &= ((1UL << BASE_MEM_FLAGS_NR_BITS) - 1);
kbase_gpu_vm_unlock(kctx);
return 0;
no_gpu_va:
no_cookie:
kbase_gpu_vm_unlock(kctx);
kbase_mem_phy_alloc_put(reg->cpu_alloc);
kbase_mem_phy_alloc_put(reg->gpu_alloc);
kfree(reg);
no_reg:
bad_flags:
*gpu_va = 0;
*va_pages = 0;
*flags = 0;
return -ENOMEM;
}
static int zap_range_nolock(struct mm_struct *mm,
const struct vm_operations_struct *vm_ops,
unsigned long start, unsigned long end)
{
struct vm_area_struct *vma;
int err = -EINVAL; /* in case end < start */
while (start < end) {
unsigned long local_end;
vma = find_vma_intersection(mm, start, end);
if (!vma)
break;
/* is it ours? */
if (vma->vm_ops != vm_ops)
goto try_next;
local_end = vma->vm_end;
if (end < local_end)
local_end = end;
/* MALI_SEC_INTEGRATION */
if (start < vma->vm_start) {
start = vma->vm_start;
}
err = zap_vma_ptes(vma, start, local_end - start);
if (unlikely(err))
break;
try_next:
/* go to next vma, if any */
start = vma->vm_end;
}
return err;
}
int kbase_mem_commit(struct kbase_context *kctx, u64 gpu_addr, u64 new_pages, enum base_backing_threshold_status *failure_reason)
{
u64 old_pages;
u64 delta;
int res = -EINVAL;
struct kbase_va_region *reg;
phys_addr_t *phy_pages;
KBASE_DEBUG_ASSERT(kctx);
KBASE_DEBUG_ASSERT(failure_reason);
KBASE_DEBUG_ASSERT(gpu_addr != 0);
down_read(¤t->mm->mmap_sem);
kbase_gpu_vm_lock(kctx);
/* Validate the region */
reg = kbase_region_tracker_find_region_base_address(kctx, gpu_addr);
if (!reg || (reg->flags & KBASE_REG_FREE)) {
*failure_reason = BASE_BACKING_THRESHOLD_ERROR_INVALID_ARGUMENTS;
goto out_unlock;
}
KBASE_DEBUG_ASSERT(reg->cpu_alloc);
KBASE_DEBUG_ASSERT(reg->gpu_alloc);
if (reg->gpu_alloc->type != KBASE_MEM_TYPE_NATIVE) {
*failure_reason = BASE_BACKING_THRESHOLD_ERROR_NOT_GROWABLE;
goto out_unlock;
}
if (0 == (reg->flags & KBASE_REG_GROWABLE)) {
*failure_reason = BASE_BACKING_THRESHOLD_ERROR_NOT_GROWABLE;
goto out_unlock;
}
if (new_pages > reg->nr_pages) {
/* Would overflow the VA region */
*failure_reason = BASE_BACKING_THRESHOLD_ERROR_INVALID_ARGUMENTS;
goto out_unlock;
}
/* can't be mapped more than once on the GPU */
if (atomic_read(®->gpu_alloc->gpu_mappings) > 1) {
*failure_reason = BASE_BACKING_THRESHOLD_ERROR_NOT_GROWABLE;
goto out_unlock;
}
if (new_pages == reg->gpu_alloc->nents) {
/* no change */
res = 0;
goto out_unlock;
}
phy_pages = kbase_get_gpu_phy_pages(reg);
old_pages = kbase_reg_current_backed_size(reg);
if (new_pages > old_pages) {
/* growing */
int err;
delta = new_pages - old_pages;
/* Allocate some more pages */
if (kbase_alloc_phy_pages_helper(reg->cpu_alloc, delta) != 0) {
*failure_reason = BASE_BACKING_THRESHOLD_ERROR_OOM;
goto out_unlock;
}
if (reg->cpu_alloc != reg->gpu_alloc) {
if (kbase_alloc_phy_pages_helper(
reg->gpu_alloc, delta) != 0) {
*failure_reason = BASE_BACKING_THRESHOLD_ERROR_OOM;
kbase_free_phy_pages_helper(reg->cpu_alloc,
delta);
goto out_unlock;
}
}
err = kbase_mmu_insert_pages(kctx, reg->start_pfn + old_pages,
phy_pages + old_pages, delta, reg->flags);
if (err) {
kbase_free_phy_pages_helper(reg->cpu_alloc, delta);
if (reg->cpu_alloc != reg->gpu_alloc)
kbase_free_phy_pages_helper(reg->gpu_alloc,
delta);
*failure_reason = BASE_BACKING_THRESHOLD_ERROR_OOM;
goto out_unlock;
}
} else {
/* shrinking */
struct kbase_cpu_mapping *mapping;
int err;
/* first, unmap from any mappings affected */
list_for_each_entry(mapping, ®->cpu_alloc->mappings, mappings_list) {
unsigned long mapping_size = (mapping->vm_end - mapping->vm_start) >> PAGE_SHIFT;
/* is this mapping affected ?*/
if ((mapping->page_off + mapping_size) > new_pages) {
unsigned long first_bad = 0;
int zap_res;
if (new_pages > mapping->page_off)
first_bad = new_pages - mapping->page_off;
zap_res = zap_range_nolock(current->mm,
&kbase_vm_ops,
mapping->vm_start +
(first_bad << PAGE_SHIFT),
mapping->vm_end);
WARN(zap_res,
"Failed to zap VA range (0x%lx - 0x%lx);\n",
mapping->vm_start +
(first_bad << PAGE_SHIFT),
mapping->vm_end
);
}
}
/* Free some pages */
delta = old_pages - new_pages;
err = kbase_mmu_teardown_pages(kctx, reg->start_pfn + new_pages,
delta);
if (err) {
*failure_reason = BASE_BACKING_THRESHOLD_ERROR_OOM;
goto out_unlock;
}
#ifndef CONFIG_MALI_NO_MALI
if (kbase_hw_has_issue(kctx->kbdev, BASE_HW_ISSUE_6367)) {
/* Wait for GPU to flush write buffer before freeing physical pages */
kbase_wait_write_flush(kctx);
}
#endif
kbase_free_phy_pages_helper(reg->cpu_alloc, delta);
if (reg->cpu_alloc != reg->gpu_alloc)
kbase_free_phy_pages_helper(reg->gpu_alloc, delta);
}
res = 0;
out_unlock:
kbase_gpu_vm_unlock(kctx);
up_read(¤t->mm->mmap_sem);
return res;
}
static void kbase_cpu_vm_open(struct vm_area_struct *vma)
{
struct kbase_cpu_mapping *map = vma->vm_private_data;
KBASE_DEBUG_ASSERT(map);
KBASE_DEBUG_ASSERT(map->count > 0);
/* non-atomic as we're under Linux' mm lock */
map->count++;
}
static void kbase_cpu_vm_close(struct vm_area_struct *vma)
{
struct kbase_cpu_mapping *map = vma->vm_private_data;
KBASE_DEBUG_ASSERT(map);
KBASE_DEBUG_ASSERT(map->count > 0);
/* non-atomic as we're under Linux' mm lock */
if (--map->count)
return;
KBASE_DEBUG_ASSERT(map->kctx);
KBASE_DEBUG_ASSERT(map->alloc);
kbase_gpu_vm_lock(map->kctx);
if (map->region) {
KBASE_DEBUG_ASSERT((map->region->flags & KBASE_REG_ZONE_MASK) ==
KBASE_REG_ZONE_SAME_VA);
/* Avoid freeing memory on the process death which results in
* GPU Page Fault. Memory will be freed in kbase_destroy_context
*/
if (!(current->flags & PF_EXITING))
kbase_mem_free_region(map->kctx, map->region);
}
list_del(&map->mappings_list);
kbase_gpu_vm_unlock(map->kctx);
kbase_mem_phy_alloc_put(map->alloc);
kfree(map);
}
KBASE_EXPORT_TEST_API(kbase_cpu_vm_close);
static int kbase_cpu_vm_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
struct kbase_cpu_mapping *map = vma->vm_private_data;
pgoff_t rel_pgoff;
size_t i;
KBASE_DEBUG_ASSERT(map);
KBASE_DEBUG_ASSERT(map->count > 0);
KBASE_DEBUG_ASSERT(map->kctx);
KBASE_DEBUG_ASSERT(map->alloc);
/* we don't use vmf->pgoff as it's affected by our mmap with
* offset being a GPU VA or a cookie */
rel_pgoff = ((unsigned long)vmf->virtual_address - map->vm_start)
>> PAGE_SHIFT;
kbase_gpu_vm_lock(map->kctx);
if (map->page_off + rel_pgoff >= map->alloc->nents)
goto locked_bad_fault;
/* insert all valid pages from the fault location */
for (i = rel_pgoff;
i < MIN((vma->vm_end - vma->vm_start) >> PAGE_SHIFT,
map->alloc->nents - map->page_off); i++) {
int ret = vm_insert_pfn(vma, map->vm_start + (i << PAGE_SHIFT),
PFN_DOWN(map->alloc->pages[map->page_off + i]));
if (ret < 0 && ret != -EBUSY)
goto locked_bad_fault;
}
kbase_gpu_vm_unlock(map->kctx);
/* we resolved it, nothing for VM to do */
return VM_FAULT_NOPAGE;
locked_bad_fault:
kbase_gpu_vm_unlock(map->kctx);
return VM_FAULT_SIGBUS;
}
static const struct vm_operations_struct kbase_vm_ops = {
.open = kbase_cpu_vm_open,
.close = kbase_cpu_vm_close,
.fault = kbase_cpu_vm_fault
};
static int kbase_cpu_mmap(struct kbase_va_region *reg, struct vm_area_struct *vma, void *kaddr, size_t nr_pages, unsigned long aligned_offset, int free_on_close)
{
struct kbase_cpu_mapping *map;
u64 start_off = vma->vm_pgoff - reg->start_pfn;
phys_addr_t *page_array;
int err = 0;
int i;
map = kzalloc(sizeof(*map), GFP_KERNEL);
if (!map) {
WARN_ON(1);
err = -ENOMEM;
goto out;
}
/*
* VM_DONTCOPY - don't make this mapping available in fork'ed processes
* VM_DONTEXPAND - disable mremap on this region
* VM_IO - disables paging
* VM_DONTDUMP - Don't include in core dumps (3.7 only)
* VM_MIXEDMAP - Support mixing struct page*s and raw pfns.
* This is needed to support using the dedicated and
* the OS based memory backends together.
*/
/*
* This will need updating to propagate coherency flags
* See MIDBASE-1057
*/
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(3, 7, 0))
vma->vm_flags |= VM_DONTCOPY | VM_DONTDUMP | VM_DONTEXPAND | VM_IO;
#else
vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_RESERVED | VM_IO;
#endif
vma->vm_ops = &kbase_vm_ops;
vma->vm_private_data = map;
page_array = kbase_get_cpu_phy_pages(reg);
if (!(reg->flags & KBASE_REG_CPU_CACHED) &&
(reg->flags & (KBASE_REG_CPU_WR|KBASE_REG_CPU_RD))) {
/* We can't map vmalloc'd memory uncached.
* Other memory will have been returned from
* kbase_mem_pool which would be
* suitable for mapping uncached.
*/
BUG_ON(kaddr);
vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot);
}
if (!kaddr) {
unsigned long addr = vma->vm_start + aligned_offset;
vma->vm_flags |= VM_PFNMAP;
for (i = 0; i < nr_pages; i++) {
unsigned long pfn = PFN_DOWN(page_array[i + start_off]);
err = vm_insert_pfn(vma, addr, pfn);
if (WARN_ON(err))
break;
addr += PAGE_SIZE;
}
} else {
WARN_ON(aligned_offset);
/* MIXEDMAP so we can vfree the kaddr early and not track it after map time */
vma->vm_flags |= VM_MIXEDMAP;
/* vmalloc remaping is easy... */
err = remap_vmalloc_range(vma, kaddr, 0);
WARN_ON(err);
}
if (err) {
kfree(map);
goto out;
}
map->page_off = start_off;
map->region = free_on_close ? reg : NULL;
map->kctx = reg->kctx;
map->vm_start = vma->vm_start + aligned_offset;
if (aligned_offset) {
KBASE_DEBUG_ASSERT(!start_off);
map->vm_end = map->vm_start + (reg->nr_pages << PAGE_SHIFT);
} else {
map->vm_end = vma->vm_end;
}
map->alloc = kbase_mem_phy_alloc_get(reg->cpu_alloc);
map->count = 1; /* start with one ref */
if (reg->flags & KBASE_REG_CPU_CACHED)
map->alloc->properties |= KBASE_MEM_PHY_ALLOC_ACCESSED_CACHED;
list_add(&map->mappings_list, &map->alloc->mappings);
out:
return err;
}
static int kbase_trace_buffer_mmap(struct kbase_context *kctx, struct vm_area_struct *vma, struct kbase_va_region **const reg, void **const kaddr)
{
struct kbase_va_region *new_reg;
u32 nr_pages;
size_t size;
int err = 0;
u32 *tb;
int owns_tb = 1;
dev_dbg(kctx->kbdev->dev, "in %s\n", __func__);
size = (vma->vm_end - vma->vm_start);
nr_pages = size >> PAGE_SHIFT;
if (!kctx->jctx.tb) {
KBASE_DEBUG_ASSERT(0 != size);
tb = vmalloc_user(size);
if (NULL == tb) {
err = -ENOMEM;
goto out;
}
kbase_device_trace_buffer_install(kctx, tb, size);
} else {
err = -EINVAL;
goto out;
}
*kaddr = kctx->jctx.tb;
new_reg = kbase_alloc_free_region(kctx, 0, nr_pages, KBASE_REG_ZONE_SAME_VA);
if (!new_reg) {
err = -ENOMEM;
WARN_ON(1);
goto out_no_region;
}
new_reg->cpu_alloc = kbase_alloc_create(0, KBASE_MEM_TYPE_TB);
if (IS_ERR_OR_NULL(new_reg->cpu_alloc)) {
err = -ENOMEM;
new_reg->cpu_alloc = NULL;
WARN_ON(1);
goto out_no_alloc;
}
new_reg->gpu_alloc = kbase_mem_phy_alloc_get(new_reg->cpu_alloc);
new_reg->cpu_alloc->imported.kctx = kctx;
new_reg->flags &= ~KBASE_REG_FREE;
new_reg->flags |= KBASE_REG_CPU_CACHED;
/* alloc now owns the tb */
owns_tb = 0;
if (kbase_add_va_region(kctx, new_reg, vma->vm_start, nr_pages, 1) != 0) {
err = -ENOMEM;
WARN_ON(1);
goto out_no_va_region;
}
*reg = new_reg;
/* map read only, noexec */
vma->vm_flags &= ~(VM_WRITE | VM_MAYWRITE | VM_EXEC | VM_MAYEXEC);
/* the rest of the flags is added by the cpu_mmap handler */
dev_dbg(kctx->kbdev->dev, "%s done\n", __func__);
return 0;
out_no_va_region:
out_no_alloc:
kbase_free_alloced_region(new_reg);
out_no_region:
if (owns_tb) {
kbase_device_trace_buffer_uninstall(kctx);
vfree(tb);
}
out:
return err;
}
static int kbase_mmu_dump_mmap(struct kbase_context *kctx, struct vm_area_struct *vma, struct kbase_va_region **const reg, void **const kmap_addr)
{
struct kbase_va_region *new_reg;
void *kaddr;
u32 nr_pages;
size_t size;
int err = 0;
dev_dbg(kctx->kbdev->dev, "in kbase_mmu_dump_mmap\n");
size = (vma->vm_end - vma->vm_start);
nr_pages = size >> PAGE_SHIFT;
kaddr = kbase_mmu_dump(kctx, nr_pages);
if (!kaddr) {
err = -ENOMEM;
goto out;
}
new_reg = kbase_alloc_free_region(kctx, 0, nr_pages, KBASE_REG_ZONE_SAME_VA);
if (!new_reg) {
err = -ENOMEM;
WARN_ON(1);
goto out;
}
new_reg->cpu_alloc = kbase_alloc_create(0, KBASE_MEM_TYPE_RAW);
if (IS_ERR_OR_NULL(new_reg->cpu_alloc)) {
err = -ENOMEM;
new_reg->cpu_alloc = NULL;
WARN_ON(1);
goto out_no_alloc;
}
new_reg->gpu_alloc = kbase_mem_phy_alloc_get(new_reg->cpu_alloc);
new_reg->flags &= ~KBASE_REG_FREE;
new_reg->flags |= KBASE_REG_CPU_CACHED;
if (kbase_add_va_region(kctx, new_reg, vma->vm_start, nr_pages, 1) != 0) {
err = -ENOMEM;
WARN_ON(1);
goto out_va_region;
}
*kmap_addr = kaddr;
*reg = new_reg;
dev_dbg(kctx->kbdev->dev, "kbase_mmu_dump_mmap done\n");
return 0;
out_no_alloc:
out_va_region:
kbase_free_alloced_region(new_reg);
out:
return err;
}
void kbase_os_mem_map_lock(struct kbase_context *kctx)
{
struct mm_struct *mm = current->mm;
(void)kctx;
down_read(&mm->mmap_sem);
}
void kbase_os_mem_map_unlock(struct kbase_context *kctx)
{
struct mm_struct *mm = current->mm;
(void)kctx;
up_read(&mm->mmap_sem);
}
#if defined(CONFIG_DMA_SHARED_BUFFER) && defined(CONFIG_MALI_TRACE_TIMELINE)
/* This section is required only for instrumentation. */
static void kbase_dma_buf_vm_open(struct vm_area_struct *vma)
{
struct kbase_cpu_mapping *map = vma->vm_private_data;
KBASE_DEBUG_ASSERT(map);
KBASE_DEBUG_ASSERT(map->count > 0);
/* Non-atomic as we're under Linux's mm lock. */
map->count++;
}
static void kbase_dma_buf_vm_close(struct vm_area_struct *vma)
{
struct kbase_cpu_mapping *map = vma->vm_private_data;
KBASE_DEBUG_ASSERT(map);
KBASE_DEBUG_ASSERT(map->count > 0);
/* Non-atomic as we're under Linux's mm lock. */
if (--map->count)
return;
KBASE_DEBUG_ASSERT(map->kctx);
kbase_gpu_vm_lock(map->kctx);
list_del(&map->mappings_list);
kbase_gpu_vm_unlock(map->kctx);
kfree(map);
}
static const struct vm_operations_struct kbase_dma_mmap_ops = {
.open = kbase_dma_buf_vm_open,
.close = kbase_dma_buf_vm_close,
};
#endif /* CONFIG_DMA_SHARED_BUFFER && CONFIG_MALI_TRACE_TIMELINE */
int kbase_mmap(struct file *file, struct vm_area_struct *vma)
{
struct kbase_context *kctx = file->private_data;
struct kbase_va_region *reg;
void *kaddr = NULL;
size_t nr_pages;
int err = 0;
int free_on_close = 0;
struct device *dev = kctx->kbdev->dev;
size_t aligned_offset = 0;
dev_dbg(dev, "kbase_mmap\n");
nr_pages = (vma->vm_end - vma->vm_start) >> PAGE_SHIFT;
/* strip away corresponding VM_MAY% flags to the VM_% flags requested */
vma->vm_flags &= ~((vma->vm_flags & (VM_READ | VM_WRITE)) << 4);
if (0 == nr_pages) {
err = -EINVAL;
goto out;
}
if (!(vma->vm_flags & VM_SHARED)) {
err = -EINVAL;
goto out;
}
kbase_gpu_vm_lock(kctx);
if (vma->vm_pgoff == PFN_DOWN(BASE_MEM_MAP_TRACKING_HANDLE)) {
/* The non-mapped tracking helper page */
err = kbase_tracking_page_setup(kctx, vma);
goto out_unlock;
}
/* if not the MTP, verify that the MTP has been mapped */
rcu_read_lock();
/* catches both when the special page isn't present or
* when we've forked */
if (rcu_dereference(kctx->process_mm) != current->mm) {
err = -EINVAL;
rcu_read_unlock();
goto out_unlock;
}
rcu_read_unlock();
switch (vma->vm_pgoff) {
case PFN_DOWN(BASE_MEM_INVALID_HANDLE):
case PFN_DOWN(BASE_MEM_WRITE_ALLOC_PAGES_HANDLE):
/* Illegal handle for direct map */
err = -EINVAL;
goto out_unlock;
case PFN_DOWN(BASE_MEM_TRACE_BUFFER_HANDLE):
err = kbase_trace_buffer_mmap(kctx, vma, ®, &kaddr);
if (0 != err)
goto out_unlock;
dev_dbg(dev, "kbase_trace_buffer_mmap ok\n");
/* free the region on munmap */
free_on_close = 1;
goto map;
case PFN_DOWN(BASE_MEM_MMU_DUMP_HANDLE):
/* MMU dump */
err = kbase_mmu_dump_mmap(kctx, vma, ®, &kaddr);
if (0 != err)
goto out_unlock;
/* free the region on munmap */
free_on_close = 1;
goto map;
case PFN_DOWN(BASE_MEM_COOKIE_BASE) ...
PFN_DOWN(BASE_MEM_FIRST_FREE_ADDRESS) - 1: {
/* SAME_VA stuff, fetch the right region */
int gpu_pc_bits;
int cookie = vma->vm_pgoff - PFN_DOWN(BASE_MEM_COOKIE_BASE);
gpu_pc_bits = kctx->kbdev->gpu_props.props.core_props.log2_program_counter_size;
reg = kctx->pending_regions[cookie];
if (!reg) {
err = -ENOMEM;
goto out_unlock;
}
if (reg->flags & KBASE_REG_ALIGNED) {
/* nr_pages must be able to hold alignment pages
* plus actual pages */
unsigned long align = 1ULL << gpu_pc_bits;
unsigned long extra_pages = 3 * PFN_DOWN(align);
unsigned long aligned_addr;
unsigned long aligned_addr_end;
unsigned long nr_bytes = reg->nr_pages << PAGE_SHIFT;
if (kctx->api_version < KBASE_API_VERSION(8, 5))
/* Maintain compatibility with old userspace */
extra_pages = PFN_DOWN(align);
if (nr_pages != reg->nr_pages + extra_pages) {
/* incorrect mmap size */
/* leave the cookie for a potential
* later mapping, or to be reclaimed
* later when the context is freed */
err = -ENOMEM;
goto out_unlock;
}
aligned_addr = ALIGN(vma->vm_start, align);
aligned_addr_end = aligned_addr + nr_bytes;
if (kctx->api_version >= KBASE_API_VERSION(8, 5)) {
if ((aligned_addr_end & BASE_MEM_MASK_4GB) == 0) {
/* Can't end at 4GB boundary */
aligned_addr += 2 * align;
} else if ((aligned_addr & BASE_MEM_MASK_4GB) == 0) {
/* Can't start at 4GB boundary */
aligned_addr += align;
}
}
aligned_offset = aligned_addr - vma->vm_start;
} else if (reg->nr_pages != nr_pages) {
/* incorrect mmap size */
/* leave the cookie for a potential later
* mapping, or to be reclaimed later when the
* context is freed */
err = -ENOMEM;
goto out_unlock;
}
if ((vma->vm_flags & VM_READ &&
!(reg->flags & KBASE_REG_CPU_RD)) ||
(vma->vm_flags & VM_WRITE &&
!(reg->flags & KBASE_REG_CPU_WR))) {
/* VM flags inconsistent with region flags */
err = -EPERM;
dev_err(dev, "%s:%d inconsistent VM flags\n",
__FILE__, __LINE__);
goto out_unlock;
}
/* adjust down nr_pages to what we have physically */
nr_pages = kbase_reg_current_backed_size(reg);
if (kbase_gpu_mmap(kctx, reg,
vma->vm_start + aligned_offset,
reg->nr_pages, 1) != 0) {
dev_err(dev, "%s:%d\n", __FILE__, __LINE__);
/* Unable to map in GPU space. */
WARN_ON(1);
err = -ENOMEM;
goto out_unlock;
}
/* no need for the cookie anymore */
kctx->pending_regions[cookie] = NULL;
kctx->cookies |= (1UL << cookie);
/*
* Overwrite the offset with the
* region start_pfn, so we effectively
* map from offset 0 in the region.
*/
vma->vm_pgoff = reg->start_pfn;
/* free the region on munmap */
free_on_close = 1;
goto map;
}
default: {
reg = kbase_region_tracker_find_region_enclosing_address(kctx, (u64)vma->vm_pgoff << PAGE_SHIFT);
if (reg && !(reg->flags & KBASE_REG_FREE)) {
/* will this mapping overflow the size of the region? */
if (nr_pages > (reg->nr_pages - (vma->vm_pgoff - reg->start_pfn)))
goto overflow;
if ((vma->vm_flags & VM_READ &&
!(reg->flags & KBASE_REG_CPU_RD)) ||
(vma->vm_flags & VM_WRITE &&
!(reg->flags & KBASE_REG_CPU_WR))) {
/* VM flags inconsistent with region flags */
err = -EPERM;
dev_err(dev, "%s:%d inconsistent VM flags\n",
__FILE__, __LINE__);
goto out_unlock;
}
#ifdef CONFIG_DMA_SHARED_BUFFER
if (reg->cpu_alloc->type == KBASE_MEM_TYPE_IMPORTED_UMM)
goto dma_map;
#endif /* CONFIG_DMA_SHARED_BUFFER */
/* limit what we map to the amount currently backed */
if (reg->cpu_alloc->nents < (vma->vm_pgoff - reg->start_pfn + nr_pages)) {
if ((vma->vm_pgoff - reg->start_pfn) >= reg->cpu_alloc->nents)
nr_pages = 0;
else
nr_pages = reg->cpu_alloc->nents - (vma->vm_pgoff - reg->start_pfn);
}
goto map;
}
overflow:
err = -ENOMEM;
goto out_unlock;
} /* default */
} /* switch */
map:
err = kbase_cpu_mmap(reg, vma, kaddr, nr_pages, aligned_offset, free_on_close);
if (vma->vm_pgoff == PFN_DOWN(BASE_MEM_MMU_DUMP_HANDLE)) {
/* MMU dump - userspace should now have a reference on
* the pages, so we can now free the kernel mapping */
vfree(kaddr);
}
goto out_unlock;
#ifdef CONFIG_DMA_SHARED_BUFFER
dma_map:
err = dma_buf_mmap(reg->cpu_alloc->imported.umm.dma_buf, vma, vma->vm_pgoff - reg->start_pfn);
#if defined(CONFIG_MALI_TRACE_TIMELINE)
/* This section is required only for instrumentation. */
/* Add created mapping to imported region mapping list.
* It is important to make it visible to dumping infrastructure.
* Add mapping only if vm_ops structure is not used by memory owner. */
WARN_ON(vma->vm_ops);
WARN_ON(vma->vm_private_data);
if (!err && !vma->vm_ops && !vma->vm_private_data) {
struct kbase_cpu_mapping *map = kzalloc(
sizeof(*map),
GFP_KERNEL);
if (map) {
map->kctx = reg->kctx;
map->region = NULL;
map->page_off = vma->vm_pgoff;
map->vm_start = vma->vm_start;
map->vm_end = vma->vm_end;
map->count = 1; /* start with one ref */
vma->vm_ops = &kbase_dma_mmap_ops;
vma->vm_private_data = map;
list_add(
&map->mappings_list,
®->cpu_alloc->mappings);
}
}
#endif /* CONFIG_MALI_TRACE_TIMELINE */
#endif /* CONFIG_DMA_SHARED_BUFFER */
out_unlock:
kbase_gpu_vm_unlock(kctx);
out:
if (err)
dev_err(dev, "mmap failed %d\n", err);
return err;
}
KBASE_EXPORT_TEST_API(kbase_mmap);
void *kbase_vmap(struct kbase_context *kctx, u64 gpu_addr, size_t size,
struct kbase_vmap_struct *map)
{
struct kbase_va_region *reg;
unsigned long page_index;
unsigned int offset = gpu_addr & ~PAGE_MASK;
size_t page_count = PFN_UP(offset + size);
phys_addr_t *page_array;
struct page **pages;
void *cpu_addr = NULL;
pgprot_t prot;
size_t i;
bool sync_needed;
if (!size || !map)
return NULL;
/* check if page_count calculation will wrap */
if (size > ((size_t)-1 / PAGE_SIZE))
return NULL;
kbase_gpu_vm_lock(kctx);
reg = kbase_region_tracker_find_region_enclosing_address(kctx, gpu_addr);
if (!reg || (reg->flags & KBASE_REG_FREE))
goto out_unlock;
page_index = (gpu_addr >> PAGE_SHIFT) - reg->start_pfn;
/* check if page_index + page_count will wrap */
if (-1UL - page_count < page_index)
goto out_unlock;
if (page_index + page_count > kbase_reg_current_backed_size(reg))
goto out_unlock;
page_array = kbase_get_cpu_phy_pages(reg);
if (!page_array)
goto out_unlock;
pages = kmalloc_array(page_count, sizeof(struct page *), GFP_KERNEL);
if (!pages)
goto out_unlock;
for (i = 0; i < page_count; i++)
pages[i] = pfn_to_page(PFN_DOWN(page_array[page_index + i]));
prot = PAGE_KERNEL;
if (!(reg->flags & KBASE_REG_CPU_CACHED)) {
/* Map uncached */
prot = pgprot_writecombine(prot);
}
cpu_addr = vmap(pages, page_count, VM_MAP, prot);
kfree(pages);
if (!cpu_addr)
goto out_unlock;
map->gpu_addr = gpu_addr;
map->cpu_alloc = kbase_mem_phy_alloc_get(reg->cpu_alloc);
map->cpu_pages = &kbase_get_cpu_phy_pages(reg)[page_index];
map->gpu_alloc = kbase_mem_phy_alloc_get(reg->gpu_alloc);
map->gpu_pages = &kbase_get_gpu_phy_pages(reg)[page_index];
map->addr = (void *)((uintptr_t)cpu_addr + offset);
map->size = size;
map->is_cached = (reg->flags & KBASE_REG_CPU_CACHED) != 0;
sync_needed = map->is_cached;
if (sync_needed) {
/* Sync first page */
size_t sz = MIN(((size_t) PAGE_SIZE - offset), size);
phys_addr_t cpu_pa = map->cpu_pages[0];
phys_addr_t gpu_pa = map->gpu_pages[0];
kbase_sync_single(kctx, cpu_pa, gpu_pa, offset, sz,
KBASE_SYNC_TO_CPU);
/* Sync middle pages (if any) */
for (i = 1; page_count > 2 && i < page_count - 1; i++) {
cpu_pa = map->cpu_pages[i];
gpu_pa = map->gpu_pages[i];
kbase_sync_single(kctx, cpu_pa, gpu_pa, 0, PAGE_SIZE,
KBASE_SYNC_TO_CPU);
}
/* Sync last page (if any) */
if (page_count > 1) {
cpu_pa = map->cpu_pages[page_count - 1];
gpu_pa = map->gpu_pages[page_count - 1];
sz = ((offset + size - 1) & ~PAGE_MASK) + 1;
kbase_sync_single(kctx, cpu_pa, gpu_pa, 0, sz,
KBASE_SYNC_TO_CPU);
}
}
kbase_gpu_vm_unlock(kctx);
return map->addr;
out_unlock:
kbase_gpu_vm_unlock(kctx);
return NULL;
}
KBASE_EXPORT_TEST_API(kbase_vmap);
void kbase_vunmap(struct kbase_context *kctx, struct kbase_vmap_struct *map)
{
void *addr = (void *)((uintptr_t)map->addr & PAGE_MASK);
bool sync_needed = map->is_cached;
vunmap(addr);
if (sync_needed) {
off_t offset = (uintptr_t)map->addr & ~PAGE_MASK;
size_t size = map->size;
size_t page_count = PFN_UP(offset + size);
size_t i;
/* Sync first page */
size_t sz = MIN(((size_t) PAGE_SIZE - offset), size);
phys_addr_t cpu_pa = map->cpu_pages[0];
phys_addr_t gpu_pa = map->gpu_pages[0];
kbase_sync_single(kctx, cpu_pa, gpu_pa, offset, sz,
KBASE_SYNC_TO_DEVICE);
/* Sync middle pages (if any) */
for (i = 1; page_count > 2 && i < page_count - 1; i++) {
cpu_pa = map->cpu_pages[i];
gpu_pa = map->gpu_pages[i];
kbase_sync_single(kctx, cpu_pa, gpu_pa, 0, PAGE_SIZE,
KBASE_SYNC_TO_DEVICE);
}
/* Sync last page (if any) */
if (page_count > 1) {
cpu_pa = map->cpu_pages[page_count - 1];
gpu_pa = map->gpu_pages[page_count - 1];
sz = ((offset + size - 1) & ~PAGE_MASK) + 1;
kbase_sync_single(kctx, cpu_pa, gpu_pa, 0, sz,
KBASE_SYNC_TO_DEVICE);
}
}
map->gpu_addr = 0;
map->cpu_alloc = kbase_mem_phy_alloc_put(map->cpu_alloc);
map->gpu_alloc = kbase_mem_phy_alloc_put(map->gpu_alloc);
map->cpu_pages = NULL;
map->gpu_pages = NULL;
map->addr = NULL;
map->size = 0;
map->is_cached = false;
}
KBASE_EXPORT_TEST_API(kbase_vunmap);
void kbasep_os_process_page_usage_update(struct kbase_context *kctx, int pages)
{
struct mm_struct *mm;
rcu_read_lock();
mm = rcu_dereference(kctx->process_mm);
if (mm) {
atomic_add(pages, &kctx->nonmapped_pages);
#ifdef SPLIT_RSS_COUNTING
add_mm_counter(mm, MM_FILEPAGES, pages);
#else
spin_lock(&mm->page_table_lock);
add_mm_counter(mm, MM_FILEPAGES, pages);
spin_unlock(&mm->page_table_lock);
#endif
}
rcu_read_unlock();
}
static void kbasep_os_process_page_usage_drain(struct kbase_context *kctx)
{
int pages;
struct mm_struct *mm;
spin_lock(&kctx->mm_update_lock);
mm = rcu_dereference_protected(kctx->process_mm, lockdep_is_held(&kctx->mm_update_lock));
if (!mm) {
spin_unlock(&kctx->mm_update_lock);
return;
}
rcu_assign_pointer(kctx->process_mm, NULL);
spin_unlock(&kctx->mm_update_lock);
synchronize_rcu();
pages = atomic_xchg(&kctx->nonmapped_pages, 0);
#ifdef SPLIT_RSS_COUNTING
add_mm_counter(mm, MM_FILEPAGES, -pages);
#else
spin_lock(&mm->page_table_lock);
add_mm_counter(mm, MM_FILEPAGES, -pages);
spin_unlock(&mm->page_table_lock);
#endif
}
static void kbase_special_vm_close(struct vm_area_struct *vma)
{
struct kbase_context *kctx;
kctx = vma->vm_private_data;
kbasep_os_process_page_usage_drain(kctx);
}
static const struct vm_operations_struct kbase_vm_special_ops = {
.close = kbase_special_vm_close,
};
static int kbase_tracking_page_setup(struct kbase_context *kctx, struct vm_area_struct *vma)
{
/* check that this is the only tracking page */
spin_lock(&kctx->mm_update_lock);
if (rcu_dereference_protected(kctx->process_mm, lockdep_is_held(&kctx->mm_update_lock))) {
spin_unlock(&kctx->mm_update_lock);
return -EFAULT;
}
rcu_assign_pointer(kctx->process_mm, current->mm);
spin_unlock(&kctx->mm_update_lock);
/* no real access */
vma->vm_flags &= ~(VM_READ | VM_MAYREAD | VM_WRITE | VM_MAYWRITE | VM_EXEC | VM_MAYEXEC);
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(3, 7, 0))
vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP | VM_IO;
#else
vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_RESERVED | VM_IO;
#endif
vma->vm_ops = &kbase_vm_special_ops;
vma->vm_private_data = kctx;
return 0;
}
void *kbase_va_alloc(struct kbase_context *kctx, u32 size, struct kbase_hwc_dma_mapping *handle)
{
int i;
int res;
void *va;
dma_addr_t dma_pa;
struct kbase_va_region *reg;
phys_addr_t *page_array;
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(3, 5, 0))
DEFINE_DMA_ATTRS(attrs);
#endif
u32 pages = ((size - 1) >> PAGE_SHIFT) + 1;
u32 flags = BASE_MEM_PROT_CPU_RD | BASE_MEM_PROT_CPU_WR |
BASE_MEM_PROT_GPU_RD | BASE_MEM_PROT_GPU_WR;
KBASE_DEBUG_ASSERT(kctx != NULL);
KBASE_DEBUG_ASSERT(0 != size);
KBASE_DEBUG_ASSERT(0 != pages);
if (size == 0)
goto err;
/* All the alloc calls return zeroed memory */
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(3, 5, 0))
dma_set_attr(DMA_ATTR_WRITE_COMBINE, &attrs);
va = dma_alloc_attrs(kctx->kbdev->dev, size, &dma_pa, GFP_KERNEL, &attrs);
#else
va = dma_alloc_writecombine(kctx->kbdev->dev, size, &dma_pa, GFP_KERNEL);
#endif
if (!va)
goto err;
/* Store the state so we can free it later. */
handle->cpu_va = va;
handle->dma_pa = dma_pa;
handle->size = size;
reg = kbase_alloc_free_region(kctx, 0, pages, KBASE_REG_ZONE_SAME_VA);
if (!reg)
goto no_reg;
reg->flags &= ~KBASE_REG_FREE;
kbase_update_region_flags(kctx, reg, flags);
reg->cpu_alloc = kbase_alloc_create(pages, KBASE_MEM_TYPE_RAW);
if (IS_ERR_OR_NULL(reg->cpu_alloc))
goto no_alloc;
reg->gpu_alloc = kbase_mem_phy_alloc_get(reg->cpu_alloc);
page_array = kbase_get_cpu_phy_pages(reg);
for (i = 0; i < pages; i++)
page_array[i] = dma_pa + (i << PAGE_SHIFT);
reg->cpu_alloc->nents = pages;
kbase_gpu_vm_lock(kctx);
res = kbase_gpu_mmap(kctx, reg, (uintptr_t) va, pages, 1);
kbase_gpu_vm_unlock(kctx);
if (res)
goto no_mmap;
return va;
no_mmap:
kbase_mem_phy_alloc_put(reg->cpu_alloc);
kbase_mem_phy_alloc_put(reg->gpu_alloc);
no_alloc:
kfree(reg);
no_reg:
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(3, 5, 0))
dma_free_attrs(kctx->kbdev->dev, size, va, dma_pa, &attrs);
#else
dma_free_writecombine(kctx->kbdev->dev, size, va, dma_pa);
#endif
err:
return NULL;
}
KBASE_EXPORT_SYMBOL(kbase_va_alloc);
void kbase_va_free(struct kbase_context *kctx, struct kbase_hwc_dma_mapping *handle)
{
struct kbase_va_region *reg;
int err;
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(3, 5, 0))
DEFINE_DMA_ATTRS(attrs);
#endif
KBASE_DEBUG_ASSERT(kctx != NULL);
KBASE_DEBUG_ASSERT(handle->cpu_va != NULL);
kbase_gpu_vm_lock(kctx);
reg = kbase_region_tracker_find_region_base_address(kctx, (uintptr_t)handle->cpu_va);
KBASE_DEBUG_ASSERT(reg);
err = kbase_gpu_munmap(kctx, reg);
kbase_gpu_vm_unlock(kctx);
KBASE_DEBUG_ASSERT(!err);
kbase_mem_phy_alloc_put(reg->cpu_alloc);
kbase_mem_phy_alloc_put(reg->gpu_alloc);
kfree(reg);
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(3, 5, 0))
dma_set_attr(DMA_ATTR_WRITE_COMBINE, &attrs);
dma_free_attrs(kctx->kbdev->dev, handle->size,
handle->cpu_va, handle->dma_pa, &attrs);
#else
dma_free_writecombine(kctx->kbdev->dev, handle->size,
handle->cpu_va, handle->dma_pa);
#endif
}
KBASE_EXPORT_SYMBOL(kbase_va_free);
| gpl-2.0 |
liudanking/linux-kernel | net/decnet/dn_route.c | 608 | 48162 | /*
* DECnet An implementation of the DECnet protocol suite for the LINUX
* operating system. DECnet is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* DECnet Routing Functions (Endnode and Router)
*
* Authors: Steve Whitehouse <SteveW@ACM.org>
* Eduardo Marcelo Serrat <emserrat@geocities.com>
*
* Changes:
* Steve Whitehouse : Fixes to allow "intra-ethernet" and
* "return-to-sender" bits on outgoing
* packets.
* Steve Whitehouse : Timeouts for cached routes.
* Steve Whitehouse : Use dst cache for input routes too.
* Steve Whitehouse : Fixed error values in dn_send_skb.
* Steve Whitehouse : Rework routing functions to better fit
* DECnet routing design
* Alexey Kuznetsov : New SMP locking
* Steve Whitehouse : More SMP locking changes & dn_cache_dump()
* Steve Whitehouse : Prerouting NF hook, now really is prerouting.
* Fixed possible skb leak in rtnetlink funcs.
* Steve Whitehouse : Dave Miller's dynamic hash table sizing and
* Alexey Kuznetsov's finer grained locking
* from ipv4/route.c.
* Steve Whitehouse : Routing is now starting to look like a
* sensible set of code now, mainly due to
* my copying the IPv4 routing code. The
* hooks here are modified and will continue
* to evolve for a while.
* Steve Whitehouse : Real SMP at last :-) Also new netfilter
* stuff. Look out raw sockets your days
* are numbered!
* Steve Whitehouse : Added return-to-sender functions. Added
* backlog congestion level return codes.
* Steve Whitehouse : Fixed bug where routes were set up with
* no ref count on net devices.
* Steve Whitehouse : RCU for the route cache
* Steve Whitehouse : Preparations for the flow cache
* Steve Whitehouse : Prepare for nonlinear skbs
*/
/******************************************************************************
(c) 1995-1998 E.M. Serrat emserrat@geocities.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
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/errno.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/kernel.h>
#include <linux/sockios.h>
#include <linux/net.h>
#include <linux/netdevice.h>
#include <linux/inet.h>
#include <linux/route.h>
#include <linux/in_route.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <linux/mm.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/init.h>
#include <linux/rtnetlink.h>
#include <linux/string.h>
#include <linux/netfilter_decnet.h>
#include <linux/rcupdate.h>
#include <linux/times.h>
#include <linux/export.h>
#include <asm/errno.h>
#include <net/net_namespace.h>
#include <net/netlink.h>
#include <net/neighbour.h>
#include <net/dst.h>
#include <net/flow.h>
#include <net/fib_rules.h>
#include <net/dn.h>
#include <net/dn_dev.h>
#include <net/dn_nsp.h>
#include <net/dn_route.h>
#include <net/dn_neigh.h>
#include <net/dn_fib.h>
struct dn_rt_hash_bucket
{
struct dn_route __rcu *chain;
spinlock_t lock;
};
extern struct neigh_table dn_neigh_table;
static unsigned char dn_hiord_addr[6] = {0xAA,0x00,0x04,0x00,0x00,0x00};
static const int dn_rt_min_delay = 2 * HZ;
static const int dn_rt_max_delay = 10 * HZ;
static const int dn_rt_mtu_expires = 10 * 60 * HZ;
static unsigned long dn_rt_deadline;
static int dn_dst_gc(struct dst_ops *ops);
static struct dst_entry *dn_dst_check(struct dst_entry *, __u32);
static unsigned int dn_dst_default_advmss(const struct dst_entry *dst);
static unsigned int dn_dst_mtu(const struct dst_entry *dst);
static void dn_dst_destroy(struct dst_entry *);
static void dn_dst_ifdown(struct dst_entry *, struct net_device *dev, int how);
static struct dst_entry *dn_dst_negative_advice(struct dst_entry *);
static void dn_dst_link_failure(struct sk_buff *);
static void dn_dst_update_pmtu(struct dst_entry *dst, struct sock *sk,
struct sk_buff *skb , u32 mtu);
static void dn_dst_redirect(struct dst_entry *dst, struct sock *sk,
struct sk_buff *skb);
static struct neighbour *dn_dst_neigh_lookup(const struct dst_entry *dst,
struct sk_buff *skb,
const void *daddr);
static int dn_route_input(struct sk_buff *);
static void dn_run_flush(unsigned long dummy);
static struct dn_rt_hash_bucket *dn_rt_hash_table;
static unsigned int dn_rt_hash_mask;
static struct timer_list dn_route_timer;
static DEFINE_TIMER(dn_rt_flush_timer, dn_run_flush, 0, 0);
int decnet_dst_gc_interval = 2;
static struct dst_ops dn_dst_ops = {
.family = PF_DECnet,
.gc_thresh = 128,
.gc = dn_dst_gc,
.check = dn_dst_check,
.default_advmss = dn_dst_default_advmss,
.mtu = dn_dst_mtu,
.cow_metrics = dst_cow_metrics_generic,
.destroy = dn_dst_destroy,
.ifdown = dn_dst_ifdown,
.negative_advice = dn_dst_negative_advice,
.link_failure = dn_dst_link_failure,
.update_pmtu = dn_dst_update_pmtu,
.redirect = dn_dst_redirect,
.neigh_lookup = dn_dst_neigh_lookup,
};
static void dn_dst_destroy(struct dst_entry *dst)
{
struct dn_route *rt = (struct dn_route *) dst;
if (rt->n)
neigh_release(rt->n);
dst_destroy_metrics_generic(dst);
}
static void dn_dst_ifdown(struct dst_entry *dst, struct net_device *dev, int how)
{
if (how) {
struct dn_route *rt = (struct dn_route *) dst;
struct neighbour *n = rt->n;
if (n && n->dev == dev) {
n->dev = dev_net(dev)->loopback_dev;
dev_hold(n->dev);
dev_put(dev);
}
}
}
static __inline__ unsigned int dn_hash(__le16 src, __le16 dst)
{
__u16 tmp = (__u16 __force)(src ^ dst);
tmp ^= (tmp >> 3);
tmp ^= (tmp >> 5);
tmp ^= (tmp >> 10);
return dn_rt_hash_mask & (unsigned int)tmp;
}
static inline void dnrt_free(struct dn_route *rt)
{
call_rcu_bh(&rt->dst.rcu_head, dst_rcu_free);
}
static inline void dnrt_drop(struct dn_route *rt)
{
dst_release(&rt->dst);
call_rcu_bh(&rt->dst.rcu_head, dst_rcu_free);
}
static void dn_dst_check_expire(unsigned long dummy)
{
int i;
struct dn_route *rt;
struct dn_route __rcu **rtp;
unsigned long now = jiffies;
unsigned long expire = 120 * HZ;
for (i = 0; i <= dn_rt_hash_mask; i++) {
rtp = &dn_rt_hash_table[i].chain;
spin_lock(&dn_rt_hash_table[i].lock);
while ((rt = rcu_dereference_protected(*rtp,
lockdep_is_held(&dn_rt_hash_table[i].lock))) != NULL) {
if (atomic_read(&rt->dst.__refcnt) ||
(now - rt->dst.lastuse) < expire) {
rtp = &rt->dst.dn_next;
continue;
}
*rtp = rt->dst.dn_next;
rt->dst.dn_next = NULL;
dnrt_free(rt);
}
spin_unlock(&dn_rt_hash_table[i].lock);
if ((jiffies - now) > 0)
break;
}
mod_timer(&dn_route_timer, now + decnet_dst_gc_interval * HZ);
}
static int dn_dst_gc(struct dst_ops *ops)
{
struct dn_route *rt;
struct dn_route __rcu **rtp;
int i;
unsigned long now = jiffies;
unsigned long expire = 10 * HZ;
for (i = 0; i <= dn_rt_hash_mask; i++) {
spin_lock_bh(&dn_rt_hash_table[i].lock);
rtp = &dn_rt_hash_table[i].chain;
while ((rt = rcu_dereference_protected(*rtp,
lockdep_is_held(&dn_rt_hash_table[i].lock))) != NULL) {
if (atomic_read(&rt->dst.__refcnt) ||
(now - rt->dst.lastuse) < expire) {
rtp = &rt->dst.dn_next;
continue;
}
*rtp = rt->dst.dn_next;
rt->dst.dn_next = NULL;
dnrt_drop(rt);
break;
}
spin_unlock_bh(&dn_rt_hash_table[i].lock);
}
return 0;
}
/*
* The decnet standards don't impose a particular minimum mtu, what they
* do insist on is that the routing layer accepts a datagram of at least
* 230 bytes long. Here we have to subtract the routing header length from
* 230 to get the minimum acceptable mtu. If there is no neighbour, then we
* assume the worst and use a long header size.
*
* We update both the mtu and the advertised mss (i.e. the segment size we
* advertise to the other end).
*/
static void dn_dst_update_pmtu(struct dst_entry *dst, struct sock *sk,
struct sk_buff *skb, u32 mtu)
{
struct dn_route *rt = (struct dn_route *) dst;
struct neighbour *n = rt->n;
u32 min_mtu = 230;
struct dn_dev *dn;
dn = n ? rcu_dereference_raw(n->dev->dn_ptr) : NULL;
if (dn && dn->use_long == 0)
min_mtu -= 6;
else
min_mtu -= 21;
if (dst_metric(dst, RTAX_MTU) > mtu && mtu >= min_mtu) {
if (!(dst_metric_locked(dst, RTAX_MTU))) {
dst_metric_set(dst, RTAX_MTU, mtu);
dst_set_expires(dst, dn_rt_mtu_expires);
}
if (!(dst_metric_locked(dst, RTAX_ADVMSS))) {
u32 mss = mtu - DN_MAX_NSP_DATA_HEADER;
u32 existing_mss = dst_metric_raw(dst, RTAX_ADVMSS);
if (!existing_mss || existing_mss > mss)
dst_metric_set(dst, RTAX_ADVMSS, mss);
}
}
}
static void dn_dst_redirect(struct dst_entry *dst, struct sock *sk,
struct sk_buff *skb)
{
}
/*
* When a route has been marked obsolete. (e.g. routing cache flush)
*/
static struct dst_entry *dn_dst_check(struct dst_entry *dst, __u32 cookie)
{
return NULL;
}
static struct dst_entry *dn_dst_negative_advice(struct dst_entry *dst)
{
dst_release(dst);
return NULL;
}
static void dn_dst_link_failure(struct sk_buff *skb)
{
}
static inline int compare_keys(struct flowidn *fl1, struct flowidn *fl2)
{
return ((fl1->daddr ^ fl2->daddr) |
(fl1->saddr ^ fl2->saddr) |
(fl1->flowidn_mark ^ fl2->flowidn_mark) |
(fl1->flowidn_scope ^ fl2->flowidn_scope) |
(fl1->flowidn_oif ^ fl2->flowidn_oif) |
(fl1->flowidn_iif ^ fl2->flowidn_iif)) == 0;
}
static int dn_insert_route(struct dn_route *rt, unsigned int hash, struct dn_route **rp)
{
struct dn_route *rth;
struct dn_route __rcu **rthp;
unsigned long now = jiffies;
rthp = &dn_rt_hash_table[hash].chain;
spin_lock_bh(&dn_rt_hash_table[hash].lock);
while ((rth = rcu_dereference_protected(*rthp,
lockdep_is_held(&dn_rt_hash_table[hash].lock))) != NULL) {
if (compare_keys(&rth->fld, &rt->fld)) {
/* Put it first */
*rthp = rth->dst.dn_next;
rcu_assign_pointer(rth->dst.dn_next,
dn_rt_hash_table[hash].chain);
rcu_assign_pointer(dn_rt_hash_table[hash].chain, rth);
dst_use(&rth->dst, now);
spin_unlock_bh(&dn_rt_hash_table[hash].lock);
dnrt_drop(rt);
*rp = rth;
return 0;
}
rthp = &rth->dst.dn_next;
}
rcu_assign_pointer(rt->dst.dn_next, dn_rt_hash_table[hash].chain);
rcu_assign_pointer(dn_rt_hash_table[hash].chain, rt);
dst_use(&rt->dst, now);
spin_unlock_bh(&dn_rt_hash_table[hash].lock);
*rp = rt;
return 0;
}
static void dn_run_flush(unsigned long dummy)
{
int i;
struct dn_route *rt, *next;
for (i = 0; i < dn_rt_hash_mask; i++) {
spin_lock_bh(&dn_rt_hash_table[i].lock);
if ((rt = xchg((struct dn_route **)&dn_rt_hash_table[i].chain, NULL)) == NULL)
goto nothing_to_declare;
for(; rt; rt = next) {
next = rcu_dereference_raw(rt->dst.dn_next);
RCU_INIT_POINTER(rt->dst.dn_next, NULL);
dst_free((struct dst_entry *)rt);
}
nothing_to_declare:
spin_unlock_bh(&dn_rt_hash_table[i].lock);
}
}
static DEFINE_SPINLOCK(dn_rt_flush_lock);
void dn_rt_cache_flush(int delay)
{
unsigned long now = jiffies;
int user_mode = !in_interrupt();
if (delay < 0)
delay = dn_rt_min_delay;
spin_lock_bh(&dn_rt_flush_lock);
if (del_timer(&dn_rt_flush_timer) && delay > 0 && dn_rt_deadline) {
long tmo = (long)(dn_rt_deadline - now);
if (user_mode && tmo < dn_rt_max_delay - dn_rt_min_delay)
tmo = 0;
if (delay > tmo)
delay = tmo;
}
if (delay <= 0) {
spin_unlock_bh(&dn_rt_flush_lock);
dn_run_flush(0);
return;
}
if (dn_rt_deadline == 0)
dn_rt_deadline = now + dn_rt_max_delay;
dn_rt_flush_timer.expires = now + delay;
add_timer(&dn_rt_flush_timer);
spin_unlock_bh(&dn_rt_flush_lock);
}
/**
* dn_return_short - Return a short packet to its sender
* @skb: The packet to return
*
*/
static int dn_return_short(struct sk_buff *skb)
{
struct dn_skb_cb *cb;
unsigned char *ptr;
__le16 *src;
__le16 *dst;
/* Add back headers */
skb_push(skb, skb->data - skb_network_header(skb));
if ((skb = skb_unshare(skb, GFP_ATOMIC)) == NULL)
return NET_RX_DROP;
cb = DN_SKB_CB(skb);
/* Skip packet length and point to flags */
ptr = skb->data + 2;
*ptr++ = (cb->rt_flags & ~DN_RT_F_RQR) | DN_RT_F_RTS;
dst = (__le16 *)ptr;
ptr += 2;
src = (__le16 *)ptr;
ptr += 2;
*ptr = 0; /* Zero hop count */
swap(*src, *dst);
skb->pkt_type = PACKET_OUTGOING;
dn_rt_finish_output(skb, NULL, NULL);
return NET_RX_SUCCESS;
}
/**
* dn_return_long - Return a long packet to its sender
* @skb: The long format packet to return
*
*/
static int dn_return_long(struct sk_buff *skb)
{
struct dn_skb_cb *cb;
unsigned char *ptr;
unsigned char *src_addr, *dst_addr;
unsigned char tmp[ETH_ALEN];
/* Add back all headers */
skb_push(skb, skb->data - skb_network_header(skb));
if ((skb = skb_unshare(skb, GFP_ATOMIC)) == NULL)
return NET_RX_DROP;
cb = DN_SKB_CB(skb);
/* Ignore packet length and point to flags */
ptr = skb->data + 2;
/* Skip padding */
if (*ptr & DN_RT_F_PF) {
char padlen = (*ptr & ~DN_RT_F_PF);
ptr += padlen;
}
*ptr++ = (cb->rt_flags & ~DN_RT_F_RQR) | DN_RT_F_RTS;
ptr += 2;
dst_addr = ptr;
ptr += 8;
src_addr = ptr;
ptr += 6;
*ptr = 0; /* Zero hop count */
/* Swap source and destination */
memcpy(tmp, src_addr, ETH_ALEN);
memcpy(src_addr, dst_addr, ETH_ALEN);
memcpy(dst_addr, tmp, ETH_ALEN);
skb->pkt_type = PACKET_OUTGOING;
dn_rt_finish_output(skb, dst_addr, src_addr);
return NET_RX_SUCCESS;
}
/**
* dn_route_rx_packet - Try and find a route for an incoming packet
* @skb: The packet to find a route for
*
* Returns: result of input function if route is found, error code otherwise
*/
static int dn_route_rx_packet(struct sock *sk, struct sk_buff *skb)
{
struct dn_skb_cb *cb;
int err;
if ((err = dn_route_input(skb)) == 0)
return dst_input(skb);
cb = DN_SKB_CB(skb);
if (decnet_debug_level & 4) {
char *devname = skb->dev ? skb->dev->name : "???";
printk(KERN_DEBUG
"DECnet: dn_route_rx_packet: rt_flags=0x%02x dev=%s len=%d src=0x%04hx dst=0x%04hx err=%d type=%d\n",
(int)cb->rt_flags, devname, skb->len,
le16_to_cpu(cb->src), le16_to_cpu(cb->dst),
err, skb->pkt_type);
}
if ((skb->pkt_type == PACKET_HOST) && (cb->rt_flags & DN_RT_F_RQR)) {
switch (cb->rt_flags & DN_RT_PKT_MSK) {
case DN_RT_PKT_SHORT:
return dn_return_short(skb);
case DN_RT_PKT_LONG:
return dn_return_long(skb);
}
}
kfree_skb(skb);
return NET_RX_DROP;
}
static int dn_route_rx_long(struct sk_buff *skb)
{
struct dn_skb_cb *cb = DN_SKB_CB(skb);
unsigned char *ptr = skb->data;
if (!pskb_may_pull(skb, 21)) /* 20 for long header, 1 for shortest nsp */
goto drop_it;
skb_pull(skb, 20);
skb_reset_transport_header(skb);
/* Destination info */
ptr += 2;
cb->dst = dn_eth2dn(ptr);
if (memcmp(ptr, dn_hiord_addr, 4) != 0)
goto drop_it;
ptr += 6;
/* Source info */
ptr += 2;
cb->src = dn_eth2dn(ptr);
if (memcmp(ptr, dn_hiord_addr, 4) != 0)
goto drop_it;
ptr += 6;
/* Other junk */
ptr++;
cb->hops = *ptr++; /* Visit Count */
return NF_HOOK(NFPROTO_DECNET, NF_DN_PRE_ROUTING, NULL, skb,
skb->dev, NULL,
dn_route_rx_packet);
drop_it:
kfree_skb(skb);
return NET_RX_DROP;
}
static int dn_route_rx_short(struct sk_buff *skb)
{
struct dn_skb_cb *cb = DN_SKB_CB(skb);
unsigned char *ptr = skb->data;
if (!pskb_may_pull(skb, 6)) /* 5 for short header + 1 for shortest nsp */
goto drop_it;
skb_pull(skb, 5);
skb_reset_transport_header(skb);
cb->dst = *(__le16 *)ptr;
ptr += 2;
cb->src = *(__le16 *)ptr;
ptr += 2;
cb->hops = *ptr & 0x3f;
return NF_HOOK(NFPROTO_DECNET, NF_DN_PRE_ROUTING, NULL, skb,
skb->dev, NULL,
dn_route_rx_packet);
drop_it:
kfree_skb(skb);
return NET_RX_DROP;
}
static int dn_route_discard(struct sock *sk, struct sk_buff *skb)
{
/*
* I know we drop the packet here, but thats considered success in
* this case
*/
kfree_skb(skb);
return NET_RX_SUCCESS;
}
static int dn_route_ptp_hello(struct sock *sk, struct sk_buff *skb)
{
dn_dev_hello(skb);
dn_neigh_pointopoint_hello(skb);
return NET_RX_SUCCESS;
}
int dn_route_rcv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev)
{
struct dn_skb_cb *cb;
unsigned char flags = 0;
__u16 len = le16_to_cpu(*(__le16 *)skb->data);
struct dn_dev *dn = rcu_dereference(dev->dn_ptr);
unsigned char padlen = 0;
if (!net_eq(dev_net(dev), &init_net))
goto dump_it;
if (dn == NULL)
goto dump_it;
if ((skb = skb_share_check(skb, GFP_ATOMIC)) == NULL)
goto out;
if (!pskb_may_pull(skb, 3))
goto dump_it;
skb_pull(skb, 2);
if (len > skb->len)
goto dump_it;
skb_trim(skb, len);
flags = *skb->data;
cb = DN_SKB_CB(skb);
cb->stamp = jiffies;
cb->iif = dev->ifindex;
/*
* If we have padding, remove it.
*/
if (flags & DN_RT_F_PF) {
padlen = flags & ~DN_RT_F_PF;
if (!pskb_may_pull(skb, padlen + 1))
goto dump_it;
skb_pull(skb, padlen);
flags = *skb->data;
}
skb_reset_network_header(skb);
/*
* Weed out future version DECnet
*/
if (flags & DN_RT_F_VER)
goto dump_it;
cb->rt_flags = flags;
if (decnet_debug_level & 1)
printk(KERN_DEBUG
"dn_route_rcv: got 0x%02x from %s [%d %d %d]\n",
(int)flags, (dev) ? dev->name : "???", len, skb->len,
padlen);
if (flags & DN_RT_PKT_CNTL) {
if (unlikely(skb_linearize(skb)))
goto dump_it;
switch (flags & DN_RT_CNTL_MSK) {
case DN_RT_PKT_INIT:
dn_dev_init_pkt(skb);
break;
case DN_RT_PKT_VERI:
dn_dev_veri_pkt(skb);
break;
}
if (dn->parms.state != DN_DEV_S_RU)
goto dump_it;
switch (flags & DN_RT_CNTL_MSK) {
case DN_RT_PKT_HELO:
return NF_HOOK(NFPROTO_DECNET, NF_DN_HELLO,
NULL, skb, skb->dev, NULL,
dn_route_ptp_hello);
case DN_RT_PKT_L1RT:
case DN_RT_PKT_L2RT:
return NF_HOOK(NFPROTO_DECNET, NF_DN_ROUTE,
NULL, skb, skb->dev, NULL,
dn_route_discard);
case DN_RT_PKT_ERTH:
return NF_HOOK(NFPROTO_DECNET, NF_DN_HELLO,
NULL, skb, skb->dev, NULL,
dn_neigh_router_hello);
case DN_RT_PKT_EEDH:
return NF_HOOK(NFPROTO_DECNET, NF_DN_HELLO,
NULL, skb, skb->dev, NULL,
dn_neigh_endnode_hello);
}
} else {
if (dn->parms.state != DN_DEV_S_RU)
goto dump_it;
skb_pull(skb, 1); /* Pull flags */
switch (flags & DN_RT_PKT_MSK) {
case DN_RT_PKT_LONG:
return dn_route_rx_long(skb);
case DN_RT_PKT_SHORT:
return dn_route_rx_short(skb);
}
}
dump_it:
kfree_skb(skb);
out:
return NET_RX_DROP;
}
static int dn_output(struct sock *sk, struct sk_buff *skb)
{
struct dst_entry *dst = skb_dst(skb);
struct dn_route *rt = (struct dn_route *)dst;
struct net_device *dev = dst->dev;
struct dn_skb_cb *cb = DN_SKB_CB(skb);
int err = -EINVAL;
if (rt->n == NULL)
goto error;
skb->dev = dev;
cb->src = rt->rt_saddr;
cb->dst = rt->rt_daddr;
/*
* Always set the Intra-Ethernet bit on all outgoing packets
* originated on this node. Only valid flag from upper layers
* is return-to-sender-requested. Set hop count to 0 too.
*/
cb->rt_flags &= ~DN_RT_F_RQR;
cb->rt_flags |= DN_RT_F_IE;
cb->hops = 0;
return NF_HOOK(NFPROTO_DECNET, NF_DN_LOCAL_OUT, sk, skb,
NULL, dev,
dn_to_neigh_output);
error:
net_dbg_ratelimited("dn_output: This should not happen\n");
kfree_skb(skb);
return err;
}
static int dn_forward(struct sk_buff *skb)
{
struct dn_skb_cb *cb = DN_SKB_CB(skb);
struct dst_entry *dst = skb_dst(skb);
struct dn_dev *dn_db = rcu_dereference(dst->dev->dn_ptr);
struct dn_route *rt;
int header_len;
#ifdef CONFIG_NETFILTER
struct net_device *dev = skb->dev;
#endif
if (skb->pkt_type != PACKET_HOST)
goto drop;
/* Ensure that we have enough space for headers */
rt = (struct dn_route *)skb_dst(skb);
header_len = dn_db->use_long ? 21 : 6;
if (skb_cow(skb, LL_RESERVED_SPACE(rt->dst.dev)+header_len))
goto drop;
/*
* Hop count exceeded.
*/
if (++cb->hops > 30)
goto drop;
skb->dev = rt->dst.dev;
/*
* If packet goes out same interface it came in on, then set
* the Intra-Ethernet bit. This has no effect for short
* packets, so we don't need to test for them here.
*/
cb->rt_flags &= ~DN_RT_F_IE;
if (rt->rt_flags & RTCF_DOREDIRECT)
cb->rt_flags |= DN_RT_F_IE;
return NF_HOOK(NFPROTO_DECNET, NF_DN_FORWARD, NULL, skb,
dev, skb->dev,
dn_to_neigh_output);
drop:
kfree_skb(skb);
return NET_RX_DROP;
}
/*
* Used to catch bugs. This should never normally get
* called.
*/
static int dn_rt_bug_sk(struct sock *sk, struct sk_buff *skb)
{
struct dn_skb_cb *cb = DN_SKB_CB(skb);
net_dbg_ratelimited("dn_rt_bug: skb from:%04x to:%04x\n",
le16_to_cpu(cb->src), le16_to_cpu(cb->dst));
kfree_skb(skb);
return NET_RX_DROP;
}
static int dn_rt_bug(struct sk_buff *skb)
{
struct dn_skb_cb *cb = DN_SKB_CB(skb);
net_dbg_ratelimited("dn_rt_bug: skb from:%04x to:%04x\n",
le16_to_cpu(cb->src), le16_to_cpu(cb->dst));
kfree_skb(skb);
return NET_RX_DROP;
}
static unsigned int dn_dst_default_advmss(const struct dst_entry *dst)
{
return dn_mss_from_pmtu(dst->dev, dst_mtu(dst));
}
static unsigned int dn_dst_mtu(const struct dst_entry *dst)
{
unsigned int mtu = dst_metric_raw(dst, RTAX_MTU);
return mtu ? : dst->dev->mtu;
}
static struct neighbour *dn_dst_neigh_lookup(const struct dst_entry *dst,
struct sk_buff *skb,
const void *daddr)
{
return __neigh_lookup_errno(&dn_neigh_table, daddr, dst->dev);
}
static int dn_rt_set_next_hop(struct dn_route *rt, struct dn_fib_res *res)
{
struct dn_fib_info *fi = res->fi;
struct net_device *dev = rt->dst.dev;
unsigned int mss_metric;
struct neighbour *n;
if (fi) {
if (DN_FIB_RES_GW(*res) &&
DN_FIB_RES_NH(*res).nh_scope == RT_SCOPE_LINK)
rt->rt_gateway = DN_FIB_RES_GW(*res);
dst_init_metrics(&rt->dst, fi->fib_metrics, true);
}
rt->rt_type = res->type;
if (dev != NULL && rt->n == NULL) {
n = __neigh_lookup_errno(&dn_neigh_table, &rt->rt_gateway, dev);
if (IS_ERR(n))
return PTR_ERR(n);
rt->n = n;
}
if (dst_metric(&rt->dst, RTAX_MTU) > rt->dst.dev->mtu)
dst_metric_set(&rt->dst, RTAX_MTU, rt->dst.dev->mtu);
mss_metric = dst_metric_raw(&rt->dst, RTAX_ADVMSS);
if (mss_metric) {
unsigned int mss = dn_mss_from_pmtu(dev, dst_mtu(&rt->dst));
if (mss_metric > mss)
dst_metric_set(&rt->dst, RTAX_ADVMSS, mss);
}
return 0;
}
static inline int dn_match_addr(__le16 addr1, __le16 addr2)
{
__u16 tmp = le16_to_cpu(addr1) ^ le16_to_cpu(addr2);
int match = 16;
while(tmp) {
tmp >>= 1;
match--;
}
return match;
}
static __le16 dnet_select_source(const struct net_device *dev, __le16 daddr, int scope)
{
__le16 saddr = 0;
struct dn_dev *dn_db;
struct dn_ifaddr *ifa;
int best_match = 0;
int ret;
rcu_read_lock();
dn_db = rcu_dereference(dev->dn_ptr);
for (ifa = rcu_dereference(dn_db->ifa_list);
ifa != NULL;
ifa = rcu_dereference(ifa->ifa_next)) {
if (ifa->ifa_scope > scope)
continue;
if (!daddr) {
saddr = ifa->ifa_local;
break;
}
ret = dn_match_addr(daddr, ifa->ifa_local);
if (ret > best_match)
saddr = ifa->ifa_local;
if (best_match == 0)
saddr = ifa->ifa_local;
}
rcu_read_unlock();
return saddr;
}
static inline __le16 __dn_fib_res_prefsrc(struct dn_fib_res *res)
{
return dnet_select_source(DN_FIB_RES_DEV(*res), DN_FIB_RES_GW(*res), res->scope);
}
static inline __le16 dn_fib_rules_map_destination(__le16 daddr, struct dn_fib_res *res)
{
__le16 mask = dnet_make_mask(res->prefixlen);
return (daddr&~mask)|res->fi->fib_nh->nh_gw;
}
static int dn_route_output_slow(struct dst_entry **pprt, const struct flowidn *oldflp, int try_hard)
{
struct flowidn fld = {
.daddr = oldflp->daddr,
.saddr = oldflp->saddr,
.flowidn_scope = RT_SCOPE_UNIVERSE,
.flowidn_mark = oldflp->flowidn_mark,
.flowidn_iif = LOOPBACK_IFINDEX,
.flowidn_oif = oldflp->flowidn_oif,
};
struct dn_route *rt = NULL;
struct net_device *dev_out = NULL, *dev;
struct neighbour *neigh = NULL;
unsigned int hash;
unsigned int flags = 0;
struct dn_fib_res res = { .fi = NULL, .type = RTN_UNICAST };
int err;
int free_res = 0;
__le16 gateway = 0;
if (decnet_debug_level & 16)
printk(KERN_DEBUG
"dn_route_output_slow: dst=%04x src=%04x mark=%d"
" iif=%d oif=%d\n", le16_to_cpu(oldflp->daddr),
le16_to_cpu(oldflp->saddr),
oldflp->flowidn_mark, LOOPBACK_IFINDEX,
oldflp->flowidn_oif);
/* If we have an output interface, verify its a DECnet device */
if (oldflp->flowidn_oif) {
dev_out = dev_get_by_index(&init_net, oldflp->flowidn_oif);
err = -ENODEV;
if (dev_out && dev_out->dn_ptr == NULL) {
dev_put(dev_out);
dev_out = NULL;
}
if (dev_out == NULL)
goto out;
}
/* If we have a source address, verify that its a local address */
if (oldflp->saddr) {
err = -EADDRNOTAVAIL;
if (dev_out) {
if (dn_dev_islocal(dev_out, oldflp->saddr))
goto source_ok;
dev_put(dev_out);
goto out;
}
rcu_read_lock();
for_each_netdev_rcu(&init_net, dev) {
if (!dev->dn_ptr)
continue;
if (!dn_dev_islocal(dev, oldflp->saddr))
continue;
if ((dev->flags & IFF_LOOPBACK) &&
oldflp->daddr &&
!dn_dev_islocal(dev, oldflp->daddr))
continue;
dev_out = dev;
break;
}
rcu_read_unlock();
if (dev_out == NULL)
goto out;
dev_hold(dev_out);
source_ok:
;
}
/* No destination? Assume its local */
if (!fld.daddr) {
fld.daddr = fld.saddr;
err = -EADDRNOTAVAIL;
if (dev_out)
dev_put(dev_out);
dev_out = init_net.loopback_dev;
dev_hold(dev_out);
if (!fld.daddr) {
fld.daddr =
fld.saddr = dnet_select_source(dev_out, 0,
RT_SCOPE_HOST);
if (!fld.daddr)
goto out;
}
fld.flowidn_oif = LOOPBACK_IFINDEX;
res.type = RTN_LOCAL;
goto make_route;
}
if (decnet_debug_level & 16)
printk(KERN_DEBUG
"dn_route_output_slow: initial checks complete."
" dst=%04x src=%04x oif=%d try_hard=%d\n",
le16_to_cpu(fld.daddr), le16_to_cpu(fld.saddr),
fld.flowidn_oif, try_hard);
/*
* N.B. If the kernel is compiled without router support then
* dn_fib_lookup() will evaluate to non-zero so this if () block
* will always be executed.
*/
err = -ESRCH;
if (try_hard || (err = dn_fib_lookup(&fld, &res)) != 0) {
struct dn_dev *dn_db;
if (err != -ESRCH)
goto out;
/*
* Here the fallback is basically the standard algorithm for
* routing in endnodes which is described in the DECnet routing
* docs
*
* If we are not trying hard, look in neighbour cache.
* The result is tested to ensure that if a specific output
* device/source address was requested, then we honour that
* here
*/
if (!try_hard) {
neigh = neigh_lookup_nodev(&dn_neigh_table, &init_net, &fld.daddr);
if (neigh) {
if ((oldflp->flowidn_oif &&
(neigh->dev->ifindex != oldflp->flowidn_oif)) ||
(oldflp->saddr &&
(!dn_dev_islocal(neigh->dev,
oldflp->saddr)))) {
neigh_release(neigh);
neigh = NULL;
} else {
if (dev_out)
dev_put(dev_out);
if (dn_dev_islocal(neigh->dev, fld.daddr)) {
dev_out = init_net.loopback_dev;
res.type = RTN_LOCAL;
} else {
dev_out = neigh->dev;
}
dev_hold(dev_out);
goto select_source;
}
}
}
/* Not there? Perhaps its a local address */
if (dev_out == NULL)
dev_out = dn_dev_get_default();
err = -ENODEV;
if (dev_out == NULL)
goto out;
dn_db = rcu_dereference_raw(dev_out->dn_ptr);
/* Possible improvement - check all devices for local addr */
if (dn_dev_islocal(dev_out, fld.daddr)) {
dev_put(dev_out);
dev_out = init_net.loopback_dev;
dev_hold(dev_out);
res.type = RTN_LOCAL;
goto select_source;
}
/* Not local either.... try sending it to the default router */
neigh = neigh_clone(dn_db->router);
BUG_ON(neigh && neigh->dev != dev_out);
/* Ok then, we assume its directly connected and move on */
select_source:
if (neigh)
gateway = ((struct dn_neigh *)neigh)->addr;
if (gateway == 0)
gateway = fld.daddr;
if (fld.saddr == 0) {
fld.saddr = dnet_select_source(dev_out, gateway,
res.type == RTN_LOCAL ?
RT_SCOPE_HOST :
RT_SCOPE_LINK);
if (fld.saddr == 0 && res.type != RTN_LOCAL)
goto e_addr;
}
fld.flowidn_oif = dev_out->ifindex;
goto make_route;
}
free_res = 1;
if (res.type == RTN_NAT)
goto e_inval;
if (res.type == RTN_LOCAL) {
if (!fld.saddr)
fld.saddr = fld.daddr;
if (dev_out)
dev_put(dev_out);
dev_out = init_net.loopback_dev;
dev_hold(dev_out);
fld.flowidn_oif = dev_out->ifindex;
if (res.fi)
dn_fib_info_put(res.fi);
res.fi = NULL;
goto make_route;
}
if (res.fi->fib_nhs > 1 && fld.flowidn_oif == 0)
dn_fib_select_multipath(&fld, &res);
/*
* We could add some logic to deal with default routes here and
* get rid of some of the special casing above.
*/
if (!fld.saddr)
fld.saddr = DN_FIB_RES_PREFSRC(res);
if (dev_out)
dev_put(dev_out);
dev_out = DN_FIB_RES_DEV(res);
dev_hold(dev_out);
fld.flowidn_oif = dev_out->ifindex;
gateway = DN_FIB_RES_GW(res);
make_route:
if (dev_out->flags & IFF_LOOPBACK)
flags |= RTCF_LOCAL;
rt = dst_alloc(&dn_dst_ops, dev_out, 1, DST_OBSOLETE_NONE, DST_HOST);
if (rt == NULL)
goto e_nobufs;
memset(&rt->fld, 0, sizeof(rt->fld));
rt->fld.saddr = oldflp->saddr;
rt->fld.daddr = oldflp->daddr;
rt->fld.flowidn_oif = oldflp->flowidn_oif;
rt->fld.flowidn_iif = 0;
rt->fld.flowidn_mark = oldflp->flowidn_mark;
rt->rt_saddr = fld.saddr;
rt->rt_daddr = fld.daddr;
rt->rt_gateway = gateway ? gateway : fld.daddr;
rt->rt_local_src = fld.saddr;
rt->rt_dst_map = fld.daddr;
rt->rt_src_map = fld.saddr;
rt->n = neigh;
neigh = NULL;
rt->dst.lastuse = jiffies;
rt->dst.output = dn_output;
rt->dst.input = dn_rt_bug;
rt->rt_flags = flags;
if (flags & RTCF_LOCAL)
rt->dst.input = dn_nsp_rx;
err = dn_rt_set_next_hop(rt, &res);
if (err)
goto e_neighbour;
hash = dn_hash(rt->fld.saddr, rt->fld.daddr);
dn_insert_route(rt, hash, (struct dn_route **)pprt);
done:
if (neigh)
neigh_release(neigh);
if (free_res)
dn_fib_res_put(&res);
if (dev_out)
dev_put(dev_out);
out:
return err;
e_addr:
err = -EADDRNOTAVAIL;
goto done;
e_inval:
err = -EINVAL;
goto done;
e_nobufs:
err = -ENOBUFS;
goto done;
e_neighbour:
dst_free(&rt->dst);
goto e_nobufs;
}
/*
* N.B. The flags may be moved into the flowi at some future stage.
*/
static int __dn_route_output_key(struct dst_entry **pprt, const struct flowidn *flp, int flags)
{
unsigned int hash = dn_hash(flp->saddr, flp->daddr);
struct dn_route *rt = NULL;
if (!(flags & MSG_TRYHARD)) {
rcu_read_lock_bh();
for (rt = rcu_dereference_bh(dn_rt_hash_table[hash].chain); rt;
rt = rcu_dereference_bh(rt->dst.dn_next)) {
if ((flp->daddr == rt->fld.daddr) &&
(flp->saddr == rt->fld.saddr) &&
(flp->flowidn_mark == rt->fld.flowidn_mark) &&
dn_is_output_route(rt) &&
(rt->fld.flowidn_oif == flp->flowidn_oif)) {
dst_use(&rt->dst, jiffies);
rcu_read_unlock_bh();
*pprt = &rt->dst;
return 0;
}
}
rcu_read_unlock_bh();
}
return dn_route_output_slow(pprt, flp, flags);
}
static int dn_route_output_key(struct dst_entry **pprt, struct flowidn *flp, int flags)
{
int err;
err = __dn_route_output_key(pprt, flp, flags);
if (err == 0 && flp->flowidn_proto) {
*pprt = xfrm_lookup(&init_net, *pprt,
flowidn_to_flowi(flp), NULL, 0);
if (IS_ERR(*pprt)) {
err = PTR_ERR(*pprt);
*pprt = NULL;
}
}
return err;
}
int dn_route_output_sock(struct dst_entry __rcu **pprt, struct flowidn *fl, struct sock *sk, int flags)
{
int err;
err = __dn_route_output_key(pprt, fl, flags & MSG_TRYHARD);
if (err == 0 && fl->flowidn_proto) {
*pprt = xfrm_lookup(&init_net, *pprt,
flowidn_to_flowi(fl), sk, 0);
if (IS_ERR(*pprt)) {
err = PTR_ERR(*pprt);
*pprt = NULL;
}
}
return err;
}
static int dn_route_input_slow(struct sk_buff *skb)
{
struct dn_route *rt = NULL;
struct dn_skb_cb *cb = DN_SKB_CB(skb);
struct net_device *in_dev = skb->dev;
struct net_device *out_dev = NULL;
struct dn_dev *dn_db;
struct neighbour *neigh = NULL;
unsigned int hash;
int flags = 0;
__le16 gateway = 0;
__le16 local_src = 0;
struct flowidn fld = {
.daddr = cb->dst,
.saddr = cb->src,
.flowidn_scope = RT_SCOPE_UNIVERSE,
.flowidn_mark = skb->mark,
.flowidn_iif = skb->dev->ifindex,
};
struct dn_fib_res res = { .fi = NULL, .type = RTN_UNREACHABLE };
int err = -EINVAL;
int free_res = 0;
dev_hold(in_dev);
if ((dn_db = rcu_dereference(in_dev->dn_ptr)) == NULL)
goto out;
/* Zero source addresses are not allowed */
if (fld.saddr == 0)
goto out;
/*
* In this case we've just received a packet from a source
* outside ourselves pretending to come from us. We don't
* allow it any further to prevent routing loops, spoofing and
* other nasties. Loopback packets already have the dst attached
* so this only affects packets which have originated elsewhere.
*/
err = -ENOTUNIQ;
if (dn_dev_islocal(in_dev, cb->src))
goto out;
err = dn_fib_lookup(&fld, &res);
if (err) {
if (err != -ESRCH)
goto out;
/*
* Is the destination us ?
*/
if (!dn_dev_islocal(in_dev, cb->dst))
goto e_inval;
res.type = RTN_LOCAL;
} else {
__le16 src_map = fld.saddr;
free_res = 1;
out_dev = DN_FIB_RES_DEV(res);
if (out_dev == NULL) {
net_crit_ratelimited("Bug in dn_route_input_slow() No output device\n");
goto e_inval;
}
dev_hold(out_dev);
if (res.r)
src_map = fld.saddr; /* no NAT support for now */
gateway = DN_FIB_RES_GW(res);
if (res.type == RTN_NAT) {
fld.daddr = dn_fib_rules_map_destination(fld.daddr, &res);
dn_fib_res_put(&res);
free_res = 0;
if (dn_fib_lookup(&fld, &res))
goto e_inval;
free_res = 1;
if (res.type != RTN_UNICAST)
goto e_inval;
flags |= RTCF_DNAT;
gateway = fld.daddr;
}
fld.saddr = src_map;
}
switch(res.type) {
case RTN_UNICAST:
/*
* Forwarding check here, we only check for forwarding
* being turned off, if you want to only forward intra
* area, its up to you to set the routing tables up
* correctly.
*/
if (dn_db->parms.forwarding == 0)
goto e_inval;
if (res.fi->fib_nhs > 1 && fld.flowidn_oif == 0)
dn_fib_select_multipath(&fld, &res);
/*
* Check for out_dev == in_dev. We use the RTCF_DOREDIRECT
* flag as a hint to set the intra-ethernet bit when
* forwarding. If we've got NAT in operation, we don't do
* this optimisation.
*/
if (out_dev == in_dev && !(flags & RTCF_NAT))
flags |= RTCF_DOREDIRECT;
local_src = DN_FIB_RES_PREFSRC(res);
case RTN_BLACKHOLE:
case RTN_UNREACHABLE:
break;
case RTN_LOCAL:
flags |= RTCF_LOCAL;
fld.saddr = cb->dst;
fld.daddr = cb->src;
/* Routing tables gave us a gateway */
if (gateway)
goto make_route;
/* Packet was intra-ethernet, so we know its on-link */
if (cb->rt_flags & DN_RT_F_IE) {
gateway = cb->src;
goto make_route;
}
/* Use the default router if there is one */
neigh = neigh_clone(dn_db->router);
if (neigh) {
gateway = ((struct dn_neigh *)neigh)->addr;
goto make_route;
}
/* Close eyes and pray */
gateway = cb->src;
goto make_route;
default:
goto e_inval;
}
make_route:
rt = dst_alloc(&dn_dst_ops, out_dev, 0, DST_OBSOLETE_NONE, DST_HOST);
if (rt == NULL)
goto e_nobufs;
memset(&rt->fld, 0, sizeof(rt->fld));
rt->rt_saddr = fld.saddr;
rt->rt_daddr = fld.daddr;
rt->rt_gateway = fld.daddr;
if (gateway)
rt->rt_gateway = gateway;
rt->rt_local_src = local_src ? local_src : rt->rt_saddr;
rt->rt_dst_map = fld.daddr;
rt->rt_src_map = fld.saddr;
rt->fld.saddr = cb->src;
rt->fld.daddr = cb->dst;
rt->fld.flowidn_oif = 0;
rt->fld.flowidn_iif = in_dev->ifindex;
rt->fld.flowidn_mark = fld.flowidn_mark;
rt->n = neigh;
rt->dst.lastuse = jiffies;
rt->dst.output = dn_rt_bug_sk;
switch (res.type) {
case RTN_UNICAST:
rt->dst.input = dn_forward;
break;
case RTN_LOCAL:
rt->dst.output = dn_output;
rt->dst.input = dn_nsp_rx;
rt->dst.dev = in_dev;
flags |= RTCF_LOCAL;
break;
default:
case RTN_UNREACHABLE:
case RTN_BLACKHOLE:
rt->dst.input = dst_discard;
}
rt->rt_flags = flags;
err = dn_rt_set_next_hop(rt, &res);
if (err)
goto e_neighbour;
hash = dn_hash(rt->fld.saddr, rt->fld.daddr);
dn_insert_route(rt, hash, &rt);
skb_dst_set(skb, &rt->dst);
done:
if (neigh)
neigh_release(neigh);
if (free_res)
dn_fib_res_put(&res);
dev_put(in_dev);
if (out_dev)
dev_put(out_dev);
out:
return err;
e_inval:
err = -EINVAL;
goto done;
e_nobufs:
err = -ENOBUFS;
goto done;
e_neighbour:
dst_free(&rt->dst);
goto done;
}
static int dn_route_input(struct sk_buff *skb)
{
struct dn_route *rt;
struct dn_skb_cb *cb = DN_SKB_CB(skb);
unsigned int hash = dn_hash(cb->src, cb->dst);
if (skb_dst(skb))
return 0;
rcu_read_lock();
for(rt = rcu_dereference(dn_rt_hash_table[hash].chain); rt != NULL;
rt = rcu_dereference(rt->dst.dn_next)) {
if ((rt->fld.saddr == cb->src) &&
(rt->fld.daddr == cb->dst) &&
(rt->fld.flowidn_oif == 0) &&
(rt->fld.flowidn_mark == skb->mark) &&
(rt->fld.flowidn_iif == cb->iif)) {
dst_use(&rt->dst, jiffies);
rcu_read_unlock();
skb_dst_set(skb, (struct dst_entry *)rt);
return 0;
}
}
rcu_read_unlock();
return dn_route_input_slow(skb);
}
static int dn_rt_fill_info(struct sk_buff *skb, u32 portid, u32 seq,
int event, int nowait, unsigned int flags)
{
struct dn_route *rt = (struct dn_route *)skb_dst(skb);
struct rtmsg *r;
struct nlmsghdr *nlh;
long expires;
nlh = nlmsg_put(skb, portid, seq, event, sizeof(*r), flags);
if (!nlh)
return -EMSGSIZE;
r = nlmsg_data(nlh);
r->rtm_family = AF_DECnet;
r->rtm_dst_len = 16;
r->rtm_src_len = 0;
r->rtm_tos = 0;
r->rtm_table = RT_TABLE_MAIN;
r->rtm_type = rt->rt_type;
r->rtm_flags = (rt->rt_flags & ~0xFFFF) | RTM_F_CLONED;
r->rtm_scope = RT_SCOPE_UNIVERSE;
r->rtm_protocol = RTPROT_UNSPEC;
if (rt->rt_flags & RTCF_NOTIFY)
r->rtm_flags |= RTM_F_NOTIFY;
if (nla_put_u32(skb, RTA_TABLE, RT_TABLE_MAIN) < 0 ||
nla_put_le16(skb, RTA_DST, rt->rt_daddr) < 0)
goto errout;
if (rt->fld.saddr) {
r->rtm_src_len = 16;
if (nla_put_le16(skb, RTA_SRC, rt->fld.saddr) < 0)
goto errout;
}
if (rt->dst.dev &&
nla_put_u32(skb, RTA_OIF, rt->dst.dev->ifindex) < 0)
goto errout;
/*
* Note to self - change this if input routes reverse direction when
* they deal only with inputs and not with replies like they do
* currently.
*/
if (nla_put_le16(skb, RTA_PREFSRC, rt->rt_local_src) < 0)
goto errout;
if (rt->rt_daddr != rt->rt_gateway &&
nla_put_le16(skb, RTA_GATEWAY, rt->rt_gateway) < 0)
goto errout;
if (rtnetlink_put_metrics(skb, dst_metrics_ptr(&rt->dst)) < 0)
goto errout;
expires = rt->dst.expires ? rt->dst.expires - jiffies : 0;
if (rtnl_put_cacheinfo(skb, &rt->dst, 0, expires,
rt->dst.error) < 0)
goto errout;
if (dn_is_input_route(rt) &&
nla_put_u32(skb, RTA_IIF, rt->fld.flowidn_iif) < 0)
goto errout;
nlmsg_end(skb, nlh);
return 0;
errout:
nlmsg_cancel(skb, nlh);
return -EMSGSIZE;
}
const struct nla_policy rtm_dn_policy[RTA_MAX + 1] = {
[RTA_DST] = { .type = NLA_U16 },
[RTA_SRC] = { .type = NLA_U16 },
[RTA_IIF] = { .type = NLA_U32 },
[RTA_OIF] = { .type = NLA_U32 },
[RTA_GATEWAY] = { .type = NLA_U16 },
[RTA_PRIORITY] = { .type = NLA_U32 },
[RTA_PREFSRC] = { .type = NLA_U16 },
[RTA_METRICS] = { .type = NLA_NESTED },
[RTA_MULTIPATH] = { .type = NLA_NESTED },
[RTA_TABLE] = { .type = NLA_U32 },
[RTA_MARK] = { .type = NLA_U32 },
};
/*
* This is called by both endnodes and routers now.
*/
static int dn_cache_getroute(struct sk_buff *in_skb, struct nlmsghdr *nlh)
{
struct net *net = sock_net(in_skb->sk);
struct rtmsg *rtm = nlmsg_data(nlh);
struct dn_route *rt = NULL;
struct dn_skb_cb *cb;
int err;
struct sk_buff *skb;
struct flowidn fld;
struct nlattr *tb[RTA_MAX+1];
if (!net_eq(net, &init_net))
return -EINVAL;
err = nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_dn_policy);
if (err < 0)
return err;
memset(&fld, 0, sizeof(fld));
fld.flowidn_proto = DNPROTO_NSP;
skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (skb == NULL)
return -ENOBUFS;
skb_reset_mac_header(skb);
cb = DN_SKB_CB(skb);
if (tb[RTA_SRC])
fld.saddr = nla_get_le16(tb[RTA_SRC]);
if (tb[RTA_DST])
fld.daddr = nla_get_le16(tb[RTA_DST]);
if (tb[RTA_IIF])
fld.flowidn_iif = nla_get_u32(tb[RTA_IIF]);
if (fld.flowidn_iif) {
struct net_device *dev;
dev = __dev_get_by_index(&init_net, fld.flowidn_iif);
if (!dev || !dev->dn_ptr) {
kfree_skb(skb);
return -ENODEV;
}
skb->protocol = htons(ETH_P_DNA_RT);
skb->dev = dev;
cb->src = fld.saddr;
cb->dst = fld.daddr;
local_bh_disable();
err = dn_route_input(skb);
local_bh_enable();
memset(cb, 0, sizeof(struct dn_skb_cb));
rt = (struct dn_route *)skb_dst(skb);
if (!err && -rt->dst.error)
err = rt->dst.error;
} else {
if (tb[RTA_OIF])
fld.flowidn_oif = nla_get_u32(tb[RTA_OIF]);
err = dn_route_output_key((struct dst_entry **)&rt, &fld, 0);
}
skb->dev = NULL;
if (err)
goto out_free;
skb_dst_set(skb, &rt->dst);
if (rtm->rtm_flags & RTM_F_NOTIFY)
rt->rt_flags |= RTCF_NOTIFY;
err = dn_rt_fill_info(skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq, RTM_NEWROUTE, 0, 0);
if (err < 0) {
err = -EMSGSIZE;
goto out_free;
}
return rtnl_unicast(skb, &init_net, NETLINK_CB(in_skb).portid);
out_free:
kfree_skb(skb);
return err;
}
/*
* For routers, this is called from dn_fib_dump, but for endnodes its
* called directly from the rtnetlink dispatch table.
*/
int dn_cache_dump(struct sk_buff *skb, struct netlink_callback *cb)
{
struct net *net = sock_net(skb->sk);
struct dn_route *rt;
int h, s_h;
int idx, s_idx;
struct rtmsg *rtm;
if (!net_eq(net, &init_net))
return 0;
if (nlmsg_len(cb->nlh) < sizeof(struct rtmsg))
return -EINVAL;
rtm = nlmsg_data(cb->nlh);
if (!(rtm->rtm_flags & RTM_F_CLONED))
return 0;
s_h = cb->args[0];
s_idx = idx = cb->args[1];
for(h = 0; h <= dn_rt_hash_mask; h++) {
if (h < s_h)
continue;
if (h > s_h)
s_idx = 0;
rcu_read_lock_bh();
for(rt = rcu_dereference_bh(dn_rt_hash_table[h].chain), idx = 0;
rt;
rt = rcu_dereference_bh(rt->dst.dn_next), idx++) {
if (idx < s_idx)
continue;
skb_dst_set(skb, dst_clone(&rt->dst));
if (dn_rt_fill_info(skb, NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq, RTM_NEWROUTE,
1, NLM_F_MULTI) < 0) {
skb_dst_drop(skb);
rcu_read_unlock_bh();
goto done;
}
skb_dst_drop(skb);
}
rcu_read_unlock_bh();
}
done:
cb->args[0] = h;
cb->args[1] = idx;
return skb->len;
}
#ifdef CONFIG_PROC_FS
struct dn_rt_cache_iter_state {
int bucket;
};
static struct dn_route *dn_rt_cache_get_first(struct seq_file *seq)
{
struct dn_route *rt = NULL;
struct dn_rt_cache_iter_state *s = seq->private;
for(s->bucket = dn_rt_hash_mask; s->bucket >= 0; --s->bucket) {
rcu_read_lock_bh();
rt = rcu_dereference_bh(dn_rt_hash_table[s->bucket].chain);
if (rt)
break;
rcu_read_unlock_bh();
}
return rt;
}
static struct dn_route *dn_rt_cache_get_next(struct seq_file *seq, struct dn_route *rt)
{
struct dn_rt_cache_iter_state *s = seq->private;
rt = rcu_dereference_bh(rt->dst.dn_next);
while (!rt) {
rcu_read_unlock_bh();
if (--s->bucket < 0)
break;
rcu_read_lock_bh();
rt = rcu_dereference_bh(dn_rt_hash_table[s->bucket].chain);
}
return rt;
}
static void *dn_rt_cache_seq_start(struct seq_file *seq, loff_t *pos)
{
struct dn_route *rt = dn_rt_cache_get_first(seq);
if (rt) {
while(*pos && (rt = dn_rt_cache_get_next(seq, rt)))
--*pos;
}
return *pos ? NULL : rt;
}
static void *dn_rt_cache_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct dn_route *rt = dn_rt_cache_get_next(seq, v);
++*pos;
return rt;
}
static void dn_rt_cache_seq_stop(struct seq_file *seq, void *v)
{
if (v)
rcu_read_unlock_bh();
}
static int dn_rt_cache_seq_show(struct seq_file *seq, void *v)
{
struct dn_route *rt = v;
char buf1[DN_ASCBUF_LEN], buf2[DN_ASCBUF_LEN];
seq_printf(seq, "%-8s %-7s %-7s %04d %04d %04d\n",
rt->dst.dev ? rt->dst.dev->name : "*",
dn_addr2asc(le16_to_cpu(rt->rt_daddr), buf1),
dn_addr2asc(le16_to_cpu(rt->rt_saddr), buf2),
atomic_read(&rt->dst.__refcnt),
rt->dst.__use, 0);
return 0;
}
static const struct seq_operations dn_rt_cache_seq_ops = {
.start = dn_rt_cache_seq_start,
.next = dn_rt_cache_seq_next,
.stop = dn_rt_cache_seq_stop,
.show = dn_rt_cache_seq_show,
};
static int dn_rt_cache_seq_open(struct inode *inode, struct file *file)
{
return seq_open_private(file, &dn_rt_cache_seq_ops,
sizeof(struct dn_rt_cache_iter_state));
}
static const struct file_operations dn_rt_cache_seq_fops = {
.owner = THIS_MODULE,
.open = dn_rt_cache_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_private,
};
#endif /* CONFIG_PROC_FS */
void __init dn_route_init(void)
{
int i, goal, order;
dn_dst_ops.kmem_cachep =
kmem_cache_create("dn_dst_cache", sizeof(struct dn_route), 0,
SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL);
dst_entries_init(&dn_dst_ops);
setup_timer(&dn_route_timer, dn_dst_check_expire, 0);
dn_route_timer.expires = jiffies + decnet_dst_gc_interval * HZ;
add_timer(&dn_route_timer);
goal = totalram_pages >> (26 - PAGE_SHIFT);
for(order = 0; (1UL << order) < goal; order++)
/* NOTHING */;
/*
* Only want 1024 entries max, since the table is very, very unlikely
* to be larger than that.
*/
while(order && ((((1UL << order) * PAGE_SIZE) /
sizeof(struct dn_rt_hash_bucket)) >= 2048))
order--;
do {
dn_rt_hash_mask = (1UL << order) * PAGE_SIZE /
sizeof(struct dn_rt_hash_bucket);
while(dn_rt_hash_mask & (dn_rt_hash_mask - 1))
dn_rt_hash_mask--;
dn_rt_hash_table = (struct dn_rt_hash_bucket *)
__get_free_pages(GFP_ATOMIC, order);
} while (dn_rt_hash_table == NULL && --order > 0);
if (!dn_rt_hash_table)
panic("Failed to allocate DECnet route cache hash table\n");
printk(KERN_INFO
"DECnet: Routing cache hash table of %u buckets, %ldKbytes\n",
dn_rt_hash_mask,
(long)(dn_rt_hash_mask*sizeof(struct dn_rt_hash_bucket))/1024);
dn_rt_hash_mask--;
for(i = 0; i <= dn_rt_hash_mask; i++) {
spin_lock_init(&dn_rt_hash_table[i].lock);
dn_rt_hash_table[i].chain = NULL;
}
dn_dst_ops.gc_thresh = (dn_rt_hash_mask + 1);
proc_create("decnet_cache", S_IRUGO, init_net.proc_net,
&dn_rt_cache_seq_fops);
#ifdef CONFIG_DECNET_ROUTER
rtnl_register(PF_DECnet, RTM_GETROUTE, dn_cache_getroute,
dn_fib_dump, NULL);
#else
rtnl_register(PF_DECnet, RTM_GETROUTE, dn_cache_getroute,
dn_cache_dump, NULL);
#endif
}
void __exit dn_route_cleanup(void)
{
del_timer(&dn_route_timer);
dn_run_flush(0);
remove_proc_entry("decnet_cache", init_net.proc_net);
dst_entries_destroy(&dn_dst_ops);
}
| gpl-2.0 |
antonizoon/linux_on_wince_htc | drivers/staging/pohmelfs/crypto.c | 608 | 19937 | /*
* 2007+ Copyright (c) Evgeniy Polyakov <zbr@ioremap.net>
* 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.
*/
#include <linux/crypto.h>
#include <linux/highmem.h>
#include <linux/kthread.h>
#include <linux/pagemap.h>
#include <linux/slab.h>
#include "netfs.h"
static struct crypto_hash *pohmelfs_init_hash(struct pohmelfs_sb *psb)
{
int err;
struct crypto_hash *hash;
hash = crypto_alloc_hash(psb->hash_string, 0, CRYPTO_ALG_ASYNC);
if (IS_ERR(hash)) {
err = PTR_ERR(hash);
dprintk("%s: idx: %u: failed to allocate hash '%s', err: %d.\n",
__func__, psb->idx, psb->hash_string, err);
goto err_out_exit;
}
psb->crypto_attached_size = crypto_hash_digestsize(hash);
if (!psb->hash_keysize)
return hash;
err = crypto_hash_setkey(hash, psb->hash_key, psb->hash_keysize);
if (err) {
dprintk("%s: idx: %u: failed to set key for hash '%s', err: %d.\n",
__func__, psb->idx, psb->hash_string, err);
goto err_out_free;
}
return hash;
err_out_free:
crypto_free_hash(hash);
err_out_exit:
return ERR_PTR(err);
}
static struct crypto_ablkcipher *pohmelfs_init_cipher(struct pohmelfs_sb *psb)
{
int err = -EINVAL;
struct crypto_ablkcipher *cipher;
if (!psb->cipher_keysize)
goto err_out_exit;
cipher = crypto_alloc_ablkcipher(psb->cipher_string, 0, 0);
if (IS_ERR(cipher)) {
err = PTR_ERR(cipher);
dprintk("%s: idx: %u: failed to allocate cipher '%s', err: %d.\n",
__func__, psb->idx, psb->cipher_string, err);
goto err_out_exit;
}
crypto_ablkcipher_clear_flags(cipher, ~0);
err = crypto_ablkcipher_setkey(cipher, psb->cipher_key, psb->cipher_keysize);
if (err) {
dprintk("%s: idx: %u: failed to set key for cipher '%s', err: %d.\n",
__func__, psb->idx, psb->cipher_string, err);
goto err_out_free;
}
return cipher;
err_out_free:
crypto_free_ablkcipher(cipher);
err_out_exit:
return ERR_PTR(err);
}
int pohmelfs_crypto_engine_init(struct pohmelfs_crypto_engine *e, struct pohmelfs_sb *psb)
{
int err;
e->page_num = 0;
e->size = PAGE_SIZE;
e->data = kmalloc(e->size, GFP_KERNEL);
if (!e->data) {
err = -ENOMEM;
goto err_out_exit;
}
if (psb->hash_string) {
e->hash = pohmelfs_init_hash(psb);
if (IS_ERR(e->hash)) {
err = PTR_ERR(e->hash);
e->hash = NULL;
goto err_out_free;
}
}
if (psb->cipher_string) {
e->cipher = pohmelfs_init_cipher(psb);
if (IS_ERR(e->cipher)) {
err = PTR_ERR(e->cipher);
e->cipher = NULL;
goto err_out_free_hash;
}
}
return 0;
err_out_free_hash:
crypto_free_hash(e->hash);
err_out_free:
kfree(e->data);
err_out_exit:
return err;
}
void pohmelfs_crypto_engine_exit(struct pohmelfs_crypto_engine *e)
{
if (e->hash)
crypto_free_hash(e->hash);
if (e->cipher)
crypto_free_ablkcipher(e->cipher);
kfree(e->data);
}
static void pohmelfs_crypto_complete(struct crypto_async_request *req, int err)
{
struct pohmelfs_crypto_completion *c = req->data;
if (err == -EINPROGRESS)
return;
dprintk("%s: req: %p, err: %d.\n", __func__, req, err);
c->error = err;
complete(&c->complete);
}
static int pohmelfs_crypto_process(struct ablkcipher_request *req,
struct scatterlist *sg_dst, struct scatterlist *sg_src,
void *iv, int enc, unsigned long timeout)
{
struct pohmelfs_crypto_completion complete;
int err;
init_completion(&complete.complete);
complete.error = -EINPROGRESS;
ablkcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG,
pohmelfs_crypto_complete, &complete);
ablkcipher_request_set_crypt(req, sg_src, sg_dst, sg_src->length, iv);
if (enc)
err = crypto_ablkcipher_encrypt(req);
else
err = crypto_ablkcipher_decrypt(req);
switch (err) {
case -EINPROGRESS:
case -EBUSY:
err = wait_for_completion_interruptible_timeout(&complete.complete,
timeout);
if (!err)
err = -ETIMEDOUT;
else if (err > 0)
err = complete.error;
break;
default:
break;
}
return err;
}
int pohmelfs_crypto_process_input_data(struct pohmelfs_crypto_engine *e, u64 cmd_iv,
void *data, struct page *page, unsigned int size)
{
int err;
struct scatterlist sg;
if (!e->cipher && !e->hash)
return 0;
dprintk("%s: eng: %p, iv: %llx, data: %p, page: %p/%lu, size: %u.\n",
__func__, e, cmd_iv, data, page, (page)?page->index:0, size);
if (data) {
sg_init_one(&sg, data, size);
} else {
sg_init_table(&sg, 1);
sg_set_page(&sg, page, size, 0);
}
if (e->cipher) {
struct ablkcipher_request *req = e->data + crypto_hash_digestsize(e->hash);
u8 iv[32];
memset(iv, 0, sizeof(iv));
memcpy(iv, &cmd_iv, sizeof(cmd_iv));
ablkcipher_request_set_tfm(req, e->cipher);
err = pohmelfs_crypto_process(req, &sg, &sg, iv, 0, e->timeout);
if (err)
goto err_out_exit;
}
if (e->hash) {
struct hash_desc desc;
void *dst = e->data + e->size/2;
desc.tfm = e->hash;
desc.flags = 0;
err = crypto_hash_init(&desc);
if (err)
goto err_out_exit;
err = crypto_hash_update(&desc, &sg, size);
if (err)
goto err_out_exit;
err = crypto_hash_final(&desc, dst);
if (err)
goto err_out_exit;
err = !!memcmp(dst, e->data, crypto_hash_digestsize(e->hash));
if (err) {
#ifdef CONFIG_POHMELFS_DEBUG
unsigned int i;
unsigned char *recv = e->data, *calc = dst;
dprintk("%s: eng: %p, hash: %p, cipher: %p: iv : %llx, hash mismatch (recv/calc): ",
__func__, e, e->hash, e->cipher, cmd_iv);
for (i=0; i<crypto_hash_digestsize(e->hash); ++i) {
#if 0
dprintka("%02x ", recv[i]);
if (recv[i] != calc[i]) {
dprintka("| calc byte: %02x.\n", calc[i]);
break;
}
#else
dprintka("%02x/%02x ", recv[i], calc[i]);
#endif
}
dprintk("\n");
#endif
goto err_out_exit;
} else {
dprintk("%s: eng: %p, hash: %p, cipher: %p: hashes matched.\n",
__func__, e, e->hash, e->cipher);
}
}
dprintk("%s: eng: %p, size: %u, hash: %p, cipher: %p: completed.\n",
__func__, e, e->size, e->hash, e->cipher);
return 0;
err_out_exit:
dprintk("%s: eng: %p, hash: %p, cipher: %p: err: %d.\n",
__func__, e, e->hash, e->cipher, err);
return err;
}
static int pohmelfs_trans_iter(struct netfs_trans *t, struct pohmelfs_crypto_engine *e,
int (* iterator) (struct pohmelfs_crypto_engine *e,
struct scatterlist *dst,
struct scatterlist *src))
{
void *data = t->iovec.iov_base + sizeof(struct netfs_cmd) + t->psb->crypto_attached_size;
unsigned int size = t->iovec.iov_len - sizeof(struct netfs_cmd) - t->psb->crypto_attached_size;
struct netfs_cmd *cmd = data;
unsigned int sz, pages = t->attached_pages, i, csize, cmd_cmd, dpage_idx;
struct scatterlist sg_src, sg_dst;
int err;
while (size) {
cmd = data;
cmd_cmd = __be16_to_cpu(cmd->cmd);
csize = __be32_to_cpu(cmd->size);
cmd->iv = __cpu_to_be64(e->iv);
if (cmd_cmd == NETFS_READ_PAGES || cmd_cmd == NETFS_READ_PAGE)
csize = __be16_to_cpu(cmd->ext);
sz = csize + __be16_to_cpu(cmd->cpad) + sizeof(struct netfs_cmd);
dprintk("%s: size: %u, sz: %u, cmd_size: %u, cmd_cpad: %u.\n",
__func__, size, sz, __be32_to_cpu(cmd->size), __be16_to_cpu(cmd->cpad));
data += sz;
size -= sz;
sg_init_one(&sg_src, cmd->data, sz - sizeof(struct netfs_cmd));
sg_init_one(&sg_dst, cmd->data, sz - sizeof(struct netfs_cmd));
err = iterator(e, &sg_dst, &sg_src);
if (err)
return err;
}
if (!pages)
return 0;
dpage_idx = 0;
for (i=0; i<t->page_num; ++i) {
struct page *page = t->pages[i];
struct page *dpage = e->pages[dpage_idx];
if (!page)
continue;
sg_init_table(&sg_src, 1);
sg_init_table(&sg_dst, 1);
sg_set_page(&sg_src, page, page_private(page), 0);
sg_set_page(&sg_dst, dpage, page_private(page), 0);
err = iterator(e, &sg_dst, &sg_src);
if (err)
return err;
pages--;
if (!pages)
break;
dpage_idx++;
}
return 0;
}
static int pohmelfs_encrypt_iterator(struct pohmelfs_crypto_engine *e,
struct scatterlist *sg_dst, struct scatterlist *sg_src)
{
struct ablkcipher_request *req = e->data;
u8 iv[32];
memset(iv, 0, sizeof(iv));
memcpy(iv, &e->iv, sizeof(e->iv));
return pohmelfs_crypto_process(req, sg_dst, sg_src, iv, 1, e->timeout);
}
static int pohmelfs_encrypt(struct pohmelfs_crypto_thread *tc)
{
struct netfs_trans *t = tc->trans;
struct pohmelfs_crypto_engine *e = &tc->eng;
struct ablkcipher_request *req = e->data;
memset(req, 0, sizeof(struct ablkcipher_request));
ablkcipher_request_set_tfm(req, e->cipher);
e->iv = pohmelfs_gen_iv(t);
return pohmelfs_trans_iter(t, e, pohmelfs_encrypt_iterator);
}
static int pohmelfs_hash_iterator(struct pohmelfs_crypto_engine *e,
struct scatterlist *sg_dst, struct scatterlist *sg_src)
{
return crypto_hash_update(e->data, sg_src, sg_src->length);
}
static int pohmelfs_hash(struct pohmelfs_crypto_thread *tc)
{
struct pohmelfs_crypto_engine *e = &tc->eng;
struct hash_desc *desc = e->data;
unsigned char *dst = tc->trans->iovec.iov_base + sizeof(struct netfs_cmd);
int err;
desc->tfm = e->hash;
desc->flags = 0;
err = crypto_hash_init(desc);
if (err)
return err;
err = pohmelfs_trans_iter(tc->trans, e, pohmelfs_hash_iterator);
if (err)
return err;
err = crypto_hash_final(desc, dst);
if (err)
return err;
{
unsigned int i;
dprintk("%s: ", __func__);
for (i=0; i<tc->psb->crypto_attached_size; ++i)
dprintka("%02x ", dst[i]);
dprintka("\n");
}
return 0;
}
static void pohmelfs_crypto_pages_free(struct pohmelfs_crypto_engine *e)
{
unsigned int i;
for (i=0; i<e->page_num; ++i)
__free_page(e->pages[i]);
kfree(e->pages);
}
static int pohmelfs_crypto_pages_alloc(struct pohmelfs_crypto_engine *e, struct pohmelfs_sb *psb)
{
unsigned int i;
e->pages = kmalloc(psb->trans_max_pages * sizeof(struct page *), GFP_KERNEL);
if (!e->pages)
return -ENOMEM;
for (i=0; i<psb->trans_max_pages; ++i) {
e->pages[i] = alloc_page(GFP_KERNEL);
if (!e->pages[i])
break;
}
e->page_num = i;
if (!e->page_num)
goto err_out_free;
return 0;
err_out_free:
kfree(e->pages);
return -ENOMEM;
}
static void pohmelfs_sys_crypto_exit_one(struct pohmelfs_crypto_thread *t)
{
struct pohmelfs_sb *psb = t->psb;
if (t->thread)
kthread_stop(t->thread);
mutex_lock(&psb->crypto_thread_lock);
list_del(&t->thread_entry);
psb->crypto_thread_num--;
mutex_unlock(&psb->crypto_thread_lock);
pohmelfs_crypto_engine_exit(&t->eng);
pohmelfs_crypto_pages_free(&t->eng);
kfree(t);
}
static int pohmelfs_crypto_finish(struct netfs_trans *t, struct pohmelfs_sb *psb, int err)
{
struct netfs_cmd *cmd = t->iovec.iov_base;
netfs_convert_cmd(cmd);
if (likely(!err))
err = netfs_trans_finish_send(t, psb);
t->result = err;
netfs_trans_put(t);
return err;
}
void pohmelfs_crypto_thread_make_ready(struct pohmelfs_crypto_thread *th)
{
struct pohmelfs_sb *psb = th->psb;
th->page = NULL;
th->trans = NULL;
mutex_lock(&psb->crypto_thread_lock);
list_move_tail(&th->thread_entry, &psb->crypto_ready_list);
mutex_unlock(&psb->crypto_thread_lock);
wake_up(&psb->wait);
}
static int pohmelfs_crypto_thread_trans(struct pohmelfs_crypto_thread *t)
{
struct netfs_trans *trans;
int err = 0;
trans = t->trans;
trans->eng = NULL;
if (t->eng.hash) {
err = pohmelfs_hash(t);
if (err)
goto out_complete;
}
if (t->eng.cipher) {
err = pohmelfs_encrypt(t);
if (err)
goto out_complete;
trans->eng = &t->eng;
}
out_complete:
t->page = NULL;
t->trans = NULL;
if (!trans->eng)
pohmelfs_crypto_thread_make_ready(t);
pohmelfs_crypto_finish(trans, t->psb, err);
return err;
}
static int pohmelfs_crypto_thread_page(struct pohmelfs_crypto_thread *t)
{
struct pohmelfs_crypto_engine *e = &t->eng;
struct page *page = t->page;
int err;
WARN_ON(!PageChecked(page));
err = pohmelfs_crypto_process_input_data(e, e->iv, NULL, page, t->size);
if (!err)
SetPageUptodate(page);
else
SetPageError(page);
unlock_page(page);
page_cache_release(page);
pohmelfs_crypto_thread_make_ready(t);
return err;
}
static int pohmelfs_crypto_thread_func(void *data)
{
struct pohmelfs_crypto_thread *t = data;
while (!kthread_should_stop()) {
wait_event_interruptible(t->wait, kthread_should_stop() ||
t->trans || t->page);
if (kthread_should_stop())
break;
if (!t->trans && !t->page)
continue;
dprintk("%s: thread: %p, trans: %p, page: %p.\n",
__func__, t, t->trans, t->page);
if (t->trans)
pohmelfs_crypto_thread_trans(t);
else if (t->page)
pohmelfs_crypto_thread_page(t);
}
return 0;
}
static void pohmelfs_crypto_flush(struct pohmelfs_sb *psb, struct list_head *head)
{
while (!list_empty(head)) {
struct pohmelfs_crypto_thread *t = NULL;
mutex_lock(&psb->crypto_thread_lock);
if (!list_empty(head)) {
t = list_first_entry(head, struct pohmelfs_crypto_thread, thread_entry);
list_del_init(&t->thread_entry);
}
mutex_unlock(&psb->crypto_thread_lock);
if (t)
pohmelfs_sys_crypto_exit_one(t);
}
}
static void pohmelfs_sys_crypto_exit(struct pohmelfs_sb *psb)
{
while (!list_empty(&psb->crypto_active_list) || !list_empty(&psb->crypto_ready_list)) {
dprintk("%s: crypto_thread_num: %u.\n", __func__, psb->crypto_thread_num);
pohmelfs_crypto_flush(psb, &psb->crypto_active_list);
pohmelfs_crypto_flush(psb, &psb->crypto_ready_list);
}
}
static int pohmelfs_sys_crypto_init(struct pohmelfs_sb *psb)
{
unsigned int i;
struct pohmelfs_crypto_thread *t;
struct pohmelfs_config *c;
struct netfs_state *st;
int err;
list_for_each_entry(c, &psb->state_list, config_entry) {
st = &c->state;
err = pohmelfs_crypto_engine_init(&st->eng, psb);
if (err)
goto err_out_exit;
dprintk("%s: st: %p, eng: %p, hash: %p, cipher: %p.\n",
__func__, st, &st->eng, &st->eng.hash, &st->eng.cipher);
}
for (i=0; i<psb->crypto_thread_num; ++i) {
err = -ENOMEM;
t = kzalloc(sizeof(struct pohmelfs_crypto_thread), GFP_KERNEL);
if (!t)
goto err_out_free_state_engines;
init_waitqueue_head(&t->wait);
t->psb = psb;
t->trans = NULL;
t->eng.thread = t;
err = pohmelfs_crypto_engine_init(&t->eng, psb);
if (err)
goto err_out_free_state_engines;
err = pohmelfs_crypto_pages_alloc(&t->eng, psb);
if (err)
goto err_out_free;
t->thread = kthread_run(pohmelfs_crypto_thread_func, t,
"pohmelfs-crypto-%d-%d", psb->idx, i);
if (IS_ERR(t->thread)) {
err = PTR_ERR(t->thread);
t->thread = NULL;
goto err_out_free;
}
if (t->eng.cipher)
psb->crypto_align_size = crypto_ablkcipher_blocksize(t->eng.cipher);
mutex_lock(&psb->crypto_thread_lock);
list_add_tail(&t->thread_entry, &psb->crypto_ready_list);
mutex_unlock(&psb->crypto_thread_lock);
}
psb->crypto_thread_num = i;
return 0;
err_out_free:
pohmelfs_sys_crypto_exit_one(t);
err_out_free_state_engines:
list_for_each_entry(c, &psb->state_list, config_entry) {
st = &c->state;
pohmelfs_crypto_engine_exit(&st->eng);
}
err_out_exit:
pohmelfs_sys_crypto_exit(psb);
return err;
}
void pohmelfs_crypto_exit(struct pohmelfs_sb *psb)
{
pohmelfs_sys_crypto_exit(psb);
kfree(psb->hash_string);
kfree(psb->cipher_string);
}
static int pohmelfs_crypt_init_complete(struct page **pages, unsigned int page_num,
void *private, int err)
{
struct pohmelfs_sb *psb = private;
psb->flags = -err;
dprintk("%s: err: %d.\n", __func__, err);
wake_up(&psb->wait);
return err;
}
static int pohmelfs_crypto_init_handshake(struct pohmelfs_sb *psb)
{
struct netfs_trans *t;
struct netfs_crypto_capabilities *cap;
struct netfs_cmd *cmd;
char *str;
int err = -ENOMEM, size;
size = sizeof(struct netfs_crypto_capabilities) +
psb->cipher_strlen + psb->hash_strlen + 2; /* 0 bytes */
t = netfs_trans_alloc(psb, size, 0, 0);
if (!t)
goto err_out_exit;
t->complete = pohmelfs_crypt_init_complete;
t->private = psb;
cmd = netfs_trans_current(t);
cap = (struct netfs_crypto_capabilities *)(cmd + 1);
str = (char *)(cap + 1);
cmd->cmd = NETFS_CAPABILITIES;
cmd->id = POHMELFS_CRYPTO_CAPABILITIES;
cmd->size = size;
cmd->start = 0;
cmd->ext = 0;
cmd->csize = 0;
netfs_convert_cmd(cmd);
netfs_trans_update(cmd, t, size);
cap->hash_strlen = psb->hash_strlen;
if (cap->hash_strlen) {
sprintf(str, "%s", psb->hash_string);
str += cap->hash_strlen;
}
cap->cipher_strlen = psb->cipher_strlen;
cap->cipher_keysize = psb->cipher_keysize;
if (cap->cipher_strlen)
sprintf(str, "%s", psb->cipher_string);
netfs_convert_crypto_capabilities(cap);
psb->flags = ~0;
err = netfs_trans_finish(t, psb);
if (err)
goto err_out_exit;
err = wait_event_interruptible_timeout(psb->wait, (psb->flags != ~0),
psb->wait_on_page_timeout);
if (!err)
err = -ETIMEDOUT;
else if (err > 0)
err = -psb->flags;
if (!err)
psb->perform_crypto = 1;
psb->flags = 0;
/*
* At this point NETFS_CAPABILITIES response command
* should setup superblock in a way, which is acceptible
* for both client and server, so if server refuses connection,
* it will send error in transaction response.
*/
if (err)
goto err_out_exit;
return 0;
err_out_exit:
return err;
}
int pohmelfs_crypto_init(struct pohmelfs_sb *psb)
{
int err;
if (!psb->cipher_string && !psb->hash_string)
return 0;
err = pohmelfs_crypto_init_handshake(psb);
if (err)
return err;
err = pohmelfs_sys_crypto_init(psb);
if (err)
return err;
return 0;
}
static int pohmelfs_crypto_thread_get(struct pohmelfs_sb *psb,
int (* action)(struct pohmelfs_crypto_thread *t, void *data), void *data)
{
struct pohmelfs_crypto_thread *t = NULL;
int err;
while (!t) {
err = wait_event_interruptible_timeout(psb->wait,
!list_empty(&psb->crypto_ready_list),
psb->wait_on_page_timeout);
t = NULL;
err = 0;
mutex_lock(&psb->crypto_thread_lock);
if (!list_empty(&psb->crypto_ready_list)) {
t = list_entry(psb->crypto_ready_list.prev,
struct pohmelfs_crypto_thread,
thread_entry);
list_move_tail(&t->thread_entry,
&psb->crypto_active_list);
action(t, data);
wake_up(&t->wait);
}
mutex_unlock(&psb->crypto_thread_lock);
}
return err;
}
static int pohmelfs_trans_crypt_action(struct pohmelfs_crypto_thread *t, void *data)
{
struct netfs_trans *trans = data;
netfs_trans_get(trans);
t->trans = trans;
dprintk("%s: t: %p, gen: %u, thread: %p.\n", __func__, trans, trans->gen, t);
return 0;
}
int pohmelfs_trans_crypt(struct netfs_trans *trans, struct pohmelfs_sb *psb)
{
if ((!psb->hash_string && !psb->cipher_string) || !psb->perform_crypto) {
netfs_trans_get(trans);
return pohmelfs_crypto_finish(trans, psb, 0);
}
return pohmelfs_crypto_thread_get(psb, pohmelfs_trans_crypt_action, trans);
}
struct pohmelfs_crypto_input_action_data {
struct page *page;
struct pohmelfs_crypto_engine *e;
u64 iv;
unsigned int size;
};
static int pohmelfs_crypt_input_page_action(struct pohmelfs_crypto_thread *t, void *data)
{
struct pohmelfs_crypto_input_action_data *act = data;
memcpy(t->eng.data, act->e->data, t->psb->crypto_attached_size);
t->size = act->size;
t->eng.iv = act->iv;
t->page = act->page;
return 0;
}
int pohmelfs_crypto_process_input_page(struct pohmelfs_crypto_engine *e,
struct page *page, unsigned int size, u64 iv)
{
struct inode *inode = page->mapping->host;
struct pohmelfs_crypto_input_action_data act;
int err = -ENOENT;
act.page = page;
act.e = e;
act.size = size;
act.iv = iv;
err = pohmelfs_crypto_thread_get(POHMELFS_SB(inode->i_sb),
pohmelfs_crypt_input_page_action, &act);
if (err)
goto err_out_exit;
return 0;
err_out_exit:
SetPageUptodate(page);
page_cache_release(page);
return err;
}
| gpl-2.0 |
Flinny/kernel_htc_msm8994 | drivers/thermal/spear_thermal.c | 2144 | 5503 | /*
* SPEAr thermal driver.
*
* Copyright (C) 2011-2012 ST Microelectronics
* Author: Vincenzo Frascino <vincenzo.frascino@st.com>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/clk.h>
#include <linux/device.h>
#include <linux/err.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/of.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/thermal.h>
#define MD_FACTOR 1000
/* SPEAr Thermal Sensor Dev Structure */
struct spear_thermal_dev {
/* pointer to base address of the thermal sensor */
void __iomem *thermal_base;
/* clk structure */
struct clk *clk;
/* pointer to thermal flags */
unsigned int flags;
};
static inline int thermal_get_temp(struct thermal_zone_device *thermal,
unsigned long *temp)
{
struct spear_thermal_dev *stdev = thermal->devdata;
/*
* Data are ready to be read after 628 usec from POWERDOWN signal
* (PDN) = 1
*/
*temp = (readl_relaxed(stdev->thermal_base) & 0x7F) * MD_FACTOR;
return 0;
}
static struct thermal_zone_device_ops ops = {
.get_temp = thermal_get_temp,
};
#ifdef CONFIG_PM
static int spear_thermal_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct thermal_zone_device *spear_thermal = platform_get_drvdata(pdev);
struct spear_thermal_dev *stdev = spear_thermal->devdata;
unsigned int actual_mask = 0;
/* Disable SPEAr Thermal Sensor */
actual_mask = readl_relaxed(stdev->thermal_base);
writel_relaxed(actual_mask & ~stdev->flags, stdev->thermal_base);
clk_disable(stdev->clk);
dev_info(dev, "Suspended.\n");
return 0;
}
static int spear_thermal_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct thermal_zone_device *spear_thermal = platform_get_drvdata(pdev);
struct spear_thermal_dev *stdev = spear_thermal->devdata;
unsigned int actual_mask = 0;
int ret = 0;
ret = clk_enable(stdev->clk);
if (ret) {
dev_err(&pdev->dev, "Can't enable clock\n");
return ret;
}
/* Enable SPEAr Thermal Sensor */
actual_mask = readl_relaxed(stdev->thermal_base);
writel_relaxed(actual_mask | stdev->flags, stdev->thermal_base);
dev_info(dev, "Resumed.\n");
return 0;
}
#endif
static SIMPLE_DEV_PM_OPS(spear_thermal_pm_ops, spear_thermal_suspend,
spear_thermal_resume);
static int spear_thermal_probe(struct platform_device *pdev)
{
struct thermal_zone_device *spear_thermal = NULL;
struct spear_thermal_dev *stdev;
struct device_node *np = pdev->dev.of_node;
struct resource *stres = platform_get_resource(pdev, IORESOURCE_MEM, 0);
int ret = 0, val;
if (!np || !of_property_read_u32(np, "st,thermal-flags", &val)) {
dev_err(&pdev->dev, "Failed: DT Pdata not passed\n");
return -EINVAL;
}
if (!stres) {
dev_err(&pdev->dev, "memory resource missing\n");
return -ENODEV;
}
stdev = devm_kzalloc(&pdev->dev, sizeof(*stdev), GFP_KERNEL);
if (!stdev) {
dev_err(&pdev->dev, "kzalloc fail\n");
return -ENOMEM;
}
/* Enable thermal sensor */
stdev->thermal_base = devm_ioremap(&pdev->dev, stres->start,
resource_size(stres));
if (!stdev->thermal_base) {
dev_err(&pdev->dev, "ioremap failed\n");
return -ENOMEM;
}
stdev->clk = devm_clk_get(&pdev->dev, NULL);
if (IS_ERR(stdev->clk)) {
dev_err(&pdev->dev, "Can't get clock\n");
return PTR_ERR(stdev->clk);
}
ret = clk_enable(stdev->clk);
if (ret) {
dev_err(&pdev->dev, "Can't enable clock\n");
return ret;
}
stdev->flags = val;
writel_relaxed(stdev->flags, stdev->thermal_base);
spear_thermal = thermal_zone_device_register("spear_thermal", 0, 0,
stdev, &ops, NULL, 0, 0);
if (IS_ERR(spear_thermal)) {
dev_err(&pdev->dev, "thermal zone device is NULL\n");
ret = PTR_ERR(spear_thermal);
goto disable_clk;
}
platform_set_drvdata(pdev, spear_thermal);
dev_info(&spear_thermal->device, "Thermal Sensor Loaded at: 0x%p.\n",
stdev->thermal_base);
return 0;
disable_clk:
clk_disable(stdev->clk);
return ret;
}
static int spear_thermal_exit(struct platform_device *pdev)
{
unsigned int actual_mask = 0;
struct thermal_zone_device *spear_thermal = platform_get_drvdata(pdev);
struct spear_thermal_dev *stdev = spear_thermal->devdata;
thermal_zone_device_unregister(spear_thermal);
platform_set_drvdata(pdev, NULL);
/* Disable SPEAr Thermal Sensor */
actual_mask = readl_relaxed(stdev->thermal_base);
writel_relaxed(actual_mask & ~stdev->flags, stdev->thermal_base);
clk_disable(stdev->clk);
return 0;
}
static const struct of_device_id spear_thermal_id_table[] = {
{ .compatible = "st,thermal-spear1340" },
{}
};
MODULE_DEVICE_TABLE(of, spear_thermal_id_table);
static struct platform_driver spear_thermal_driver = {
.probe = spear_thermal_probe,
.remove = spear_thermal_exit,
.driver = {
.name = "spear_thermal",
.owner = THIS_MODULE,
.pm = &spear_thermal_pm_ops,
.of_match_table = of_match_ptr(spear_thermal_id_table),
},
};
module_platform_driver(spear_thermal_driver);
MODULE_AUTHOR("Vincenzo Frascino <vincenzo.frascino@st.com>");
MODULE_DESCRIPTION("SPEAr thermal driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
pio-masaki/kernel_at300 | arch/arm/mach-exynos4/dev-sysmmu.c | 2400 | 5250 | /* linux/arch/arm/mach-exynos4/dev-sysmmu.c
*
* Copyright (c) 2010 Samsung Electronics Co., Ltd.
* http://www.samsung.com
*
* EXYNOS4 - System MMU support
*
* 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/platform_device.h>
#include <linux/dma-mapping.h>
#include <mach/map.h>
#include <mach/irqs.h>
#include <mach/sysmmu.h>
#include <plat/s5p-clock.h>
/* These names must be equal to the clock names in mach-exynos4/clock.c */
const char *sysmmu_ips_name[EXYNOS4_SYSMMU_TOTAL_IPNUM] = {
"SYSMMU_MDMA" ,
"SYSMMU_SSS" ,
"SYSMMU_FIMC0" ,
"SYSMMU_FIMC1" ,
"SYSMMU_FIMC2" ,
"SYSMMU_FIMC3" ,
"SYSMMU_JPEG" ,
"SYSMMU_FIMD0" ,
"SYSMMU_FIMD1" ,
"SYSMMU_PCIe" ,
"SYSMMU_G2D" ,
"SYSMMU_ROTATOR",
"SYSMMU_MDMA2" ,
"SYSMMU_TV" ,
"SYSMMU_MFC_L" ,
"SYSMMU_MFC_R" ,
};
static struct resource exynos4_sysmmu_resource[] = {
[0] = {
.start = EXYNOS4_PA_SYSMMU_MDMA,
.end = EXYNOS4_PA_SYSMMU_MDMA + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_SYSMMU_MDMA0_0,
.end = IRQ_SYSMMU_MDMA0_0,
.flags = IORESOURCE_IRQ,
},
[2] = {
.start = EXYNOS4_PA_SYSMMU_SSS,
.end = EXYNOS4_PA_SYSMMU_SSS + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[3] = {
.start = IRQ_SYSMMU_SSS_0,
.end = IRQ_SYSMMU_SSS_0,
.flags = IORESOURCE_IRQ,
},
[4] = {
.start = EXYNOS4_PA_SYSMMU_FIMC0,
.end = EXYNOS4_PA_SYSMMU_FIMC0 + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[5] = {
.start = IRQ_SYSMMU_FIMC0_0,
.end = IRQ_SYSMMU_FIMC0_0,
.flags = IORESOURCE_IRQ,
},
[6] = {
.start = EXYNOS4_PA_SYSMMU_FIMC1,
.end = EXYNOS4_PA_SYSMMU_FIMC1 + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[7] = {
.start = IRQ_SYSMMU_FIMC1_0,
.end = IRQ_SYSMMU_FIMC1_0,
.flags = IORESOURCE_IRQ,
},
[8] = {
.start = EXYNOS4_PA_SYSMMU_FIMC2,
.end = EXYNOS4_PA_SYSMMU_FIMC2 + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[9] = {
.start = IRQ_SYSMMU_FIMC2_0,
.end = IRQ_SYSMMU_FIMC2_0,
.flags = IORESOURCE_IRQ,
},
[10] = {
.start = EXYNOS4_PA_SYSMMU_FIMC3,
.end = EXYNOS4_PA_SYSMMU_FIMC3 + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[11] = {
.start = IRQ_SYSMMU_FIMC3_0,
.end = IRQ_SYSMMU_FIMC3_0,
.flags = IORESOURCE_IRQ,
},
[12] = {
.start = EXYNOS4_PA_SYSMMU_JPEG,
.end = EXYNOS4_PA_SYSMMU_JPEG + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[13] = {
.start = IRQ_SYSMMU_JPEG_0,
.end = IRQ_SYSMMU_JPEG_0,
.flags = IORESOURCE_IRQ,
},
[14] = {
.start = EXYNOS4_PA_SYSMMU_FIMD0,
.end = EXYNOS4_PA_SYSMMU_FIMD0 + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[15] = {
.start = IRQ_SYSMMU_LCD0_M0_0,
.end = IRQ_SYSMMU_LCD0_M0_0,
.flags = IORESOURCE_IRQ,
},
[16] = {
.start = EXYNOS4_PA_SYSMMU_FIMD1,
.end = EXYNOS4_PA_SYSMMU_FIMD1 + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[17] = {
.start = IRQ_SYSMMU_LCD1_M1_0,
.end = IRQ_SYSMMU_LCD1_M1_0,
.flags = IORESOURCE_IRQ,
},
[18] = {
.start = EXYNOS4_PA_SYSMMU_PCIe,
.end = EXYNOS4_PA_SYSMMU_PCIe + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[19] = {
.start = IRQ_SYSMMU_PCIE_0,
.end = IRQ_SYSMMU_PCIE_0,
.flags = IORESOURCE_IRQ,
},
[20] = {
.start = EXYNOS4_PA_SYSMMU_G2D,
.end = EXYNOS4_PA_SYSMMU_G2D + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[21] = {
.start = IRQ_SYSMMU_2D_0,
.end = IRQ_SYSMMU_2D_0,
.flags = IORESOURCE_IRQ,
},
[22] = {
.start = EXYNOS4_PA_SYSMMU_ROTATOR,
.end = EXYNOS4_PA_SYSMMU_ROTATOR + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[23] = {
.start = IRQ_SYSMMU_ROTATOR_0,
.end = IRQ_SYSMMU_ROTATOR_0,
.flags = IORESOURCE_IRQ,
},
[24] = {
.start = EXYNOS4_PA_SYSMMU_MDMA2,
.end = EXYNOS4_PA_SYSMMU_MDMA2 + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[25] = {
.start = IRQ_SYSMMU_MDMA1_0,
.end = IRQ_SYSMMU_MDMA1_0,
.flags = IORESOURCE_IRQ,
},
[26] = {
.start = EXYNOS4_PA_SYSMMU_TV,
.end = EXYNOS4_PA_SYSMMU_TV + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[27] = {
.start = IRQ_SYSMMU_TV_M0_0,
.end = IRQ_SYSMMU_TV_M0_0,
.flags = IORESOURCE_IRQ,
},
[28] = {
.start = EXYNOS4_PA_SYSMMU_MFC_L,
.end = EXYNOS4_PA_SYSMMU_MFC_L + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[29] = {
.start = IRQ_SYSMMU_MFC_M0_0,
.end = IRQ_SYSMMU_MFC_M0_0,
.flags = IORESOURCE_IRQ,
},
[30] = {
.start = EXYNOS4_PA_SYSMMU_MFC_R,
.end = EXYNOS4_PA_SYSMMU_MFC_R + SZ_64K - 1,
.flags = IORESOURCE_MEM,
},
[31] = {
.start = IRQ_SYSMMU_MFC_M1_0,
.end = IRQ_SYSMMU_MFC_M1_0,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device exynos4_device_sysmmu = {
.name = "s5p-sysmmu",
.id = 32,
.num_resources = ARRAY_SIZE(exynos4_sysmmu_resource),
.resource = exynos4_sysmmu_resource,
};
EXPORT_SYMBOL(exynos4_device_sysmmu);
static struct clk *sysmmu_clk[S5P_SYSMMU_TOTAL_IPNUM];
void sysmmu_clk_init(struct device *dev, sysmmu_ips ips)
{
sysmmu_clk[ips] = clk_get(dev, sysmmu_ips_name[ips]);
if (IS_ERR(sysmmu_clk[ips]))
sysmmu_clk[ips] = NULL;
else
clk_put(sysmmu_clk[ips]);
}
void sysmmu_clk_enable(sysmmu_ips ips)
{
if (sysmmu_clk[ips])
clk_enable(sysmmu_clk[ips]);
}
void sysmmu_clk_disable(sysmmu_ips ips)
{
if (sysmmu_clk[ips])
clk_disable(sysmmu_clk[ips]);
}
| gpl-2.0 |
tonyho/Linux-3.7-TQ2440 | arch/sparc/kernel/hvapi.c | 2656 | 4562 | /* hvapi.c: Hypervisor API management.
*
* Copyright (C) 2007 David S. Miller <davem@davemloft.net>
*/
#include <linux/kernel.h>
#include <linux/export.h>
#include <linux/init.h>
#include <asm/hypervisor.h>
#include <asm/oplib.h>
/* If the hypervisor indicates that the API setting
* calls are unsupported, by returning HV_EBADTRAP or
* HV_ENOTSUPPORTED, we assume that API groups with the
* PRE_API flag set are major 1 minor 0.
*/
struct api_info {
unsigned long group;
unsigned long major;
unsigned long minor;
unsigned int refcnt;
unsigned int flags;
#define FLAG_PRE_API 0x00000001
};
static struct api_info api_table[] = {
{ .group = HV_GRP_SUN4V, .flags = FLAG_PRE_API },
{ .group = HV_GRP_CORE, .flags = FLAG_PRE_API },
{ .group = HV_GRP_INTR, },
{ .group = HV_GRP_SOFT_STATE, },
{ .group = HV_GRP_TM, },
{ .group = HV_GRP_PCI, .flags = FLAG_PRE_API },
{ .group = HV_GRP_LDOM, },
{ .group = HV_GRP_SVC_CHAN, .flags = FLAG_PRE_API },
{ .group = HV_GRP_NCS, .flags = FLAG_PRE_API },
{ .group = HV_GRP_RNG, },
{ .group = HV_GRP_PBOOT, },
{ .group = HV_GRP_TPM, },
{ .group = HV_GRP_SDIO, },
{ .group = HV_GRP_SDIO_ERR, },
{ .group = HV_GRP_REBOOT_DATA, },
{ .group = HV_GRP_NIAG_PERF, .flags = FLAG_PRE_API },
{ .group = HV_GRP_FIRE_PERF, },
{ .group = HV_GRP_N2_CPU, },
{ .group = HV_GRP_NIU, },
{ .group = HV_GRP_VF_CPU, },
{ .group = HV_GRP_KT_CPU, },
{ .group = HV_GRP_VT_CPU, },
{ .group = HV_GRP_DIAG, .flags = FLAG_PRE_API },
};
static DEFINE_SPINLOCK(hvapi_lock);
static struct api_info *__get_info(unsigned long group)
{
int i;
for (i = 0; i < ARRAY_SIZE(api_table); i++) {
if (api_table[i].group == group)
return &api_table[i];
}
return NULL;
}
static void __get_ref(struct api_info *p)
{
p->refcnt++;
}
static void __put_ref(struct api_info *p)
{
if (--p->refcnt == 0) {
unsigned long ignore;
sun4v_set_version(p->group, 0, 0, &ignore);
p->major = p->minor = 0;
}
}
/* Register a hypervisor API specification. It indicates the
* API group and desired major+minor.
*
* If an existing API registration exists '0' (success) will
* be returned if it is compatible with the one being registered.
* Otherwise a negative error code will be returned.
*
* Otherwise an attempt will be made to negotiate the requested
* API group/major/minor with the hypervisor, and errors returned
* if that does not succeed.
*/
int sun4v_hvapi_register(unsigned long group, unsigned long major,
unsigned long *minor)
{
struct api_info *p;
unsigned long flags;
int ret;
spin_lock_irqsave(&hvapi_lock, flags);
p = __get_info(group);
ret = -EINVAL;
if (p) {
if (p->refcnt) {
ret = -EINVAL;
if (p->major == major) {
*minor = p->minor;
ret = 0;
}
} else {
unsigned long actual_minor;
unsigned long hv_ret;
hv_ret = sun4v_set_version(group, major, *minor,
&actual_minor);
ret = -EINVAL;
if (hv_ret == HV_EOK) {
*minor = actual_minor;
p->major = major;
p->minor = actual_minor;
ret = 0;
} else if (hv_ret == HV_EBADTRAP ||
hv_ret == HV_ENOTSUPPORTED) {
if (p->flags & FLAG_PRE_API) {
if (major == 1) {
p->major = 1;
p->minor = 0;
*minor = 0;
ret = 0;
}
}
}
}
if (ret == 0)
__get_ref(p);
}
spin_unlock_irqrestore(&hvapi_lock, flags);
return ret;
}
EXPORT_SYMBOL(sun4v_hvapi_register);
void sun4v_hvapi_unregister(unsigned long group)
{
struct api_info *p;
unsigned long flags;
spin_lock_irqsave(&hvapi_lock, flags);
p = __get_info(group);
if (p)
__put_ref(p);
spin_unlock_irqrestore(&hvapi_lock, flags);
}
EXPORT_SYMBOL(sun4v_hvapi_unregister);
int sun4v_hvapi_get(unsigned long group,
unsigned long *major,
unsigned long *minor)
{
struct api_info *p;
unsigned long flags;
int ret;
spin_lock_irqsave(&hvapi_lock, flags);
ret = -EINVAL;
p = __get_info(group);
if (p && p->refcnt) {
*major = p->major;
*minor = p->minor;
ret = 0;
}
spin_unlock_irqrestore(&hvapi_lock, flags);
return ret;
}
EXPORT_SYMBOL(sun4v_hvapi_get);
void __init sun4v_hvapi_init(void)
{
unsigned long group, major, minor;
group = HV_GRP_SUN4V;
major = 1;
minor = 0;
if (sun4v_hvapi_register(group, major, &minor))
goto bad;
group = HV_GRP_CORE;
major = 1;
minor = 1;
if (sun4v_hvapi_register(group, major, &minor))
goto bad;
return;
bad:
prom_printf("HVAPI: Cannot register API group "
"%lx with major(%lu) minor(%lu)\n",
group, major, minor);
prom_halt();
}
| gpl-2.0 |
infected-lp/android_kernel_sony_msm | drivers/hid/hid-uclogic.c | 3168 | 33813 | /*
* HID driver for UC-Logic devices not fully compliant with HID standard
*
* Copyright (c) 2010 Nikolai Kondrashov
*/
/*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*/
#include <linux/device.h>
#include <linux/hid.h>
#include <linux/module.h>
#include <linux/usb.h>
#include "hid-ids.h"
/*
* See WPXXXXU model descriptions, device and HID report descriptors at
* http://sf.net/apps/mediawiki/digimend/?title=UC-Logic_Tablet_WP4030U
* http://sf.net/apps/mediawiki/digimend/?title=UC-Logic_Tablet_WP5540U
* http://sf.net/apps/mediawiki/digimend/?title=UC-Logic_Tablet_WP8060U
*/
/* Size of the original descriptor of WPXXXXU tablets */
#define WPXXXXU_RDESC_ORIG_SIZE 212
/* Fixed WP4030U report descriptor */
static __u8 wp4030u_rdesc_fixed[] = {
0x05, 0x0D, /* Usage Page (Digitizer), */
0x09, 0x02, /* Usage (Pen), */
0xA1, 0x01, /* Collection (Application), */
0x85, 0x09, /* Report ID (9), */
0x09, 0x20, /* Usage (Stylus), */
0xA0, /* Collection (Physical), */
0x75, 0x01, /* Report Size (1), */
0x09, 0x42, /* Usage (Tip Switch), */
0x09, 0x44, /* Usage (Barrel Switch), */
0x09, 0x46, /* Usage (Tablet Pick), */
0x14, /* Logical Minimum (0), */
0x25, 0x01, /* Logical Maximum (1), */
0x95, 0x03, /* Report Count (3), */
0x81, 0x02, /* Input (Variable), */
0x95, 0x05, /* Report Count (5), */
0x81, 0x01, /* Input (Constant), */
0x75, 0x10, /* Report Size (16), */
0x95, 0x01, /* Report Count (1), */
0x14, /* Logical Minimum (0), */
0xA4, /* Push, */
0x05, 0x01, /* Usage Page (Desktop), */
0x55, 0xFD, /* Unit Exponent (-3), */
0x65, 0x13, /* Unit (Inch), */
0x34, /* Physical Minimum (0), */
0x09, 0x30, /* Usage (X), */
0x46, 0xA0, 0x0F, /* Physical Maximum (4000), */
0x26, 0xFF, 0x7F, /* Logical Maximum (32767), */
0x81, 0x02, /* Input (Variable), */
0x09, 0x31, /* Usage (Y), */
0x46, 0xB8, 0x0B, /* Physical Maximum (3000), */
0x26, 0xFF, 0x7F, /* Logical Maximum (32767), */
0x81, 0x02, /* Input (Variable), */
0xB4, /* Pop, */
0x09, 0x30, /* Usage (Tip Pressure), */
0x26, 0xFF, 0x03, /* Logical Maximum (1023), */
0x81, 0x02, /* Input (Variable), */
0xC0, /* End Collection, */
0xC0 /* End Collection */
};
/* Fixed WP5540U report descriptor */
static __u8 wp5540u_rdesc_fixed[] = {
0x05, 0x0D, /* Usage Page (Digitizer), */
0x09, 0x02, /* Usage (Pen), */
0xA1, 0x01, /* Collection (Application), */
0x85, 0x09, /* Report ID (9), */
0x09, 0x20, /* Usage (Stylus), */
0xA0, /* Collection (Physical), */
0x75, 0x01, /* Report Size (1), */
0x09, 0x42, /* Usage (Tip Switch), */
0x09, 0x44, /* Usage (Barrel Switch), */
0x09, 0x46, /* Usage (Tablet Pick), */
0x14, /* Logical Minimum (0), */
0x25, 0x01, /* Logical Maximum (1), */
0x95, 0x03, /* Report Count (3), */
0x81, 0x02, /* Input (Variable), */
0x95, 0x05, /* Report Count (5), */
0x81, 0x01, /* Input (Constant), */
0x75, 0x10, /* Report Size (16), */
0x95, 0x01, /* Report Count (1), */
0x14, /* Logical Minimum (0), */
0xA4, /* Push, */
0x05, 0x01, /* Usage Page (Desktop), */
0x55, 0xFD, /* Unit Exponent (-3), */
0x65, 0x13, /* Unit (Inch), */
0x34, /* Physical Minimum (0), */
0x09, 0x30, /* Usage (X), */
0x46, 0x7C, 0x15, /* Physical Maximum (5500), */
0x26, 0xFF, 0x7F, /* Logical Maximum (32767), */
0x81, 0x02, /* Input (Variable), */
0x09, 0x31, /* Usage (Y), */
0x46, 0xA0, 0x0F, /* Physical Maximum (4000), */
0x26, 0xFF, 0x7F, /* Logical Maximum (32767), */
0x81, 0x02, /* Input (Variable), */
0xB4, /* Pop, */
0x09, 0x30, /* Usage (Tip Pressure), */
0x26, 0xFF, 0x03, /* Logical Maximum (1023), */
0x81, 0x02, /* Input (Variable), */
0xC0, /* End Collection, */
0xC0, /* End Collection, */
0x05, 0x01, /* Usage Page (Desktop), */
0x09, 0x02, /* Usage (Mouse), */
0xA1, 0x01, /* Collection (Application), */
0x85, 0x08, /* Report ID (8), */
0x09, 0x01, /* Usage (Pointer), */
0xA0, /* Collection (Physical), */
0x75, 0x01, /* Report Size (1), */
0x05, 0x09, /* Usage Page (Button), */
0x19, 0x01, /* Usage Minimum (01h), */
0x29, 0x03, /* Usage Maximum (03h), */
0x14, /* Logical Minimum (0), */
0x25, 0x01, /* Logical Maximum (1), */
0x95, 0x03, /* Report Count (3), */
0x81, 0x02, /* Input (Variable), */
0x95, 0x05, /* Report Count (5), */
0x81, 0x01, /* Input (Constant), */
0x05, 0x01, /* Usage Page (Desktop), */
0x75, 0x08, /* Report Size (8), */
0x09, 0x30, /* Usage (X), */
0x09, 0x31, /* Usage (Y), */
0x15, 0x81, /* Logical Minimum (-127), */
0x25, 0x7F, /* Logical Maximum (127), */
0x95, 0x02, /* Report Count (2), */
0x81, 0x06, /* Input (Variable, Relative), */
0x09, 0x38, /* Usage (Wheel), */
0x15, 0xFF, /* Logical Minimum (-1), */
0x25, 0x01, /* Logical Maximum (1), */
0x95, 0x01, /* Report Count (1), */
0x81, 0x06, /* Input (Variable, Relative), */
0x81, 0x01, /* Input (Constant), */
0xC0, /* End Collection, */
0xC0 /* End Collection */
};
/* Fixed WP8060U report descriptor */
static __u8 wp8060u_rdesc_fixed[] = {
0x05, 0x0D, /* Usage Page (Digitizer), */
0x09, 0x02, /* Usage (Pen), */
0xA1, 0x01, /* Collection (Application), */
0x85, 0x09, /* Report ID (9), */
0x09, 0x20, /* Usage (Stylus), */
0xA0, /* Collection (Physical), */
0x75, 0x01, /* Report Size (1), */
0x09, 0x42, /* Usage (Tip Switch), */
0x09, 0x44, /* Usage (Barrel Switch), */
0x09, 0x46, /* Usage (Tablet Pick), */
0x14, /* Logical Minimum (0), */
0x25, 0x01, /* Logical Maximum (1), */
0x95, 0x03, /* Report Count (3), */
0x81, 0x02, /* Input (Variable), */
0x95, 0x05, /* Report Count (5), */
0x81, 0x01, /* Input (Constant), */
0x75, 0x10, /* Report Size (16), */
0x95, 0x01, /* Report Count (1), */
0x14, /* Logical Minimum (0), */
0xA4, /* Push, */
0x05, 0x01, /* Usage Page (Desktop), */
0x55, 0xFD, /* Unit Exponent (-3), */
0x65, 0x13, /* Unit (Inch), */
0x34, /* Physical Minimum (0), */
0x09, 0x30, /* Usage (X), */
0x46, 0x40, 0x1F, /* Physical Maximum (8000), */
0x26, 0xFF, 0x7F, /* Logical Maximum (32767), */
0x81, 0x02, /* Input (Variable), */
0x09, 0x31, /* Usage (Y), */
0x46, 0x70, 0x17, /* Physical Maximum (6000), */
0x26, 0xFF, 0x7F, /* Logical Maximum (32767), */
0x81, 0x02, /* Input (Variable), */
0xB4, /* Pop, */
0x09, 0x30, /* Usage (Tip Pressure), */
0x26, 0xFF, 0x03, /* Logical Maximum (1023), */
0x81, 0x02, /* Input (Variable), */
0xC0, /* End Collection, */
0xC0, /* End Collection, */
0x05, 0x01, /* Usage Page (Desktop), */
0x09, 0x02, /* Usage (Mouse), */
0xA1, 0x01, /* Collection (Application), */
0x85, 0x08, /* Report ID (8), */
0x09, 0x01, /* Usage (Pointer), */
0xA0, /* Collection (Physical), */
0x75, 0x01, /* Report Size (1), */
0x05, 0x09, /* Usage Page (Button), */
0x19, 0x01, /* Usage Minimum (01h), */
0x29, 0x03, /* Usage Maximum (03h), */
0x14, /* Logical Minimum (0), */
0x25, 0x01, /* Logical Maximum (1), */
0x95, 0x03, /* Report Count (3), */
0x81, 0x02, /* Input (Variable), */
0x95, 0x05, /* Report Count (5), */
0x81, 0x01, /* Input (Constant), */
0x05, 0x01, /* Usage Page (Desktop), */
0x75, 0x08, /* Report Size (8), */
0x09, 0x30, /* Usage (X), */
0x09, 0x31, /* Usage (Y), */
0x15, 0x81, /* Logical Minimum (-127), */
0x25, 0x7F, /* Logical Maximum (127), */
0x95, 0x02, /* Report Count (2), */
0x81, 0x06, /* Input (Variable, Relative), */
0x09, 0x38, /* Usage (Wheel), */
0x15, 0xFF, /* Logical Minimum (-1), */
0x25, 0x01, /* Logical Maximum (1), */
0x95, 0x01, /* Report Count (1), */
0x81, 0x06, /* Input (Variable, Relative), */
0x81, 0x01, /* Input (Constant), */
0xC0, /* End Collection, */
0xC0 /* End Collection */
};
/*
* See WP1062 description, device and HID report descriptors at
* http://sf.net/apps/mediawiki/digimend/?title=UC-Logic_Tablet_WP1062
*/
/* Size of the original descriptor of WP1062 tablet */
#define WP1062_RDESC_ORIG_SIZE 254
/* Fixed WP1062 report descriptor */
static __u8 wp1062_rdesc_fixed[] = {
0x05, 0x0D, /* Usage Page (Digitizer), */
0x09, 0x02, /* Usage (Pen), */
0xA1, 0x01, /* Collection (Application), */
0x85, 0x09, /* Report ID (9), */
0x09, 0x20, /* Usage (Stylus), */
0xA0, /* Collection (Physical), */
0x75, 0x01, /* Report Size (1), */
0x09, 0x42, /* Usage (Tip Switch), */
0x09, 0x44, /* Usage (Barrel Switch), */
0x09, 0x46, /* Usage (Tablet Pick), */
0x14, /* Logical Minimum (0), */
0x25, 0x01, /* Logical Maximum (1), */
0x95, 0x03, /* Report Count (3), */
0x81, 0x02, /* Input (Variable), */
0x95, 0x04, /* Report Count (4), */
0x81, 0x01, /* Input (Constant), */
0x09, 0x32, /* Usage (In Range), */
0x95, 0x01, /* Report Count (1), */
0x81, 0x02, /* Input (Variable), */
0x75, 0x10, /* Report Size (16), */
0x95, 0x01, /* Report Count (1), */
0x14, /* Logical Minimum (0), */
0xA4, /* Push, */
0x05, 0x01, /* Usage Page (Desktop), */
0x55, 0xFD, /* Unit Exponent (-3), */
0x65, 0x13, /* Unit (Inch), */
0x34, /* Physical Minimum (0), */
0x09, 0x30, /* Usage (X), */
0x46, 0x10, 0x27, /* Physical Maximum (10000), */
0x26, 0x20, 0x4E, /* Logical Maximum (20000), */
0x81, 0x02, /* Input (Variable), */
0x09, 0x31, /* Usage (Y), */
0x46, 0xB7, 0x19, /* Physical Maximum (6583), */
0x26, 0x6E, 0x33, /* Logical Maximum (13166), */
0x81, 0x02, /* Input (Variable), */
0xB4, /* Pop, */
0x09, 0x30, /* Usage (Tip Pressure), */
0x26, 0xFF, 0x03, /* Logical Maximum (1023), */
0x81, 0x02, /* Input (Variable), */
0xC0, /* End Collection, */
0xC0 /* End Collection */
};
/*
* See PF1209 description, device and HID report descriptors at
* http://sf.net/apps/mediawiki/digimend/?title=UC-Logic_Tablet_PF1209
*/
/* Size of the original descriptor of PF1209 tablet */
#define PF1209_RDESC_ORIG_SIZE 234
/* Fixed PF1209 report descriptor */
static __u8 pf1209_rdesc_fixed[] = {
0x05, 0x0D, /* Usage Page (Digitizer), */
0x09, 0x02, /* Usage (Pen), */
0xA1, 0x01, /* Collection (Application), */
0x85, 0x09, /* Report ID (9), */
0x09, 0x20, /* Usage (Stylus), */
0xA0, /* Collection (Physical), */
0x75, 0x01, /* Report Size (1), */
0x09, 0x42, /* Usage (Tip Switch), */
0x09, 0x44, /* Usage (Barrel Switch), */
0x09, 0x46, /* Usage (Tablet Pick), */
0x14, /* Logical Minimum (0), */
0x25, 0x01, /* Logical Maximum (1), */
0x95, 0x03, /* Report Count (3), */
0x81, 0x02, /* Input (Variable), */
0x95, 0x05, /* Report Count (5), */
0x81, 0x01, /* Input (Constant), */
0x75, 0x10, /* Report Size (16), */
0x95, 0x01, /* Report Count (1), */
0x14, /* Logical Minimum (0), */
0xA4, /* Push, */
0x05, 0x01, /* Usage Page (Desktop), */
0x55, 0xFD, /* Unit Exponent (-3), */
0x65, 0x13, /* Unit (Inch), */
0x34, /* Physical Minimum (0), */
0x09, 0x30, /* Usage (X), */
0x46, 0xE0, 0x2E, /* Physical Maximum (12000), */
0x26, 0xFF, 0x7F, /* Logical Maximum (32767), */
0x81, 0x02, /* Input (Variable), */
0x09, 0x31, /* Usage (Y), */
0x46, 0x28, 0x23, /* Physical Maximum (9000), */
0x26, 0xFF, 0x7F, /* Logical Maximum (32767), */
0x81, 0x02, /* Input (Variable), */
0xB4, /* Pop, */
0x09, 0x30, /* Usage (Tip Pressure), */
0x26, 0xFF, 0x03, /* Logical Maximum (1023), */
0x81, 0x02, /* Input (Variable), */
0xC0, /* End Collection, */
0xC0, /* End Collection, */
0x05, 0x01, /* Usage Page (Desktop), */
0x09, 0x02, /* Usage (Mouse), */
0xA1, 0x01, /* Collection (Application), */
0x85, 0x08, /* Report ID (8), */
0x09, 0x01, /* Usage (Pointer), */
0xA0, /* Collection (Physical), */
0x75, 0x01, /* Report Size (1), */
0x05, 0x09, /* Usage Page (Button), */
0x19, 0x01, /* Usage Minimum (01h), */
0x29, 0x03, /* Usage Maximum (03h), */
0x14, /* Logical Minimum (0), */
0x25, 0x01, /* Logical Maximum (1), */
0x95, 0x03, /* Report Count (3), */
0x81, 0x02, /* Input (Variable), */
0x95, 0x05, /* Report Count (5), */
0x81, 0x01, /* Input (Constant), */
0x05, 0x01, /* Usage Page (Desktop), */
0x75, 0x08, /* Report Size (8), */
0x09, 0x30, /* Usage (X), */
0x09, 0x31, /* Usage (Y), */
0x15, 0x81, /* Logical Minimum (-127), */
0x25, 0x7F, /* Logical Maximum (127), */
0x95, 0x02, /* Report Count (2), */
0x81, 0x06, /* Input (Variable, Relative), */
0x09, 0x38, /* Usage (Wheel), */
0x15, 0xFF, /* Logical Minimum (-1), */
0x25, 0x01, /* Logical Maximum (1), */
0x95, 0x01, /* Report Count (1), */
0x81, 0x06, /* Input (Variable, Relative), */
0x81, 0x01, /* Input (Constant), */
0xC0, /* End Collection, */
0xC0 /* End Collection */
};
/*
* See TWHL850 description, device and HID report descriptors at
* http://sf.net/apps/mediawiki/digimend/?title=UC-Logic_Wireless_Tablet_TWHL850
*/
/* Size of the original descriptors of TWHL850 tablet */
#define TWHL850_RDESC_ORIG_SIZE0 182
#define TWHL850_RDESC_ORIG_SIZE1 161
#define TWHL850_RDESC_ORIG_SIZE2 92
/* Fixed PID 0522 tablet report descriptor, interface 0 (stylus) */
static __u8 twhl850_rdesc_fixed0[] = {
0x05, 0x0D, /* Usage Page (Digitizer), */
0x09, 0x02, /* Usage (Pen), */
0xA1, 0x01, /* Collection (Application), */
0x85, 0x09, /* Report ID (9), */
0x09, 0x20, /* Usage (Stylus), */
0xA0, /* Collection (Physical), */
0x14, /* Logical Minimum (0), */
0x25, 0x01, /* Logical Maximum (1), */
0x75, 0x01, /* Report Size (1), */
0x95, 0x03, /* Report Count (3), */
0x09, 0x42, /* Usage (Tip Switch), */
0x09, 0x44, /* Usage (Barrel Switch), */
0x09, 0x46, /* Usage (Tablet Pick), */
0x81, 0x02, /* Input (Variable), */
0x81, 0x03, /* Input (Constant, Variable), */
0x95, 0x01, /* Report Count (1), */
0x09, 0x32, /* Usage (In Range), */
0x81, 0x02, /* Input (Variable), */
0x81, 0x03, /* Input (Constant, Variable), */
0x75, 0x10, /* Report Size (16), */
0xA4, /* Push, */
0x05, 0x01, /* Usage Page (Desktop), */
0x65, 0x13, /* Unit (Inch), */
0x55, 0xFD, /* Unit Exponent (-3), */
0x34, /* Physical Minimum (0), */
0x09, 0x30, /* Usage (X), */
0x46, 0x40, 0x1F, /* Physical Maximum (8000), */
0x26, 0x00, 0x7D, /* Logical Maximum (32000), */
0x81, 0x02, /* Input (Variable), */
0x09, 0x31, /* Usage (Y), */
0x46, 0x88, 0x13, /* Physical Maximum (5000), */
0x26, 0x20, 0x4E, /* Logical Maximum (20000), */
0x81, 0x02, /* Input (Variable), */
0xB4, /* Pop, */
0x09, 0x30, /* Usage (Tip Pressure), */
0x26, 0xFF, 0x03, /* Logical Maximum (1023), */
0x81, 0x02, /* Input (Variable), */
0xC0, /* End Collection, */
0xC0 /* End Collection */
};
/* Fixed PID 0522 tablet report descriptor, interface 1 (mouse) */
static __u8 twhl850_rdesc_fixed1[] = {
0x05, 0x01, /* Usage Page (Desktop), */
0x09, 0x02, /* Usage (Mouse), */
0xA1, 0x01, /* Collection (Application), */
0x85, 0x01, /* Report ID (1), */
0x09, 0x01, /* Usage (Pointer), */
0xA0, /* Collection (Physical), */
0x05, 0x09, /* Usage Page (Button), */
0x75, 0x01, /* Report Size (1), */
0x95, 0x03, /* Report Count (3), */
0x19, 0x01, /* Usage Minimum (01h), */
0x29, 0x03, /* Usage Maximum (03h), */
0x14, /* Logical Minimum (0), */
0x25, 0x01, /* Logical Maximum (1), */
0x81, 0x02, /* Input (Variable), */
0x95, 0x05, /* Report Count (5), */
0x81, 0x03, /* Input (Constant, Variable), */
0x05, 0x01, /* Usage Page (Desktop), */
0x09, 0x30, /* Usage (X), */
0x09, 0x31, /* Usage (Y), */
0x16, 0x00, 0x80, /* Logical Minimum (-32768), */
0x26, 0xFF, 0x7F, /* Logical Maximum (32767), */
0x75, 0x10, /* Report Size (16), */
0x95, 0x02, /* Report Count (2), */
0x81, 0x06, /* Input (Variable, Relative), */
0x09, 0x38, /* Usage (Wheel), */
0x15, 0xFF, /* Logical Minimum (-1), */
0x25, 0x01, /* Logical Maximum (1), */
0x95, 0x01, /* Report Count (1), */
0x75, 0x08, /* Report Size (8), */
0x81, 0x06, /* Input (Variable, Relative), */
0x81, 0x03, /* Input (Constant, Variable), */
0xC0, /* End Collection, */
0xC0 /* End Collection */
};
/* Fixed PID 0522 tablet report descriptor, interface 2 (frame buttons) */
static __u8 twhl850_rdesc_fixed2[] = {
0x05, 0x01, /* Usage Page (Desktop), */
0x09, 0x06, /* Usage (Keyboard), */
0xA1, 0x01, /* Collection (Application), */
0x85, 0x03, /* Report ID (3), */
0x05, 0x07, /* Usage Page (Keyboard), */
0x14, /* Logical Minimum (0), */
0x19, 0xE0, /* Usage Minimum (KB Leftcontrol), */
0x29, 0xE7, /* Usage Maximum (KB Right GUI), */
0x25, 0x01, /* Logical Maximum (1), */
0x75, 0x01, /* Report Size (1), */
0x95, 0x08, /* Report Count (8), */
0x81, 0x02, /* Input (Variable), */
0x18, /* Usage Minimum (None), */
0x29, 0xFF, /* Usage Maximum (FFh), */
0x26, 0xFF, 0x00, /* Logical Maximum (255), */
0x75, 0x08, /* Report Size (8), */
0x95, 0x06, /* Report Count (6), */
0x80, /* Input, */
0xC0 /* End Collection */
};
/*
* See TWHA60 description, device and HID report descriptors at
* http://sf.net/apps/mediawiki/digimend/?title=UC-Logic_Tablet_TWHA60
*/
/* Size of the original descriptors of TWHA60 tablet */
#define TWHA60_RDESC_ORIG_SIZE0 254
#define TWHA60_RDESC_ORIG_SIZE1 139
/* Fixed TWHA60 report descriptor, interface 0 (stylus) */
static __u8 twha60_rdesc_fixed0[] = {
0x05, 0x0D, /* Usage Page (Digitizer), */
0x09, 0x02, /* Usage (Pen), */
0xA1, 0x01, /* Collection (Application), */
0x85, 0x09, /* Report ID (9), */
0x09, 0x20, /* Usage (Stylus), */
0xA0, /* Collection (Physical), */
0x75, 0x01, /* Report Size (1), */
0x09, 0x42, /* Usage (Tip Switch), */
0x09, 0x44, /* Usage (Barrel Switch), */
0x09, 0x46, /* Usage (Tablet Pick), */
0x14, /* Logical Minimum (0), */
0x25, 0x01, /* Logical Maximum (1), */
0x95, 0x03, /* Report Count (3), */
0x81, 0x02, /* Input (Variable), */
0x95, 0x04, /* Report Count (4), */
0x81, 0x01, /* Input (Constant), */
0x09, 0x32, /* Usage (In Range), */
0x95, 0x01, /* Report Count (1), */
0x81, 0x02, /* Input (Variable), */
0x75, 0x10, /* Report Size (16), */
0x95, 0x01, /* Report Count (1), */
0x14, /* Logical Minimum (0), */
0xA4, /* Push, */
0x05, 0x01, /* Usage Page (Desktop), */
0x55, 0xFD, /* Unit Exponent (-3), */
0x65, 0x13, /* Unit (Inch), */
0x34, /* Physical Minimum (0), */
0x09, 0x30, /* Usage (X), */
0x46, 0x10, 0x27, /* Physical Maximum (10000), */
0x27, 0x3F, 0x9C,
0x00, 0x00, /* Logical Maximum (39999), */
0x81, 0x02, /* Input (Variable), */
0x09, 0x31, /* Usage (Y), */
0x46, 0x6A, 0x18, /* Physical Maximum (6250), */
0x26, 0xA7, 0x61, /* Logical Maximum (24999), */
0x81, 0x02, /* Input (Variable), */
0xB4, /* Pop, */
0x09, 0x30, /* Usage (Tip Pressure), */
0x26, 0xFF, 0x03, /* Logical Maximum (1023), */
0x81, 0x02, /* Input (Variable), */
0xC0, /* End Collection, */
0xC0 /* End Collection */
};
/* Fixed TWHA60 report descriptor, interface 1 (frame buttons) */
static __u8 twha60_rdesc_fixed1[] = {
0x05, 0x01, /* Usage Page (Desktop), */
0x09, 0x06, /* Usage (Keyboard), */
0xA1, 0x01, /* Collection (Application), */
0x85, 0x05, /* Report ID (5), */
0x05, 0x07, /* Usage Page (Keyboard), */
0x14, /* Logical Minimum (0), */
0x25, 0x01, /* Logical Maximum (1), */
0x75, 0x01, /* Report Size (1), */
0x95, 0x08, /* Report Count (8), */
0x81, 0x01, /* Input (Constant), */
0x95, 0x0C, /* Report Count (12), */
0x19, 0x3A, /* Usage Minimum (KB F1), */
0x29, 0x45, /* Usage Maximum (KB F12), */
0x81, 0x02, /* Input (Variable), */
0x95, 0x0C, /* Report Count (12), */
0x19, 0x68, /* Usage Minimum (KB F13), */
0x29, 0x73, /* Usage Maximum (KB F24), */
0x81, 0x02, /* Input (Variable), */
0x95, 0x08, /* Report Count (8), */
0x81, 0x01, /* Input (Constant), */
0xC0 /* End Collection */
};
static __u8 *uclogic_report_fixup(struct hid_device *hdev, __u8 *rdesc,
unsigned int *rsize)
{
struct usb_interface *iface = to_usb_interface(hdev->dev.parent);
__u8 iface_num = iface->cur_altsetting->desc.bInterfaceNumber;
switch (hdev->product) {
case USB_DEVICE_ID_UCLOGIC_TABLET_PF1209:
if (*rsize == PF1209_RDESC_ORIG_SIZE) {
rdesc = pf1209_rdesc_fixed;
*rsize = sizeof(pf1209_rdesc_fixed);
}
break;
case USB_DEVICE_ID_UCLOGIC_TABLET_WP4030U:
if (*rsize == WPXXXXU_RDESC_ORIG_SIZE) {
rdesc = wp4030u_rdesc_fixed;
*rsize = sizeof(wp4030u_rdesc_fixed);
}
break;
case USB_DEVICE_ID_UCLOGIC_TABLET_WP5540U:
if (*rsize == WPXXXXU_RDESC_ORIG_SIZE) {
rdesc = wp5540u_rdesc_fixed;
*rsize = sizeof(wp5540u_rdesc_fixed);
}
break;
case USB_DEVICE_ID_UCLOGIC_TABLET_WP8060U:
if (*rsize == WPXXXXU_RDESC_ORIG_SIZE) {
rdesc = wp8060u_rdesc_fixed;
*rsize = sizeof(wp8060u_rdesc_fixed);
}
break;
case USB_DEVICE_ID_UCLOGIC_TABLET_WP1062:
if (*rsize == WP1062_RDESC_ORIG_SIZE) {
rdesc = wp1062_rdesc_fixed;
*rsize = sizeof(wp1062_rdesc_fixed);
}
break;
case USB_DEVICE_ID_UCLOGIC_WIRELESS_TABLET_TWHL850:
switch (iface_num) {
case 0:
if (*rsize == TWHL850_RDESC_ORIG_SIZE0) {
rdesc = twhl850_rdesc_fixed0;
*rsize = sizeof(twhl850_rdesc_fixed0);
}
break;
case 1:
if (*rsize == TWHL850_RDESC_ORIG_SIZE1) {
rdesc = twhl850_rdesc_fixed1;
*rsize = sizeof(twhl850_rdesc_fixed1);
}
break;
case 2:
if (*rsize == TWHL850_RDESC_ORIG_SIZE2) {
rdesc = twhl850_rdesc_fixed2;
*rsize = sizeof(twhl850_rdesc_fixed2);
}
break;
}
break;
case USB_DEVICE_ID_UCLOGIC_TABLET_TWHA60:
switch (iface_num) {
case 0:
if (*rsize == TWHA60_RDESC_ORIG_SIZE0) {
rdesc = twha60_rdesc_fixed0;
*rsize = sizeof(twha60_rdesc_fixed0);
}
break;
case 1:
if (*rsize == TWHA60_RDESC_ORIG_SIZE1) {
rdesc = twha60_rdesc_fixed1;
*rsize = sizeof(twha60_rdesc_fixed1);
}
break;
}
break;
}
return rdesc;
}
static const struct hid_device_id uclogic_devices[] = {
{ HID_USB_DEVICE(USB_VENDOR_ID_UCLOGIC,
USB_DEVICE_ID_UCLOGIC_TABLET_PF1209) },
{ HID_USB_DEVICE(USB_VENDOR_ID_UCLOGIC,
USB_DEVICE_ID_UCLOGIC_TABLET_WP4030U) },
{ HID_USB_DEVICE(USB_VENDOR_ID_UCLOGIC,
USB_DEVICE_ID_UCLOGIC_TABLET_WP5540U) },
{ HID_USB_DEVICE(USB_VENDOR_ID_UCLOGIC,
USB_DEVICE_ID_UCLOGIC_TABLET_WP8060U) },
{ HID_USB_DEVICE(USB_VENDOR_ID_UCLOGIC,
USB_DEVICE_ID_UCLOGIC_TABLET_WP1062) },
{ HID_USB_DEVICE(USB_VENDOR_ID_UCLOGIC,
USB_DEVICE_ID_UCLOGIC_WIRELESS_TABLET_TWHL850) },
{ HID_USB_DEVICE(USB_VENDOR_ID_UCLOGIC,
USB_DEVICE_ID_UCLOGIC_TABLET_TWHA60) },
{ }
};
MODULE_DEVICE_TABLE(hid, uclogic_devices);
static struct hid_driver uclogic_driver = {
.name = "uclogic",
.id_table = uclogic_devices,
.report_fixup = uclogic_report_fixup,
};
module_hid_driver(uclogic_driver);
MODULE_LICENSE("GPL");
| gpl-2.0 |
SolidRun/linux-imx6 | drivers/video/macfb.c | 4192 | 23643 | /*
* macfb.c: Generic framebuffer for Macs whose colourmaps/modes we
* don't know how to set.
*
* (c) 1999 David Huggins-Daines <dhd@debian.org>
*
* Primarily based on vesafb.c, by Gerd Knorr
* (c) 1998 Gerd Knorr <kraxel@cs.tu-berlin.de>
*
* Also uses information and code from:
*
* The original macfb.c from Linux/mac68k 2.0, by Alan Cox, Juergen
* Mellinger, Mikael Forselius, Michael Schmitz, and others.
*
* valkyriefb.c, by Martin Costabel, Kevin Schoedel, Barry Nathan, Dan
* Jacobowitz, Paul Mackerras, Fabio Riccardi, and Geert Uytterhoeven.
*
* The VideoToolbox "Bugs" web page at
* http://rajsky.psych.nyu.edu/Tips/VideoBugs.html
*
* This code is free software. You may copy, modify, and distribute
* it subject to the terms and conditions of the GNU General Public
* License, version 2, or any later version, at your convenience.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/delay.h>
#include <linux/nubus.h>
#include <linux/init.h>
#include <linux/fb.h>
#include <asm/setup.h>
#include <asm/bootinfo.h>
#include <asm/macintosh.h>
#include <asm/io.h>
/* Common DAC base address for the LC, RBV, Valkyrie, and IIvx */
#define DAC_BASE 0x50f24000
/* Some addresses for the DAFB */
#define DAFB_BASE 0xf9800200
/* Address for the built-in Civic framebuffer in Quadra AVs */
#define CIVIC_BASE 0x50f30800
/* GSC (Gray Scale Controller) base address */
#define GSC_BASE 0x50F20000
/* CSC (Color Screen Controller) base address */
#define CSC_BASE 0x50F20000
static int (*macfb_setpalette)(unsigned int regno, unsigned int red,
unsigned int green, unsigned int blue,
struct fb_info *info);
static struct {
unsigned char addr;
unsigned char lut;
} __iomem *v8_brazil_cmap_regs;
static struct {
unsigned char addr;
char pad1[3]; /* word aligned */
unsigned char lut;
char pad2[3]; /* word aligned */
unsigned char cntl; /* a guess as to purpose */
} __iomem *rbv_cmap_regs;
static struct {
unsigned long reset;
unsigned long pad1[3];
unsigned char pad2[3];
unsigned char lut;
} __iomem *dafb_cmap_regs;
static struct {
unsigned char addr; /* OFFSET: 0x00 */
unsigned char pad1[15];
unsigned char lut; /* OFFSET: 0x10 */
unsigned char pad2[15];
unsigned char status; /* OFFSET: 0x20 */
unsigned char pad3[7];
unsigned long vbl_addr; /* OFFSET: 0x28 */
unsigned int status2; /* OFFSET: 0x2C */
} __iomem *civic_cmap_regs;
static struct {
char pad1[0x40];
unsigned char clut_waddr; /* 0x40 */
char pad2;
unsigned char clut_data; /* 0x42 */
char pad3[0x3];
unsigned char clut_raddr; /* 0x46 */
} __iomem *csc_cmap_regs;
/* The registers in these structs are in NuBus slot space */
struct mdc_cmap_regs {
char pad1[0x200200];
unsigned char addr;
char pad2[6];
unsigned char lut;
};
struct toby_cmap_regs {
char pad1[0x90018];
unsigned char lut; /* TFBClutWDataReg, offset 0x90018 */
char pad2[3];
unsigned char addr; /* TFBClutAddrReg, offset 0x9001C */
};
struct jet_cmap_regs {
char pad1[0xe0e000];
unsigned char addr;
unsigned char lut;
};
#define PIXEL_TO_MM(a) (((a)*10)/28) /* width in mm at 72 dpi */
static struct fb_var_screeninfo macfb_defined = {
.bits_per_pixel = 8,
.activate = FB_ACTIVATE_NOW,
.width = -1,
.height = -1,
.right_margin = 32,
.upper_margin = 16,
.lower_margin = 4,
.vsync_len = 4,
.vmode = FB_VMODE_NONINTERLACED,
};
static struct fb_fix_screeninfo macfb_fix = {
.type = FB_TYPE_PACKED_PIXELS,
.accel = FB_ACCEL_NONE,
};
static void *slot_addr;
static struct fb_info fb_info;
static u32 pseudo_palette[16];
static int inverse;
static int vidtest;
/*
* Unlike the Valkyrie, the DAFB cannot set individual colormap
* registers. Therefore, we do what the MacOS driver does (no
* kidding!) and simply set them one by one until we hit the one we
* want.
*/
static int dafb_setpalette(unsigned int regno, unsigned int red,
unsigned int green, unsigned int blue,
struct fb_info *info)
{
static int lastreg = -1;
unsigned long flags;
local_irq_save(flags);
/*
* fbdev will set an entire colourmap, but X won't. Hopefully
* this should accommodate both of them
*/
if (regno != lastreg + 1) {
int i;
/* Stab in the dark trying to reset the CLUT pointer */
nubus_writel(0, &dafb_cmap_regs->reset);
nop();
/* Loop until we get to the register we want */
for (i = 0; i < regno; i++) {
nubus_writeb(info->cmap.red[i] >> 8,
&dafb_cmap_regs->lut);
nop();
nubus_writeb(info->cmap.green[i] >> 8,
&dafb_cmap_regs->lut);
nop();
nubus_writeb(info->cmap.blue[i] >> 8,
&dafb_cmap_regs->lut);
nop();
}
}
nubus_writeb(red, &dafb_cmap_regs->lut);
nop();
nubus_writeb(green, &dafb_cmap_regs->lut);
nop();
nubus_writeb(blue, &dafb_cmap_regs->lut);
local_irq_restore(flags);
lastreg = regno;
return 0;
}
/* V8 and Brazil seem to use the same DAC. Sonora does as well. */
static int v8_brazil_setpalette(unsigned int regno, unsigned int red,
unsigned int green, unsigned int blue,
struct fb_info *info)
{
unsigned int bpp = info->var.bits_per_pixel;
unsigned long flags;
if (bpp > 8)
return 1; /* failsafe */
local_irq_save(flags);
/* On these chips, the CLUT register numbers are spread out
* across the register space. Thus:
* In 8bpp, all regnos are valid.
* In 4bpp, the regnos are 0x0f, 0x1f, 0x2f, etc, etc
* In 2bpp, the regnos are 0x3f, 0x7f, 0xbf, 0xff
*/
regno = (regno << (8 - bpp)) | (0xFF >> bpp);
nubus_writeb(regno, &v8_brazil_cmap_regs->addr);
nop();
/* send one color channel at a time */
nubus_writeb(red, &v8_brazil_cmap_regs->lut);
nop();
nubus_writeb(green, &v8_brazil_cmap_regs->lut);
nop();
nubus_writeb(blue, &v8_brazil_cmap_regs->lut);
local_irq_restore(flags);
return 0;
}
/* RAM-Based Video */
static int rbv_setpalette(unsigned int regno, unsigned int red,
unsigned int green, unsigned int blue,
struct fb_info *info)
{
unsigned long flags;
if (info->var.bits_per_pixel > 8)
return 1; /* failsafe */
local_irq_save(flags);
/* From the VideoToolbox driver. Seems to be saying that
* regno #254 and #255 are the important ones for 1-bit color,
* regno #252-255 are the important ones for 2-bit color, etc.
*/
regno += 256 - (1 << info->var.bits_per_pixel);
/* reset clut? (VideoToolbox sez "not necessary") */
nubus_writeb(0xFF, &rbv_cmap_regs->cntl);
nop();
/* tell clut which address to use. */
nubus_writeb(regno, &rbv_cmap_regs->addr);
nop();
/* send one color channel at a time. */
nubus_writeb(red, &rbv_cmap_regs->lut);
nop();
nubus_writeb(green, &rbv_cmap_regs->lut);
nop();
nubus_writeb(blue, &rbv_cmap_regs->lut);
local_irq_restore(flags);
return 0;
}
/* Macintosh Display Card (8*24) */
static int mdc_setpalette(unsigned int regno, unsigned int red,
unsigned int green, unsigned int blue,
struct fb_info *info)
{
struct mdc_cmap_regs *cmap_regs = slot_addr;
unsigned long flags;
local_irq_save(flags);
/* the nop's are there to order writes. */
nubus_writeb(regno, &cmap_regs->addr);
nop();
nubus_writeb(red, &cmap_regs->lut);
nop();
nubus_writeb(green, &cmap_regs->lut);
nop();
nubus_writeb(blue, &cmap_regs->lut);
local_irq_restore(flags);
return 0;
}
/* Toby frame buffer */
static int toby_setpalette(unsigned int regno, unsigned int red,
unsigned int green, unsigned int blue,
struct fb_info *info)
{
struct toby_cmap_regs *cmap_regs = slot_addr;
unsigned int bpp = info->var.bits_per_pixel;
unsigned long flags;
red = ~red;
green = ~green;
blue = ~blue;
regno = (regno << (8 - bpp)) | (0xFF >> bpp);
local_irq_save(flags);
nubus_writeb(regno, &cmap_regs->addr);
nop();
nubus_writeb(red, &cmap_regs->lut);
nop();
nubus_writeb(green, &cmap_regs->lut);
nop();
nubus_writeb(blue, &cmap_regs->lut);
local_irq_restore(flags);
return 0;
}
/* Jet frame buffer */
static int jet_setpalette(unsigned int regno, unsigned int red,
unsigned int green, unsigned int blue,
struct fb_info *info)
{
struct jet_cmap_regs *cmap_regs = slot_addr;
unsigned long flags;
local_irq_save(flags);
nubus_writeb(regno, &cmap_regs->addr);
nop();
nubus_writeb(red, &cmap_regs->lut);
nop();
nubus_writeb(green, &cmap_regs->lut);
nop();
nubus_writeb(blue, &cmap_regs->lut);
local_irq_restore(flags);
return 0;
}
/*
* Civic framebuffer -- Quadra AV built-in video. A chip
* called Sebastian holds the actual color palettes, and
* apparently, there are two different banks of 512K RAM
* which can act as separate framebuffers for doing video
* input and viewing the screen at the same time! The 840AV
* Can add another 1MB RAM to give the two framebuffers
* 1MB RAM apiece.
*/
static int civic_setpalette(unsigned int regno, unsigned int red,
unsigned int green, unsigned int blue,
struct fb_info *info)
{
unsigned long flags;
int clut_status;
if (info->var.bits_per_pixel > 8)
return 1; /* failsafe */
local_irq_save(flags);
/* Set the register address */
nubus_writeb(regno, &civic_cmap_regs->addr);
nop();
/*
* Grab a status word and do some checking;
* Then finally write the clut!
*/
clut_status = nubus_readb(&civic_cmap_regs->status2);
if ((clut_status & 0x0008) == 0)
{
#if 0
if ((clut_status & 0x000D) != 0)
{
nubus_writeb(0x00, &civic_cmap_regs->lut);
nop();
nubus_writeb(0x00, &civic_cmap_regs->lut);
nop();
}
#endif
nubus_writeb(red, &civic_cmap_regs->lut);
nop();
nubus_writeb(green, &civic_cmap_regs->lut);
nop();
nubus_writeb(blue, &civic_cmap_regs->lut);
nop();
nubus_writeb(0x00, &civic_cmap_regs->lut);
}
else
{
unsigned char junk;
junk = nubus_readb(&civic_cmap_regs->lut);
nop();
junk = nubus_readb(&civic_cmap_regs->lut);
nop();
junk = nubus_readb(&civic_cmap_regs->lut);
nop();
junk = nubus_readb(&civic_cmap_regs->lut);
nop();
if ((clut_status & 0x000D) != 0)
{
nubus_writeb(0x00, &civic_cmap_regs->lut);
nop();
nubus_writeb(0x00, &civic_cmap_regs->lut);
nop();
}
nubus_writeb(red, &civic_cmap_regs->lut);
nop();
nubus_writeb(green, &civic_cmap_regs->lut);
nop();
nubus_writeb(blue, &civic_cmap_regs->lut);
nop();
nubus_writeb(junk, &civic_cmap_regs->lut);
}
local_irq_restore(flags);
return 0;
}
/*
* The CSC is the framebuffer on the PowerBook 190 series
* (and the 5300 too, but that's a PowerMac). This function
* brought to you in part by the ECSC driver for MkLinux.
*/
static int csc_setpalette(unsigned int regno, unsigned int red,
unsigned int green, unsigned int blue,
struct fb_info *info)
{
unsigned long flags;
local_irq_save(flags);
udelay(1); /* mklinux on PB 5300 waits for 260 ns */
nubus_writeb(regno, &csc_cmap_regs->clut_waddr);
nubus_writeb(red, &csc_cmap_regs->clut_data);
nubus_writeb(green, &csc_cmap_regs->clut_data);
nubus_writeb(blue, &csc_cmap_regs->clut_data);
local_irq_restore(flags);
return 0;
}
static int macfb_setcolreg(unsigned regno, unsigned red, unsigned green,
unsigned blue, unsigned transp,
struct fb_info *fb_info)
{
/*
* Set a single color register. The values supplied are
* already rounded down to the hardware's capabilities
* (according to the entries in the `var' structure).
* Return non-zero for invalid regno.
*/
if (regno >= fb_info->cmap.len)
return 1;
if (fb_info->var.bits_per_pixel <= 8) {
switch (fb_info->var.bits_per_pixel) {
case 1:
/* We shouldn't get here */
break;
case 2:
case 4:
case 8:
if (macfb_setpalette)
macfb_setpalette(regno, red >> 8, green >> 8,
blue >> 8, fb_info);
else
return 1;
break;
}
} else if (regno < 16) {
switch (fb_info->var.bits_per_pixel) {
case 16:
if (fb_info->var.red.offset == 10) {
/* 1:5:5:5 */
((u32*) (fb_info->pseudo_palette))[regno] =
((red & 0xf800) >> 1) |
((green & 0xf800) >> 6) |
((blue & 0xf800) >> 11) |
((transp != 0) << 15);
} else {
/* 0:5:6:5 */
((u32*) (fb_info->pseudo_palette))[regno] =
((red & 0xf800) >> 0) |
((green & 0xfc00) >> 5) |
((blue & 0xf800) >> 11);
}
break;
/*
* 24-bit colour almost doesn't exist on 68k Macs --
* http://support.apple.com/kb/TA28634 (Old Article: 10992)
*/
case 24:
case 32:
red >>= 8;
green >>= 8;
blue >>= 8;
((u32 *)(fb_info->pseudo_palette))[regno] =
(red << fb_info->var.red.offset) |
(green << fb_info->var.green.offset) |
(blue << fb_info->var.blue.offset);
break;
}
}
return 0;
}
static struct fb_ops macfb_ops = {
.owner = THIS_MODULE,
.fb_setcolreg = macfb_setcolreg,
.fb_fillrect = cfb_fillrect,
.fb_copyarea = cfb_copyarea,
.fb_imageblit = cfb_imageblit,
};
static void __init macfb_setup(char *options)
{
char *this_opt;
if (!options || !*options)
return;
while ((this_opt = strsep(&options, ",")) != NULL) {
if (!*this_opt)
continue;
if (!strcmp(this_opt, "inverse"))
inverse = 1;
else
if (!strcmp(this_opt, "vidtest"))
vidtest = 1; /* enable experimental CLUT code */
}
}
static void __init iounmap_macfb(void)
{
if (dafb_cmap_regs)
iounmap(dafb_cmap_regs);
if (v8_brazil_cmap_regs)
iounmap(v8_brazil_cmap_regs);
if (rbv_cmap_regs)
iounmap(rbv_cmap_regs);
if (civic_cmap_regs)
iounmap(civic_cmap_regs);
if (csc_cmap_regs)
iounmap(csc_cmap_regs);
}
static int __init macfb_init(void)
{
int video_cmap_len, video_is_nubus = 0;
struct nubus_dev* ndev = NULL;
char *option = NULL;
int err;
if (fb_get_options("macfb", &option))
return -ENODEV;
macfb_setup(option);
if (!MACH_IS_MAC)
return -ENODEV;
if (mac_bi_data.id == MAC_MODEL_Q630 ||
mac_bi_data.id == MAC_MODEL_P588)
return -ENODEV; /* See valkyriefb.c */
macfb_defined.xres = mac_bi_data.dimensions & 0xFFFF;
macfb_defined.yres = mac_bi_data.dimensions >> 16;
macfb_defined.bits_per_pixel = mac_bi_data.videodepth;
macfb_fix.line_length = mac_bi_data.videorow;
macfb_fix.smem_len = macfb_fix.line_length * macfb_defined.yres;
/* Note: physical address (since 2.1.127) */
macfb_fix.smem_start = mac_bi_data.videoaddr;
/*
* This is actually redundant with the initial mappings.
* However, there are some non-obvious aspects to the way
* those mappings are set up, so this is in fact the safest
* way to ensure that this driver will work on every possible Mac
*/
fb_info.screen_base = ioremap(mac_bi_data.videoaddr,
macfb_fix.smem_len);
if (!fb_info.screen_base)
return -ENODEV;
printk("macfb: framebuffer at 0x%08lx, mapped to 0x%p, size %dk\n",
macfb_fix.smem_start, fb_info.screen_base,
macfb_fix.smem_len / 1024);
printk("macfb: mode is %dx%dx%d, linelength=%d\n",
macfb_defined.xres, macfb_defined.yres,
macfb_defined.bits_per_pixel, macfb_fix.line_length);
/* Fill in the available video resolution */
macfb_defined.xres_virtual = macfb_defined.xres;
macfb_defined.yres_virtual = macfb_defined.yres;
macfb_defined.height = PIXEL_TO_MM(macfb_defined.yres);
macfb_defined.width = PIXEL_TO_MM(macfb_defined.xres);
/* Some dummy values for timing to make fbset happy */
macfb_defined.pixclock = 10000000 / macfb_defined.xres *
1000 / macfb_defined.yres;
macfb_defined.left_margin = (macfb_defined.xres / 8) & 0xf8;
macfb_defined.hsync_len = (macfb_defined.xres / 8) & 0xf8;
switch (macfb_defined.bits_per_pixel) {
case 1:
/*
* XXX: I think this will catch any program that tries
* to do FBIO_PUTCMAP when the visual is monochrome.
*/
macfb_defined.red.length = macfb_defined.bits_per_pixel;
macfb_defined.green.length = macfb_defined.bits_per_pixel;
macfb_defined.blue.length = macfb_defined.bits_per_pixel;
video_cmap_len = 0;
macfb_fix.visual = FB_VISUAL_MONO01;
break;
case 2:
case 4:
case 8:
macfb_defined.red.length = macfb_defined.bits_per_pixel;
macfb_defined.green.length = macfb_defined.bits_per_pixel;
macfb_defined.blue.length = macfb_defined.bits_per_pixel;
video_cmap_len = 1 << macfb_defined.bits_per_pixel;
macfb_fix.visual = FB_VISUAL_PSEUDOCOLOR;
break;
case 16:
macfb_defined.transp.offset = 15;
macfb_defined.transp.length = 1;
macfb_defined.red.offset = 10;
macfb_defined.red.length = 5;
macfb_defined.green.offset = 5;
macfb_defined.green.length = 5;
macfb_defined.blue.offset = 0;
macfb_defined.blue.length = 5;
video_cmap_len = 16;
/*
* Should actually be FB_VISUAL_DIRECTCOLOR, but this
* works too
*/
macfb_fix.visual = FB_VISUAL_TRUECOLOR;
break;
case 24:
case 32:
macfb_defined.red.offset = 16;
macfb_defined.red.length = 8;
macfb_defined.green.offset = 8;
macfb_defined.green.length = 8;
macfb_defined.blue.offset = 0;
macfb_defined.blue.length = 8;
video_cmap_len = 16;
macfb_fix.visual = FB_VISUAL_TRUECOLOR;
break;
default:
video_cmap_len = 0;
macfb_fix.visual = FB_VISUAL_MONO01;
printk("macfb: unknown or unsupported bit depth: %d\n",
macfb_defined.bits_per_pixel);
break;
}
/*
* We take a wild guess that if the video physical address is
* in nubus slot space, that the nubus card is driving video.
* Penguin really ought to tell us whether we are using internal
* video or not.
* Hopefully we only find one of them. Otherwise our NuBus
* code is really broken :-)
*/
while ((ndev = nubus_find_type(NUBUS_CAT_DISPLAY,
NUBUS_TYPE_VIDEO, ndev)))
{
unsigned long base = ndev->board->slot_addr;
if (mac_bi_data.videoaddr < base ||
mac_bi_data.videoaddr - base > 0xFFFFFF)
continue;
video_is_nubus = 1;
slot_addr = (unsigned char *)base;
switch(ndev->dr_hw) {
case NUBUS_DRHW_APPLE_MDC:
strcpy(macfb_fix.id, "Mac Disp. Card");
macfb_setpalette = mdc_setpalette;
macfb_defined.activate = FB_ACTIVATE_NOW;
break;
case NUBUS_DRHW_APPLE_TFB:
strcpy(macfb_fix.id, "Toby");
macfb_setpalette = toby_setpalette;
macfb_defined.activate = FB_ACTIVATE_NOW;
break;
case NUBUS_DRHW_APPLE_JET:
strcpy(macfb_fix.id, "Jet");
macfb_setpalette = jet_setpalette;
macfb_defined.activate = FB_ACTIVATE_NOW;
break;
default:
strcpy(macfb_fix.id, "Generic NuBus");
break;
}
}
/* If it's not a NuBus card, it must be internal video */
if (!video_is_nubus)
switch (mac_bi_data.id) {
/*
* DAFB Quadras
* Note: these first four have the v7 DAFB, which is
* known to be rather unlike the ones used in the
* other models
*/
case MAC_MODEL_P475:
case MAC_MODEL_P475F:
case MAC_MODEL_P575:
case MAC_MODEL_Q605:
case MAC_MODEL_Q800:
case MAC_MODEL_Q650:
case MAC_MODEL_Q610:
case MAC_MODEL_C650:
case MAC_MODEL_C610:
case MAC_MODEL_Q700:
case MAC_MODEL_Q900:
case MAC_MODEL_Q950:
strcpy(macfb_fix.id, "DAFB");
macfb_setpalette = dafb_setpalette;
macfb_defined.activate = FB_ACTIVATE_NOW;
dafb_cmap_regs = ioremap(DAFB_BASE, 0x1000);
break;
/*
* LC II uses the V8 framebuffer
*/
case MAC_MODEL_LCII:
strcpy(macfb_fix.id, "V8");
macfb_setpalette = v8_brazil_setpalette;
macfb_defined.activate = FB_ACTIVATE_NOW;
v8_brazil_cmap_regs = ioremap(DAC_BASE, 0x1000);
break;
/*
* IIvi, IIvx use the "Brazil" framebuffer (which is
* very much like the V8, it seems, and probably uses
* the same DAC)
*/
case MAC_MODEL_IIVI:
case MAC_MODEL_IIVX:
case MAC_MODEL_P600:
strcpy(macfb_fix.id, "Brazil");
macfb_setpalette = v8_brazil_setpalette;
macfb_defined.activate = FB_ACTIVATE_NOW;
v8_brazil_cmap_regs = ioremap(DAC_BASE, 0x1000);
break;
/*
* LC III (and friends) use the Sonora framebuffer
* Incidentally this is also used in the non-AV models
* of the x100 PowerMacs
* These do in fact seem to use the same DAC interface
* as the LC II.
*/
case MAC_MODEL_LCIII:
case MAC_MODEL_P520:
case MAC_MODEL_P550:
case MAC_MODEL_P460:
macfb_setpalette = v8_brazil_setpalette;
macfb_defined.activate = FB_ACTIVATE_NOW;
strcpy(macfb_fix.id, "Sonora");
v8_brazil_cmap_regs = ioremap(DAC_BASE, 0x1000);
break;
/*
* IIci and IIsi use the infamous RBV chip
* (the IIsi is just a rebadged and crippled
* IIci in a different case, BTW)
*/
case MAC_MODEL_IICI:
case MAC_MODEL_IISI:
macfb_setpalette = rbv_setpalette;
macfb_defined.activate = FB_ACTIVATE_NOW;
strcpy(macfb_fix.id, "RBV");
rbv_cmap_regs = ioremap(DAC_BASE, 0x1000);
break;
/*
* AVs use the Civic framebuffer
*/
case MAC_MODEL_Q840:
case MAC_MODEL_C660:
macfb_setpalette = civic_setpalette;
macfb_defined.activate = FB_ACTIVATE_NOW;
strcpy(macfb_fix.id, "Civic");
civic_cmap_regs = ioremap(CIVIC_BASE, 0x1000);
break;
/*
* Assorted weirdos
* We think this may be like the LC II
*/
case MAC_MODEL_LC:
if (vidtest) {
macfb_setpalette = v8_brazil_setpalette;
macfb_defined.activate = FB_ACTIVATE_NOW;
v8_brazil_cmap_regs =
ioremap(DAC_BASE, 0x1000);
}
strcpy(macfb_fix.id, "LC");
break;
/*
* We think this may be like the LC II
*/
case MAC_MODEL_CCL:
if (vidtest) {
macfb_setpalette = v8_brazil_setpalette;
macfb_defined.activate = FB_ACTIVATE_NOW;
v8_brazil_cmap_regs =
ioremap(DAC_BASE, 0x1000);
}
strcpy(macfb_fix.id, "Color Classic");
break;
/*
* And we *do* mean "weirdos"
*/
case MAC_MODEL_TV:
strcpy(macfb_fix.id, "Mac TV");
break;
/*
* These don't have colour, so no need to worry
*/
case MAC_MODEL_SE30:
case MAC_MODEL_CLII:
strcpy(macfb_fix.id, "Monochrome");
break;
/*
* Powerbooks are particularly difficult. Many of
* them have separate framebuffers for external and
* internal video, which is admittedly pretty cool,
* but will be a bit of a headache to support here.
* Also, many of them are grayscale, and we don't
* really support that.
*/
/*
* Slot 0 ROM says TIM. No external video. B&W.
*/
case MAC_MODEL_PB140:
case MAC_MODEL_PB145:
case MAC_MODEL_PB170:
strcpy(macfb_fix.id, "DDC");
break;
/*
* Internal is GSC, External (if present) is ViSC
*/
case MAC_MODEL_PB150: /* no external video */
case MAC_MODEL_PB160:
case MAC_MODEL_PB165:
case MAC_MODEL_PB180:
case MAC_MODEL_PB210:
case MAC_MODEL_PB230:
strcpy(macfb_fix.id, "GSC");
break;
/*
* Internal is TIM, External is ViSC
*/
case MAC_MODEL_PB165C:
case MAC_MODEL_PB180C:
strcpy(macfb_fix.id, "TIM");
break;
/*
* Internal is CSC, External is Keystone+Ariel.
*/
case MAC_MODEL_PB190: /* external video is optional */
case MAC_MODEL_PB520:
case MAC_MODEL_PB250:
case MAC_MODEL_PB270C:
case MAC_MODEL_PB280:
case MAC_MODEL_PB280C:
macfb_setpalette = csc_setpalette;
macfb_defined.activate = FB_ACTIVATE_NOW;
strcpy(macfb_fix.id, "CSC");
csc_cmap_regs = ioremap(CSC_BASE, 0x1000);
break;
default:
strcpy(macfb_fix.id, "Unknown");
break;
}
fb_info.fbops = &macfb_ops;
fb_info.var = macfb_defined;
fb_info.fix = macfb_fix;
fb_info.pseudo_palette = pseudo_palette;
fb_info.flags = FBINFO_DEFAULT;
err = fb_alloc_cmap(&fb_info.cmap, video_cmap_len, 0);
if (err)
goto fail_unmap;
err = register_framebuffer(&fb_info);
if (err)
goto fail_dealloc;
printk("fb%d: %s frame buffer device\n",
fb_info.node, fb_info.fix.id);
return 0;
fail_dealloc:
fb_dealloc_cmap(&fb_info.cmap);
fail_unmap:
iounmap(fb_info.screen_base);
iounmap_macfb();
return err;
}
module_init(macfb_init);
MODULE_LICENSE("GPL");
| gpl-2.0 |
i2t/rmptcp | drivers/media/pci/ivtv/ivtv-alsa-mixer.c | 4448 | 4866 | /*
* ALSA mixer controls for the
* ALSA interface to ivtv PCM capture streams
*
* Copyright (C) 2009,2012 Andy Walls <awalls@md.metrocast.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/spinlock.h>
#include <linux/videodev2.h>
#include <media/v4l2-device.h>
#include <sound/core.h>
#include <sound/control.h>
#include <sound/tlv.h>
#include "ivtv-alsa.h"
#include "ivtv-driver.h"
/*
* Note the cx25840-core volume scale is funny, due to the alignment of the
* scale with another chip's range:
*
* v4l2_control value /512 indicated dB actual dB reg 0x8d4
* 0x0000 - 0x01ff 0 -119 -96 228
* 0x0200 - 0x02ff 1 -118 -96 228
* ...
* 0x2c00 - 0x2dff 22 -97 -96 228
* 0x2e00 - 0x2fff 23 -96 -96 228
* 0x3000 - 0x31ff 24 -95 -95 226
* ...
* 0xee00 - 0xefff 119 0 0 36
* ...
* 0xfe00 - 0xffff 127 +8 +8 20
*/
static inline int dB_to_cx25840_vol(int dB)
{
if (dB < -96)
dB = -96;
else if (dB > 8)
dB = 8;
return (dB + 119) << 9;
}
static inline int cx25840_vol_to_dB(int v)
{
if (v < (23 << 9))
v = (23 << 9);
else if (v > (127 << 9))
v = (127 << 9);
return (v >> 9) - 119;
}
static int snd_ivtv_mixer_tv_vol_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
uinfo->count = 1;
/* We're already translating values, just keep this control in dB */
uinfo->value.integer.min = -96;
uinfo->value.integer.max = 8;
uinfo->value.integer.step = 1;
return 0;
}
static int snd_ivtv_mixer_tv_vol_get(struct snd_kcontrol *kctl,
struct snd_ctl_elem_value *uctl)
{
struct snd_ivtv_card *itvsc = snd_kcontrol_chip(kctl);
struct ivtv *itv = to_ivtv(itvsc->v4l2_dev);
struct v4l2_control vctrl;
int ret;
vctrl.id = V4L2_CID_AUDIO_VOLUME;
vctrl.value = dB_to_cx25840_vol(uctl->value.integer.value[0]);
snd_ivtv_lock(itvsc);
ret = v4l2_subdev_call(itv->sd_audio, core, g_ctrl, &vctrl);
snd_ivtv_unlock(itvsc);
if (!ret)
uctl->value.integer.value[0] = cx25840_vol_to_dB(vctrl.value);
return ret;
}
static int snd_ivtv_mixer_tv_vol_put(struct snd_kcontrol *kctl,
struct snd_ctl_elem_value *uctl)
{
struct snd_ivtv_card *itvsc = snd_kcontrol_chip(kctl);
struct ivtv *itv = to_ivtv(itvsc->v4l2_dev);
struct v4l2_control vctrl;
int ret;
vctrl.id = V4L2_CID_AUDIO_VOLUME;
vctrl.value = dB_to_cx25840_vol(uctl->value.integer.value[0]);
snd_ivtv_lock(itvsc);
/* Fetch current state */
ret = v4l2_subdev_call(itv->sd_audio, core, g_ctrl, &vctrl);
if (ret ||
(cx25840_vol_to_dB(vctrl.value) != uctl->value.integer.value[0])) {
/* Set, if needed */
vctrl.value = dB_to_cx25840_vol(uctl->value.integer.value[0]);
ret = v4l2_subdev_call(itv->sd_audio, core, s_ctrl, &vctrl);
if (!ret)
ret = 1; /* Indicate control was changed w/o error */
}
snd_ivtv_unlock(itvsc);
return ret;
}
/* This is a bit of overkill, the slider is already in dB internally */
static DECLARE_TLV_DB_SCALE(snd_ivtv_mixer_tv_vol_db_scale, -9600, 100, 0);
static struct snd_kcontrol_new snd_ivtv_mixer_tv_vol __initdata = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Analog TV Capture Volume",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE |
SNDRV_CTL_ELEM_ACCESS_TLV_READ,
.info = snd_ivtv_mixer_tv_volume_info,
.get = snd_ivtv_mixer_tv_volume_get,
.put = snd_ivtv_mixer_tv_volume_put,
.tlv.p = snd_ivtv_mixer_tv_vol_db_scale
};
/* FIXME - add mute switch and balance, bass, treble sliders:
V4L2_CID_AUDIO_MUTE
V4L2_CID_AUDIO_BALANCE
V4L2_CID_AUDIO_BASS
V4L2_CID_AUDIO_TREBLE
*/
/* FIXME - add stereo, lang1, lang2, mono menu */
/* FIXME - add I2S volume */
int __init snd_ivtv_mixer_create(struct snd_ivtv_card *itvsc)
{
struct v4l2_device *v4l2_dev = itvsc->v4l2_dev;
struct snd_card *sc = itvsc->sc;
int ret;
strlcpy(sc->mixername, "CX2341[56] Mixer", sizeof(sc->mixername));
ret = snd_ctl_add(sc, snd_ctl_new1(snd_ivtv_mixer_tv_vol, itvsc));
if (ret) {
IVTV_ALSA_WARN("%s: failed to add %s control, err %d\n",
__func__, snd_ivtv_mixer_tv_vol.name, ret);
}
return ret;
}
| gpl-2.0 |
ltelg/kernel_lge_geeb-cm10.1 | arch/ia64/kernel/topology.c | 4448 | 11167 | /*
* 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.
*
* This file contains NUMA specific variables and functions which can
* be split away from DISCONTIGMEM and are used on NUMA machines with
* contiguous memory.
* 2002/08/07 Erich Focht <efocht@ess.nec.de>
* Populate cpu entries in sysfs for non-numa systems as well
* Intel Corporation - Ashok Raj
* 02/27/2006 Zhang, Yanmin
* Populate cpu cache entries in sysfs for cpu cache info
*/
#include <linux/cpu.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/node.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/bootmem.h>
#include <linux/nodemask.h>
#include <linux/notifier.h>
#include <linux/export.h>
#include <asm/mmzone.h>
#include <asm/numa.h>
#include <asm/cpu.h>
static struct ia64_cpu *sysfs_cpus;
void arch_fix_phys_package_id(int num, u32 slot)
{
#ifdef CONFIG_SMP
if (cpu_data(num)->socket_id == -1)
cpu_data(num)->socket_id = slot;
#endif
}
EXPORT_SYMBOL_GPL(arch_fix_phys_package_id);
#ifdef CONFIG_HOTPLUG_CPU
int __ref arch_register_cpu(int num)
{
#ifdef CONFIG_ACPI
/*
* If CPEI can be re-targeted or if this is not
* CPEI target, then it is hotpluggable
*/
if (can_cpei_retarget() || !is_cpu_cpei_target(num))
sysfs_cpus[num].cpu.hotpluggable = 1;
map_cpu_to_node(num, node_cpuid[num].nid);
#endif
return register_cpu(&sysfs_cpus[num].cpu, num);
}
EXPORT_SYMBOL(arch_register_cpu);
void __ref arch_unregister_cpu(int num)
{
unregister_cpu(&sysfs_cpus[num].cpu);
#ifdef CONFIG_ACPI
unmap_cpu_from_node(num, cpu_to_node(num));
#endif
}
EXPORT_SYMBOL(arch_unregister_cpu);
#else
static int __init arch_register_cpu(int num)
{
return register_cpu(&sysfs_cpus[num].cpu, num);
}
#endif /*CONFIG_HOTPLUG_CPU*/
static int __init topology_init(void)
{
int i, err = 0;
#ifdef CONFIG_NUMA
/*
* MCD - Do we want to register all ONLINE nodes, or all POSSIBLE nodes?
*/
for_each_online_node(i) {
if ((err = register_one_node(i)))
goto out;
}
#endif
sysfs_cpus = kzalloc(sizeof(struct ia64_cpu) * NR_CPUS, GFP_KERNEL);
if (!sysfs_cpus)
panic("kzalloc in topology_init failed - NR_CPUS too big?");
for_each_present_cpu(i) {
if((err = arch_register_cpu(i)))
goto out;
}
out:
return err;
}
subsys_initcall(topology_init);
/*
* Export cpu cache information through sysfs
*/
/*
* A bunch of string array to get pretty printing
*/
static const char *cache_types[] = {
"", /* not used */
"Instruction",
"Data",
"Unified" /* unified */
};
static const char *cache_mattrib[]={
"WriteThrough",
"WriteBack",
"", /* reserved */
"" /* reserved */
};
struct cache_info {
pal_cache_config_info_t cci;
cpumask_t shared_cpu_map;
int level;
int type;
struct kobject kobj;
};
struct cpu_cache_info {
struct cache_info *cache_leaves;
int num_cache_leaves;
struct kobject kobj;
};
static struct cpu_cache_info all_cpu_cache_info[NR_CPUS] __cpuinitdata;
#define LEAF_KOBJECT_PTR(x,y) (&all_cpu_cache_info[x].cache_leaves[y])
#ifdef CONFIG_SMP
static void __cpuinit cache_shared_cpu_map_setup( unsigned int cpu,
struct cache_info * this_leaf)
{
pal_cache_shared_info_t csi;
int num_shared, i = 0;
unsigned int j;
if (cpu_data(cpu)->threads_per_core <= 1 &&
cpu_data(cpu)->cores_per_socket <= 1) {
cpu_set(cpu, this_leaf->shared_cpu_map);
return;
}
if (ia64_pal_cache_shared_info(this_leaf->level,
this_leaf->type,
0,
&csi) != PAL_STATUS_SUCCESS)
return;
num_shared = (int) csi.num_shared;
do {
for_each_possible_cpu(j)
if (cpu_data(cpu)->socket_id == cpu_data(j)->socket_id
&& cpu_data(j)->core_id == csi.log1_cid
&& cpu_data(j)->thread_id == csi.log1_tid)
cpu_set(j, this_leaf->shared_cpu_map);
i++;
} while (i < num_shared &&
ia64_pal_cache_shared_info(this_leaf->level,
this_leaf->type,
i,
&csi) == PAL_STATUS_SUCCESS);
}
#else
static void __cpuinit cache_shared_cpu_map_setup(unsigned int cpu,
struct cache_info * this_leaf)
{
cpu_set(cpu, this_leaf->shared_cpu_map);
return;
}
#endif
static ssize_t show_coherency_line_size(struct cache_info *this_leaf,
char *buf)
{
return sprintf(buf, "%u\n", 1 << this_leaf->cci.pcci_line_size);
}
static ssize_t show_ways_of_associativity(struct cache_info *this_leaf,
char *buf)
{
return sprintf(buf, "%u\n", this_leaf->cci.pcci_assoc);
}
static ssize_t show_attributes(struct cache_info *this_leaf, char *buf)
{
return sprintf(buf,
"%s\n",
cache_mattrib[this_leaf->cci.pcci_cache_attr]);
}
static ssize_t show_size(struct cache_info *this_leaf, char *buf)
{
return sprintf(buf, "%uK\n", this_leaf->cci.pcci_cache_size / 1024);
}
static ssize_t show_number_of_sets(struct cache_info *this_leaf, char *buf)
{
unsigned number_of_sets = this_leaf->cci.pcci_cache_size;
number_of_sets /= this_leaf->cci.pcci_assoc;
number_of_sets /= 1 << this_leaf->cci.pcci_line_size;
return sprintf(buf, "%u\n", number_of_sets);
}
static ssize_t show_shared_cpu_map(struct cache_info *this_leaf, char *buf)
{
ssize_t len;
cpumask_t shared_cpu_map;
cpumask_and(&shared_cpu_map,
&this_leaf->shared_cpu_map, cpu_online_mask);
len = cpumask_scnprintf(buf, NR_CPUS+1, &shared_cpu_map);
len += sprintf(buf+len, "\n");
return len;
}
static ssize_t show_type(struct cache_info *this_leaf, char *buf)
{
int type = this_leaf->type + this_leaf->cci.pcci_unified;
return sprintf(buf, "%s\n", cache_types[type]);
}
static ssize_t show_level(struct cache_info *this_leaf, char *buf)
{
return sprintf(buf, "%u\n", this_leaf->level);
}
struct cache_attr {
struct attribute attr;
ssize_t (*show)(struct cache_info *, char *);
ssize_t (*store)(struct cache_info *, const char *, size_t count);
};
#ifdef define_one_ro
#undef define_one_ro
#endif
#define define_one_ro(_name) \
static struct cache_attr _name = \
__ATTR(_name, 0444, show_##_name, NULL)
define_one_ro(level);
define_one_ro(type);
define_one_ro(coherency_line_size);
define_one_ro(ways_of_associativity);
define_one_ro(size);
define_one_ro(number_of_sets);
define_one_ro(shared_cpu_map);
define_one_ro(attributes);
static struct attribute * cache_default_attrs[] = {
&type.attr,
&level.attr,
&coherency_line_size.attr,
&ways_of_associativity.attr,
&attributes.attr,
&size.attr,
&number_of_sets.attr,
&shared_cpu_map.attr,
NULL
};
#define to_object(k) container_of(k, struct cache_info, kobj)
#define to_attr(a) container_of(a, struct cache_attr, attr)
static ssize_t cache_show(struct kobject * kobj, struct attribute * attr, char * buf)
{
struct cache_attr *fattr = to_attr(attr);
struct cache_info *this_leaf = to_object(kobj);
ssize_t ret;
ret = fattr->show ? fattr->show(this_leaf, buf) : 0;
return ret;
}
static const struct sysfs_ops cache_sysfs_ops = {
.show = cache_show
};
static struct kobj_type cache_ktype = {
.sysfs_ops = &cache_sysfs_ops,
.default_attrs = cache_default_attrs,
};
static struct kobj_type cache_ktype_percpu_entry = {
.sysfs_ops = &cache_sysfs_ops,
};
static void __cpuinit cpu_cache_sysfs_exit(unsigned int cpu)
{
kfree(all_cpu_cache_info[cpu].cache_leaves);
all_cpu_cache_info[cpu].cache_leaves = NULL;
all_cpu_cache_info[cpu].num_cache_leaves = 0;
memset(&all_cpu_cache_info[cpu].kobj, 0, sizeof(struct kobject));
return;
}
static int __cpuinit cpu_cache_sysfs_init(unsigned int cpu)
{
unsigned long i, levels, unique_caches;
pal_cache_config_info_t cci;
int j;
long status;
struct cache_info *this_cache;
int num_cache_leaves = 0;
if ((status = ia64_pal_cache_summary(&levels, &unique_caches)) != 0) {
printk(KERN_ERR "ia64_pal_cache_summary=%ld\n", status);
return -1;
}
this_cache=kzalloc(sizeof(struct cache_info)*unique_caches,
GFP_KERNEL);
if (this_cache == NULL)
return -ENOMEM;
for (i=0; i < levels; i++) {
for (j=2; j >0 ; j--) {
if ((status=ia64_pal_cache_config_info(i,j, &cci)) !=
PAL_STATUS_SUCCESS)
continue;
this_cache[num_cache_leaves].cci = cci;
this_cache[num_cache_leaves].level = i + 1;
this_cache[num_cache_leaves].type = j;
cache_shared_cpu_map_setup(cpu,
&this_cache[num_cache_leaves]);
num_cache_leaves ++;
}
}
all_cpu_cache_info[cpu].cache_leaves = this_cache;
all_cpu_cache_info[cpu].num_cache_leaves = num_cache_leaves;
memset(&all_cpu_cache_info[cpu].kobj, 0, sizeof(struct kobject));
return 0;
}
/* Add cache interface for CPU device */
static int __cpuinit cache_add_dev(struct device * sys_dev)
{
unsigned int cpu = sys_dev->id;
unsigned long i, j;
struct cache_info *this_object;
int retval = 0;
cpumask_t oldmask;
if (all_cpu_cache_info[cpu].kobj.parent)
return 0;
oldmask = current->cpus_allowed;
retval = set_cpus_allowed_ptr(current, cpumask_of(cpu));
if (unlikely(retval))
return retval;
retval = cpu_cache_sysfs_init(cpu);
set_cpus_allowed_ptr(current, &oldmask);
if (unlikely(retval < 0))
return retval;
retval = kobject_init_and_add(&all_cpu_cache_info[cpu].kobj,
&cache_ktype_percpu_entry, &sys_dev->kobj,
"%s", "cache");
if (unlikely(retval < 0)) {
cpu_cache_sysfs_exit(cpu);
return retval;
}
for (i = 0; i < all_cpu_cache_info[cpu].num_cache_leaves; i++) {
this_object = LEAF_KOBJECT_PTR(cpu,i);
retval = kobject_init_and_add(&(this_object->kobj),
&cache_ktype,
&all_cpu_cache_info[cpu].kobj,
"index%1lu", i);
if (unlikely(retval)) {
for (j = 0; j < i; j++) {
kobject_put(&(LEAF_KOBJECT_PTR(cpu,j)->kobj));
}
kobject_put(&all_cpu_cache_info[cpu].kobj);
cpu_cache_sysfs_exit(cpu);
return retval;
}
kobject_uevent(&(this_object->kobj), KOBJ_ADD);
}
kobject_uevent(&all_cpu_cache_info[cpu].kobj, KOBJ_ADD);
return retval;
}
/* Remove cache interface for CPU device */
static int __cpuinit cache_remove_dev(struct device * sys_dev)
{
unsigned int cpu = sys_dev->id;
unsigned long i;
for (i = 0; i < all_cpu_cache_info[cpu].num_cache_leaves; i++)
kobject_put(&(LEAF_KOBJECT_PTR(cpu,i)->kobj));
if (all_cpu_cache_info[cpu].kobj.parent) {
kobject_put(&all_cpu_cache_info[cpu].kobj);
memset(&all_cpu_cache_info[cpu].kobj,
0,
sizeof(struct kobject));
}
cpu_cache_sysfs_exit(cpu);
return 0;
}
/*
* When a cpu is hot-plugged, do a check and initiate
* cache kobject if necessary
*/
static int __cpuinit cache_cpu_callback(struct notifier_block *nfb,
unsigned long action, void *hcpu)
{
unsigned int cpu = (unsigned long)hcpu;
struct device *sys_dev;
sys_dev = get_cpu_device(cpu);
switch (action) {
case CPU_ONLINE:
case CPU_ONLINE_FROZEN:
cache_add_dev(sys_dev);
break;
case CPU_DEAD:
case CPU_DEAD_FROZEN:
cache_remove_dev(sys_dev);
break;
}
return NOTIFY_OK;
}
static struct notifier_block __cpuinitdata cache_cpu_notifier =
{
.notifier_call = cache_cpu_callback
};
static int __init cache_sysfs_init(void)
{
int i;
for_each_online_cpu(i) {
struct device *sys_dev = get_cpu_device((unsigned int)i);
cache_add_dev(sys_dev);
}
register_hotcpu_notifier(&cache_cpu_notifier);
return 0;
}
device_initcall(cache_sysfs_init);
| gpl-2.0 |
CM-Tab-S/stock_chagalllte | arch/powerpc/platforms/cell/spufs/context.c | 7520 | 4880 | /*
* SPU file system -- SPU context management
*
* (C) Copyright IBM Deutschland Entwicklung GmbH 2005
*
* Author: Arnd Bergmann <arndb@de.ibm.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/atomic.h>
#include <linux/sched.h>
#include <asm/spu.h>
#include <asm/spu_csa.h>
#include "spufs.h"
#include "sputrace.h"
atomic_t nr_spu_contexts = ATOMIC_INIT(0);
struct spu_context *alloc_spu_context(struct spu_gang *gang)
{
struct spu_context *ctx;
struct timespec ts;
ctx = kzalloc(sizeof *ctx, GFP_KERNEL);
if (!ctx)
goto out;
/* Binding to physical processor deferred
* until spu_activate().
*/
if (spu_init_csa(&ctx->csa))
goto out_free;
spin_lock_init(&ctx->mmio_lock);
mutex_init(&ctx->mapping_lock);
kref_init(&ctx->kref);
mutex_init(&ctx->state_mutex);
mutex_init(&ctx->run_mutex);
init_waitqueue_head(&ctx->ibox_wq);
init_waitqueue_head(&ctx->wbox_wq);
init_waitqueue_head(&ctx->stop_wq);
init_waitqueue_head(&ctx->mfc_wq);
init_waitqueue_head(&ctx->run_wq);
ctx->state = SPU_STATE_SAVED;
ctx->ops = &spu_backing_ops;
ctx->owner = get_task_mm(current);
INIT_LIST_HEAD(&ctx->rq);
INIT_LIST_HEAD(&ctx->aff_list);
if (gang)
spu_gang_add_ctx(gang, ctx);
__spu_update_sched_info(ctx);
spu_set_timeslice(ctx);
ctx->stats.util_state = SPU_UTIL_IDLE_LOADED;
ktime_get_ts(&ts);
ctx->stats.tstamp = timespec_to_ns(&ts);
atomic_inc(&nr_spu_contexts);
goto out;
out_free:
kfree(ctx);
ctx = NULL;
out:
return ctx;
}
void destroy_spu_context(struct kref *kref)
{
struct spu_context *ctx;
ctx = container_of(kref, struct spu_context, kref);
spu_context_nospu_trace(destroy_spu_context__enter, ctx);
mutex_lock(&ctx->state_mutex);
spu_deactivate(ctx);
mutex_unlock(&ctx->state_mutex);
spu_fini_csa(&ctx->csa);
if (ctx->gang)
spu_gang_remove_ctx(ctx->gang, ctx);
if (ctx->prof_priv_kref)
kref_put(ctx->prof_priv_kref, ctx->prof_priv_release);
BUG_ON(!list_empty(&ctx->rq));
atomic_dec(&nr_spu_contexts);
kfree(ctx->switch_log);
kfree(ctx);
}
struct spu_context * get_spu_context(struct spu_context *ctx)
{
kref_get(&ctx->kref);
return ctx;
}
int put_spu_context(struct spu_context *ctx)
{
return kref_put(&ctx->kref, &destroy_spu_context);
}
/* give up the mm reference when the context is about to be destroyed */
void spu_forget(struct spu_context *ctx)
{
struct mm_struct *mm;
/*
* This is basically an open-coded spu_acquire_saved, except that
* we don't acquire the state mutex interruptible, and we don't
* want this context to be rescheduled on release.
*/
mutex_lock(&ctx->state_mutex);
if (ctx->state != SPU_STATE_SAVED)
spu_deactivate(ctx);
mm = ctx->owner;
ctx->owner = NULL;
mmput(mm);
spu_release(ctx);
}
void spu_unmap_mappings(struct spu_context *ctx)
{
mutex_lock(&ctx->mapping_lock);
if (ctx->local_store)
unmap_mapping_range(ctx->local_store, 0, LS_SIZE, 1);
if (ctx->mfc)
unmap_mapping_range(ctx->mfc, 0, SPUFS_MFC_MAP_SIZE, 1);
if (ctx->cntl)
unmap_mapping_range(ctx->cntl, 0, SPUFS_CNTL_MAP_SIZE, 1);
if (ctx->signal1)
unmap_mapping_range(ctx->signal1, 0, SPUFS_SIGNAL_MAP_SIZE, 1);
if (ctx->signal2)
unmap_mapping_range(ctx->signal2, 0, SPUFS_SIGNAL_MAP_SIZE, 1);
if (ctx->mss)
unmap_mapping_range(ctx->mss, 0, SPUFS_MSS_MAP_SIZE, 1);
if (ctx->psmap)
unmap_mapping_range(ctx->psmap, 0, SPUFS_PS_MAP_SIZE, 1);
mutex_unlock(&ctx->mapping_lock);
}
/**
* spu_acquire_saved - lock spu contex and make sure it is in saved state
* @ctx: spu contex to lock
*/
int spu_acquire_saved(struct spu_context *ctx)
{
int ret;
spu_context_nospu_trace(spu_acquire_saved__enter, ctx);
ret = spu_acquire(ctx);
if (ret)
return ret;
if (ctx->state != SPU_STATE_SAVED) {
set_bit(SPU_SCHED_WAS_ACTIVE, &ctx->sched_flags);
spu_deactivate(ctx);
}
return 0;
}
/**
* spu_release_saved - unlock spu context and return it to the runqueue
* @ctx: context to unlock
*/
void spu_release_saved(struct spu_context *ctx)
{
BUG_ON(ctx->state != SPU_STATE_SAVED);
if (test_and_clear_bit(SPU_SCHED_WAS_ACTIVE, &ctx->sched_flags) &&
test_bit(SPU_SCHED_SPU_RUN, &ctx->sched_flags))
spu_activate(ctx, 0);
spu_release(ctx);
}
| gpl-2.0 |
benschhold/android_kernel_oneplus_msm8994_custom | fs/ntfs/mft.c | 9312 | 101923 | /**
* mft.c - NTFS kernel mft record operations. Part of the Linux-NTFS project.
*
* Copyright (c) 2001-2012 Anton Altaparmakov and Tuxera Inc.
* Copyright (c) 2002 Richard Russon
*
* This program/include file 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/include file 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 (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/buffer_head.h>
#include <linux/slab.h>
#include <linux/swap.h>
#include "attrib.h"
#include "aops.h"
#include "bitmap.h"
#include "debug.h"
#include "dir.h"
#include "lcnalloc.h"
#include "malloc.h"
#include "mft.h"
#include "ntfs.h"
/**
* map_mft_record_page - map the page in which a specific mft record resides
* @ni: ntfs inode whose mft record page to map
*
* This maps the page in which the mft record of the ntfs inode @ni is situated
* and returns a pointer to the mft record within the mapped page.
*
* Return value needs to be checked with IS_ERR() and if that is true PTR_ERR()
* contains the negative error code returned.
*/
static inline MFT_RECORD *map_mft_record_page(ntfs_inode *ni)
{
loff_t i_size;
ntfs_volume *vol = ni->vol;
struct inode *mft_vi = vol->mft_ino;
struct page *page;
unsigned long index, end_index;
unsigned ofs;
BUG_ON(ni->page);
/*
* The index into the page cache and the offset within the page cache
* page of the wanted mft record. FIXME: We need to check for
* overflowing the unsigned long, but I don't think we would ever get
* here if the volume was that big...
*/
index = (u64)ni->mft_no << vol->mft_record_size_bits >>
PAGE_CACHE_SHIFT;
ofs = (ni->mft_no << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
i_size = i_size_read(mft_vi);
/* The maximum valid index into the page cache for $MFT's data. */
end_index = i_size >> PAGE_CACHE_SHIFT;
/* If the wanted index is out of bounds the mft record doesn't exist. */
if (unlikely(index >= end_index)) {
if (index > end_index || (i_size & ~PAGE_CACHE_MASK) < ofs +
vol->mft_record_size) {
page = ERR_PTR(-ENOENT);
ntfs_error(vol->sb, "Attempt to read mft record 0x%lx, "
"which is beyond the end of the mft. "
"This is probably a bug in the ntfs "
"driver.", ni->mft_no);
goto err_out;
}
}
/* Read, map, and pin the page. */
page = ntfs_map_page(mft_vi->i_mapping, index);
if (likely(!IS_ERR(page))) {
/* Catch multi sector transfer fixup errors. */
if (likely(ntfs_is_mft_recordp((le32*)(page_address(page) +
ofs)))) {
ni->page = page;
ni->page_ofs = ofs;
return page_address(page) + ofs;
}
ntfs_error(vol->sb, "Mft record 0x%lx is corrupt. "
"Run chkdsk.", ni->mft_no);
ntfs_unmap_page(page);
page = ERR_PTR(-EIO);
NVolSetErrors(vol);
}
err_out:
ni->page = NULL;
ni->page_ofs = 0;
return (void*)page;
}
/**
* map_mft_record - map, pin and lock an mft record
* @ni: ntfs inode whose MFT record to map
*
* First, take the mrec_lock mutex. We might now be sleeping, while waiting
* for the mutex if it was already locked by someone else.
*
* The page of the record is mapped using map_mft_record_page() before being
* returned to the caller.
*
* This in turn uses ntfs_map_page() to get the page containing the wanted mft
* record (it in turn calls read_cache_page() which reads it in from disk if
* necessary, increments the use count on the page so that it cannot disappear
* under us and returns a reference to the page cache page).
*
* If read_cache_page() invokes ntfs_readpage() to load the page from disk, it
* sets PG_locked and clears PG_uptodate on the page. Once I/O has completed
* and the post-read mst fixups on each mft record in the page have been
* performed, the page gets PG_uptodate set and PG_locked cleared (this is done
* in our asynchronous I/O completion handler end_buffer_read_mft_async()).
* ntfs_map_page() waits for PG_locked to become clear and checks if
* PG_uptodate is set and returns an error code if not. This provides
* sufficient protection against races when reading/using the page.
*
* However there is the write mapping to think about. Doing the above described
* checking here will be fine, because when initiating the write we will set
* PG_locked and clear PG_uptodate making sure nobody is touching the page
* contents. Doing the locking this way means that the commit to disk code in
* the page cache code paths is automatically sufficiently locked with us as
* we will not touch a page that has been locked or is not uptodate. The only
* locking problem then is them locking the page while we are accessing it.
*
* So that code will end up having to own the mrec_lock of all mft
* records/inodes present in the page before I/O can proceed. In that case we
* wouldn't need to bother with PG_locked and PG_uptodate as nobody will be
* accessing anything without owning the mrec_lock mutex. But we do need to
* use them because of the read_cache_page() invocation and the code becomes so
* much simpler this way that it is well worth it.
*
* The mft record is now ours and we return a pointer to it. You need to check
* the returned pointer with IS_ERR() and if that is true, PTR_ERR() will return
* the error code.
*
* NOTE: Caller is responsible for setting the mft record dirty before calling
* unmap_mft_record(). This is obviously only necessary if the caller really
* modified the mft record...
* Q: Do we want to recycle one of the VFS inode state bits instead?
* A: No, the inode ones mean we want to change the mft record, not we want to
* write it out.
*/
MFT_RECORD *map_mft_record(ntfs_inode *ni)
{
MFT_RECORD *m;
ntfs_debug("Entering for mft_no 0x%lx.", ni->mft_no);
/* Make sure the ntfs inode doesn't go away. */
atomic_inc(&ni->count);
/* Serialize access to this mft record. */
mutex_lock(&ni->mrec_lock);
m = map_mft_record_page(ni);
if (likely(!IS_ERR(m)))
return m;
mutex_unlock(&ni->mrec_lock);
atomic_dec(&ni->count);
ntfs_error(ni->vol->sb, "Failed with error code %lu.", -PTR_ERR(m));
return m;
}
/**
* unmap_mft_record_page - unmap the page in which a specific mft record resides
* @ni: ntfs inode whose mft record page to unmap
*
* This unmaps the page in which the mft record of the ntfs inode @ni is
* situated and returns. This is a NOOP if highmem is not configured.
*
* The unmap happens via ntfs_unmap_page() which in turn decrements the use
* count on the page thus releasing it from the pinned state.
*
* We do not actually unmap the page from memory of course, as that will be
* done by the page cache code itself when memory pressure increases or
* whatever.
*/
static inline void unmap_mft_record_page(ntfs_inode *ni)
{
BUG_ON(!ni->page);
// TODO: If dirty, blah...
ntfs_unmap_page(ni->page);
ni->page = NULL;
ni->page_ofs = 0;
return;
}
/**
* unmap_mft_record - release a mapped mft record
* @ni: ntfs inode whose MFT record to unmap
*
* We release the page mapping and the mrec_lock mutex which unmaps the mft
* record and releases it for others to get hold of. We also release the ntfs
* inode by decrementing the ntfs inode reference count.
*
* NOTE: If caller has modified the mft record, it is imperative to set the mft
* record dirty BEFORE calling unmap_mft_record().
*/
void unmap_mft_record(ntfs_inode *ni)
{
struct page *page = ni->page;
BUG_ON(!page);
ntfs_debug("Entering for mft_no 0x%lx.", ni->mft_no);
unmap_mft_record_page(ni);
mutex_unlock(&ni->mrec_lock);
atomic_dec(&ni->count);
/*
* If pure ntfs_inode, i.e. no vfs inode attached, we leave it to
* ntfs_clear_extent_inode() in the extent inode case, and to the
* caller in the non-extent, yet pure ntfs inode case, to do the actual
* tear down of all structures and freeing of all allocated memory.
*/
return;
}
/**
* map_extent_mft_record - load an extent inode and attach it to its base
* @base_ni: base ntfs inode
* @mref: mft reference of the extent inode to load
* @ntfs_ino: on successful return, pointer to the ntfs_inode structure
*
* Load the extent mft record @mref and attach it to its base inode @base_ni.
* Return the mapped extent mft record if IS_ERR(result) is false. Otherwise
* PTR_ERR(result) gives the negative error code.
*
* On successful return, @ntfs_ino contains a pointer to the ntfs_inode
* structure of the mapped extent inode.
*/
MFT_RECORD *map_extent_mft_record(ntfs_inode *base_ni, MFT_REF mref,
ntfs_inode **ntfs_ino)
{
MFT_RECORD *m;
ntfs_inode *ni = NULL;
ntfs_inode **extent_nis = NULL;
int i;
unsigned long mft_no = MREF(mref);
u16 seq_no = MSEQNO(mref);
bool destroy_ni = false;
ntfs_debug("Mapping extent mft record 0x%lx (base mft record 0x%lx).",
mft_no, base_ni->mft_no);
/* Make sure the base ntfs inode doesn't go away. */
atomic_inc(&base_ni->count);
/*
* Check if this extent inode has already been added to the base inode,
* in which case just return it. If not found, add it to the base
* inode before returning it.
*/
mutex_lock(&base_ni->extent_lock);
if (base_ni->nr_extents > 0) {
extent_nis = base_ni->ext.extent_ntfs_inos;
for (i = 0; i < base_ni->nr_extents; i++) {
if (mft_no != extent_nis[i]->mft_no)
continue;
ni = extent_nis[i];
/* Make sure the ntfs inode doesn't go away. */
atomic_inc(&ni->count);
break;
}
}
if (likely(ni != NULL)) {
mutex_unlock(&base_ni->extent_lock);
atomic_dec(&base_ni->count);
/* We found the record; just have to map and return it. */
m = map_mft_record(ni);
/* map_mft_record() has incremented this on success. */
atomic_dec(&ni->count);
if (likely(!IS_ERR(m))) {
/* Verify the sequence number. */
if (likely(le16_to_cpu(m->sequence_number) == seq_no)) {
ntfs_debug("Done 1.");
*ntfs_ino = ni;
return m;
}
unmap_mft_record(ni);
ntfs_error(base_ni->vol->sb, "Found stale extent mft "
"reference! Corrupt filesystem. "
"Run chkdsk.");
return ERR_PTR(-EIO);
}
map_err_out:
ntfs_error(base_ni->vol->sb, "Failed to map extent "
"mft record, error code %ld.", -PTR_ERR(m));
return m;
}
/* Record wasn't there. Get a new ntfs inode and initialize it. */
ni = ntfs_new_extent_inode(base_ni->vol->sb, mft_no);
if (unlikely(!ni)) {
mutex_unlock(&base_ni->extent_lock);
atomic_dec(&base_ni->count);
return ERR_PTR(-ENOMEM);
}
ni->vol = base_ni->vol;
ni->seq_no = seq_no;
ni->nr_extents = -1;
ni->ext.base_ntfs_ino = base_ni;
/* Now map the record. */
m = map_mft_record(ni);
if (IS_ERR(m)) {
mutex_unlock(&base_ni->extent_lock);
atomic_dec(&base_ni->count);
ntfs_clear_extent_inode(ni);
goto map_err_out;
}
/* Verify the sequence number if it is present. */
if (seq_no && (le16_to_cpu(m->sequence_number) != seq_no)) {
ntfs_error(base_ni->vol->sb, "Found stale extent mft "
"reference! Corrupt filesystem. Run chkdsk.");
destroy_ni = true;
m = ERR_PTR(-EIO);
goto unm_err_out;
}
/* Attach extent inode to base inode, reallocating memory if needed. */
if (!(base_ni->nr_extents & 3)) {
ntfs_inode **tmp;
int new_size = (base_ni->nr_extents + 4) * sizeof(ntfs_inode *);
tmp = kmalloc(new_size, GFP_NOFS);
if (unlikely(!tmp)) {
ntfs_error(base_ni->vol->sb, "Failed to allocate "
"internal buffer.");
destroy_ni = true;
m = ERR_PTR(-ENOMEM);
goto unm_err_out;
}
if (base_ni->nr_extents) {
BUG_ON(!base_ni->ext.extent_ntfs_inos);
memcpy(tmp, base_ni->ext.extent_ntfs_inos, new_size -
4 * sizeof(ntfs_inode *));
kfree(base_ni->ext.extent_ntfs_inos);
}
base_ni->ext.extent_ntfs_inos = tmp;
}
base_ni->ext.extent_ntfs_inos[base_ni->nr_extents++] = ni;
mutex_unlock(&base_ni->extent_lock);
atomic_dec(&base_ni->count);
ntfs_debug("Done 2.");
*ntfs_ino = ni;
return m;
unm_err_out:
unmap_mft_record(ni);
mutex_unlock(&base_ni->extent_lock);
atomic_dec(&base_ni->count);
/*
* If the extent inode was not attached to the base inode we need to
* release it or we will leak memory.
*/
if (destroy_ni)
ntfs_clear_extent_inode(ni);
return m;
}
#ifdef NTFS_RW
/**
* __mark_mft_record_dirty - set the mft record and the page containing it dirty
* @ni: ntfs inode describing the mapped mft record
*
* Internal function. Users should call mark_mft_record_dirty() instead.
*
* Set the mapped (extent) mft record of the (base or extent) ntfs inode @ni,
* as well as the page containing the mft record, dirty. Also, mark the base
* vfs inode dirty. This ensures that any changes to the mft record are
* written out to disk.
*
* NOTE: We only set I_DIRTY_SYNC and I_DIRTY_DATASYNC (and not I_DIRTY_PAGES)
* on the base vfs inode, because even though file data may have been modified,
* it is dirty in the inode meta data rather than the data page cache of the
* inode, and thus there are no data pages that need writing out. Therefore, a
* full mark_inode_dirty() is overkill. A mark_inode_dirty_sync(), on the
* other hand, is not sufficient, because ->write_inode needs to be called even
* in case of fdatasync. This needs to happen or the file data would not
* necessarily hit the device synchronously, even though the vfs inode has the
* O_SYNC flag set. Also, I_DIRTY_DATASYNC simply "feels" better than just
* I_DIRTY_SYNC, since the file data has not actually hit the block device yet,
* which is not what I_DIRTY_SYNC on its own would suggest.
*/
void __mark_mft_record_dirty(ntfs_inode *ni)
{
ntfs_inode *base_ni;
ntfs_debug("Entering for inode 0x%lx.", ni->mft_no);
BUG_ON(NInoAttr(ni));
mark_ntfs_record_dirty(ni->page, ni->page_ofs);
/* Determine the base vfs inode and mark it dirty, too. */
mutex_lock(&ni->extent_lock);
if (likely(ni->nr_extents >= 0))
base_ni = ni;
else
base_ni = ni->ext.base_ntfs_ino;
mutex_unlock(&ni->extent_lock);
__mark_inode_dirty(VFS_I(base_ni), I_DIRTY_SYNC | I_DIRTY_DATASYNC);
}
static const char *ntfs_please_email = "Please email "
"linux-ntfs-dev@lists.sourceforge.net and say that you saw "
"this message. Thank you.";
/**
* ntfs_sync_mft_mirror_umount - synchronise an mft record to the mft mirror
* @vol: ntfs volume on which the mft record to synchronize resides
* @mft_no: mft record number of mft record to synchronize
* @m: mapped, mst protected (extent) mft record to synchronize
*
* Write the mapped, mst protected (extent) mft record @m with mft record
* number @mft_no to the mft mirror ($MFTMirr) of the ntfs volume @vol,
* bypassing the page cache and the $MFTMirr inode itself.
*
* This function is only for use at umount time when the mft mirror inode has
* already been disposed off. We BUG() if we are called while the mft mirror
* inode is still attached to the volume.
*
* On success return 0. On error return -errno.
*
* NOTE: This function is not implemented yet as I am not convinced it can
* actually be triggered considering the sequence of commits we do in super.c::
* ntfs_put_super(). But just in case we provide this place holder as the
* alternative would be either to BUG() or to get a NULL pointer dereference
* and Oops.
*/
static int ntfs_sync_mft_mirror_umount(ntfs_volume *vol,
const unsigned long mft_no, MFT_RECORD *m)
{
BUG_ON(vol->mftmirr_ino);
ntfs_error(vol->sb, "Umount time mft mirror syncing is not "
"implemented yet. %s", ntfs_please_email);
return -EOPNOTSUPP;
}
/**
* ntfs_sync_mft_mirror - synchronize an mft record to the mft mirror
* @vol: ntfs volume on which the mft record to synchronize resides
* @mft_no: mft record number of mft record to synchronize
* @m: mapped, mst protected (extent) mft record to synchronize
* @sync: if true, wait for i/o completion
*
* Write the mapped, mst protected (extent) mft record @m with mft record
* number @mft_no to the mft mirror ($MFTMirr) of the ntfs volume @vol.
*
* On success return 0. On error return -errno and set the volume errors flag
* in the ntfs volume @vol.
*
* NOTE: We always perform synchronous i/o and ignore the @sync parameter.
*
* TODO: If @sync is false, want to do truly asynchronous i/o, i.e. just
* schedule i/o via ->writepage or do it via kntfsd or whatever.
*/
int ntfs_sync_mft_mirror(ntfs_volume *vol, const unsigned long mft_no,
MFT_RECORD *m, int sync)
{
struct page *page;
unsigned int blocksize = vol->sb->s_blocksize;
int max_bhs = vol->mft_record_size / blocksize;
struct buffer_head *bhs[max_bhs];
struct buffer_head *bh, *head;
u8 *kmirr;
runlist_element *rl;
unsigned int block_start, block_end, m_start, m_end, page_ofs;
int i_bhs, nr_bhs, err = 0;
unsigned char blocksize_bits = vol->sb->s_blocksize_bits;
ntfs_debug("Entering for inode 0x%lx.", mft_no);
BUG_ON(!max_bhs);
if (unlikely(!vol->mftmirr_ino)) {
/* This could happen during umount... */
err = ntfs_sync_mft_mirror_umount(vol, mft_no, m);
if (likely(!err))
return err;
goto err_out;
}
/* Get the page containing the mirror copy of the mft record @m. */
page = ntfs_map_page(vol->mftmirr_ino->i_mapping, mft_no >>
(PAGE_CACHE_SHIFT - vol->mft_record_size_bits));
if (IS_ERR(page)) {
ntfs_error(vol->sb, "Failed to map mft mirror page.");
err = PTR_ERR(page);
goto err_out;
}
lock_page(page);
BUG_ON(!PageUptodate(page));
ClearPageUptodate(page);
/* Offset of the mft mirror record inside the page. */
page_ofs = (mft_no << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
/* The address in the page of the mirror copy of the mft record @m. */
kmirr = page_address(page) + page_ofs;
/* Copy the mst protected mft record to the mirror. */
memcpy(kmirr, m, vol->mft_record_size);
/* Create uptodate buffers if not present. */
if (unlikely(!page_has_buffers(page))) {
struct buffer_head *tail;
bh = head = alloc_page_buffers(page, blocksize, 1);
do {
set_buffer_uptodate(bh);
tail = bh;
bh = bh->b_this_page;
} while (bh);
tail->b_this_page = head;
attach_page_buffers(page, head);
}
bh = head = page_buffers(page);
BUG_ON(!bh);
rl = NULL;
nr_bhs = 0;
block_start = 0;
m_start = kmirr - (u8*)page_address(page);
m_end = m_start + vol->mft_record_size;
do {
block_end = block_start + blocksize;
/* If the buffer is outside the mft record, skip it. */
if (block_end <= m_start)
continue;
if (unlikely(block_start >= m_end))
break;
/* Need to map the buffer if it is not mapped already. */
if (unlikely(!buffer_mapped(bh))) {
VCN vcn;
LCN lcn;
unsigned int vcn_ofs;
bh->b_bdev = vol->sb->s_bdev;
/* Obtain the vcn and offset of the current block. */
vcn = ((VCN)mft_no << vol->mft_record_size_bits) +
(block_start - m_start);
vcn_ofs = vcn & vol->cluster_size_mask;
vcn >>= vol->cluster_size_bits;
if (!rl) {
down_read(&NTFS_I(vol->mftmirr_ino)->
runlist.lock);
rl = NTFS_I(vol->mftmirr_ino)->runlist.rl;
/*
* $MFTMirr always has the whole of its runlist
* in memory.
*/
BUG_ON(!rl);
}
/* Seek to element containing target vcn. */
while (rl->length && rl[1].vcn <= vcn)
rl++;
lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
/* For $MFTMirr, only lcn >= 0 is a successful remap. */
if (likely(lcn >= 0)) {
/* Setup buffer head to correct block. */
bh->b_blocknr = ((lcn <<
vol->cluster_size_bits) +
vcn_ofs) >> blocksize_bits;
set_buffer_mapped(bh);
} else {
bh->b_blocknr = -1;
ntfs_error(vol->sb, "Cannot write mft mirror "
"record 0x%lx because its "
"location on disk could not "
"be determined (error code "
"%lli).", mft_no,
(long long)lcn);
err = -EIO;
}
}
BUG_ON(!buffer_uptodate(bh));
BUG_ON(!nr_bhs && (m_start != block_start));
BUG_ON(nr_bhs >= max_bhs);
bhs[nr_bhs++] = bh;
BUG_ON((nr_bhs >= max_bhs) && (m_end != block_end));
} while (block_start = block_end, (bh = bh->b_this_page) != head);
if (unlikely(rl))
up_read(&NTFS_I(vol->mftmirr_ino)->runlist.lock);
if (likely(!err)) {
/* Lock buffers and start synchronous write i/o on them. */
for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
struct buffer_head *tbh = bhs[i_bhs];
if (!trylock_buffer(tbh))
BUG();
BUG_ON(!buffer_uptodate(tbh));
clear_buffer_dirty(tbh);
get_bh(tbh);
tbh->b_end_io = end_buffer_write_sync;
submit_bh(WRITE, tbh);
}
/* Wait on i/o completion of buffers. */
for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
struct buffer_head *tbh = bhs[i_bhs];
wait_on_buffer(tbh);
if (unlikely(!buffer_uptodate(tbh))) {
err = -EIO;
/*
* Set the buffer uptodate so the page and
* buffer states do not become out of sync.
*/
set_buffer_uptodate(tbh);
}
}
} else /* if (unlikely(err)) */ {
/* Clean the buffers. */
for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++)
clear_buffer_dirty(bhs[i_bhs]);
}
/* Current state: all buffers are clean, unlocked, and uptodate. */
/* Remove the mst protection fixups again. */
post_write_mst_fixup((NTFS_RECORD*)kmirr);
flush_dcache_page(page);
SetPageUptodate(page);
unlock_page(page);
ntfs_unmap_page(page);
if (likely(!err)) {
ntfs_debug("Done.");
} else {
ntfs_error(vol->sb, "I/O error while writing mft mirror "
"record 0x%lx!", mft_no);
err_out:
ntfs_error(vol->sb, "Failed to synchronize $MFTMirr (error "
"code %i). Volume will be left marked dirty "
"on umount. Run ntfsfix on the partition "
"after umounting to correct this.", -err);
NVolSetErrors(vol);
}
return err;
}
/**
* write_mft_record_nolock - write out a mapped (extent) mft record
* @ni: ntfs inode describing the mapped (extent) mft record
* @m: mapped (extent) mft record to write
* @sync: if true, wait for i/o completion
*
* Write the mapped (extent) mft record @m described by the (regular or extent)
* ntfs inode @ni to backing store. If the mft record @m has a counterpart in
* the mft mirror, that is also updated.
*
* We only write the mft record if the ntfs inode @ni is dirty and the first
* buffer belonging to its mft record is dirty, too. We ignore the dirty state
* of subsequent buffers because we could have raced with
* fs/ntfs/aops.c::mark_ntfs_record_dirty().
*
* On success, clean the mft record and return 0. On error, leave the mft
* record dirty and return -errno.
*
* NOTE: We always perform synchronous i/o and ignore the @sync parameter.
* However, if the mft record has a counterpart in the mft mirror and @sync is
* true, we write the mft record, wait for i/o completion, and only then write
* the mft mirror copy. This ensures that if the system crashes either the mft
* or the mft mirror will contain a self-consistent mft record @m. If @sync is
* false on the other hand, we start i/o on both and then wait for completion
* on them. This provides a speedup but no longer guarantees that you will end
* up with a self-consistent mft record in the case of a crash but if you asked
* for asynchronous writing you probably do not care about that anyway.
*
* TODO: If @sync is false, want to do truly asynchronous i/o, i.e. just
* schedule i/o via ->writepage or do it via kntfsd or whatever.
*/
int write_mft_record_nolock(ntfs_inode *ni, MFT_RECORD *m, int sync)
{
ntfs_volume *vol = ni->vol;
struct page *page = ni->page;
unsigned int blocksize = vol->sb->s_blocksize;
unsigned char blocksize_bits = vol->sb->s_blocksize_bits;
int max_bhs = vol->mft_record_size / blocksize;
struct buffer_head *bhs[max_bhs];
struct buffer_head *bh, *head;
runlist_element *rl;
unsigned int block_start, block_end, m_start, m_end;
int i_bhs, nr_bhs, err = 0;
ntfs_debug("Entering for inode 0x%lx.", ni->mft_no);
BUG_ON(NInoAttr(ni));
BUG_ON(!max_bhs);
BUG_ON(!PageLocked(page));
/*
* If the ntfs_inode is clean no need to do anything. If it is dirty,
* mark it as clean now so that it can be redirtied later on if needed.
* There is no danger of races since the caller is holding the locks
* for the mft record @m and the page it is in.
*/
if (!NInoTestClearDirty(ni))
goto done;
bh = head = page_buffers(page);
BUG_ON(!bh);
rl = NULL;
nr_bhs = 0;
block_start = 0;
m_start = ni->page_ofs;
m_end = m_start + vol->mft_record_size;
do {
block_end = block_start + blocksize;
/* If the buffer is outside the mft record, skip it. */
if (block_end <= m_start)
continue;
if (unlikely(block_start >= m_end))
break;
/*
* If this block is not the first one in the record, we ignore
* the buffer's dirty state because we could have raced with a
* parallel mark_ntfs_record_dirty().
*/
if (block_start == m_start) {
/* This block is the first one in the record. */
if (!buffer_dirty(bh)) {
BUG_ON(nr_bhs);
/* Clean records are not written out. */
break;
}
}
/* Need to map the buffer if it is not mapped already. */
if (unlikely(!buffer_mapped(bh))) {
VCN vcn;
LCN lcn;
unsigned int vcn_ofs;
bh->b_bdev = vol->sb->s_bdev;
/* Obtain the vcn and offset of the current block. */
vcn = ((VCN)ni->mft_no << vol->mft_record_size_bits) +
(block_start - m_start);
vcn_ofs = vcn & vol->cluster_size_mask;
vcn >>= vol->cluster_size_bits;
if (!rl) {
down_read(&NTFS_I(vol->mft_ino)->runlist.lock);
rl = NTFS_I(vol->mft_ino)->runlist.rl;
BUG_ON(!rl);
}
/* Seek to element containing target vcn. */
while (rl->length && rl[1].vcn <= vcn)
rl++;
lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
/* For $MFT, only lcn >= 0 is a successful remap. */
if (likely(lcn >= 0)) {
/* Setup buffer head to correct block. */
bh->b_blocknr = ((lcn <<
vol->cluster_size_bits) +
vcn_ofs) >> blocksize_bits;
set_buffer_mapped(bh);
} else {
bh->b_blocknr = -1;
ntfs_error(vol->sb, "Cannot write mft record "
"0x%lx because its location "
"on disk could not be "
"determined (error code %lli).",
ni->mft_no, (long long)lcn);
err = -EIO;
}
}
BUG_ON(!buffer_uptodate(bh));
BUG_ON(!nr_bhs && (m_start != block_start));
BUG_ON(nr_bhs >= max_bhs);
bhs[nr_bhs++] = bh;
BUG_ON((nr_bhs >= max_bhs) && (m_end != block_end));
} while (block_start = block_end, (bh = bh->b_this_page) != head);
if (unlikely(rl))
up_read(&NTFS_I(vol->mft_ino)->runlist.lock);
if (!nr_bhs)
goto done;
if (unlikely(err))
goto cleanup_out;
/* Apply the mst protection fixups. */
err = pre_write_mst_fixup((NTFS_RECORD*)m, vol->mft_record_size);
if (err) {
ntfs_error(vol->sb, "Failed to apply mst fixups!");
goto cleanup_out;
}
flush_dcache_mft_record_page(ni);
/* Lock buffers and start synchronous write i/o on them. */
for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
struct buffer_head *tbh = bhs[i_bhs];
if (!trylock_buffer(tbh))
BUG();
BUG_ON(!buffer_uptodate(tbh));
clear_buffer_dirty(tbh);
get_bh(tbh);
tbh->b_end_io = end_buffer_write_sync;
submit_bh(WRITE, tbh);
}
/* Synchronize the mft mirror now if not @sync. */
if (!sync && ni->mft_no < vol->mftmirr_size)
ntfs_sync_mft_mirror(vol, ni->mft_no, m, sync);
/* Wait on i/o completion of buffers. */
for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
struct buffer_head *tbh = bhs[i_bhs];
wait_on_buffer(tbh);
if (unlikely(!buffer_uptodate(tbh))) {
err = -EIO;
/*
* Set the buffer uptodate so the page and buffer
* states do not become out of sync.
*/
if (PageUptodate(page))
set_buffer_uptodate(tbh);
}
}
/* If @sync, now synchronize the mft mirror. */
if (sync && ni->mft_no < vol->mftmirr_size)
ntfs_sync_mft_mirror(vol, ni->mft_no, m, sync);
/* Remove the mst protection fixups again. */
post_write_mst_fixup((NTFS_RECORD*)m);
flush_dcache_mft_record_page(ni);
if (unlikely(err)) {
/* I/O error during writing. This is really bad! */
ntfs_error(vol->sb, "I/O error while writing mft record "
"0x%lx! Marking base inode as bad. You "
"should unmount the volume and run chkdsk.",
ni->mft_no);
goto err_out;
}
done:
ntfs_debug("Done.");
return 0;
cleanup_out:
/* Clean the buffers. */
for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++)
clear_buffer_dirty(bhs[i_bhs]);
err_out:
/*
* Current state: all buffers are clean, unlocked, and uptodate.
* The caller should mark the base inode as bad so that no more i/o
* happens. ->clear_inode() will still be invoked so all extent inodes
* and other allocated memory will be freed.
*/
if (err == -ENOMEM) {
ntfs_error(vol->sb, "Not enough memory to write mft record. "
"Redirtying so the write is retried later.");
mark_mft_record_dirty(ni);
err = 0;
} else
NVolSetErrors(vol);
return err;
}
/**
* ntfs_may_write_mft_record - check if an mft record may be written out
* @vol: [IN] ntfs volume on which the mft record to check resides
* @mft_no: [IN] mft record number of the mft record to check
* @m: [IN] mapped mft record to check
* @locked_ni: [OUT] caller has to unlock this ntfs inode if one is returned
*
* Check if the mapped (base or extent) mft record @m with mft record number
* @mft_no belonging to the ntfs volume @vol may be written out. If necessary
* and possible the ntfs inode of the mft record is locked and the base vfs
* inode is pinned. The locked ntfs inode is then returned in @locked_ni. The
* caller is responsible for unlocking the ntfs inode and unpinning the base
* vfs inode.
*
* Return 'true' if the mft record may be written out and 'false' if not.
*
* The caller has locked the page and cleared the uptodate flag on it which
* means that we can safely write out any dirty mft records that do not have
* their inodes in icache as determined by ilookup5() as anyone
* opening/creating such an inode would block when attempting to map the mft
* record in read_cache_page() until we are finished with the write out.
*
* Here is a description of the tests we perform:
*
* If the inode is found in icache we know the mft record must be a base mft
* record. If it is dirty, we do not write it and return 'false' as the vfs
* inode write paths will result in the access times being updated which would
* cause the base mft record to be redirtied and written out again. (We know
* the access time update will modify the base mft record because Windows
* chkdsk complains if the standard information attribute is not in the base
* mft record.)
*
* If the inode is in icache and not dirty, we attempt to lock the mft record
* and if we find the lock was already taken, it is not safe to write the mft
* record and we return 'false'.
*
* If we manage to obtain the lock we have exclusive access to the mft record,
* which also allows us safe writeout of the mft record. We then set
* @locked_ni to the locked ntfs inode and return 'true'.
*
* Note we cannot just lock the mft record and sleep while waiting for the lock
* because this would deadlock due to lock reversal (normally the mft record is
* locked before the page is locked but we already have the page locked here
* when we try to lock the mft record).
*
* If the inode is not in icache we need to perform further checks.
*
* If the mft record is not a FILE record or it is a base mft record, we can
* safely write it and return 'true'.
*
* We now know the mft record is an extent mft record. We check if the inode
* corresponding to its base mft record is in icache and obtain a reference to
* it if it is. If it is not, we can safely write it and return 'true'.
*
* We now have the base inode for the extent mft record. We check if it has an
* ntfs inode for the extent mft record attached and if not it is safe to write
* the extent mft record and we return 'true'.
*
* The ntfs inode for the extent mft record is attached to the base inode so we
* attempt to lock the extent mft record and if we find the lock was already
* taken, it is not safe to write the extent mft record and we return 'false'.
*
* If we manage to obtain the lock we have exclusive access to the extent mft
* record, which also allows us safe writeout of the extent mft record. We
* set the ntfs inode of the extent mft record clean and then set @locked_ni to
* the now locked ntfs inode and return 'true'.
*
* Note, the reason for actually writing dirty mft records here and not just
* relying on the vfs inode dirty code paths is that we can have mft records
* modified without them ever having actual inodes in memory. Also we can have
* dirty mft records with clean ntfs inodes in memory. None of the described
* cases would result in the dirty mft records being written out if we only
* relied on the vfs inode dirty code paths. And these cases can really occur
* during allocation of new mft records and in particular when the
* initialized_size of the $MFT/$DATA attribute is extended and the new space
* is initialized using ntfs_mft_record_format(). The clean inode can then
* appear if the mft record is reused for a new inode before it got written
* out.
*/
bool ntfs_may_write_mft_record(ntfs_volume *vol, const unsigned long mft_no,
const MFT_RECORD *m, ntfs_inode **locked_ni)
{
struct super_block *sb = vol->sb;
struct inode *mft_vi = vol->mft_ino;
struct inode *vi;
ntfs_inode *ni, *eni, **extent_nis;
int i;
ntfs_attr na;
ntfs_debug("Entering for inode 0x%lx.", mft_no);
/*
* Normally we do not return a locked inode so set @locked_ni to NULL.
*/
BUG_ON(!locked_ni);
*locked_ni = NULL;
/*
* Check if the inode corresponding to this mft record is in the VFS
* inode cache and obtain a reference to it if it is.
*/
ntfs_debug("Looking for inode 0x%lx in icache.", mft_no);
na.mft_no = mft_no;
na.name = NULL;
na.name_len = 0;
na.type = AT_UNUSED;
/*
* Optimize inode 0, i.e. $MFT itself, since we have it in memory and
* we get here for it rather often.
*/
if (!mft_no) {
/* Balance the below iput(). */
vi = igrab(mft_vi);
BUG_ON(vi != mft_vi);
} else {
/*
* Have to use ilookup5_nowait() since ilookup5() waits for the
* inode lock which causes ntfs to deadlock when a concurrent
* inode write via the inode dirty code paths and the page
* dirty code path of the inode dirty code path when writing
* $MFT occurs.
*/
vi = ilookup5_nowait(sb, mft_no, (test_t)ntfs_test_inode, &na);
}
if (vi) {
ntfs_debug("Base inode 0x%lx is in icache.", mft_no);
/* The inode is in icache. */
ni = NTFS_I(vi);
/* Take a reference to the ntfs inode. */
atomic_inc(&ni->count);
/* If the inode is dirty, do not write this record. */
if (NInoDirty(ni)) {
ntfs_debug("Inode 0x%lx is dirty, do not write it.",
mft_no);
atomic_dec(&ni->count);
iput(vi);
return false;
}
ntfs_debug("Inode 0x%lx is not dirty.", mft_no);
/* The inode is not dirty, try to take the mft record lock. */
if (unlikely(!mutex_trylock(&ni->mrec_lock))) {
ntfs_debug("Mft record 0x%lx is already locked, do "
"not write it.", mft_no);
atomic_dec(&ni->count);
iput(vi);
return false;
}
ntfs_debug("Managed to lock mft record 0x%lx, write it.",
mft_no);
/*
* The write has to occur while we hold the mft record lock so
* return the locked ntfs inode.
*/
*locked_ni = ni;
return true;
}
ntfs_debug("Inode 0x%lx is not in icache.", mft_no);
/* The inode is not in icache. */
/* Write the record if it is not a mft record (type "FILE"). */
if (!ntfs_is_mft_record(m->magic)) {
ntfs_debug("Mft record 0x%lx is not a FILE record, write it.",
mft_no);
return true;
}
/* Write the mft record if it is a base inode. */
if (!m->base_mft_record) {
ntfs_debug("Mft record 0x%lx is a base record, write it.",
mft_no);
return true;
}
/*
* This is an extent mft record. Check if the inode corresponding to
* its base mft record is in icache and obtain a reference to it if it
* is.
*/
na.mft_no = MREF_LE(m->base_mft_record);
ntfs_debug("Mft record 0x%lx is an extent record. Looking for base "
"inode 0x%lx in icache.", mft_no, na.mft_no);
if (!na.mft_no) {
/* Balance the below iput(). */
vi = igrab(mft_vi);
BUG_ON(vi != mft_vi);
} else
vi = ilookup5_nowait(sb, na.mft_no, (test_t)ntfs_test_inode,
&na);
if (!vi) {
/*
* The base inode is not in icache, write this extent mft
* record.
*/
ntfs_debug("Base inode 0x%lx is not in icache, write the "
"extent record.", na.mft_no);
return true;
}
ntfs_debug("Base inode 0x%lx is in icache.", na.mft_no);
/*
* The base inode is in icache. Check if it has the extent inode
* corresponding to this extent mft record attached.
*/
ni = NTFS_I(vi);
mutex_lock(&ni->extent_lock);
if (ni->nr_extents <= 0) {
/*
* The base inode has no attached extent inodes, write this
* extent mft record.
*/
mutex_unlock(&ni->extent_lock);
iput(vi);
ntfs_debug("Base inode 0x%lx has no attached extent inodes, "
"write the extent record.", na.mft_no);
return true;
}
/* Iterate over the attached extent inodes. */
extent_nis = ni->ext.extent_ntfs_inos;
for (eni = NULL, i = 0; i < ni->nr_extents; ++i) {
if (mft_no == extent_nis[i]->mft_no) {
/*
* Found the extent inode corresponding to this extent
* mft record.
*/
eni = extent_nis[i];
break;
}
}
/*
* If the extent inode was not attached to the base inode, write this
* extent mft record.
*/
if (!eni) {
mutex_unlock(&ni->extent_lock);
iput(vi);
ntfs_debug("Extent inode 0x%lx is not attached to its base "
"inode 0x%lx, write the extent record.",
mft_no, na.mft_no);
return true;
}
ntfs_debug("Extent inode 0x%lx is attached to its base inode 0x%lx.",
mft_no, na.mft_no);
/* Take a reference to the extent ntfs inode. */
atomic_inc(&eni->count);
mutex_unlock(&ni->extent_lock);
/*
* Found the extent inode coresponding to this extent mft record.
* Try to take the mft record lock.
*/
if (unlikely(!mutex_trylock(&eni->mrec_lock))) {
atomic_dec(&eni->count);
iput(vi);
ntfs_debug("Extent mft record 0x%lx is already locked, do "
"not write it.", mft_no);
return false;
}
ntfs_debug("Managed to lock extent mft record 0x%lx, write it.",
mft_no);
if (NInoTestClearDirty(eni))
ntfs_debug("Extent inode 0x%lx is dirty, marking it clean.",
mft_no);
/*
* The write has to occur while we hold the mft record lock so return
* the locked extent ntfs inode.
*/
*locked_ni = eni;
return true;
}
static const char *es = " Leaving inconsistent metadata. Unmount and run "
"chkdsk.";
/**
* ntfs_mft_bitmap_find_and_alloc_free_rec_nolock - see name
* @vol: volume on which to search for a free mft record
* @base_ni: open base inode if allocating an extent mft record or NULL
*
* Search for a free mft record in the mft bitmap attribute on the ntfs volume
* @vol.
*
* If @base_ni is NULL start the search at the default allocator position.
*
* If @base_ni is not NULL start the search at the mft record after the base
* mft record @base_ni.
*
* Return the free mft record on success and -errno on error. An error code of
* -ENOSPC means that there are no free mft records in the currently
* initialized mft bitmap.
*
* Locking: Caller must hold vol->mftbmp_lock for writing.
*/
static int ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(ntfs_volume *vol,
ntfs_inode *base_ni)
{
s64 pass_end, ll, data_pos, pass_start, ofs, bit;
unsigned long flags;
struct address_space *mftbmp_mapping;
u8 *buf, *byte;
struct page *page;
unsigned int page_ofs, size;
u8 pass, b;
ntfs_debug("Searching for free mft record in the currently "
"initialized mft bitmap.");
mftbmp_mapping = vol->mftbmp_ino->i_mapping;
/*
* Set the end of the pass making sure we do not overflow the mft
* bitmap.
*/
read_lock_irqsave(&NTFS_I(vol->mft_ino)->size_lock, flags);
pass_end = NTFS_I(vol->mft_ino)->allocated_size >>
vol->mft_record_size_bits;
read_unlock_irqrestore(&NTFS_I(vol->mft_ino)->size_lock, flags);
read_lock_irqsave(&NTFS_I(vol->mftbmp_ino)->size_lock, flags);
ll = NTFS_I(vol->mftbmp_ino)->initialized_size << 3;
read_unlock_irqrestore(&NTFS_I(vol->mftbmp_ino)->size_lock, flags);
if (pass_end > ll)
pass_end = ll;
pass = 1;
if (!base_ni)
data_pos = vol->mft_data_pos;
else
data_pos = base_ni->mft_no + 1;
if (data_pos < 24)
data_pos = 24;
if (data_pos >= pass_end) {
data_pos = 24;
pass = 2;
/* This happens on a freshly formatted volume. */
if (data_pos >= pass_end)
return -ENOSPC;
}
pass_start = data_pos;
ntfs_debug("Starting bitmap search: pass %u, pass_start 0x%llx, "
"pass_end 0x%llx, data_pos 0x%llx.", pass,
(long long)pass_start, (long long)pass_end,
(long long)data_pos);
/* Loop until a free mft record is found. */
for (; pass <= 2;) {
/* Cap size to pass_end. */
ofs = data_pos >> 3;
page_ofs = ofs & ~PAGE_CACHE_MASK;
size = PAGE_CACHE_SIZE - page_ofs;
ll = ((pass_end + 7) >> 3) - ofs;
if (size > ll)
size = ll;
size <<= 3;
/*
* If we are still within the active pass, search the next page
* for a zero bit.
*/
if (size) {
page = ntfs_map_page(mftbmp_mapping,
ofs >> PAGE_CACHE_SHIFT);
if (IS_ERR(page)) {
ntfs_error(vol->sb, "Failed to read mft "
"bitmap, aborting.");
return PTR_ERR(page);
}
buf = (u8*)page_address(page) + page_ofs;
bit = data_pos & 7;
data_pos &= ~7ull;
ntfs_debug("Before inner for loop: size 0x%x, "
"data_pos 0x%llx, bit 0x%llx", size,
(long long)data_pos, (long long)bit);
for (; bit < size && data_pos + bit < pass_end;
bit &= ~7ull, bit += 8) {
byte = buf + (bit >> 3);
if (*byte == 0xff)
continue;
b = ffz((unsigned long)*byte);
if (b < 8 && b >= (bit & 7)) {
ll = data_pos + (bit & ~7ull) + b;
if (unlikely(ll > (1ll << 32))) {
ntfs_unmap_page(page);
return -ENOSPC;
}
*byte |= 1 << b;
flush_dcache_page(page);
set_page_dirty(page);
ntfs_unmap_page(page);
ntfs_debug("Done. (Found and "
"allocated mft record "
"0x%llx.)",
(long long)ll);
return ll;
}
}
ntfs_debug("After inner for loop: size 0x%x, "
"data_pos 0x%llx, bit 0x%llx", size,
(long long)data_pos, (long long)bit);
data_pos += size;
ntfs_unmap_page(page);
/*
* If the end of the pass has not been reached yet,
* continue searching the mft bitmap for a zero bit.
*/
if (data_pos < pass_end)
continue;
}
/* Do the next pass. */
if (++pass == 2) {
/*
* Starting the second pass, in which we scan the first
* part of the zone which we omitted earlier.
*/
pass_end = pass_start;
data_pos = pass_start = 24;
ntfs_debug("pass %i, pass_start 0x%llx, pass_end "
"0x%llx.", pass, (long long)pass_start,
(long long)pass_end);
if (data_pos >= pass_end)
break;
}
}
/* No free mft records in currently initialized mft bitmap. */
ntfs_debug("Done. (No free mft records left in currently initialized "
"mft bitmap.)");
return -ENOSPC;
}
/**
* ntfs_mft_bitmap_extend_allocation_nolock - extend mft bitmap by a cluster
* @vol: volume on which to extend the mft bitmap attribute
*
* Extend the mft bitmap attribute on the ntfs volume @vol by one cluster.
*
* Note: Only changes allocated_size, i.e. does not touch initialized_size or
* data_size.
*
* Return 0 on success and -errno on error.
*
* Locking: - Caller must hold vol->mftbmp_lock for writing.
* - This function takes NTFS_I(vol->mftbmp_ino)->runlist.lock for
* writing and releases it before returning.
* - This function takes vol->lcnbmp_lock for writing and releases it
* before returning.
*/
static int ntfs_mft_bitmap_extend_allocation_nolock(ntfs_volume *vol)
{
LCN lcn;
s64 ll;
unsigned long flags;
struct page *page;
ntfs_inode *mft_ni, *mftbmp_ni;
runlist_element *rl, *rl2 = NULL;
ntfs_attr_search_ctx *ctx = NULL;
MFT_RECORD *mrec;
ATTR_RECORD *a = NULL;
int ret, mp_size;
u32 old_alen = 0;
u8 *b, tb;
struct {
u8 added_cluster:1;
u8 added_run:1;
u8 mp_rebuilt:1;
} status = { 0, 0, 0 };
ntfs_debug("Extending mft bitmap allocation.");
mft_ni = NTFS_I(vol->mft_ino);
mftbmp_ni = NTFS_I(vol->mftbmp_ino);
/*
* Determine the last lcn of the mft bitmap. The allocated size of the
* mft bitmap cannot be zero so we are ok to do this.
*/
down_write(&mftbmp_ni->runlist.lock);
read_lock_irqsave(&mftbmp_ni->size_lock, flags);
ll = mftbmp_ni->allocated_size;
read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
rl = ntfs_attr_find_vcn_nolock(mftbmp_ni,
(ll - 1) >> vol->cluster_size_bits, NULL);
if (unlikely(IS_ERR(rl) || !rl->length || rl->lcn < 0)) {
up_write(&mftbmp_ni->runlist.lock);
ntfs_error(vol->sb, "Failed to determine last allocated "
"cluster of mft bitmap attribute.");
if (!IS_ERR(rl))
ret = -EIO;
else
ret = PTR_ERR(rl);
return ret;
}
lcn = rl->lcn + rl->length;
ntfs_debug("Last lcn of mft bitmap attribute is 0x%llx.",
(long long)lcn);
/*
* Attempt to get the cluster following the last allocated cluster by
* hand as it may be in the MFT zone so the allocator would not give it
* to us.
*/
ll = lcn >> 3;
page = ntfs_map_page(vol->lcnbmp_ino->i_mapping,
ll >> PAGE_CACHE_SHIFT);
if (IS_ERR(page)) {
up_write(&mftbmp_ni->runlist.lock);
ntfs_error(vol->sb, "Failed to read from lcn bitmap.");
return PTR_ERR(page);
}
b = (u8*)page_address(page) + (ll & ~PAGE_CACHE_MASK);
tb = 1 << (lcn & 7ull);
down_write(&vol->lcnbmp_lock);
if (*b != 0xff && !(*b & tb)) {
/* Next cluster is free, allocate it. */
*b |= tb;
flush_dcache_page(page);
set_page_dirty(page);
up_write(&vol->lcnbmp_lock);
ntfs_unmap_page(page);
/* Update the mft bitmap runlist. */
rl->length++;
rl[1].vcn++;
status.added_cluster = 1;
ntfs_debug("Appending one cluster to mft bitmap.");
} else {
up_write(&vol->lcnbmp_lock);
ntfs_unmap_page(page);
/* Allocate a cluster from the DATA_ZONE. */
rl2 = ntfs_cluster_alloc(vol, rl[1].vcn, 1, lcn, DATA_ZONE,
true);
if (IS_ERR(rl2)) {
up_write(&mftbmp_ni->runlist.lock);
ntfs_error(vol->sb, "Failed to allocate a cluster for "
"the mft bitmap.");
return PTR_ERR(rl2);
}
rl = ntfs_runlists_merge(mftbmp_ni->runlist.rl, rl2);
if (IS_ERR(rl)) {
up_write(&mftbmp_ni->runlist.lock);
ntfs_error(vol->sb, "Failed to merge runlists for mft "
"bitmap.");
if (ntfs_cluster_free_from_rl(vol, rl2)) {
ntfs_error(vol->sb, "Failed to deallocate "
"allocated cluster.%s", es);
NVolSetErrors(vol);
}
ntfs_free(rl2);
return PTR_ERR(rl);
}
mftbmp_ni->runlist.rl = rl;
status.added_run = 1;
ntfs_debug("Adding one run to mft bitmap.");
/* Find the last run in the new runlist. */
for (; rl[1].length; rl++)
;
}
/*
* Update the attribute record as well. Note: @rl is the last
* (non-terminator) runlist element of mft bitmap.
*/
mrec = map_mft_record(mft_ni);
if (IS_ERR(mrec)) {
ntfs_error(vol->sb, "Failed to map mft record.");
ret = PTR_ERR(mrec);
goto undo_alloc;
}
ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
if (unlikely(!ctx)) {
ntfs_error(vol->sb, "Failed to get search context.");
ret = -ENOMEM;
goto undo_alloc;
}
ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
mftbmp_ni->name_len, CASE_SENSITIVE, rl[1].vcn, NULL,
0, ctx);
if (unlikely(ret)) {
ntfs_error(vol->sb, "Failed to find last attribute extent of "
"mft bitmap attribute.");
if (ret == -ENOENT)
ret = -EIO;
goto undo_alloc;
}
a = ctx->attr;
ll = sle64_to_cpu(a->data.non_resident.lowest_vcn);
/* Search back for the previous last allocated cluster of mft bitmap. */
for (rl2 = rl; rl2 > mftbmp_ni->runlist.rl; rl2--) {
if (ll >= rl2->vcn)
break;
}
BUG_ON(ll < rl2->vcn);
BUG_ON(ll >= rl2->vcn + rl2->length);
/* Get the size for the new mapping pairs array for this extent. */
mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, -1);
if (unlikely(mp_size <= 0)) {
ntfs_error(vol->sb, "Get size for mapping pairs failed for "
"mft bitmap attribute extent.");
ret = mp_size;
if (!ret)
ret = -EIO;
goto undo_alloc;
}
/* Expand the attribute record if necessary. */
old_alen = le32_to_cpu(a->length);
ret = ntfs_attr_record_resize(ctx->mrec, a, mp_size +
le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
if (unlikely(ret)) {
if (ret != -ENOSPC) {
ntfs_error(vol->sb, "Failed to resize attribute "
"record for mft bitmap attribute.");
goto undo_alloc;
}
// TODO: Deal with this by moving this extent to a new mft
// record or by starting a new extent in a new mft record or by
// moving other attributes out of this mft record.
// Note: It will need to be a special mft record and if none of
// those are available it gets rather complicated...
ntfs_error(vol->sb, "Not enough space in this mft record to "
"accommodate extended mft bitmap attribute "
"extent. Cannot handle this yet.");
ret = -EOPNOTSUPP;
goto undo_alloc;
}
status.mp_rebuilt = 1;
/* Generate the mapping pairs array directly into the attr record. */
ret = ntfs_mapping_pairs_build(vol, (u8*)a +
le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
mp_size, rl2, ll, -1, NULL);
if (unlikely(ret)) {
ntfs_error(vol->sb, "Failed to build mapping pairs array for "
"mft bitmap attribute.");
goto undo_alloc;
}
/* Update the highest_vcn. */
a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
/*
* We now have extended the mft bitmap allocated_size by one cluster.
* Reflect this in the ntfs_inode structure and the attribute record.
*/
if (a->data.non_resident.lowest_vcn) {
/*
* We are not in the first attribute extent, switch to it, but
* first ensure the changes will make it to disk later.
*/
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
ntfs_attr_reinit_search_ctx(ctx);
ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL,
0, ctx);
if (unlikely(ret)) {
ntfs_error(vol->sb, "Failed to find first attribute "
"extent of mft bitmap attribute.");
goto restore_undo_alloc;
}
a = ctx->attr;
}
write_lock_irqsave(&mftbmp_ni->size_lock, flags);
mftbmp_ni->allocated_size += vol->cluster_size;
a->data.non_resident.allocated_size =
cpu_to_sle64(mftbmp_ni->allocated_size);
write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
/* Ensure the changes make it to disk. */
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(mft_ni);
up_write(&mftbmp_ni->runlist.lock);
ntfs_debug("Done.");
return 0;
restore_undo_alloc:
ntfs_attr_reinit_search_ctx(ctx);
if (ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
mftbmp_ni->name_len, CASE_SENSITIVE, rl[1].vcn, NULL,
0, ctx)) {
ntfs_error(vol->sb, "Failed to find last attribute extent of "
"mft bitmap attribute.%s", es);
write_lock_irqsave(&mftbmp_ni->size_lock, flags);
mftbmp_ni->allocated_size += vol->cluster_size;
write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(mft_ni);
up_write(&mftbmp_ni->runlist.lock);
/*
* The only thing that is now wrong is ->allocated_size of the
* base attribute extent which chkdsk should be able to fix.
*/
NVolSetErrors(vol);
return ret;
}
a = ctx->attr;
a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 2);
undo_alloc:
if (status.added_cluster) {
/* Truncate the last run in the runlist by one cluster. */
rl->length--;
rl[1].vcn--;
} else if (status.added_run) {
lcn = rl->lcn;
/* Remove the last run from the runlist. */
rl->lcn = rl[1].lcn;
rl->length = 0;
}
/* Deallocate the cluster. */
down_write(&vol->lcnbmp_lock);
if (ntfs_bitmap_clear_bit(vol->lcnbmp_ino, lcn)) {
ntfs_error(vol->sb, "Failed to free allocated cluster.%s", es);
NVolSetErrors(vol);
}
up_write(&vol->lcnbmp_lock);
if (status.mp_rebuilt) {
if (ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
a->data.non_resident.mapping_pairs_offset),
old_alen - le16_to_cpu(
a->data.non_resident.mapping_pairs_offset),
rl2, ll, -1, NULL)) {
ntfs_error(vol->sb, "Failed to restore mapping pairs "
"array.%s", es);
NVolSetErrors(vol);
}
if (ntfs_attr_record_resize(ctx->mrec, a, old_alen)) {
ntfs_error(vol->sb, "Failed to restore attribute "
"record.%s", es);
NVolSetErrors(vol);
}
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
}
if (ctx)
ntfs_attr_put_search_ctx(ctx);
if (!IS_ERR(mrec))
unmap_mft_record(mft_ni);
up_write(&mftbmp_ni->runlist.lock);
return ret;
}
/**
* ntfs_mft_bitmap_extend_initialized_nolock - extend mftbmp initialized data
* @vol: volume on which to extend the mft bitmap attribute
*
* Extend the initialized portion of the mft bitmap attribute on the ntfs
* volume @vol by 8 bytes.
*
* Note: Only changes initialized_size and data_size, i.e. requires that
* allocated_size is big enough to fit the new initialized_size.
*
* Return 0 on success and -error on error.
*
* Locking: Caller must hold vol->mftbmp_lock for writing.
*/
static int ntfs_mft_bitmap_extend_initialized_nolock(ntfs_volume *vol)
{
s64 old_data_size, old_initialized_size;
unsigned long flags;
struct inode *mftbmp_vi;
ntfs_inode *mft_ni, *mftbmp_ni;
ntfs_attr_search_ctx *ctx;
MFT_RECORD *mrec;
ATTR_RECORD *a;
int ret;
ntfs_debug("Extending mft bitmap initiailized (and data) size.");
mft_ni = NTFS_I(vol->mft_ino);
mftbmp_vi = vol->mftbmp_ino;
mftbmp_ni = NTFS_I(mftbmp_vi);
/* Get the attribute record. */
mrec = map_mft_record(mft_ni);
if (IS_ERR(mrec)) {
ntfs_error(vol->sb, "Failed to map mft record.");
return PTR_ERR(mrec);
}
ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
if (unlikely(!ctx)) {
ntfs_error(vol->sb, "Failed to get search context.");
ret = -ENOMEM;
goto unm_err_out;
}
ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL, 0, ctx);
if (unlikely(ret)) {
ntfs_error(vol->sb, "Failed to find first attribute extent of "
"mft bitmap attribute.");
if (ret == -ENOENT)
ret = -EIO;
goto put_err_out;
}
a = ctx->attr;
write_lock_irqsave(&mftbmp_ni->size_lock, flags);
old_data_size = i_size_read(mftbmp_vi);
old_initialized_size = mftbmp_ni->initialized_size;
/*
* We can simply update the initialized_size before filling the space
* with zeroes because the caller is holding the mft bitmap lock for
* writing which ensures that no one else is trying to access the data.
*/
mftbmp_ni->initialized_size += 8;
a->data.non_resident.initialized_size =
cpu_to_sle64(mftbmp_ni->initialized_size);
if (mftbmp_ni->initialized_size > old_data_size) {
i_size_write(mftbmp_vi, mftbmp_ni->initialized_size);
a->data.non_resident.data_size =
cpu_to_sle64(mftbmp_ni->initialized_size);
}
write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
/* Ensure the changes make it to disk. */
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(mft_ni);
/* Initialize the mft bitmap attribute value with zeroes. */
ret = ntfs_attr_set(mftbmp_ni, old_initialized_size, 8, 0);
if (likely(!ret)) {
ntfs_debug("Done. (Wrote eight initialized bytes to mft "
"bitmap.");
return 0;
}
ntfs_error(vol->sb, "Failed to write to mft bitmap.");
/* Try to recover from the error. */
mrec = map_mft_record(mft_ni);
if (IS_ERR(mrec)) {
ntfs_error(vol->sb, "Failed to map mft record.%s", es);
NVolSetErrors(vol);
return ret;
}
ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
if (unlikely(!ctx)) {
ntfs_error(vol->sb, "Failed to get search context.%s", es);
NVolSetErrors(vol);
goto unm_err_out;
}
if (ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL, 0, ctx)) {
ntfs_error(vol->sb, "Failed to find first attribute extent of "
"mft bitmap attribute.%s", es);
NVolSetErrors(vol);
put_err_out:
ntfs_attr_put_search_ctx(ctx);
unm_err_out:
unmap_mft_record(mft_ni);
goto err_out;
}
a = ctx->attr;
write_lock_irqsave(&mftbmp_ni->size_lock, flags);
mftbmp_ni->initialized_size = old_initialized_size;
a->data.non_resident.initialized_size =
cpu_to_sle64(old_initialized_size);
if (i_size_read(mftbmp_vi) != old_data_size) {
i_size_write(mftbmp_vi, old_data_size);
a->data.non_resident.data_size = cpu_to_sle64(old_data_size);
}
write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(mft_ni);
#ifdef DEBUG
read_lock_irqsave(&mftbmp_ni->size_lock, flags);
ntfs_debug("Restored status of mftbmp: allocated_size 0x%llx, "
"data_size 0x%llx, initialized_size 0x%llx.",
(long long)mftbmp_ni->allocated_size,
(long long)i_size_read(mftbmp_vi),
(long long)mftbmp_ni->initialized_size);
read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
#endif /* DEBUG */
err_out:
return ret;
}
/**
* ntfs_mft_data_extend_allocation_nolock - extend mft data attribute
* @vol: volume on which to extend the mft data attribute
*
* Extend the mft data attribute on the ntfs volume @vol by 16 mft records
* worth of clusters or if not enough space for this by one mft record worth
* of clusters.
*
* Note: Only changes allocated_size, i.e. does not touch initialized_size or
* data_size.
*
* Return 0 on success and -errno on error.
*
* Locking: - Caller must hold vol->mftbmp_lock for writing.
* - This function takes NTFS_I(vol->mft_ino)->runlist.lock for
* writing and releases it before returning.
* - This function calls functions which take vol->lcnbmp_lock for
* writing and release it before returning.
*/
static int ntfs_mft_data_extend_allocation_nolock(ntfs_volume *vol)
{
LCN lcn;
VCN old_last_vcn;
s64 min_nr, nr, ll;
unsigned long flags;
ntfs_inode *mft_ni;
runlist_element *rl, *rl2;
ntfs_attr_search_ctx *ctx = NULL;
MFT_RECORD *mrec;
ATTR_RECORD *a = NULL;
int ret, mp_size;
u32 old_alen = 0;
bool mp_rebuilt = false;
ntfs_debug("Extending mft data allocation.");
mft_ni = NTFS_I(vol->mft_ino);
/*
* Determine the preferred allocation location, i.e. the last lcn of
* the mft data attribute. The allocated size of the mft data
* attribute cannot be zero so we are ok to do this.
*/
down_write(&mft_ni->runlist.lock);
read_lock_irqsave(&mft_ni->size_lock, flags);
ll = mft_ni->allocated_size;
read_unlock_irqrestore(&mft_ni->size_lock, flags);
rl = ntfs_attr_find_vcn_nolock(mft_ni,
(ll - 1) >> vol->cluster_size_bits, NULL);
if (unlikely(IS_ERR(rl) || !rl->length || rl->lcn < 0)) {
up_write(&mft_ni->runlist.lock);
ntfs_error(vol->sb, "Failed to determine last allocated "
"cluster of mft data attribute.");
if (!IS_ERR(rl))
ret = -EIO;
else
ret = PTR_ERR(rl);
return ret;
}
lcn = rl->lcn + rl->length;
ntfs_debug("Last lcn of mft data attribute is 0x%llx.", (long long)lcn);
/* Minimum allocation is one mft record worth of clusters. */
min_nr = vol->mft_record_size >> vol->cluster_size_bits;
if (!min_nr)
min_nr = 1;
/* Want to allocate 16 mft records worth of clusters. */
nr = vol->mft_record_size << 4 >> vol->cluster_size_bits;
if (!nr)
nr = min_nr;
/* Ensure we do not go above 2^32-1 mft records. */
read_lock_irqsave(&mft_ni->size_lock, flags);
ll = mft_ni->allocated_size;
read_unlock_irqrestore(&mft_ni->size_lock, flags);
if (unlikely((ll + (nr << vol->cluster_size_bits)) >>
vol->mft_record_size_bits >= (1ll << 32))) {
nr = min_nr;
if (unlikely((ll + (nr << vol->cluster_size_bits)) >>
vol->mft_record_size_bits >= (1ll << 32))) {
ntfs_warning(vol->sb, "Cannot allocate mft record "
"because the maximum number of inodes "
"(2^32) has already been reached.");
up_write(&mft_ni->runlist.lock);
return -ENOSPC;
}
}
ntfs_debug("Trying mft data allocation with %s cluster count %lli.",
nr > min_nr ? "default" : "minimal", (long long)nr);
old_last_vcn = rl[1].vcn;
do {
rl2 = ntfs_cluster_alloc(vol, old_last_vcn, nr, lcn, MFT_ZONE,
true);
if (likely(!IS_ERR(rl2)))
break;
if (PTR_ERR(rl2) != -ENOSPC || nr == min_nr) {
ntfs_error(vol->sb, "Failed to allocate the minimal "
"number of clusters (%lli) for the "
"mft data attribute.", (long long)nr);
up_write(&mft_ni->runlist.lock);
return PTR_ERR(rl2);
}
/*
* There is not enough space to do the allocation, but there
* might be enough space to do a minimal allocation so try that
* before failing.
*/
nr = min_nr;
ntfs_debug("Retrying mft data allocation with minimal cluster "
"count %lli.", (long long)nr);
} while (1);
rl = ntfs_runlists_merge(mft_ni->runlist.rl, rl2);
if (IS_ERR(rl)) {
up_write(&mft_ni->runlist.lock);
ntfs_error(vol->sb, "Failed to merge runlists for mft data "
"attribute.");
if (ntfs_cluster_free_from_rl(vol, rl2)) {
ntfs_error(vol->sb, "Failed to deallocate clusters "
"from the mft data attribute.%s", es);
NVolSetErrors(vol);
}
ntfs_free(rl2);
return PTR_ERR(rl);
}
mft_ni->runlist.rl = rl;
ntfs_debug("Allocated %lli clusters.", (long long)nr);
/* Find the last run in the new runlist. */
for (; rl[1].length; rl++)
;
/* Update the attribute record as well. */
mrec = map_mft_record(mft_ni);
if (IS_ERR(mrec)) {
ntfs_error(vol->sb, "Failed to map mft record.");
ret = PTR_ERR(mrec);
goto undo_alloc;
}
ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
if (unlikely(!ctx)) {
ntfs_error(vol->sb, "Failed to get search context.");
ret = -ENOMEM;
goto undo_alloc;
}
ret = ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
CASE_SENSITIVE, rl[1].vcn, NULL, 0, ctx);
if (unlikely(ret)) {
ntfs_error(vol->sb, "Failed to find last attribute extent of "
"mft data attribute.");
if (ret == -ENOENT)
ret = -EIO;
goto undo_alloc;
}
a = ctx->attr;
ll = sle64_to_cpu(a->data.non_resident.lowest_vcn);
/* Search back for the previous last allocated cluster of mft bitmap. */
for (rl2 = rl; rl2 > mft_ni->runlist.rl; rl2--) {
if (ll >= rl2->vcn)
break;
}
BUG_ON(ll < rl2->vcn);
BUG_ON(ll >= rl2->vcn + rl2->length);
/* Get the size for the new mapping pairs array for this extent. */
mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, -1);
if (unlikely(mp_size <= 0)) {
ntfs_error(vol->sb, "Get size for mapping pairs failed for "
"mft data attribute extent.");
ret = mp_size;
if (!ret)
ret = -EIO;
goto undo_alloc;
}
/* Expand the attribute record if necessary. */
old_alen = le32_to_cpu(a->length);
ret = ntfs_attr_record_resize(ctx->mrec, a, mp_size +
le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
if (unlikely(ret)) {
if (ret != -ENOSPC) {
ntfs_error(vol->sb, "Failed to resize attribute "
"record for mft data attribute.");
goto undo_alloc;
}
// TODO: Deal with this by moving this extent to a new mft
// record or by starting a new extent in a new mft record or by
// moving other attributes out of this mft record.
// Note: Use the special reserved mft records and ensure that
// this extent is not required to find the mft record in
// question. If no free special records left we would need to
// move an existing record away, insert ours in its place, and
// then place the moved record into the newly allocated space
// and we would then need to update all references to this mft
// record appropriately. This is rather complicated...
ntfs_error(vol->sb, "Not enough space in this mft record to "
"accommodate extended mft data attribute "
"extent. Cannot handle this yet.");
ret = -EOPNOTSUPP;
goto undo_alloc;
}
mp_rebuilt = true;
/* Generate the mapping pairs array directly into the attr record. */
ret = ntfs_mapping_pairs_build(vol, (u8*)a +
le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
mp_size, rl2, ll, -1, NULL);
if (unlikely(ret)) {
ntfs_error(vol->sb, "Failed to build mapping pairs array of "
"mft data attribute.");
goto undo_alloc;
}
/* Update the highest_vcn. */
a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
/*
* We now have extended the mft data allocated_size by nr clusters.
* Reflect this in the ntfs_inode structure and the attribute record.
* @rl is the last (non-terminator) runlist element of mft data
* attribute.
*/
if (a->data.non_resident.lowest_vcn) {
/*
* We are not in the first attribute extent, switch to it, but
* first ensure the changes will make it to disk later.
*/
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
ntfs_attr_reinit_search_ctx(ctx);
ret = ntfs_attr_lookup(mft_ni->type, mft_ni->name,
mft_ni->name_len, CASE_SENSITIVE, 0, NULL, 0,
ctx);
if (unlikely(ret)) {
ntfs_error(vol->sb, "Failed to find first attribute "
"extent of mft data attribute.");
goto restore_undo_alloc;
}
a = ctx->attr;
}
write_lock_irqsave(&mft_ni->size_lock, flags);
mft_ni->allocated_size += nr << vol->cluster_size_bits;
a->data.non_resident.allocated_size =
cpu_to_sle64(mft_ni->allocated_size);
write_unlock_irqrestore(&mft_ni->size_lock, flags);
/* Ensure the changes make it to disk. */
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(mft_ni);
up_write(&mft_ni->runlist.lock);
ntfs_debug("Done.");
return 0;
restore_undo_alloc:
ntfs_attr_reinit_search_ctx(ctx);
if (ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
CASE_SENSITIVE, rl[1].vcn, NULL, 0, ctx)) {
ntfs_error(vol->sb, "Failed to find last attribute extent of "
"mft data attribute.%s", es);
write_lock_irqsave(&mft_ni->size_lock, flags);
mft_ni->allocated_size += nr << vol->cluster_size_bits;
write_unlock_irqrestore(&mft_ni->size_lock, flags);
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(mft_ni);
up_write(&mft_ni->runlist.lock);
/*
* The only thing that is now wrong is ->allocated_size of the
* base attribute extent which chkdsk should be able to fix.
*/
NVolSetErrors(vol);
return ret;
}
ctx->attr->data.non_resident.highest_vcn =
cpu_to_sle64(old_last_vcn - 1);
undo_alloc:
if (ntfs_cluster_free(mft_ni, old_last_vcn, -1, ctx) < 0) {
ntfs_error(vol->sb, "Failed to free clusters from mft data "
"attribute.%s", es);
NVolSetErrors(vol);
}
a = ctx->attr;
if (ntfs_rl_truncate_nolock(vol, &mft_ni->runlist, old_last_vcn)) {
ntfs_error(vol->sb, "Failed to truncate mft data attribute "
"runlist.%s", es);
NVolSetErrors(vol);
}
if (mp_rebuilt && !IS_ERR(ctx->mrec)) {
if (ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
a->data.non_resident.mapping_pairs_offset),
old_alen - le16_to_cpu(
a->data.non_resident.mapping_pairs_offset),
rl2, ll, -1, NULL)) {
ntfs_error(vol->sb, "Failed to restore mapping pairs "
"array.%s", es);
NVolSetErrors(vol);
}
if (ntfs_attr_record_resize(ctx->mrec, a, old_alen)) {
ntfs_error(vol->sb, "Failed to restore attribute "
"record.%s", es);
NVolSetErrors(vol);
}
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
} else if (IS_ERR(ctx->mrec)) {
ntfs_error(vol->sb, "Failed to restore attribute search "
"context.%s", es);
NVolSetErrors(vol);
}
if (ctx)
ntfs_attr_put_search_ctx(ctx);
if (!IS_ERR(mrec))
unmap_mft_record(mft_ni);
up_write(&mft_ni->runlist.lock);
return ret;
}
/**
* ntfs_mft_record_layout - layout an mft record into a memory buffer
* @vol: volume to which the mft record will belong
* @mft_no: mft reference specifying the mft record number
* @m: destination buffer of size >= @vol->mft_record_size bytes
*
* Layout an empty, unused mft record with the mft record number @mft_no into
* the buffer @m. The volume @vol is needed because the mft record structure
* was modified in NTFS 3.1 so we need to know which volume version this mft
* record will be used on.
*
* Return 0 on success and -errno on error.
*/
static int ntfs_mft_record_layout(const ntfs_volume *vol, const s64 mft_no,
MFT_RECORD *m)
{
ATTR_RECORD *a;
ntfs_debug("Entering for mft record 0x%llx.", (long long)mft_no);
if (mft_no >= (1ll << 32)) {
ntfs_error(vol->sb, "Mft record number 0x%llx exceeds "
"maximum of 2^32.", (long long)mft_no);
return -ERANGE;
}
/* Start by clearing the whole mft record to gives us a clean slate. */
memset(m, 0, vol->mft_record_size);
/* Aligned to 2-byte boundary. */
if (vol->major_ver < 3 || (vol->major_ver == 3 && !vol->minor_ver))
m->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD_OLD) + 1) & ~1);
else {
m->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD) + 1) & ~1);
/*
* Set the NTFS 3.1+ specific fields while we know that the
* volume version is 3.1+.
*/
m->reserved = 0;
m->mft_record_number = cpu_to_le32((u32)mft_no);
}
m->magic = magic_FILE;
if (vol->mft_record_size >= NTFS_BLOCK_SIZE)
m->usa_count = cpu_to_le16(vol->mft_record_size /
NTFS_BLOCK_SIZE + 1);
else {
m->usa_count = cpu_to_le16(1);
ntfs_warning(vol->sb, "Sector size is bigger than mft record "
"size. Setting usa_count to 1. If chkdsk "
"reports this as corruption, please email "
"linux-ntfs-dev@lists.sourceforge.net stating "
"that you saw this message and that the "
"modified filesystem created was corrupt. "
"Thank you.");
}
/* Set the update sequence number to 1. */
*(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = cpu_to_le16(1);
m->lsn = 0;
m->sequence_number = cpu_to_le16(1);
m->link_count = 0;
/*
* Place the attributes straight after the update sequence array,
* aligned to 8-byte boundary.
*/
m->attrs_offset = cpu_to_le16((le16_to_cpu(m->usa_ofs) +
(le16_to_cpu(m->usa_count) << 1) + 7) & ~7);
m->flags = 0;
/*
* Using attrs_offset plus eight bytes (for the termination attribute).
* attrs_offset is already aligned to 8-byte boundary, so no need to
* align again.
*/
m->bytes_in_use = cpu_to_le32(le16_to_cpu(m->attrs_offset) + 8);
m->bytes_allocated = cpu_to_le32(vol->mft_record_size);
m->base_mft_record = 0;
m->next_attr_instance = 0;
/* Add the termination attribute. */
a = (ATTR_RECORD*)((u8*)m + le16_to_cpu(m->attrs_offset));
a->type = AT_END;
a->length = 0;
ntfs_debug("Done.");
return 0;
}
/**
* ntfs_mft_record_format - format an mft record on an ntfs volume
* @vol: volume on which to format the mft record
* @mft_no: mft record number to format
*
* Format the mft record @mft_no in $MFT/$DATA, i.e. lay out an empty, unused
* mft record into the appropriate place of the mft data attribute. This is
* used when extending the mft data attribute.
*
* Return 0 on success and -errno on error.
*/
static int ntfs_mft_record_format(const ntfs_volume *vol, const s64 mft_no)
{
loff_t i_size;
struct inode *mft_vi = vol->mft_ino;
struct page *page;
MFT_RECORD *m;
pgoff_t index, end_index;
unsigned int ofs;
int err;
ntfs_debug("Entering for mft record 0x%llx.", (long long)mft_no);
/*
* The index into the page cache and the offset within the page cache
* page of the wanted mft record.
*/
index = mft_no << vol->mft_record_size_bits >> PAGE_CACHE_SHIFT;
ofs = (mft_no << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
/* The maximum valid index into the page cache for $MFT's data. */
i_size = i_size_read(mft_vi);
end_index = i_size >> PAGE_CACHE_SHIFT;
if (unlikely(index >= end_index)) {
if (unlikely(index > end_index || ofs + vol->mft_record_size >=
(i_size & ~PAGE_CACHE_MASK))) {
ntfs_error(vol->sb, "Tried to format non-existing mft "
"record 0x%llx.", (long long)mft_no);
return -ENOENT;
}
}
/* Read, map, and pin the page containing the mft record. */
page = ntfs_map_page(mft_vi->i_mapping, index);
if (IS_ERR(page)) {
ntfs_error(vol->sb, "Failed to map page containing mft record "
"to format 0x%llx.", (long long)mft_no);
return PTR_ERR(page);
}
lock_page(page);
BUG_ON(!PageUptodate(page));
ClearPageUptodate(page);
m = (MFT_RECORD*)((u8*)page_address(page) + ofs);
err = ntfs_mft_record_layout(vol, mft_no, m);
if (unlikely(err)) {
ntfs_error(vol->sb, "Failed to layout mft record 0x%llx.",
(long long)mft_no);
SetPageUptodate(page);
unlock_page(page);
ntfs_unmap_page(page);
return err;
}
flush_dcache_page(page);
SetPageUptodate(page);
unlock_page(page);
/*
* Make sure the mft record is written out to disk. We could use
* ilookup5() to check if an inode is in icache and so on but this is
* unnecessary as ntfs_writepage() will write the dirty record anyway.
*/
mark_ntfs_record_dirty(page, ofs);
ntfs_unmap_page(page);
ntfs_debug("Done.");
return 0;
}
/**
* ntfs_mft_record_alloc - allocate an mft record on an ntfs volume
* @vol: [IN] volume on which to allocate the mft record
* @mode: [IN] mode if want a file or directory, i.e. base inode or 0
* @base_ni: [IN] open base inode if allocating an extent mft record or NULL
* @mrec: [OUT] on successful return this is the mapped mft record
*
* Allocate an mft record in $MFT/$DATA of an open ntfs volume @vol.
*
* If @base_ni is NULL make the mft record a base mft record, i.e. a file or
* direvctory inode, and allocate it at the default allocator position. In
* this case @mode is the file mode as given to us by the caller. We in
* particular use @mode to distinguish whether a file or a directory is being
* created (S_IFDIR(mode) and S_IFREG(mode), respectively).
*
* If @base_ni is not NULL make the allocated mft record an extent record,
* allocate it starting at the mft record after the base mft record and attach
* the allocated and opened ntfs inode to the base inode @base_ni. In this
* case @mode must be 0 as it is meaningless for extent inodes.
*
* You need to check the return value with IS_ERR(). If false, the function
* was successful and the return value is the now opened ntfs inode of the
* allocated mft record. *@mrec is then set to the allocated, mapped, pinned,
* and locked mft record. If IS_ERR() is true, the function failed and the
* error code is obtained from PTR_ERR(return value). *@mrec is undefined in
* this case.
*
* Allocation strategy:
*
* To find a free mft record, we scan the mft bitmap for a zero bit. To
* optimize this we start scanning at the place specified by @base_ni or if
* @base_ni is NULL we start where we last stopped and we perform wrap around
* when we reach the end. Note, we do not try to allocate mft records below
* number 24 because numbers 0 to 15 are the defined system files anyway and 16
* to 24 are special in that they are used for storing extension mft records
* for the $DATA attribute of $MFT. This is required to avoid the possibility
* of creating a runlist with a circular dependency which once written to disk
* can never be read in again. Windows will only use records 16 to 24 for
* normal files if the volume is completely out of space. We never use them
* which means that when the volume is really out of space we cannot create any
* more files while Windows can still create up to 8 small files. We can start
* doing this at some later time, it does not matter much for now.
*
* When scanning the mft bitmap, we only search up to the last allocated mft
* record. If there are no free records left in the range 24 to number of
* allocated mft records, then we extend the $MFT/$DATA attribute in order to
* create free mft records. We extend the allocated size of $MFT/$DATA by 16
* records at a time or one cluster, if cluster size is above 16kiB. If there
* is not sufficient space to do this, we try to extend by a single mft record
* or one cluster, if cluster size is above the mft record size.
*
* No matter how many mft records we allocate, we initialize only the first
* allocated mft record, incrementing mft data size and initialized size
* accordingly, open an ntfs_inode for it and return it to the caller, unless
* there are less than 24 mft records, in which case we allocate and initialize
* mft records until we reach record 24 which we consider as the first free mft
* record for use by normal files.
*
* If during any stage we overflow the initialized data in the mft bitmap, we
* extend the initialized size (and data size) by 8 bytes, allocating another
* cluster if required. The bitmap data size has to be at least equal to the
* number of mft records in the mft, but it can be bigger, in which case the
* superflous bits are padded with zeroes.
*
* Thus, when we return successfully (IS_ERR() is false), we will have:
* - initialized / extended the mft bitmap if necessary,
* - initialized / extended the mft data if necessary,
* - set the bit corresponding to the mft record being allocated in the
* mft bitmap,
* - opened an ntfs_inode for the allocated mft record, and we will have
* - returned the ntfs_inode as well as the allocated mapped, pinned, and
* locked mft record.
*
* On error, the volume will be left in a consistent state and no record will
* be allocated. If rolling back a partial operation fails, we may leave some
* inconsistent metadata in which case we set NVolErrors() so the volume is
* left dirty when unmounted.
*
* Note, this function cannot make use of most of the normal functions, like
* for example for attribute resizing, etc, because when the run list overflows
* the base mft record and an attribute list is used, it is very important that
* the extension mft records used to store the $DATA attribute of $MFT can be
* reached without having to read the information contained inside them, as
* this would make it impossible to find them in the first place after the
* volume is unmounted. $MFT/$BITMAP probably does not need to follow this
* rule because the bitmap is not essential for finding the mft records, but on
* the other hand, handling the bitmap in this special way would make life
* easier because otherwise there might be circular invocations of functions
* when reading the bitmap.
*/
ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, const int mode,
ntfs_inode *base_ni, MFT_RECORD **mrec)
{
s64 ll, bit, old_data_initialized, old_data_size;
unsigned long flags;
struct inode *vi;
struct page *page;
ntfs_inode *mft_ni, *mftbmp_ni, *ni;
ntfs_attr_search_ctx *ctx;
MFT_RECORD *m;
ATTR_RECORD *a;
pgoff_t index;
unsigned int ofs;
int err;
le16 seq_no, usn;
bool record_formatted = false;
if (base_ni) {
ntfs_debug("Entering (allocating an extent mft record for "
"base mft record 0x%llx).",
(long long)base_ni->mft_no);
/* @mode and @base_ni are mutually exclusive. */
BUG_ON(mode);
} else
ntfs_debug("Entering (allocating a base mft record).");
if (mode) {
/* @mode and @base_ni are mutually exclusive. */
BUG_ON(base_ni);
/* We only support creation of normal files and directories. */
if (!S_ISREG(mode) && !S_ISDIR(mode))
return ERR_PTR(-EOPNOTSUPP);
}
BUG_ON(!mrec);
mft_ni = NTFS_I(vol->mft_ino);
mftbmp_ni = NTFS_I(vol->mftbmp_ino);
down_write(&vol->mftbmp_lock);
bit = ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(vol, base_ni);
if (bit >= 0) {
ntfs_debug("Found and allocated free record (#1), bit 0x%llx.",
(long long)bit);
goto have_alloc_rec;
}
if (bit != -ENOSPC) {
up_write(&vol->mftbmp_lock);
return ERR_PTR(bit);
}
/*
* No free mft records left. If the mft bitmap already covers more
* than the currently used mft records, the next records are all free,
* so we can simply allocate the first unused mft record.
* Note: We also have to make sure that the mft bitmap at least covers
* the first 24 mft records as they are special and whilst they may not
* be in use, we do not allocate from them.
*/
read_lock_irqsave(&mft_ni->size_lock, flags);
ll = mft_ni->initialized_size >> vol->mft_record_size_bits;
read_unlock_irqrestore(&mft_ni->size_lock, flags);
read_lock_irqsave(&mftbmp_ni->size_lock, flags);
old_data_initialized = mftbmp_ni->initialized_size;
read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
if (old_data_initialized << 3 > ll && old_data_initialized > 3) {
bit = ll;
if (bit < 24)
bit = 24;
if (unlikely(bit >= (1ll << 32)))
goto max_err_out;
ntfs_debug("Found free record (#2), bit 0x%llx.",
(long long)bit);
goto found_free_rec;
}
/*
* The mft bitmap needs to be expanded until it covers the first unused
* mft record that we can allocate.
* Note: The smallest mft record we allocate is mft record 24.
*/
bit = old_data_initialized << 3;
if (unlikely(bit >= (1ll << 32)))
goto max_err_out;
read_lock_irqsave(&mftbmp_ni->size_lock, flags);
old_data_size = mftbmp_ni->allocated_size;
ntfs_debug("Status of mftbmp before extension: allocated_size 0x%llx, "
"data_size 0x%llx, initialized_size 0x%llx.",
(long long)old_data_size,
(long long)i_size_read(vol->mftbmp_ino),
(long long)old_data_initialized);
read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
if (old_data_initialized + 8 > old_data_size) {
/* Need to extend bitmap by one more cluster. */
ntfs_debug("mftbmp: initialized_size + 8 > allocated_size.");
err = ntfs_mft_bitmap_extend_allocation_nolock(vol);
if (unlikely(err)) {
up_write(&vol->mftbmp_lock);
goto err_out;
}
#ifdef DEBUG
read_lock_irqsave(&mftbmp_ni->size_lock, flags);
ntfs_debug("Status of mftbmp after allocation extension: "
"allocated_size 0x%llx, data_size 0x%llx, "
"initialized_size 0x%llx.",
(long long)mftbmp_ni->allocated_size,
(long long)i_size_read(vol->mftbmp_ino),
(long long)mftbmp_ni->initialized_size);
read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
#endif /* DEBUG */
}
/*
* We now have sufficient allocated space, extend the initialized_size
* as well as the data_size if necessary and fill the new space with
* zeroes.
*/
err = ntfs_mft_bitmap_extend_initialized_nolock(vol);
if (unlikely(err)) {
up_write(&vol->mftbmp_lock);
goto err_out;
}
#ifdef DEBUG
read_lock_irqsave(&mftbmp_ni->size_lock, flags);
ntfs_debug("Status of mftbmp after initialized extension: "
"allocated_size 0x%llx, data_size 0x%llx, "
"initialized_size 0x%llx.",
(long long)mftbmp_ni->allocated_size,
(long long)i_size_read(vol->mftbmp_ino),
(long long)mftbmp_ni->initialized_size);
read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
#endif /* DEBUG */
ntfs_debug("Found free record (#3), bit 0x%llx.", (long long)bit);
found_free_rec:
/* @bit is the found free mft record, allocate it in the mft bitmap. */
ntfs_debug("At found_free_rec.");
err = ntfs_bitmap_set_bit(vol->mftbmp_ino, bit);
if (unlikely(err)) {
ntfs_error(vol->sb, "Failed to allocate bit in mft bitmap.");
up_write(&vol->mftbmp_lock);
goto err_out;
}
ntfs_debug("Set bit 0x%llx in mft bitmap.", (long long)bit);
have_alloc_rec:
/*
* The mft bitmap is now uptodate. Deal with mft data attribute now.
* Note, we keep hold of the mft bitmap lock for writing until all
* modifications to the mft data attribute are complete, too, as they
* will impact decisions for mft bitmap and mft record allocation done
* by a parallel allocation and if the lock is not maintained a
* parallel allocation could allocate the same mft record as this one.
*/
ll = (bit + 1) << vol->mft_record_size_bits;
read_lock_irqsave(&mft_ni->size_lock, flags);
old_data_initialized = mft_ni->initialized_size;
read_unlock_irqrestore(&mft_ni->size_lock, flags);
if (ll <= old_data_initialized) {
ntfs_debug("Allocated mft record already initialized.");
goto mft_rec_already_initialized;
}
ntfs_debug("Initializing allocated mft record.");
/*
* The mft record is outside the initialized data. Extend the mft data
* attribute until it covers the allocated record. The loop is only
* actually traversed more than once when a freshly formatted volume is
* first written to so it optimizes away nicely in the common case.
*/
read_lock_irqsave(&mft_ni->size_lock, flags);
ntfs_debug("Status of mft data before extension: "
"allocated_size 0x%llx, data_size 0x%llx, "
"initialized_size 0x%llx.",
(long long)mft_ni->allocated_size,
(long long)i_size_read(vol->mft_ino),
(long long)mft_ni->initialized_size);
while (ll > mft_ni->allocated_size) {
read_unlock_irqrestore(&mft_ni->size_lock, flags);
err = ntfs_mft_data_extend_allocation_nolock(vol);
if (unlikely(err)) {
ntfs_error(vol->sb, "Failed to extend mft data "
"allocation.");
goto undo_mftbmp_alloc_nolock;
}
read_lock_irqsave(&mft_ni->size_lock, flags);
ntfs_debug("Status of mft data after allocation extension: "
"allocated_size 0x%llx, data_size 0x%llx, "
"initialized_size 0x%llx.",
(long long)mft_ni->allocated_size,
(long long)i_size_read(vol->mft_ino),
(long long)mft_ni->initialized_size);
}
read_unlock_irqrestore(&mft_ni->size_lock, flags);
/*
* Extend mft data initialized size (and data size of course) to reach
* the allocated mft record, formatting the mft records allong the way.
* Note: We only modify the ntfs_inode structure as that is all that is
* needed by ntfs_mft_record_format(). We will update the attribute
* record itself in one fell swoop later on.
*/
write_lock_irqsave(&mft_ni->size_lock, flags);
old_data_initialized = mft_ni->initialized_size;
old_data_size = vol->mft_ino->i_size;
while (ll > mft_ni->initialized_size) {
s64 new_initialized_size, mft_no;
new_initialized_size = mft_ni->initialized_size +
vol->mft_record_size;
mft_no = mft_ni->initialized_size >> vol->mft_record_size_bits;
if (new_initialized_size > i_size_read(vol->mft_ino))
i_size_write(vol->mft_ino, new_initialized_size);
write_unlock_irqrestore(&mft_ni->size_lock, flags);
ntfs_debug("Initializing mft record 0x%llx.",
(long long)mft_no);
err = ntfs_mft_record_format(vol, mft_no);
if (unlikely(err)) {
ntfs_error(vol->sb, "Failed to format mft record.");
goto undo_data_init;
}
write_lock_irqsave(&mft_ni->size_lock, flags);
mft_ni->initialized_size = new_initialized_size;
}
write_unlock_irqrestore(&mft_ni->size_lock, flags);
record_formatted = true;
/* Update the mft data attribute record to reflect the new sizes. */
m = map_mft_record(mft_ni);
if (IS_ERR(m)) {
ntfs_error(vol->sb, "Failed to map mft record.");
err = PTR_ERR(m);
goto undo_data_init;
}
ctx = ntfs_attr_get_search_ctx(mft_ni, m);
if (unlikely(!ctx)) {
ntfs_error(vol->sb, "Failed to get search context.");
err = -ENOMEM;
unmap_mft_record(mft_ni);
goto undo_data_init;
}
err = ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
CASE_SENSITIVE, 0, NULL, 0, ctx);
if (unlikely(err)) {
ntfs_error(vol->sb, "Failed to find first attribute extent of "
"mft data attribute.");
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(mft_ni);
goto undo_data_init;
}
a = ctx->attr;
read_lock_irqsave(&mft_ni->size_lock, flags);
a->data.non_resident.initialized_size =
cpu_to_sle64(mft_ni->initialized_size);
a->data.non_resident.data_size =
cpu_to_sle64(i_size_read(vol->mft_ino));
read_unlock_irqrestore(&mft_ni->size_lock, flags);
/* Ensure the changes make it to disk. */
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(mft_ni);
read_lock_irqsave(&mft_ni->size_lock, flags);
ntfs_debug("Status of mft data after mft record initialization: "
"allocated_size 0x%llx, data_size 0x%llx, "
"initialized_size 0x%llx.",
(long long)mft_ni->allocated_size,
(long long)i_size_read(vol->mft_ino),
(long long)mft_ni->initialized_size);
BUG_ON(i_size_read(vol->mft_ino) > mft_ni->allocated_size);
BUG_ON(mft_ni->initialized_size > i_size_read(vol->mft_ino));
read_unlock_irqrestore(&mft_ni->size_lock, flags);
mft_rec_already_initialized:
/*
* We can finally drop the mft bitmap lock as the mft data attribute
* has been fully updated. The only disparity left is that the
* allocated mft record still needs to be marked as in use to match the
* set bit in the mft bitmap but this is actually not a problem since
* this mft record is not referenced from anywhere yet and the fact
* that it is allocated in the mft bitmap means that no-one will try to
* allocate it either.
*/
up_write(&vol->mftbmp_lock);
/*
* We now have allocated and initialized the mft record. Calculate the
* index of and the offset within the page cache page the record is in.
*/
index = bit << vol->mft_record_size_bits >> PAGE_CACHE_SHIFT;
ofs = (bit << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
/* Read, map, and pin the page containing the mft record. */
page = ntfs_map_page(vol->mft_ino->i_mapping, index);
if (IS_ERR(page)) {
ntfs_error(vol->sb, "Failed to map page containing allocated "
"mft record 0x%llx.", (long long)bit);
err = PTR_ERR(page);
goto undo_mftbmp_alloc;
}
lock_page(page);
BUG_ON(!PageUptodate(page));
ClearPageUptodate(page);
m = (MFT_RECORD*)((u8*)page_address(page) + ofs);
/* If we just formatted the mft record no need to do it again. */
if (!record_formatted) {
/* Sanity check that the mft record is really not in use. */
if (ntfs_is_file_record(m->magic) &&
(m->flags & MFT_RECORD_IN_USE)) {
ntfs_error(vol->sb, "Mft record 0x%llx was marked "
"free in mft bitmap but is marked "
"used itself. Corrupt filesystem. "
"Unmount and run chkdsk.",
(long long)bit);
err = -EIO;
SetPageUptodate(page);
unlock_page(page);
ntfs_unmap_page(page);
NVolSetErrors(vol);
goto undo_mftbmp_alloc;
}
/*
* We need to (re-)format the mft record, preserving the
* sequence number if it is not zero as well as the update
* sequence number if it is not zero or -1 (0xffff). This
* means we do not need to care whether or not something went
* wrong with the previous mft record.
*/
seq_no = m->sequence_number;
usn = *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs));
err = ntfs_mft_record_layout(vol, bit, m);
if (unlikely(err)) {
ntfs_error(vol->sb, "Failed to layout allocated mft "
"record 0x%llx.", (long long)bit);
SetPageUptodate(page);
unlock_page(page);
ntfs_unmap_page(page);
goto undo_mftbmp_alloc;
}
if (seq_no)
m->sequence_number = seq_no;
if (usn && le16_to_cpu(usn) != 0xffff)
*(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = usn;
}
/* Set the mft record itself in use. */
m->flags |= MFT_RECORD_IN_USE;
if (S_ISDIR(mode))
m->flags |= MFT_RECORD_IS_DIRECTORY;
flush_dcache_page(page);
SetPageUptodate(page);
if (base_ni) {
MFT_RECORD *m_tmp;
/*
* Setup the base mft record in the extent mft record. This
* completes initialization of the allocated extent mft record
* and we can simply use it with map_extent_mft_record().
*/
m->base_mft_record = MK_LE_MREF(base_ni->mft_no,
base_ni->seq_no);
/*
* Allocate an extent inode structure for the new mft record,
* attach it to the base inode @base_ni and map, pin, and lock
* its, i.e. the allocated, mft record.
*/
m_tmp = map_extent_mft_record(base_ni, bit, &ni);
if (IS_ERR(m_tmp)) {
ntfs_error(vol->sb, "Failed to map allocated extent "
"mft record 0x%llx.", (long long)bit);
err = PTR_ERR(m_tmp);
/* Set the mft record itself not in use. */
m->flags &= cpu_to_le16(
~le16_to_cpu(MFT_RECORD_IN_USE));
flush_dcache_page(page);
/* Make sure the mft record is written out to disk. */
mark_ntfs_record_dirty(page, ofs);
unlock_page(page);
ntfs_unmap_page(page);
goto undo_mftbmp_alloc;
}
BUG_ON(m != m_tmp);
/*
* Make sure the allocated mft record is written out to disk.
* No need to set the inode dirty because the caller is going
* to do that anyway after finishing with the new extent mft
* record (e.g. at a minimum a new attribute will be added to
* the mft record.
*/
mark_ntfs_record_dirty(page, ofs);
unlock_page(page);
/*
* Need to unmap the page since map_extent_mft_record() mapped
* it as well so we have it mapped twice at the moment.
*/
ntfs_unmap_page(page);
} else {
/*
* Allocate a new VFS inode and set it up. NOTE: @vi->i_nlink
* is set to 1 but the mft record->link_count is 0. The caller
* needs to bear this in mind.
*/
vi = new_inode(vol->sb);
if (unlikely(!vi)) {
err = -ENOMEM;
/* Set the mft record itself not in use. */
m->flags &= cpu_to_le16(
~le16_to_cpu(MFT_RECORD_IN_USE));
flush_dcache_page(page);
/* Make sure the mft record is written out to disk. */
mark_ntfs_record_dirty(page, ofs);
unlock_page(page);
ntfs_unmap_page(page);
goto undo_mftbmp_alloc;
}
vi->i_ino = bit;
/*
* This is for checking whether an inode has changed w.r.t. a
* file so that the file can be updated if necessary (compare
* with f_version).
*/
vi->i_version = 1;
/* The owner and group come from the ntfs volume. */
vi->i_uid = vol->uid;
vi->i_gid = vol->gid;
/* Initialize the ntfs specific part of @vi. */
ntfs_init_big_inode(vi);
ni = NTFS_I(vi);
/*
* Set the appropriate mode, attribute type, and name. For
* directories, also setup the index values to the defaults.
*/
if (S_ISDIR(mode)) {
vi->i_mode = S_IFDIR | S_IRWXUGO;
vi->i_mode &= ~vol->dmask;
NInoSetMstProtected(ni);
ni->type = AT_INDEX_ALLOCATION;
ni->name = I30;
ni->name_len = 4;
ni->itype.index.block_size = 4096;
ni->itype.index.block_size_bits = ntfs_ffs(4096) - 1;
ni->itype.index.collation_rule = COLLATION_FILE_NAME;
if (vol->cluster_size <= ni->itype.index.block_size) {
ni->itype.index.vcn_size = vol->cluster_size;
ni->itype.index.vcn_size_bits =
vol->cluster_size_bits;
} else {
ni->itype.index.vcn_size = vol->sector_size;
ni->itype.index.vcn_size_bits =
vol->sector_size_bits;
}
} else {
vi->i_mode = S_IFREG | S_IRWXUGO;
vi->i_mode &= ~vol->fmask;
ni->type = AT_DATA;
ni->name = NULL;
ni->name_len = 0;
}
if (IS_RDONLY(vi))
vi->i_mode &= ~S_IWUGO;
/* Set the inode times to the current time. */
vi->i_atime = vi->i_mtime = vi->i_ctime =
current_fs_time(vi->i_sb);
/*
* Set the file size to 0, the ntfs inode sizes are set to 0 by
* the call to ntfs_init_big_inode() below.
*/
vi->i_size = 0;
vi->i_blocks = 0;
/* Set the sequence number. */
vi->i_generation = ni->seq_no = le16_to_cpu(m->sequence_number);
/*
* Manually map, pin, and lock the mft record as we already
* have its page mapped and it is very easy to do.
*/
atomic_inc(&ni->count);
mutex_lock(&ni->mrec_lock);
ni->page = page;
ni->page_ofs = ofs;
/*
* Make sure the allocated mft record is written out to disk.
* NOTE: We do not set the ntfs inode dirty because this would
* fail in ntfs_write_inode() because the inode does not have a
* standard information attribute yet. Also, there is no need
* to set the inode dirty because the caller is going to do
* that anyway after finishing with the new mft record (e.g. at
* a minimum some new attributes will be added to the mft
* record.
*/
mark_ntfs_record_dirty(page, ofs);
unlock_page(page);
/* Add the inode to the inode hash for the superblock. */
insert_inode_hash(vi);
/* Update the default mft allocation position. */
vol->mft_data_pos = bit + 1;
}
/*
* Return the opened, allocated inode of the allocated mft record as
* well as the mapped, pinned, and locked mft record.
*/
ntfs_debug("Returning opened, allocated %sinode 0x%llx.",
base_ni ? "extent " : "", (long long)bit);
*mrec = m;
return ni;
undo_data_init:
write_lock_irqsave(&mft_ni->size_lock, flags);
mft_ni->initialized_size = old_data_initialized;
i_size_write(vol->mft_ino, old_data_size);
write_unlock_irqrestore(&mft_ni->size_lock, flags);
goto undo_mftbmp_alloc_nolock;
undo_mftbmp_alloc:
down_write(&vol->mftbmp_lock);
undo_mftbmp_alloc_nolock:
if (ntfs_bitmap_clear_bit(vol->mftbmp_ino, bit)) {
ntfs_error(vol->sb, "Failed to clear bit in mft bitmap.%s", es);
NVolSetErrors(vol);
}
up_write(&vol->mftbmp_lock);
err_out:
return ERR_PTR(err);
max_err_out:
ntfs_warning(vol->sb, "Cannot allocate mft record because the maximum "
"number of inodes (2^32) has already been reached.");
up_write(&vol->mftbmp_lock);
return ERR_PTR(-ENOSPC);
}
/**
* ntfs_extent_mft_record_free - free an extent mft record on an ntfs volume
* @ni: ntfs inode of the mapped extent mft record to free
* @m: mapped extent mft record of the ntfs inode @ni
*
* Free the mapped extent mft record @m of the extent ntfs inode @ni.
*
* Note that this function unmaps the mft record and closes and destroys @ni
* internally and hence you cannot use either @ni nor @m any more after this
* function returns success.
*
* On success return 0 and on error return -errno. @ni and @m are still valid
* in this case and have not been freed.
*
* For some errors an error message is displayed and the success code 0 is
* returned and the volume is then left dirty on umount. This makes sense in
* case we could not rollback the changes that were already done since the
* caller no longer wants to reference this mft record so it does not matter to
* the caller if something is wrong with it as long as it is properly detached
* from the base inode.
*/
int ntfs_extent_mft_record_free(ntfs_inode *ni, MFT_RECORD *m)
{
unsigned long mft_no = ni->mft_no;
ntfs_volume *vol = ni->vol;
ntfs_inode *base_ni;
ntfs_inode **extent_nis;
int i, err;
le16 old_seq_no;
u16 seq_no;
BUG_ON(NInoAttr(ni));
BUG_ON(ni->nr_extents != -1);
mutex_lock(&ni->extent_lock);
base_ni = ni->ext.base_ntfs_ino;
mutex_unlock(&ni->extent_lock);
BUG_ON(base_ni->nr_extents <= 0);
ntfs_debug("Entering for extent inode 0x%lx, base inode 0x%lx.\n",
mft_no, base_ni->mft_no);
mutex_lock(&base_ni->extent_lock);
/* Make sure we are holding the only reference to the extent inode. */
if (atomic_read(&ni->count) > 2) {
ntfs_error(vol->sb, "Tried to free busy extent inode 0x%lx, "
"not freeing.", base_ni->mft_no);
mutex_unlock(&base_ni->extent_lock);
return -EBUSY;
}
/* Dissociate the ntfs inode from the base inode. */
extent_nis = base_ni->ext.extent_ntfs_inos;
err = -ENOENT;
for (i = 0; i < base_ni->nr_extents; i++) {
if (ni != extent_nis[i])
continue;
extent_nis += i;
base_ni->nr_extents--;
memmove(extent_nis, extent_nis + 1, (base_ni->nr_extents - i) *
sizeof(ntfs_inode*));
err = 0;
break;
}
mutex_unlock(&base_ni->extent_lock);
if (unlikely(err)) {
ntfs_error(vol->sb, "Extent inode 0x%lx is not attached to "
"its base inode 0x%lx.", mft_no,
base_ni->mft_no);
BUG();
}
/*
* The extent inode is no longer attached to the base inode so no one
* can get a reference to it any more.
*/
/* Mark the mft record as not in use. */
m->flags &= ~MFT_RECORD_IN_USE;
/* Increment the sequence number, skipping zero, if it is not zero. */
old_seq_no = m->sequence_number;
seq_no = le16_to_cpu(old_seq_no);
if (seq_no == 0xffff)
seq_no = 1;
else if (seq_no)
seq_no++;
m->sequence_number = cpu_to_le16(seq_no);
/*
* Set the ntfs inode dirty and write it out. We do not need to worry
* about the base inode here since whatever caused the extent mft
* record to be freed is guaranteed to do it already.
*/
NInoSetDirty(ni);
err = write_mft_record(ni, m, 0);
if (unlikely(err)) {
ntfs_error(vol->sb, "Failed to write mft record 0x%lx, not "
"freeing.", mft_no);
goto rollback;
}
rollback_error:
/* Unmap and throw away the now freed extent inode. */
unmap_extent_mft_record(ni);
ntfs_clear_extent_inode(ni);
/* Clear the bit in the $MFT/$BITMAP corresponding to this record. */
down_write(&vol->mftbmp_lock);
err = ntfs_bitmap_clear_bit(vol->mftbmp_ino, mft_no);
up_write(&vol->mftbmp_lock);
if (unlikely(err)) {
/*
* The extent inode is gone but we failed to deallocate it in
* the mft bitmap. Just emit a warning and leave the volume
* dirty on umount.
*/
ntfs_error(vol->sb, "Failed to clear bit in mft bitmap.%s", es);
NVolSetErrors(vol);
}
return 0;
rollback:
/* Rollback what we did... */
mutex_lock(&base_ni->extent_lock);
extent_nis = base_ni->ext.extent_ntfs_inos;
if (!(base_ni->nr_extents & 3)) {
int new_size = (base_ni->nr_extents + 4) * sizeof(ntfs_inode*);
extent_nis = kmalloc(new_size, GFP_NOFS);
if (unlikely(!extent_nis)) {
ntfs_error(vol->sb, "Failed to allocate internal "
"buffer during rollback.%s", es);
mutex_unlock(&base_ni->extent_lock);
NVolSetErrors(vol);
goto rollback_error;
}
if (base_ni->nr_extents) {
BUG_ON(!base_ni->ext.extent_ntfs_inos);
memcpy(extent_nis, base_ni->ext.extent_ntfs_inos,
new_size - 4 * sizeof(ntfs_inode*));
kfree(base_ni->ext.extent_ntfs_inos);
}
base_ni->ext.extent_ntfs_inos = extent_nis;
}
m->flags |= MFT_RECORD_IN_USE;
m->sequence_number = old_seq_no;
extent_nis[base_ni->nr_extents++] = ni;
mutex_unlock(&base_ni->extent_lock);
mark_mft_record_dirty(ni);
return err;
}
#endif /* NTFS_RW */
| gpl-2.0 |
esgie/viennalte_p905_kernel_source | fs/ntfs/mft.c | 9312 | 101923 | /**
* mft.c - NTFS kernel mft record operations. Part of the Linux-NTFS project.
*
* Copyright (c) 2001-2012 Anton Altaparmakov and Tuxera Inc.
* Copyright (c) 2002 Richard Russon
*
* This program/include file 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/include file 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 (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/buffer_head.h>
#include <linux/slab.h>
#include <linux/swap.h>
#include "attrib.h"
#include "aops.h"
#include "bitmap.h"
#include "debug.h"
#include "dir.h"
#include "lcnalloc.h"
#include "malloc.h"
#include "mft.h"
#include "ntfs.h"
/**
* map_mft_record_page - map the page in which a specific mft record resides
* @ni: ntfs inode whose mft record page to map
*
* This maps the page in which the mft record of the ntfs inode @ni is situated
* and returns a pointer to the mft record within the mapped page.
*
* Return value needs to be checked with IS_ERR() and if that is true PTR_ERR()
* contains the negative error code returned.
*/
static inline MFT_RECORD *map_mft_record_page(ntfs_inode *ni)
{
loff_t i_size;
ntfs_volume *vol = ni->vol;
struct inode *mft_vi = vol->mft_ino;
struct page *page;
unsigned long index, end_index;
unsigned ofs;
BUG_ON(ni->page);
/*
* The index into the page cache and the offset within the page cache
* page of the wanted mft record. FIXME: We need to check for
* overflowing the unsigned long, but I don't think we would ever get
* here if the volume was that big...
*/
index = (u64)ni->mft_no << vol->mft_record_size_bits >>
PAGE_CACHE_SHIFT;
ofs = (ni->mft_no << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
i_size = i_size_read(mft_vi);
/* The maximum valid index into the page cache for $MFT's data. */
end_index = i_size >> PAGE_CACHE_SHIFT;
/* If the wanted index is out of bounds the mft record doesn't exist. */
if (unlikely(index >= end_index)) {
if (index > end_index || (i_size & ~PAGE_CACHE_MASK) < ofs +
vol->mft_record_size) {
page = ERR_PTR(-ENOENT);
ntfs_error(vol->sb, "Attempt to read mft record 0x%lx, "
"which is beyond the end of the mft. "
"This is probably a bug in the ntfs "
"driver.", ni->mft_no);
goto err_out;
}
}
/* Read, map, and pin the page. */
page = ntfs_map_page(mft_vi->i_mapping, index);
if (likely(!IS_ERR(page))) {
/* Catch multi sector transfer fixup errors. */
if (likely(ntfs_is_mft_recordp((le32*)(page_address(page) +
ofs)))) {
ni->page = page;
ni->page_ofs = ofs;
return page_address(page) + ofs;
}
ntfs_error(vol->sb, "Mft record 0x%lx is corrupt. "
"Run chkdsk.", ni->mft_no);
ntfs_unmap_page(page);
page = ERR_PTR(-EIO);
NVolSetErrors(vol);
}
err_out:
ni->page = NULL;
ni->page_ofs = 0;
return (void*)page;
}
/**
* map_mft_record - map, pin and lock an mft record
* @ni: ntfs inode whose MFT record to map
*
* First, take the mrec_lock mutex. We might now be sleeping, while waiting
* for the mutex if it was already locked by someone else.
*
* The page of the record is mapped using map_mft_record_page() before being
* returned to the caller.
*
* This in turn uses ntfs_map_page() to get the page containing the wanted mft
* record (it in turn calls read_cache_page() which reads it in from disk if
* necessary, increments the use count on the page so that it cannot disappear
* under us and returns a reference to the page cache page).
*
* If read_cache_page() invokes ntfs_readpage() to load the page from disk, it
* sets PG_locked and clears PG_uptodate on the page. Once I/O has completed
* and the post-read mst fixups on each mft record in the page have been
* performed, the page gets PG_uptodate set and PG_locked cleared (this is done
* in our asynchronous I/O completion handler end_buffer_read_mft_async()).
* ntfs_map_page() waits for PG_locked to become clear and checks if
* PG_uptodate is set and returns an error code if not. This provides
* sufficient protection against races when reading/using the page.
*
* However there is the write mapping to think about. Doing the above described
* checking here will be fine, because when initiating the write we will set
* PG_locked and clear PG_uptodate making sure nobody is touching the page
* contents. Doing the locking this way means that the commit to disk code in
* the page cache code paths is automatically sufficiently locked with us as
* we will not touch a page that has been locked or is not uptodate. The only
* locking problem then is them locking the page while we are accessing it.
*
* So that code will end up having to own the mrec_lock of all mft
* records/inodes present in the page before I/O can proceed. In that case we
* wouldn't need to bother with PG_locked and PG_uptodate as nobody will be
* accessing anything without owning the mrec_lock mutex. But we do need to
* use them because of the read_cache_page() invocation and the code becomes so
* much simpler this way that it is well worth it.
*
* The mft record is now ours and we return a pointer to it. You need to check
* the returned pointer with IS_ERR() and if that is true, PTR_ERR() will return
* the error code.
*
* NOTE: Caller is responsible for setting the mft record dirty before calling
* unmap_mft_record(). This is obviously only necessary if the caller really
* modified the mft record...
* Q: Do we want to recycle one of the VFS inode state bits instead?
* A: No, the inode ones mean we want to change the mft record, not we want to
* write it out.
*/
MFT_RECORD *map_mft_record(ntfs_inode *ni)
{
MFT_RECORD *m;
ntfs_debug("Entering for mft_no 0x%lx.", ni->mft_no);
/* Make sure the ntfs inode doesn't go away. */
atomic_inc(&ni->count);
/* Serialize access to this mft record. */
mutex_lock(&ni->mrec_lock);
m = map_mft_record_page(ni);
if (likely(!IS_ERR(m)))
return m;
mutex_unlock(&ni->mrec_lock);
atomic_dec(&ni->count);
ntfs_error(ni->vol->sb, "Failed with error code %lu.", -PTR_ERR(m));
return m;
}
/**
* unmap_mft_record_page - unmap the page in which a specific mft record resides
* @ni: ntfs inode whose mft record page to unmap
*
* This unmaps the page in which the mft record of the ntfs inode @ni is
* situated and returns. This is a NOOP if highmem is not configured.
*
* The unmap happens via ntfs_unmap_page() which in turn decrements the use
* count on the page thus releasing it from the pinned state.
*
* We do not actually unmap the page from memory of course, as that will be
* done by the page cache code itself when memory pressure increases or
* whatever.
*/
static inline void unmap_mft_record_page(ntfs_inode *ni)
{
BUG_ON(!ni->page);
// TODO: If dirty, blah...
ntfs_unmap_page(ni->page);
ni->page = NULL;
ni->page_ofs = 0;
return;
}
/**
* unmap_mft_record - release a mapped mft record
* @ni: ntfs inode whose MFT record to unmap
*
* We release the page mapping and the mrec_lock mutex which unmaps the mft
* record and releases it for others to get hold of. We also release the ntfs
* inode by decrementing the ntfs inode reference count.
*
* NOTE: If caller has modified the mft record, it is imperative to set the mft
* record dirty BEFORE calling unmap_mft_record().
*/
void unmap_mft_record(ntfs_inode *ni)
{
struct page *page = ni->page;
BUG_ON(!page);
ntfs_debug("Entering for mft_no 0x%lx.", ni->mft_no);
unmap_mft_record_page(ni);
mutex_unlock(&ni->mrec_lock);
atomic_dec(&ni->count);
/*
* If pure ntfs_inode, i.e. no vfs inode attached, we leave it to
* ntfs_clear_extent_inode() in the extent inode case, and to the
* caller in the non-extent, yet pure ntfs inode case, to do the actual
* tear down of all structures and freeing of all allocated memory.
*/
return;
}
/**
* map_extent_mft_record - load an extent inode and attach it to its base
* @base_ni: base ntfs inode
* @mref: mft reference of the extent inode to load
* @ntfs_ino: on successful return, pointer to the ntfs_inode structure
*
* Load the extent mft record @mref and attach it to its base inode @base_ni.
* Return the mapped extent mft record if IS_ERR(result) is false. Otherwise
* PTR_ERR(result) gives the negative error code.
*
* On successful return, @ntfs_ino contains a pointer to the ntfs_inode
* structure of the mapped extent inode.
*/
MFT_RECORD *map_extent_mft_record(ntfs_inode *base_ni, MFT_REF mref,
ntfs_inode **ntfs_ino)
{
MFT_RECORD *m;
ntfs_inode *ni = NULL;
ntfs_inode **extent_nis = NULL;
int i;
unsigned long mft_no = MREF(mref);
u16 seq_no = MSEQNO(mref);
bool destroy_ni = false;
ntfs_debug("Mapping extent mft record 0x%lx (base mft record 0x%lx).",
mft_no, base_ni->mft_no);
/* Make sure the base ntfs inode doesn't go away. */
atomic_inc(&base_ni->count);
/*
* Check if this extent inode has already been added to the base inode,
* in which case just return it. If not found, add it to the base
* inode before returning it.
*/
mutex_lock(&base_ni->extent_lock);
if (base_ni->nr_extents > 0) {
extent_nis = base_ni->ext.extent_ntfs_inos;
for (i = 0; i < base_ni->nr_extents; i++) {
if (mft_no != extent_nis[i]->mft_no)
continue;
ni = extent_nis[i];
/* Make sure the ntfs inode doesn't go away. */
atomic_inc(&ni->count);
break;
}
}
if (likely(ni != NULL)) {
mutex_unlock(&base_ni->extent_lock);
atomic_dec(&base_ni->count);
/* We found the record; just have to map and return it. */
m = map_mft_record(ni);
/* map_mft_record() has incremented this on success. */
atomic_dec(&ni->count);
if (likely(!IS_ERR(m))) {
/* Verify the sequence number. */
if (likely(le16_to_cpu(m->sequence_number) == seq_no)) {
ntfs_debug("Done 1.");
*ntfs_ino = ni;
return m;
}
unmap_mft_record(ni);
ntfs_error(base_ni->vol->sb, "Found stale extent mft "
"reference! Corrupt filesystem. "
"Run chkdsk.");
return ERR_PTR(-EIO);
}
map_err_out:
ntfs_error(base_ni->vol->sb, "Failed to map extent "
"mft record, error code %ld.", -PTR_ERR(m));
return m;
}
/* Record wasn't there. Get a new ntfs inode and initialize it. */
ni = ntfs_new_extent_inode(base_ni->vol->sb, mft_no);
if (unlikely(!ni)) {
mutex_unlock(&base_ni->extent_lock);
atomic_dec(&base_ni->count);
return ERR_PTR(-ENOMEM);
}
ni->vol = base_ni->vol;
ni->seq_no = seq_no;
ni->nr_extents = -1;
ni->ext.base_ntfs_ino = base_ni;
/* Now map the record. */
m = map_mft_record(ni);
if (IS_ERR(m)) {
mutex_unlock(&base_ni->extent_lock);
atomic_dec(&base_ni->count);
ntfs_clear_extent_inode(ni);
goto map_err_out;
}
/* Verify the sequence number if it is present. */
if (seq_no && (le16_to_cpu(m->sequence_number) != seq_no)) {
ntfs_error(base_ni->vol->sb, "Found stale extent mft "
"reference! Corrupt filesystem. Run chkdsk.");
destroy_ni = true;
m = ERR_PTR(-EIO);
goto unm_err_out;
}
/* Attach extent inode to base inode, reallocating memory if needed. */
if (!(base_ni->nr_extents & 3)) {
ntfs_inode **tmp;
int new_size = (base_ni->nr_extents + 4) * sizeof(ntfs_inode *);
tmp = kmalloc(new_size, GFP_NOFS);
if (unlikely(!tmp)) {
ntfs_error(base_ni->vol->sb, "Failed to allocate "
"internal buffer.");
destroy_ni = true;
m = ERR_PTR(-ENOMEM);
goto unm_err_out;
}
if (base_ni->nr_extents) {
BUG_ON(!base_ni->ext.extent_ntfs_inos);
memcpy(tmp, base_ni->ext.extent_ntfs_inos, new_size -
4 * sizeof(ntfs_inode *));
kfree(base_ni->ext.extent_ntfs_inos);
}
base_ni->ext.extent_ntfs_inos = tmp;
}
base_ni->ext.extent_ntfs_inos[base_ni->nr_extents++] = ni;
mutex_unlock(&base_ni->extent_lock);
atomic_dec(&base_ni->count);
ntfs_debug("Done 2.");
*ntfs_ino = ni;
return m;
unm_err_out:
unmap_mft_record(ni);
mutex_unlock(&base_ni->extent_lock);
atomic_dec(&base_ni->count);
/*
* If the extent inode was not attached to the base inode we need to
* release it or we will leak memory.
*/
if (destroy_ni)
ntfs_clear_extent_inode(ni);
return m;
}
#ifdef NTFS_RW
/**
* __mark_mft_record_dirty - set the mft record and the page containing it dirty
* @ni: ntfs inode describing the mapped mft record
*
* Internal function. Users should call mark_mft_record_dirty() instead.
*
* Set the mapped (extent) mft record of the (base or extent) ntfs inode @ni,
* as well as the page containing the mft record, dirty. Also, mark the base
* vfs inode dirty. This ensures that any changes to the mft record are
* written out to disk.
*
* NOTE: We only set I_DIRTY_SYNC and I_DIRTY_DATASYNC (and not I_DIRTY_PAGES)
* on the base vfs inode, because even though file data may have been modified,
* it is dirty in the inode meta data rather than the data page cache of the
* inode, and thus there are no data pages that need writing out. Therefore, a
* full mark_inode_dirty() is overkill. A mark_inode_dirty_sync(), on the
* other hand, is not sufficient, because ->write_inode needs to be called even
* in case of fdatasync. This needs to happen or the file data would not
* necessarily hit the device synchronously, even though the vfs inode has the
* O_SYNC flag set. Also, I_DIRTY_DATASYNC simply "feels" better than just
* I_DIRTY_SYNC, since the file data has not actually hit the block device yet,
* which is not what I_DIRTY_SYNC on its own would suggest.
*/
void __mark_mft_record_dirty(ntfs_inode *ni)
{
ntfs_inode *base_ni;
ntfs_debug("Entering for inode 0x%lx.", ni->mft_no);
BUG_ON(NInoAttr(ni));
mark_ntfs_record_dirty(ni->page, ni->page_ofs);
/* Determine the base vfs inode and mark it dirty, too. */
mutex_lock(&ni->extent_lock);
if (likely(ni->nr_extents >= 0))
base_ni = ni;
else
base_ni = ni->ext.base_ntfs_ino;
mutex_unlock(&ni->extent_lock);
__mark_inode_dirty(VFS_I(base_ni), I_DIRTY_SYNC | I_DIRTY_DATASYNC);
}
static const char *ntfs_please_email = "Please email "
"linux-ntfs-dev@lists.sourceforge.net and say that you saw "
"this message. Thank you.";
/**
* ntfs_sync_mft_mirror_umount - synchronise an mft record to the mft mirror
* @vol: ntfs volume on which the mft record to synchronize resides
* @mft_no: mft record number of mft record to synchronize
* @m: mapped, mst protected (extent) mft record to synchronize
*
* Write the mapped, mst protected (extent) mft record @m with mft record
* number @mft_no to the mft mirror ($MFTMirr) of the ntfs volume @vol,
* bypassing the page cache and the $MFTMirr inode itself.
*
* This function is only for use at umount time when the mft mirror inode has
* already been disposed off. We BUG() if we are called while the mft mirror
* inode is still attached to the volume.
*
* On success return 0. On error return -errno.
*
* NOTE: This function is not implemented yet as I am not convinced it can
* actually be triggered considering the sequence of commits we do in super.c::
* ntfs_put_super(). But just in case we provide this place holder as the
* alternative would be either to BUG() or to get a NULL pointer dereference
* and Oops.
*/
static int ntfs_sync_mft_mirror_umount(ntfs_volume *vol,
const unsigned long mft_no, MFT_RECORD *m)
{
BUG_ON(vol->mftmirr_ino);
ntfs_error(vol->sb, "Umount time mft mirror syncing is not "
"implemented yet. %s", ntfs_please_email);
return -EOPNOTSUPP;
}
/**
* ntfs_sync_mft_mirror - synchronize an mft record to the mft mirror
* @vol: ntfs volume on which the mft record to synchronize resides
* @mft_no: mft record number of mft record to synchronize
* @m: mapped, mst protected (extent) mft record to synchronize
* @sync: if true, wait for i/o completion
*
* Write the mapped, mst protected (extent) mft record @m with mft record
* number @mft_no to the mft mirror ($MFTMirr) of the ntfs volume @vol.
*
* On success return 0. On error return -errno and set the volume errors flag
* in the ntfs volume @vol.
*
* NOTE: We always perform synchronous i/o and ignore the @sync parameter.
*
* TODO: If @sync is false, want to do truly asynchronous i/o, i.e. just
* schedule i/o via ->writepage or do it via kntfsd or whatever.
*/
int ntfs_sync_mft_mirror(ntfs_volume *vol, const unsigned long mft_no,
MFT_RECORD *m, int sync)
{
struct page *page;
unsigned int blocksize = vol->sb->s_blocksize;
int max_bhs = vol->mft_record_size / blocksize;
struct buffer_head *bhs[max_bhs];
struct buffer_head *bh, *head;
u8 *kmirr;
runlist_element *rl;
unsigned int block_start, block_end, m_start, m_end, page_ofs;
int i_bhs, nr_bhs, err = 0;
unsigned char blocksize_bits = vol->sb->s_blocksize_bits;
ntfs_debug("Entering for inode 0x%lx.", mft_no);
BUG_ON(!max_bhs);
if (unlikely(!vol->mftmirr_ino)) {
/* This could happen during umount... */
err = ntfs_sync_mft_mirror_umount(vol, mft_no, m);
if (likely(!err))
return err;
goto err_out;
}
/* Get the page containing the mirror copy of the mft record @m. */
page = ntfs_map_page(vol->mftmirr_ino->i_mapping, mft_no >>
(PAGE_CACHE_SHIFT - vol->mft_record_size_bits));
if (IS_ERR(page)) {
ntfs_error(vol->sb, "Failed to map mft mirror page.");
err = PTR_ERR(page);
goto err_out;
}
lock_page(page);
BUG_ON(!PageUptodate(page));
ClearPageUptodate(page);
/* Offset of the mft mirror record inside the page. */
page_ofs = (mft_no << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
/* The address in the page of the mirror copy of the mft record @m. */
kmirr = page_address(page) + page_ofs;
/* Copy the mst protected mft record to the mirror. */
memcpy(kmirr, m, vol->mft_record_size);
/* Create uptodate buffers if not present. */
if (unlikely(!page_has_buffers(page))) {
struct buffer_head *tail;
bh = head = alloc_page_buffers(page, blocksize, 1);
do {
set_buffer_uptodate(bh);
tail = bh;
bh = bh->b_this_page;
} while (bh);
tail->b_this_page = head;
attach_page_buffers(page, head);
}
bh = head = page_buffers(page);
BUG_ON(!bh);
rl = NULL;
nr_bhs = 0;
block_start = 0;
m_start = kmirr - (u8*)page_address(page);
m_end = m_start + vol->mft_record_size;
do {
block_end = block_start + blocksize;
/* If the buffer is outside the mft record, skip it. */
if (block_end <= m_start)
continue;
if (unlikely(block_start >= m_end))
break;
/* Need to map the buffer if it is not mapped already. */
if (unlikely(!buffer_mapped(bh))) {
VCN vcn;
LCN lcn;
unsigned int vcn_ofs;
bh->b_bdev = vol->sb->s_bdev;
/* Obtain the vcn and offset of the current block. */
vcn = ((VCN)mft_no << vol->mft_record_size_bits) +
(block_start - m_start);
vcn_ofs = vcn & vol->cluster_size_mask;
vcn >>= vol->cluster_size_bits;
if (!rl) {
down_read(&NTFS_I(vol->mftmirr_ino)->
runlist.lock);
rl = NTFS_I(vol->mftmirr_ino)->runlist.rl;
/*
* $MFTMirr always has the whole of its runlist
* in memory.
*/
BUG_ON(!rl);
}
/* Seek to element containing target vcn. */
while (rl->length && rl[1].vcn <= vcn)
rl++;
lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
/* For $MFTMirr, only lcn >= 0 is a successful remap. */
if (likely(lcn >= 0)) {
/* Setup buffer head to correct block. */
bh->b_blocknr = ((lcn <<
vol->cluster_size_bits) +
vcn_ofs) >> blocksize_bits;
set_buffer_mapped(bh);
} else {
bh->b_blocknr = -1;
ntfs_error(vol->sb, "Cannot write mft mirror "
"record 0x%lx because its "
"location on disk could not "
"be determined (error code "
"%lli).", mft_no,
(long long)lcn);
err = -EIO;
}
}
BUG_ON(!buffer_uptodate(bh));
BUG_ON(!nr_bhs && (m_start != block_start));
BUG_ON(nr_bhs >= max_bhs);
bhs[nr_bhs++] = bh;
BUG_ON((nr_bhs >= max_bhs) && (m_end != block_end));
} while (block_start = block_end, (bh = bh->b_this_page) != head);
if (unlikely(rl))
up_read(&NTFS_I(vol->mftmirr_ino)->runlist.lock);
if (likely(!err)) {
/* Lock buffers and start synchronous write i/o on them. */
for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
struct buffer_head *tbh = bhs[i_bhs];
if (!trylock_buffer(tbh))
BUG();
BUG_ON(!buffer_uptodate(tbh));
clear_buffer_dirty(tbh);
get_bh(tbh);
tbh->b_end_io = end_buffer_write_sync;
submit_bh(WRITE, tbh);
}
/* Wait on i/o completion of buffers. */
for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
struct buffer_head *tbh = bhs[i_bhs];
wait_on_buffer(tbh);
if (unlikely(!buffer_uptodate(tbh))) {
err = -EIO;
/*
* Set the buffer uptodate so the page and
* buffer states do not become out of sync.
*/
set_buffer_uptodate(tbh);
}
}
} else /* if (unlikely(err)) */ {
/* Clean the buffers. */
for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++)
clear_buffer_dirty(bhs[i_bhs]);
}
/* Current state: all buffers are clean, unlocked, and uptodate. */
/* Remove the mst protection fixups again. */
post_write_mst_fixup((NTFS_RECORD*)kmirr);
flush_dcache_page(page);
SetPageUptodate(page);
unlock_page(page);
ntfs_unmap_page(page);
if (likely(!err)) {
ntfs_debug("Done.");
} else {
ntfs_error(vol->sb, "I/O error while writing mft mirror "
"record 0x%lx!", mft_no);
err_out:
ntfs_error(vol->sb, "Failed to synchronize $MFTMirr (error "
"code %i). Volume will be left marked dirty "
"on umount. Run ntfsfix on the partition "
"after umounting to correct this.", -err);
NVolSetErrors(vol);
}
return err;
}
/**
* write_mft_record_nolock - write out a mapped (extent) mft record
* @ni: ntfs inode describing the mapped (extent) mft record
* @m: mapped (extent) mft record to write
* @sync: if true, wait for i/o completion
*
* Write the mapped (extent) mft record @m described by the (regular or extent)
* ntfs inode @ni to backing store. If the mft record @m has a counterpart in
* the mft mirror, that is also updated.
*
* We only write the mft record if the ntfs inode @ni is dirty and the first
* buffer belonging to its mft record is dirty, too. We ignore the dirty state
* of subsequent buffers because we could have raced with
* fs/ntfs/aops.c::mark_ntfs_record_dirty().
*
* On success, clean the mft record and return 0. On error, leave the mft
* record dirty and return -errno.
*
* NOTE: We always perform synchronous i/o and ignore the @sync parameter.
* However, if the mft record has a counterpart in the mft mirror and @sync is
* true, we write the mft record, wait for i/o completion, and only then write
* the mft mirror copy. This ensures that if the system crashes either the mft
* or the mft mirror will contain a self-consistent mft record @m. If @sync is
* false on the other hand, we start i/o on both and then wait for completion
* on them. This provides a speedup but no longer guarantees that you will end
* up with a self-consistent mft record in the case of a crash but if you asked
* for asynchronous writing you probably do not care about that anyway.
*
* TODO: If @sync is false, want to do truly asynchronous i/o, i.e. just
* schedule i/o via ->writepage or do it via kntfsd or whatever.
*/
int write_mft_record_nolock(ntfs_inode *ni, MFT_RECORD *m, int sync)
{
ntfs_volume *vol = ni->vol;
struct page *page = ni->page;
unsigned int blocksize = vol->sb->s_blocksize;
unsigned char blocksize_bits = vol->sb->s_blocksize_bits;
int max_bhs = vol->mft_record_size / blocksize;
struct buffer_head *bhs[max_bhs];
struct buffer_head *bh, *head;
runlist_element *rl;
unsigned int block_start, block_end, m_start, m_end;
int i_bhs, nr_bhs, err = 0;
ntfs_debug("Entering for inode 0x%lx.", ni->mft_no);
BUG_ON(NInoAttr(ni));
BUG_ON(!max_bhs);
BUG_ON(!PageLocked(page));
/*
* If the ntfs_inode is clean no need to do anything. If it is dirty,
* mark it as clean now so that it can be redirtied later on if needed.
* There is no danger of races since the caller is holding the locks
* for the mft record @m and the page it is in.
*/
if (!NInoTestClearDirty(ni))
goto done;
bh = head = page_buffers(page);
BUG_ON(!bh);
rl = NULL;
nr_bhs = 0;
block_start = 0;
m_start = ni->page_ofs;
m_end = m_start + vol->mft_record_size;
do {
block_end = block_start + blocksize;
/* If the buffer is outside the mft record, skip it. */
if (block_end <= m_start)
continue;
if (unlikely(block_start >= m_end))
break;
/*
* If this block is not the first one in the record, we ignore
* the buffer's dirty state because we could have raced with a
* parallel mark_ntfs_record_dirty().
*/
if (block_start == m_start) {
/* This block is the first one in the record. */
if (!buffer_dirty(bh)) {
BUG_ON(nr_bhs);
/* Clean records are not written out. */
break;
}
}
/* Need to map the buffer if it is not mapped already. */
if (unlikely(!buffer_mapped(bh))) {
VCN vcn;
LCN lcn;
unsigned int vcn_ofs;
bh->b_bdev = vol->sb->s_bdev;
/* Obtain the vcn and offset of the current block. */
vcn = ((VCN)ni->mft_no << vol->mft_record_size_bits) +
(block_start - m_start);
vcn_ofs = vcn & vol->cluster_size_mask;
vcn >>= vol->cluster_size_bits;
if (!rl) {
down_read(&NTFS_I(vol->mft_ino)->runlist.lock);
rl = NTFS_I(vol->mft_ino)->runlist.rl;
BUG_ON(!rl);
}
/* Seek to element containing target vcn. */
while (rl->length && rl[1].vcn <= vcn)
rl++;
lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
/* For $MFT, only lcn >= 0 is a successful remap. */
if (likely(lcn >= 0)) {
/* Setup buffer head to correct block. */
bh->b_blocknr = ((lcn <<
vol->cluster_size_bits) +
vcn_ofs) >> blocksize_bits;
set_buffer_mapped(bh);
} else {
bh->b_blocknr = -1;
ntfs_error(vol->sb, "Cannot write mft record "
"0x%lx because its location "
"on disk could not be "
"determined (error code %lli).",
ni->mft_no, (long long)lcn);
err = -EIO;
}
}
BUG_ON(!buffer_uptodate(bh));
BUG_ON(!nr_bhs && (m_start != block_start));
BUG_ON(nr_bhs >= max_bhs);
bhs[nr_bhs++] = bh;
BUG_ON((nr_bhs >= max_bhs) && (m_end != block_end));
} while (block_start = block_end, (bh = bh->b_this_page) != head);
if (unlikely(rl))
up_read(&NTFS_I(vol->mft_ino)->runlist.lock);
if (!nr_bhs)
goto done;
if (unlikely(err))
goto cleanup_out;
/* Apply the mst protection fixups. */
err = pre_write_mst_fixup((NTFS_RECORD*)m, vol->mft_record_size);
if (err) {
ntfs_error(vol->sb, "Failed to apply mst fixups!");
goto cleanup_out;
}
flush_dcache_mft_record_page(ni);
/* Lock buffers and start synchronous write i/o on them. */
for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
struct buffer_head *tbh = bhs[i_bhs];
if (!trylock_buffer(tbh))
BUG();
BUG_ON(!buffer_uptodate(tbh));
clear_buffer_dirty(tbh);
get_bh(tbh);
tbh->b_end_io = end_buffer_write_sync;
submit_bh(WRITE, tbh);
}
/* Synchronize the mft mirror now if not @sync. */
if (!sync && ni->mft_no < vol->mftmirr_size)
ntfs_sync_mft_mirror(vol, ni->mft_no, m, sync);
/* Wait on i/o completion of buffers. */
for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++) {
struct buffer_head *tbh = bhs[i_bhs];
wait_on_buffer(tbh);
if (unlikely(!buffer_uptodate(tbh))) {
err = -EIO;
/*
* Set the buffer uptodate so the page and buffer
* states do not become out of sync.
*/
if (PageUptodate(page))
set_buffer_uptodate(tbh);
}
}
/* If @sync, now synchronize the mft mirror. */
if (sync && ni->mft_no < vol->mftmirr_size)
ntfs_sync_mft_mirror(vol, ni->mft_no, m, sync);
/* Remove the mst protection fixups again. */
post_write_mst_fixup((NTFS_RECORD*)m);
flush_dcache_mft_record_page(ni);
if (unlikely(err)) {
/* I/O error during writing. This is really bad! */
ntfs_error(vol->sb, "I/O error while writing mft record "
"0x%lx! Marking base inode as bad. You "
"should unmount the volume and run chkdsk.",
ni->mft_no);
goto err_out;
}
done:
ntfs_debug("Done.");
return 0;
cleanup_out:
/* Clean the buffers. */
for (i_bhs = 0; i_bhs < nr_bhs; i_bhs++)
clear_buffer_dirty(bhs[i_bhs]);
err_out:
/*
* Current state: all buffers are clean, unlocked, and uptodate.
* The caller should mark the base inode as bad so that no more i/o
* happens. ->clear_inode() will still be invoked so all extent inodes
* and other allocated memory will be freed.
*/
if (err == -ENOMEM) {
ntfs_error(vol->sb, "Not enough memory to write mft record. "
"Redirtying so the write is retried later.");
mark_mft_record_dirty(ni);
err = 0;
} else
NVolSetErrors(vol);
return err;
}
/**
* ntfs_may_write_mft_record - check if an mft record may be written out
* @vol: [IN] ntfs volume on which the mft record to check resides
* @mft_no: [IN] mft record number of the mft record to check
* @m: [IN] mapped mft record to check
* @locked_ni: [OUT] caller has to unlock this ntfs inode if one is returned
*
* Check if the mapped (base or extent) mft record @m with mft record number
* @mft_no belonging to the ntfs volume @vol may be written out. If necessary
* and possible the ntfs inode of the mft record is locked and the base vfs
* inode is pinned. The locked ntfs inode is then returned in @locked_ni. The
* caller is responsible for unlocking the ntfs inode and unpinning the base
* vfs inode.
*
* Return 'true' if the mft record may be written out and 'false' if not.
*
* The caller has locked the page and cleared the uptodate flag on it which
* means that we can safely write out any dirty mft records that do not have
* their inodes in icache as determined by ilookup5() as anyone
* opening/creating such an inode would block when attempting to map the mft
* record in read_cache_page() until we are finished with the write out.
*
* Here is a description of the tests we perform:
*
* If the inode is found in icache we know the mft record must be a base mft
* record. If it is dirty, we do not write it and return 'false' as the vfs
* inode write paths will result in the access times being updated which would
* cause the base mft record to be redirtied and written out again. (We know
* the access time update will modify the base mft record because Windows
* chkdsk complains if the standard information attribute is not in the base
* mft record.)
*
* If the inode is in icache and not dirty, we attempt to lock the mft record
* and if we find the lock was already taken, it is not safe to write the mft
* record and we return 'false'.
*
* If we manage to obtain the lock we have exclusive access to the mft record,
* which also allows us safe writeout of the mft record. We then set
* @locked_ni to the locked ntfs inode and return 'true'.
*
* Note we cannot just lock the mft record and sleep while waiting for the lock
* because this would deadlock due to lock reversal (normally the mft record is
* locked before the page is locked but we already have the page locked here
* when we try to lock the mft record).
*
* If the inode is not in icache we need to perform further checks.
*
* If the mft record is not a FILE record or it is a base mft record, we can
* safely write it and return 'true'.
*
* We now know the mft record is an extent mft record. We check if the inode
* corresponding to its base mft record is in icache and obtain a reference to
* it if it is. If it is not, we can safely write it and return 'true'.
*
* We now have the base inode for the extent mft record. We check if it has an
* ntfs inode for the extent mft record attached and if not it is safe to write
* the extent mft record and we return 'true'.
*
* The ntfs inode for the extent mft record is attached to the base inode so we
* attempt to lock the extent mft record and if we find the lock was already
* taken, it is not safe to write the extent mft record and we return 'false'.
*
* If we manage to obtain the lock we have exclusive access to the extent mft
* record, which also allows us safe writeout of the extent mft record. We
* set the ntfs inode of the extent mft record clean and then set @locked_ni to
* the now locked ntfs inode and return 'true'.
*
* Note, the reason for actually writing dirty mft records here and not just
* relying on the vfs inode dirty code paths is that we can have mft records
* modified without them ever having actual inodes in memory. Also we can have
* dirty mft records with clean ntfs inodes in memory. None of the described
* cases would result in the dirty mft records being written out if we only
* relied on the vfs inode dirty code paths. And these cases can really occur
* during allocation of new mft records and in particular when the
* initialized_size of the $MFT/$DATA attribute is extended and the new space
* is initialized using ntfs_mft_record_format(). The clean inode can then
* appear if the mft record is reused for a new inode before it got written
* out.
*/
bool ntfs_may_write_mft_record(ntfs_volume *vol, const unsigned long mft_no,
const MFT_RECORD *m, ntfs_inode **locked_ni)
{
struct super_block *sb = vol->sb;
struct inode *mft_vi = vol->mft_ino;
struct inode *vi;
ntfs_inode *ni, *eni, **extent_nis;
int i;
ntfs_attr na;
ntfs_debug("Entering for inode 0x%lx.", mft_no);
/*
* Normally we do not return a locked inode so set @locked_ni to NULL.
*/
BUG_ON(!locked_ni);
*locked_ni = NULL;
/*
* Check if the inode corresponding to this mft record is in the VFS
* inode cache and obtain a reference to it if it is.
*/
ntfs_debug("Looking for inode 0x%lx in icache.", mft_no);
na.mft_no = mft_no;
na.name = NULL;
na.name_len = 0;
na.type = AT_UNUSED;
/*
* Optimize inode 0, i.e. $MFT itself, since we have it in memory and
* we get here for it rather often.
*/
if (!mft_no) {
/* Balance the below iput(). */
vi = igrab(mft_vi);
BUG_ON(vi != mft_vi);
} else {
/*
* Have to use ilookup5_nowait() since ilookup5() waits for the
* inode lock which causes ntfs to deadlock when a concurrent
* inode write via the inode dirty code paths and the page
* dirty code path of the inode dirty code path when writing
* $MFT occurs.
*/
vi = ilookup5_nowait(sb, mft_no, (test_t)ntfs_test_inode, &na);
}
if (vi) {
ntfs_debug("Base inode 0x%lx is in icache.", mft_no);
/* The inode is in icache. */
ni = NTFS_I(vi);
/* Take a reference to the ntfs inode. */
atomic_inc(&ni->count);
/* If the inode is dirty, do not write this record. */
if (NInoDirty(ni)) {
ntfs_debug("Inode 0x%lx is dirty, do not write it.",
mft_no);
atomic_dec(&ni->count);
iput(vi);
return false;
}
ntfs_debug("Inode 0x%lx is not dirty.", mft_no);
/* The inode is not dirty, try to take the mft record lock. */
if (unlikely(!mutex_trylock(&ni->mrec_lock))) {
ntfs_debug("Mft record 0x%lx is already locked, do "
"not write it.", mft_no);
atomic_dec(&ni->count);
iput(vi);
return false;
}
ntfs_debug("Managed to lock mft record 0x%lx, write it.",
mft_no);
/*
* The write has to occur while we hold the mft record lock so
* return the locked ntfs inode.
*/
*locked_ni = ni;
return true;
}
ntfs_debug("Inode 0x%lx is not in icache.", mft_no);
/* The inode is not in icache. */
/* Write the record if it is not a mft record (type "FILE"). */
if (!ntfs_is_mft_record(m->magic)) {
ntfs_debug("Mft record 0x%lx is not a FILE record, write it.",
mft_no);
return true;
}
/* Write the mft record if it is a base inode. */
if (!m->base_mft_record) {
ntfs_debug("Mft record 0x%lx is a base record, write it.",
mft_no);
return true;
}
/*
* This is an extent mft record. Check if the inode corresponding to
* its base mft record is in icache and obtain a reference to it if it
* is.
*/
na.mft_no = MREF_LE(m->base_mft_record);
ntfs_debug("Mft record 0x%lx is an extent record. Looking for base "
"inode 0x%lx in icache.", mft_no, na.mft_no);
if (!na.mft_no) {
/* Balance the below iput(). */
vi = igrab(mft_vi);
BUG_ON(vi != mft_vi);
} else
vi = ilookup5_nowait(sb, na.mft_no, (test_t)ntfs_test_inode,
&na);
if (!vi) {
/*
* The base inode is not in icache, write this extent mft
* record.
*/
ntfs_debug("Base inode 0x%lx is not in icache, write the "
"extent record.", na.mft_no);
return true;
}
ntfs_debug("Base inode 0x%lx is in icache.", na.mft_no);
/*
* The base inode is in icache. Check if it has the extent inode
* corresponding to this extent mft record attached.
*/
ni = NTFS_I(vi);
mutex_lock(&ni->extent_lock);
if (ni->nr_extents <= 0) {
/*
* The base inode has no attached extent inodes, write this
* extent mft record.
*/
mutex_unlock(&ni->extent_lock);
iput(vi);
ntfs_debug("Base inode 0x%lx has no attached extent inodes, "
"write the extent record.", na.mft_no);
return true;
}
/* Iterate over the attached extent inodes. */
extent_nis = ni->ext.extent_ntfs_inos;
for (eni = NULL, i = 0; i < ni->nr_extents; ++i) {
if (mft_no == extent_nis[i]->mft_no) {
/*
* Found the extent inode corresponding to this extent
* mft record.
*/
eni = extent_nis[i];
break;
}
}
/*
* If the extent inode was not attached to the base inode, write this
* extent mft record.
*/
if (!eni) {
mutex_unlock(&ni->extent_lock);
iput(vi);
ntfs_debug("Extent inode 0x%lx is not attached to its base "
"inode 0x%lx, write the extent record.",
mft_no, na.mft_no);
return true;
}
ntfs_debug("Extent inode 0x%lx is attached to its base inode 0x%lx.",
mft_no, na.mft_no);
/* Take a reference to the extent ntfs inode. */
atomic_inc(&eni->count);
mutex_unlock(&ni->extent_lock);
/*
* Found the extent inode coresponding to this extent mft record.
* Try to take the mft record lock.
*/
if (unlikely(!mutex_trylock(&eni->mrec_lock))) {
atomic_dec(&eni->count);
iput(vi);
ntfs_debug("Extent mft record 0x%lx is already locked, do "
"not write it.", mft_no);
return false;
}
ntfs_debug("Managed to lock extent mft record 0x%lx, write it.",
mft_no);
if (NInoTestClearDirty(eni))
ntfs_debug("Extent inode 0x%lx is dirty, marking it clean.",
mft_no);
/*
* The write has to occur while we hold the mft record lock so return
* the locked extent ntfs inode.
*/
*locked_ni = eni;
return true;
}
static const char *es = " Leaving inconsistent metadata. Unmount and run "
"chkdsk.";
/**
* ntfs_mft_bitmap_find_and_alloc_free_rec_nolock - see name
* @vol: volume on which to search for a free mft record
* @base_ni: open base inode if allocating an extent mft record or NULL
*
* Search for a free mft record in the mft bitmap attribute on the ntfs volume
* @vol.
*
* If @base_ni is NULL start the search at the default allocator position.
*
* If @base_ni is not NULL start the search at the mft record after the base
* mft record @base_ni.
*
* Return the free mft record on success and -errno on error. An error code of
* -ENOSPC means that there are no free mft records in the currently
* initialized mft bitmap.
*
* Locking: Caller must hold vol->mftbmp_lock for writing.
*/
static int ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(ntfs_volume *vol,
ntfs_inode *base_ni)
{
s64 pass_end, ll, data_pos, pass_start, ofs, bit;
unsigned long flags;
struct address_space *mftbmp_mapping;
u8 *buf, *byte;
struct page *page;
unsigned int page_ofs, size;
u8 pass, b;
ntfs_debug("Searching for free mft record in the currently "
"initialized mft bitmap.");
mftbmp_mapping = vol->mftbmp_ino->i_mapping;
/*
* Set the end of the pass making sure we do not overflow the mft
* bitmap.
*/
read_lock_irqsave(&NTFS_I(vol->mft_ino)->size_lock, flags);
pass_end = NTFS_I(vol->mft_ino)->allocated_size >>
vol->mft_record_size_bits;
read_unlock_irqrestore(&NTFS_I(vol->mft_ino)->size_lock, flags);
read_lock_irqsave(&NTFS_I(vol->mftbmp_ino)->size_lock, flags);
ll = NTFS_I(vol->mftbmp_ino)->initialized_size << 3;
read_unlock_irqrestore(&NTFS_I(vol->mftbmp_ino)->size_lock, flags);
if (pass_end > ll)
pass_end = ll;
pass = 1;
if (!base_ni)
data_pos = vol->mft_data_pos;
else
data_pos = base_ni->mft_no + 1;
if (data_pos < 24)
data_pos = 24;
if (data_pos >= pass_end) {
data_pos = 24;
pass = 2;
/* This happens on a freshly formatted volume. */
if (data_pos >= pass_end)
return -ENOSPC;
}
pass_start = data_pos;
ntfs_debug("Starting bitmap search: pass %u, pass_start 0x%llx, "
"pass_end 0x%llx, data_pos 0x%llx.", pass,
(long long)pass_start, (long long)pass_end,
(long long)data_pos);
/* Loop until a free mft record is found. */
for (; pass <= 2;) {
/* Cap size to pass_end. */
ofs = data_pos >> 3;
page_ofs = ofs & ~PAGE_CACHE_MASK;
size = PAGE_CACHE_SIZE - page_ofs;
ll = ((pass_end + 7) >> 3) - ofs;
if (size > ll)
size = ll;
size <<= 3;
/*
* If we are still within the active pass, search the next page
* for a zero bit.
*/
if (size) {
page = ntfs_map_page(mftbmp_mapping,
ofs >> PAGE_CACHE_SHIFT);
if (IS_ERR(page)) {
ntfs_error(vol->sb, "Failed to read mft "
"bitmap, aborting.");
return PTR_ERR(page);
}
buf = (u8*)page_address(page) + page_ofs;
bit = data_pos & 7;
data_pos &= ~7ull;
ntfs_debug("Before inner for loop: size 0x%x, "
"data_pos 0x%llx, bit 0x%llx", size,
(long long)data_pos, (long long)bit);
for (; bit < size && data_pos + bit < pass_end;
bit &= ~7ull, bit += 8) {
byte = buf + (bit >> 3);
if (*byte == 0xff)
continue;
b = ffz((unsigned long)*byte);
if (b < 8 && b >= (bit & 7)) {
ll = data_pos + (bit & ~7ull) + b;
if (unlikely(ll > (1ll << 32))) {
ntfs_unmap_page(page);
return -ENOSPC;
}
*byte |= 1 << b;
flush_dcache_page(page);
set_page_dirty(page);
ntfs_unmap_page(page);
ntfs_debug("Done. (Found and "
"allocated mft record "
"0x%llx.)",
(long long)ll);
return ll;
}
}
ntfs_debug("After inner for loop: size 0x%x, "
"data_pos 0x%llx, bit 0x%llx", size,
(long long)data_pos, (long long)bit);
data_pos += size;
ntfs_unmap_page(page);
/*
* If the end of the pass has not been reached yet,
* continue searching the mft bitmap for a zero bit.
*/
if (data_pos < pass_end)
continue;
}
/* Do the next pass. */
if (++pass == 2) {
/*
* Starting the second pass, in which we scan the first
* part of the zone which we omitted earlier.
*/
pass_end = pass_start;
data_pos = pass_start = 24;
ntfs_debug("pass %i, pass_start 0x%llx, pass_end "
"0x%llx.", pass, (long long)pass_start,
(long long)pass_end);
if (data_pos >= pass_end)
break;
}
}
/* No free mft records in currently initialized mft bitmap. */
ntfs_debug("Done. (No free mft records left in currently initialized "
"mft bitmap.)");
return -ENOSPC;
}
/**
* ntfs_mft_bitmap_extend_allocation_nolock - extend mft bitmap by a cluster
* @vol: volume on which to extend the mft bitmap attribute
*
* Extend the mft bitmap attribute on the ntfs volume @vol by one cluster.
*
* Note: Only changes allocated_size, i.e. does not touch initialized_size or
* data_size.
*
* Return 0 on success and -errno on error.
*
* Locking: - Caller must hold vol->mftbmp_lock for writing.
* - This function takes NTFS_I(vol->mftbmp_ino)->runlist.lock for
* writing and releases it before returning.
* - This function takes vol->lcnbmp_lock for writing and releases it
* before returning.
*/
static int ntfs_mft_bitmap_extend_allocation_nolock(ntfs_volume *vol)
{
LCN lcn;
s64 ll;
unsigned long flags;
struct page *page;
ntfs_inode *mft_ni, *mftbmp_ni;
runlist_element *rl, *rl2 = NULL;
ntfs_attr_search_ctx *ctx = NULL;
MFT_RECORD *mrec;
ATTR_RECORD *a = NULL;
int ret, mp_size;
u32 old_alen = 0;
u8 *b, tb;
struct {
u8 added_cluster:1;
u8 added_run:1;
u8 mp_rebuilt:1;
} status = { 0, 0, 0 };
ntfs_debug("Extending mft bitmap allocation.");
mft_ni = NTFS_I(vol->mft_ino);
mftbmp_ni = NTFS_I(vol->mftbmp_ino);
/*
* Determine the last lcn of the mft bitmap. The allocated size of the
* mft bitmap cannot be zero so we are ok to do this.
*/
down_write(&mftbmp_ni->runlist.lock);
read_lock_irqsave(&mftbmp_ni->size_lock, flags);
ll = mftbmp_ni->allocated_size;
read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
rl = ntfs_attr_find_vcn_nolock(mftbmp_ni,
(ll - 1) >> vol->cluster_size_bits, NULL);
if (unlikely(IS_ERR(rl) || !rl->length || rl->lcn < 0)) {
up_write(&mftbmp_ni->runlist.lock);
ntfs_error(vol->sb, "Failed to determine last allocated "
"cluster of mft bitmap attribute.");
if (!IS_ERR(rl))
ret = -EIO;
else
ret = PTR_ERR(rl);
return ret;
}
lcn = rl->lcn + rl->length;
ntfs_debug("Last lcn of mft bitmap attribute is 0x%llx.",
(long long)lcn);
/*
* Attempt to get the cluster following the last allocated cluster by
* hand as it may be in the MFT zone so the allocator would not give it
* to us.
*/
ll = lcn >> 3;
page = ntfs_map_page(vol->lcnbmp_ino->i_mapping,
ll >> PAGE_CACHE_SHIFT);
if (IS_ERR(page)) {
up_write(&mftbmp_ni->runlist.lock);
ntfs_error(vol->sb, "Failed to read from lcn bitmap.");
return PTR_ERR(page);
}
b = (u8*)page_address(page) + (ll & ~PAGE_CACHE_MASK);
tb = 1 << (lcn & 7ull);
down_write(&vol->lcnbmp_lock);
if (*b != 0xff && !(*b & tb)) {
/* Next cluster is free, allocate it. */
*b |= tb;
flush_dcache_page(page);
set_page_dirty(page);
up_write(&vol->lcnbmp_lock);
ntfs_unmap_page(page);
/* Update the mft bitmap runlist. */
rl->length++;
rl[1].vcn++;
status.added_cluster = 1;
ntfs_debug("Appending one cluster to mft bitmap.");
} else {
up_write(&vol->lcnbmp_lock);
ntfs_unmap_page(page);
/* Allocate a cluster from the DATA_ZONE. */
rl2 = ntfs_cluster_alloc(vol, rl[1].vcn, 1, lcn, DATA_ZONE,
true);
if (IS_ERR(rl2)) {
up_write(&mftbmp_ni->runlist.lock);
ntfs_error(vol->sb, "Failed to allocate a cluster for "
"the mft bitmap.");
return PTR_ERR(rl2);
}
rl = ntfs_runlists_merge(mftbmp_ni->runlist.rl, rl2);
if (IS_ERR(rl)) {
up_write(&mftbmp_ni->runlist.lock);
ntfs_error(vol->sb, "Failed to merge runlists for mft "
"bitmap.");
if (ntfs_cluster_free_from_rl(vol, rl2)) {
ntfs_error(vol->sb, "Failed to deallocate "
"allocated cluster.%s", es);
NVolSetErrors(vol);
}
ntfs_free(rl2);
return PTR_ERR(rl);
}
mftbmp_ni->runlist.rl = rl;
status.added_run = 1;
ntfs_debug("Adding one run to mft bitmap.");
/* Find the last run in the new runlist. */
for (; rl[1].length; rl++)
;
}
/*
* Update the attribute record as well. Note: @rl is the last
* (non-terminator) runlist element of mft bitmap.
*/
mrec = map_mft_record(mft_ni);
if (IS_ERR(mrec)) {
ntfs_error(vol->sb, "Failed to map mft record.");
ret = PTR_ERR(mrec);
goto undo_alloc;
}
ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
if (unlikely(!ctx)) {
ntfs_error(vol->sb, "Failed to get search context.");
ret = -ENOMEM;
goto undo_alloc;
}
ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
mftbmp_ni->name_len, CASE_SENSITIVE, rl[1].vcn, NULL,
0, ctx);
if (unlikely(ret)) {
ntfs_error(vol->sb, "Failed to find last attribute extent of "
"mft bitmap attribute.");
if (ret == -ENOENT)
ret = -EIO;
goto undo_alloc;
}
a = ctx->attr;
ll = sle64_to_cpu(a->data.non_resident.lowest_vcn);
/* Search back for the previous last allocated cluster of mft bitmap. */
for (rl2 = rl; rl2 > mftbmp_ni->runlist.rl; rl2--) {
if (ll >= rl2->vcn)
break;
}
BUG_ON(ll < rl2->vcn);
BUG_ON(ll >= rl2->vcn + rl2->length);
/* Get the size for the new mapping pairs array for this extent. */
mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, -1);
if (unlikely(mp_size <= 0)) {
ntfs_error(vol->sb, "Get size for mapping pairs failed for "
"mft bitmap attribute extent.");
ret = mp_size;
if (!ret)
ret = -EIO;
goto undo_alloc;
}
/* Expand the attribute record if necessary. */
old_alen = le32_to_cpu(a->length);
ret = ntfs_attr_record_resize(ctx->mrec, a, mp_size +
le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
if (unlikely(ret)) {
if (ret != -ENOSPC) {
ntfs_error(vol->sb, "Failed to resize attribute "
"record for mft bitmap attribute.");
goto undo_alloc;
}
// TODO: Deal with this by moving this extent to a new mft
// record or by starting a new extent in a new mft record or by
// moving other attributes out of this mft record.
// Note: It will need to be a special mft record and if none of
// those are available it gets rather complicated...
ntfs_error(vol->sb, "Not enough space in this mft record to "
"accommodate extended mft bitmap attribute "
"extent. Cannot handle this yet.");
ret = -EOPNOTSUPP;
goto undo_alloc;
}
status.mp_rebuilt = 1;
/* Generate the mapping pairs array directly into the attr record. */
ret = ntfs_mapping_pairs_build(vol, (u8*)a +
le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
mp_size, rl2, ll, -1, NULL);
if (unlikely(ret)) {
ntfs_error(vol->sb, "Failed to build mapping pairs array for "
"mft bitmap attribute.");
goto undo_alloc;
}
/* Update the highest_vcn. */
a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
/*
* We now have extended the mft bitmap allocated_size by one cluster.
* Reflect this in the ntfs_inode structure and the attribute record.
*/
if (a->data.non_resident.lowest_vcn) {
/*
* We are not in the first attribute extent, switch to it, but
* first ensure the changes will make it to disk later.
*/
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
ntfs_attr_reinit_search_ctx(ctx);
ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL,
0, ctx);
if (unlikely(ret)) {
ntfs_error(vol->sb, "Failed to find first attribute "
"extent of mft bitmap attribute.");
goto restore_undo_alloc;
}
a = ctx->attr;
}
write_lock_irqsave(&mftbmp_ni->size_lock, flags);
mftbmp_ni->allocated_size += vol->cluster_size;
a->data.non_resident.allocated_size =
cpu_to_sle64(mftbmp_ni->allocated_size);
write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
/* Ensure the changes make it to disk. */
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(mft_ni);
up_write(&mftbmp_ni->runlist.lock);
ntfs_debug("Done.");
return 0;
restore_undo_alloc:
ntfs_attr_reinit_search_ctx(ctx);
if (ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
mftbmp_ni->name_len, CASE_SENSITIVE, rl[1].vcn, NULL,
0, ctx)) {
ntfs_error(vol->sb, "Failed to find last attribute extent of "
"mft bitmap attribute.%s", es);
write_lock_irqsave(&mftbmp_ni->size_lock, flags);
mftbmp_ni->allocated_size += vol->cluster_size;
write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(mft_ni);
up_write(&mftbmp_ni->runlist.lock);
/*
* The only thing that is now wrong is ->allocated_size of the
* base attribute extent which chkdsk should be able to fix.
*/
NVolSetErrors(vol);
return ret;
}
a = ctx->attr;
a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 2);
undo_alloc:
if (status.added_cluster) {
/* Truncate the last run in the runlist by one cluster. */
rl->length--;
rl[1].vcn--;
} else if (status.added_run) {
lcn = rl->lcn;
/* Remove the last run from the runlist. */
rl->lcn = rl[1].lcn;
rl->length = 0;
}
/* Deallocate the cluster. */
down_write(&vol->lcnbmp_lock);
if (ntfs_bitmap_clear_bit(vol->lcnbmp_ino, lcn)) {
ntfs_error(vol->sb, "Failed to free allocated cluster.%s", es);
NVolSetErrors(vol);
}
up_write(&vol->lcnbmp_lock);
if (status.mp_rebuilt) {
if (ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
a->data.non_resident.mapping_pairs_offset),
old_alen - le16_to_cpu(
a->data.non_resident.mapping_pairs_offset),
rl2, ll, -1, NULL)) {
ntfs_error(vol->sb, "Failed to restore mapping pairs "
"array.%s", es);
NVolSetErrors(vol);
}
if (ntfs_attr_record_resize(ctx->mrec, a, old_alen)) {
ntfs_error(vol->sb, "Failed to restore attribute "
"record.%s", es);
NVolSetErrors(vol);
}
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
}
if (ctx)
ntfs_attr_put_search_ctx(ctx);
if (!IS_ERR(mrec))
unmap_mft_record(mft_ni);
up_write(&mftbmp_ni->runlist.lock);
return ret;
}
/**
* ntfs_mft_bitmap_extend_initialized_nolock - extend mftbmp initialized data
* @vol: volume on which to extend the mft bitmap attribute
*
* Extend the initialized portion of the mft bitmap attribute on the ntfs
* volume @vol by 8 bytes.
*
* Note: Only changes initialized_size and data_size, i.e. requires that
* allocated_size is big enough to fit the new initialized_size.
*
* Return 0 on success and -error on error.
*
* Locking: Caller must hold vol->mftbmp_lock for writing.
*/
static int ntfs_mft_bitmap_extend_initialized_nolock(ntfs_volume *vol)
{
s64 old_data_size, old_initialized_size;
unsigned long flags;
struct inode *mftbmp_vi;
ntfs_inode *mft_ni, *mftbmp_ni;
ntfs_attr_search_ctx *ctx;
MFT_RECORD *mrec;
ATTR_RECORD *a;
int ret;
ntfs_debug("Extending mft bitmap initiailized (and data) size.");
mft_ni = NTFS_I(vol->mft_ino);
mftbmp_vi = vol->mftbmp_ino;
mftbmp_ni = NTFS_I(mftbmp_vi);
/* Get the attribute record. */
mrec = map_mft_record(mft_ni);
if (IS_ERR(mrec)) {
ntfs_error(vol->sb, "Failed to map mft record.");
return PTR_ERR(mrec);
}
ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
if (unlikely(!ctx)) {
ntfs_error(vol->sb, "Failed to get search context.");
ret = -ENOMEM;
goto unm_err_out;
}
ret = ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL, 0, ctx);
if (unlikely(ret)) {
ntfs_error(vol->sb, "Failed to find first attribute extent of "
"mft bitmap attribute.");
if (ret == -ENOENT)
ret = -EIO;
goto put_err_out;
}
a = ctx->attr;
write_lock_irqsave(&mftbmp_ni->size_lock, flags);
old_data_size = i_size_read(mftbmp_vi);
old_initialized_size = mftbmp_ni->initialized_size;
/*
* We can simply update the initialized_size before filling the space
* with zeroes because the caller is holding the mft bitmap lock for
* writing which ensures that no one else is trying to access the data.
*/
mftbmp_ni->initialized_size += 8;
a->data.non_resident.initialized_size =
cpu_to_sle64(mftbmp_ni->initialized_size);
if (mftbmp_ni->initialized_size > old_data_size) {
i_size_write(mftbmp_vi, mftbmp_ni->initialized_size);
a->data.non_resident.data_size =
cpu_to_sle64(mftbmp_ni->initialized_size);
}
write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
/* Ensure the changes make it to disk. */
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(mft_ni);
/* Initialize the mft bitmap attribute value with zeroes. */
ret = ntfs_attr_set(mftbmp_ni, old_initialized_size, 8, 0);
if (likely(!ret)) {
ntfs_debug("Done. (Wrote eight initialized bytes to mft "
"bitmap.");
return 0;
}
ntfs_error(vol->sb, "Failed to write to mft bitmap.");
/* Try to recover from the error. */
mrec = map_mft_record(mft_ni);
if (IS_ERR(mrec)) {
ntfs_error(vol->sb, "Failed to map mft record.%s", es);
NVolSetErrors(vol);
return ret;
}
ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
if (unlikely(!ctx)) {
ntfs_error(vol->sb, "Failed to get search context.%s", es);
NVolSetErrors(vol);
goto unm_err_out;
}
if (ntfs_attr_lookup(mftbmp_ni->type, mftbmp_ni->name,
mftbmp_ni->name_len, CASE_SENSITIVE, 0, NULL, 0, ctx)) {
ntfs_error(vol->sb, "Failed to find first attribute extent of "
"mft bitmap attribute.%s", es);
NVolSetErrors(vol);
put_err_out:
ntfs_attr_put_search_ctx(ctx);
unm_err_out:
unmap_mft_record(mft_ni);
goto err_out;
}
a = ctx->attr;
write_lock_irqsave(&mftbmp_ni->size_lock, flags);
mftbmp_ni->initialized_size = old_initialized_size;
a->data.non_resident.initialized_size =
cpu_to_sle64(old_initialized_size);
if (i_size_read(mftbmp_vi) != old_data_size) {
i_size_write(mftbmp_vi, old_data_size);
a->data.non_resident.data_size = cpu_to_sle64(old_data_size);
}
write_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(mft_ni);
#ifdef DEBUG
read_lock_irqsave(&mftbmp_ni->size_lock, flags);
ntfs_debug("Restored status of mftbmp: allocated_size 0x%llx, "
"data_size 0x%llx, initialized_size 0x%llx.",
(long long)mftbmp_ni->allocated_size,
(long long)i_size_read(mftbmp_vi),
(long long)mftbmp_ni->initialized_size);
read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
#endif /* DEBUG */
err_out:
return ret;
}
/**
* ntfs_mft_data_extend_allocation_nolock - extend mft data attribute
* @vol: volume on which to extend the mft data attribute
*
* Extend the mft data attribute on the ntfs volume @vol by 16 mft records
* worth of clusters or if not enough space for this by one mft record worth
* of clusters.
*
* Note: Only changes allocated_size, i.e. does not touch initialized_size or
* data_size.
*
* Return 0 on success and -errno on error.
*
* Locking: - Caller must hold vol->mftbmp_lock for writing.
* - This function takes NTFS_I(vol->mft_ino)->runlist.lock for
* writing and releases it before returning.
* - This function calls functions which take vol->lcnbmp_lock for
* writing and release it before returning.
*/
static int ntfs_mft_data_extend_allocation_nolock(ntfs_volume *vol)
{
LCN lcn;
VCN old_last_vcn;
s64 min_nr, nr, ll;
unsigned long flags;
ntfs_inode *mft_ni;
runlist_element *rl, *rl2;
ntfs_attr_search_ctx *ctx = NULL;
MFT_RECORD *mrec;
ATTR_RECORD *a = NULL;
int ret, mp_size;
u32 old_alen = 0;
bool mp_rebuilt = false;
ntfs_debug("Extending mft data allocation.");
mft_ni = NTFS_I(vol->mft_ino);
/*
* Determine the preferred allocation location, i.e. the last lcn of
* the mft data attribute. The allocated size of the mft data
* attribute cannot be zero so we are ok to do this.
*/
down_write(&mft_ni->runlist.lock);
read_lock_irqsave(&mft_ni->size_lock, flags);
ll = mft_ni->allocated_size;
read_unlock_irqrestore(&mft_ni->size_lock, flags);
rl = ntfs_attr_find_vcn_nolock(mft_ni,
(ll - 1) >> vol->cluster_size_bits, NULL);
if (unlikely(IS_ERR(rl) || !rl->length || rl->lcn < 0)) {
up_write(&mft_ni->runlist.lock);
ntfs_error(vol->sb, "Failed to determine last allocated "
"cluster of mft data attribute.");
if (!IS_ERR(rl))
ret = -EIO;
else
ret = PTR_ERR(rl);
return ret;
}
lcn = rl->lcn + rl->length;
ntfs_debug("Last lcn of mft data attribute is 0x%llx.", (long long)lcn);
/* Minimum allocation is one mft record worth of clusters. */
min_nr = vol->mft_record_size >> vol->cluster_size_bits;
if (!min_nr)
min_nr = 1;
/* Want to allocate 16 mft records worth of clusters. */
nr = vol->mft_record_size << 4 >> vol->cluster_size_bits;
if (!nr)
nr = min_nr;
/* Ensure we do not go above 2^32-1 mft records. */
read_lock_irqsave(&mft_ni->size_lock, flags);
ll = mft_ni->allocated_size;
read_unlock_irqrestore(&mft_ni->size_lock, flags);
if (unlikely((ll + (nr << vol->cluster_size_bits)) >>
vol->mft_record_size_bits >= (1ll << 32))) {
nr = min_nr;
if (unlikely((ll + (nr << vol->cluster_size_bits)) >>
vol->mft_record_size_bits >= (1ll << 32))) {
ntfs_warning(vol->sb, "Cannot allocate mft record "
"because the maximum number of inodes "
"(2^32) has already been reached.");
up_write(&mft_ni->runlist.lock);
return -ENOSPC;
}
}
ntfs_debug("Trying mft data allocation with %s cluster count %lli.",
nr > min_nr ? "default" : "minimal", (long long)nr);
old_last_vcn = rl[1].vcn;
do {
rl2 = ntfs_cluster_alloc(vol, old_last_vcn, nr, lcn, MFT_ZONE,
true);
if (likely(!IS_ERR(rl2)))
break;
if (PTR_ERR(rl2) != -ENOSPC || nr == min_nr) {
ntfs_error(vol->sb, "Failed to allocate the minimal "
"number of clusters (%lli) for the "
"mft data attribute.", (long long)nr);
up_write(&mft_ni->runlist.lock);
return PTR_ERR(rl2);
}
/*
* There is not enough space to do the allocation, but there
* might be enough space to do a minimal allocation so try that
* before failing.
*/
nr = min_nr;
ntfs_debug("Retrying mft data allocation with minimal cluster "
"count %lli.", (long long)nr);
} while (1);
rl = ntfs_runlists_merge(mft_ni->runlist.rl, rl2);
if (IS_ERR(rl)) {
up_write(&mft_ni->runlist.lock);
ntfs_error(vol->sb, "Failed to merge runlists for mft data "
"attribute.");
if (ntfs_cluster_free_from_rl(vol, rl2)) {
ntfs_error(vol->sb, "Failed to deallocate clusters "
"from the mft data attribute.%s", es);
NVolSetErrors(vol);
}
ntfs_free(rl2);
return PTR_ERR(rl);
}
mft_ni->runlist.rl = rl;
ntfs_debug("Allocated %lli clusters.", (long long)nr);
/* Find the last run in the new runlist. */
for (; rl[1].length; rl++)
;
/* Update the attribute record as well. */
mrec = map_mft_record(mft_ni);
if (IS_ERR(mrec)) {
ntfs_error(vol->sb, "Failed to map mft record.");
ret = PTR_ERR(mrec);
goto undo_alloc;
}
ctx = ntfs_attr_get_search_ctx(mft_ni, mrec);
if (unlikely(!ctx)) {
ntfs_error(vol->sb, "Failed to get search context.");
ret = -ENOMEM;
goto undo_alloc;
}
ret = ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
CASE_SENSITIVE, rl[1].vcn, NULL, 0, ctx);
if (unlikely(ret)) {
ntfs_error(vol->sb, "Failed to find last attribute extent of "
"mft data attribute.");
if (ret == -ENOENT)
ret = -EIO;
goto undo_alloc;
}
a = ctx->attr;
ll = sle64_to_cpu(a->data.non_resident.lowest_vcn);
/* Search back for the previous last allocated cluster of mft bitmap. */
for (rl2 = rl; rl2 > mft_ni->runlist.rl; rl2--) {
if (ll >= rl2->vcn)
break;
}
BUG_ON(ll < rl2->vcn);
BUG_ON(ll >= rl2->vcn + rl2->length);
/* Get the size for the new mapping pairs array for this extent. */
mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, ll, -1);
if (unlikely(mp_size <= 0)) {
ntfs_error(vol->sb, "Get size for mapping pairs failed for "
"mft data attribute extent.");
ret = mp_size;
if (!ret)
ret = -EIO;
goto undo_alloc;
}
/* Expand the attribute record if necessary. */
old_alen = le32_to_cpu(a->length);
ret = ntfs_attr_record_resize(ctx->mrec, a, mp_size +
le16_to_cpu(a->data.non_resident.mapping_pairs_offset));
if (unlikely(ret)) {
if (ret != -ENOSPC) {
ntfs_error(vol->sb, "Failed to resize attribute "
"record for mft data attribute.");
goto undo_alloc;
}
// TODO: Deal with this by moving this extent to a new mft
// record or by starting a new extent in a new mft record or by
// moving other attributes out of this mft record.
// Note: Use the special reserved mft records and ensure that
// this extent is not required to find the mft record in
// question. If no free special records left we would need to
// move an existing record away, insert ours in its place, and
// then place the moved record into the newly allocated space
// and we would then need to update all references to this mft
// record appropriately. This is rather complicated...
ntfs_error(vol->sb, "Not enough space in this mft record to "
"accommodate extended mft data attribute "
"extent. Cannot handle this yet.");
ret = -EOPNOTSUPP;
goto undo_alloc;
}
mp_rebuilt = true;
/* Generate the mapping pairs array directly into the attr record. */
ret = ntfs_mapping_pairs_build(vol, (u8*)a +
le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
mp_size, rl2, ll, -1, NULL);
if (unlikely(ret)) {
ntfs_error(vol->sb, "Failed to build mapping pairs array of "
"mft data attribute.");
goto undo_alloc;
}
/* Update the highest_vcn. */
a->data.non_resident.highest_vcn = cpu_to_sle64(rl[1].vcn - 1);
/*
* We now have extended the mft data allocated_size by nr clusters.
* Reflect this in the ntfs_inode structure and the attribute record.
* @rl is the last (non-terminator) runlist element of mft data
* attribute.
*/
if (a->data.non_resident.lowest_vcn) {
/*
* We are not in the first attribute extent, switch to it, but
* first ensure the changes will make it to disk later.
*/
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
ntfs_attr_reinit_search_ctx(ctx);
ret = ntfs_attr_lookup(mft_ni->type, mft_ni->name,
mft_ni->name_len, CASE_SENSITIVE, 0, NULL, 0,
ctx);
if (unlikely(ret)) {
ntfs_error(vol->sb, "Failed to find first attribute "
"extent of mft data attribute.");
goto restore_undo_alloc;
}
a = ctx->attr;
}
write_lock_irqsave(&mft_ni->size_lock, flags);
mft_ni->allocated_size += nr << vol->cluster_size_bits;
a->data.non_resident.allocated_size =
cpu_to_sle64(mft_ni->allocated_size);
write_unlock_irqrestore(&mft_ni->size_lock, flags);
/* Ensure the changes make it to disk. */
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(mft_ni);
up_write(&mft_ni->runlist.lock);
ntfs_debug("Done.");
return 0;
restore_undo_alloc:
ntfs_attr_reinit_search_ctx(ctx);
if (ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
CASE_SENSITIVE, rl[1].vcn, NULL, 0, ctx)) {
ntfs_error(vol->sb, "Failed to find last attribute extent of "
"mft data attribute.%s", es);
write_lock_irqsave(&mft_ni->size_lock, flags);
mft_ni->allocated_size += nr << vol->cluster_size_bits;
write_unlock_irqrestore(&mft_ni->size_lock, flags);
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(mft_ni);
up_write(&mft_ni->runlist.lock);
/*
* The only thing that is now wrong is ->allocated_size of the
* base attribute extent which chkdsk should be able to fix.
*/
NVolSetErrors(vol);
return ret;
}
ctx->attr->data.non_resident.highest_vcn =
cpu_to_sle64(old_last_vcn - 1);
undo_alloc:
if (ntfs_cluster_free(mft_ni, old_last_vcn, -1, ctx) < 0) {
ntfs_error(vol->sb, "Failed to free clusters from mft data "
"attribute.%s", es);
NVolSetErrors(vol);
}
a = ctx->attr;
if (ntfs_rl_truncate_nolock(vol, &mft_ni->runlist, old_last_vcn)) {
ntfs_error(vol->sb, "Failed to truncate mft data attribute "
"runlist.%s", es);
NVolSetErrors(vol);
}
if (mp_rebuilt && !IS_ERR(ctx->mrec)) {
if (ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
a->data.non_resident.mapping_pairs_offset),
old_alen - le16_to_cpu(
a->data.non_resident.mapping_pairs_offset),
rl2, ll, -1, NULL)) {
ntfs_error(vol->sb, "Failed to restore mapping pairs "
"array.%s", es);
NVolSetErrors(vol);
}
if (ntfs_attr_record_resize(ctx->mrec, a, old_alen)) {
ntfs_error(vol->sb, "Failed to restore attribute "
"record.%s", es);
NVolSetErrors(vol);
}
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
} else if (IS_ERR(ctx->mrec)) {
ntfs_error(vol->sb, "Failed to restore attribute search "
"context.%s", es);
NVolSetErrors(vol);
}
if (ctx)
ntfs_attr_put_search_ctx(ctx);
if (!IS_ERR(mrec))
unmap_mft_record(mft_ni);
up_write(&mft_ni->runlist.lock);
return ret;
}
/**
* ntfs_mft_record_layout - layout an mft record into a memory buffer
* @vol: volume to which the mft record will belong
* @mft_no: mft reference specifying the mft record number
* @m: destination buffer of size >= @vol->mft_record_size bytes
*
* Layout an empty, unused mft record with the mft record number @mft_no into
* the buffer @m. The volume @vol is needed because the mft record structure
* was modified in NTFS 3.1 so we need to know which volume version this mft
* record will be used on.
*
* Return 0 on success and -errno on error.
*/
static int ntfs_mft_record_layout(const ntfs_volume *vol, const s64 mft_no,
MFT_RECORD *m)
{
ATTR_RECORD *a;
ntfs_debug("Entering for mft record 0x%llx.", (long long)mft_no);
if (mft_no >= (1ll << 32)) {
ntfs_error(vol->sb, "Mft record number 0x%llx exceeds "
"maximum of 2^32.", (long long)mft_no);
return -ERANGE;
}
/* Start by clearing the whole mft record to gives us a clean slate. */
memset(m, 0, vol->mft_record_size);
/* Aligned to 2-byte boundary. */
if (vol->major_ver < 3 || (vol->major_ver == 3 && !vol->minor_ver))
m->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD_OLD) + 1) & ~1);
else {
m->usa_ofs = cpu_to_le16((sizeof(MFT_RECORD) + 1) & ~1);
/*
* Set the NTFS 3.1+ specific fields while we know that the
* volume version is 3.1+.
*/
m->reserved = 0;
m->mft_record_number = cpu_to_le32((u32)mft_no);
}
m->magic = magic_FILE;
if (vol->mft_record_size >= NTFS_BLOCK_SIZE)
m->usa_count = cpu_to_le16(vol->mft_record_size /
NTFS_BLOCK_SIZE + 1);
else {
m->usa_count = cpu_to_le16(1);
ntfs_warning(vol->sb, "Sector size is bigger than mft record "
"size. Setting usa_count to 1. If chkdsk "
"reports this as corruption, please email "
"linux-ntfs-dev@lists.sourceforge.net stating "
"that you saw this message and that the "
"modified filesystem created was corrupt. "
"Thank you.");
}
/* Set the update sequence number to 1. */
*(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = cpu_to_le16(1);
m->lsn = 0;
m->sequence_number = cpu_to_le16(1);
m->link_count = 0;
/*
* Place the attributes straight after the update sequence array,
* aligned to 8-byte boundary.
*/
m->attrs_offset = cpu_to_le16((le16_to_cpu(m->usa_ofs) +
(le16_to_cpu(m->usa_count) << 1) + 7) & ~7);
m->flags = 0;
/*
* Using attrs_offset plus eight bytes (for the termination attribute).
* attrs_offset is already aligned to 8-byte boundary, so no need to
* align again.
*/
m->bytes_in_use = cpu_to_le32(le16_to_cpu(m->attrs_offset) + 8);
m->bytes_allocated = cpu_to_le32(vol->mft_record_size);
m->base_mft_record = 0;
m->next_attr_instance = 0;
/* Add the termination attribute. */
a = (ATTR_RECORD*)((u8*)m + le16_to_cpu(m->attrs_offset));
a->type = AT_END;
a->length = 0;
ntfs_debug("Done.");
return 0;
}
/**
* ntfs_mft_record_format - format an mft record on an ntfs volume
* @vol: volume on which to format the mft record
* @mft_no: mft record number to format
*
* Format the mft record @mft_no in $MFT/$DATA, i.e. lay out an empty, unused
* mft record into the appropriate place of the mft data attribute. This is
* used when extending the mft data attribute.
*
* Return 0 on success and -errno on error.
*/
static int ntfs_mft_record_format(const ntfs_volume *vol, const s64 mft_no)
{
loff_t i_size;
struct inode *mft_vi = vol->mft_ino;
struct page *page;
MFT_RECORD *m;
pgoff_t index, end_index;
unsigned int ofs;
int err;
ntfs_debug("Entering for mft record 0x%llx.", (long long)mft_no);
/*
* The index into the page cache and the offset within the page cache
* page of the wanted mft record.
*/
index = mft_no << vol->mft_record_size_bits >> PAGE_CACHE_SHIFT;
ofs = (mft_no << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
/* The maximum valid index into the page cache for $MFT's data. */
i_size = i_size_read(mft_vi);
end_index = i_size >> PAGE_CACHE_SHIFT;
if (unlikely(index >= end_index)) {
if (unlikely(index > end_index || ofs + vol->mft_record_size >=
(i_size & ~PAGE_CACHE_MASK))) {
ntfs_error(vol->sb, "Tried to format non-existing mft "
"record 0x%llx.", (long long)mft_no);
return -ENOENT;
}
}
/* Read, map, and pin the page containing the mft record. */
page = ntfs_map_page(mft_vi->i_mapping, index);
if (IS_ERR(page)) {
ntfs_error(vol->sb, "Failed to map page containing mft record "
"to format 0x%llx.", (long long)mft_no);
return PTR_ERR(page);
}
lock_page(page);
BUG_ON(!PageUptodate(page));
ClearPageUptodate(page);
m = (MFT_RECORD*)((u8*)page_address(page) + ofs);
err = ntfs_mft_record_layout(vol, mft_no, m);
if (unlikely(err)) {
ntfs_error(vol->sb, "Failed to layout mft record 0x%llx.",
(long long)mft_no);
SetPageUptodate(page);
unlock_page(page);
ntfs_unmap_page(page);
return err;
}
flush_dcache_page(page);
SetPageUptodate(page);
unlock_page(page);
/*
* Make sure the mft record is written out to disk. We could use
* ilookup5() to check if an inode is in icache and so on but this is
* unnecessary as ntfs_writepage() will write the dirty record anyway.
*/
mark_ntfs_record_dirty(page, ofs);
ntfs_unmap_page(page);
ntfs_debug("Done.");
return 0;
}
/**
* ntfs_mft_record_alloc - allocate an mft record on an ntfs volume
* @vol: [IN] volume on which to allocate the mft record
* @mode: [IN] mode if want a file or directory, i.e. base inode or 0
* @base_ni: [IN] open base inode if allocating an extent mft record or NULL
* @mrec: [OUT] on successful return this is the mapped mft record
*
* Allocate an mft record in $MFT/$DATA of an open ntfs volume @vol.
*
* If @base_ni is NULL make the mft record a base mft record, i.e. a file or
* direvctory inode, and allocate it at the default allocator position. In
* this case @mode is the file mode as given to us by the caller. We in
* particular use @mode to distinguish whether a file or a directory is being
* created (S_IFDIR(mode) and S_IFREG(mode), respectively).
*
* If @base_ni is not NULL make the allocated mft record an extent record,
* allocate it starting at the mft record after the base mft record and attach
* the allocated and opened ntfs inode to the base inode @base_ni. In this
* case @mode must be 0 as it is meaningless for extent inodes.
*
* You need to check the return value with IS_ERR(). If false, the function
* was successful and the return value is the now opened ntfs inode of the
* allocated mft record. *@mrec is then set to the allocated, mapped, pinned,
* and locked mft record. If IS_ERR() is true, the function failed and the
* error code is obtained from PTR_ERR(return value). *@mrec is undefined in
* this case.
*
* Allocation strategy:
*
* To find a free mft record, we scan the mft bitmap for a zero bit. To
* optimize this we start scanning at the place specified by @base_ni or if
* @base_ni is NULL we start where we last stopped and we perform wrap around
* when we reach the end. Note, we do not try to allocate mft records below
* number 24 because numbers 0 to 15 are the defined system files anyway and 16
* to 24 are special in that they are used for storing extension mft records
* for the $DATA attribute of $MFT. This is required to avoid the possibility
* of creating a runlist with a circular dependency which once written to disk
* can never be read in again. Windows will only use records 16 to 24 for
* normal files if the volume is completely out of space. We never use them
* which means that when the volume is really out of space we cannot create any
* more files while Windows can still create up to 8 small files. We can start
* doing this at some later time, it does not matter much for now.
*
* When scanning the mft bitmap, we only search up to the last allocated mft
* record. If there are no free records left in the range 24 to number of
* allocated mft records, then we extend the $MFT/$DATA attribute in order to
* create free mft records. We extend the allocated size of $MFT/$DATA by 16
* records at a time or one cluster, if cluster size is above 16kiB. If there
* is not sufficient space to do this, we try to extend by a single mft record
* or one cluster, if cluster size is above the mft record size.
*
* No matter how many mft records we allocate, we initialize only the first
* allocated mft record, incrementing mft data size and initialized size
* accordingly, open an ntfs_inode for it and return it to the caller, unless
* there are less than 24 mft records, in which case we allocate and initialize
* mft records until we reach record 24 which we consider as the first free mft
* record for use by normal files.
*
* If during any stage we overflow the initialized data in the mft bitmap, we
* extend the initialized size (and data size) by 8 bytes, allocating another
* cluster if required. The bitmap data size has to be at least equal to the
* number of mft records in the mft, but it can be bigger, in which case the
* superflous bits are padded with zeroes.
*
* Thus, when we return successfully (IS_ERR() is false), we will have:
* - initialized / extended the mft bitmap if necessary,
* - initialized / extended the mft data if necessary,
* - set the bit corresponding to the mft record being allocated in the
* mft bitmap,
* - opened an ntfs_inode for the allocated mft record, and we will have
* - returned the ntfs_inode as well as the allocated mapped, pinned, and
* locked mft record.
*
* On error, the volume will be left in a consistent state and no record will
* be allocated. If rolling back a partial operation fails, we may leave some
* inconsistent metadata in which case we set NVolErrors() so the volume is
* left dirty when unmounted.
*
* Note, this function cannot make use of most of the normal functions, like
* for example for attribute resizing, etc, because when the run list overflows
* the base mft record and an attribute list is used, it is very important that
* the extension mft records used to store the $DATA attribute of $MFT can be
* reached without having to read the information contained inside them, as
* this would make it impossible to find them in the first place after the
* volume is unmounted. $MFT/$BITMAP probably does not need to follow this
* rule because the bitmap is not essential for finding the mft records, but on
* the other hand, handling the bitmap in this special way would make life
* easier because otherwise there might be circular invocations of functions
* when reading the bitmap.
*/
ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, const int mode,
ntfs_inode *base_ni, MFT_RECORD **mrec)
{
s64 ll, bit, old_data_initialized, old_data_size;
unsigned long flags;
struct inode *vi;
struct page *page;
ntfs_inode *mft_ni, *mftbmp_ni, *ni;
ntfs_attr_search_ctx *ctx;
MFT_RECORD *m;
ATTR_RECORD *a;
pgoff_t index;
unsigned int ofs;
int err;
le16 seq_no, usn;
bool record_formatted = false;
if (base_ni) {
ntfs_debug("Entering (allocating an extent mft record for "
"base mft record 0x%llx).",
(long long)base_ni->mft_no);
/* @mode and @base_ni are mutually exclusive. */
BUG_ON(mode);
} else
ntfs_debug("Entering (allocating a base mft record).");
if (mode) {
/* @mode and @base_ni are mutually exclusive. */
BUG_ON(base_ni);
/* We only support creation of normal files and directories. */
if (!S_ISREG(mode) && !S_ISDIR(mode))
return ERR_PTR(-EOPNOTSUPP);
}
BUG_ON(!mrec);
mft_ni = NTFS_I(vol->mft_ino);
mftbmp_ni = NTFS_I(vol->mftbmp_ino);
down_write(&vol->mftbmp_lock);
bit = ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(vol, base_ni);
if (bit >= 0) {
ntfs_debug("Found and allocated free record (#1), bit 0x%llx.",
(long long)bit);
goto have_alloc_rec;
}
if (bit != -ENOSPC) {
up_write(&vol->mftbmp_lock);
return ERR_PTR(bit);
}
/*
* No free mft records left. If the mft bitmap already covers more
* than the currently used mft records, the next records are all free,
* so we can simply allocate the first unused mft record.
* Note: We also have to make sure that the mft bitmap at least covers
* the first 24 mft records as they are special and whilst they may not
* be in use, we do not allocate from them.
*/
read_lock_irqsave(&mft_ni->size_lock, flags);
ll = mft_ni->initialized_size >> vol->mft_record_size_bits;
read_unlock_irqrestore(&mft_ni->size_lock, flags);
read_lock_irqsave(&mftbmp_ni->size_lock, flags);
old_data_initialized = mftbmp_ni->initialized_size;
read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
if (old_data_initialized << 3 > ll && old_data_initialized > 3) {
bit = ll;
if (bit < 24)
bit = 24;
if (unlikely(bit >= (1ll << 32)))
goto max_err_out;
ntfs_debug("Found free record (#2), bit 0x%llx.",
(long long)bit);
goto found_free_rec;
}
/*
* The mft bitmap needs to be expanded until it covers the first unused
* mft record that we can allocate.
* Note: The smallest mft record we allocate is mft record 24.
*/
bit = old_data_initialized << 3;
if (unlikely(bit >= (1ll << 32)))
goto max_err_out;
read_lock_irqsave(&mftbmp_ni->size_lock, flags);
old_data_size = mftbmp_ni->allocated_size;
ntfs_debug("Status of mftbmp before extension: allocated_size 0x%llx, "
"data_size 0x%llx, initialized_size 0x%llx.",
(long long)old_data_size,
(long long)i_size_read(vol->mftbmp_ino),
(long long)old_data_initialized);
read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
if (old_data_initialized + 8 > old_data_size) {
/* Need to extend bitmap by one more cluster. */
ntfs_debug("mftbmp: initialized_size + 8 > allocated_size.");
err = ntfs_mft_bitmap_extend_allocation_nolock(vol);
if (unlikely(err)) {
up_write(&vol->mftbmp_lock);
goto err_out;
}
#ifdef DEBUG
read_lock_irqsave(&mftbmp_ni->size_lock, flags);
ntfs_debug("Status of mftbmp after allocation extension: "
"allocated_size 0x%llx, data_size 0x%llx, "
"initialized_size 0x%llx.",
(long long)mftbmp_ni->allocated_size,
(long long)i_size_read(vol->mftbmp_ino),
(long long)mftbmp_ni->initialized_size);
read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
#endif /* DEBUG */
}
/*
* We now have sufficient allocated space, extend the initialized_size
* as well as the data_size if necessary and fill the new space with
* zeroes.
*/
err = ntfs_mft_bitmap_extend_initialized_nolock(vol);
if (unlikely(err)) {
up_write(&vol->mftbmp_lock);
goto err_out;
}
#ifdef DEBUG
read_lock_irqsave(&mftbmp_ni->size_lock, flags);
ntfs_debug("Status of mftbmp after initialized extension: "
"allocated_size 0x%llx, data_size 0x%llx, "
"initialized_size 0x%llx.",
(long long)mftbmp_ni->allocated_size,
(long long)i_size_read(vol->mftbmp_ino),
(long long)mftbmp_ni->initialized_size);
read_unlock_irqrestore(&mftbmp_ni->size_lock, flags);
#endif /* DEBUG */
ntfs_debug("Found free record (#3), bit 0x%llx.", (long long)bit);
found_free_rec:
/* @bit is the found free mft record, allocate it in the mft bitmap. */
ntfs_debug("At found_free_rec.");
err = ntfs_bitmap_set_bit(vol->mftbmp_ino, bit);
if (unlikely(err)) {
ntfs_error(vol->sb, "Failed to allocate bit in mft bitmap.");
up_write(&vol->mftbmp_lock);
goto err_out;
}
ntfs_debug("Set bit 0x%llx in mft bitmap.", (long long)bit);
have_alloc_rec:
/*
* The mft bitmap is now uptodate. Deal with mft data attribute now.
* Note, we keep hold of the mft bitmap lock for writing until all
* modifications to the mft data attribute are complete, too, as they
* will impact decisions for mft bitmap and mft record allocation done
* by a parallel allocation and if the lock is not maintained a
* parallel allocation could allocate the same mft record as this one.
*/
ll = (bit + 1) << vol->mft_record_size_bits;
read_lock_irqsave(&mft_ni->size_lock, flags);
old_data_initialized = mft_ni->initialized_size;
read_unlock_irqrestore(&mft_ni->size_lock, flags);
if (ll <= old_data_initialized) {
ntfs_debug("Allocated mft record already initialized.");
goto mft_rec_already_initialized;
}
ntfs_debug("Initializing allocated mft record.");
/*
* The mft record is outside the initialized data. Extend the mft data
* attribute until it covers the allocated record. The loop is only
* actually traversed more than once when a freshly formatted volume is
* first written to so it optimizes away nicely in the common case.
*/
read_lock_irqsave(&mft_ni->size_lock, flags);
ntfs_debug("Status of mft data before extension: "
"allocated_size 0x%llx, data_size 0x%llx, "
"initialized_size 0x%llx.",
(long long)mft_ni->allocated_size,
(long long)i_size_read(vol->mft_ino),
(long long)mft_ni->initialized_size);
while (ll > mft_ni->allocated_size) {
read_unlock_irqrestore(&mft_ni->size_lock, flags);
err = ntfs_mft_data_extend_allocation_nolock(vol);
if (unlikely(err)) {
ntfs_error(vol->sb, "Failed to extend mft data "
"allocation.");
goto undo_mftbmp_alloc_nolock;
}
read_lock_irqsave(&mft_ni->size_lock, flags);
ntfs_debug("Status of mft data after allocation extension: "
"allocated_size 0x%llx, data_size 0x%llx, "
"initialized_size 0x%llx.",
(long long)mft_ni->allocated_size,
(long long)i_size_read(vol->mft_ino),
(long long)mft_ni->initialized_size);
}
read_unlock_irqrestore(&mft_ni->size_lock, flags);
/*
* Extend mft data initialized size (and data size of course) to reach
* the allocated mft record, formatting the mft records allong the way.
* Note: We only modify the ntfs_inode structure as that is all that is
* needed by ntfs_mft_record_format(). We will update the attribute
* record itself in one fell swoop later on.
*/
write_lock_irqsave(&mft_ni->size_lock, flags);
old_data_initialized = mft_ni->initialized_size;
old_data_size = vol->mft_ino->i_size;
while (ll > mft_ni->initialized_size) {
s64 new_initialized_size, mft_no;
new_initialized_size = mft_ni->initialized_size +
vol->mft_record_size;
mft_no = mft_ni->initialized_size >> vol->mft_record_size_bits;
if (new_initialized_size > i_size_read(vol->mft_ino))
i_size_write(vol->mft_ino, new_initialized_size);
write_unlock_irqrestore(&mft_ni->size_lock, flags);
ntfs_debug("Initializing mft record 0x%llx.",
(long long)mft_no);
err = ntfs_mft_record_format(vol, mft_no);
if (unlikely(err)) {
ntfs_error(vol->sb, "Failed to format mft record.");
goto undo_data_init;
}
write_lock_irqsave(&mft_ni->size_lock, flags);
mft_ni->initialized_size = new_initialized_size;
}
write_unlock_irqrestore(&mft_ni->size_lock, flags);
record_formatted = true;
/* Update the mft data attribute record to reflect the new sizes. */
m = map_mft_record(mft_ni);
if (IS_ERR(m)) {
ntfs_error(vol->sb, "Failed to map mft record.");
err = PTR_ERR(m);
goto undo_data_init;
}
ctx = ntfs_attr_get_search_ctx(mft_ni, m);
if (unlikely(!ctx)) {
ntfs_error(vol->sb, "Failed to get search context.");
err = -ENOMEM;
unmap_mft_record(mft_ni);
goto undo_data_init;
}
err = ntfs_attr_lookup(mft_ni->type, mft_ni->name, mft_ni->name_len,
CASE_SENSITIVE, 0, NULL, 0, ctx);
if (unlikely(err)) {
ntfs_error(vol->sb, "Failed to find first attribute extent of "
"mft data attribute.");
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(mft_ni);
goto undo_data_init;
}
a = ctx->attr;
read_lock_irqsave(&mft_ni->size_lock, flags);
a->data.non_resident.initialized_size =
cpu_to_sle64(mft_ni->initialized_size);
a->data.non_resident.data_size =
cpu_to_sle64(i_size_read(vol->mft_ino));
read_unlock_irqrestore(&mft_ni->size_lock, flags);
/* Ensure the changes make it to disk. */
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(mft_ni);
read_lock_irqsave(&mft_ni->size_lock, flags);
ntfs_debug("Status of mft data after mft record initialization: "
"allocated_size 0x%llx, data_size 0x%llx, "
"initialized_size 0x%llx.",
(long long)mft_ni->allocated_size,
(long long)i_size_read(vol->mft_ino),
(long long)mft_ni->initialized_size);
BUG_ON(i_size_read(vol->mft_ino) > mft_ni->allocated_size);
BUG_ON(mft_ni->initialized_size > i_size_read(vol->mft_ino));
read_unlock_irqrestore(&mft_ni->size_lock, flags);
mft_rec_already_initialized:
/*
* We can finally drop the mft bitmap lock as the mft data attribute
* has been fully updated. The only disparity left is that the
* allocated mft record still needs to be marked as in use to match the
* set bit in the mft bitmap but this is actually not a problem since
* this mft record is not referenced from anywhere yet and the fact
* that it is allocated in the mft bitmap means that no-one will try to
* allocate it either.
*/
up_write(&vol->mftbmp_lock);
/*
* We now have allocated and initialized the mft record. Calculate the
* index of and the offset within the page cache page the record is in.
*/
index = bit << vol->mft_record_size_bits >> PAGE_CACHE_SHIFT;
ofs = (bit << vol->mft_record_size_bits) & ~PAGE_CACHE_MASK;
/* Read, map, and pin the page containing the mft record. */
page = ntfs_map_page(vol->mft_ino->i_mapping, index);
if (IS_ERR(page)) {
ntfs_error(vol->sb, "Failed to map page containing allocated "
"mft record 0x%llx.", (long long)bit);
err = PTR_ERR(page);
goto undo_mftbmp_alloc;
}
lock_page(page);
BUG_ON(!PageUptodate(page));
ClearPageUptodate(page);
m = (MFT_RECORD*)((u8*)page_address(page) + ofs);
/* If we just formatted the mft record no need to do it again. */
if (!record_formatted) {
/* Sanity check that the mft record is really not in use. */
if (ntfs_is_file_record(m->magic) &&
(m->flags & MFT_RECORD_IN_USE)) {
ntfs_error(vol->sb, "Mft record 0x%llx was marked "
"free in mft bitmap but is marked "
"used itself. Corrupt filesystem. "
"Unmount and run chkdsk.",
(long long)bit);
err = -EIO;
SetPageUptodate(page);
unlock_page(page);
ntfs_unmap_page(page);
NVolSetErrors(vol);
goto undo_mftbmp_alloc;
}
/*
* We need to (re-)format the mft record, preserving the
* sequence number if it is not zero as well as the update
* sequence number if it is not zero or -1 (0xffff). This
* means we do not need to care whether or not something went
* wrong with the previous mft record.
*/
seq_no = m->sequence_number;
usn = *(le16*)((u8*)m + le16_to_cpu(m->usa_ofs));
err = ntfs_mft_record_layout(vol, bit, m);
if (unlikely(err)) {
ntfs_error(vol->sb, "Failed to layout allocated mft "
"record 0x%llx.", (long long)bit);
SetPageUptodate(page);
unlock_page(page);
ntfs_unmap_page(page);
goto undo_mftbmp_alloc;
}
if (seq_no)
m->sequence_number = seq_no;
if (usn && le16_to_cpu(usn) != 0xffff)
*(le16*)((u8*)m + le16_to_cpu(m->usa_ofs)) = usn;
}
/* Set the mft record itself in use. */
m->flags |= MFT_RECORD_IN_USE;
if (S_ISDIR(mode))
m->flags |= MFT_RECORD_IS_DIRECTORY;
flush_dcache_page(page);
SetPageUptodate(page);
if (base_ni) {
MFT_RECORD *m_tmp;
/*
* Setup the base mft record in the extent mft record. This
* completes initialization of the allocated extent mft record
* and we can simply use it with map_extent_mft_record().
*/
m->base_mft_record = MK_LE_MREF(base_ni->mft_no,
base_ni->seq_no);
/*
* Allocate an extent inode structure for the new mft record,
* attach it to the base inode @base_ni and map, pin, and lock
* its, i.e. the allocated, mft record.
*/
m_tmp = map_extent_mft_record(base_ni, bit, &ni);
if (IS_ERR(m_tmp)) {
ntfs_error(vol->sb, "Failed to map allocated extent "
"mft record 0x%llx.", (long long)bit);
err = PTR_ERR(m_tmp);
/* Set the mft record itself not in use. */
m->flags &= cpu_to_le16(
~le16_to_cpu(MFT_RECORD_IN_USE));
flush_dcache_page(page);
/* Make sure the mft record is written out to disk. */
mark_ntfs_record_dirty(page, ofs);
unlock_page(page);
ntfs_unmap_page(page);
goto undo_mftbmp_alloc;
}
BUG_ON(m != m_tmp);
/*
* Make sure the allocated mft record is written out to disk.
* No need to set the inode dirty because the caller is going
* to do that anyway after finishing with the new extent mft
* record (e.g. at a minimum a new attribute will be added to
* the mft record.
*/
mark_ntfs_record_dirty(page, ofs);
unlock_page(page);
/*
* Need to unmap the page since map_extent_mft_record() mapped
* it as well so we have it mapped twice at the moment.
*/
ntfs_unmap_page(page);
} else {
/*
* Allocate a new VFS inode and set it up. NOTE: @vi->i_nlink
* is set to 1 but the mft record->link_count is 0. The caller
* needs to bear this in mind.
*/
vi = new_inode(vol->sb);
if (unlikely(!vi)) {
err = -ENOMEM;
/* Set the mft record itself not in use. */
m->flags &= cpu_to_le16(
~le16_to_cpu(MFT_RECORD_IN_USE));
flush_dcache_page(page);
/* Make sure the mft record is written out to disk. */
mark_ntfs_record_dirty(page, ofs);
unlock_page(page);
ntfs_unmap_page(page);
goto undo_mftbmp_alloc;
}
vi->i_ino = bit;
/*
* This is for checking whether an inode has changed w.r.t. a
* file so that the file can be updated if necessary (compare
* with f_version).
*/
vi->i_version = 1;
/* The owner and group come from the ntfs volume. */
vi->i_uid = vol->uid;
vi->i_gid = vol->gid;
/* Initialize the ntfs specific part of @vi. */
ntfs_init_big_inode(vi);
ni = NTFS_I(vi);
/*
* Set the appropriate mode, attribute type, and name. For
* directories, also setup the index values to the defaults.
*/
if (S_ISDIR(mode)) {
vi->i_mode = S_IFDIR | S_IRWXUGO;
vi->i_mode &= ~vol->dmask;
NInoSetMstProtected(ni);
ni->type = AT_INDEX_ALLOCATION;
ni->name = I30;
ni->name_len = 4;
ni->itype.index.block_size = 4096;
ni->itype.index.block_size_bits = ntfs_ffs(4096) - 1;
ni->itype.index.collation_rule = COLLATION_FILE_NAME;
if (vol->cluster_size <= ni->itype.index.block_size) {
ni->itype.index.vcn_size = vol->cluster_size;
ni->itype.index.vcn_size_bits =
vol->cluster_size_bits;
} else {
ni->itype.index.vcn_size = vol->sector_size;
ni->itype.index.vcn_size_bits =
vol->sector_size_bits;
}
} else {
vi->i_mode = S_IFREG | S_IRWXUGO;
vi->i_mode &= ~vol->fmask;
ni->type = AT_DATA;
ni->name = NULL;
ni->name_len = 0;
}
if (IS_RDONLY(vi))
vi->i_mode &= ~S_IWUGO;
/* Set the inode times to the current time. */
vi->i_atime = vi->i_mtime = vi->i_ctime =
current_fs_time(vi->i_sb);
/*
* Set the file size to 0, the ntfs inode sizes are set to 0 by
* the call to ntfs_init_big_inode() below.
*/
vi->i_size = 0;
vi->i_blocks = 0;
/* Set the sequence number. */
vi->i_generation = ni->seq_no = le16_to_cpu(m->sequence_number);
/*
* Manually map, pin, and lock the mft record as we already
* have its page mapped and it is very easy to do.
*/
atomic_inc(&ni->count);
mutex_lock(&ni->mrec_lock);
ni->page = page;
ni->page_ofs = ofs;
/*
* Make sure the allocated mft record is written out to disk.
* NOTE: We do not set the ntfs inode dirty because this would
* fail in ntfs_write_inode() because the inode does not have a
* standard information attribute yet. Also, there is no need
* to set the inode dirty because the caller is going to do
* that anyway after finishing with the new mft record (e.g. at
* a minimum some new attributes will be added to the mft
* record.
*/
mark_ntfs_record_dirty(page, ofs);
unlock_page(page);
/* Add the inode to the inode hash for the superblock. */
insert_inode_hash(vi);
/* Update the default mft allocation position. */
vol->mft_data_pos = bit + 1;
}
/*
* Return the opened, allocated inode of the allocated mft record as
* well as the mapped, pinned, and locked mft record.
*/
ntfs_debug("Returning opened, allocated %sinode 0x%llx.",
base_ni ? "extent " : "", (long long)bit);
*mrec = m;
return ni;
undo_data_init:
write_lock_irqsave(&mft_ni->size_lock, flags);
mft_ni->initialized_size = old_data_initialized;
i_size_write(vol->mft_ino, old_data_size);
write_unlock_irqrestore(&mft_ni->size_lock, flags);
goto undo_mftbmp_alloc_nolock;
undo_mftbmp_alloc:
down_write(&vol->mftbmp_lock);
undo_mftbmp_alloc_nolock:
if (ntfs_bitmap_clear_bit(vol->mftbmp_ino, bit)) {
ntfs_error(vol->sb, "Failed to clear bit in mft bitmap.%s", es);
NVolSetErrors(vol);
}
up_write(&vol->mftbmp_lock);
err_out:
return ERR_PTR(err);
max_err_out:
ntfs_warning(vol->sb, "Cannot allocate mft record because the maximum "
"number of inodes (2^32) has already been reached.");
up_write(&vol->mftbmp_lock);
return ERR_PTR(-ENOSPC);
}
/**
* ntfs_extent_mft_record_free - free an extent mft record on an ntfs volume
* @ni: ntfs inode of the mapped extent mft record to free
* @m: mapped extent mft record of the ntfs inode @ni
*
* Free the mapped extent mft record @m of the extent ntfs inode @ni.
*
* Note that this function unmaps the mft record and closes and destroys @ni
* internally and hence you cannot use either @ni nor @m any more after this
* function returns success.
*
* On success return 0 and on error return -errno. @ni and @m are still valid
* in this case and have not been freed.
*
* For some errors an error message is displayed and the success code 0 is
* returned and the volume is then left dirty on umount. This makes sense in
* case we could not rollback the changes that were already done since the
* caller no longer wants to reference this mft record so it does not matter to
* the caller if something is wrong with it as long as it is properly detached
* from the base inode.
*/
int ntfs_extent_mft_record_free(ntfs_inode *ni, MFT_RECORD *m)
{
unsigned long mft_no = ni->mft_no;
ntfs_volume *vol = ni->vol;
ntfs_inode *base_ni;
ntfs_inode **extent_nis;
int i, err;
le16 old_seq_no;
u16 seq_no;
BUG_ON(NInoAttr(ni));
BUG_ON(ni->nr_extents != -1);
mutex_lock(&ni->extent_lock);
base_ni = ni->ext.base_ntfs_ino;
mutex_unlock(&ni->extent_lock);
BUG_ON(base_ni->nr_extents <= 0);
ntfs_debug("Entering for extent inode 0x%lx, base inode 0x%lx.\n",
mft_no, base_ni->mft_no);
mutex_lock(&base_ni->extent_lock);
/* Make sure we are holding the only reference to the extent inode. */
if (atomic_read(&ni->count) > 2) {
ntfs_error(vol->sb, "Tried to free busy extent inode 0x%lx, "
"not freeing.", base_ni->mft_no);
mutex_unlock(&base_ni->extent_lock);
return -EBUSY;
}
/* Dissociate the ntfs inode from the base inode. */
extent_nis = base_ni->ext.extent_ntfs_inos;
err = -ENOENT;
for (i = 0; i < base_ni->nr_extents; i++) {
if (ni != extent_nis[i])
continue;
extent_nis += i;
base_ni->nr_extents--;
memmove(extent_nis, extent_nis + 1, (base_ni->nr_extents - i) *
sizeof(ntfs_inode*));
err = 0;
break;
}
mutex_unlock(&base_ni->extent_lock);
if (unlikely(err)) {
ntfs_error(vol->sb, "Extent inode 0x%lx is not attached to "
"its base inode 0x%lx.", mft_no,
base_ni->mft_no);
BUG();
}
/*
* The extent inode is no longer attached to the base inode so no one
* can get a reference to it any more.
*/
/* Mark the mft record as not in use. */
m->flags &= ~MFT_RECORD_IN_USE;
/* Increment the sequence number, skipping zero, if it is not zero. */
old_seq_no = m->sequence_number;
seq_no = le16_to_cpu(old_seq_no);
if (seq_no == 0xffff)
seq_no = 1;
else if (seq_no)
seq_no++;
m->sequence_number = cpu_to_le16(seq_no);
/*
* Set the ntfs inode dirty and write it out. We do not need to worry
* about the base inode here since whatever caused the extent mft
* record to be freed is guaranteed to do it already.
*/
NInoSetDirty(ni);
err = write_mft_record(ni, m, 0);
if (unlikely(err)) {
ntfs_error(vol->sb, "Failed to write mft record 0x%lx, not "
"freeing.", mft_no);
goto rollback;
}
rollback_error:
/* Unmap and throw away the now freed extent inode. */
unmap_extent_mft_record(ni);
ntfs_clear_extent_inode(ni);
/* Clear the bit in the $MFT/$BITMAP corresponding to this record. */
down_write(&vol->mftbmp_lock);
err = ntfs_bitmap_clear_bit(vol->mftbmp_ino, mft_no);
up_write(&vol->mftbmp_lock);
if (unlikely(err)) {
/*
* The extent inode is gone but we failed to deallocate it in
* the mft bitmap. Just emit a warning and leave the volume
* dirty on umount.
*/
ntfs_error(vol->sb, "Failed to clear bit in mft bitmap.%s", es);
NVolSetErrors(vol);
}
return 0;
rollback:
/* Rollback what we did... */
mutex_lock(&base_ni->extent_lock);
extent_nis = base_ni->ext.extent_ntfs_inos;
if (!(base_ni->nr_extents & 3)) {
int new_size = (base_ni->nr_extents + 4) * sizeof(ntfs_inode*);
extent_nis = kmalloc(new_size, GFP_NOFS);
if (unlikely(!extent_nis)) {
ntfs_error(vol->sb, "Failed to allocate internal "
"buffer during rollback.%s", es);
mutex_unlock(&base_ni->extent_lock);
NVolSetErrors(vol);
goto rollback_error;
}
if (base_ni->nr_extents) {
BUG_ON(!base_ni->ext.extent_ntfs_inos);
memcpy(extent_nis, base_ni->ext.extent_ntfs_inos,
new_size - 4 * sizeof(ntfs_inode*));
kfree(base_ni->ext.extent_ntfs_inos);
}
base_ni->ext.extent_ntfs_inos = extent_nis;
}
m->flags |= MFT_RECORD_IN_USE;
m->sequence_number = old_seq_no;
extent_nis[base_ni->nr_extents++] = ni;
mutex_unlock(&base_ni->extent_lock);
mark_mft_record_dirty(ni);
return err;
}
#endif /* NTFS_RW */
| gpl-2.0 |
TheScarastic/kenzo | arch/alpha/boot/tools/objstrip.c | 12384 | 6095 | /*
* arch/alpha/boot/tools/objstrip.c
*
* Strip the object file headers/trailers from an executable (ELF or ECOFF).
*
* Copyright (C) 1996 David Mosberger-Tang.
*/
/*
* Converts an ECOFF or ELF object file into a bootable file. The
* object file must be a OMAGIC file (i.e., data and bss follow immediately
* behind the text). See DEC "Assembly Language Programmer's Guide"
* documentation for details. The SRM boot process is documented in
* the Alpha AXP Architecture Reference Manual, Second Edition by
* Richard L. Sites and Richard T. Witek.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <linux/a.out.h>
#include <linux/coff.h>
#include <linux/param.h>
#ifdef __ELF__
# include <linux/elf.h>
#endif
/* bootfile size must be multiple of BLOCK_SIZE: */
#define BLOCK_SIZE 512
const char * prog_name;
static void
usage (void)
{
fprintf(stderr,
"usage: %s [-v] -p file primary\n"
" %s [-vb] file [secondary]\n", prog_name, prog_name);
exit(1);
}
int
main (int argc, char *argv[])
{
size_t nwritten, tocopy, n, mem_size, fil_size, pad = 0;
int fd, ofd, i, j, verbose = 0, primary = 0;
char buf[8192], *inname;
struct exec * aout; /* includes file & aout header */
long offset;
#ifdef __ELF__
struct elfhdr *elf;
struct elf_phdr *elf_phdr; /* program header */
unsigned long long e_entry;
#endif
prog_name = argv[0];
for (i = 1; i < argc && argv[i][0] == '-'; ++i) {
for (j = 1; argv[i][j]; ++j) {
switch (argv[i][j]) {
case 'v':
verbose = ~verbose;
break;
case 'b':
pad = BLOCK_SIZE;
break;
case 'p':
primary = 1; /* make primary bootblock */
break;
}
}
}
if (i >= argc) {
usage();
}
inname = argv[i++];
fd = open(inname, O_RDONLY);
if (fd == -1) {
perror("open");
exit(1);
}
ofd = 1;
if (i < argc) {
ofd = open(argv[i++], O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (ofd == -1) {
perror("open");
exit(1);
}
}
if (primary) {
/* generate bootblock for primary loader */
unsigned long bb[64], sum = 0;
struct stat st;
off_t size;
int i;
if (ofd == 1) {
usage();
}
if (fstat(fd, &st) == -1) {
perror("fstat");
exit(1);
}
size = (st.st_size + BLOCK_SIZE - 1) & ~(BLOCK_SIZE - 1);
memset(bb, 0, sizeof(bb));
strcpy((char *) bb, "Linux SRM bootblock");
bb[60] = size / BLOCK_SIZE; /* count */
bb[61] = 1; /* starting sector # */
bb[62] = 0; /* flags---must be 0 */
for (i = 0; i < 63; ++i) {
sum += bb[i];
}
bb[63] = sum;
if (write(ofd, bb, sizeof(bb)) != sizeof(bb)) {
perror("boot-block write");
exit(1);
}
printf("%lu\n", size);
return 0;
}
/* read and inspect exec header: */
if (read(fd, buf, sizeof(buf)) < 0) {
perror("read");
exit(1);
}
#ifdef __ELF__
elf = (struct elfhdr *) buf;
if (elf->e_ident[0] == 0x7f && strncmp((char *)elf->e_ident + 1, "ELF", 3) == 0) {
if (elf->e_type != ET_EXEC) {
fprintf(stderr, "%s: %s is not an ELF executable\n",
prog_name, inname);
exit(1);
}
if (!elf_check_arch(elf)) {
fprintf(stderr, "%s: is not for this processor (e_machine=%d)\n",
prog_name, elf->e_machine);
exit(1);
}
if (elf->e_phnum != 1) {
fprintf(stderr,
"%s: %d program headers (forgot to link with -N?)\n",
prog_name, elf->e_phnum);
}
e_entry = elf->e_entry;
lseek(fd, elf->e_phoff, SEEK_SET);
if (read(fd, buf, sizeof(*elf_phdr)) != sizeof(*elf_phdr)) {
perror("read");
exit(1);
}
elf_phdr = (struct elf_phdr *) buf;
offset = elf_phdr->p_offset;
mem_size = elf_phdr->p_memsz;
fil_size = elf_phdr->p_filesz;
/* work around ELF bug: */
if (elf_phdr->p_vaddr < e_entry) {
unsigned long delta = e_entry - elf_phdr->p_vaddr;
offset += delta;
mem_size -= delta;
fil_size -= delta;
elf_phdr->p_vaddr += delta;
}
if (verbose) {
fprintf(stderr, "%s: extracting %#016lx-%#016lx (at %lx)\n",
prog_name, (long) elf_phdr->p_vaddr,
elf_phdr->p_vaddr + fil_size, offset);
}
} else
#endif
{
aout = (struct exec *) buf;
if (!(aout->fh.f_flags & COFF_F_EXEC)) {
fprintf(stderr, "%s: %s is not in executable format\n",
prog_name, inname);
exit(1);
}
if (aout->fh.f_opthdr != sizeof(aout->ah)) {
fprintf(stderr, "%s: %s has unexpected optional header size\n",
prog_name, inname);
exit(1);
}
if (N_MAGIC(*aout) != OMAGIC) {
fprintf(stderr, "%s: %s is not an OMAGIC file\n",
prog_name, inname);
exit(1);
}
offset = N_TXTOFF(*aout);
fil_size = aout->ah.tsize + aout->ah.dsize;
mem_size = fil_size + aout->ah.bsize;
if (verbose) {
fprintf(stderr, "%s: extracting %#016lx-%#016lx (at %lx)\n",
prog_name, aout->ah.text_start,
aout->ah.text_start + fil_size, offset);
}
}
if (lseek(fd, offset, SEEK_SET) != offset) {
perror("lseek");
exit(1);
}
if (verbose) {
fprintf(stderr, "%s: copying %lu byte from %s\n",
prog_name, (unsigned long) fil_size, inname);
}
tocopy = fil_size;
while (tocopy > 0) {
n = tocopy;
if (n > sizeof(buf)) {
n = sizeof(buf);
}
tocopy -= n;
if ((size_t) read(fd, buf, n) != n) {
perror("read");
exit(1);
}
do {
nwritten = write(ofd, buf, n);
if ((ssize_t) nwritten == -1) {
perror("write");
exit(1);
}
n -= nwritten;
} while (n > 0);
}
if (pad) {
mem_size = ((mem_size + pad - 1) / pad) * pad;
}
tocopy = mem_size - fil_size;
if (tocopy > 0) {
fprintf(stderr,
"%s: zero-filling bss and aligning to %lu with %lu bytes\n",
prog_name, pad, (unsigned long) tocopy);
memset(buf, 0x00, sizeof(buf));
do {
n = tocopy;
if (n > sizeof(buf)) {
n = sizeof(buf);
}
nwritten = write(ofd, buf, n);
if ((ssize_t) nwritten == -1) {
perror("write");
exit(1);
}
tocopy -= nwritten;
} while (tocopy > 0);
}
return 0;
}
| gpl-2.0 |
evnit/android_kernel_samsung_msm8660-common-10.2 | arch/arm/mach-msm/peripheral-reset.c | 97 | 3161 | /* Copyright (c) 2010-2011, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/kernel.h>
#include <linux/err.h>
#include <linux/io.h>
#include <linux/elf.h>
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/clk.h>
#include <linux/timer.h>
#include <linux/jiffies.h>
#include <linux/platform_device.h>
#include <asm/mach-types.h>
#include <mach/scm.h>
#include <mach/msm_iomap.h>
#include "peripheral-loader.h"
#include "scm-pas.h"
#define PPSS_RESET (MSM_CLK_CTL_BASE + 0x2594)
#define PPSS_PROC_CLK_CTL (MSM_CLK_CTL_BASE + 0x2588)
#define CLK_HALT_DFAB_STATE (MSM_CLK_CTL_BASE + 0x2FC8)
static int dsps_start;
static int init_image_dsps_trusted(struct pil_desc *pil, const u8 *metadata,
size_t size)
{
return pas_init_image(PAS_DSPS, metadata, size);
}
static int init_image_dsps_untrusted(struct pil_desc *pil, const u8 *metadata,
size_t size)
{
struct elf32_hdr *ehdr = (struct elf32_hdr *)metadata;
dsps_start = ehdr->e_entry;
/* Bring memory and bus interface out of reset */
__raw_writel(0x2, PPSS_RESET);
mb();
return 0;
}
static int verify_blob(struct pil_desc *pil, u32 phy_addr, size_t size)
{
return 0;
}
static int reset_dsps_untrusted(struct pil_desc *pil)
{
__raw_writel(0x10, PPSS_PROC_CLK_CTL);
while (__raw_readl(CLK_HALT_DFAB_STATE) & BIT(18))
cpu_relax();
/* Bring DSPS out of reset */
__raw_writel(0x0, PPSS_RESET);
return 0;
}
static int reset_dsps_trusted(struct pil_desc *pil)
{
return pas_auth_and_reset(PAS_DSPS);
}
static int shutdown_dsps_trusted(struct pil_desc *pil)
{
return pas_shutdown(PAS_DSPS);
}
static int shutdown_dsps_untrusted(struct pil_desc *pil)
{
__raw_writel(0x3, PPSS_RESET);
__raw_writel(0x0, PPSS_PROC_CLK_CTL);
return 0;
}
struct pil_reset_ops pil_dsps_ops = {
.init_image = init_image_dsps_untrusted,
.verify_blob = verify_blob,
.auth_and_reset = reset_dsps_untrusted,
.shutdown = shutdown_dsps_untrusted,
};
static struct platform_device pil_dsps = {
.name = "pil_dsps",
};
static struct pil_desc pil_dsps_desc = {
.name = "dsps",
.dev = &pil_dsps.dev,
.ops = &pil_dsps_ops,
};
static int __init msm_peripheral_reset_init(void)
{
if (pas_supported(PAS_DSPS) > 0) {
pil_dsps_ops.init_image = init_image_dsps_trusted;
pil_dsps_ops.auth_and_reset = reset_dsps_trusted;
pil_dsps_ops.shutdown = shutdown_dsps_trusted;
}
if (machine_is_msm8x60_fluid())
pil_dsps_desc.name = "dsps_fluid";
BUG_ON(platform_device_register(&pil_dsps));
BUG_ON(msm_pil_register(&pil_dsps_desc));
return 0;
}
arch_initcall(msm_peripheral_reset_init);
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("Validate and bring peripherals out of reset");
| gpl-2.0 |
cminyard/linux-live-app-coredump | net/sched/sch_cbq.c | 97 | 43035 | // SPDX-License-Identifier: GPL-2.0-or-later
/*
* net/sched/sch_cbq.c Class-Based Queueing discipline.
*
* Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/skbuff.h>
#include <net/netlink.h>
#include <net/pkt_sched.h>
#include <net/pkt_cls.h>
/* Class-Based Queueing (CBQ) algorithm.
=======================================
Sources: [1] Sally Floyd and Van Jacobson, "Link-sharing and Resource
Management Models for Packet Networks",
IEEE/ACM Transactions on Networking, Vol.3, No.4, 1995
[2] Sally Floyd, "Notes on CBQ and Guaranteed Service", 1995
[3] Sally Floyd, "Notes on Class-Based Queueing: Setting
Parameters", 1996
[4] Sally Floyd and Michael Speer, "Experimental Results
for Class-Based Queueing", 1998, not published.
-----------------------------------------------------------------------
Algorithm skeleton was taken from NS simulator cbq.cc.
If someone wants to check this code against the LBL version,
he should take into account that ONLY the skeleton was borrowed,
the implementation is different. Particularly:
--- The WRR algorithm is different. Our version looks more
reasonable (I hope) and works when quanta are allowed to be
less than MTU, which is always the case when real time classes
have small rates. Note, that the statement of [3] is
incomplete, delay may actually be estimated even if class
per-round allotment is less than MTU. Namely, if per-round
allotment is W*r_i, and r_1+...+r_k = r < 1
delay_i <= ([MTU/(W*r_i)]*W*r + W*r + k*MTU)/B
In the worst case we have IntServ estimate with D = W*r+k*MTU
and C = MTU*r. The proof (if correct at all) is trivial.
--- It seems that cbq-2.0 is not very accurate. At least, I cannot
interpret some places, which look like wrong translations
from NS. Anyone is advised to find these differences
and explain to me, why I am wrong 8).
--- Linux has no EOI event, so that we cannot estimate true class
idle time. Workaround is to consider the next dequeue event
as sign that previous packet is finished. This is wrong because of
internal device queueing, but on a permanently loaded link it is true.
Moreover, combined with clock integrator, this scheme looks
very close to an ideal solution. */
struct cbq_sched_data;
struct cbq_class {
struct Qdisc_class_common common;
struct cbq_class *next_alive; /* next class with backlog in this priority band */
/* Parameters */
unsigned char priority; /* class priority */
unsigned char priority2; /* priority to be used after overlimit */
unsigned char ewma_log; /* time constant for idle time calculation */
u32 defmap;
/* Link-sharing scheduler parameters */
long maxidle; /* Class parameters: see below. */
long offtime;
long minidle;
u32 avpkt;
struct qdisc_rate_table *R_tab;
/* General scheduler (WRR) parameters */
long allot;
long quantum; /* Allotment per WRR round */
long weight; /* Relative allotment: see below */
struct Qdisc *qdisc; /* Ptr to CBQ discipline */
struct cbq_class *split; /* Ptr to split node */
struct cbq_class *share; /* Ptr to LS parent in the class tree */
struct cbq_class *tparent; /* Ptr to tree parent in the class tree */
struct cbq_class *borrow; /* NULL if class is bandwidth limited;
parent otherwise */
struct cbq_class *sibling; /* Sibling chain */
struct cbq_class *children; /* Pointer to children chain */
struct Qdisc *q; /* Elementary queueing discipline */
/* Variables */
unsigned char cpriority; /* Effective priority */
unsigned char delayed;
unsigned char level; /* level of the class in hierarchy:
0 for leaf classes, and maximal
level of children + 1 for nodes.
*/
psched_time_t last; /* Last end of service */
psched_time_t undertime;
long avgidle;
long deficit; /* Saved deficit for WRR */
psched_time_t penalized;
struct gnet_stats_basic_sync bstats;
struct gnet_stats_queue qstats;
struct net_rate_estimator __rcu *rate_est;
struct tc_cbq_xstats xstats;
struct tcf_proto __rcu *filter_list;
struct tcf_block *block;
int filters;
struct cbq_class *defaults[TC_PRIO_MAX + 1];
};
struct cbq_sched_data {
struct Qdisc_class_hash clhash; /* Hash table of all classes */
int nclasses[TC_CBQ_MAXPRIO + 1];
unsigned int quanta[TC_CBQ_MAXPRIO + 1];
struct cbq_class link;
unsigned int activemask;
struct cbq_class *active[TC_CBQ_MAXPRIO + 1]; /* List of all classes
with backlog */
#ifdef CONFIG_NET_CLS_ACT
struct cbq_class *rx_class;
#endif
struct cbq_class *tx_class;
struct cbq_class *tx_borrowed;
int tx_len;
psched_time_t now; /* Cached timestamp */
unsigned int pmask;
struct hrtimer delay_timer;
struct qdisc_watchdog watchdog; /* Watchdog timer,
started when CBQ has
backlog, but cannot
transmit just now */
psched_tdiff_t wd_expires;
int toplevel;
u32 hgenerator;
};
#define L2T(cl, len) qdisc_l2t((cl)->R_tab, len)
static inline struct cbq_class *
cbq_class_lookup(struct cbq_sched_data *q, u32 classid)
{
struct Qdisc_class_common *clc;
clc = qdisc_class_find(&q->clhash, classid);
if (clc == NULL)
return NULL;
return container_of(clc, struct cbq_class, common);
}
#ifdef CONFIG_NET_CLS_ACT
static struct cbq_class *
cbq_reclassify(struct sk_buff *skb, struct cbq_class *this)
{
struct cbq_class *cl;
for (cl = this->tparent; cl; cl = cl->tparent) {
struct cbq_class *new = cl->defaults[TC_PRIO_BESTEFFORT];
if (new != NULL && new != this)
return new;
}
return NULL;
}
#endif
/* Classify packet. The procedure is pretty complicated, but
* it allows us to combine link sharing and priority scheduling
* transparently.
*
* Namely, you can put link sharing rules (f.e. route based) at root of CBQ,
* so that it resolves to split nodes. Then packets are classified
* by logical priority, or a more specific classifier may be attached
* to the split node.
*/
static struct cbq_class *
cbq_classify(struct sk_buff *skb, struct Qdisc *sch, int *qerr)
{
struct cbq_sched_data *q = qdisc_priv(sch);
struct cbq_class *head = &q->link;
struct cbq_class **defmap;
struct cbq_class *cl = NULL;
u32 prio = skb->priority;
struct tcf_proto *fl;
struct tcf_result res;
/*
* Step 1. If skb->priority points to one of our classes, use it.
*/
if (TC_H_MAJ(prio ^ sch->handle) == 0 &&
(cl = cbq_class_lookup(q, prio)) != NULL)
return cl;
*qerr = NET_XMIT_SUCCESS | __NET_XMIT_BYPASS;
for (;;) {
int result = 0;
defmap = head->defaults;
fl = rcu_dereference_bh(head->filter_list);
/*
* Step 2+n. Apply classifier.
*/
result = tcf_classify(skb, NULL, fl, &res, true);
if (!fl || result < 0)
goto fallback;
cl = (void *)res.class;
if (!cl) {
if (TC_H_MAJ(res.classid))
cl = cbq_class_lookup(q, res.classid);
else if ((cl = defmap[res.classid & TC_PRIO_MAX]) == NULL)
cl = defmap[TC_PRIO_BESTEFFORT];
if (cl == NULL)
goto fallback;
}
if (cl->level >= head->level)
goto fallback;
#ifdef CONFIG_NET_CLS_ACT
switch (result) {
case TC_ACT_QUEUED:
case TC_ACT_STOLEN:
case TC_ACT_TRAP:
*qerr = NET_XMIT_SUCCESS | __NET_XMIT_STOLEN;
fallthrough;
case TC_ACT_SHOT:
return NULL;
case TC_ACT_RECLASSIFY:
return cbq_reclassify(skb, cl);
}
#endif
if (cl->level == 0)
return cl;
/*
* Step 3+n. If classifier selected a link sharing class,
* apply agency specific classifier.
* Repeat this procedure until we hit a leaf node.
*/
head = cl;
}
fallback:
cl = head;
/*
* Step 4. No success...
*/
if (TC_H_MAJ(prio) == 0 &&
!(cl = head->defaults[prio & TC_PRIO_MAX]) &&
!(cl = head->defaults[TC_PRIO_BESTEFFORT]))
return head;
return cl;
}
/*
* A packet has just been enqueued on the empty class.
* cbq_activate_class adds it to the tail of active class list
* of its priority band.
*/
static inline void cbq_activate_class(struct cbq_class *cl)
{
struct cbq_sched_data *q = qdisc_priv(cl->qdisc);
int prio = cl->cpriority;
struct cbq_class *cl_tail;
cl_tail = q->active[prio];
q->active[prio] = cl;
if (cl_tail != NULL) {
cl->next_alive = cl_tail->next_alive;
cl_tail->next_alive = cl;
} else {
cl->next_alive = cl;
q->activemask |= (1<<prio);
}
}
/*
* Unlink class from active chain.
* Note that this same procedure is done directly in cbq_dequeue*
* during round-robin procedure.
*/
static void cbq_deactivate_class(struct cbq_class *this)
{
struct cbq_sched_data *q = qdisc_priv(this->qdisc);
int prio = this->cpriority;
struct cbq_class *cl;
struct cbq_class *cl_prev = q->active[prio];
do {
cl = cl_prev->next_alive;
if (cl == this) {
cl_prev->next_alive = cl->next_alive;
cl->next_alive = NULL;
if (cl == q->active[prio]) {
q->active[prio] = cl_prev;
if (cl == q->active[prio]) {
q->active[prio] = NULL;
q->activemask &= ~(1<<prio);
return;
}
}
return;
}
} while ((cl_prev = cl) != q->active[prio]);
}
static void
cbq_mark_toplevel(struct cbq_sched_data *q, struct cbq_class *cl)
{
int toplevel = q->toplevel;
if (toplevel > cl->level) {
psched_time_t now = psched_get_time();
do {
if (cl->undertime < now) {
q->toplevel = cl->level;
return;
}
} while ((cl = cl->borrow) != NULL && toplevel > cl->level);
}
}
static int
cbq_enqueue(struct sk_buff *skb, struct Qdisc *sch,
struct sk_buff **to_free)
{
struct cbq_sched_data *q = qdisc_priv(sch);
int ret;
struct cbq_class *cl = cbq_classify(skb, sch, &ret);
#ifdef CONFIG_NET_CLS_ACT
q->rx_class = cl;
#endif
if (cl == NULL) {
if (ret & __NET_XMIT_BYPASS)
qdisc_qstats_drop(sch);
__qdisc_drop(skb, to_free);
return ret;
}
ret = qdisc_enqueue(skb, cl->q, to_free);
if (ret == NET_XMIT_SUCCESS) {
sch->q.qlen++;
cbq_mark_toplevel(q, cl);
if (!cl->next_alive)
cbq_activate_class(cl);
return ret;
}
if (net_xmit_drop_count(ret)) {
qdisc_qstats_drop(sch);
cbq_mark_toplevel(q, cl);
cl->qstats.drops++;
}
return ret;
}
/* Overlimit action: penalize leaf class by adding offtime */
static void cbq_overlimit(struct cbq_class *cl)
{
struct cbq_sched_data *q = qdisc_priv(cl->qdisc);
psched_tdiff_t delay = cl->undertime - q->now;
if (!cl->delayed) {
delay += cl->offtime;
/*
* Class goes to sleep, so that it will have no
* chance to work avgidle. Let's forgive it 8)
*
* BTW cbq-2.0 has a crap in this
* place, apparently they forgot to shift it by cl->ewma_log.
*/
if (cl->avgidle < 0)
delay -= (-cl->avgidle) - ((-cl->avgidle) >> cl->ewma_log);
if (cl->avgidle < cl->minidle)
cl->avgidle = cl->minidle;
if (delay <= 0)
delay = 1;
cl->undertime = q->now + delay;
cl->xstats.overactions++;
cl->delayed = 1;
}
if (q->wd_expires == 0 || q->wd_expires > delay)
q->wd_expires = delay;
/* Dirty work! We must schedule wakeups based on
* real available rate, rather than leaf rate,
* which may be tiny (even zero).
*/
if (q->toplevel == TC_CBQ_MAXLEVEL) {
struct cbq_class *b;
psched_tdiff_t base_delay = q->wd_expires;
for (b = cl->borrow; b; b = b->borrow) {
delay = b->undertime - q->now;
if (delay < base_delay) {
if (delay <= 0)
delay = 1;
base_delay = delay;
}
}
q->wd_expires = base_delay;
}
}
static psched_tdiff_t cbq_undelay_prio(struct cbq_sched_data *q, int prio,
psched_time_t now)
{
struct cbq_class *cl;
struct cbq_class *cl_prev = q->active[prio];
psched_time_t sched = now;
if (cl_prev == NULL)
return 0;
do {
cl = cl_prev->next_alive;
if (now - cl->penalized > 0) {
cl_prev->next_alive = cl->next_alive;
cl->next_alive = NULL;
cl->cpriority = cl->priority;
cl->delayed = 0;
cbq_activate_class(cl);
if (cl == q->active[prio]) {
q->active[prio] = cl_prev;
if (cl == q->active[prio]) {
q->active[prio] = NULL;
return 0;
}
}
cl = cl_prev->next_alive;
} else if (sched - cl->penalized > 0)
sched = cl->penalized;
} while ((cl_prev = cl) != q->active[prio]);
return sched - now;
}
static enum hrtimer_restart cbq_undelay(struct hrtimer *timer)
{
struct cbq_sched_data *q = container_of(timer, struct cbq_sched_data,
delay_timer);
struct Qdisc *sch = q->watchdog.qdisc;
psched_time_t now;
psched_tdiff_t delay = 0;
unsigned int pmask;
now = psched_get_time();
pmask = q->pmask;
q->pmask = 0;
while (pmask) {
int prio = ffz(~pmask);
psched_tdiff_t tmp;
pmask &= ~(1<<prio);
tmp = cbq_undelay_prio(q, prio, now);
if (tmp > 0) {
q->pmask |= 1<<prio;
if (tmp < delay || delay == 0)
delay = tmp;
}
}
if (delay) {
ktime_t time;
time = 0;
time = ktime_add_ns(time, PSCHED_TICKS2NS(now + delay));
hrtimer_start(&q->delay_timer, time, HRTIMER_MODE_ABS_PINNED);
}
__netif_schedule(qdisc_root(sch));
return HRTIMER_NORESTART;
}
/*
* It is mission critical procedure.
*
* We "regenerate" toplevel cutoff, if transmitting class
* has backlog and it is not regulated. It is not part of
* original CBQ description, but looks more reasonable.
* Probably, it is wrong. This question needs further investigation.
*/
static inline void
cbq_update_toplevel(struct cbq_sched_data *q, struct cbq_class *cl,
struct cbq_class *borrowed)
{
if (cl && q->toplevel >= borrowed->level) {
if (cl->q->q.qlen > 1) {
do {
if (borrowed->undertime == PSCHED_PASTPERFECT) {
q->toplevel = borrowed->level;
return;
}
} while ((borrowed = borrowed->borrow) != NULL);
}
#if 0
/* It is not necessary now. Uncommenting it
will save CPU cycles, but decrease fairness.
*/
q->toplevel = TC_CBQ_MAXLEVEL;
#endif
}
}
static void
cbq_update(struct cbq_sched_data *q)
{
struct cbq_class *this = q->tx_class;
struct cbq_class *cl = this;
int len = q->tx_len;
psched_time_t now;
q->tx_class = NULL;
/* Time integrator. We calculate EOS time
* by adding expected packet transmission time.
*/
now = q->now + L2T(&q->link, len);
for ( ; cl; cl = cl->share) {
long avgidle = cl->avgidle;
long idle;
_bstats_update(&cl->bstats, len, 1);
/*
* (now - last) is total time between packet right edges.
* (last_pktlen/rate) is "virtual" busy time, so that
*
* idle = (now - last) - last_pktlen/rate
*/
idle = now - cl->last;
if ((unsigned long)idle > 128*1024*1024) {
avgidle = cl->maxidle;
} else {
idle -= L2T(cl, len);
/* true_avgidle := (1-W)*true_avgidle + W*idle,
* where W=2^{-ewma_log}. But cl->avgidle is scaled:
* cl->avgidle == true_avgidle/W,
* hence:
*/
avgidle += idle - (avgidle>>cl->ewma_log);
}
if (avgidle <= 0) {
/* Overlimit or at-limit */
if (avgidle < cl->minidle)
avgidle = cl->minidle;
cl->avgidle = avgidle;
/* Calculate expected time, when this class
* will be allowed to send.
* It will occur, when:
* (1-W)*true_avgidle + W*delay = 0, i.e.
* idle = (1/W - 1)*(-true_avgidle)
* or
* idle = (1 - W)*(-cl->avgidle);
*/
idle = (-avgidle) - ((-avgidle) >> cl->ewma_log);
/*
* That is not all.
* To maintain the rate allocated to the class,
* we add to undertime virtual clock,
* necessary to complete transmitted packet.
* (len/phys_bandwidth has been already passed
* to the moment of cbq_update)
*/
idle -= L2T(&q->link, len);
idle += L2T(cl, len);
cl->undertime = now + idle;
} else {
/* Underlimit */
cl->undertime = PSCHED_PASTPERFECT;
if (avgidle > cl->maxidle)
cl->avgidle = cl->maxidle;
else
cl->avgidle = avgidle;
}
if ((s64)(now - cl->last) > 0)
cl->last = now;
}
cbq_update_toplevel(q, this, q->tx_borrowed);
}
static inline struct cbq_class *
cbq_under_limit(struct cbq_class *cl)
{
struct cbq_sched_data *q = qdisc_priv(cl->qdisc);
struct cbq_class *this_cl = cl;
if (cl->tparent == NULL)
return cl;
if (cl->undertime == PSCHED_PASTPERFECT || q->now >= cl->undertime) {
cl->delayed = 0;
return cl;
}
do {
/* It is very suspicious place. Now overlimit
* action is generated for not bounded classes
* only if link is completely congested.
* Though it is in agree with ancestor-only paradigm,
* it looks very stupid. Particularly,
* it means that this chunk of code will either
* never be called or result in strong amplification
* of burstiness. Dangerous, silly, and, however,
* no another solution exists.
*/
cl = cl->borrow;
if (!cl) {
this_cl->qstats.overlimits++;
cbq_overlimit(this_cl);
return NULL;
}
if (cl->level > q->toplevel)
return NULL;
} while (cl->undertime != PSCHED_PASTPERFECT && q->now < cl->undertime);
cl->delayed = 0;
return cl;
}
static inline struct sk_buff *
cbq_dequeue_prio(struct Qdisc *sch, int prio)
{
struct cbq_sched_data *q = qdisc_priv(sch);
struct cbq_class *cl_tail, *cl_prev, *cl;
struct sk_buff *skb;
int deficit;
cl_tail = cl_prev = q->active[prio];
cl = cl_prev->next_alive;
do {
deficit = 0;
/* Start round */
do {
struct cbq_class *borrow = cl;
if (cl->q->q.qlen &&
(borrow = cbq_under_limit(cl)) == NULL)
goto skip_class;
if (cl->deficit <= 0) {
/* Class exhausted its allotment per
* this round. Switch to the next one.
*/
deficit = 1;
cl->deficit += cl->quantum;
goto next_class;
}
skb = cl->q->dequeue(cl->q);
/* Class did not give us any skb :-(
* It could occur even if cl->q->q.qlen != 0
* f.e. if cl->q == "tbf"
*/
if (skb == NULL)
goto skip_class;
cl->deficit -= qdisc_pkt_len(skb);
q->tx_class = cl;
q->tx_borrowed = borrow;
if (borrow != cl) {
#ifndef CBQ_XSTATS_BORROWS_BYTES
borrow->xstats.borrows++;
cl->xstats.borrows++;
#else
borrow->xstats.borrows += qdisc_pkt_len(skb);
cl->xstats.borrows += qdisc_pkt_len(skb);
#endif
}
q->tx_len = qdisc_pkt_len(skb);
if (cl->deficit <= 0) {
q->active[prio] = cl;
cl = cl->next_alive;
cl->deficit += cl->quantum;
}
return skb;
skip_class:
if (cl->q->q.qlen == 0 || prio != cl->cpriority) {
/* Class is empty or penalized.
* Unlink it from active chain.
*/
cl_prev->next_alive = cl->next_alive;
cl->next_alive = NULL;
/* Did cl_tail point to it? */
if (cl == cl_tail) {
/* Repair it! */
cl_tail = cl_prev;
/* Was it the last class in this band? */
if (cl == cl_tail) {
/* Kill the band! */
q->active[prio] = NULL;
q->activemask &= ~(1<<prio);
if (cl->q->q.qlen)
cbq_activate_class(cl);
return NULL;
}
q->active[prio] = cl_tail;
}
if (cl->q->q.qlen)
cbq_activate_class(cl);
cl = cl_prev;
}
next_class:
cl_prev = cl;
cl = cl->next_alive;
} while (cl_prev != cl_tail);
} while (deficit);
q->active[prio] = cl_prev;
return NULL;
}
static inline struct sk_buff *
cbq_dequeue_1(struct Qdisc *sch)
{
struct cbq_sched_data *q = qdisc_priv(sch);
struct sk_buff *skb;
unsigned int activemask;
activemask = q->activemask & 0xFF;
while (activemask) {
int prio = ffz(~activemask);
activemask &= ~(1<<prio);
skb = cbq_dequeue_prio(sch, prio);
if (skb)
return skb;
}
return NULL;
}
static struct sk_buff *
cbq_dequeue(struct Qdisc *sch)
{
struct sk_buff *skb;
struct cbq_sched_data *q = qdisc_priv(sch);
psched_time_t now;
now = psched_get_time();
if (q->tx_class)
cbq_update(q);
q->now = now;
for (;;) {
q->wd_expires = 0;
skb = cbq_dequeue_1(sch);
if (skb) {
qdisc_bstats_update(sch, skb);
sch->q.qlen--;
return skb;
}
/* All the classes are overlimit.
*
* It is possible, if:
*
* 1. Scheduler is empty.
* 2. Toplevel cutoff inhibited borrowing.
* 3. Root class is overlimit.
*
* Reset 2d and 3d conditions and retry.
*
* Note, that NS and cbq-2.0 are buggy, peeking
* an arbitrary class is appropriate for ancestor-only
* sharing, but not for toplevel algorithm.
*
* Our version is better, but slower, because it requires
* two passes, but it is unavoidable with top-level sharing.
*/
if (q->toplevel == TC_CBQ_MAXLEVEL &&
q->link.undertime == PSCHED_PASTPERFECT)
break;
q->toplevel = TC_CBQ_MAXLEVEL;
q->link.undertime = PSCHED_PASTPERFECT;
}
/* No packets in scheduler or nobody wants to give them to us :-(
* Sigh... start watchdog timer in the last case.
*/
if (sch->q.qlen) {
qdisc_qstats_overlimit(sch);
if (q->wd_expires)
qdisc_watchdog_schedule(&q->watchdog,
now + q->wd_expires);
}
return NULL;
}
/* CBQ class maintenance routines */
static void cbq_adjust_levels(struct cbq_class *this)
{
if (this == NULL)
return;
do {
int level = 0;
struct cbq_class *cl;
cl = this->children;
if (cl) {
do {
if (cl->level > level)
level = cl->level;
} while ((cl = cl->sibling) != this->children);
}
this->level = level + 1;
} while ((this = this->tparent) != NULL);
}
static void cbq_normalize_quanta(struct cbq_sched_data *q, int prio)
{
struct cbq_class *cl;
unsigned int h;
if (q->quanta[prio] == 0)
return;
for (h = 0; h < q->clhash.hashsize; h++) {
hlist_for_each_entry(cl, &q->clhash.hash[h], common.hnode) {
/* BUGGGG... Beware! This expression suffer of
* arithmetic overflows!
*/
if (cl->priority == prio) {
cl->quantum = (cl->weight*cl->allot*q->nclasses[prio])/
q->quanta[prio];
}
if (cl->quantum <= 0 ||
cl->quantum > 32*qdisc_dev(cl->qdisc)->mtu) {
pr_warn("CBQ: class %08x has bad quantum==%ld, repaired.\n",
cl->common.classid, cl->quantum);
cl->quantum = qdisc_dev(cl->qdisc)->mtu/2 + 1;
}
}
}
}
static void cbq_sync_defmap(struct cbq_class *cl)
{
struct cbq_sched_data *q = qdisc_priv(cl->qdisc);
struct cbq_class *split = cl->split;
unsigned int h;
int i;
if (split == NULL)
return;
for (i = 0; i <= TC_PRIO_MAX; i++) {
if (split->defaults[i] == cl && !(cl->defmap & (1<<i)))
split->defaults[i] = NULL;
}
for (i = 0; i <= TC_PRIO_MAX; i++) {
int level = split->level;
if (split->defaults[i])
continue;
for (h = 0; h < q->clhash.hashsize; h++) {
struct cbq_class *c;
hlist_for_each_entry(c, &q->clhash.hash[h],
common.hnode) {
if (c->split == split && c->level < level &&
c->defmap & (1<<i)) {
split->defaults[i] = c;
level = c->level;
}
}
}
}
}
static void cbq_change_defmap(struct cbq_class *cl, u32 splitid, u32 def, u32 mask)
{
struct cbq_class *split = NULL;
if (splitid == 0) {
split = cl->split;
if (!split)
return;
splitid = split->common.classid;
}
if (split == NULL || split->common.classid != splitid) {
for (split = cl->tparent; split; split = split->tparent)
if (split->common.classid == splitid)
break;
}
if (split == NULL)
return;
if (cl->split != split) {
cl->defmap = 0;
cbq_sync_defmap(cl);
cl->split = split;
cl->defmap = def & mask;
} else
cl->defmap = (cl->defmap & ~mask) | (def & mask);
cbq_sync_defmap(cl);
}
static void cbq_unlink_class(struct cbq_class *this)
{
struct cbq_class *cl, **clp;
struct cbq_sched_data *q = qdisc_priv(this->qdisc);
qdisc_class_hash_remove(&q->clhash, &this->common);
if (this->tparent) {
clp = &this->sibling;
cl = *clp;
do {
if (cl == this) {
*clp = cl->sibling;
break;
}
clp = &cl->sibling;
} while ((cl = *clp) != this->sibling);
if (this->tparent->children == this) {
this->tparent->children = this->sibling;
if (this->sibling == this)
this->tparent->children = NULL;
}
} else {
WARN_ON(this->sibling != this);
}
}
static void cbq_link_class(struct cbq_class *this)
{
struct cbq_sched_data *q = qdisc_priv(this->qdisc);
struct cbq_class *parent = this->tparent;
this->sibling = this;
qdisc_class_hash_insert(&q->clhash, &this->common);
if (parent == NULL)
return;
if (parent->children == NULL) {
parent->children = this;
} else {
this->sibling = parent->children->sibling;
parent->children->sibling = this;
}
}
static void
cbq_reset(struct Qdisc *sch)
{
struct cbq_sched_data *q = qdisc_priv(sch);
struct cbq_class *cl;
int prio;
unsigned int h;
q->activemask = 0;
q->pmask = 0;
q->tx_class = NULL;
q->tx_borrowed = NULL;
qdisc_watchdog_cancel(&q->watchdog);
hrtimer_cancel(&q->delay_timer);
q->toplevel = TC_CBQ_MAXLEVEL;
q->now = psched_get_time();
for (prio = 0; prio <= TC_CBQ_MAXPRIO; prio++)
q->active[prio] = NULL;
for (h = 0; h < q->clhash.hashsize; h++) {
hlist_for_each_entry(cl, &q->clhash.hash[h], common.hnode) {
qdisc_reset(cl->q);
cl->next_alive = NULL;
cl->undertime = PSCHED_PASTPERFECT;
cl->avgidle = cl->maxidle;
cl->deficit = cl->quantum;
cl->cpriority = cl->priority;
}
}
sch->q.qlen = 0;
}
static int cbq_set_lss(struct cbq_class *cl, struct tc_cbq_lssopt *lss)
{
if (lss->change & TCF_CBQ_LSS_FLAGS) {
cl->share = (lss->flags & TCF_CBQ_LSS_ISOLATED) ? NULL : cl->tparent;
cl->borrow = (lss->flags & TCF_CBQ_LSS_BOUNDED) ? NULL : cl->tparent;
}
if (lss->change & TCF_CBQ_LSS_EWMA)
cl->ewma_log = lss->ewma_log;
if (lss->change & TCF_CBQ_LSS_AVPKT)
cl->avpkt = lss->avpkt;
if (lss->change & TCF_CBQ_LSS_MINIDLE)
cl->minidle = -(long)lss->minidle;
if (lss->change & TCF_CBQ_LSS_MAXIDLE) {
cl->maxidle = lss->maxidle;
cl->avgidle = lss->maxidle;
}
if (lss->change & TCF_CBQ_LSS_OFFTIME)
cl->offtime = lss->offtime;
return 0;
}
static void cbq_rmprio(struct cbq_sched_data *q, struct cbq_class *cl)
{
q->nclasses[cl->priority]--;
q->quanta[cl->priority] -= cl->weight;
cbq_normalize_quanta(q, cl->priority);
}
static void cbq_addprio(struct cbq_sched_data *q, struct cbq_class *cl)
{
q->nclasses[cl->priority]++;
q->quanta[cl->priority] += cl->weight;
cbq_normalize_quanta(q, cl->priority);
}
static int cbq_set_wrr(struct cbq_class *cl, struct tc_cbq_wrropt *wrr)
{
struct cbq_sched_data *q = qdisc_priv(cl->qdisc);
if (wrr->allot)
cl->allot = wrr->allot;
if (wrr->weight)
cl->weight = wrr->weight;
if (wrr->priority) {
cl->priority = wrr->priority - 1;
cl->cpriority = cl->priority;
if (cl->priority >= cl->priority2)
cl->priority2 = TC_CBQ_MAXPRIO - 1;
}
cbq_addprio(q, cl);
return 0;
}
static int cbq_set_fopt(struct cbq_class *cl, struct tc_cbq_fopt *fopt)
{
cbq_change_defmap(cl, fopt->split, fopt->defmap, fopt->defchange);
return 0;
}
static const struct nla_policy cbq_policy[TCA_CBQ_MAX + 1] = {
[TCA_CBQ_LSSOPT] = { .len = sizeof(struct tc_cbq_lssopt) },
[TCA_CBQ_WRROPT] = { .len = sizeof(struct tc_cbq_wrropt) },
[TCA_CBQ_FOPT] = { .len = sizeof(struct tc_cbq_fopt) },
[TCA_CBQ_OVL_STRATEGY] = { .len = sizeof(struct tc_cbq_ovl) },
[TCA_CBQ_RATE] = { .len = sizeof(struct tc_ratespec) },
[TCA_CBQ_RTAB] = { .type = NLA_BINARY, .len = TC_RTAB_SIZE },
[TCA_CBQ_POLICE] = { .len = sizeof(struct tc_cbq_police) },
};
static int cbq_opt_parse(struct nlattr *tb[TCA_CBQ_MAX + 1],
struct nlattr *opt,
struct netlink_ext_ack *extack)
{
int err;
if (!opt) {
NL_SET_ERR_MSG(extack, "CBQ options are required for this operation");
return -EINVAL;
}
err = nla_parse_nested_deprecated(tb, TCA_CBQ_MAX, opt,
cbq_policy, extack);
if (err < 0)
return err;
if (tb[TCA_CBQ_WRROPT]) {
const struct tc_cbq_wrropt *wrr = nla_data(tb[TCA_CBQ_WRROPT]);
if (wrr->priority > TC_CBQ_MAXPRIO) {
NL_SET_ERR_MSG(extack, "priority is bigger than TC_CBQ_MAXPRIO");
err = -EINVAL;
}
}
return err;
}
static int cbq_init(struct Qdisc *sch, struct nlattr *opt,
struct netlink_ext_ack *extack)
{
struct cbq_sched_data *q = qdisc_priv(sch);
struct nlattr *tb[TCA_CBQ_MAX + 1];
struct tc_ratespec *r;
int err;
qdisc_watchdog_init(&q->watchdog, sch);
hrtimer_init(&q->delay_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED);
q->delay_timer.function = cbq_undelay;
err = cbq_opt_parse(tb, opt, extack);
if (err < 0)
return err;
if (!tb[TCA_CBQ_RTAB] || !tb[TCA_CBQ_RATE]) {
NL_SET_ERR_MSG(extack, "Rate specification missing or incomplete");
return -EINVAL;
}
r = nla_data(tb[TCA_CBQ_RATE]);
q->link.R_tab = qdisc_get_rtab(r, tb[TCA_CBQ_RTAB], extack);
if (!q->link.R_tab)
return -EINVAL;
err = tcf_block_get(&q->link.block, &q->link.filter_list, sch, extack);
if (err)
goto put_rtab;
err = qdisc_class_hash_init(&q->clhash);
if (err < 0)
goto put_block;
q->link.sibling = &q->link;
q->link.common.classid = sch->handle;
q->link.qdisc = sch;
q->link.q = qdisc_create_dflt(sch->dev_queue, &pfifo_qdisc_ops,
sch->handle, NULL);
if (!q->link.q)
q->link.q = &noop_qdisc;
else
qdisc_hash_add(q->link.q, true);
q->link.priority = TC_CBQ_MAXPRIO - 1;
q->link.priority2 = TC_CBQ_MAXPRIO - 1;
q->link.cpriority = TC_CBQ_MAXPRIO - 1;
q->link.allot = psched_mtu(qdisc_dev(sch));
q->link.quantum = q->link.allot;
q->link.weight = q->link.R_tab->rate.rate;
q->link.ewma_log = TC_CBQ_DEF_EWMA;
q->link.avpkt = q->link.allot/2;
q->link.minidle = -0x7FFFFFFF;
q->toplevel = TC_CBQ_MAXLEVEL;
q->now = psched_get_time();
cbq_link_class(&q->link);
if (tb[TCA_CBQ_LSSOPT])
cbq_set_lss(&q->link, nla_data(tb[TCA_CBQ_LSSOPT]));
cbq_addprio(q, &q->link);
return 0;
put_block:
tcf_block_put(q->link.block);
put_rtab:
qdisc_put_rtab(q->link.R_tab);
return err;
}
static int cbq_dump_rate(struct sk_buff *skb, struct cbq_class *cl)
{
unsigned char *b = skb_tail_pointer(skb);
if (nla_put(skb, TCA_CBQ_RATE, sizeof(cl->R_tab->rate), &cl->R_tab->rate))
goto nla_put_failure;
return skb->len;
nla_put_failure:
nlmsg_trim(skb, b);
return -1;
}
static int cbq_dump_lss(struct sk_buff *skb, struct cbq_class *cl)
{
unsigned char *b = skb_tail_pointer(skb);
struct tc_cbq_lssopt opt;
opt.flags = 0;
if (cl->borrow == NULL)
opt.flags |= TCF_CBQ_LSS_BOUNDED;
if (cl->share == NULL)
opt.flags |= TCF_CBQ_LSS_ISOLATED;
opt.ewma_log = cl->ewma_log;
opt.level = cl->level;
opt.avpkt = cl->avpkt;
opt.maxidle = cl->maxidle;
opt.minidle = (u32)(-cl->minidle);
opt.offtime = cl->offtime;
opt.change = ~0;
if (nla_put(skb, TCA_CBQ_LSSOPT, sizeof(opt), &opt))
goto nla_put_failure;
return skb->len;
nla_put_failure:
nlmsg_trim(skb, b);
return -1;
}
static int cbq_dump_wrr(struct sk_buff *skb, struct cbq_class *cl)
{
unsigned char *b = skb_tail_pointer(skb);
struct tc_cbq_wrropt opt;
memset(&opt, 0, sizeof(opt));
opt.flags = 0;
opt.allot = cl->allot;
opt.priority = cl->priority + 1;
opt.cpriority = cl->cpriority + 1;
opt.weight = cl->weight;
if (nla_put(skb, TCA_CBQ_WRROPT, sizeof(opt), &opt))
goto nla_put_failure;
return skb->len;
nla_put_failure:
nlmsg_trim(skb, b);
return -1;
}
static int cbq_dump_fopt(struct sk_buff *skb, struct cbq_class *cl)
{
unsigned char *b = skb_tail_pointer(skb);
struct tc_cbq_fopt opt;
if (cl->split || cl->defmap) {
opt.split = cl->split ? cl->split->common.classid : 0;
opt.defmap = cl->defmap;
opt.defchange = ~0;
if (nla_put(skb, TCA_CBQ_FOPT, sizeof(opt), &opt))
goto nla_put_failure;
}
return skb->len;
nla_put_failure:
nlmsg_trim(skb, b);
return -1;
}
static int cbq_dump_attr(struct sk_buff *skb, struct cbq_class *cl)
{
if (cbq_dump_lss(skb, cl) < 0 ||
cbq_dump_rate(skb, cl) < 0 ||
cbq_dump_wrr(skb, cl) < 0 ||
cbq_dump_fopt(skb, cl) < 0)
return -1;
return 0;
}
static int cbq_dump(struct Qdisc *sch, struct sk_buff *skb)
{
struct cbq_sched_data *q = qdisc_priv(sch);
struct nlattr *nest;
nest = nla_nest_start_noflag(skb, TCA_OPTIONS);
if (nest == NULL)
goto nla_put_failure;
if (cbq_dump_attr(skb, &q->link) < 0)
goto nla_put_failure;
return nla_nest_end(skb, nest);
nla_put_failure:
nla_nest_cancel(skb, nest);
return -1;
}
static int
cbq_dump_stats(struct Qdisc *sch, struct gnet_dump *d)
{
struct cbq_sched_data *q = qdisc_priv(sch);
q->link.xstats.avgidle = q->link.avgidle;
return gnet_stats_copy_app(d, &q->link.xstats, sizeof(q->link.xstats));
}
static int
cbq_dump_class(struct Qdisc *sch, unsigned long arg,
struct sk_buff *skb, struct tcmsg *tcm)
{
struct cbq_class *cl = (struct cbq_class *)arg;
struct nlattr *nest;
if (cl->tparent)
tcm->tcm_parent = cl->tparent->common.classid;
else
tcm->tcm_parent = TC_H_ROOT;
tcm->tcm_handle = cl->common.classid;
tcm->tcm_info = cl->q->handle;
nest = nla_nest_start_noflag(skb, TCA_OPTIONS);
if (nest == NULL)
goto nla_put_failure;
if (cbq_dump_attr(skb, cl) < 0)
goto nla_put_failure;
return nla_nest_end(skb, nest);
nla_put_failure:
nla_nest_cancel(skb, nest);
return -1;
}
static int
cbq_dump_class_stats(struct Qdisc *sch, unsigned long arg,
struct gnet_dump *d)
{
struct cbq_sched_data *q = qdisc_priv(sch);
struct cbq_class *cl = (struct cbq_class *)arg;
__u32 qlen;
cl->xstats.avgidle = cl->avgidle;
cl->xstats.undertime = 0;
qdisc_qstats_qlen_backlog(cl->q, &qlen, &cl->qstats.backlog);
if (cl->undertime != PSCHED_PASTPERFECT)
cl->xstats.undertime = cl->undertime - q->now;
if (gnet_stats_copy_basic(d, NULL, &cl->bstats, true) < 0 ||
gnet_stats_copy_rate_est(d, &cl->rate_est) < 0 ||
gnet_stats_copy_queue(d, NULL, &cl->qstats, qlen) < 0)
return -1;
return gnet_stats_copy_app(d, &cl->xstats, sizeof(cl->xstats));
}
static int cbq_graft(struct Qdisc *sch, unsigned long arg, struct Qdisc *new,
struct Qdisc **old, struct netlink_ext_ack *extack)
{
struct cbq_class *cl = (struct cbq_class *)arg;
if (new == NULL) {
new = qdisc_create_dflt(sch->dev_queue, &pfifo_qdisc_ops,
cl->common.classid, extack);
if (new == NULL)
return -ENOBUFS;
}
*old = qdisc_replace(sch, new, &cl->q);
return 0;
}
static struct Qdisc *cbq_leaf(struct Qdisc *sch, unsigned long arg)
{
struct cbq_class *cl = (struct cbq_class *)arg;
return cl->q;
}
static void cbq_qlen_notify(struct Qdisc *sch, unsigned long arg)
{
struct cbq_class *cl = (struct cbq_class *)arg;
cbq_deactivate_class(cl);
}
static unsigned long cbq_find(struct Qdisc *sch, u32 classid)
{
struct cbq_sched_data *q = qdisc_priv(sch);
return (unsigned long)cbq_class_lookup(q, classid);
}
static void cbq_destroy_class(struct Qdisc *sch, struct cbq_class *cl)
{
struct cbq_sched_data *q = qdisc_priv(sch);
WARN_ON(cl->filters);
tcf_block_put(cl->block);
qdisc_put(cl->q);
qdisc_put_rtab(cl->R_tab);
gen_kill_estimator(&cl->rate_est);
if (cl != &q->link)
kfree(cl);
}
static void cbq_destroy(struct Qdisc *sch)
{
struct cbq_sched_data *q = qdisc_priv(sch);
struct hlist_node *next;
struct cbq_class *cl;
unsigned int h;
#ifdef CONFIG_NET_CLS_ACT
q->rx_class = NULL;
#endif
/*
* Filters must be destroyed first because we don't destroy the
* classes from root to leafs which means that filters can still
* be bound to classes which have been destroyed already. --TGR '04
*/
for (h = 0; h < q->clhash.hashsize; h++) {
hlist_for_each_entry(cl, &q->clhash.hash[h], common.hnode) {
tcf_block_put(cl->block);
cl->block = NULL;
}
}
for (h = 0; h < q->clhash.hashsize; h++) {
hlist_for_each_entry_safe(cl, next, &q->clhash.hash[h],
common.hnode)
cbq_destroy_class(sch, cl);
}
qdisc_class_hash_destroy(&q->clhash);
}
static int
cbq_change_class(struct Qdisc *sch, u32 classid, u32 parentid, struct nlattr **tca,
unsigned long *arg, struct netlink_ext_ack *extack)
{
int err;
struct cbq_sched_data *q = qdisc_priv(sch);
struct cbq_class *cl = (struct cbq_class *)*arg;
struct nlattr *opt = tca[TCA_OPTIONS];
struct nlattr *tb[TCA_CBQ_MAX + 1];
struct cbq_class *parent;
struct qdisc_rate_table *rtab = NULL;
err = cbq_opt_parse(tb, opt, extack);
if (err < 0)
return err;
if (tb[TCA_CBQ_OVL_STRATEGY] || tb[TCA_CBQ_POLICE]) {
NL_SET_ERR_MSG(extack, "Neither overlimit strategy nor policing attributes can be used for changing class params");
return -EOPNOTSUPP;
}
if (cl) {
/* Check parent */
if (parentid) {
if (cl->tparent &&
cl->tparent->common.classid != parentid) {
NL_SET_ERR_MSG(extack, "Invalid parent id");
return -EINVAL;
}
if (!cl->tparent && parentid != TC_H_ROOT) {
NL_SET_ERR_MSG(extack, "Parent must be root");
return -EINVAL;
}
}
if (tb[TCA_CBQ_RATE]) {
rtab = qdisc_get_rtab(nla_data(tb[TCA_CBQ_RATE]),
tb[TCA_CBQ_RTAB], extack);
if (rtab == NULL)
return -EINVAL;
}
if (tca[TCA_RATE]) {
err = gen_replace_estimator(&cl->bstats, NULL,
&cl->rate_est,
NULL,
true,
tca[TCA_RATE]);
if (err) {
NL_SET_ERR_MSG(extack, "Failed to replace specified rate estimator");
qdisc_put_rtab(rtab);
return err;
}
}
/* Change class parameters */
sch_tree_lock(sch);
if (cl->next_alive != NULL)
cbq_deactivate_class(cl);
if (rtab) {
qdisc_put_rtab(cl->R_tab);
cl->R_tab = rtab;
}
if (tb[TCA_CBQ_LSSOPT])
cbq_set_lss(cl, nla_data(tb[TCA_CBQ_LSSOPT]));
if (tb[TCA_CBQ_WRROPT]) {
cbq_rmprio(q, cl);
cbq_set_wrr(cl, nla_data(tb[TCA_CBQ_WRROPT]));
}
if (tb[TCA_CBQ_FOPT])
cbq_set_fopt(cl, nla_data(tb[TCA_CBQ_FOPT]));
if (cl->q->q.qlen)
cbq_activate_class(cl);
sch_tree_unlock(sch);
return 0;
}
if (parentid == TC_H_ROOT)
return -EINVAL;
if (!tb[TCA_CBQ_WRROPT] || !tb[TCA_CBQ_RATE] || !tb[TCA_CBQ_LSSOPT]) {
NL_SET_ERR_MSG(extack, "One of the following attributes MUST be specified: WRR, rate or link sharing");
return -EINVAL;
}
rtab = qdisc_get_rtab(nla_data(tb[TCA_CBQ_RATE]), tb[TCA_CBQ_RTAB],
extack);
if (rtab == NULL)
return -EINVAL;
if (classid) {
err = -EINVAL;
if (TC_H_MAJ(classid ^ sch->handle) ||
cbq_class_lookup(q, classid)) {
NL_SET_ERR_MSG(extack, "Specified class not found");
goto failure;
}
} else {
int i;
classid = TC_H_MAKE(sch->handle, 0x8000);
for (i = 0; i < 0x8000; i++) {
if (++q->hgenerator >= 0x8000)
q->hgenerator = 1;
if (cbq_class_lookup(q, classid|q->hgenerator) == NULL)
break;
}
err = -ENOSR;
if (i >= 0x8000) {
NL_SET_ERR_MSG(extack, "Unable to generate classid");
goto failure;
}
classid = classid|q->hgenerator;
}
parent = &q->link;
if (parentid) {
parent = cbq_class_lookup(q, parentid);
err = -EINVAL;
if (!parent) {
NL_SET_ERR_MSG(extack, "Failed to find parentid");
goto failure;
}
}
err = -ENOBUFS;
cl = kzalloc(sizeof(*cl), GFP_KERNEL);
if (cl == NULL)
goto failure;
gnet_stats_basic_sync_init(&cl->bstats);
err = tcf_block_get(&cl->block, &cl->filter_list, sch, extack);
if (err) {
kfree(cl);
goto failure;
}
if (tca[TCA_RATE]) {
err = gen_new_estimator(&cl->bstats, NULL, &cl->rate_est,
NULL, true, tca[TCA_RATE]);
if (err) {
NL_SET_ERR_MSG(extack, "Couldn't create new estimator");
tcf_block_put(cl->block);
kfree(cl);
goto failure;
}
}
cl->R_tab = rtab;
rtab = NULL;
cl->q = qdisc_create_dflt(sch->dev_queue, &pfifo_qdisc_ops, classid,
NULL);
if (!cl->q)
cl->q = &noop_qdisc;
else
qdisc_hash_add(cl->q, true);
cl->common.classid = classid;
cl->tparent = parent;
cl->qdisc = sch;
cl->allot = parent->allot;
cl->quantum = cl->allot;
cl->weight = cl->R_tab->rate.rate;
sch_tree_lock(sch);
cbq_link_class(cl);
cl->borrow = cl->tparent;
if (cl->tparent != &q->link)
cl->share = cl->tparent;
cbq_adjust_levels(parent);
cl->minidle = -0x7FFFFFFF;
cbq_set_lss(cl, nla_data(tb[TCA_CBQ_LSSOPT]));
cbq_set_wrr(cl, nla_data(tb[TCA_CBQ_WRROPT]));
if (cl->ewma_log == 0)
cl->ewma_log = q->link.ewma_log;
if (cl->maxidle == 0)
cl->maxidle = q->link.maxidle;
if (cl->avpkt == 0)
cl->avpkt = q->link.avpkt;
if (tb[TCA_CBQ_FOPT])
cbq_set_fopt(cl, nla_data(tb[TCA_CBQ_FOPT]));
sch_tree_unlock(sch);
qdisc_class_hash_grow(sch, &q->clhash);
*arg = (unsigned long)cl;
return 0;
failure:
qdisc_put_rtab(rtab);
return err;
}
static int cbq_delete(struct Qdisc *sch, unsigned long arg,
struct netlink_ext_ack *extack)
{
struct cbq_sched_data *q = qdisc_priv(sch);
struct cbq_class *cl = (struct cbq_class *)arg;
if (cl->filters || cl->children || cl == &q->link)
return -EBUSY;
sch_tree_lock(sch);
qdisc_purge_queue(cl->q);
if (cl->next_alive)
cbq_deactivate_class(cl);
if (q->tx_borrowed == cl)
q->tx_borrowed = q->tx_class;
if (q->tx_class == cl) {
q->tx_class = NULL;
q->tx_borrowed = NULL;
}
#ifdef CONFIG_NET_CLS_ACT
if (q->rx_class == cl)
q->rx_class = NULL;
#endif
cbq_unlink_class(cl);
cbq_adjust_levels(cl->tparent);
cl->defmap = 0;
cbq_sync_defmap(cl);
cbq_rmprio(q, cl);
sch_tree_unlock(sch);
cbq_destroy_class(sch, cl);
return 0;
}
static struct tcf_block *cbq_tcf_block(struct Qdisc *sch, unsigned long arg,
struct netlink_ext_ack *extack)
{
struct cbq_sched_data *q = qdisc_priv(sch);
struct cbq_class *cl = (struct cbq_class *)arg;
if (cl == NULL)
cl = &q->link;
return cl->block;
}
static unsigned long cbq_bind_filter(struct Qdisc *sch, unsigned long parent,
u32 classid)
{
struct cbq_sched_data *q = qdisc_priv(sch);
struct cbq_class *p = (struct cbq_class *)parent;
struct cbq_class *cl = cbq_class_lookup(q, classid);
if (cl) {
if (p && p->level <= cl->level)
return 0;
cl->filters++;
return (unsigned long)cl;
}
return 0;
}
static void cbq_unbind_filter(struct Qdisc *sch, unsigned long arg)
{
struct cbq_class *cl = (struct cbq_class *)arg;
cl->filters--;
}
static void cbq_walk(struct Qdisc *sch, struct qdisc_walker *arg)
{
struct cbq_sched_data *q = qdisc_priv(sch);
struct cbq_class *cl;
unsigned int h;
if (arg->stop)
return;
for (h = 0; h < q->clhash.hashsize; h++) {
hlist_for_each_entry(cl, &q->clhash.hash[h], common.hnode) {
if (arg->count < arg->skip) {
arg->count++;
continue;
}
if (arg->fn(sch, (unsigned long)cl, arg) < 0) {
arg->stop = 1;
return;
}
arg->count++;
}
}
}
static const struct Qdisc_class_ops cbq_class_ops = {
.graft = cbq_graft,
.leaf = cbq_leaf,
.qlen_notify = cbq_qlen_notify,
.find = cbq_find,
.change = cbq_change_class,
.delete = cbq_delete,
.walk = cbq_walk,
.tcf_block = cbq_tcf_block,
.bind_tcf = cbq_bind_filter,
.unbind_tcf = cbq_unbind_filter,
.dump = cbq_dump_class,
.dump_stats = cbq_dump_class_stats,
};
static struct Qdisc_ops cbq_qdisc_ops __read_mostly = {
.next = NULL,
.cl_ops = &cbq_class_ops,
.id = "cbq",
.priv_size = sizeof(struct cbq_sched_data),
.enqueue = cbq_enqueue,
.dequeue = cbq_dequeue,
.peek = qdisc_peek_dequeued,
.init = cbq_init,
.reset = cbq_reset,
.destroy = cbq_destroy,
.change = NULL,
.dump = cbq_dump,
.dump_stats = cbq_dump_stats,
.owner = THIS_MODULE,
};
static int __init cbq_module_init(void)
{
return register_qdisc(&cbq_qdisc_ops);
}
static void __exit cbq_module_exit(void)
{
unregister_qdisc(&cbq_qdisc_ops);
}
module_init(cbq_module_init)
module_exit(cbq_module_exit)
MODULE_LICENSE("GPL");
| gpl-2.0 |
AOSPXS/kernel_sony_msm8x60 | sound/soc/msm/msm-multi-ch-pcm-q6.c | 353 | 24406 | /* Copyright (c) 2011-2012, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/init.h>
#include <linux/err.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/time.h>
#include <linux/wait.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/dma-mapping.h>
#include <linux/android_pmem.h>
#include <asm/dma.h>
#include <sound/core.h>
#include <sound/soc.h>
#include <sound/soc-dapm.h>
#include <sound/pcm.h>
#include <sound/initval.h>
#include <sound/control.h>
#include <sound/timer.h>
#include "msm-pcm-q6.h"
#include "msm-pcm-routing.h"
static struct audio_locks the_locks;
struct snd_msm {
struct snd_card *card;
struct snd_pcm *pcm;
};
struct snd_msm_volume {
struct msm_audio *prtd;
unsigned volume;
};
static struct snd_msm_volume multi_ch_pcm_audio = {NULL, 0x2000};
#define PLAYBACK_NUM_PERIODS 8
#define PLAYBACK_MAX_PERIOD_SIZE 12288
#define PLAYBACK_MIN_PERIOD_SIZE 256
#define CAPTURE_NUM_PERIODS 16
#define CAPTURE_MIN_PERIOD_SIZE 320
#define CAPTURE_MAX_PERIOD_SIZE 12288
static struct snd_pcm_hardware msm_pcm_hardware_capture = {
.info = (SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_PAUSE | SNDRV_PCM_INFO_RESUME),
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_8000_48000,
.rate_min = 8000,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 8,
.buffer_bytes_max = CAPTURE_NUM_PERIODS * CAPTURE_MAX_PERIOD_SIZE,
.period_bytes_min = CAPTURE_MIN_PERIOD_SIZE,
.period_bytes_max = CAPTURE_MAX_PERIOD_SIZE,
.periods_min = CAPTURE_NUM_PERIODS,
.periods_max = CAPTURE_NUM_PERIODS,
.fifo_size = 0,
};
static struct snd_pcm_hardware msm_pcm_hardware_playback = {
.info = (SNDRV_PCM_INFO_MMAP |
SNDRV_PCM_INFO_BLOCK_TRANSFER |
SNDRV_PCM_INFO_MMAP_VALID |
SNDRV_PCM_INFO_INTERLEAVED |
SNDRV_PCM_INFO_PAUSE | SNDRV_PCM_INFO_RESUME),
.formats = SNDRV_PCM_FMTBIT_S16_LE,
.rates = SNDRV_PCM_RATE_8000_48000 | SNDRV_PCM_RATE_KNOT,
.rate_min = 8000,
.rate_max = 48000,
.channels_min = 1,
.channels_max = 8,
.buffer_bytes_max = PLAYBACK_NUM_PERIODS * PLAYBACK_MAX_PERIOD_SIZE,
.period_bytes_min = PLAYBACK_MIN_PERIOD_SIZE,
.period_bytes_max = PLAYBACK_MAX_PERIOD_SIZE,
.periods_min = PLAYBACK_NUM_PERIODS,
.periods_max = PLAYBACK_NUM_PERIODS,
.fifo_size = 0,
};
/* Conventional and unconventional sample rate supported */
static unsigned int supported_sample_rates[] = {
8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000
};
static uint32_t in_frame_info[CAPTURE_NUM_PERIODS][2];
static struct snd_pcm_hw_constraint_list constraints_sample_rates = {
.count = ARRAY_SIZE(supported_sample_rates),
.list = supported_sample_rates,
.mask = 0,
};
static void event_handler(uint32_t opcode,
uint32_t token, uint32_t *payload, void *priv)
{
struct msm_audio *prtd = priv;
struct snd_pcm_substream *substream = prtd->substream;
struct snd_pcm_runtime *runtime = substream->runtime;
struct audio_aio_write_param param;
struct audio_buffer *buf = NULL;
uint32_t *ptrmem = (uint32_t *)payload;
int i = 0;
uint32_t idx = 0;
uint32_t size = 0;
pr_debug("%s\n", __func__);
switch (opcode) {
case ASM_DATA_EVENT_WRITE_DONE: {
uint32_t *ptrmem = (uint32_t *)¶m;
pr_debug("ASM_DATA_EVENT_WRITE_DONE\n");
pr_debug("Buffer Consumed = 0x%08x\n", *ptrmem);
prtd->pcm_irq_pos += prtd->pcm_count;
if (atomic_read(&prtd->start))
snd_pcm_period_elapsed(substream);
atomic_inc(&prtd->out_count);
wake_up(&the_locks.write_wait);
if (!atomic_read(&prtd->start))
break;
if (!prtd->mmap_flag)
break;
buf = prtd->audio_client->port[IN].buf;
pr_debug("%s:writing %d bytes of buffer[%d] to dsp 2\n",
__func__, prtd->pcm_count, prtd->out_head);
pr_debug("%s:writing buffer[%d] from 0x%08x\n",
__func__, prtd->out_head,
((unsigned int)buf[0].phys
+ (prtd->out_head * prtd->pcm_count)));
param.paddr = (unsigned long)buf[0].phys
+ (prtd->out_head * prtd->pcm_count);
param.len = prtd->pcm_count;
param.msw_ts = 0;
param.lsw_ts = 0;
param.flags = NO_TIMESTAMP;
param.uid = (unsigned long)buf[0].phys
+ (prtd->out_head * prtd->pcm_count);
for (i = 0; i < sizeof(struct audio_aio_write_param)/4;
i++, ++ptrmem)
pr_debug("cmd[%d]=0x%08x\n", i, *ptrmem);
if (q6asm_async_write(prtd->audio_client,
¶m) < 0)
pr_err("%s:q6asm_async_write failed\n",
__func__);
else
prtd->out_head =
(prtd->out_head + 1) & (runtime->periods - 1);
break;
}
case ASM_DATA_CMDRSP_EOS:
pr_debug("ASM_DATA_CMDRSP_EOS\n");
prtd->cmd_ack = 1;
wake_up(&the_locks.eos_wait);
break;
case ASM_DATA_EVENT_READ_DONE: {
pr_debug("ASM_DATA_EVENT_READ_DONE\n");
pr_debug("token = 0x%08x\n", token);
for (i = 0; i < 8; i++, ++ptrmem)
pr_debug("cmd[%d]=0x%08x\n", i, *ptrmem);
in_frame_info[token][0] = payload[2];
in_frame_info[token][1] = payload[3];
prtd->pcm_irq_pos += in_frame_info[token][0];
pr_debug("pcm_irq_pos=%d\n", prtd->pcm_irq_pos);
if (atomic_read(&prtd->start))
snd_pcm_period_elapsed(substream);
if (atomic_read(&prtd->in_count) <= prtd->periods)
atomic_inc(&prtd->in_count);
wake_up(&the_locks.read_wait);
if (prtd->mmap_flag
&& q6asm_is_cpu_buf_avail_nolock(OUT,
prtd->audio_client,
&size, &idx))
q6asm_read_nolock(prtd->audio_client);
break;
}
case APR_BASIC_RSP_RESULT: {
switch (payload[0]) {
case ASM_SESSION_CMD_RUN:
if (substream->stream
!= SNDRV_PCM_STREAM_PLAYBACK) {
atomic_set(&prtd->start, 1);
break;
}
if (prtd->mmap_flag) {
pr_debug("%s:writing %d bytes"\
" of buffer[%d] to dsp\n",
__func__, prtd->pcm_count,
prtd->out_head);
buf = prtd->audio_client->port[IN].buf;
pr_debug("%s:writing buffer[%d] from 0x%08x\n",
__func__, prtd->out_head,
((unsigned int)buf[0].phys
+ (prtd->out_head * prtd->pcm_count)));
param.paddr = (unsigned long)
buf[prtd->out_head].phys;
param.len = prtd->pcm_count;
param.msw_ts = 0;
param.lsw_ts = 0;
param.flags = NO_TIMESTAMP;
param.uid = (unsigned long)
buf[prtd->out_head].phys;
if (q6asm_async_write(prtd->audio_client,
¶m) < 0)
pr_err("%s:q6asm_async_write failed\n",
__func__);
else
prtd->out_head =
(prtd->out_head + 1)
& (runtime->periods - 1);
} else {
while (atomic_read(&prtd->out_needed)) {
pr_debug("%s:writing %d bytesi" \
" of buffer to dsp\n", \
__func__, \
prtd->pcm_count);
q6asm_write_nolock(prtd->audio_client,
prtd->pcm_count,
0, 0, NO_TIMESTAMP);
atomic_dec(&prtd->out_needed);
wake_up(&the_locks.write_wait);
};
}
atomic_set(&prtd->start, 1);
break;
default:
break;
}
}
break;
default:
pr_debug("Not Supported Event opcode[0x%x]\n", opcode);
break;
}
}
static int msm_pcm_playback_prepare(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct msm_audio *prtd = runtime->private_data;
int ret;
pr_debug("%s\n", __func__);
if (prtd->mmap_flag) {
ret = q6asm_set_io_mode(prtd->audio_client, ASYNC_IO_MODE);
if (ret < 0) {
pr_err("%s: Set IO mode failed\n", __func__);
return -ENOMEM;
}
}
prtd->pcm_size = snd_pcm_lib_buffer_bytes(substream);
prtd->pcm_count = snd_pcm_lib_period_bytes(substream);
prtd->pcm_irq_pos = 0;
/* rate and channels are sent to audio driver */
prtd->samp_rate = runtime->rate;
prtd->channel_mode = runtime->channels;
if (prtd->enabled)
return 0;
ret = q6asm_media_format_block_multi_ch_pcm(prtd->audio_client,
runtime->rate, runtime->channels);
if (ret < 0)
pr_info("%s: CMD Format block failed\n", __func__);
atomic_set(&prtd->out_count, runtime->periods);
prtd->enabled = 1;
prtd->cmd_ack = 0;
return 0;
}
static int msm_pcm_capture_prepare(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct msm_audio *prtd = runtime->private_data;
int ret = 0;
int i = 0;
pr_debug("%s\n", __func__);
prtd->pcm_size = snd_pcm_lib_buffer_bytes(substream);
prtd->pcm_count = snd_pcm_lib_period_bytes(substream);
prtd->pcm_irq_pos = 0;
/* rate and channels are sent to audio driver */
prtd->samp_rate = runtime->rate;
prtd->channel_mode = runtime->channels;
if (prtd->enabled)
return 0;
pr_debug("Samp_rate = %d\n", prtd->samp_rate);
pr_debug("Channel = %d\n", prtd->channel_mode);
ret = q6asm_enc_cfg_blk_multi_ch_pcm(prtd->audio_client,
prtd->samp_rate, prtd->channel_mode);
if (ret < 0)
pr_debug("%s: cmd cfg pcm was block failed", __func__);
for (i = 0; i < runtime->periods; i++)
q6asm_read(prtd->audio_client);
prtd->periods = runtime->periods;
prtd->enabled = 1;
return ret;
}
static int msm_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
{
int ret = 0;
struct snd_pcm_runtime *runtime = substream->runtime;
struct msm_audio *prtd = runtime->private_data;
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_RESUME:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
pr_debug("%s: Trigger start\n", __func__);
q6asm_run_nowait(prtd->audio_client, 0, 0, 0);
break;
case SNDRV_PCM_TRIGGER_STOP:
pr_debug("SNDRV_PCM_TRIGGER_STOP\n");
atomic_set(&prtd->start, 0);
if (substream->stream != SNDRV_PCM_STREAM_PLAYBACK)
break;
prtd->cmd_ack = 0;
q6asm_cmd_nowait(prtd->audio_client, CMD_EOS);
break;
case SNDRV_PCM_TRIGGER_SUSPEND:
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
pr_debug("SNDRV_PCM_TRIGGER_PAUSE\n");
q6asm_cmd_nowait(prtd->audio_client, CMD_PAUSE);
atomic_set(&prtd->start, 0);
break;
default:
ret = -EINVAL;
break;
}
return ret;
}
static int msm_pcm_open(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_soc_pcm_runtime *soc_prtd = substream->private_data;
struct msm_audio *prtd;
int ret = 0;
struct asm_softpause_params softpause = {
.enable = SOFT_PAUSE_ENABLE,
.period = SOFT_PAUSE_PERIOD,
.step = SOFT_PAUSE_STEP,
.rampingcurve = SOFT_PAUSE_CURVE_LINEAR,
};
struct asm_softvolume_params softvol = {
.period = SOFT_VOLUME_PERIOD,
.step = SOFT_VOLUME_STEP,
.rampingcurve = SOFT_VOLUME_CURVE_LINEAR,
};
pr_debug("%s\n", __func__);
prtd = kzalloc(sizeof(struct msm_audio), GFP_KERNEL);
if (prtd == NULL) {
pr_err("Failed to allocate memory for msm_audio\n");
return -ENOMEM;
}
prtd->substream = substream;
prtd->audio_client = q6asm_audio_client_alloc(
(app_cb)event_handler, prtd);
if (!prtd->audio_client) {
pr_err("%s: Could not allocate memory\n", __func__);
kfree(prtd);
return -ENOMEM;
}
prtd->audio_client->perf_mode = false;
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
runtime->hw = msm_pcm_hardware_playback;
ret = q6asm_open_write(prtd->audio_client,
FORMAT_MULTI_CHANNEL_LINEAR_PCM);
if (ret < 0) {
pr_err("%s: pcm out open failed\n", __func__);
q6asm_audio_client_free(prtd->audio_client);
kfree(prtd);
return -ENOMEM;
}
}
/* Capture path */
if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) {
runtime->hw = msm_pcm_hardware_capture;
ret = q6asm_open_read(prtd->audio_client,
FORMAT_MULTI_CHANNEL_LINEAR_PCM);
if (ret < 0) {
pr_err("%s: pcm in open failed\n", __func__);
q6asm_audio_client_free(prtd->audio_client);
kfree(prtd);
return -ENOMEM;
}
}
pr_debug("%s: session ID %d\n", __func__, prtd->audio_client->session);
prtd->session_id = prtd->audio_client->session;
msm_pcm_routing_reg_phy_stream(soc_prtd->dai_link->be_id,
prtd->audio_client->perf_mode,
prtd->session_id, substream->stream);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
prtd->cmd_ack = 1;
ret = snd_pcm_hw_constraint_list(runtime, 0,
SNDRV_PCM_HW_PARAM_RATE,
&constraints_sample_rates);
if (ret < 0)
pr_err("snd_pcm_hw_constraint_list failed\n");
/* Ensure that buffer size is a multiple of period size */
ret = snd_pcm_hw_constraint_integer(runtime,
SNDRV_PCM_HW_PARAM_PERIODS);
if (ret < 0)
pr_err("snd_pcm_hw_constraint_integer failed\n");
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
ret = snd_pcm_hw_constraint_minmax(runtime,
SNDRV_PCM_HW_PARAM_BUFFER_BYTES,
PLAYBACK_NUM_PERIODS * PLAYBACK_MIN_PERIOD_SIZE,
PLAYBACK_NUM_PERIODS * PLAYBACK_MAX_PERIOD_SIZE);
if (ret < 0) {
pr_err("constraint for buffer bytes min max ret = %d\n",
ret);
}
}
if (substream->stream == SNDRV_PCM_STREAM_CAPTURE) {
ret = snd_pcm_hw_constraint_minmax(runtime,
SNDRV_PCM_HW_PARAM_BUFFER_BYTES,
CAPTURE_NUM_PERIODS * CAPTURE_MIN_PERIOD_SIZE,
CAPTURE_NUM_PERIODS * CAPTURE_MAX_PERIOD_SIZE);
if (ret < 0) {
pr_err("constraint for buffer bytes min max ret = %d\n",
ret);
}
}
prtd->dsp_cnt = 0;
runtime->private_data = prtd;
pr_debug("substream->pcm->device = %d\n", substream->pcm->device);
pr_debug("soc_prtd->dai_link->be_id = %d\n", soc_prtd->dai_link->be_id);
multi_ch_pcm_audio.prtd = prtd;
ret = multi_ch_pcm_set_volume(multi_ch_pcm_audio.volume);
if (ret < 0)
pr_err("%s : Set Volume failed : %d", __func__, ret);
ret = q6asm_set_softpause(multi_ch_pcm_audio.prtd->audio_client,
&softpause);
if (ret < 0)
pr_err("%s: Send SoftPause Param failed ret=%d\n",
__func__, ret);
ret = q6asm_set_softvolume(multi_ch_pcm_audio.prtd->audio_client,
&softvol);
if (ret < 0)
pr_err("%s: Send SoftVolume Param failed ret=%d\n",
__func__, ret);
return 0;
}
int multi_ch_pcm_set_volume(unsigned volume)
{
int rc = 0;
pr_err("multi_ch_pcm_set_volume\n");
if (multi_ch_pcm_audio.prtd && multi_ch_pcm_audio.prtd->audio_client) {
pr_err("%s q6asm_set_volume\n", __func__);
rc = q6asm_set_volume(multi_ch_pcm_audio.prtd->audio_client,
volume);
if (rc < 0) {
pr_err("%s: Send Volume command failed"
" rc=%d\n", __func__, rc);
}
}
multi_ch_pcm_audio.volume = volume;
return rc;
}
static int msm_pcm_playback_copy(struct snd_pcm_substream *substream, int a,
snd_pcm_uframes_t hwoff, void __user *buf, snd_pcm_uframes_t frames)
{
int ret = 0;
int fbytes = 0;
int xfer = 0;
char *bufptr = NULL;
void *data = NULL;
uint32_t idx = 0;
uint32_t size = 0;
struct snd_pcm_runtime *runtime = substream->runtime;
struct msm_audio *prtd = runtime->private_data;
fbytes = frames_to_bytes(runtime, frames);
pr_debug("%s: prtd->out_count = %d\n",
__func__, atomic_read(&prtd->out_count));
ret = wait_event_timeout(the_locks.write_wait,
(atomic_read(&prtd->out_count)), 5 * HZ);
if (ret < 0) {
pr_err("%s: wait_event_timeout failed\n", __func__);
goto fail;
}
if (!atomic_read(&prtd->out_count)) {
pr_err("%s: pcm stopped out_count 0\n", __func__);
return 0;
}
data = q6asm_is_cpu_buf_avail(IN, prtd->audio_client, &size, &idx);
bufptr = data;
if (bufptr) {
pr_debug("%s:fbytes =%d: xfer=%d size=%d\n",
__func__, fbytes, xfer, size);
xfer = fbytes;
if (copy_from_user(bufptr, buf, xfer)) {
ret = -EFAULT;
goto fail;
}
buf += xfer;
fbytes -= xfer;
pr_debug("%s:fbytes = %d: xfer=%d\n", __func__, fbytes, xfer);
if (atomic_read(&prtd->start)) {
pr_debug("%s:writing %d bytes of buffer to dsp\n",
__func__, xfer);
ret = q6asm_write(prtd->audio_client, xfer,
0, 0, NO_TIMESTAMP);
if (ret < 0) {
ret = -EFAULT;
goto fail;
}
} else
atomic_inc(&prtd->out_needed);
atomic_dec(&prtd->out_count);
}
fail:
return ret;
}
static int msm_pcm_playback_close(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_soc_pcm_runtime *soc_prtd = substream->private_data;
struct msm_audio *prtd = runtime->private_data;
int dir = 0;
int ret = 0;
pr_debug("%s\n", __func__);
dir = IN;
ret = wait_event_timeout(the_locks.eos_wait,
prtd->cmd_ack, 5 * HZ);
if (ret < 0)
pr_err("%s: CMD_EOS failed\n", __func__);
q6asm_cmd(prtd->audio_client, CMD_CLOSE);
q6asm_audio_client_buf_free_contiguous(dir,
prtd->audio_client);
msm_pcm_routing_dereg_phy_stream(soc_prtd->dai_link->be_id,
SNDRV_PCM_STREAM_PLAYBACK);
multi_ch_pcm_audio.prtd = NULL;
q6asm_audio_client_free(prtd->audio_client);
kfree(prtd);
return 0;
}
static int msm_pcm_capture_copy(struct snd_pcm_substream *substream,
int channel, snd_pcm_uframes_t hwoff, void __user *buf,
snd_pcm_uframes_t frames)
{
int ret = 0;
int fbytes = 0;
int xfer;
char *bufptr;
void *data = NULL;
static uint32_t idx;
static uint32_t size;
uint32_t offset = 0;
struct snd_pcm_runtime *runtime = substream->runtime;
struct msm_audio *prtd = substream->runtime->private_data;
pr_debug("%s\n", __func__);
fbytes = frames_to_bytes(runtime, frames);
pr_debug("appl_ptr %d\n", (int)runtime->control->appl_ptr);
pr_debug("hw_ptr %d\n", (int)runtime->status->hw_ptr);
pr_debug("avail_min %d\n", (int)runtime->control->avail_min);
ret = wait_event_timeout(the_locks.read_wait,
(atomic_read(&prtd->in_count)), 5 * HZ);
if (ret < 0) {
pr_debug("%s: wait_event_timeout failed\n", __func__);
goto fail;
}
if (!atomic_read(&prtd->in_count)) {
pr_debug("%s: pcm stopped in_count 0\n", __func__);
return 0;
}
pr_debug("Checking if valid buffer is available...%08x\n",
(unsigned int) data);
data = q6asm_is_cpu_buf_avail(OUT, prtd->audio_client, &size, &idx);
bufptr = data;
pr_debug("Size = %d\n", size);
pr_debug("fbytes = %d\n", fbytes);
pr_debug("idx = %d\n", idx);
if (bufptr) {
xfer = fbytes;
if (xfer > size)
xfer = size;
offset = in_frame_info[idx][1];
pr_debug("Offset value = %d\n", offset);
if (copy_to_user(buf, bufptr+offset, xfer)) {
pr_err("Failed to copy buf to user\n");
ret = -EFAULT;
goto fail;
}
fbytes -= xfer;
size -= xfer;
in_frame_info[idx][1] += xfer;
pr_debug("%s:fbytes = %d: size=%d: xfer=%d\n",
__func__, fbytes, size, xfer);
pr_debug(" Sending next buffer to dsp\n");
memset(&in_frame_info[idx], 0,
sizeof(uint32_t) * 2);
atomic_dec(&prtd->in_count);
ret = q6asm_read(prtd->audio_client);
if (ret < 0) {
pr_err("q6asm read failed\n");
ret = -EFAULT;
goto fail;
}
} else
pr_err("No valid buffer\n");
pr_debug("Returning from capture_copy... %d\n", ret);
fail:
return ret;
}
static int msm_pcm_capture_close(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct snd_soc_pcm_runtime *soc_prtd = substream->private_data;
struct msm_audio *prtd = runtime->private_data;
int dir = OUT;
pr_debug("%s\n", __func__);
q6asm_cmd(prtd->audio_client, CMD_CLOSE);
q6asm_audio_client_buf_free_contiguous(dir,
prtd->audio_client);
msm_pcm_routing_dereg_phy_stream(soc_prtd->dai_link->be_id,
SNDRV_PCM_STREAM_CAPTURE);
q6asm_audio_client_free(prtd->audio_client);
kfree(prtd);
return 0;
}
static int msm_pcm_copy(struct snd_pcm_substream *substream, int a,
snd_pcm_uframes_t hwoff, void __user *buf, snd_pcm_uframes_t frames)
{
int ret = 0;
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
ret = msm_pcm_playback_copy(substream, a, hwoff, buf, frames);
else if (substream->stream == SNDRV_PCM_STREAM_CAPTURE)
ret = msm_pcm_capture_copy(substream, a, hwoff, buf, frames);
return ret;
}
static int msm_pcm_close(struct snd_pcm_substream *substream)
{
int ret = 0;
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
ret = msm_pcm_playback_close(substream);
else if (substream->stream == SNDRV_PCM_STREAM_CAPTURE)
ret = msm_pcm_capture_close(substream);
return ret;
}
static int msm_pcm_prepare(struct snd_pcm_substream *substream)
{
int ret = 0;
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
ret = msm_pcm_playback_prepare(substream);
else if (substream->stream == SNDRV_PCM_STREAM_CAPTURE)
ret = msm_pcm_capture_prepare(substream);
return ret;
}
static snd_pcm_uframes_t msm_pcm_pointer(struct snd_pcm_substream *substream)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct msm_audio *prtd = runtime->private_data;
if (prtd->pcm_irq_pos >= prtd->pcm_size)
prtd->pcm_irq_pos = 0;
pr_debug("pcm_irq_pos = %d\n", prtd->pcm_irq_pos);
return bytes_to_frames(runtime, (prtd->pcm_irq_pos));
}
static int msm_pcm_mmap(struct snd_pcm_substream *substream,
struct vm_area_struct *vma)
{
int result = 0;
struct snd_pcm_runtime *runtime = substream->runtime;
struct msm_audio *prtd = runtime->private_data;
pr_debug("%s\n", __func__);
prtd->mmap_flag = 1;
if (runtime->dma_addr && runtime->dma_bytes) {
vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
result = remap_pfn_range(vma, vma->vm_start,
runtime->dma_addr >> PAGE_SHIFT,
runtime->dma_bytes,
vma->vm_page_prot);
} else {
pr_err("Physical address or size of buf is NULL");
return -EINVAL;
}
return result;
}
static int msm_pcm_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_pcm_runtime *runtime = substream->runtime;
struct msm_audio *prtd = runtime->private_data;
struct snd_dma_buffer *dma_buf = &substream->dma_buffer;
struct audio_buffer *buf;
int dir, ret;
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
dir = IN;
else
dir = OUT;
ret = q6asm_audio_client_buf_alloc_contiguous(dir,
prtd->audio_client,
(params_buffer_bytes(params) / params_periods(params)),
params_periods(params));
if (ret < 0) {
pr_err("Audio Start: Buffer Allocation failed rc = %d\n", ret);
return -ENOMEM;
}
buf = prtd->audio_client->port[dir].buf;
pr_debug("%s:buf = %p\n", __func__, buf);
dma_buf->dev.type = SNDRV_DMA_TYPE_DEV;
dma_buf->dev.dev = substream->pcm->card->dev;
dma_buf->private_data = NULL;
dma_buf->area = buf[0].data;
dma_buf->addr = buf[0].phys;
dma_buf->bytes = params_buffer_bytes(params);
if (!dma_buf->area)
return -ENOMEM;
snd_pcm_set_runtime_buffer(substream, &substream->dma_buffer);
return 0;
}
static struct snd_pcm_ops msm_pcm_ops = {
.open = msm_pcm_open,
.copy = msm_pcm_copy,
.hw_params = msm_pcm_hw_params,
.close = msm_pcm_close,
.ioctl = snd_pcm_lib_ioctl,
.prepare = msm_pcm_prepare,
.trigger = msm_pcm_trigger,
.pointer = msm_pcm_pointer,
.mmap = msm_pcm_mmap,
};
static int msm_asoc_pcm_new(struct snd_soc_pcm_runtime *rtd)
{
struct snd_card *card = rtd->card->snd_card;
int ret = 0;
if (!card->dev->coherent_dma_mask)
card->dev->coherent_dma_mask = DMA_BIT_MASK(32);
return ret;
}
static struct snd_soc_platform_driver msm_soc_platform = {
.ops = &msm_pcm_ops,
.pcm_new = msm_asoc_pcm_new,
};
static __devinit int msm_pcm_probe(struct platform_device *pdev)
{
pr_info("%s: dev name %s\n", __func__, dev_name(&pdev->dev));
return snd_soc_register_platform(&pdev->dev,
&msm_soc_platform);
}
static int msm_pcm_remove(struct platform_device *pdev)
{
snd_soc_unregister_platform(&pdev->dev);
return 0;
}
static struct platform_driver msm_pcm_driver = {
.driver = {
.name = "msm-multi-ch-pcm-dsp",
.owner = THIS_MODULE,
},
.probe = msm_pcm_probe,
.remove = __devexit_p(msm_pcm_remove),
};
static int __init msm_soc_platform_init(void)
{
init_waitqueue_head(&the_locks.enable_wait);
init_waitqueue_head(&the_locks.eos_wait);
init_waitqueue_head(&the_locks.write_wait);
init_waitqueue_head(&the_locks.read_wait);
return platform_driver_register(&msm_pcm_driver);
}
module_init(msm_soc_platform_init);
static void __exit msm_soc_platform_exit(void)
{
platform_driver_unregister(&msm_pcm_driver);
}
module_exit(msm_soc_platform_exit);
MODULE_DESCRIPTION("Multi channel PCM module platform driver");
MODULE_LICENSE("GPL v2");
| gpl-2.0 |
jt1134/android_kernel_samsung_expressatt | arch/arm/mach-msm/idle_stats_device.c | 353 | 10438 | /* Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/mutex.h>
#include <linux/miscdevice.h>
#include <linux/poll.h>
#include <linux/uaccess.h>
#include <linux/idle_stats_device.h>
DEFINE_MUTEX(device_list_lock);
LIST_HEAD(device_list);
static ktime_t us_to_ktime(__u32 us)
{
return ns_to_ktime((u64)us * NSEC_PER_USEC);
}
static struct msm_idle_stats_device *_device_from_minor(unsigned int minor)
{
struct msm_idle_stats_device *device, *ret = NULL;
mutex_lock(&device_list_lock);
list_for_each_entry(device, &device_list, list) {
if (minor == device->miscdev.minor) {
ret = device;
break;
}
}
mutex_unlock(&device_list_lock);
return ret;
}
void msm_idle_stats_update_event(struct msm_idle_stats_device *device,
__u32 event)
{
__u32 wake_up = !device->stats->event;
device->stats->event |= event;
if (wake_up)
wake_up_interruptible(&device->wait);
}
EXPORT_SYMBOL(msm_idle_stats_update_event);
static enum hrtimer_restart msm_idle_stats_busy_timer(struct hrtimer *timer)
{
struct msm_idle_stats_device *device =
container_of(timer, struct msm_idle_stats_device, busy_timer);
/* This is the only case that the event is modified without a device
* lock. However, since the timer is cancelled in the other cases we are
* assured that we have exclusive access to the event at this time.
*/
hrtimer_set_expires(&device->busy_timer, us_to_ktime(0));
msm_idle_stats_update_event(device,
MSM_IDLE_STATS_EVENT_BUSY_TIMER_EXPIRED);
return HRTIMER_NORESTART;
}
static void start_busy_timer(struct msm_idle_stats_device *device,
ktime_t relative_time)
{
hrtimer_cancel(&device->busy_timer);
hrtimer_set_expires(&device->busy_timer, us_to_ktime(0));
if (!((device->stats->event &
MSM_IDLE_STATS_EVENT_BUSY_TIMER_EXPIRED) ||
(device->stats->event & MSM_IDLE_STATS_EVENT_COLLECTION_FULL))) {
if (ktime_to_us(relative_time) > 0) {
hrtimer_start(&device->busy_timer,
relative_time,
HRTIMER_MODE_REL);
}
}
}
static unsigned int msm_idle_stats_device_poll(struct file *file,
poll_table *wait)
{
struct msm_idle_stats_device *device = file->private_data;
unsigned int mask = 0;
poll_wait(file, &device->wait, wait);
if (device->stats->event)
mask = POLLIN | POLLRDNORM;
return mask;
}
static void msm_idle_stats_add_sample(struct msm_idle_stats_device *device,
struct msm_idle_pulse *pulse)
{
hrtimer_cancel(&device->busy_timer);
hrtimer_set_expires(&device->busy_timer, us_to_ktime(0));
if (device->stats->nr_collected >= device->max_samples)
return;
device->stats->pulse_chain[device->stats->nr_collected] = *pulse;
device->stats->nr_collected++;
if (device->stats->nr_collected == device->max_samples) {
msm_idle_stats_update_event(device,
MSM_IDLE_STATS_EVENT_COLLECTION_FULL);
} else if (device->stats->nr_collected ==
((device->max_samples * 3) / 4)) {
msm_idle_stats_update_event(device,
MSM_IDLE_STATS_EVENT_COLLECTION_NEARLY_FULL);
}
}
static long ioctl_read_stats(struct msm_idle_stats_device *device,
unsigned long arg)
{
int remaining;
int requested;
struct msm_idle_pulse pulse;
struct msm_idle_read_stats *stats;
__s64 remaining_time =
ktime_to_us(hrtimer_get_remaining(&device->busy_timer));
device->get_sample(device, &pulse);
spin_lock(&device->lock);
hrtimer_cancel(&device->busy_timer);
stats = device->stats;
if (stats == &device->stats_vector[0])
device->stats = &device->stats_vector[1];
else
device->stats = &device->stats_vector[0];
device->stats->event = 0;
device->stats->nr_collected = 0;
spin_unlock(&device->lock);
if (stats->nr_collected >= device->max_samples) {
stats->nr_collected = device->max_samples;
} else {
stats->pulse_chain[stats->nr_collected] = pulse;
stats->nr_collected++;
if (stats->nr_collected == device->max_samples)
stats->event |= MSM_IDLE_STATS_EVENT_COLLECTION_FULL;
else if (stats->nr_collected ==
((device->max_samples * 3) / 4))
stats->event |=
MSM_IDLE_STATS_EVENT_COLLECTION_NEARLY_FULL;
}
if (remaining_time < 0) {
stats->busy_timer_remaining = 0;
} else {
stats->busy_timer_remaining = remaining_time;
if ((__s64)stats->busy_timer_remaining != remaining_time)
stats->busy_timer_remaining = -1;
}
stats->return_timestamp = ktime_to_us(ktime_get());
requested =
((sizeof(*stats) - sizeof(stats->pulse_chain)) +
(sizeof(stats->pulse_chain[0]) * stats->nr_collected));
remaining = copy_to_user((void __user *)arg, stats, requested);
if (remaining > 0)
return -EFAULT;
return 0;
}
static long ioctl_write_stats(struct msm_idle_stats_device *device,
unsigned long arg)
{
struct msm_idle_write_stats stats;
int remaining;
int ret = 0;
remaining = copy_from_user(&stats, (void __user *) arg, sizeof(stats));
if (remaining > 0) {
ret = -EFAULT;
} else {
spin_lock(&device->lock);
device->busy_timer_interval = us_to_ktime(stats.next_busy_timer);
if (ktime_to_us(device->idle_start) == 0)
start_busy_timer(device, us_to_ktime(stats.busy_timer));
if ((stats.max_samples > 0) &&
(stats.max_samples <= MSM_IDLE_STATS_NR_MAX_INTERVALS))
device->max_samples = stats.max_samples;
spin_unlock(&device->lock);
}
return ret;
}
void msm_idle_stats_prepare_idle_start(struct msm_idle_stats_device *device)
{
spin_lock(&device->lock);
hrtimer_cancel(&device->busy_timer);
spin_unlock(&device->lock);
}
EXPORT_SYMBOL(msm_idle_stats_prepare_idle_start);
void msm_idle_stats_abort_idle_start(struct msm_idle_stats_device *device)
{
spin_lock(&device->lock);
if (ktime_to_us(hrtimer_get_expires(&device->busy_timer)) > 0)
hrtimer_restart(&device->busy_timer);
spin_unlock(&device->lock);
}
EXPORT_SYMBOL(msm_idle_stats_abort_idle_start);
void msm_idle_stats_idle_start(struct msm_idle_stats_device *device)
{
spin_lock(&device->lock);
hrtimer_cancel(&device->busy_timer);
device->idle_start = ktime_get();
if (ktime_to_us(hrtimer_get_expires(&device->busy_timer)) > 0) {
device->remaining_time =
hrtimer_get_remaining(&device->busy_timer);
if (ktime_to_us(device->remaining_time) <= 0)
device->remaining_time = us_to_ktime(0);
} else {
device->remaining_time = us_to_ktime(0);
}
spin_unlock(&device->lock);
}
EXPORT_SYMBOL(msm_idle_stats_idle_start);
void msm_idle_stats_idle_end(struct msm_idle_stats_device *device,
struct msm_idle_pulse *pulse)
{
u32 idle_time = 0;
spin_lock(&device->lock);
if (ktime_to_us(device->idle_start) != 0) {
idle_time = ktime_to_us(ktime_get())
- ktime_to_us(device->idle_start);
device->idle_start = us_to_ktime(0);
msm_idle_stats_add_sample(device, pulse);
if (device->stats->event &
MSM_IDLE_STATS_EVENT_BUSY_TIMER_EXPIRED) {
device->stats->event &=
~MSM_IDLE_STATS_EVENT_BUSY_TIMER_EXPIRED;
msm_idle_stats_update_event(device,
MSM_IDLE_STATS_EVENT_BUSY_TIMER_EXPIRED_RESET);
} else if (ktime_to_us(device->busy_timer_interval) > 0) {
ktime_t busy_timer = device->busy_timer_interval;
/* if it is serialized, it would be full busy,
* checking 80%
*/
if ((pulse->wait_interval*5 >= idle_time*4) &&
(ktime_to_us(device->remaining_time) > 0) &&
(ktime_to_us(device->remaining_time) <
ktime_to_us(busy_timer)))
busy_timer = device->remaining_time;
start_busy_timer(device, busy_timer);
}
}
spin_unlock(&device->lock);
}
EXPORT_SYMBOL(msm_idle_stats_idle_end);
static long msm_idle_stats_device_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
struct msm_idle_stats_device *device = file->private_data;
int ret;
switch (cmd) {
case MSM_IDLE_STATS_IOC_READ_STATS:
ret = ioctl_read_stats(device, arg);
break;
case MSM_IDLE_STATS_IOC_WRITE_STATS:
ret = ioctl_write_stats(device, arg);
break;
default:
ret = -EINVAL;
}
return ret;
}
static int msm_idle_stats_device_release
(struct inode *inode, struct file *filep)
{
return 0;
}
static int msm_idle_stats_device_open(struct inode *inode, struct file *filep)
{
struct msm_idle_stats_device *device;
device = _device_from_minor(iminor(inode));
if (device == NULL)
return -EPERM;
filep->private_data = device;
return 0;
}
static const struct file_operations msm_idle_stats_fops = {
.open = msm_idle_stats_device_open,
.release = msm_idle_stats_device_release,
.unlocked_ioctl = msm_idle_stats_device_ioctl,
.poll = msm_idle_stats_device_poll,
};
int msm_idle_stats_register_device(struct msm_idle_stats_device *device)
{
int ret = -ENOMEM;
spin_lock_init(&device->lock);
init_waitqueue_head(&device->wait);
hrtimer_init(&device->busy_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
device->busy_timer.function = msm_idle_stats_busy_timer;
device->stats_vector[0].event = 0;
device->stats_vector[0].nr_collected = 0;
device->stats_vector[1].event = 0;
device->stats_vector[1].nr_collected = 0;
device->stats = &device->stats_vector[0];
device->busy_timer_interval = us_to_ktime(0);
device->max_samples = MSM_IDLE_STATS_NR_MAX_INTERVALS;
mutex_lock(&device_list_lock);
list_add(&device->list, &device_list);
mutex_unlock(&device_list_lock);
device->miscdev.minor = MISC_DYNAMIC_MINOR;
device->miscdev.name = device->name;
device->miscdev.fops = &msm_idle_stats_fops;
ret = misc_register(&device->miscdev);
if (ret)
goto err_list;
return ret;
err_list:
mutex_lock(&device_list_lock);
list_del(&device->list);
mutex_unlock(&device_list_lock);
return ret;
}
EXPORT_SYMBOL(msm_idle_stats_register_device);
int msm_idle_stats_deregister_device(struct msm_idle_stats_device *device)
{
if (device == NULL)
return 0;
mutex_lock(&device_list_lock);
spin_lock(&device->lock);
hrtimer_cancel(&device->busy_timer);
list_del(&device->list);
spin_unlock(&device->lock);
mutex_unlock(&device_list_lock);
return misc_deregister(&device->miscdev);
}
EXPORT_SYMBOL(msm_idle_stats_deregister_device);
| gpl-2.0 |
El-Nath/shamu | arch/arm/kernel/stacktrace.c | 865 | 3343 | #include <linux/export.h>
#include <linux/sched.h>
#include <linux/stacktrace.h>
#include <asm/stacktrace.h>
#if defined(CONFIG_FRAME_POINTER) && !defined(CONFIG_ARM_UNWIND)
/*
* Unwind the current stack frame and store the new register values in the
* structure passed as argument. Unwinding is equivalent to a function return,
* hence the new PC value rather than LR should be used for backtrace.
*
* With framepointer enabled, a simple function prologue looks like this:
* mov ip, sp
* stmdb sp!, {fp, ip, lr, pc}
* sub fp, ip, #4
*
* A simple function epilogue looks like this:
* ldm sp, {fp, sp, pc}
*
* Note that with framepointer enabled, even the leaf functions have the same
* prologue and epilogue, therefore we can ignore the LR value in this case.
*/
int notrace unwind_frame(struct stackframe *frame)
{
unsigned long high, low;
unsigned long fp = frame->fp;
/* only go to a higher address on the stack */
low = frame->sp;
high = ALIGN(low, THREAD_SIZE);
/* check current frame pointer is within bounds */
if (fp < low + 12 || fp > high - 4)
return -EINVAL;
/* restore the registers from the stack frame */
frame->fp = *(unsigned long *)(fp - 12);
frame->sp = *(unsigned long *)(fp - 8);
frame->pc = *(unsigned long *)(fp - 4);
return 0;
}
#endif
void notrace walk_stackframe(struct stackframe *frame,
int (*fn)(struct stackframe *, void *), void *data)
{
while (1) {
int ret;
if (fn(frame, data))
break;
ret = unwind_frame(frame);
if (ret < 0)
break;
}
}
EXPORT_SYMBOL(walk_stackframe);
#ifdef CONFIG_STACKTRACE
struct stack_trace_data {
struct stack_trace *trace;
unsigned int no_sched_functions;
unsigned int skip;
};
static int save_trace(struct stackframe *frame, void *d)
{
struct stack_trace_data *data = d;
struct stack_trace *trace = data->trace;
unsigned long addr = frame->pc;
if (data->no_sched_functions && in_sched_functions(addr))
return 0;
if (data->skip) {
data->skip--;
return 0;
}
trace->entries[trace->nr_entries++] = addr;
return trace->nr_entries >= trace->max_entries;
}
void save_stack_trace_tsk(struct task_struct *tsk, struct stack_trace *trace)
{
struct stack_trace_data data;
struct stackframe frame;
data.trace = trace;
data.skip = trace->skip;
if (tsk != current) {
#ifdef CONFIG_SMP
/*
* What guarantees do we have here that 'tsk' is not
* running on another CPU? For now, ignore it as we
* can't guarantee we won't explode.
*/
if (trace->nr_entries < trace->max_entries)
trace->entries[trace->nr_entries++] = ULONG_MAX;
return;
#else
data.no_sched_functions = 1;
frame.fp = thread_saved_fp(tsk);
frame.sp = thread_saved_sp(tsk);
frame.lr = 0; /* recovered from the stack */
frame.pc = thread_saved_pc(tsk);
#endif
} else {
register unsigned long current_sp asm ("sp");
data.no_sched_functions = 0;
frame.fp = (unsigned long)__builtin_frame_address(0);
frame.sp = current_sp;
frame.lr = (unsigned long)__builtin_return_address(0);
frame.pc = (unsigned long)save_stack_trace_tsk;
}
walk_stackframe(&frame, save_trace, &data);
if (trace->nr_entries < trace->max_entries)
trace->entries[trace->nr_entries++] = ULONG_MAX;
}
void save_stack_trace(struct stack_trace *trace)
{
save_stack_trace_tsk(current, trace);
}
EXPORT_SYMBOL_GPL(save_stack_trace);
#endif
| gpl-2.0 |
ztemt/A476_V1B_5.1_kernel | drivers/gpu/drm/nouveau/core/subdev/bios/init.c | 1633 | 51078 | #include <core/engine.h>
#include <core/device.h>
#include <subdev/bios.h>
#include <subdev/bios/bmp.h>
#include <subdev/bios/bit.h>
#include <subdev/bios/conn.h>
#include <subdev/bios/dcb.h>
#include <subdev/bios/dp.h>
#include <subdev/bios/gpio.h>
#include <subdev/bios/init.h>
#include <subdev/devinit.h>
#include <subdev/clock.h>
#include <subdev/i2c.h>
#include <subdev/vga.h>
#include <subdev/gpio.h>
#define bioslog(lvl, fmt, args...) do { \
nv_printk(init->bios, lvl, "0x%04x[%c]: "fmt, init->offset, \
init_exec(init) ? '0' + (init->nested - 1) : ' ', ##args); \
} while(0)
#define cont(fmt, args...) do { \
if (nv_subdev(init->bios)->debug >= NV_DBG_TRACE) \
printk(fmt, ##args); \
} while(0)
#define trace(fmt, args...) bioslog(TRACE, fmt, ##args)
#define warn(fmt, args...) bioslog(WARN, fmt, ##args)
#define error(fmt, args...) bioslog(ERROR, fmt, ##args)
/******************************************************************************
* init parser control flow helpers
*****************************************************************************/
static inline bool
init_exec(struct nvbios_init *init)
{
return (init->execute == 1) || ((init->execute & 5) == 5);
}
static inline void
init_exec_set(struct nvbios_init *init, bool exec)
{
if (exec) init->execute &= 0xfd;
else init->execute |= 0x02;
}
static inline void
init_exec_inv(struct nvbios_init *init)
{
init->execute ^= 0x02;
}
static inline void
init_exec_force(struct nvbios_init *init, bool exec)
{
if (exec) init->execute |= 0x04;
else init->execute &= 0xfb;
}
/******************************************************************************
* init parser wrappers for normal register/i2c/whatever accessors
*****************************************************************************/
static inline int
init_or(struct nvbios_init *init)
{
if (init_exec(init)) {
if (init->outp)
return ffs(init->outp->or) - 1;
error("script needs OR!!\n");
}
return 0;
}
static inline int
init_link(struct nvbios_init *init)
{
if (init_exec(init)) {
if (init->outp)
return !(init->outp->sorconf.link & 1);
error("script needs OR link\n");
}
return 0;
}
static inline int
init_crtc(struct nvbios_init *init)
{
if (init_exec(init)) {
if (init->crtc >= 0)
return init->crtc;
error("script needs crtc\n");
}
return 0;
}
static u8
init_conn(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 ver, len;
u16 conn;
if (init_exec(init)) {
if (init->outp) {
conn = init->outp->connector;
conn = dcb_conn(bios, conn, &ver, &len);
if (conn)
return nv_ro08(bios, conn);
}
error("script needs connector type\n");
}
return 0xff;
}
static inline u32
init_nvreg(struct nvbios_init *init, u32 reg)
{
/* C51 (at least) sometimes has the lower bits set which the VBIOS
* interprets to mean that access needs to go through certain IO
* ports instead. The NVIDIA binary driver has been seen to access
* these through the NV register address, so lets assume we can
* do the same
*/
reg &= ~0x00000003;
/* GF8+ display scripts need register addresses mangled a bit to
* select a specific CRTC/OR
*/
if (nv_device(init->bios)->card_type >= NV_50) {
if (reg & 0x80000000) {
reg += init_crtc(init) * 0x800;
reg &= ~0x80000000;
}
if (reg & 0x40000000) {
reg += init_or(init) * 0x800;
reg &= ~0x40000000;
if (reg & 0x20000000) {
reg += init_link(init) * 0x80;
reg &= ~0x20000000;
}
}
}
if (reg & ~0x00fffffc)
warn("unknown bits in register 0x%08x\n", reg);
return reg;
}
static u32
init_rd32(struct nvbios_init *init, u32 reg)
{
reg = init_nvreg(init, reg);
if (init_exec(init))
return nv_rd32(init->subdev, reg);
return 0x00000000;
}
static void
init_wr32(struct nvbios_init *init, u32 reg, u32 val)
{
reg = init_nvreg(init, reg);
if (init_exec(init))
nv_wr32(init->subdev, reg, val);
}
static u32
init_mask(struct nvbios_init *init, u32 reg, u32 mask, u32 val)
{
reg = init_nvreg(init, reg);
if (init_exec(init)) {
u32 tmp = nv_rd32(init->subdev, reg);
nv_wr32(init->subdev, reg, (tmp & ~mask) | val);
return tmp;
}
return 0x00000000;
}
static u8
init_rdport(struct nvbios_init *init, u16 port)
{
if (init_exec(init))
return nv_rdport(init->subdev, init->crtc, port);
return 0x00;
}
static void
init_wrport(struct nvbios_init *init, u16 port, u8 value)
{
if (init_exec(init))
nv_wrport(init->subdev, init->crtc, port, value);
}
static u8
init_rdvgai(struct nvbios_init *init, u16 port, u8 index)
{
struct nouveau_subdev *subdev = init->subdev;
if (init_exec(init)) {
int head = init->crtc < 0 ? 0 : init->crtc;
return nv_rdvgai(subdev, head, port, index);
}
return 0x00;
}
static void
init_wrvgai(struct nvbios_init *init, u16 port, u8 index, u8 value)
{
/* force head 0 for updates to cr44, it only exists on first head */
if (nv_device(init->subdev)->card_type < NV_50) {
if (port == 0x03d4 && index == 0x44)
init->crtc = 0;
}
if (init_exec(init)) {
int head = init->crtc < 0 ? 0 : init->crtc;
nv_wrvgai(init->subdev, head, port, index, value);
}
/* select head 1 if cr44 write selected it */
if (nv_device(init->subdev)->card_type < NV_50) {
if (port == 0x03d4 && index == 0x44 && value == 3)
init->crtc = 1;
}
}
static struct nouveau_i2c_port *
init_i2c(struct nvbios_init *init, int index)
{
struct nouveau_i2c *i2c = nouveau_i2c(init->bios);
if (index == 0xff) {
index = NV_I2C_DEFAULT(0);
if (init->outp && init->outp->i2c_upper_default)
index = NV_I2C_DEFAULT(1);
} else
if (index < 0) {
if (!init->outp) {
if (init_exec(init))
error("script needs output for i2c\n");
return NULL;
}
if (index == -2 && init->outp->location) {
index = NV_I2C_TYPE_EXTAUX(init->outp->extdev);
return i2c->find_type(i2c, index);
}
index = init->outp->i2c_index;
}
return i2c->find(i2c, index);
}
static int
init_rdi2cr(struct nvbios_init *init, u8 index, u8 addr, u8 reg)
{
struct nouveau_i2c_port *port = init_i2c(init, index);
if (port && init_exec(init))
return nv_rdi2cr(port, addr, reg);
return -ENODEV;
}
static int
init_wri2cr(struct nvbios_init *init, u8 index, u8 addr, u8 reg, u8 val)
{
struct nouveau_i2c_port *port = init_i2c(init, index);
if (port && init_exec(init))
return nv_wri2cr(port, addr, reg, val);
return -ENODEV;
}
static int
init_rdauxr(struct nvbios_init *init, u32 addr)
{
struct nouveau_i2c_port *port = init_i2c(init, -2);
u8 data;
if (port && init_exec(init)) {
int ret = nv_rdaux(port, addr, &data, 1);
if (ret)
return ret;
return data;
}
return -ENODEV;
}
static int
init_wrauxr(struct nvbios_init *init, u32 addr, u8 data)
{
struct nouveau_i2c_port *port = init_i2c(init, -2);
if (port && init_exec(init))
return nv_wraux(port, addr, &data, 1);
return -ENODEV;
}
static void
init_prog_pll(struct nvbios_init *init, u32 id, u32 freq)
{
struct nouveau_clock *clk = nouveau_clock(init->bios);
if (clk && clk->pll_set && init_exec(init)) {
int ret = clk->pll_set(clk, id, freq);
if (ret)
warn("failed to prog pll 0x%08x to %dkHz\n", id, freq);
}
}
/******************************************************************************
* parsing of bios structures that are required to execute init tables
*****************************************************************************/
static u16
init_table(struct nouveau_bios *bios, u16 *len)
{
struct bit_entry bit_I;
if (!bit_entry(bios, 'I', &bit_I)) {
*len = bit_I.length;
return bit_I.offset;
}
if (bmp_version(bios) >= 0x0510) {
*len = 14;
return bios->bmp_offset + 75;
}
return 0x0000;
}
static u16
init_table_(struct nvbios_init *init, u16 offset, const char *name)
{
struct nouveau_bios *bios = init->bios;
u16 len, data = init_table(bios, &len);
if (data) {
if (len >= offset + 2) {
data = nv_ro16(bios, data + offset);
if (data)
return data;
warn("%s pointer invalid\n", name);
return 0x0000;
}
warn("init data too short for %s pointer", name);
return 0x0000;
}
warn("init data not found\n");
return 0x0000;
}
#define init_script_table(b) init_table_((b), 0x00, "script table")
#define init_macro_index_table(b) init_table_((b), 0x02, "macro index table")
#define init_macro_table(b) init_table_((b), 0x04, "macro table")
#define init_condition_table(b) init_table_((b), 0x06, "condition table")
#define init_io_condition_table(b) init_table_((b), 0x08, "io condition table")
#define init_io_flag_condition_table(b) init_table_((b), 0x0a, "io flag conditon table")
#define init_function_table(b) init_table_((b), 0x0c, "function table")
#define init_xlat_table(b) init_table_((b), 0x10, "xlat table");
static u16
init_script(struct nouveau_bios *bios, int index)
{
struct nvbios_init init = { .bios = bios };
u16 bmp_ver = bmp_version(bios), data;
if (bmp_ver && bmp_ver < 0x0510) {
if (index > 1 || bmp_ver < 0x0100)
return 0x0000;
data = bios->bmp_offset + (bmp_ver < 0x0200 ? 14 : 18);
return nv_ro16(bios, data + (index * 2));
}
data = init_script_table(&init);
if (data)
return nv_ro16(bios, data + (index * 2));
return 0x0000;
}
static u16
init_unknown_script(struct nouveau_bios *bios)
{
u16 len, data = init_table(bios, &len);
if (data && len >= 16)
return nv_ro16(bios, data + 14);
return 0x0000;
}
static u16
init_ram_restrict_table(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
struct bit_entry bit_M;
u16 data = 0x0000;
if (!bit_entry(bios, 'M', &bit_M)) {
if (bit_M.version == 1 && bit_M.length >= 5)
data = nv_ro16(bios, bit_M.offset + 3);
if (bit_M.version == 2 && bit_M.length >= 3)
data = nv_ro16(bios, bit_M.offset + 1);
}
if (data == 0x0000)
warn("ram restrict table not found\n");
return data;
}
static u8
init_ram_restrict_group_count(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
struct bit_entry bit_M;
if (!bit_entry(bios, 'M', &bit_M)) {
if (bit_M.version == 1 && bit_M.length >= 5)
return nv_ro08(bios, bit_M.offset + 2);
if (bit_M.version == 2 && bit_M.length >= 3)
return nv_ro08(bios, bit_M.offset + 0);
}
return 0x00;
}
static u8
init_ram_restrict_strap(struct nvbios_init *init)
{
/* This appears to be the behaviour of the VBIOS parser, and *is*
* important to cache the NV_PEXTDEV_BOOT0 on later chipsets to
* avoid fucking up the memory controller (somehow) by reading it
* on every INIT_RAM_RESTRICT_ZM_GROUP opcode.
*
* Preserving the non-caching behaviour on earlier chipsets just
* in case *not* re-reading the strap causes similar breakage.
*/
if (!init->ramcfg || init->bios->version.major < 0x70)
init->ramcfg = init_rd32(init, 0x101000);
return (init->ramcfg & 0x00000003c) >> 2;
}
static u8
init_ram_restrict(struct nvbios_init *init)
{
u8 strap = init_ram_restrict_strap(init);
u16 table = init_ram_restrict_table(init);
if (table)
return nv_ro08(init->bios, table + strap);
return 0x00;
}
static u8
init_xlat_(struct nvbios_init *init, u8 index, u8 offset)
{
struct nouveau_bios *bios = init->bios;
u16 table = init_xlat_table(init);
if (table) {
u16 data = nv_ro16(bios, table + (index * 2));
if (data)
return nv_ro08(bios, data + offset);
warn("xlat table pointer %d invalid\n", index);
}
return 0x00;
}
/******************************************************************************
* utility functions used by various init opcode handlers
*****************************************************************************/
static bool
init_condition_met(struct nvbios_init *init, u8 cond)
{
struct nouveau_bios *bios = init->bios;
u16 table = init_condition_table(init);
if (table) {
u32 reg = nv_ro32(bios, table + (cond * 12) + 0);
u32 msk = nv_ro32(bios, table + (cond * 12) + 4);
u32 val = nv_ro32(bios, table + (cond * 12) + 8);
trace("\t[0x%02x] (R[0x%06x] & 0x%08x) == 0x%08x\n",
cond, reg, msk, val);
return (init_rd32(init, reg) & msk) == val;
}
return false;
}
static bool
init_io_condition_met(struct nvbios_init *init, u8 cond)
{
struct nouveau_bios *bios = init->bios;
u16 table = init_io_condition_table(init);
if (table) {
u16 port = nv_ro16(bios, table + (cond * 5) + 0);
u8 index = nv_ro08(bios, table + (cond * 5) + 2);
u8 mask = nv_ro08(bios, table + (cond * 5) + 3);
u8 value = nv_ro08(bios, table + (cond * 5) + 4);
trace("\t[0x%02x] (0x%04x[0x%02x] & 0x%02x) == 0x%02x\n",
cond, port, index, mask, value);
return (init_rdvgai(init, port, index) & mask) == value;
}
return false;
}
static bool
init_io_flag_condition_met(struct nvbios_init *init, u8 cond)
{
struct nouveau_bios *bios = init->bios;
u16 table = init_io_flag_condition_table(init);
if (table) {
u16 port = nv_ro16(bios, table + (cond * 9) + 0);
u8 index = nv_ro08(bios, table + (cond * 9) + 2);
u8 mask = nv_ro08(bios, table + (cond * 9) + 3);
u8 shift = nv_ro08(bios, table + (cond * 9) + 4);
u16 data = nv_ro16(bios, table + (cond * 9) + 5);
u8 dmask = nv_ro08(bios, table + (cond * 9) + 7);
u8 value = nv_ro08(bios, table + (cond * 9) + 8);
u8 ioval = (init_rdvgai(init, port, index) & mask) >> shift;
return (nv_ro08(bios, data + ioval) & dmask) == value;
}
return false;
}
static inline u32
init_shift(u32 data, u8 shift)
{
if (shift < 0x80)
return data >> shift;
return data << (0x100 - shift);
}
static u32
init_tmds_reg(struct nvbios_init *init, u8 tmds)
{
/* For mlv < 0x80, it is an index into a table of TMDS base addresses.
* For mlv == 0x80 use the "or" value of the dcb_entry indexed by
* CR58 for CR57 = 0 to index a table of offsets to the basic
* 0x6808b0 address.
* For mlv == 0x81 use the "or" value of the dcb_entry indexed by
* CR58 for CR57 = 0 to index a table of offsets to the basic
* 0x6808b0 address, and then flip the offset by 8.
*/
const int pramdac_offset[13] = {
0, 0, 0x8, 0, 0x2000, 0, 0, 0, 0x2008, 0, 0, 0, 0x2000 };
const u32 pramdac_table[4] = {
0x6808b0, 0x6808b8, 0x6828b0, 0x6828b8 };
if (tmds >= 0x80) {
if (init->outp) {
u32 dacoffset = pramdac_offset[init->outp->or];
if (tmds == 0x81)
dacoffset ^= 8;
return 0x6808b0 + dacoffset;
}
if (init_exec(init))
error("tmds opcodes need dcb\n");
} else {
if (tmds < ARRAY_SIZE(pramdac_table))
return pramdac_table[tmds];
error("tmds selector 0x%02x unknown\n", tmds);
}
return 0;
}
/******************************************************************************
* init opcode handlers
*****************************************************************************/
/**
* init_reserved - stub for various unknown/unused single-byte opcodes
*
*/
static void
init_reserved(struct nvbios_init *init)
{
u8 opcode = nv_ro08(init->bios, init->offset);
u8 length, i;
switch (opcode) {
case 0xaa:
length = 4;
break;
default:
length = 1;
break;
}
trace("RESERVED 0x%02x\t", opcode);
for (i = 1; i < length; i++)
cont(" 0x%02x", nv_ro08(init->bios, init->offset + i));
cont("\n");
init->offset += length;
}
/**
* INIT_DONE - opcode 0x71
*
*/
static void
init_done(struct nvbios_init *init)
{
trace("DONE\n");
init->offset = 0x0000;
}
/**
* INIT_IO_RESTRICT_PROG - opcode 0x32
*
*/
static void
init_io_restrict_prog(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 port = nv_ro16(bios, init->offset + 1);
u8 index = nv_ro08(bios, init->offset + 3);
u8 mask = nv_ro08(bios, init->offset + 4);
u8 shift = nv_ro08(bios, init->offset + 5);
u8 count = nv_ro08(bios, init->offset + 6);
u32 reg = nv_ro32(bios, init->offset + 7);
u8 conf, i;
trace("IO_RESTRICT_PROG\tR[0x%06x] = "
"((0x%04x[0x%02x] & 0x%02x) >> %d) [{\n",
reg, port, index, mask, shift);
init->offset += 11;
conf = (init_rdvgai(init, port, index) & mask) >> shift;
for (i = 0; i < count; i++) {
u32 data = nv_ro32(bios, init->offset);
if (i == conf) {
trace("\t0x%08x *\n", data);
init_wr32(init, reg, data);
} else {
trace("\t0x%08x\n", data);
}
init->offset += 4;
}
trace("}]\n");
}
/**
* INIT_REPEAT - opcode 0x33
*
*/
static void
init_repeat(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 count = nv_ro08(bios, init->offset + 1);
u16 repeat = init->repeat;
trace("REPEAT\t0x%02x\n", count);
init->offset += 2;
init->repeat = init->offset;
init->repend = init->offset;
while (count--) {
init->offset = init->repeat;
nvbios_exec(init);
if (count)
trace("REPEAT\t0x%02x\n", count);
}
init->offset = init->repend;
init->repeat = repeat;
}
/**
* INIT_IO_RESTRICT_PLL - opcode 0x34
*
*/
static void
init_io_restrict_pll(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 port = nv_ro16(bios, init->offset + 1);
u8 index = nv_ro08(bios, init->offset + 3);
u8 mask = nv_ro08(bios, init->offset + 4);
u8 shift = nv_ro08(bios, init->offset + 5);
s8 iofc = nv_ro08(bios, init->offset + 6);
u8 count = nv_ro08(bios, init->offset + 7);
u32 reg = nv_ro32(bios, init->offset + 8);
u8 conf, i;
trace("IO_RESTRICT_PLL\tR[0x%06x] =PLL= "
"((0x%04x[0x%02x] & 0x%02x) >> 0x%02x) IOFCOND 0x%02x [{\n",
reg, port, index, mask, shift, iofc);
init->offset += 12;
conf = (init_rdvgai(init, port, index) & mask) >> shift;
for (i = 0; i < count; i++) {
u32 freq = nv_ro16(bios, init->offset) * 10;
if (i == conf) {
trace("\t%dkHz *\n", freq);
if (iofc > 0 && init_io_flag_condition_met(init, iofc))
freq *= 2;
init_prog_pll(init, reg, freq);
} else {
trace("\t%dkHz\n", freq);
}
init->offset += 2;
}
trace("}]\n");
}
/**
* INIT_END_REPEAT - opcode 0x36
*
*/
static void
init_end_repeat(struct nvbios_init *init)
{
trace("END_REPEAT\n");
init->offset += 1;
if (init->repeat) {
init->repend = init->offset;
init->offset = 0;
}
}
/**
* INIT_COPY - opcode 0x37
*
*/
static void
init_copy(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 reg = nv_ro32(bios, init->offset + 1);
u8 shift = nv_ro08(bios, init->offset + 5);
u8 smask = nv_ro08(bios, init->offset + 6);
u16 port = nv_ro16(bios, init->offset + 7);
u8 index = nv_ro08(bios, init->offset + 9);
u8 mask = nv_ro08(bios, init->offset + 10);
u8 data;
trace("COPY\t0x%04x[0x%02x] &= 0x%02x |= "
"((R[0x%06x] %s 0x%02x) & 0x%02x)\n",
port, index, mask, reg, (shift & 0x80) ? "<<" : ">>",
(shift & 0x80) ? (0x100 - shift) : shift, smask);
init->offset += 11;
data = init_rdvgai(init, port, index) & mask;
data |= init_shift(init_rd32(init, reg), shift) & smask;
init_wrvgai(init, port, index, data);
}
/**
* INIT_NOT - opcode 0x38
*
*/
static void
init_not(struct nvbios_init *init)
{
trace("NOT\n");
init->offset += 1;
init_exec_inv(init);
}
/**
* INIT_IO_FLAG_CONDITION - opcode 0x39
*
*/
static void
init_io_flag_condition(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 cond = nv_ro08(bios, init->offset + 1);
trace("IO_FLAG_CONDITION\t0x%02x\n", cond);
init->offset += 2;
if (!init_io_flag_condition_met(init, cond))
init_exec_set(init, false);
}
/**
* INIT_DP_CONDITION - opcode 0x3a
*
*/
static void
init_dp_condition(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
struct nvbios_dpout info;
u8 cond = nv_ro08(bios, init->offset + 1);
u8 unkn = nv_ro08(bios, init->offset + 2);
u8 ver, hdr, cnt, len;
u16 data;
trace("DP_CONDITION\t0x%02x 0x%02x\n", cond, unkn);
init->offset += 3;
switch (cond) {
case 0:
if (init_conn(init) != DCB_CONNECTOR_eDP)
init_exec_set(init, false);
break;
case 1:
case 2:
if ( init->outp &&
(data = nvbios_dpout_match(bios, DCB_OUTPUT_DP,
(init->outp->or << 0) |
(init->outp->sorconf.link << 6),
&ver, &hdr, &cnt, &len, &info)))
{
if (!(info.flags & cond))
init_exec_set(init, false);
break;
}
if (init_exec(init))
warn("script needs dp output table data\n");
break;
case 5:
if (!(init_rdauxr(init, 0x0d) & 1))
init_exec_set(init, false);
break;
default:
warn("unknown dp condition 0x%02x\n", cond);
break;
}
}
/**
* INIT_IO_MASK_OR - opcode 0x3b
*
*/
static void
init_io_mask_or(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 index = nv_ro08(bios, init->offset + 1);
u8 or = init_or(init);
u8 data;
trace("IO_MASK_OR\t0x03d4[0x%02x] &= ~(1 << 0x%02x)\n", index, or);
init->offset += 2;
data = init_rdvgai(init, 0x03d4, index);
init_wrvgai(init, 0x03d4, index, data &= ~(1 << or));
}
/**
* INIT_IO_OR - opcode 0x3c
*
*/
static void
init_io_or(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 index = nv_ro08(bios, init->offset + 1);
u8 or = init_or(init);
u8 data;
trace("IO_OR\t0x03d4[0x%02x] |= (1 << 0x%02x)\n", index, or);
init->offset += 2;
data = init_rdvgai(init, 0x03d4, index);
init_wrvgai(init, 0x03d4, index, data | (1 << or));
}
/**
* INIT_INDEX_ADDRESS_LATCHED - opcode 0x49
*
*/
static void
init_idx_addr_latched(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 creg = nv_ro32(bios, init->offset + 1);
u32 dreg = nv_ro32(bios, init->offset + 5);
u32 mask = nv_ro32(bios, init->offset + 9);
u32 data = nv_ro32(bios, init->offset + 13);
u8 count = nv_ro08(bios, init->offset + 17);
trace("INDEX_ADDRESS_LATCHED\t"
"R[0x%06x] : R[0x%06x]\n\tCTRL &= 0x%08x |= 0x%08x\n",
creg, dreg, mask, data);
init->offset += 18;
while (count--) {
u8 iaddr = nv_ro08(bios, init->offset + 0);
u8 idata = nv_ro08(bios, init->offset + 1);
trace("\t[0x%02x] = 0x%02x\n", iaddr, idata);
init->offset += 2;
init_wr32(init, dreg, idata);
init_mask(init, creg, ~mask, data | iaddr);
}
}
/**
* INIT_IO_RESTRICT_PLL2 - opcode 0x4a
*
*/
static void
init_io_restrict_pll2(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 port = nv_ro16(bios, init->offset + 1);
u8 index = nv_ro08(bios, init->offset + 3);
u8 mask = nv_ro08(bios, init->offset + 4);
u8 shift = nv_ro08(bios, init->offset + 5);
u8 count = nv_ro08(bios, init->offset + 6);
u32 reg = nv_ro32(bios, init->offset + 7);
u8 conf, i;
trace("IO_RESTRICT_PLL2\t"
"R[0x%06x] =PLL= ((0x%04x[0x%02x] & 0x%02x) >> 0x%02x) [{\n",
reg, port, index, mask, shift);
init->offset += 11;
conf = (init_rdvgai(init, port, index) & mask) >> shift;
for (i = 0; i < count; i++) {
u32 freq = nv_ro32(bios, init->offset);
if (i == conf) {
trace("\t%dkHz *\n", freq);
init_prog_pll(init, reg, freq);
} else {
trace("\t%dkHz\n", freq);
}
init->offset += 4;
}
trace("}]\n");
}
/**
* INIT_PLL2 - opcode 0x4b
*
*/
static void
init_pll2(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 reg = nv_ro32(bios, init->offset + 1);
u32 freq = nv_ro32(bios, init->offset + 5);
trace("PLL2\tR[0x%06x] =PLL= %dkHz\n", reg, freq);
init->offset += 9;
init_prog_pll(init, reg, freq);
}
/**
* INIT_I2C_BYTE - opcode 0x4c
*
*/
static void
init_i2c_byte(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 index = nv_ro08(bios, init->offset + 1);
u8 addr = nv_ro08(bios, init->offset + 2) >> 1;
u8 count = nv_ro08(bios, init->offset + 3);
trace("I2C_BYTE\tI2C[0x%02x][0x%02x]\n", index, addr);
init->offset += 4;
while (count--) {
u8 reg = nv_ro08(bios, init->offset + 0);
u8 mask = nv_ro08(bios, init->offset + 1);
u8 data = nv_ro08(bios, init->offset + 2);
int val;
trace("\t[0x%02x] &= 0x%02x |= 0x%02x\n", reg, mask, data);
init->offset += 3;
val = init_rdi2cr(init, index, addr, reg);
if (val < 0)
continue;
init_wri2cr(init, index, addr, reg, (val & mask) | data);
}
}
/**
* INIT_ZM_I2C_BYTE - opcode 0x4d
*
*/
static void
init_zm_i2c_byte(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 index = nv_ro08(bios, init->offset + 1);
u8 addr = nv_ro08(bios, init->offset + 2) >> 1;
u8 count = nv_ro08(bios, init->offset + 3);
trace("ZM_I2C_BYTE\tI2C[0x%02x][0x%02x]\n", index, addr);
init->offset += 4;
while (count--) {
u8 reg = nv_ro08(bios, init->offset + 0);
u8 data = nv_ro08(bios, init->offset + 1);
trace("\t[0x%02x] = 0x%02x\n", reg, data);
init->offset += 2;
init_wri2cr(init, index, addr, reg, data);
}
}
/**
* INIT_ZM_I2C - opcode 0x4e
*
*/
static void
init_zm_i2c(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 index = nv_ro08(bios, init->offset + 1);
u8 addr = nv_ro08(bios, init->offset + 2) >> 1;
u8 count = nv_ro08(bios, init->offset + 3);
u8 data[256], i;
trace("ZM_I2C\tI2C[0x%02x][0x%02x]\n", index, addr);
init->offset += 4;
for (i = 0; i < count; i++) {
data[i] = nv_ro08(bios, init->offset);
trace("\t0x%02x\n", data[i]);
init->offset++;
}
if (init_exec(init)) {
struct nouveau_i2c_port *port = init_i2c(init, index);
struct i2c_msg msg = {
.addr = addr, .flags = 0, .len = count, .buf = data,
};
int ret;
if (port && (ret = i2c_transfer(&port->adapter, &msg, 1)) != 1)
warn("i2c wr failed, %d\n", ret);
}
}
/**
* INIT_TMDS - opcode 0x4f
*
*/
static void
init_tmds(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 tmds = nv_ro08(bios, init->offset + 1);
u8 addr = nv_ro08(bios, init->offset + 2);
u8 mask = nv_ro08(bios, init->offset + 3);
u8 data = nv_ro08(bios, init->offset + 4);
u32 reg = init_tmds_reg(init, tmds);
trace("TMDS\tT[0x%02x][0x%02x] &= 0x%02x |= 0x%02x\n",
tmds, addr, mask, data);
init->offset += 5;
if (reg == 0)
return;
init_wr32(init, reg + 0, addr | 0x00010000);
init_wr32(init, reg + 4, data | (init_rd32(init, reg + 4) & mask));
init_wr32(init, reg + 0, addr);
}
/**
* INIT_ZM_TMDS_GROUP - opcode 0x50
*
*/
static void
init_zm_tmds_group(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 tmds = nv_ro08(bios, init->offset + 1);
u8 count = nv_ro08(bios, init->offset + 2);
u32 reg = init_tmds_reg(init, tmds);
trace("TMDS_ZM_GROUP\tT[0x%02x]\n", tmds);
init->offset += 3;
while (count--) {
u8 addr = nv_ro08(bios, init->offset + 0);
u8 data = nv_ro08(bios, init->offset + 1);
trace("\t[0x%02x] = 0x%02x\n", addr, data);
init->offset += 2;
init_wr32(init, reg + 4, data);
init_wr32(init, reg + 0, addr);
}
}
/**
* INIT_CR_INDEX_ADDRESS_LATCHED - opcode 0x51
*
*/
static void
init_cr_idx_adr_latch(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 addr0 = nv_ro08(bios, init->offset + 1);
u8 addr1 = nv_ro08(bios, init->offset + 2);
u8 base = nv_ro08(bios, init->offset + 3);
u8 count = nv_ro08(bios, init->offset + 4);
u8 save0;
trace("CR_INDEX_ADDR C[%02x] C[%02x]\n", addr0, addr1);
init->offset += 5;
save0 = init_rdvgai(init, 0x03d4, addr0);
while (count--) {
u8 data = nv_ro08(bios, init->offset);
trace("\t\t[0x%02x] = 0x%02x\n", base, data);
init->offset += 1;
init_wrvgai(init, 0x03d4, addr0, base++);
init_wrvgai(init, 0x03d4, addr1, data);
}
init_wrvgai(init, 0x03d4, addr0, save0);
}
/**
* INIT_CR - opcode 0x52
*
*/
static void
init_cr(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 addr = nv_ro08(bios, init->offset + 1);
u8 mask = nv_ro08(bios, init->offset + 2);
u8 data = nv_ro08(bios, init->offset + 3);
u8 val;
trace("CR\t\tC[0x%02x] &= 0x%02x |= 0x%02x\n", addr, mask, data);
init->offset += 4;
val = init_rdvgai(init, 0x03d4, addr) & mask;
init_wrvgai(init, 0x03d4, addr, val | data);
}
/**
* INIT_ZM_CR - opcode 0x53
*
*/
static void
init_zm_cr(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 addr = nv_ro08(bios, init->offset + 1);
u8 data = nv_ro08(bios, init->offset + 2);
trace("ZM_CR\tC[0x%02x] = 0x%02x\n", addr, data);
init->offset += 3;
init_wrvgai(init, 0x03d4, addr, data);
}
/**
* INIT_ZM_CR_GROUP - opcode 0x54
*
*/
static void
init_zm_cr_group(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 count = nv_ro08(bios, init->offset + 1);
trace("ZM_CR_GROUP\n");
init->offset += 2;
while (count--) {
u8 addr = nv_ro08(bios, init->offset + 0);
u8 data = nv_ro08(bios, init->offset + 1);
trace("\t\tC[0x%02x] = 0x%02x\n", addr, data);
init->offset += 2;
init_wrvgai(init, 0x03d4, addr, data);
}
}
/**
* INIT_CONDITION_TIME - opcode 0x56
*
*/
static void
init_condition_time(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 cond = nv_ro08(bios, init->offset + 1);
u8 retry = nv_ro08(bios, init->offset + 2);
u8 wait = min((u16)retry * 50, 100);
trace("CONDITION_TIME\t0x%02x 0x%02x\n", cond, retry);
init->offset += 3;
if (!init_exec(init))
return;
while (wait--) {
if (init_condition_met(init, cond))
return;
mdelay(20);
}
init_exec_set(init, false);
}
/**
* INIT_LTIME - opcode 0x57
*
*/
static void
init_ltime(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 msec = nv_ro16(bios, init->offset + 1);
trace("LTIME\t0x%04x\n", msec);
init->offset += 3;
if (init_exec(init))
mdelay(msec);
}
/**
* INIT_ZM_REG_SEQUENCE - opcode 0x58
*
*/
static void
init_zm_reg_sequence(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 base = nv_ro32(bios, init->offset + 1);
u8 count = nv_ro08(bios, init->offset + 5);
trace("ZM_REG_SEQUENCE\t0x%02x\n", count);
init->offset += 6;
while (count--) {
u32 data = nv_ro32(bios, init->offset);
trace("\t\tR[0x%06x] = 0x%08x\n", base, data);
init->offset += 4;
init_wr32(init, base, data);
base += 4;
}
}
/**
* INIT_SUB_DIRECT - opcode 0x5b
*
*/
static void
init_sub_direct(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 addr = nv_ro16(bios, init->offset + 1);
u16 save;
trace("SUB_DIRECT\t0x%04x\n", addr);
if (init_exec(init)) {
save = init->offset;
init->offset = addr;
if (nvbios_exec(init)) {
error("error parsing sub-table\n");
return;
}
init->offset = save;
}
init->offset += 3;
}
/**
* INIT_JUMP - opcode 0x5c
*
*/
static void
init_jump(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 offset = nv_ro16(bios, init->offset + 1);
trace("JUMP\t0x%04x\n", offset);
if (init_exec(init))
init->offset = offset;
else
init->offset += 3;
}
/**
* INIT_I2C_IF - opcode 0x5e
*
*/
static void
init_i2c_if(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 index = nv_ro08(bios, init->offset + 1);
u8 addr = nv_ro08(bios, init->offset + 2);
u8 reg = nv_ro08(bios, init->offset + 3);
u8 mask = nv_ro08(bios, init->offset + 4);
u8 data = nv_ro08(bios, init->offset + 5);
u8 value;
trace("I2C_IF\tI2C[0x%02x][0x%02x][0x%02x] & 0x%02x == 0x%02x\n",
index, addr, reg, mask, data);
init->offset += 6;
init_exec_force(init, true);
value = init_rdi2cr(init, index, addr, reg);
if ((value & mask) != data)
init_exec_set(init, false);
init_exec_force(init, false);
}
/**
* INIT_COPY_NV_REG - opcode 0x5f
*
*/
static void
init_copy_nv_reg(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 sreg = nv_ro32(bios, init->offset + 1);
u8 shift = nv_ro08(bios, init->offset + 5);
u32 smask = nv_ro32(bios, init->offset + 6);
u32 sxor = nv_ro32(bios, init->offset + 10);
u32 dreg = nv_ro32(bios, init->offset + 14);
u32 dmask = nv_ro32(bios, init->offset + 18);
u32 data;
trace("COPY_NV_REG\tR[0x%06x] &= 0x%08x |= "
"((R[0x%06x] %s 0x%02x) & 0x%08x ^ 0x%08x)\n",
dreg, dmask, sreg, (shift & 0x80) ? "<<" : ">>",
(shift & 0x80) ? (0x100 - shift) : shift, smask, sxor);
init->offset += 22;
data = init_shift(init_rd32(init, sreg), shift);
init_mask(init, dreg, ~dmask, (data & smask) ^ sxor);
}
/**
* INIT_ZM_INDEX_IO - opcode 0x62
*
*/
static void
init_zm_index_io(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 port = nv_ro16(bios, init->offset + 1);
u8 index = nv_ro08(bios, init->offset + 3);
u8 data = nv_ro08(bios, init->offset + 4);
trace("ZM_INDEX_IO\tI[0x%04x][0x%02x] = 0x%02x\n", port, index, data);
init->offset += 5;
init_wrvgai(init, port, index, data);
}
/**
* INIT_COMPUTE_MEM - opcode 0x63
*
*/
static void
init_compute_mem(struct nvbios_init *init)
{
struct nouveau_devinit *devinit = nouveau_devinit(init->bios);
trace("COMPUTE_MEM\n");
init->offset += 1;
init_exec_force(init, true);
if (init_exec(init) && devinit->meminit)
devinit->meminit(devinit);
init_exec_force(init, false);
}
/**
* INIT_RESET - opcode 0x65
*
*/
static void
init_reset(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 reg = nv_ro32(bios, init->offset + 1);
u32 data1 = nv_ro32(bios, init->offset + 5);
u32 data2 = nv_ro32(bios, init->offset + 9);
u32 savepci19;
trace("RESET\tR[0x%08x] = 0x%08x, 0x%08x", reg, data1, data2);
init->offset += 13;
init_exec_force(init, true);
savepci19 = init_mask(init, 0x00184c, 0x00000f00, 0x00000000);
init_wr32(init, reg, data1);
udelay(10);
init_wr32(init, reg, data2);
init_wr32(init, 0x00184c, savepci19);
init_mask(init, 0x001850, 0x00000001, 0x00000000);
init_exec_force(init, false);
}
/**
* INIT_CONFIGURE_MEM - opcode 0x66
*
*/
static u16
init_configure_mem_clk(struct nvbios_init *init)
{
u16 mdata = bmp_mem_init_table(init->bios);
if (mdata)
mdata += (init_rdvgai(init, 0x03d4, 0x3c) >> 4) * 66;
return mdata;
}
static void
init_configure_mem(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 mdata, sdata;
u32 addr, data;
trace("CONFIGURE_MEM\n");
init->offset += 1;
if (bios->version.major > 2) {
init_done(init);
return;
}
init_exec_force(init, true);
mdata = init_configure_mem_clk(init);
sdata = bmp_sdr_seq_table(bios);
if (nv_ro08(bios, mdata) & 0x01)
sdata = bmp_ddr_seq_table(bios);
mdata += 6; /* skip to data */
data = init_rdvgai(init, 0x03c4, 0x01);
init_wrvgai(init, 0x03c4, 0x01, data | 0x20);
while ((addr = nv_ro32(bios, sdata)) != 0xffffffff) {
switch (addr) {
case 0x10021c: /* CKE_NORMAL */
case 0x1002d0: /* CMD_REFRESH */
case 0x1002d4: /* CMD_PRECHARGE */
data = 0x00000001;
break;
default:
data = nv_ro32(bios, mdata);
mdata += 4;
if (data == 0xffffffff)
continue;
break;
}
init_wr32(init, addr, data);
}
init_exec_force(init, false);
}
/**
* INIT_CONFIGURE_CLK - opcode 0x67
*
*/
static void
init_configure_clk(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 mdata, clock;
trace("CONFIGURE_CLK\n");
init->offset += 1;
if (bios->version.major > 2) {
init_done(init);
return;
}
init_exec_force(init, true);
mdata = init_configure_mem_clk(init);
/* NVPLL */
clock = nv_ro16(bios, mdata + 4) * 10;
init_prog_pll(init, 0x680500, clock);
/* MPLL */
clock = nv_ro16(bios, mdata + 2) * 10;
if (nv_ro08(bios, mdata) & 0x01)
clock *= 2;
init_prog_pll(init, 0x680504, clock);
init_exec_force(init, false);
}
/**
* INIT_CONFIGURE_PREINIT - opcode 0x68
*
*/
static void
init_configure_preinit(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 strap;
trace("CONFIGURE_PREINIT\n");
init->offset += 1;
if (bios->version.major > 2) {
init_done(init);
return;
}
init_exec_force(init, true);
strap = init_rd32(init, 0x101000);
strap = ((strap << 2) & 0xf0) | ((strap & 0x40) >> 6);
init_wrvgai(init, 0x03d4, 0x3c, strap);
init_exec_force(init, false);
}
/**
* INIT_IO - opcode 0x69
*
*/
static void
init_io(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 port = nv_ro16(bios, init->offset + 1);
u8 mask = nv_ro16(bios, init->offset + 3);
u8 data = nv_ro16(bios, init->offset + 4);
u8 value;
trace("IO\t\tI[0x%04x] &= 0x%02x |= 0x%02x\n", port, mask, data);
init->offset += 5;
/* ummm.. yes.. should really figure out wtf this is and why it's
* needed some day.. it's almost certainly wrong, but, it also
* somehow makes things work...
*/
if (nv_device(init->bios)->card_type >= NV_50 &&
port == 0x03c3 && data == 0x01) {
init_mask(init, 0x614100, 0xf0800000, 0x00800000);
init_mask(init, 0x00e18c, 0x00020000, 0x00020000);
init_mask(init, 0x614900, 0xf0800000, 0x00800000);
init_mask(init, 0x000200, 0x40000000, 0x00000000);
mdelay(10);
init_mask(init, 0x00e18c, 0x00020000, 0x00000000);
init_mask(init, 0x000200, 0x40000000, 0x40000000);
init_wr32(init, 0x614100, 0x00800018);
init_wr32(init, 0x614900, 0x00800018);
mdelay(10);
init_wr32(init, 0x614100, 0x10000018);
init_wr32(init, 0x614900, 0x10000018);
}
value = init_rdport(init, port) & mask;
init_wrport(init, port, data | value);
}
/**
* INIT_SUB - opcode 0x6b
*
*/
static void
init_sub(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 index = nv_ro08(bios, init->offset + 1);
u16 addr, save;
trace("SUB\t0x%02x\n", index);
addr = init_script(bios, index);
if (addr && init_exec(init)) {
save = init->offset;
init->offset = addr;
if (nvbios_exec(init)) {
error("error parsing sub-table\n");
return;
}
init->offset = save;
}
init->offset += 2;
}
/**
* INIT_RAM_CONDITION - opcode 0x6d
*
*/
static void
init_ram_condition(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 mask = nv_ro08(bios, init->offset + 1);
u8 value = nv_ro08(bios, init->offset + 2);
trace("RAM_CONDITION\t"
"(R[0x100000] & 0x%02x) == 0x%02x\n", mask, value);
init->offset += 3;
if ((init_rd32(init, 0x100000) & mask) != value)
init_exec_set(init, false);
}
/**
* INIT_NV_REG - opcode 0x6e
*
*/
static void
init_nv_reg(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 reg = nv_ro32(bios, init->offset + 1);
u32 mask = nv_ro32(bios, init->offset + 5);
u32 data = nv_ro32(bios, init->offset + 9);
trace("NV_REG\tR[0x%06x] &= 0x%08x |= 0x%08x\n", reg, mask, data);
init->offset += 13;
init_mask(init, reg, ~mask, data);
}
/**
* INIT_MACRO - opcode 0x6f
*
*/
static void
init_macro(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 macro = nv_ro08(bios, init->offset + 1);
u16 table;
trace("MACRO\t0x%02x\n", macro);
table = init_macro_table(init);
if (table) {
u32 addr = nv_ro32(bios, table + (macro * 8) + 0);
u32 data = nv_ro32(bios, table + (macro * 8) + 4);
trace("\t\tR[0x%06x] = 0x%08x\n", addr, data);
init_wr32(init, addr, data);
}
init->offset += 2;
}
/**
* INIT_RESUME - opcode 0x72
*
*/
static void
init_resume(struct nvbios_init *init)
{
trace("RESUME\n");
init->offset += 1;
init_exec_set(init, true);
}
/**
* INIT_TIME - opcode 0x74
*
*/
static void
init_time(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 usec = nv_ro16(bios, init->offset + 1);
trace("TIME\t0x%04x\n", usec);
init->offset += 3;
if (init_exec(init)) {
if (usec < 1000)
udelay(usec);
else
mdelay((usec + 900) / 1000);
}
}
/**
* INIT_CONDITION - opcode 0x75
*
*/
static void
init_condition(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 cond = nv_ro08(bios, init->offset + 1);
trace("CONDITION\t0x%02x\n", cond);
init->offset += 2;
if (!init_condition_met(init, cond))
init_exec_set(init, false);
}
/**
* INIT_IO_CONDITION - opcode 0x76
*
*/
static void
init_io_condition(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 cond = nv_ro08(bios, init->offset + 1);
trace("IO_CONDITION\t0x%02x\n", cond);
init->offset += 2;
if (!init_io_condition_met(init, cond))
init_exec_set(init, false);
}
/**
* INIT_INDEX_IO - opcode 0x78
*
*/
static void
init_index_io(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u16 port = nv_ro16(bios, init->offset + 1);
u8 index = nv_ro16(bios, init->offset + 3);
u8 mask = nv_ro08(bios, init->offset + 4);
u8 data = nv_ro08(bios, init->offset + 5);
u8 value;
trace("INDEX_IO\tI[0x%04x][0x%02x] &= 0x%02x |= 0x%02x\n",
port, index, mask, data);
init->offset += 6;
value = init_rdvgai(init, port, index) & mask;
init_wrvgai(init, port, index, data | value);
}
/**
* INIT_PLL - opcode 0x79
*
*/
static void
init_pll(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 reg = nv_ro32(bios, init->offset + 1);
u32 freq = nv_ro16(bios, init->offset + 5) * 10;
trace("PLL\tR[0x%06x] =PLL= %dkHz\n", reg, freq);
init->offset += 7;
init_prog_pll(init, reg, freq);
}
/**
* INIT_ZM_REG - opcode 0x7a
*
*/
static void
init_zm_reg(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 addr = nv_ro32(bios, init->offset + 1);
u32 data = nv_ro32(bios, init->offset + 5);
trace("ZM_REG\tR[0x%06x] = 0x%08x\n", addr, data);
init->offset += 9;
if (addr == 0x000200)
data |= 0x00000001;
init_wr32(init, addr, data);
}
/**
* INIT_RAM_RESTRICT_PLL - opcde 0x87
*
*/
static void
init_ram_restrict_pll(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 type = nv_ro08(bios, init->offset + 1);
u8 count = init_ram_restrict_group_count(init);
u8 strap = init_ram_restrict(init);
u8 cconf;
trace("RAM_RESTRICT_PLL\t0x%02x\n", type);
init->offset += 2;
for (cconf = 0; cconf < count; cconf++) {
u32 freq = nv_ro32(bios, init->offset);
if (cconf == strap) {
trace("%dkHz *\n", freq);
init_prog_pll(init, type, freq);
} else {
trace("%dkHz\n", freq);
}
init->offset += 4;
}
}
/**
* INIT_GPIO - opcode 0x8e
*
*/
static void
init_gpio(struct nvbios_init *init)
{
struct nouveau_gpio *gpio = nouveau_gpio(init->bios);
trace("GPIO\n");
init->offset += 1;
if (init_exec(init) && gpio && gpio->reset)
gpio->reset(gpio, DCB_GPIO_UNUSED);
}
/**
* INIT_RAM_RESTRICT_ZM_GROUP - opcode 0x8f
*
*/
static void
init_ram_restrict_zm_reg_group(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 addr = nv_ro32(bios, init->offset + 1);
u8 incr = nv_ro08(bios, init->offset + 5);
u8 num = nv_ro08(bios, init->offset + 6);
u8 count = init_ram_restrict_group_count(init);
u8 index = init_ram_restrict(init);
u8 i, j;
trace("RAM_RESTRICT_ZM_REG_GROUP\t"
"R[0x%08x] 0x%02x 0x%02x\n", addr, incr, num);
init->offset += 7;
for (i = 0; i < num; i++) {
trace("\tR[0x%06x] = {\n", addr);
for (j = 0; j < count; j++) {
u32 data = nv_ro32(bios, init->offset);
if (j == index) {
trace("\t\t0x%08x *\n", data);
init_wr32(init, addr, data);
} else {
trace("\t\t0x%08x\n", data);
}
init->offset += 4;
}
trace("\t}\n");
addr += incr;
}
}
/**
* INIT_COPY_ZM_REG - opcode 0x90
*
*/
static void
init_copy_zm_reg(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 sreg = nv_ro32(bios, init->offset + 1);
u32 dreg = nv_ro32(bios, init->offset + 5);
trace("COPY_ZM_REG\tR[0x%06x] = R[0x%06x]\n", dreg, sreg);
init->offset += 9;
init_wr32(init, dreg, init_rd32(init, sreg));
}
/**
* INIT_ZM_REG_GROUP - opcode 0x91
*
*/
static void
init_zm_reg_group(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 addr = nv_ro32(bios, init->offset + 1);
u8 count = nv_ro08(bios, init->offset + 5);
trace("ZM_REG_GROUP\tR[0x%06x] =\n", addr);
init->offset += 6;
while (count--) {
u32 data = nv_ro32(bios, init->offset);
trace("\t0x%08x\n", data);
init_wr32(init, addr, data);
init->offset += 4;
}
}
/**
* INIT_XLAT - opcode 0x96
*
*/
static void
init_xlat(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 saddr = nv_ro32(bios, init->offset + 1);
u8 sshift = nv_ro08(bios, init->offset + 5);
u8 smask = nv_ro08(bios, init->offset + 6);
u8 index = nv_ro08(bios, init->offset + 7);
u32 daddr = nv_ro32(bios, init->offset + 8);
u32 dmask = nv_ro32(bios, init->offset + 12);
u8 shift = nv_ro08(bios, init->offset + 16);
u32 data;
trace("INIT_XLAT\tR[0x%06x] &= 0x%08x |= "
"(X%02x((R[0x%06x] %s 0x%02x) & 0x%02x) << 0x%02x)\n",
daddr, dmask, index, saddr, (sshift & 0x80) ? "<<" : ">>",
(sshift & 0x80) ? (0x100 - sshift) : sshift, smask, shift);
init->offset += 17;
data = init_shift(init_rd32(init, saddr), sshift) & smask;
data = init_xlat_(init, index, data) << shift;
init_mask(init, daddr, ~dmask, data);
}
/**
* INIT_ZM_MASK_ADD - opcode 0x97
*
*/
static void
init_zm_mask_add(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 addr = nv_ro32(bios, init->offset + 1);
u32 mask = nv_ro32(bios, init->offset + 5);
u32 add = nv_ro32(bios, init->offset + 9);
u32 data;
trace("ZM_MASK_ADD\tR[0x%06x] &= 0x%08x += 0x%08x\n", addr, mask, add);
init->offset += 13;
data = init_rd32(init, addr);
data = (data & mask) | ((data + add) & ~mask);
init_wr32(init, addr, data);
}
/**
* INIT_AUXCH - opcode 0x98
*
*/
static void
init_auxch(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 addr = nv_ro32(bios, init->offset + 1);
u8 count = nv_ro08(bios, init->offset + 5);
trace("AUXCH\tAUX[0x%08x] 0x%02x\n", addr, count);
init->offset += 6;
while (count--) {
u8 mask = nv_ro08(bios, init->offset + 0);
u8 data = nv_ro08(bios, init->offset + 1);
trace("\tAUX[0x%08x] &= 0x%02x |= 0x%02x\n", addr, mask, data);
mask = init_rdauxr(init, addr) & mask;
init_wrauxr(init, addr, mask | data);
init->offset += 2;
}
}
/**
* INIT_AUXCH - opcode 0x99
*
*/
static void
init_zm_auxch(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u32 addr = nv_ro32(bios, init->offset + 1);
u8 count = nv_ro08(bios, init->offset + 5);
trace("ZM_AUXCH\tAUX[0x%08x] 0x%02x\n", addr, count);
init->offset += 6;
while (count--) {
u8 data = nv_ro08(bios, init->offset + 0);
trace("\tAUX[0x%08x] = 0x%02x\n", addr, data);
init_wrauxr(init, addr, data);
init->offset += 1;
}
}
/**
* INIT_I2C_LONG_IF - opcode 0x9a
*
*/
static void
init_i2c_long_if(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
u8 index = nv_ro08(bios, init->offset + 1);
u8 addr = nv_ro08(bios, init->offset + 2) >> 1;
u8 reglo = nv_ro08(bios, init->offset + 3);
u8 reghi = nv_ro08(bios, init->offset + 4);
u8 mask = nv_ro08(bios, init->offset + 5);
u8 data = nv_ro08(bios, init->offset + 6);
struct nouveau_i2c_port *port;
trace("I2C_LONG_IF\t"
"I2C[0x%02x][0x%02x][0x%02x%02x] & 0x%02x == 0x%02x\n",
index, addr, reglo, reghi, mask, data);
init->offset += 7;
port = init_i2c(init, index);
if (port) {
u8 i[2] = { reghi, reglo };
u8 o[1] = {};
struct i2c_msg msg[] = {
{ .addr = addr, .flags = 0, .len = 2, .buf = i },
{ .addr = addr, .flags = I2C_M_RD, .len = 1, .buf = o }
};
int ret;
ret = i2c_transfer(&port->adapter, msg, 2);
if (ret == 2 && ((o[0] & mask) == data))
return;
}
init_exec_set(init, false);
}
/**
* INIT_GPIO_NE - opcode 0xa9
*
*/
static void
init_gpio_ne(struct nvbios_init *init)
{
struct nouveau_bios *bios = init->bios;
struct nouveau_gpio *gpio = nouveau_gpio(bios);
struct dcb_gpio_func func;
u8 count = nv_ro08(bios, init->offset + 1);
u8 idx = 0, ver, len;
u16 data, i;
trace("GPIO_NE\t");
init->offset += 2;
for (i = init->offset; i < init->offset + count; i++)
cont("0x%02x ", nv_ro08(bios, i));
cont("\n");
while ((data = dcb_gpio_parse(bios, 0, idx++, &ver, &len, &func))) {
if (func.func != DCB_GPIO_UNUSED) {
for (i = init->offset; i < init->offset + count; i++) {
if (func.func == nv_ro08(bios, i))
break;
}
trace("\tFUNC[0x%02x]", func.func);
if (i == (init->offset + count)) {
cont(" *");
if (init_exec(init) && gpio && gpio->reset)
gpio->reset(gpio, func.func);
}
cont("\n");
}
}
init->offset += count;
}
static struct nvbios_init_opcode {
void (*exec)(struct nvbios_init *);
} init_opcode[] = {
[0x32] = { init_io_restrict_prog },
[0x33] = { init_repeat },
[0x34] = { init_io_restrict_pll },
[0x36] = { init_end_repeat },
[0x37] = { init_copy },
[0x38] = { init_not },
[0x39] = { init_io_flag_condition },
[0x3a] = { init_dp_condition },
[0x3b] = { init_io_mask_or },
[0x3c] = { init_io_or },
[0x49] = { init_idx_addr_latched },
[0x4a] = { init_io_restrict_pll2 },
[0x4b] = { init_pll2 },
[0x4c] = { init_i2c_byte },
[0x4d] = { init_zm_i2c_byte },
[0x4e] = { init_zm_i2c },
[0x4f] = { init_tmds },
[0x50] = { init_zm_tmds_group },
[0x51] = { init_cr_idx_adr_latch },
[0x52] = { init_cr },
[0x53] = { init_zm_cr },
[0x54] = { init_zm_cr_group },
[0x56] = { init_condition_time },
[0x57] = { init_ltime },
[0x58] = { init_zm_reg_sequence },
[0x5b] = { init_sub_direct },
[0x5c] = { init_jump },
[0x5e] = { init_i2c_if },
[0x5f] = { init_copy_nv_reg },
[0x62] = { init_zm_index_io },
[0x63] = { init_compute_mem },
[0x65] = { init_reset },
[0x66] = { init_configure_mem },
[0x67] = { init_configure_clk },
[0x68] = { init_configure_preinit },
[0x69] = { init_io },
[0x6b] = { init_sub },
[0x6d] = { init_ram_condition },
[0x6e] = { init_nv_reg },
[0x6f] = { init_macro },
[0x71] = { init_done },
[0x72] = { init_resume },
[0x74] = { init_time },
[0x75] = { init_condition },
[0x76] = { init_io_condition },
[0x78] = { init_index_io },
[0x79] = { init_pll },
[0x7a] = { init_zm_reg },
[0x87] = { init_ram_restrict_pll },
[0x8c] = { init_reserved },
[0x8d] = { init_reserved },
[0x8e] = { init_gpio },
[0x8f] = { init_ram_restrict_zm_reg_group },
[0x90] = { init_copy_zm_reg },
[0x91] = { init_zm_reg_group },
[0x92] = { init_reserved },
[0x96] = { init_xlat },
[0x97] = { init_zm_mask_add },
[0x98] = { init_auxch },
[0x99] = { init_zm_auxch },
[0x9a] = { init_i2c_long_if },
[0xa9] = { init_gpio_ne },
[0xaa] = { init_reserved },
};
#define init_opcode_nr (sizeof(init_opcode) / sizeof(init_opcode[0]))
int
nvbios_exec(struct nvbios_init *init)
{
init->nested++;
while (init->offset) {
u8 opcode = nv_ro08(init->bios, init->offset);
if (opcode >= init_opcode_nr || !init_opcode[opcode].exec) {
error("unknown opcode 0x%02x\n", opcode);
return -EINVAL;
}
init_opcode[opcode].exec(init);
}
init->nested--;
return 0;
}
int
nvbios_init(struct nouveau_subdev *subdev, bool execute)
{
struct nouveau_bios *bios = nouveau_bios(subdev);
int ret = 0;
int i = -1;
u16 data;
if (execute)
nv_info(bios, "running init tables\n");
while (!ret && (data = (init_script(bios, ++i)))) {
struct nvbios_init init = {
.subdev = subdev,
.bios = bios,
.offset = data,
.outp = NULL,
.crtc = -1,
.execute = execute ? 1 : 0,
};
ret = nvbios_exec(&init);
}
/* the vbios parser will run this right after the normal init
* tables, whereas the binary driver appears to run it later.
*/
if (!ret && (data = init_unknown_script(bios))) {
struct nvbios_init init = {
.subdev = subdev,
.bios = bios,
.offset = data,
.outp = NULL,
.crtc = -1,
.execute = execute ? 1 : 0,
};
ret = nvbios_exec(&init);
}
return 0;
}
| gpl-2.0 |
pakohan/syso-kernel | linux-3.10.16/sound/soc/atmel/sam9g20_wm8731.c | 2145 | 8484 | /*
* sam9g20_wm8731 -- SoC audio for AT91SAM9G20-based
* ATMEL AT91SAM9G20ek board.
*
* Copyright (C) 2005 SAN People
* Copyright (C) 2008 Atmel
*
* Authors: Sedji Gaouaou <sedji.gaouaou@atmel.com>
*
* Based on ati_b1_wm8731.c by:
* Frank Mandarino <fmandarino@endrelia.com>
* Copyright 2006 Endrelia Technologies Inc.
* Based on corgi.c by:
* Copyright 2005 Wolfson Microelectronics PLC.
* Copyright 2005 Openedhand Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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/moduleparam.h>
#include <linux/kernel.h>
#include <linux/clk.h>
#include <linux/timer.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/i2c.h>
#include <linux/pinctrl/consumer.h>
#include <linux/atmel-ssc.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <asm/mach-types.h>
#include <mach/hardware.h>
#include <mach/gpio.h>
#include "../codecs/wm8731.h"
#include "atmel-pcm.h"
#include "atmel_ssc_dai.h"
#define MCLK_RATE 12000000
/*
* As shipped the board does not have inputs. However, it is relatively
* straightforward to modify the board to hook them up so support is left
* in the driver.
*/
#undef ENABLE_MIC_INPUT
static struct clk *mclk;
static int at91sam9g20ek_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;
int 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 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;
return 0;
}
static struct snd_soc_ops at91sam9g20ek_ops = {
.hw_params = at91sam9g20ek_hw_params,
};
static int at91sam9g20ek_set_bias_level(struct snd_soc_card *card,
struct snd_soc_dapm_context *dapm,
enum snd_soc_bias_level level)
{
static int mclk_on;
int ret = 0;
switch (level) {
case SND_SOC_BIAS_ON:
case SND_SOC_BIAS_PREPARE:
if (!mclk_on)
ret = clk_enable(mclk);
if (ret == 0)
mclk_on = 1;
break;
case SND_SOC_BIAS_OFF:
case SND_SOC_BIAS_STANDBY:
if (mclk_on)
clk_disable(mclk);
mclk_on = 0;
break;
}
return ret;
}
static const struct snd_soc_dapm_widget at91sam9g20ek_dapm_widgets[] = {
SND_SOC_DAPM_MIC("Int Mic", NULL),
SND_SOC_DAPM_SPK("Ext Spk", NULL),
};
static const struct snd_soc_dapm_route intercon[] = {
/* speaker connected to LHPOUT */
{"Ext Spk", NULL, "LHPOUT"},
/* mic is connected to Mic Jack, with WM8731 Mic Bias */
{"MICIN", NULL, "Mic Bias"},
{"Mic Bias", NULL, "Int Mic"},
};
/*
* Logic for a wm8731 as connected on a at91sam9g20ek board.
*/
static int at91sam9g20ek_wm8731_init(struct snd_soc_pcm_runtime *rtd)
{
struct snd_soc_codec *codec = rtd->codec;
struct snd_soc_dai *codec_dai = rtd->codec_dai;
struct snd_soc_dapm_context *dapm = &codec->dapm;
int ret;
printk(KERN_DEBUG
"at91sam9g20ek_wm8731 "
": at91sam9g20ek_wm8731_init() called\n");
ret = snd_soc_dai_set_sysclk(codec_dai, WM8731_SYSCLK_MCLK,
MCLK_RATE, SND_SOC_CLOCK_IN);
if (ret < 0) {
printk(KERN_ERR "Failed to set WM8731 SYSCLK: %d\n", ret);
return ret;
}
/* Add specific widgets */
snd_soc_dapm_new_controls(dapm, at91sam9g20ek_dapm_widgets,
ARRAY_SIZE(at91sam9g20ek_dapm_widgets));
/* Set up specific audio path interconnects */
snd_soc_dapm_add_routes(dapm, intercon, ARRAY_SIZE(intercon));
/* not connected */
snd_soc_dapm_nc_pin(dapm, "RLINEIN");
snd_soc_dapm_nc_pin(dapm, "LLINEIN");
#ifdef ENABLE_MIC_INPUT
snd_soc_dapm_enable_pin(dapm, "Int Mic");
#else
snd_soc_dapm_nc_pin(dapm, "Int Mic");
#endif
/* always connected */
snd_soc_dapm_enable_pin(dapm, "Ext Spk");
return 0;
}
static struct snd_soc_dai_link at91sam9g20ek_dai = {
.name = "WM8731",
.stream_name = "WM8731 PCM",
.cpu_dai_name = "at91rm9200_ssc.0",
.codec_dai_name = "wm8731-hifi",
.init = at91sam9g20ek_wm8731_init,
.platform_name = "at91rm9200_ssc.0",
.codec_name = "wm8731.0-001b",
.ops = &at91sam9g20ek_ops,
};
static struct snd_soc_card snd_soc_at91sam9g20ek = {
.name = "AT91SAMG20-EK",
.owner = THIS_MODULE,
.dai_link = &at91sam9g20ek_dai,
.num_links = 1,
.set_bias_level = at91sam9g20ek_set_bias_level,
};
static int at91sam9g20ek_audio_probe(struct platform_device *pdev)
{
struct device_node *np = pdev->dev.of_node;
struct device_node *codec_np, *cpu_np;
struct clk *pllb;
struct snd_soc_card *card = &snd_soc_at91sam9g20ek;
struct pinctrl *pinctrl;
int ret;
pinctrl = devm_pinctrl_get_select_default(&pdev->dev);
if (IS_ERR(pinctrl)) {
dev_err(&pdev->dev, "Failed to request pinctrl for mck\n");
return PTR_ERR(pinctrl);
}
if (!np) {
if (!(machine_is_at91sam9g20ek() ||
machine_is_at91sam9g20ek_2mmc()))
return -ENODEV;
}
ret = atmel_ssc_set_audio(0);
if (ret) {
dev_err(&pdev->dev, "ssc channel is not valid\n");
return -EINVAL;
}
/*
* Codec MCLK is supplied by PCK0 - set it up.
*/
mclk = clk_get(NULL, "pck0");
if (IS_ERR(mclk)) {
printk(KERN_ERR "ASoC: Failed to get MCLK\n");
ret = PTR_ERR(mclk);
goto err;
}
pllb = clk_get(NULL, "pllb");
if (IS_ERR(pllb)) {
printk(KERN_ERR "ASoC: Failed to get PLLB\n");
ret = PTR_ERR(pllb);
goto err_mclk;
}
ret = clk_set_parent(mclk, pllb);
clk_put(pllb);
if (ret != 0) {
printk(KERN_ERR "ASoC: Failed to set MCLK parent\n");
goto err_mclk;
}
clk_set_rate(mclk, MCLK_RATE);
card->dev = &pdev->dev;
/* Parse device node info */
if (np) {
ret = snd_soc_of_parse_card_name(card, "atmel,model");
if (ret)
goto err;
ret = snd_soc_of_parse_audio_routing(card,
"atmel,audio-routing");
if (ret)
goto err;
/* Parse codec info */
at91sam9g20ek_dai.codec_name = NULL;
codec_np = of_parse_phandle(np, "atmel,audio-codec", 0);
if (!codec_np) {
dev_err(&pdev->dev, "codec info missing\n");
return -EINVAL;
}
at91sam9g20ek_dai.codec_of_node = codec_np;
/* Parse dai and platform info */
at91sam9g20ek_dai.cpu_dai_name = NULL;
at91sam9g20ek_dai.platform_name = NULL;
cpu_np = of_parse_phandle(np, "atmel,ssc-controller", 0);
if (!cpu_np) {
dev_err(&pdev->dev, "dai and pcm info missing\n");
return -EINVAL;
}
at91sam9g20ek_dai.cpu_of_node = cpu_np;
at91sam9g20ek_dai.platform_of_node = cpu_np;
of_node_put(codec_np);
of_node_put(cpu_np);
}
ret = snd_soc_register_card(card);
if (ret) {
printk(KERN_ERR "ASoC: snd_soc_register_card() failed\n");
}
return ret;
err_mclk:
clk_put(mclk);
mclk = NULL;
err:
atmel_ssc_put_audio(0);
return ret;
}
static int at91sam9g20ek_audio_remove(struct platform_device *pdev)
{
struct snd_soc_card *card = platform_get_drvdata(pdev);
clk_disable(mclk);
mclk = NULL;
snd_soc_unregister_card(card);
atmel_ssc_put_audio(0);
return 0;
}
#ifdef CONFIG_OF
static const struct of_device_id at91sam9g20ek_wm8731_dt_ids[] = {
{ .compatible = "atmel,at91sam9g20ek-wm8731-audio", },
{ }
};
MODULE_DEVICE_TABLE(of, at91sam9g20ek_wm8731_dt_ids);
#endif
static struct platform_driver at91sam9g20ek_audio_driver = {
.driver = {
.name = "at91sam9g20ek-audio",
.owner = THIS_MODULE,
.of_match_table = of_match_ptr(at91sam9g20ek_wm8731_dt_ids),
},
.probe = at91sam9g20ek_audio_probe,
.remove = at91sam9g20ek_audio_remove,
};
module_platform_driver(at91sam9g20ek_audio_driver);
/* Module information */
MODULE_AUTHOR("Sedji Gaouaou <sedji.gaouaou@atmel.com>");
MODULE_DESCRIPTION("ALSA SoC AT91SAM9G20EK_WM8731");
MODULE_ALIAS("platform:at91sam9g20ek-audio");
MODULE_LICENSE("GPL");
| gpl-2.0 |
friedrich420/AEL_NOTE4_N910FXXU1ANK4 | drivers/scsi/fcoe/fcoe_sysfs.c | 2145 | 26408 | /*
* Copyright(c) 2011 - 2012 Intel Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* 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.
*
* Maintained at www.Open-FCoE.org
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/etherdevice.h>
#include <linux/ctype.h>
#include <scsi/fcoe_sysfs.h>
#include <scsi/libfcoe.h>
/*
* OK to include local libfcoe.h for debug_logging, but cannot include
* <scsi/libfcoe.h> otherwise non-netdev based fcoe solutions would have
* have to include more than fcoe_sysfs.h.
*/
#include "libfcoe.h"
static atomic_t ctlr_num;
static atomic_t fcf_num;
/*
* fcoe_fcf_dev_loss_tmo: the default number of seconds that fcoe sysfs
* should insulate the loss of a fcf.
*/
static unsigned int fcoe_fcf_dev_loss_tmo = 1800; /* seconds */
module_param_named(fcf_dev_loss_tmo, fcoe_fcf_dev_loss_tmo,
uint, S_IRUGO|S_IWUSR);
MODULE_PARM_DESC(fcf_dev_loss_tmo,
"Maximum number of seconds that libfcoe should"
" insulate the loss of a fcf. Once this value is"
" exceeded, the fcf is removed.");
/*
* These are used by the fcoe_*_show_function routines, they
* are intentionally placed in the .c file as they're not intended
* for use throughout the code.
*/
#define fcoe_ctlr_id(x) \
((x)->id)
#define fcoe_ctlr_work_q_name(x) \
((x)->work_q_name)
#define fcoe_ctlr_work_q(x) \
((x)->work_q)
#define fcoe_ctlr_devloss_work_q_name(x) \
((x)->devloss_work_q_name)
#define fcoe_ctlr_devloss_work_q(x) \
((x)->devloss_work_q)
#define fcoe_ctlr_mode(x) \
((x)->mode)
#define fcoe_ctlr_fcf_dev_loss_tmo(x) \
((x)->fcf_dev_loss_tmo)
#define fcoe_ctlr_link_fail(x) \
((x)->lesb.lesb_link_fail)
#define fcoe_ctlr_vlink_fail(x) \
((x)->lesb.lesb_vlink_fail)
#define fcoe_ctlr_miss_fka(x) \
((x)->lesb.lesb_miss_fka)
#define fcoe_ctlr_symb_err(x) \
((x)->lesb.lesb_symb_err)
#define fcoe_ctlr_err_block(x) \
((x)->lesb.lesb_err_block)
#define fcoe_ctlr_fcs_error(x) \
((x)->lesb.lesb_fcs_error)
#define fcoe_ctlr_enabled(x) \
((x)->enabled)
#define fcoe_fcf_state(x) \
((x)->state)
#define fcoe_fcf_fabric_name(x) \
((x)->fabric_name)
#define fcoe_fcf_switch_name(x) \
((x)->switch_name)
#define fcoe_fcf_fc_map(x) \
((x)->fc_map)
#define fcoe_fcf_vfid(x) \
((x)->vfid)
#define fcoe_fcf_mac(x) \
((x)->mac)
#define fcoe_fcf_priority(x) \
((x)->priority)
#define fcoe_fcf_fka_period(x) \
((x)->fka_period)
#define fcoe_fcf_dev_loss_tmo(x) \
((x)->dev_loss_tmo)
#define fcoe_fcf_selected(x) \
((x)->selected)
#define fcoe_fcf_vlan_id(x) \
((x)->vlan_id)
/*
* dev_loss_tmo attribute
*/
static int fcoe_str_to_dev_loss(const char *buf, unsigned long *val)
{
int ret;
ret = kstrtoul(buf, 0, val);
if (ret)
return -EINVAL;
/*
* Check for overflow; dev_loss_tmo is u32
*/
if (*val > UINT_MAX)
return -EINVAL;
return 0;
}
static int fcoe_fcf_set_dev_loss_tmo(struct fcoe_fcf_device *fcf,
unsigned long val)
{
if ((fcf->state == FCOE_FCF_STATE_UNKNOWN) ||
(fcf->state == FCOE_FCF_STATE_DISCONNECTED) ||
(fcf->state == FCOE_FCF_STATE_DELETED))
return -EBUSY;
/*
* Check for overflow; dev_loss_tmo is u32
*/
if (val > UINT_MAX)
return -EINVAL;
fcoe_fcf_dev_loss_tmo(fcf) = val;
return 0;
}
#define FCOE_DEVICE_ATTR(_prefix, _name, _mode, _show, _store) \
struct device_attribute device_attr_fcoe_##_prefix##_##_name = \
__ATTR(_name, _mode, _show, _store)
#define fcoe_ctlr_show_function(field, format_string, sz, cast) \
static ssize_t show_fcoe_ctlr_device_##field(struct device *dev, \
struct device_attribute *attr, \
char *buf) \
{ \
struct fcoe_ctlr_device *ctlr = dev_to_ctlr(dev); \
if (ctlr->f->get_fcoe_ctlr_##field) \
ctlr->f->get_fcoe_ctlr_##field(ctlr); \
return snprintf(buf, sz, format_string, \
cast fcoe_ctlr_##field(ctlr)); \
}
#define fcoe_fcf_show_function(field, format_string, sz, cast) \
static ssize_t show_fcoe_fcf_device_##field(struct device *dev, \
struct device_attribute *attr, \
char *buf) \
{ \
struct fcoe_fcf_device *fcf = dev_to_fcf(dev); \
struct fcoe_ctlr_device *ctlr = fcoe_fcf_dev_to_ctlr_dev(fcf); \
if (ctlr->f->get_fcoe_fcf_##field) \
ctlr->f->get_fcoe_fcf_##field(fcf); \
return snprintf(buf, sz, format_string, \
cast fcoe_fcf_##field(fcf)); \
}
#define fcoe_ctlr_private_show_function(field, format_string, sz, cast) \
static ssize_t show_fcoe_ctlr_device_##field(struct device *dev, \
struct device_attribute *attr, \
char *buf) \
{ \
struct fcoe_ctlr_device *ctlr = dev_to_ctlr(dev); \
return snprintf(buf, sz, format_string, cast fcoe_ctlr_##field(ctlr)); \
}
#define fcoe_fcf_private_show_function(field, format_string, sz, cast) \
static ssize_t show_fcoe_fcf_device_##field(struct device *dev, \
struct device_attribute *attr, \
char *buf) \
{ \
struct fcoe_fcf_device *fcf = dev_to_fcf(dev); \
return snprintf(buf, sz, format_string, cast fcoe_fcf_##field(fcf)); \
}
#define fcoe_ctlr_private_rd_attr(field, format_string, sz) \
fcoe_ctlr_private_show_function(field, format_string, sz, ) \
static FCOE_DEVICE_ATTR(ctlr, field, S_IRUGO, \
show_fcoe_ctlr_device_##field, NULL)
#define fcoe_ctlr_rd_attr(field, format_string, sz) \
fcoe_ctlr_show_function(field, format_string, sz, ) \
static FCOE_DEVICE_ATTR(ctlr, field, S_IRUGO, \
show_fcoe_ctlr_device_##field, NULL)
#define fcoe_fcf_rd_attr(field, format_string, sz) \
fcoe_fcf_show_function(field, format_string, sz, ) \
static FCOE_DEVICE_ATTR(fcf, field, S_IRUGO, \
show_fcoe_fcf_device_##field, NULL)
#define fcoe_fcf_private_rd_attr(field, format_string, sz) \
fcoe_fcf_private_show_function(field, format_string, sz, ) \
static FCOE_DEVICE_ATTR(fcf, field, S_IRUGO, \
show_fcoe_fcf_device_##field, NULL)
#define fcoe_ctlr_private_rd_attr_cast(field, format_string, sz, cast) \
fcoe_ctlr_private_show_function(field, format_string, sz, (cast)) \
static FCOE_DEVICE_ATTR(ctlr, field, S_IRUGO, \
show_fcoe_ctlr_device_##field, NULL)
#define fcoe_fcf_private_rd_attr_cast(field, format_string, sz, cast) \
fcoe_fcf_private_show_function(field, format_string, sz, (cast)) \
static FCOE_DEVICE_ATTR(fcf, field, S_IRUGO, \
show_fcoe_fcf_device_##field, NULL)
#define fcoe_enum_name_search(title, table_type, table) \
static const char *get_fcoe_##title##_name(enum table_type table_key) \
{ \
if (table_key < 0 || table_key >= ARRAY_SIZE(table)) \
return NULL; \
return table[table_key]; \
}
static char *fip_conn_type_names[] = {
[ FIP_CONN_TYPE_UNKNOWN ] = "Unknown",
[ FIP_CONN_TYPE_FABRIC ] = "Fabric",
[ FIP_CONN_TYPE_VN2VN ] = "VN2VN",
};
fcoe_enum_name_search(ctlr_mode, fip_conn_type, fip_conn_type_names)
static enum fip_conn_type fcoe_parse_mode(const char *buf)
{
int i;
for (i = 0; i < ARRAY_SIZE(fip_conn_type_names); i++) {
if (strcasecmp(buf, fip_conn_type_names[i]) == 0)
return i;
}
return FIP_CONN_TYPE_UNKNOWN;
}
static char *fcf_state_names[] = {
[ FCOE_FCF_STATE_UNKNOWN ] = "Unknown",
[ FCOE_FCF_STATE_DISCONNECTED ] = "Disconnected",
[ FCOE_FCF_STATE_CONNECTED ] = "Connected",
};
fcoe_enum_name_search(fcf_state, fcf_state, fcf_state_names)
#define FCOE_FCF_STATE_MAX_NAMELEN 50
static ssize_t show_fcf_state(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct fcoe_fcf_device *fcf = dev_to_fcf(dev);
const char *name;
name = get_fcoe_fcf_state_name(fcf->state);
if (!name)
return -EINVAL;
return snprintf(buf, FCOE_FCF_STATE_MAX_NAMELEN, "%s\n", name);
}
static FCOE_DEVICE_ATTR(fcf, state, S_IRUGO, show_fcf_state, NULL);
#define FCOE_MAX_MODENAME_LEN 20
static ssize_t show_ctlr_mode(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct fcoe_ctlr_device *ctlr = dev_to_ctlr(dev);
const char *name;
name = get_fcoe_ctlr_mode_name(ctlr->mode);
if (!name)
return -EINVAL;
return snprintf(buf, FCOE_MAX_MODENAME_LEN,
"%s\n", name);
}
static ssize_t store_ctlr_mode(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct fcoe_ctlr_device *ctlr = dev_to_ctlr(dev);
char mode[FCOE_MAX_MODENAME_LEN + 1];
if (count > FCOE_MAX_MODENAME_LEN)
return -EINVAL;
strncpy(mode, buf, count);
if (mode[count - 1] == '\n')
mode[count - 1] = '\0';
else
mode[count] = '\0';
switch (ctlr->enabled) {
case FCOE_CTLR_ENABLED:
LIBFCOE_SYSFS_DBG(ctlr, "Cannot change mode when enabled.");
return -EBUSY;
case FCOE_CTLR_DISABLED:
if (!ctlr->f->set_fcoe_ctlr_mode) {
LIBFCOE_SYSFS_DBG(ctlr,
"Mode change not supported by LLD.");
return -ENOTSUPP;
}
ctlr->mode = fcoe_parse_mode(mode);
if (ctlr->mode == FIP_CONN_TYPE_UNKNOWN) {
LIBFCOE_SYSFS_DBG(ctlr,
"Unknown mode %s provided.", buf);
return -EINVAL;
}
ctlr->f->set_fcoe_ctlr_mode(ctlr);
LIBFCOE_SYSFS_DBG(ctlr, "Mode changed to %s.", buf);
return count;
case FCOE_CTLR_UNUSED:
default:
LIBFCOE_SYSFS_DBG(ctlr, "Mode change not supported.");
return -ENOTSUPP;
};
}
static FCOE_DEVICE_ATTR(ctlr, mode, S_IRUGO | S_IWUSR,
show_ctlr_mode, store_ctlr_mode);
static ssize_t store_ctlr_enabled(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct fcoe_ctlr_device *ctlr = dev_to_ctlr(dev);
int rc;
switch (ctlr->enabled) {
case FCOE_CTLR_ENABLED:
if (*buf == '1')
return count;
ctlr->enabled = FCOE_CTLR_DISABLED;
break;
case FCOE_CTLR_DISABLED:
if (*buf == '0')
return count;
ctlr->enabled = FCOE_CTLR_ENABLED;
break;
case FCOE_CTLR_UNUSED:
return -ENOTSUPP;
};
rc = ctlr->f->set_fcoe_ctlr_enabled(ctlr);
if (rc)
return rc;
return count;
}
static char *ctlr_enabled_state_names[] = {
[ FCOE_CTLR_ENABLED ] = "1",
[ FCOE_CTLR_DISABLED ] = "0",
};
fcoe_enum_name_search(ctlr_enabled_state, ctlr_enabled_state,
ctlr_enabled_state_names)
#define FCOE_CTLR_ENABLED_MAX_NAMELEN 50
static ssize_t show_ctlr_enabled_state(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct fcoe_ctlr_device *ctlr = dev_to_ctlr(dev);
const char *name;
name = get_fcoe_ctlr_enabled_state_name(ctlr->enabled);
if (!name)
return -EINVAL;
return snprintf(buf, FCOE_CTLR_ENABLED_MAX_NAMELEN,
"%s\n", name);
}
static FCOE_DEVICE_ATTR(ctlr, enabled, S_IRUGO | S_IWUSR,
show_ctlr_enabled_state,
store_ctlr_enabled);
static ssize_t
store_private_fcoe_ctlr_fcf_dev_loss_tmo(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct fcoe_ctlr_device *ctlr = dev_to_ctlr(dev);
struct fcoe_fcf_device *fcf;
unsigned long val;
int rc;
rc = fcoe_str_to_dev_loss(buf, &val);
if (rc)
return rc;
fcoe_ctlr_fcf_dev_loss_tmo(ctlr) = val;
mutex_lock(&ctlr->lock);
list_for_each_entry(fcf, &ctlr->fcfs, peers)
fcoe_fcf_set_dev_loss_tmo(fcf, val);
mutex_unlock(&ctlr->lock);
return count;
}
fcoe_ctlr_private_show_function(fcf_dev_loss_tmo, "%d\n", 20, );
static FCOE_DEVICE_ATTR(ctlr, fcf_dev_loss_tmo, S_IRUGO | S_IWUSR,
show_fcoe_ctlr_device_fcf_dev_loss_tmo,
store_private_fcoe_ctlr_fcf_dev_loss_tmo);
/* Link Error Status Block (LESB) */
fcoe_ctlr_rd_attr(link_fail, "%u\n", 20);
fcoe_ctlr_rd_attr(vlink_fail, "%u\n", 20);
fcoe_ctlr_rd_attr(miss_fka, "%u\n", 20);
fcoe_ctlr_rd_attr(symb_err, "%u\n", 20);
fcoe_ctlr_rd_attr(err_block, "%u\n", 20);
fcoe_ctlr_rd_attr(fcs_error, "%u\n", 20);
fcoe_fcf_private_rd_attr_cast(fabric_name, "0x%llx\n", 20, unsigned long long);
fcoe_fcf_private_rd_attr_cast(switch_name, "0x%llx\n", 20, unsigned long long);
fcoe_fcf_private_rd_attr(priority, "%u\n", 20);
fcoe_fcf_private_rd_attr(fc_map, "0x%x\n", 20);
fcoe_fcf_private_rd_attr(vfid, "%u\n", 20);
fcoe_fcf_private_rd_attr(mac, "%pM\n", 20);
fcoe_fcf_private_rd_attr(fka_period, "%u\n", 20);
fcoe_fcf_rd_attr(selected, "%u\n", 20);
fcoe_fcf_rd_attr(vlan_id, "%u\n", 20);
fcoe_fcf_private_show_function(dev_loss_tmo, "%d\n", 20, )
static ssize_t
store_fcoe_fcf_dev_loss_tmo(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct fcoe_fcf_device *fcf = dev_to_fcf(dev);
unsigned long val;
int rc;
rc = fcoe_str_to_dev_loss(buf, &val);
if (rc)
return rc;
rc = fcoe_fcf_set_dev_loss_tmo(fcf, val);
if (rc)
return rc;
return count;
}
static FCOE_DEVICE_ATTR(fcf, dev_loss_tmo, S_IRUGO | S_IWUSR,
show_fcoe_fcf_device_dev_loss_tmo,
store_fcoe_fcf_dev_loss_tmo);
static struct attribute *fcoe_ctlr_lesb_attrs[] = {
&device_attr_fcoe_ctlr_link_fail.attr,
&device_attr_fcoe_ctlr_vlink_fail.attr,
&device_attr_fcoe_ctlr_miss_fka.attr,
&device_attr_fcoe_ctlr_symb_err.attr,
&device_attr_fcoe_ctlr_err_block.attr,
&device_attr_fcoe_ctlr_fcs_error.attr,
NULL,
};
static struct attribute_group fcoe_ctlr_lesb_attr_group = {
.name = "lesb",
.attrs = fcoe_ctlr_lesb_attrs,
};
static struct attribute *fcoe_ctlr_attrs[] = {
&device_attr_fcoe_ctlr_fcf_dev_loss_tmo.attr,
&device_attr_fcoe_ctlr_enabled.attr,
&device_attr_fcoe_ctlr_mode.attr,
NULL,
};
static struct attribute_group fcoe_ctlr_attr_group = {
.attrs = fcoe_ctlr_attrs,
};
static const struct attribute_group *fcoe_ctlr_attr_groups[] = {
&fcoe_ctlr_attr_group,
&fcoe_ctlr_lesb_attr_group,
NULL,
};
static struct attribute *fcoe_fcf_attrs[] = {
&device_attr_fcoe_fcf_fabric_name.attr,
&device_attr_fcoe_fcf_switch_name.attr,
&device_attr_fcoe_fcf_dev_loss_tmo.attr,
&device_attr_fcoe_fcf_fc_map.attr,
&device_attr_fcoe_fcf_vfid.attr,
&device_attr_fcoe_fcf_mac.attr,
&device_attr_fcoe_fcf_priority.attr,
&device_attr_fcoe_fcf_fka_period.attr,
&device_attr_fcoe_fcf_state.attr,
&device_attr_fcoe_fcf_selected.attr,
&device_attr_fcoe_fcf_vlan_id.attr,
NULL
};
static struct attribute_group fcoe_fcf_attr_group = {
.attrs = fcoe_fcf_attrs,
};
static const struct attribute_group *fcoe_fcf_attr_groups[] = {
&fcoe_fcf_attr_group,
NULL,
};
struct bus_type fcoe_bus_type;
static int fcoe_bus_match(struct device *dev,
struct device_driver *drv)
{
if (dev->bus == &fcoe_bus_type)
return 1;
return 0;
}
/**
* fcoe_ctlr_device_release() - Release the FIP ctlr memory
* @dev: Pointer to the FIP ctlr's embedded device
*
* Called when the last FIP ctlr reference is released.
*/
static void fcoe_ctlr_device_release(struct device *dev)
{
struct fcoe_ctlr_device *ctlr = dev_to_ctlr(dev);
kfree(ctlr);
}
/**
* fcoe_fcf_device_release() - Release the FIP fcf memory
* @dev: Pointer to the fcf's embedded device
*
* Called when the last FIP fcf reference is released.
*/
static void fcoe_fcf_device_release(struct device *dev)
{
struct fcoe_fcf_device *fcf = dev_to_fcf(dev);
kfree(fcf);
}
struct device_type fcoe_ctlr_device_type = {
.name = "fcoe_ctlr",
.groups = fcoe_ctlr_attr_groups,
.release = fcoe_ctlr_device_release,
};
struct device_type fcoe_fcf_device_type = {
.name = "fcoe_fcf",
.groups = fcoe_fcf_attr_groups,
.release = fcoe_fcf_device_release,
};
struct bus_attribute fcoe_bus_attr_group[] = {
__ATTR(ctlr_create, S_IWUSR, NULL, fcoe_ctlr_create_store),
__ATTR(ctlr_destroy, S_IWUSR, NULL, fcoe_ctlr_destroy_store),
__ATTR_NULL
};
struct bus_type fcoe_bus_type = {
.name = "fcoe",
.match = &fcoe_bus_match,
.bus_attrs = fcoe_bus_attr_group,
};
/**
* fcoe_ctlr_device_flush_work() - Flush a FIP ctlr's workqueue
* @ctlr: Pointer to the FIP ctlr whose workqueue is to be flushed
*/
void fcoe_ctlr_device_flush_work(struct fcoe_ctlr_device *ctlr)
{
if (!fcoe_ctlr_work_q(ctlr)) {
printk(KERN_ERR
"ERROR: FIP Ctlr '%d' attempted to flush work, "
"when no workqueue created.\n", ctlr->id);
dump_stack();
return;
}
flush_workqueue(fcoe_ctlr_work_q(ctlr));
}
/**
* fcoe_ctlr_device_queue_work() - Schedule work for a FIP ctlr's workqueue
* @ctlr: Pointer to the FIP ctlr who owns the devloss workqueue
* @work: Work to queue for execution
*
* Return value:
* 1 on success / 0 already queued / < 0 for error
*/
int fcoe_ctlr_device_queue_work(struct fcoe_ctlr_device *ctlr,
struct work_struct *work)
{
if (unlikely(!fcoe_ctlr_work_q(ctlr))) {
printk(KERN_ERR
"ERROR: FIP Ctlr '%d' attempted to queue work, "
"when no workqueue created.\n", ctlr->id);
dump_stack();
return -EINVAL;
}
return queue_work(fcoe_ctlr_work_q(ctlr), work);
}
/**
* fcoe_ctlr_device_flush_devloss() - Flush a FIP ctlr's devloss workqueue
* @ctlr: Pointer to FIP ctlr whose workqueue is to be flushed
*/
void fcoe_ctlr_device_flush_devloss(struct fcoe_ctlr_device *ctlr)
{
if (!fcoe_ctlr_devloss_work_q(ctlr)) {
printk(KERN_ERR
"ERROR: FIP Ctlr '%d' attempted to flush work, "
"when no workqueue created.\n", ctlr->id);
dump_stack();
return;
}
flush_workqueue(fcoe_ctlr_devloss_work_q(ctlr));
}
/**
* fcoe_ctlr_device_queue_devloss_work() - Schedule work for a FIP ctlr's devloss workqueue
* @ctlr: Pointer to the FIP ctlr who owns the devloss workqueue
* @work: Work to queue for execution
* @delay: jiffies to delay the work queuing
*
* Return value:
* 1 on success / 0 already queued / < 0 for error
*/
int fcoe_ctlr_device_queue_devloss_work(struct fcoe_ctlr_device *ctlr,
struct delayed_work *work,
unsigned long delay)
{
if (unlikely(!fcoe_ctlr_devloss_work_q(ctlr))) {
printk(KERN_ERR
"ERROR: FIP Ctlr '%d' attempted to queue work, "
"when no workqueue created.\n", ctlr->id);
dump_stack();
return -EINVAL;
}
return queue_delayed_work(fcoe_ctlr_devloss_work_q(ctlr), work, delay);
}
static int fcoe_fcf_device_match(struct fcoe_fcf_device *new,
struct fcoe_fcf_device *old)
{
if (new->switch_name == old->switch_name &&
new->fabric_name == old->fabric_name &&
new->fc_map == old->fc_map &&
compare_ether_addr(new->mac, old->mac) == 0)
return 1;
return 0;
}
/**
* fcoe_ctlr_device_add() - Add a FIP ctlr to sysfs
* @parent: The parent device to which the fcoe_ctlr instance
* should be attached
* @f: The LLD's FCoE sysfs function template pointer
* @priv_size: Size to be allocated with the fcoe_ctlr_device for the LLD
*
* This routine allocates a FIP ctlr object with some additional memory
* for the LLD. The FIP ctlr is initialized, added to sysfs and then
* attributes are added to it.
*/
struct fcoe_ctlr_device *fcoe_ctlr_device_add(struct device *parent,
struct fcoe_sysfs_function_template *f,
int priv_size)
{
struct fcoe_ctlr_device *ctlr;
int error = 0;
ctlr = kzalloc(sizeof(struct fcoe_ctlr_device) + priv_size,
GFP_KERNEL);
if (!ctlr)
goto out;
ctlr->id = atomic_inc_return(&ctlr_num) - 1;
ctlr->f = f;
ctlr->mode = FIP_CONN_TYPE_FABRIC;
INIT_LIST_HEAD(&ctlr->fcfs);
mutex_init(&ctlr->lock);
ctlr->dev.parent = parent;
ctlr->dev.bus = &fcoe_bus_type;
ctlr->dev.type = &fcoe_ctlr_device_type;
ctlr->fcf_dev_loss_tmo = fcoe_fcf_dev_loss_tmo;
snprintf(ctlr->work_q_name, sizeof(ctlr->work_q_name),
"ctlr_wq_%d", ctlr->id);
ctlr->work_q = create_singlethread_workqueue(
ctlr->work_q_name);
if (!ctlr->work_q)
goto out_del;
snprintf(ctlr->devloss_work_q_name,
sizeof(ctlr->devloss_work_q_name),
"ctlr_dl_wq_%d", ctlr->id);
ctlr->devloss_work_q = create_singlethread_workqueue(
ctlr->devloss_work_q_name);
if (!ctlr->devloss_work_q)
goto out_del_q;
dev_set_name(&ctlr->dev, "ctlr_%d", ctlr->id);
error = device_register(&ctlr->dev);
if (error)
goto out_del_q2;
return ctlr;
out_del_q2:
destroy_workqueue(ctlr->devloss_work_q);
ctlr->devloss_work_q = NULL;
out_del_q:
destroy_workqueue(ctlr->work_q);
ctlr->work_q = NULL;
out_del:
kfree(ctlr);
out:
return NULL;
}
EXPORT_SYMBOL_GPL(fcoe_ctlr_device_add);
/**
* fcoe_ctlr_device_delete() - Delete a FIP ctlr and its subtree from sysfs
* @ctlr: A pointer to the ctlr to be deleted
*
* Deletes a FIP ctlr and any fcfs attached
* to it. Deleting fcfs will cause their childen
* to be deleted as well.
*
* The ctlr is detached from sysfs and it's resources
* are freed (work q), but the memory is not freed
* until its last reference is released.
*
* This routine expects no locks to be held before
* calling.
*
* TODO: Currently there are no callbacks to clean up LLD data
* for a fcoe_fcf_device. LLDs must keep this in mind as they need
* to clean up each of their LLD data for all fcoe_fcf_device before
* calling fcoe_ctlr_device_delete.
*/
void fcoe_ctlr_device_delete(struct fcoe_ctlr_device *ctlr)
{
struct fcoe_fcf_device *fcf, *next;
/* Remove any attached fcfs */
mutex_lock(&ctlr->lock);
list_for_each_entry_safe(fcf, next,
&ctlr->fcfs, peers) {
list_del(&fcf->peers);
fcf->state = FCOE_FCF_STATE_DELETED;
fcoe_ctlr_device_queue_work(ctlr, &fcf->delete_work);
}
mutex_unlock(&ctlr->lock);
fcoe_ctlr_device_flush_work(ctlr);
destroy_workqueue(ctlr->devloss_work_q);
ctlr->devloss_work_q = NULL;
destroy_workqueue(ctlr->work_q);
ctlr->work_q = NULL;
device_unregister(&ctlr->dev);
}
EXPORT_SYMBOL_GPL(fcoe_ctlr_device_delete);
/**
* fcoe_fcf_device_final_delete() - Final delete routine
* @work: The FIP fcf's embedded work struct
*
* It is expected that the fcf has been removed from
* the FIP ctlr's list before calling this routine.
*/
static void fcoe_fcf_device_final_delete(struct work_struct *work)
{
struct fcoe_fcf_device *fcf =
container_of(work, struct fcoe_fcf_device, delete_work);
struct fcoe_ctlr_device *ctlr = fcoe_fcf_dev_to_ctlr_dev(fcf);
/*
* Cancel any outstanding timers. These should really exist
* only when rmmod'ing the LLDD and we're asking for
* immediate termination of the rports
*/
if (!cancel_delayed_work(&fcf->dev_loss_work))
fcoe_ctlr_device_flush_devloss(ctlr);
device_unregister(&fcf->dev);
}
/**
* fip_timeout_deleted_fcf() - Delete a fcf when the devloss timer fires
* @work: The FIP fcf's embedded work struct
*
* Removes the fcf from the FIP ctlr's list of fcfs and
* queues the final deletion.
*/
static void fip_timeout_deleted_fcf(struct work_struct *work)
{
struct fcoe_fcf_device *fcf =
container_of(work, struct fcoe_fcf_device, dev_loss_work.work);
struct fcoe_ctlr_device *ctlr = fcoe_fcf_dev_to_ctlr_dev(fcf);
mutex_lock(&ctlr->lock);
/*
* If the fcf is deleted or reconnected before the timer
* fires the devloss queue will be flushed, but the state will
* either be CONNECTED or DELETED. If that is the case we
* cancel deleting the fcf.
*/
if (fcf->state != FCOE_FCF_STATE_DISCONNECTED)
goto out;
dev_printk(KERN_ERR, &fcf->dev,
"FIP fcf connection time out: removing fcf\n");
list_del(&fcf->peers);
fcf->state = FCOE_FCF_STATE_DELETED;
fcoe_ctlr_device_queue_work(ctlr, &fcf->delete_work);
out:
mutex_unlock(&ctlr->lock);
}
/**
* fcoe_fcf_device_delete() - Delete a FIP fcf
* @fcf: Pointer to the fcf which is to be deleted
*
* Queues the FIP fcf on the devloss workqueue
*
* Expects the ctlr_attrs mutex to be held for fcf
* state change.
*/
void fcoe_fcf_device_delete(struct fcoe_fcf_device *fcf)
{
struct fcoe_ctlr_device *ctlr = fcoe_fcf_dev_to_ctlr_dev(fcf);
int timeout = fcf->dev_loss_tmo;
if (fcf->state != FCOE_FCF_STATE_CONNECTED)
return;
fcf->state = FCOE_FCF_STATE_DISCONNECTED;
/*
* FCF will only be re-connected by the LLD calling
* fcoe_fcf_device_add, and it should be setting up
* priv then.
*/
fcf->priv = NULL;
fcoe_ctlr_device_queue_devloss_work(ctlr, &fcf->dev_loss_work,
timeout * HZ);
}
EXPORT_SYMBOL_GPL(fcoe_fcf_device_delete);
/**
* fcoe_fcf_device_add() - Add a FCoE sysfs fcoe_fcf_device to the system
* @ctlr: The fcoe_ctlr_device that will be the fcoe_fcf_device parent
* @new_fcf: A temporary FCF used for lookups on the current list of fcfs
*
* Expects to be called with the ctlr->lock held
*/
struct fcoe_fcf_device *fcoe_fcf_device_add(struct fcoe_ctlr_device *ctlr,
struct fcoe_fcf_device *new_fcf)
{
struct fcoe_fcf_device *fcf;
int error = 0;
list_for_each_entry(fcf, &ctlr->fcfs, peers) {
if (fcoe_fcf_device_match(new_fcf, fcf)) {
if (fcf->state == FCOE_FCF_STATE_CONNECTED)
return fcf;
fcf->state = FCOE_FCF_STATE_CONNECTED;
if (!cancel_delayed_work(&fcf->dev_loss_work))
fcoe_ctlr_device_flush_devloss(ctlr);
return fcf;
}
}
fcf = kzalloc(sizeof(struct fcoe_fcf_device), GFP_ATOMIC);
if (unlikely(!fcf))
goto out;
INIT_WORK(&fcf->delete_work, fcoe_fcf_device_final_delete);
INIT_DELAYED_WORK(&fcf->dev_loss_work, fip_timeout_deleted_fcf);
fcf->dev.parent = &ctlr->dev;
fcf->dev.bus = &fcoe_bus_type;
fcf->dev.type = &fcoe_fcf_device_type;
fcf->id = atomic_inc_return(&fcf_num) - 1;
fcf->state = FCOE_FCF_STATE_UNKNOWN;
fcf->dev_loss_tmo = ctlr->fcf_dev_loss_tmo;
dev_set_name(&fcf->dev, "fcf_%d", fcf->id);
fcf->fabric_name = new_fcf->fabric_name;
fcf->switch_name = new_fcf->switch_name;
fcf->fc_map = new_fcf->fc_map;
fcf->vfid = new_fcf->vfid;
memcpy(fcf->mac, new_fcf->mac, ETH_ALEN);
fcf->priority = new_fcf->priority;
fcf->fka_period = new_fcf->fka_period;
fcf->selected = new_fcf->selected;
error = device_register(&fcf->dev);
if (error)
goto out_del;
fcf->state = FCOE_FCF_STATE_CONNECTED;
list_add_tail(&fcf->peers, &ctlr->fcfs);
return fcf;
out_del:
kfree(fcf);
out:
return NULL;
}
EXPORT_SYMBOL_GPL(fcoe_fcf_device_add);
int __init fcoe_sysfs_setup(void)
{
int error;
atomic_set(&ctlr_num, 0);
atomic_set(&fcf_num, 0);
error = bus_register(&fcoe_bus_type);
if (error)
return error;
return 0;
}
void __exit fcoe_sysfs_teardown(void)
{
bus_unregister(&fcoe_bus_type);
}
| gpl-2.0 |
AndroidGX/SimpleGX-MM-6.0_H811 | net/ipv4/ah4.c | 2145 | 12808 | #define pr_fmt(fmt) "IPsec: " fmt
#include <crypto/hash.h>
#include <linux/err.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <net/ip.h>
#include <net/xfrm.h>
#include <net/ah.h>
#include <linux/crypto.h>
#include <linux/pfkeyv2.h>
#include <linux/scatterlist.h>
#include <net/icmp.h>
#include <net/protocol.h>
struct ah_skb_cb {
struct xfrm_skb_cb xfrm;
void *tmp;
};
#define AH_SKB_CB(__skb) ((struct ah_skb_cb *)&((__skb)->cb[0]))
static void *ah_alloc_tmp(struct crypto_ahash *ahash, int nfrags,
unsigned int size)
{
unsigned int len;
len = size + crypto_ahash_digestsize(ahash) +
(crypto_ahash_alignmask(ahash) &
~(crypto_tfm_ctx_alignment() - 1));
len = ALIGN(len, crypto_tfm_ctx_alignment());
len += sizeof(struct ahash_request) + crypto_ahash_reqsize(ahash);
len = ALIGN(len, __alignof__(struct scatterlist));
len += sizeof(struct scatterlist) * nfrags;
return kmalloc(len, GFP_ATOMIC);
}
static inline u8 *ah_tmp_auth(void *tmp, unsigned int offset)
{
return tmp + offset;
}
static inline u8 *ah_tmp_icv(struct crypto_ahash *ahash, void *tmp,
unsigned int offset)
{
return PTR_ALIGN((u8 *)tmp + offset, crypto_ahash_alignmask(ahash) + 1);
}
static inline struct ahash_request *ah_tmp_req(struct crypto_ahash *ahash,
u8 *icv)
{
struct ahash_request *req;
req = (void *)PTR_ALIGN(icv + crypto_ahash_digestsize(ahash),
crypto_tfm_ctx_alignment());
ahash_request_set_tfm(req, ahash);
return req;
}
static inline struct scatterlist *ah_req_sg(struct crypto_ahash *ahash,
struct ahash_request *req)
{
return (void *)ALIGN((unsigned long)(req + 1) +
crypto_ahash_reqsize(ahash),
__alignof__(struct scatterlist));
}
/* Clear mutable options and find final destination to substitute
* into IP header for icv calculation. Options are already checked
* for validity, so paranoia is not required. */
static int ip_clear_mutable_options(const struct iphdr *iph, __be32 *daddr)
{
unsigned char *optptr = (unsigned char *)(iph+1);
int l = iph->ihl*4 - sizeof(struct iphdr);
int optlen;
while (l > 0) {
switch (*optptr) {
case IPOPT_END:
return 0;
case IPOPT_NOOP:
l--;
optptr++;
continue;
}
optlen = optptr[1];
if (optlen<2 || optlen>l)
return -EINVAL;
switch (*optptr) {
case IPOPT_SEC:
case 0x85: /* Some "Extended Security" crap. */
case IPOPT_CIPSO:
case IPOPT_RA:
case 0x80|21: /* RFC1770 */
break;
case IPOPT_LSRR:
case IPOPT_SSRR:
if (optlen < 6)
return -EINVAL;
memcpy(daddr, optptr+optlen-4, 4);
/* Fall through */
default:
memset(optptr, 0, optlen);
}
l -= optlen;
optptr += optlen;
}
return 0;
}
static void ah_output_done(struct crypto_async_request *base, int err)
{
u8 *icv;
struct iphdr *iph;
struct sk_buff *skb = base->data;
struct xfrm_state *x = skb_dst(skb)->xfrm;
struct ah_data *ahp = x->data;
struct iphdr *top_iph = ip_hdr(skb);
struct ip_auth_hdr *ah = ip_auth_hdr(skb);
int ihl = ip_hdrlen(skb);
iph = AH_SKB_CB(skb)->tmp;
icv = ah_tmp_icv(ahp->ahash, iph, ihl);
memcpy(ah->auth_data, icv, ahp->icv_trunc_len);
top_iph->tos = iph->tos;
top_iph->ttl = iph->ttl;
top_iph->frag_off = iph->frag_off;
if (top_iph->ihl != 5) {
top_iph->daddr = iph->daddr;
memcpy(top_iph+1, iph+1, top_iph->ihl*4 - sizeof(struct iphdr));
}
kfree(AH_SKB_CB(skb)->tmp);
xfrm_output_resume(skb, err);
}
static int ah_output(struct xfrm_state *x, struct sk_buff *skb)
{
int err;
int nfrags;
int ihl;
u8 *icv;
struct sk_buff *trailer;
struct crypto_ahash *ahash;
struct ahash_request *req;
struct scatterlist *sg;
struct iphdr *iph, *top_iph;
struct ip_auth_hdr *ah;
struct ah_data *ahp;
ahp = x->data;
ahash = ahp->ahash;
if ((err = skb_cow_data(skb, 0, &trailer)) < 0)
goto out;
nfrags = err;
skb_push(skb, -skb_network_offset(skb));
ah = ip_auth_hdr(skb);
ihl = ip_hdrlen(skb);
err = -ENOMEM;
iph = ah_alloc_tmp(ahash, nfrags, ihl);
if (!iph)
goto out;
icv = ah_tmp_icv(ahash, iph, ihl);
req = ah_tmp_req(ahash, icv);
sg = ah_req_sg(ahash, req);
memset(ah->auth_data, 0, ahp->icv_trunc_len);
top_iph = ip_hdr(skb);
iph->tos = top_iph->tos;
iph->ttl = top_iph->ttl;
iph->frag_off = top_iph->frag_off;
if (top_iph->ihl != 5) {
iph->daddr = top_iph->daddr;
memcpy(iph+1, top_iph+1, top_iph->ihl*4 - sizeof(struct iphdr));
err = ip_clear_mutable_options(top_iph, &top_iph->daddr);
if (err)
goto out_free;
}
ah->nexthdr = *skb_mac_header(skb);
*skb_mac_header(skb) = IPPROTO_AH;
top_iph->tos = 0;
top_iph->tot_len = htons(skb->len);
top_iph->frag_off = 0;
top_iph->ttl = 0;
top_iph->check = 0;
if (x->props.flags & XFRM_STATE_ALIGN4)
ah->hdrlen = (XFRM_ALIGN4(sizeof(*ah) + ahp->icv_trunc_len) >> 2) - 2;
else
ah->hdrlen = (XFRM_ALIGN8(sizeof(*ah) + ahp->icv_trunc_len) >> 2) - 2;
ah->reserved = 0;
ah->spi = x->id.spi;
ah->seq_no = htonl(XFRM_SKB_CB(skb)->seq.output.low);
sg_init_table(sg, nfrags);
skb_to_sgvec(skb, sg, 0, skb->len);
ahash_request_set_crypt(req, sg, icv, skb->len);
ahash_request_set_callback(req, 0, ah_output_done, skb);
AH_SKB_CB(skb)->tmp = iph;
err = crypto_ahash_digest(req);
if (err) {
if (err == -EINPROGRESS)
goto out;
if (err == -EBUSY)
err = NET_XMIT_DROP;
goto out_free;
}
memcpy(ah->auth_data, icv, ahp->icv_trunc_len);
top_iph->tos = iph->tos;
top_iph->ttl = iph->ttl;
top_iph->frag_off = iph->frag_off;
if (top_iph->ihl != 5) {
top_iph->daddr = iph->daddr;
memcpy(top_iph+1, iph+1, top_iph->ihl*4 - sizeof(struct iphdr));
}
out_free:
kfree(iph);
out:
return err;
}
static void ah_input_done(struct crypto_async_request *base, int err)
{
u8 *auth_data;
u8 *icv;
struct iphdr *work_iph;
struct sk_buff *skb = base->data;
struct xfrm_state *x = xfrm_input_state(skb);
struct ah_data *ahp = x->data;
struct ip_auth_hdr *ah = ip_auth_hdr(skb);
int ihl = ip_hdrlen(skb);
int ah_hlen = (ah->hdrlen + 2) << 2;
work_iph = AH_SKB_CB(skb)->tmp;
auth_data = ah_tmp_auth(work_iph, ihl);
icv = ah_tmp_icv(ahp->ahash, auth_data, ahp->icv_trunc_len);
err = memcmp(icv, auth_data, ahp->icv_trunc_len) ? -EBADMSG: 0;
if (err)
goto out;
err = ah->nexthdr;
skb->network_header += ah_hlen;
memcpy(skb_network_header(skb), work_iph, ihl);
__skb_pull(skb, ah_hlen + ihl);
if (x->props.mode == XFRM_MODE_TUNNEL)
skb_reset_transport_header(skb);
else
skb_set_transport_header(skb, -ihl);
out:
kfree(AH_SKB_CB(skb)->tmp);
xfrm_input_resume(skb, err);
}
static int ah_input(struct xfrm_state *x, struct sk_buff *skb)
{
int ah_hlen;
int ihl;
int nexthdr;
int nfrags;
u8 *auth_data;
u8 *icv;
struct sk_buff *trailer;
struct crypto_ahash *ahash;
struct ahash_request *req;
struct scatterlist *sg;
struct iphdr *iph, *work_iph;
struct ip_auth_hdr *ah;
struct ah_data *ahp;
int err = -ENOMEM;
if (!pskb_may_pull(skb, sizeof(*ah)))
goto out;
ah = (struct ip_auth_hdr *)skb->data;
ahp = x->data;
ahash = ahp->ahash;
nexthdr = ah->nexthdr;
ah_hlen = (ah->hdrlen + 2) << 2;
if (x->props.flags & XFRM_STATE_ALIGN4) {
if (ah_hlen != XFRM_ALIGN4(sizeof(*ah) + ahp->icv_full_len) &&
ah_hlen != XFRM_ALIGN4(sizeof(*ah) + ahp->icv_trunc_len))
goto out;
} else {
if (ah_hlen != XFRM_ALIGN8(sizeof(*ah) + ahp->icv_full_len) &&
ah_hlen != XFRM_ALIGN8(sizeof(*ah) + ahp->icv_trunc_len))
goto out;
}
if (!pskb_may_pull(skb, ah_hlen))
goto out;
/* We are going to _remove_ AH header to keep sockets happy,
* so... Later this can change. */
if (skb_unclone(skb, GFP_ATOMIC))
goto out;
skb->ip_summed = CHECKSUM_NONE;
if ((err = skb_cow_data(skb, 0, &trailer)) < 0)
goto out;
nfrags = err;
ah = (struct ip_auth_hdr *)skb->data;
iph = ip_hdr(skb);
ihl = ip_hdrlen(skb);
work_iph = ah_alloc_tmp(ahash, nfrags, ihl + ahp->icv_trunc_len);
if (!work_iph)
goto out;
auth_data = ah_tmp_auth(work_iph, ihl);
icv = ah_tmp_icv(ahash, auth_data, ahp->icv_trunc_len);
req = ah_tmp_req(ahash, icv);
sg = ah_req_sg(ahash, req);
memcpy(work_iph, iph, ihl);
memcpy(auth_data, ah->auth_data, ahp->icv_trunc_len);
memset(ah->auth_data, 0, ahp->icv_trunc_len);
iph->ttl = 0;
iph->tos = 0;
iph->frag_off = 0;
iph->check = 0;
if (ihl > sizeof(*iph)) {
__be32 dummy;
err = ip_clear_mutable_options(iph, &dummy);
if (err)
goto out_free;
}
skb_push(skb, ihl);
sg_init_table(sg, nfrags);
skb_to_sgvec(skb, sg, 0, skb->len);
ahash_request_set_crypt(req, sg, icv, skb->len);
ahash_request_set_callback(req, 0, ah_input_done, skb);
AH_SKB_CB(skb)->tmp = work_iph;
err = crypto_ahash_digest(req);
if (err) {
if (err == -EINPROGRESS)
goto out;
goto out_free;
}
err = memcmp(icv, auth_data, ahp->icv_trunc_len) ? -EBADMSG: 0;
if (err)
goto out_free;
skb->network_header += ah_hlen;
memcpy(skb_network_header(skb), work_iph, ihl);
__skb_pull(skb, ah_hlen + ihl);
if (x->props.mode == XFRM_MODE_TUNNEL)
skb_reset_transport_header(skb);
else
skb_set_transport_header(skb, -ihl);
err = nexthdr;
out_free:
kfree (work_iph);
out:
return err;
}
static void ah4_err(struct sk_buff *skb, u32 info)
{
struct net *net = dev_net(skb->dev);
const struct iphdr *iph = (const struct iphdr *)skb->data;
struct ip_auth_hdr *ah = (struct ip_auth_hdr *)(skb->data+(iph->ihl<<2));
struct xfrm_state *x;
switch (icmp_hdr(skb)->type) {
case ICMP_DEST_UNREACH:
if (icmp_hdr(skb)->code != ICMP_FRAG_NEEDED)
return;
case ICMP_REDIRECT:
break;
default:
return;
}
x = xfrm_state_lookup(net, skb->mark, (const xfrm_address_t *)&iph->daddr,
ah->spi, IPPROTO_AH, AF_INET);
if (!x)
return;
if (icmp_hdr(skb)->type == ICMP_DEST_UNREACH) {
atomic_inc(&flow_cache_genid);
rt_genid_bump(net);
ipv4_update_pmtu(skb, net, info, 0, 0, IPPROTO_AH, 0);
} else
ipv4_redirect(skb, net, 0, 0, IPPROTO_AH, 0);
xfrm_state_put(x);
}
static int ah_init_state(struct xfrm_state *x)
{
struct ah_data *ahp = NULL;
struct xfrm_algo_desc *aalg_desc;
struct crypto_ahash *ahash;
if (!x->aalg)
goto error;
if (x->encap)
goto error;
ahp = kzalloc(sizeof(*ahp), GFP_KERNEL);
if (!ahp)
return -ENOMEM;
ahash = crypto_alloc_ahash(x->aalg->alg_name, 0, 0);
if (IS_ERR(ahash))
goto error;
ahp->ahash = ahash;
if (crypto_ahash_setkey(ahash, x->aalg->alg_key,
(x->aalg->alg_key_len + 7) / 8))
goto error;
/*
* Lookup the algorithm description maintained by xfrm_algo,
* verify crypto transform properties, and store information
* we need for AH processing. This lookup cannot fail here
* after a successful crypto_alloc_ahash().
*/
aalg_desc = xfrm_aalg_get_byname(x->aalg->alg_name, 0);
BUG_ON(!aalg_desc);
if (aalg_desc->uinfo.auth.icv_fullbits/8 !=
crypto_ahash_digestsize(ahash)) {
pr_info("%s: %s digestsize %u != %hu\n",
__func__, x->aalg->alg_name,
crypto_ahash_digestsize(ahash),
aalg_desc->uinfo.auth.icv_fullbits / 8);
goto error;
}
ahp->icv_full_len = aalg_desc->uinfo.auth.icv_fullbits/8;
ahp->icv_trunc_len = x->aalg->alg_trunc_len/8;
BUG_ON(ahp->icv_trunc_len > MAX_AH_AUTH_LEN);
if (x->props.flags & XFRM_STATE_ALIGN4)
x->props.header_len = XFRM_ALIGN4(sizeof(struct ip_auth_hdr) +
ahp->icv_trunc_len);
else
x->props.header_len = XFRM_ALIGN8(sizeof(struct ip_auth_hdr) +
ahp->icv_trunc_len);
if (x->props.mode == XFRM_MODE_TUNNEL)
x->props.header_len += sizeof(struct iphdr);
x->data = ahp;
return 0;
error:
if (ahp) {
crypto_free_ahash(ahp->ahash);
kfree(ahp);
}
return -EINVAL;
}
static void ah_destroy(struct xfrm_state *x)
{
struct ah_data *ahp = x->data;
if (!ahp)
return;
crypto_free_ahash(ahp->ahash);
kfree(ahp);
}
static const struct xfrm_type ah_type =
{
.description = "AH4",
.owner = THIS_MODULE,
.proto = IPPROTO_AH,
.flags = XFRM_TYPE_REPLAY_PROT,
.init_state = ah_init_state,
.destructor = ah_destroy,
.input = ah_input,
.output = ah_output
};
static const struct net_protocol ah4_protocol = {
.handler = xfrm4_rcv,
.err_handler = ah4_err,
.no_policy = 1,
.netns_ok = 1,
};
static int __init ah4_init(void)
{
if (xfrm_register_type(&ah_type, AF_INET) < 0) {
pr_info("%s: can't add xfrm type\n", __func__);
return -EAGAIN;
}
if (inet_add_protocol(&ah4_protocol, IPPROTO_AH) < 0) {
pr_info("%s: can't add protocol\n", __func__);
xfrm_unregister_type(&ah_type, AF_INET);
return -EAGAIN;
}
return 0;
}
static void __exit ah4_fini(void)
{
if (inet_del_protocol(&ah4_protocol, IPPROTO_AH) < 0)
pr_info("%s: can't remove protocol\n", __func__);
if (xfrm_unregister_type(&ah_type, AF_INET) < 0)
pr_info("%s: can't remove xfrm type\n", __func__);
}
module_init(ah4_init);
module_exit(ah4_fini);
MODULE_LICENSE("GPL");
MODULE_ALIAS_XFRM_TYPE(AF_INET, XFRM_PROTO_AH);
| gpl-2.0 |
IonKiwi/android_kernel_samsung_kccat6 | drivers/staging/rtl8192u/r8190_rtl8256.c | 2145 | 10473 | /*
This is part of the rtl8192 driver
released under the GPL (See file COPYING for details).
This files contains programming code for the rtl8256
radio frontend.
*Many* thanks to Realtek Corp. for their great support!
*/
#include "r8192U.h"
#include "r8192U_hw.h"
#include "r819xU_phyreg.h"
#include "r819xU_phy.h"
#include "r8190_rtl8256.h"
/*--------------------------------------------------------------------------
* Overview: set RF band width (20M or 40M)
* Input: struct net_device* dev
* WIRELESS_BANDWIDTH_E Bandwidth //20M or 40M
* Output: NONE
* Return: NONE
* Note: 8226 support both 20M and 40 MHz
*---------------------------------------------------------------------------*/
void PHY_SetRF8256Bandwidth(struct net_device* dev , HT_CHANNEL_WIDTH Bandwidth) //20M or 40M
{
u8 eRFPath;
struct r8192_priv *priv = ieee80211_priv(dev);
//for(eRFPath = RF90_PATH_A; eRFPath <pHalData->NumTotalRFPath; eRFPath++)
for(eRFPath = 0; eRFPath <RF90_PATH_MAX; eRFPath++)
{
if (!rtl8192_phy_CheckIsLegalRFPath(dev, eRFPath))
continue;
switch(Bandwidth)
{
case HT_CHANNEL_WIDTH_20:
if(priv->card_8192_version == VERSION_819xU_A || priv->card_8192_version == VERSION_819xU_B)// 8256 D-cut, E-cut, xiong: consider it later!
{
rtl8192_phy_SetRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, 0x0b, bMask12Bits, 0x100); //phy para:1ba
rtl8192_phy_SetRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, 0x2c, bMask12Bits, 0x3d7);
rtl8192_phy_SetRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, 0x0e, bMask12Bits, 0x021);
//cosa add for sd3's request 01/23/2008
rtl8192_phy_SetRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, 0x14, bMask12Bits, 0x5ab);
}
else
{
RT_TRACE(COMP_ERR, "PHY_SetRF8256Bandwidth(): unknown hardware version\n");
}
break;
case HT_CHANNEL_WIDTH_20_40:
if(priv->card_8192_version == VERSION_819xU_A ||priv->card_8192_version == VERSION_819xU_B)// 8256 D-cut, E-cut, xiong: consider it later!
{
rtl8192_phy_SetRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, 0x0b, bMask12Bits, 0x300); //phy para:3ba
rtl8192_phy_SetRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, 0x2c, bMask12Bits, 0x3df);
rtl8192_phy_SetRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, 0x0e, bMask12Bits, 0x0a1);
//cosa add for sd3's request 01/23/2008
if(priv->chan == 3 || priv->chan == 9) //I need to set priv->chan whenever current channel changes
rtl8192_phy_SetRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, 0x14, bMask12Bits, 0x59b);
else
rtl8192_phy_SetRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, 0x14, bMask12Bits, 0x5ab);
}
else
{
RT_TRACE(COMP_ERR, "PHY_SetRF8256Bandwidth(): unknown hardware version\n");
}
break;
default:
RT_TRACE(COMP_ERR, "PHY_SetRF8256Bandwidth(): unknown Bandwidth: %#X\n",Bandwidth );
break;
}
}
return;
}
/*--------------------------------------------------------------------------
* Overview: Interface to config 8256
* Input: struct net_device* dev
* Output: NONE
* Return: NONE
*---------------------------------------------------------------------------*/
void PHY_RF8256_Config(struct net_device* dev)
{
struct r8192_priv *priv = ieee80211_priv(dev);
// Initialize general global value
//
// TODO: Extend RF_PATH_C and RF_PATH_D in the future
priv->NumTotalRFPath = RTL819X_TOTAL_RF_PATH;
// Config BB and RF
phy_RF8256_Config_ParaFile(dev);
return;
}
/*--------------------------------------------------------------------------
* Overview: Interface to config 8256
* Input: struct net_device* dev
* Output: NONE
* Return: NONE
*---------------------------------------------------------------------------*/
void phy_RF8256_Config_ParaFile(struct net_device* dev)
{
u32 u4RegValue = 0;
//static s1Byte szRadioAFile[] = RTL819X_PHY_RADIO_A;
//static s1Byte szRadioBFile[] = RTL819X_PHY_RADIO_B;
//static s1Byte szRadioCFile[] = RTL819X_PHY_RADIO_C;
//static s1Byte szRadioDFile[] = RTL819X_PHY_RADIO_D;
u8 eRFPath;
BB_REGISTER_DEFINITION_T *pPhyReg;
struct r8192_priv *priv = ieee80211_priv(dev);
u32 RegOffSetToBeCheck = 0x3;
u32 RegValueToBeCheck = 0x7f1;
u32 RF3_Final_Value = 0;
u8 ConstRetryTimes = 5, RetryTimes = 5;
u8 ret = 0;
//3//-----------------------------------------------------------------
//3// <2> Initialize RF
//3//-----------------------------------------------------------------
for(eRFPath = (RF90_RADIO_PATH_E)RF90_PATH_A; eRFPath <priv->NumTotalRFPath; eRFPath++)
{
if (!rtl8192_phy_CheckIsLegalRFPath(dev, eRFPath))
continue;
pPhyReg = &priv->PHYRegDef[eRFPath];
// Joseph test for shorten RF config
// pHalData->RfReg0Value[eRFPath] = rtl8192_phy_QueryRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, rGlobalCtrl, bMaskDWord);
/*----Store original RFENV control type----*/
switch(eRFPath)
{
case RF90_PATH_A:
case RF90_PATH_C:
u4RegValue = rtl8192_QueryBBReg(dev, pPhyReg->rfintfs, bRFSI_RFENV);
break;
case RF90_PATH_B :
case RF90_PATH_D:
u4RegValue = rtl8192_QueryBBReg(dev, pPhyReg->rfintfs, bRFSI_RFENV<<16);
break;
}
/*----Set RF_ENV enable----*/
rtl8192_setBBreg(dev, pPhyReg->rfintfe, bRFSI_RFENV<<16, 0x1);
/*----Set RF_ENV output high----*/
rtl8192_setBBreg(dev, pPhyReg->rfintfo, bRFSI_RFENV, 0x1);
/* Set bit number of Address and Data for RF register */
rtl8192_setBBreg(dev, pPhyReg->rfHSSIPara2, b3WireAddressLength, 0x0); // Set 0 to 4 bits for Z-serial and set 1 to 6 bits for 8258
rtl8192_setBBreg(dev, pPhyReg->rfHSSIPara2, b3WireDataLength, 0x0); // Set 0 to 12 bits for Z-serial and 8258, and set 1 to 14 bits for ???
rtl8192_phy_SetRFReg(dev, (RF90_RADIO_PATH_E) eRFPath, 0x0, bMask12Bits, 0xbf);
/*----Check RF block (for FPGA platform only)----*/
// TODO: this function should be removed on ASIC , Emily 2007.2.2
if (rtl8192_phy_checkBBAndRF(dev, HW90_BLOCK_RF, (RF90_RADIO_PATH_E)eRFPath))
{
RT_TRACE(COMP_ERR, "PHY_RF8256_Config():Check Radio[%d] Fail!!\n", eRFPath);
goto phy_RF8256_Config_ParaFile_Fail;
}
RetryTimes = ConstRetryTimes;
RF3_Final_Value = 0;
/*----Initialize RF fom connfiguration file----*/
switch(eRFPath)
{
case RF90_PATH_A:
while(RF3_Final_Value!=RegValueToBeCheck && RetryTimes!=0)
{
ret = rtl8192_phy_ConfigRFWithHeaderFile(dev,(RF90_RADIO_PATH_E)eRFPath);
RF3_Final_Value = rtl8192_phy_QueryRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, RegOffSetToBeCheck, bMask12Bits);
RT_TRACE(COMP_RF, "RF %d %d register final value: %x\n", eRFPath, RegOffSetToBeCheck, RF3_Final_Value);
RetryTimes--;
}
break;
case RF90_PATH_B:
while(RF3_Final_Value!=RegValueToBeCheck && RetryTimes!=0)
{
ret = rtl8192_phy_ConfigRFWithHeaderFile(dev,(RF90_RADIO_PATH_E)eRFPath);
RF3_Final_Value = rtl8192_phy_QueryRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, RegOffSetToBeCheck, bMask12Bits);
RT_TRACE(COMP_RF, "RF %d %d register final value: %x\n", eRFPath, RegOffSetToBeCheck, RF3_Final_Value);
RetryTimes--;
}
break;
case RF90_PATH_C:
while(RF3_Final_Value!=RegValueToBeCheck && RetryTimes!=0)
{
ret = rtl8192_phy_ConfigRFWithHeaderFile(dev,(RF90_RADIO_PATH_E)eRFPath);
RF3_Final_Value = rtl8192_phy_QueryRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, RegOffSetToBeCheck, bMask12Bits);
RT_TRACE(COMP_RF, "RF %d %d register final value: %x\n", eRFPath, RegOffSetToBeCheck, RF3_Final_Value);
RetryTimes--;
}
break;
case RF90_PATH_D:
while(RF3_Final_Value!=RegValueToBeCheck && RetryTimes!=0)
{
ret = rtl8192_phy_ConfigRFWithHeaderFile(dev,(RF90_RADIO_PATH_E)eRFPath);
RF3_Final_Value = rtl8192_phy_QueryRFReg(dev, (RF90_RADIO_PATH_E)eRFPath, RegOffSetToBeCheck, bMask12Bits);
RT_TRACE(COMP_RF, "RF %d %d register final value: %x\n", eRFPath, RegOffSetToBeCheck, RF3_Final_Value);
RetryTimes--;
}
break;
}
/*----Restore RFENV control type----*/;
switch(eRFPath)
{
case RF90_PATH_A:
case RF90_PATH_C:
rtl8192_setBBreg(dev, pPhyReg->rfintfs, bRFSI_RFENV, u4RegValue);
break;
case RF90_PATH_B :
case RF90_PATH_D:
rtl8192_setBBreg(dev, pPhyReg->rfintfs, bRFSI_RFENV<<16, u4RegValue);
break;
}
if(ret){
RT_TRACE(COMP_ERR, "phy_RF8256_Config_ParaFile():Radio[%d] Fail!!", eRFPath);
goto phy_RF8256_Config_ParaFile_Fail;
}
}
RT_TRACE(COMP_PHY, "PHY Initialization Success\n") ;
return ;
phy_RF8256_Config_ParaFile_Fail:
RT_TRACE(COMP_ERR, "PHY Initialization failed\n") ;
return ;
}
void PHY_SetRF8256CCKTxPower(struct net_device* dev, u8 powerlevel)
{
u32 TxAGC=0;
struct r8192_priv *priv = ieee80211_priv(dev);
//modified by vivi, 20080109
TxAGC = powerlevel;
if(priv->bDynamicTxLowPower == TRUE ) //cosa 05/22/2008 for scan
{
if(priv->CustomerID == RT_CID_819x_Netcore)
TxAGC = 0x22;
else
TxAGC += priv->CckPwEnl;
}
if(TxAGC > 0x24)
TxAGC = 0x24;
rtl8192_setBBreg(dev, rTxAGC_CCK_Mcs32, bTxAGCRateCCK, TxAGC);
}
void PHY_SetRF8256OFDMTxPower(struct net_device* dev, u8 powerlevel)
{
struct r8192_priv *priv = ieee80211_priv(dev);
//Joseph TxPower for 8192 testing
u32 writeVal, powerBase0, powerBase1, writeVal_tmp;
u8 index = 0;
u16 RegOffset[6] = {0xe00, 0xe04, 0xe10, 0xe14, 0xe18, 0xe1c};
u8 byte0, byte1, byte2, byte3;
powerBase0 = powerlevel + priv->TxPowerDiff; //OFDM rates
powerBase0 = (powerBase0<<24) | (powerBase0<<16) |(powerBase0<<8) |powerBase0;
powerBase1 = powerlevel; //MCS rates
powerBase1 = (powerBase1<<24) | (powerBase1<<16) |(powerBase1<<8) |powerBase1;
for(index=0; index<6; index++)
{
writeVal = priv->MCSTxPowerLevelOriginalOffset[index] + ((index<2)?powerBase0:powerBase1);
byte0 = (u8)(writeVal & 0x7f);
byte1 = (u8)((writeVal & 0x7f00)>>8);
byte2 = (u8)((writeVal & 0x7f0000)>>16);
byte3 = (u8)((writeVal & 0x7f000000)>>24);
if(byte0 > 0x24) // Max power index = 0x24
byte0 = 0x24;
if(byte1 > 0x24)
byte1 = 0x24;
if(byte2 > 0x24)
byte2 = 0x24;
if(byte3 > 0x24)
byte3 = 0x24;
//for tx power track
if(index == 3)
{
writeVal_tmp = (byte3<<24) | (byte2<<16) |(byte1<<8) |byte0;
priv->Pwr_Track = writeVal_tmp;
}
if(priv->bDynamicTxHighPower == TRUE) //Add by Jacken 2008/03/06
{
// Emily, 20080613. Set low tx power for both MCS and legacy OFDM
writeVal = 0x03030303;
}
else
{
writeVal = (byte3<<24) | (byte2<<16) |(byte1<<8) |byte0;
}
rtl8192_setBBreg(dev, RegOffset[index], 0x7f7f7f7f, writeVal);
}
return;
}
| gpl-2.0 |
Galaxy-Tab-S2/android_kernel_samsung_gts28wifi | fs/nfsd/nfsfh.c | 2401 | 18702 | /*
* NFS server file handle treatment.
*
* Copyright (C) 1995, 1996 Olaf Kirch <okir@monad.swb.de>
* Portions Copyright (C) 1999 G. Allen Morris III <gam3@acm.org>
* Extensive rewrite by Neil Brown <neilb@cse.unsw.edu.au> Southern-Spring 1999
* ... and again Southern-Winter 2001 to support export_operations
*/
#include <linux/exportfs.h>
#include <linux/sunrpc/svcauth_gss.h>
#include "nfsd.h"
#include "vfs.h"
#include "auth.h"
#define NFSDDBG_FACILITY NFSDDBG_FH
/*
* our acceptability function.
* if NOSUBTREECHECK, accept anything
* if not, require that we can walk up to exp->ex_dentry
* doing some checks on the 'x' bits
*/
static int nfsd_acceptable(void *expv, struct dentry *dentry)
{
struct svc_export *exp = expv;
int rv;
struct dentry *tdentry;
struct dentry *parent;
if (exp->ex_flags & NFSEXP_NOSUBTREECHECK)
return 1;
tdentry = dget(dentry);
while (tdentry != exp->ex_path.dentry && !IS_ROOT(tdentry)) {
/* make sure parents give x permission to user */
int err;
parent = dget_parent(tdentry);
err = inode_permission(parent->d_inode, MAY_EXEC);
if (err < 0) {
dput(parent);
break;
}
dput(tdentry);
tdentry = parent;
}
if (tdentry != exp->ex_path.dentry)
dprintk("nfsd_acceptable failed at %p %s\n", tdentry, tdentry->d_name.name);
rv = (tdentry == exp->ex_path.dentry);
dput(tdentry);
return rv;
}
/* Type check. The correct error return for type mismatches does not seem to be
* generally agreed upon. SunOS seems to use EISDIR if file isn't S_IFREG; a
* comment in the NFSv3 spec says this is incorrect (implementation notes for
* the write call).
*/
static inline __be32
nfsd_mode_check(struct svc_rqst *rqstp, umode_t mode, umode_t requested)
{
mode &= S_IFMT;
if (requested == 0) /* the caller doesn't care */
return nfs_ok;
if (mode == requested)
return nfs_ok;
/*
* v4 has an error more specific than err_notdir which we should
* return in preference to err_notdir:
*/
if (rqstp->rq_vers == 4 && mode == S_IFLNK)
return nfserr_symlink;
if (requested == S_IFDIR)
return nfserr_notdir;
if (mode == S_IFDIR)
return nfserr_isdir;
return nfserr_inval;
}
static __be32 nfsd_setuser_and_check_port(struct svc_rqst *rqstp,
struct svc_export *exp)
{
int flags = nfsexp_flags(rqstp, exp);
/* Check if the request originated from a secure port. */
if (!rqstp->rq_secure && !(flags & NFSEXP_INSECURE_PORT)) {
RPC_IFDEBUG(char buf[RPC_MAX_ADDRBUFLEN]);
dprintk(KERN_WARNING
"nfsd: request from insecure port %s!\n",
svc_print_addr(rqstp, buf, sizeof(buf)));
return nfserr_perm;
}
/* Set user creds for this exportpoint */
return nfserrno(nfsd_setuser(rqstp, exp));
}
static inline __be32 check_pseudo_root(struct svc_rqst *rqstp,
struct dentry *dentry, struct svc_export *exp)
{
if (!(exp->ex_flags & NFSEXP_V4ROOT))
return nfs_ok;
/*
* v2/v3 clients have no need for the V4ROOT export--they use
* the mount protocl instead; also, further V4ROOT checks may be
* in v4-specific code, in which case v2/v3 clients could bypass
* them.
*/
if (!nfsd_v4client(rqstp))
return nfserr_stale;
/*
* We're exposing only the directories and symlinks that have to be
* traversed on the way to real exports:
*/
if (unlikely(!S_ISDIR(dentry->d_inode->i_mode) &&
!S_ISLNK(dentry->d_inode->i_mode)))
return nfserr_stale;
/*
* A pseudoroot export gives permission to access only one
* single directory; the kernel has to make another upcall
* before granting access to anything else under it:
*/
if (unlikely(dentry != exp->ex_path.dentry))
return nfserr_stale;
return nfs_ok;
}
/*
* Use the given filehandle to look up the corresponding export and
* dentry. On success, the results are used to set fh_export and
* fh_dentry.
*/
static __be32 nfsd_set_fh_dentry(struct svc_rqst *rqstp, struct svc_fh *fhp)
{
struct knfsd_fh *fh = &fhp->fh_handle;
struct fid *fid = NULL, sfid;
struct svc_export *exp;
struct dentry *dentry;
int fileid_type;
int data_left = fh->fh_size/4;
__be32 error;
error = nfserr_stale;
if (rqstp->rq_vers > 2)
error = nfserr_badhandle;
if (rqstp->rq_vers == 4 && fh->fh_size == 0)
return nfserr_nofilehandle;
if (fh->fh_version == 1) {
int len;
if (--data_left < 0)
return error;
if (fh->fh_auth_type != 0)
return error;
len = key_len(fh->fh_fsid_type) / 4;
if (len == 0)
return error;
if (fh->fh_fsid_type == FSID_MAJOR_MINOR) {
/* deprecated, convert to type 3 */
len = key_len(FSID_ENCODE_DEV)/4;
fh->fh_fsid_type = FSID_ENCODE_DEV;
fh->fh_fsid[0] = new_encode_dev(MKDEV(ntohl(fh->fh_fsid[0]), ntohl(fh->fh_fsid[1])));
fh->fh_fsid[1] = fh->fh_fsid[2];
}
data_left -= len;
if (data_left < 0)
return error;
exp = rqst_exp_find(rqstp, fh->fh_fsid_type, fh->fh_auth);
fid = (struct fid *)(fh->fh_auth + len);
} else {
__u32 tfh[2];
dev_t xdev;
ino_t xino;
if (fh->fh_size != NFS_FHSIZE)
return error;
/* assume old filehandle format */
xdev = old_decode_dev(fh->ofh_xdev);
xino = u32_to_ino_t(fh->ofh_xino);
mk_fsid(FSID_DEV, tfh, xdev, xino, 0, NULL);
exp = rqst_exp_find(rqstp, FSID_DEV, tfh);
}
error = nfserr_stale;
if (PTR_ERR(exp) == -ENOENT)
return error;
if (IS_ERR(exp))
return nfserrno(PTR_ERR(exp));
if (exp->ex_flags & NFSEXP_NOSUBTREECHECK) {
/* Elevate privileges so that the lack of 'r' or 'x'
* permission on some parent directory will
* not stop exportfs_decode_fh from being able
* to reconnect a directory into the dentry cache.
* The same problem can affect "SUBTREECHECK" exports,
* but as nfsd_acceptable depends on correct
* access control settings being in effect, we cannot
* fix that case easily.
*/
struct cred *new = prepare_creds();
if (!new)
return nfserrno(-ENOMEM);
new->cap_effective =
cap_raise_nfsd_set(new->cap_effective,
new->cap_permitted);
put_cred(override_creds(new));
put_cred(new);
} else {
error = nfsd_setuser_and_check_port(rqstp, exp);
if (error)
goto out;
}
/*
* Look up the dentry using the NFS file handle.
*/
error = nfserr_stale;
if (rqstp->rq_vers > 2)
error = nfserr_badhandle;
if (fh->fh_version != 1) {
sfid.i32.ino = fh->ofh_ino;
sfid.i32.gen = fh->ofh_generation;
sfid.i32.parent_ino = fh->ofh_dirino;
fid = &sfid;
data_left = 3;
if (fh->ofh_dirino == 0)
fileid_type = FILEID_INO32_GEN;
else
fileid_type = FILEID_INO32_GEN_PARENT;
} else
fileid_type = fh->fh_fileid_type;
if (fileid_type == FILEID_ROOT)
dentry = dget(exp->ex_path.dentry);
else {
dentry = exportfs_decode_fh(exp->ex_path.mnt, fid,
data_left, fileid_type,
nfsd_acceptable, exp);
}
if (dentry == NULL)
goto out;
if (IS_ERR(dentry)) {
if (PTR_ERR(dentry) != -EINVAL)
error = nfserrno(PTR_ERR(dentry));
goto out;
}
if (S_ISDIR(dentry->d_inode->i_mode) &&
(dentry->d_flags & DCACHE_DISCONNECTED)) {
printk("nfsd: find_fh_dentry returned a DISCONNECTED directory: %s/%s\n",
dentry->d_parent->d_name.name, dentry->d_name.name);
}
fhp->fh_dentry = dentry;
fhp->fh_export = exp;
return 0;
out:
exp_put(exp);
return error;
}
/**
* fh_verify - filehandle lookup and access checking
* @rqstp: pointer to current rpc request
* @fhp: filehandle to be verified
* @type: expected type of object pointed to by filehandle
* @access: type of access needed to object
*
* Look up a dentry from the on-the-wire filehandle, check the client's
* access to the export, and set the current task's credentials.
*
* Regardless of success or failure of fh_verify(), fh_put() should be
* called on @fhp when the caller is finished with the filehandle.
*
* fh_verify() may be called multiple times on a given filehandle, for
* example, when processing an NFSv4 compound. The first call will look
* up a dentry using the on-the-wire filehandle. Subsequent calls will
* skip the lookup and just perform the other checks and possibly change
* the current task's credentials.
*
* @type specifies the type of object expected using one of the S_IF*
* constants defined in include/linux/stat.h. The caller may use zero
* to indicate that it doesn't care, or a negative integer to indicate
* that it expects something not of the given type.
*
* @access is formed from the NFSD_MAY_* constants defined in
* include/linux/nfsd/nfsd.h.
*/
__be32
fh_verify(struct svc_rqst *rqstp, struct svc_fh *fhp, umode_t type, int access)
{
struct svc_export *exp;
struct dentry *dentry;
__be32 error;
dprintk("nfsd: fh_verify(%s)\n", SVCFH_fmt(fhp));
if (!fhp->fh_dentry) {
error = nfsd_set_fh_dentry(rqstp, fhp);
if (error)
goto out;
}
dentry = fhp->fh_dentry;
exp = fhp->fh_export;
/*
* We still have to do all these permission checks, even when
* fh_dentry is already set:
* - fh_verify may be called multiple times with different
* "access" arguments (e.g. nfsd_proc_create calls
* fh_verify(...,NFSD_MAY_EXEC) first, then later (in
* nfsd_create) calls fh_verify(...,NFSD_MAY_CREATE).
* - in the NFSv4 case, the filehandle may have been filled
* in by fh_compose, and given a dentry, but further
* compound operations performed with that filehandle
* still need permissions checks. In the worst case, a
* mountpoint crossing may have changed the export
* options, and we may now need to use a different uid
* (for example, if different id-squashing options are in
* effect on the new filesystem).
*/
error = check_pseudo_root(rqstp, dentry, exp);
if (error)
goto out;
error = nfsd_setuser_and_check_port(rqstp, exp);
if (error)
goto out;
error = nfsd_mode_check(rqstp, dentry->d_inode->i_mode, type);
if (error)
goto out;
/*
* pseudoflavor restrictions are not enforced on NLM,
* which clients virtually always use auth_sys for,
* even while using RPCSEC_GSS for NFS.
*/
if (access & NFSD_MAY_LOCK || access & NFSD_MAY_BYPASS_GSS)
goto skip_pseudoflavor_check;
/*
* Clients may expect to be able to use auth_sys during mount,
* even if they use gss for everything else; see section 2.3.2
* of rfc 2623.
*/
if (access & NFSD_MAY_BYPASS_GSS_ON_ROOT
&& exp->ex_path.dentry == dentry)
goto skip_pseudoflavor_check;
error = check_nfsd_access(exp, rqstp);
if (error)
goto out;
skip_pseudoflavor_check:
/* Finally, check access permissions. */
error = nfsd_permission(rqstp, exp, dentry, access);
if (error) {
dprintk("fh_verify: %s/%s permission failure, "
"acc=%x, error=%d\n",
dentry->d_parent->d_name.name,
dentry->d_name.name,
access, ntohl(error));
}
out:
if (error == nfserr_stale)
nfsdstats.fh_stale++;
return error;
}
/*
* Compose a file handle for an NFS reply.
*
* Note that when first composed, the dentry may not yet have
* an inode. In this case a call to fh_update should be made
* before the fh goes out on the wire ...
*/
static void _fh_update(struct svc_fh *fhp, struct svc_export *exp,
struct dentry *dentry)
{
if (dentry != exp->ex_path.dentry) {
struct fid *fid = (struct fid *)
(fhp->fh_handle.fh_auth + fhp->fh_handle.fh_size/4 - 1);
int maxsize = (fhp->fh_maxsize - fhp->fh_handle.fh_size)/4;
int subtreecheck = !(exp->ex_flags & NFSEXP_NOSUBTREECHECK);
fhp->fh_handle.fh_fileid_type =
exportfs_encode_fh(dentry, fid, &maxsize, subtreecheck);
fhp->fh_handle.fh_size += maxsize * 4;
} else {
fhp->fh_handle.fh_fileid_type = FILEID_ROOT;
}
}
/*
* for composing old style file handles
*/
static inline void _fh_update_old(struct dentry *dentry,
struct svc_export *exp,
struct knfsd_fh *fh)
{
fh->ofh_ino = ino_t_to_u32(dentry->d_inode->i_ino);
fh->ofh_generation = dentry->d_inode->i_generation;
if (S_ISDIR(dentry->d_inode->i_mode) ||
(exp->ex_flags & NFSEXP_NOSUBTREECHECK))
fh->ofh_dirino = 0;
}
static bool is_root_export(struct svc_export *exp)
{
return exp->ex_path.dentry == exp->ex_path.dentry->d_sb->s_root;
}
static struct super_block *exp_sb(struct svc_export *exp)
{
return exp->ex_path.dentry->d_inode->i_sb;
}
static bool fsid_type_ok_for_exp(u8 fsid_type, struct svc_export *exp)
{
switch (fsid_type) {
case FSID_DEV:
if (!old_valid_dev(exp_sb(exp)->s_dev))
return 0;
/* FALL THROUGH */
case FSID_MAJOR_MINOR:
case FSID_ENCODE_DEV:
return exp_sb(exp)->s_type->fs_flags & FS_REQUIRES_DEV;
case FSID_NUM:
return exp->ex_flags & NFSEXP_FSID;
case FSID_UUID8:
case FSID_UUID16:
if (!is_root_export(exp))
return 0;
/* fall through */
case FSID_UUID4_INUM:
case FSID_UUID16_INUM:
return exp->ex_uuid != NULL;
}
return 1;
}
static void set_version_and_fsid_type(struct svc_fh *fhp, struct svc_export *exp, struct svc_fh *ref_fh)
{
u8 version;
u8 fsid_type;
retry:
version = 1;
if (ref_fh && ref_fh->fh_export == exp) {
version = ref_fh->fh_handle.fh_version;
fsid_type = ref_fh->fh_handle.fh_fsid_type;
ref_fh = NULL;
switch (version) {
case 0xca:
fsid_type = FSID_DEV;
break;
case 1:
break;
default:
goto retry;
}
/*
* As the fsid -> filesystem mapping was guided by
* user-space, there is no guarantee that the filesystem
* actually supports that fsid type. If it doesn't we
* loop around again without ref_fh set.
*/
if (!fsid_type_ok_for_exp(fsid_type, exp))
goto retry;
} else if (exp->ex_flags & NFSEXP_FSID) {
fsid_type = FSID_NUM;
} else if (exp->ex_uuid) {
if (fhp->fh_maxsize >= 64) {
if (is_root_export(exp))
fsid_type = FSID_UUID16;
else
fsid_type = FSID_UUID16_INUM;
} else {
if (is_root_export(exp))
fsid_type = FSID_UUID8;
else
fsid_type = FSID_UUID4_INUM;
}
} else if (!old_valid_dev(exp_sb(exp)->s_dev))
/* for newer device numbers, we must use a newer fsid format */
fsid_type = FSID_ENCODE_DEV;
else
fsid_type = FSID_DEV;
fhp->fh_handle.fh_version = version;
if (version)
fhp->fh_handle.fh_fsid_type = fsid_type;
}
__be32
fh_compose(struct svc_fh *fhp, struct svc_export *exp, struct dentry *dentry,
struct svc_fh *ref_fh)
{
/* ref_fh is a reference file handle.
* if it is non-null and for the same filesystem, then we should compose
* a filehandle which is of the same version, where possible.
* Currently, that means that if ref_fh->fh_handle.fh_version == 0xca
* Then create a 32byte filehandle using nfs_fhbase_old
*
*/
struct inode * inode = dentry->d_inode;
struct dentry *parent = dentry->d_parent;
__u32 *datap;
dev_t ex_dev = exp_sb(exp)->s_dev;
dprintk("nfsd: fh_compose(exp %02x:%02x/%ld %s/%s, ino=%ld)\n",
MAJOR(ex_dev), MINOR(ex_dev),
(long) exp->ex_path.dentry->d_inode->i_ino,
parent->d_name.name, dentry->d_name.name,
(inode ? inode->i_ino : 0));
/* Choose filehandle version and fsid type based on
* the reference filehandle (if it is in the same export)
* or the export options.
*/
set_version_and_fsid_type(fhp, exp, ref_fh);
if (ref_fh == fhp)
fh_put(ref_fh);
if (fhp->fh_locked || fhp->fh_dentry) {
printk(KERN_ERR "fh_compose: fh %s/%s not initialized!\n",
parent->d_name.name, dentry->d_name.name);
}
if (fhp->fh_maxsize < NFS_FHSIZE)
printk(KERN_ERR "fh_compose: called with maxsize %d! %s/%s\n",
fhp->fh_maxsize,
parent->d_name.name, dentry->d_name.name);
fhp->fh_dentry = dget(dentry); /* our internal copy */
fhp->fh_export = exp;
cache_get(&exp->h);
if (fhp->fh_handle.fh_version == 0xca) {
/* old style filehandle please */
memset(&fhp->fh_handle.fh_base, 0, NFS_FHSIZE);
fhp->fh_handle.fh_size = NFS_FHSIZE;
fhp->fh_handle.ofh_dcookie = 0xfeebbaca;
fhp->fh_handle.ofh_dev = old_encode_dev(ex_dev);
fhp->fh_handle.ofh_xdev = fhp->fh_handle.ofh_dev;
fhp->fh_handle.ofh_xino =
ino_t_to_u32(exp->ex_path.dentry->d_inode->i_ino);
fhp->fh_handle.ofh_dirino = ino_t_to_u32(parent_ino(dentry));
if (inode)
_fh_update_old(dentry, exp, &fhp->fh_handle);
} else {
int len;
fhp->fh_handle.fh_auth_type = 0;
datap = fhp->fh_handle.fh_auth+0;
mk_fsid(fhp->fh_handle.fh_fsid_type, datap, ex_dev,
exp->ex_path.dentry->d_inode->i_ino,
exp->ex_fsid, exp->ex_uuid);
len = key_len(fhp->fh_handle.fh_fsid_type);
datap += len/4;
fhp->fh_handle.fh_size = 4 + len;
if (inode)
_fh_update(fhp, exp, dentry);
if (fhp->fh_handle.fh_fileid_type == FILEID_INVALID) {
fh_put(fhp);
return nfserr_opnotsupp;
}
}
return 0;
}
/*
* Update file handle information after changing a dentry.
* This is only called by nfsd_create, nfsd_create_v3 and nfsd_proc_create
*/
__be32
fh_update(struct svc_fh *fhp)
{
struct dentry *dentry;
if (!fhp->fh_dentry)
goto out_bad;
dentry = fhp->fh_dentry;
if (!dentry->d_inode)
goto out_negative;
if (fhp->fh_handle.fh_version != 1) {
_fh_update_old(dentry, fhp->fh_export, &fhp->fh_handle);
} else {
if (fhp->fh_handle.fh_fileid_type != FILEID_ROOT)
goto out;
_fh_update(fhp, fhp->fh_export, dentry);
if (fhp->fh_handle.fh_fileid_type == FILEID_INVALID)
return nfserr_opnotsupp;
}
out:
return 0;
out_bad:
printk(KERN_ERR "fh_update: fh not verified!\n");
goto out;
out_negative:
printk(KERN_ERR "fh_update: %s/%s still negative!\n",
dentry->d_parent->d_name.name, dentry->d_name.name);
goto out;
}
/*
* Release a file handle.
*/
void
fh_put(struct svc_fh *fhp)
{
struct dentry * dentry = fhp->fh_dentry;
struct svc_export * exp = fhp->fh_export;
if (dentry) {
fh_unlock(fhp);
fhp->fh_dentry = NULL;
dput(dentry);
#ifdef CONFIG_NFSD_V3
fhp->fh_pre_saved = 0;
fhp->fh_post_saved = 0;
#endif
}
fh_drop_write(fhp);
if (exp) {
exp_put(exp);
fhp->fh_export = NULL;
}
return;
}
/*
* Shorthand for dprintk()'s
*/
char * SVCFH_fmt(struct svc_fh *fhp)
{
struct knfsd_fh *fh = &fhp->fh_handle;
static char buf[80];
sprintf(buf, "%d: %08x %08x %08x %08x %08x %08x",
fh->fh_size,
fh->fh_base.fh_pad[0],
fh->fh_base.fh_pad[1],
fh->fh_base.fh_pad[2],
fh->fh_base.fh_pad[3],
fh->fh_base.fh_pad[4],
fh->fh_base.fh_pad[5]);
return buf;
}
enum fsid_source fsid_source(struct svc_fh *fhp)
{
if (fhp->fh_handle.fh_version != 1)
return FSIDSOURCE_DEV;
switch(fhp->fh_handle.fh_fsid_type) {
case FSID_DEV:
case FSID_ENCODE_DEV:
case FSID_MAJOR_MINOR:
if (exp_sb(fhp->fh_export)->s_type->fs_flags & FS_REQUIRES_DEV)
return FSIDSOURCE_DEV;
break;
case FSID_NUM:
if (fhp->fh_export->ex_flags & NFSEXP_FSID)
return FSIDSOURCE_FSID;
break;
default:
break;
}
/* either a UUID type filehandle, or the filehandle doesn't
* match the export.
*/
if (fhp->fh_export->ex_flags & NFSEXP_FSID)
return FSIDSOURCE_FSID;
if (fhp->fh_export->ex_uuid)
return FSIDSOURCE_UUID;
return FSIDSOURCE_DEV;
}
| gpl-2.0 |
sandeep1027/kernel-3.10 | drivers/media/rc/keymaps/rc-asus-ps3-100.c | 2913 | 2684 | /* asus-ps3-100.h - Keytable for asus_ps3_100 Remote Controller
*
* Copyright (c) 2012 by Mauro Carvalho Chehab <mchehab@redhat.com>
*
* Based on a previous patch from Remi Schwartz <remi.schwartz@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <media/rc-map.h>
#include <linux/module.h>
static struct rc_map_table asus_ps3_100[] = {
{ 0x081c, KEY_HOME }, /* home */
{ 0x081e, KEY_TV }, /* tv */
{ 0x0803, KEY_TEXT }, /* teletext */
{ 0x0829, KEY_POWER }, /* close */
{ 0x080b, KEY_RED }, /* red */
{ 0x080d, KEY_YELLOW }, /* yellow */
{ 0x0806, KEY_BLUE }, /* blue */
{ 0x0807, KEY_GREEN }, /* green */
/* Keys 0 to 9 */
{ 0x082a, KEY_0 },
{ 0x0816, KEY_1 },
{ 0x0812, KEY_2 },
{ 0x0814, KEY_3 },
{ 0x0836, KEY_4 },
{ 0x0832, KEY_5 },
{ 0x0834, KEY_6 },
{ 0x080e, KEY_7 },
{ 0x080a, KEY_8 },
{ 0x080c, KEY_9 },
{ 0x0815, KEY_VOLUMEUP },
{ 0x0826, KEY_VOLUMEDOWN },
{ 0x0835, KEY_CHANNELUP }, /* channel / program + */
{ 0x0824, KEY_CHANNELDOWN }, /* channel / program - */
{ 0x0808, KEY_UP },
{ 0x0804, KEY_DOWN },
{ 0x0818, KEY_LEFT },
{ 0x0810, KEY_RIGHT },
{ 0x0825, KEY_ENTER }, /* enter */
{ 0x0822, KEY_EXIT }, /* back */
{ 0x082c, KEY_AB }, /* recall */
{ 0x0820, KEY_AUDIO }, /* TV audio */
{ 0x0837, KEY_SCREEN }, /* snapshot */
{ 0x082e, KEY_ZOOM }, /* full screen */
{ 0x0802, KEY_MUTE }, /* mute */
{ 0x0831, KEY_REWIND }, /* backward << */
{ 0x0811, KEY_RECORD }, /* recording */
{ 0x0809, KEY_STOP },
{ 0x0805, KEY_FASTFORWARD }, /* forward >> */
{ 0x0821, KEY_PREVIOUS }, /* rew */
{ 0x081a, KEY_PAUSE }, /* pause */
{ 0x0839, KEY_PLAY }, /* play */
{ 0x0819, KEY_NEXT }, /* forward */
};
static struct rc_map_list asus_ps3_100_map = {
.map = {
.scan = asus_ps3_100,
.size = ARRAY_SIZE(asus_ps3_100),
.rc_type = RC_TYPE_RC5,
.name = RC_MAP_ASUS_PS3_100,
}
};
static int __init init_rc_map_asus_ps3_100(void)
{
return rc_map_register(&asus_ps3_100_map);
}
static void __exit exit_rc_map_asus_ps3_100(void)
{
rc_map_unregister(&asus_ps3_100_map);
}
module_init(init_rc_map_asus_ps3_100)
module_exit(exit_rc_map_asus_ps3_100)
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Mauro Carvalho Chehab <mchehab@redhat.com>");
| gpl-2.0 |
rcstar6696/kernel | drivers/gpu/drm/nouveau/nvc0_fbcon.c | 2913 | 7108 | /*
* Copyright 2010 Red Hat Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Ben Skeggs
*/
#include "nouveau_drm.h"
#include "nouveau_dma.h"
#include "nouveau_fbcon.h"
int
nvc0_fbcon_fillrect(struct fb_info *info, const struct fb_fillrect *rect)
{
struct nouveau_fbdev *nfbdev = info->par;
struct nouveau_drm *drm = nouveau_drm(nfbdev->dev);
struct nouveau_channel *chan = drm->channel;
int ret;
ret = RING_SPACE(chan, rect->rop == ROP_COPY ? 7 : 11);
if (ret)
return ret;
if (rect->rop != ROP_COPY) {
BEGIN_NVC0(chan, NvSub2D, 0x02ac, 1);
OUT_RING (chan, 1);
}
BEGIN_NVC0(chan, NvSub2D, 0x0588, 1);
if (info->fix.visual == FB_VISUAL_TRUECOLOR ||
info->fix.visual == FB_VISUAL_DIRECTCOLOR)
OUT_RING (chan, ((uint32_t *)info->pseudo_palette)[rect->color]);
else
OUT_RING (chan, rect->color);
BEGIN_NVC0(chan, NvSub2D, 0x0600, 4);
OUT_RING (chan, rect->dx);
OUT_RING (chan, rect->dy);
OUT_RING (chan, rect->dx + rect->width);
OUT_RING (chan, rect->dy + rect->height);
if (rect->rop != ROP_COPY) {
BEGIN_NVC0(chan, NvSub2D, 0x02ac, 1);
OUT_RING (chan, 3);
}
FIRE_RING(chan);
return 0;
}
int
nvc0_fbcon_copyarea(struct fb_info *info, const struct fb_copyarea *region)
{
struct nouveau_fbdev *nfbdev = info->par;
struct nouveau_drm *drm = nouveau_drm(nfbdev->dev);
struct nouveau_channel *chan = drm->channel;
int ret;
ret = RING_SPACE(chan, 12);
if (ret)
return ret;
BEGIN_NVC0(chan, NvSub2D, 0x0110, 1);
OUT_RING (chan, 0);
BEGIN_NVC0(chan, NvSub2D, 0x08b0, 4);
OUT_RING (chan, region->dx);
OUT_RING (chan, region->dy);
OUT_RING (chan, region->width);
OUT_RING (chan, region->height);
BEGIN_NVC0(chan, NvSub2D, 0x08d0, 4);
OUT_RING (chan, 0);
OUT_RING (chan, region->sx);
OUT_RING (chan, 0);
OUT_RING (chan, region->sy);
FIRE_RING(chan);
return 0;
}
int
nvc0_fbcon_imageblit(struct fb_info *info, const struct fb_image *image)
{
struct nouveau_fbdev *nfbdev = info->par;
struct nouveau_drm *drm = nouveau_drm(nfbdev->dev);
struct nouveau_channel *chan = drm->channel;
uint32_t width, dwords, *data = (uint32_t *)image->data;
uint32_t mask = ~(~0 >> (32 - info->var.bits_per_pixel));
uint32_t *palette = info->pseudo_palette;
int ret;
if (image->depth != 1)
return -ENODEV;
ret = RING_SPACE(chan, 11);
if (ret)
return ret;
width = ALIGN(image->width, 32);
dwords = (width * image->height) >> 5;
BEGIN_NVC0(chan, NvSub2D, 0x0814, 2);
if (info->fix.visual == FB_VISUAL_TRUECOLOR ||
info->fix.visual == FB_VISUAL_DIRECTCOLOR) {
OUT_RING (chan, palette[image->bg_color] | mask);
OUT_RING (chan, palette[image->fg_color] | mask);
} else {
OUT_RING (chan, image->bg_color);
OUT_RING (chan, image->fg_color);
}
BEGIN_NVC0(chan, NvSub2D, 0x0838, 2);
OUT_RING (chan, image->width);
OUT_RING (chan, image->height);
BEGIN_NVC0(chan, NvSub2D, 0x0850, 4);
OUT_RING (chan, 0);
OUT_RING (chan, image->dx);
OUT_RING (chan, 0);
OUT_RING (chan, image->dy);
while (dwords) {
int push = dwords > 2047 ? 2047 : dwords;
ret = RING_SPACE(chan, push + 1);
if (ret)
return ret;
dwords -= push;
BEGIN_NIC0(chan, NvSub2D, 0x0860, push);
OUT_RINGp(chan, data, push);
data += push;
}
FIRE_RING(chan);
return 0;
}
int
nvc0_fbcon_accel_init(struct fb_info *info)
{
struct nouveau_fbdev *nfbdev = info->par;
struct drm_device *dev = nfbdev->dev;
struct nouveau_framebuffer *fb = &nfbdev->nouveau_fb;
struct nouveau_drm *drm = nouveau_drm(dev);
struct nouveau_channel *chan = drm->channel;
struct nouveau_object *object;
int ret, format;
ret = nouveau_object_new(nv_object(chan->cli), NVDRM_CHAN, Nv2D,
0x902d, NULL, 0, &object);
if (ret)
return ret;
switch (info->var.bits_per_pixel) {
case 8:
format = 0xf3;
break;
case 15:
format = 0xf8;
break;
case 16:
format = 0xe8;
break;
case 32:
switch (info->var.transp.length) {
case 0: /* depth 24 */
case 8: /* depth 32, just use 24.. */
format = 0xe6;
break;
case 2: /* depth 30 */
format = 0xd1;
break;
default:
return -EINVAL;
}
break;
default:
return -EINVAL;
}
ret = RING_SPACE(chan, 60);
if (ret) {
WARN_ON(1);
nouveau_fbcon_gpu_lockup(info);
return ret;
}
BEGIN_NVC0(chan, NvSub2D, 0x0000, 1);
OUT_RING (chan, 0x0000902d);
BEGIN_NVC0(chan, NvSub2D, 0x0290, 1);
OUT_RING (chan, 0);
BEGIN_NVC0(chan, NvSub2D, 0x0888, 1);
OUT_RING (chan, 1);
BEGIN_NVC0(chan, NvSub2D, 0x02ac, 1);
OUT_RING (chan, 3);
BEGIN_NVC0(chan, NvSub2D, 0x02a0, 1);
OUT_RING (chan, 0x55);
BEGIN_NVC0(chan, NvSub2D, 0x08c0, 4);
OUT_RING (chan, 0);
OUT_RING (chan, 1);
OUT_RING (chan, 0);
OUT_RING (chan, 1);
BEGIN_NVC0(chan, NvSub2D, 0x0580, 2);
OUT_RING (chan, 4);
OUT_RING (chan, format);
BEGIN_NVC0(chan, NvSub2D, 0x02e8, 2);
OUT_RING (chan, 2);
OUT_RING (chan, 1);
BEGIN_NVC0(chan, NvSub2D, 0x0804, 1);
OUT_RING (chan, format);
BEGIN_NVC0(chan, NvSub2D, 0x0800, 1);
OUT_RING (chan, 1);
BEGIN_NVC0(chan, NvSub2D, 0x0808, 3);
OUT_RING (chan, 0);
OUT_RING (chan, 0);
OUT_RING (chan, 1);
BEGIN_NVC0(chan, NvSub2D, 0x081c, 1);
OUT_RING (chan, 1);
BEGIN_NVC0(chan, NvSub2D, 0x0840, 4);
OUT_RING (chan, 0);
OUT_RING (chan, 1);
OUT_RING (chan, 0);
OUT_RING (chan, 1);
BEGIN_NVC0(chan, NvSub2D, 0x0200, 10);
OUT_RING (chan, format);
OUT_RING (chan, 1);
OUT_RING (chan, 0);
OUT_RING (chan, 1);
OUT_RING (chan, 0);
OUT_RING (chan, info->fix.line_length);
OUT_RING (chan, info->var.xres_virtual);
OUT_RING (chan, info->var.yres_virtual);
OUT_RING (chan, upper_32_bits(fb->vma.offset));
OUT_RING (chan, lower_32_bits(fb->vma.offset));
BEGIN_NVC0(chan, NvSub2D, 0x0230, 10);
OUT_RING (chan, format);
OUT_RING (chan, 1);
OUT_RING (chan, 0);
OUT_RING (chan, 1);
OUT_RING (chan, 0);
OUT_RING (chan, info->fix.line_length);
OUT_RING (chan, info->var.xres_virtual);
OUT_RING (chan, info->var.yres_virtual);
OUT_RING (chan, upper_32_bits(fb->vma.offset));
OUT_RING (chan, lower_32_bits(fb->vma.offset));
FIRE_RING (chan);
return 0;
}
| gpl-2.0 |
gdachs/linux | drivers/clk/ux500/clk-sysctrl.c | 3681 | 5718 | /*
* Sysctrl clock implementation for ux500 platform.
*
* Copyright (C) 2013 ST-Ericsson SA
* Author: Ulf Hansson <ulf.hansson@linaro.org>
*
* License terms: GNU General Public License (GPL) version 2
*/
#include <linux/clk-provider.h>
#include <linux/mfd/abx500/ab8500-sysctrl.h>
#include <linux/device.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/io.h>
#include <linux/err.h>
#include "clk.h"
#define SYSCTRL_MAX_NUM_PARENTS 4
#define to_clk_sysctrl(_hw) container_of(_hw, struct clk_sysctrl, hw)
struct clk_sysctrl {
struct clk_hw hw;
struct device *dev;
u8 parent_index;
u16 reg_sel[SYSCTRL_MAX_NUM_PARENTS];
u8 reg_mask[SYSCTRL_MAX_NUM_PARENTS];
u8 reg_bits[SYSCTRL_MAX_NUM_PARENTS];
unsigned long rate;
unsigned long enable_delay_us;
};
/* Sysctrl clock operations. */
static int clk_sysctrl_prepare(struct clk_hw *hw)
{
int ret;
struct clk_sysctrl *clk = to_clk_sysctrl(hw);
ret = ab8500_sysctrl_write(clk->reg_sel[0], clk->reg_mask[0],
clk->reg_bits[0]);
if (!ret && clk->enable_delay_us)
usleep_range(clk->enable_delay_us, clk->enable_delay_us);
return ret;
}
static void clk_sysctrl_unprepare(struct clk_hw *hw)
{
struct clk_sysctrl *clk = to_clk_sysctrl(hw);
if (ab8500_sysctrl_clear(clk->reg_sel[0], clk->reg_mask[0]))
dev_err(clk->dev, "clk_sysctrl: %s fail to clear %s.\n",
__func__, __clk_get_name(hw->clk));
}
static unsigned long clk_sysctrl_recalc_rate(struct clk_hw *hw,
unsigned long parent_rate)
{
struct clk_sysctrl *clk = to_clk_sysctrl(hw);
return clk->rate;
}
static int clk_sysctrl_set_parent(struct clk_hw *hw, u8 index)
{
struct clk_sysctrl *clk = to_clk_sysctrl(hw);
u8 old_index = clk->parent_index;
int ret = 0;
if (clk->reg_sel[old_index]) {
ret = ab8500_sysctrl_clear(clk->reg_sel[old_index],
clk->reg_mask[old_index]);
if (ret)
return ret;
}
if (clk->reg_sel[index]) {
ret = ab8500_sysctrl_write(clk->reg_sel[index],
clk->reg_mask[index],
clk->reg_bits[index]);
if (ret) {
if (clk->reg_sel[old_index])
ab8500_sysctrl_write(clk->reg_sel[old_index],
clk->reg_mask[old_index],
clk->reg_bits[old_index]);
return ret;
}
}
clk->parent_index = index;
return ret;
}
static u8 clk_sysctrl_get_parent(struct clk_hw *hw)
{
struct clk_sysctrl *clk = to_clk_sysctrl(hw);
return clk->parent_index;
}
static struct clk_ops clk_sysctrl_gate_ops = {
.prepare = clk_sysctrl_prepare,
.unprepare = clk_sysctrl_unprepare,
};
static struct clk_ops clk_sysctrl_gate_fixed_rate_ops = {
.prepare = clk_sysctrl_prepare,
.unprepare = clk_sysctrl_unprepare,
.recalc_rate = clk_sysctrl_recalc_rate,
};
static struct clk_ops clk_sysctrl_set_parent_ops = {
.set_parent = clk_sysctrl_set_parent,
.get_parent = clk_sysctrl_get_parent,
};
static struct clk *clk_reg_sysctrl(struct device *dev,
const char *name,
const char **parent_names,
u8 num_parents,
u16 *reg_sel,
u8 *reg_mask,
u8 *reg_bits,
unsigned long rate,
unsigned long enable_delay_us,
unsigned long flags,
struct clk_ops *clk_sysctrl_ops)
{
struct clk_sysctrl *clk;
struct clk_init_data clk_sysctrl_init;
struct clk *clk_reg;
int i;
if (!dev)
return ERR_PTR(-EINVAL);
if (!name || (num_parents > SYSCTRL_MAX_NUM_PARENTS)) {
dev_err(dev, "clk_sysctrl: invalid arguments passed\n");
return ERR_PTR(-EINVAL);
}
clk = devm_kzalloc(dev, sizeof(struct clk_sysctrl), GFP_KERNEL);
if (!clk) {
dev_err(dev, "clk_sysctrl: could not allocate clk\n");
return ERR_PTR(-ENOMEM);
}
/* set main clock registers */
clk->reg_sel[0] = reg_sel[0];
clk->reg_bits[0] = reg_bits[0];
clk->reg_mask[0] = reg_mask[0];
/* handle clocks with more than one parent */
for (i = 1; i < num_parents; i++) {
clk->reg_sel[i] = reg_sel[i];
clk->reg_bits[i] = reg_bits[i];
clk->reg_mask[i] = reg_mask[i];
}
clk->parent_index = 0;
clk->rate = rate;
clk->enable_delay_us = enable_delay_us;
clk->dev = dev;
clk_sysctrl_init.name = name;
clk_sysctrl_init.ops = clk_sysctrl_ops;
clk_sysctrl_init.flags = flags;
clk_sysctrl_init.parent_names = parent_names;
clk_sysctrl_init.num_parents = num_parents;
clk->hw.init = &clk_sysctrl_init;
clk_reg = devm_clk_register(clk->dev, &clk->hw);
if (IS_ERR(clk_reg))
dev_err(dev, "clk_sysctrl: clk_register failed\n");
return clk_reg;
}
struct clk *clk_reg_sysctrl_gate(struct device *dev,
const char *name,
const char *parent_name,
u16 reg_sel,
u8 reg_mask,
u8 reg_bits,
unsigned long enable_delay_us,
unsigned long flags)
{
const char **parent_names = (parent_name ? &parent_name : NULL);
u8 num_parents = (parent_name ? 1 : 0);
return clk_reg_sysctrl(dev, name, parent_names, num_parents,
®_sel, ®_mask, ®_bits, 0, enable_delay_us,
flags, &clk_sysctrl_gate_ops);
}
struct clk *clk_reg_sysctrl_gate_fixed_rate(struct device *dev,
const char *name,
const char *parent_name,
u16 reg_sel,
u8 reg_mask,
u8 reg_bits,
unsigned long rate,
unsigned long enable_delay_us,
unsigned long flags)
{
const char **parent_names = (parent_name ? &parent_name : NULL);
u8 num_parents = (parent_name ? 1 : 0);
return clk_reg_sysctrl(dev, name, parent_names, num_parents,
®_sel, ®_mask, ®_bits,
rate, enable_delay_us, flags,
&clk_sysctrl_gate_fixed_rate_ops);
}
struct clk *clk_reg_sysctrl_set_parent(struct device *dev,
const char *name,
const char **parent_names,
u8 num_parents,
u16 *reg_sel,
u8 *reg_mask,
u8 *reg_bits,
unsigned long flags)
{
return clk_reg_sysctrl(dev, name, parent_names, num_parents,
reg_sel, reg_mask, reg_bits, 0, 0, flags,
&clk_sysctrl_set_parent_ops);
}
| gpl-2.0 |
EPDCenter/android_kernel_rockchip | drivers/mtd/maps/esb2rom.c | 3681 | 13012 | /*
* esb2rom.c
*
* Normal mappings of flash chips in physical memory
* through the Intel ESB2 Southbridge.
*
* This was derived from ichxrom.c in May 2006 by
* Lew Glendenning <lglendenning@lnxi.com>
*
* Eric Biederman, of course, was a major help in this effort.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <asm/io.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/map.h>
#include <linux/mtd/cfi.h>
#include <linux/mtd/flashchip.h>
#include <linux/pci.h>
#include <linux/pci_ids.h>
#include <linux/list.h>
#define MOD_NAME KBUILD_BASENAME
#define ADDRESS_NAME_LEN 18
#define ROM_PROBE_STEP_SIZE (64*1024) /* 64KiB */
#define BIOS_CNTL 0xDC
#define BIOS_LOCK_ENABLE 0x02
#define BIOS_WRITE_ENABLE 0x01
/* This became a 16-bit register, and EN2 has disappeared */
#define FWH_DEC_EN1 0xD8
#define FWH_F8_EN 0x8000
#define FWH_F0_EN 0x4000
#define FWH_E8_EN 0x2000
#define FWH_E0_EN 0x1000
#define FWH_D8_EN 0x0800
#define FWH_D0_EN 0x0400
#define FWH_C8_EN 0x0200
#define FWH_C0_EN 0x0100
#define FWH_LEGACY_F_EN 0x0080
#define FWH_LEGACY_E_EN 0x0040
/* reserved 0x0020 and 0x0010 */
#define FWH_70_EN 0x0008
#define FWH_60_EN 0x0004
#define FWH_50_EN 0x0002
#define FWH_40_EN 0x0001
/* these are 32-bit values */
#define FWH_SEL1 0xD0
#define FWH_SEL2 0xD4
#define FWH_8MiB (FWH_F8_EN | FWH_F0_EN | FWH_E8_EN | FWH_E0_EN | \
FWH_D8_EN | FWH_D0_EN | FWH_C8_EN | FWH_C0_EN | \
FWH_70_EN | FWH_60_EN | FWH_50_EN | FWH_40_EN)
#define FWH_7MiB (FWH_F8_EN | FWH_F0_EN | FWH_E8_EN | FWH_E0_EN | \
FWH_D8_EN | FWH_D0_EN | FWH_C8_EN | FWH_C0_EN | \
FWH_70_EN | FWH_60_EN | FWH_50_EN)
#define FWH_6MiB (FWH_F8_EN | FWH_F0_EN | FWH_E8_EN | FWH_E0_EN | \
FWH_D8_EN | FWH_D0_EN | FWH_C8_EN | FWH_C0_EN | \
FWH_70_EN | FWH_60_EN)
#define FWH_5MiB (FWH_F8_EN | FWH_F0_EN | FWH_E8_EN | FWH_E0_EN | \
FWH_D8_EN | FWH_D0_EN | FWH_C8_EN | FWH_C0_EN | \
FWH_70_EN)
#define FWH_4MiB (FWH_F8_EN | FWH_F0_EN | FWH_E8_EN | FWH_E0_EN | \
FWH_D8_EN | FWH_D0_EN | FWH_C8_EN | FWH_C0_EN)
#define FWH_3_5MiB (FWH_F8_EN | FWH_F0_EN | FWH_E8_EN | FWH_E0_EN | \
FWH_D8_EN | FWH_D0_EN | FWH_C8_EN)
#define FWH_3MiB (FWH_F8_EN | FWH_F0_EN | FWH_E8_EN | FWH_E0_EN | \
FWH_D8_EN | FWH_D0_EN)
#define FWH_2_5MiB (FWH_F8_EN | FWH_F0_EN | FWH_E8_EN | FWH_E0_EN | \
FWH_D8_EN)
#define FWH_2MiB (FWH_F8_EN | FWH_F0_EN | FWH_E8_EN | FWH_E0_EN)
#define FWH_1_5MiB (FWH_F8_EN | FWH_F0_EN | FWH_E8_EN)
#define FWH_1MiB (FWH_F8_EN | FWH_F0_EN)
#define FWH_0_5MiB (FWH_F8_EN)
struct esb2rom_window {
void __iomem* virt;
unsigned long phys;
unsigned long size;
struct list_head maps;
struct resource rsrc;
struct pci_dev *pdev;
};
struct esb2rom_map_info {
struct list_head list;
struct map_info map;
struct mtd_info *mtd;
struct resource rsrc;
char map_name[sizeof(MOD_NAME) + 2 + ADDRESS_NAME_LEN];
};
static struct esb2rom_window esb2rom_window = {
.maps = LIST_HEAD_INIT(esb2rom_window.maps),
};
static void esb2rom_cleanup(struct esb2rom_window *window)
{
struct esb2rom_map_info *map, *scratch;
u8 byte;
/* Disable writes through the rom window */
pci_read_config_byte(window->pdev, BIOS_CNTL, &byte);
pci_write_config_byte(window->pdev, BIOS_CNTL,
byte & ~BIOS_WRITE_ENABLE);
/* Free all of the mtd devices */
list_for_each_entry_safe(map, scratch, &window->maps, list) {
if (map->rsrc.parent)
release_resource(&map->rsrc);
mtd_device_unregister(map->mtd);
map_destroy(map->mtd);
list_del(&map->list);
kfree(map);
}
if (window->rsrc.parent)
release_resource(&window->rsrc);
if (window->virt) {
iounmap(window->virt);
window->virt = NULL;
window->phys = 0;
window->size = 0;
}
pci_dev_put(window->pdev);
}
static int esb2rom_init_one(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
static char *rom_probe_types[] = { "cfi_probe", "jedec_probe", NULL };
struct esb2rom_window *window = &esb2rom_window;
struct esb2rom_map_info *map = NULL;
unsigned long map_top;
u8 byte;
u16 word;
/* For now I just handle the ecb2 and I assume there
* are not a lot of resources up at the top of the address
* space. It is possible to handle other devices in the
* top 16MiB but it is very painful. Also since
* you can only really attach a FWH to an ICHX there
* a number of simplifications you can make.
*
* Also you can page firmware hubs if an 8MiB window isn't enough
* but don't currently handle that case either.
*/
window->pdev = pci_dev_get(pdev);
/* RLG: experiment 2. Force the window registers to the widest values */
/*
pci_read_config_word(pdev, FWH_DEC_EN1, &word);
printk(KERN_DEBUG "Original FWH_DEC_EN1 : %x\n", word);
pci_write_config_byte(pdev, FWH_DEC_EN1, 0xff);
pci_read_config_byte(pdev, FWH_DEC_EN1, &byte);
printk(KERN_DEBUG "New FWH_DEC_EN1 : %x\n", byte);
pci_read_config_byte(pdev, FWH_DEC_EN2, &byte);
printk(KERN_DEBUG "Original FWH_DEC_EN2 : %x\n", byte);
pci_write_config_byte(pdev, FWH_DEC_EN2, 0x0f);
pci_read_config_byte(pdev, FWH_DEC_EN2, &byte);
printk(KERN_DEBUG "New FWH_DEC_EN2 : %x\n", byte);
*/
/* Find a region continuous to the end of the ROM window */
window->phys = 0;
pci_read_config_word(pdev, FWH_DEC_EN1, &word);
printk(KERN_DEBUG "pci_read_config_word : %x\n", word);
if ((word & FWH_8MiB) == FWH_8MiB)
window->phys = 0xff400000;
else if ((word & FWH_7MiB) == FWH_7MiB)
window->phys = 0xff500000;
else if ((word & FWH_6MiB) == FWH_6MiB)
window->phys = 0xff600000;
else if ((word & FWH_5MiB) == FWH_5MiB)
window->phys = 0xFF700000;
else if ((word & FWH_4MiB) == FWH_4MiB)
window->phys = 0xffc00000;
else if ((word & FWH_3_5MiB) == FWH_3_5MiB)
window->phys = 0xffc80000;
else if ((word & FWH_3MiB) == FWH_3MiB)
window->phys = 0xffd00000;
else if ((word & FWH_2_5MiB) == FWH_2_5MiB)
window->phys = 0xffd80000;
else if ((word & FWH_2MiB) == FWH_2MiB)
window->phys = 0xffe00000;
else if ((word & FWH_1_5MiB) == FWH_1_5MiB)
window->phys = 0xffe80000;
else if ((word & FWH_1MiB) == FWH_1MiB)
window->phys = 0xfff00000;
else if ((word & FWH_0_5MiB) == FWH_0_5MiB)
window->phys = 0xfff80000;
if (window->phys == 0) {
printk(KERN_ERR MOD_NAME ": Rom window is closed\n");
goto out;
}
/* reserved 0x0020 and 0x0010 */
window->phys -= 0x400000UL;
window->size = (0xffffffffUL - window->phys) + 1UL;
/* Enable writes through the rom window */
pci_read_config_byte(pdev, BIOS_CNTL, &byte);
if (!(byte & BIOS_WRITE_ENABLE) && (byte & (BIOS_LOCK_ENABLE))) {
/* The BIOS will generate an error if I enable
* this device, so don't even try.
*/
printk(KERN_ERR MOD_NAME ": firmware access control, I can't enable writes\n");
goto out;
}
pci_write_config_byte(pdev, BIOS_CNTL, byte | BIOS_WRITE_ENABLE);
/*
* Try to reserve the window mem region. If this fails then
* it is likely due to the window being "reseved" by the BIOS.
*/
window->rsrc.name = MOD_NAME;
window->rsrc.start = window->phys;
window->rsrc.end = window->phys + window->size - 1;
window->rsrc.flags = IORESOURCE_MEM | IORESOURCE_BUSY;
if (request_resource(&iomem_resource, &window->rsrc)) {
window->rsrc.parent = NULL;
printk(KERN_DEBUG MOD_NAME ": "
"%s(): Unable to register resource %pR - kernel bug?\n",
__func__, &window->rsrc);
}
/* Map the firmware hub into my address space. */
window->virt = ioremap_nocache(window->phys, window->size);
if (!window->virt) {
printk(KERN_ERR MOD_NAME ": ioremap(%08lx, %08lx) failed\n",
window->phys, window->size);
goto out;
}
/* Get the first address to look for an rom chip at */
map_top = window->phys;
if ((window->phys & 0x3fffff) != 0) {
/* if not aligned on 4MiB, look 4MiB lower in address space */
map_top = window->phys + 0x400000;
}
#if 1
/* The probe sequence run over the firmware hub lock
* registers sets them to 0x7 (no access).
* (Insane hardware design, but most copied Intel's.)
* ==> Probe at most the last 4M of the address space.
*/
if (map_top < 0xffc00000)
map_top = 0xffc00000;
#endif
/* Loop through and look for rom chips */
while ((map_top - 1) < 0xffffffffUL) {
struct cfi_private *cfi;
unsigned long offset;
int i;
if (!map)
map = kmalloc(sizeof(*map), GFP_KERNEL);
if (!map) {
printk(KERN_ERR MOD_NAME ": kmalloc failed");
goto out;
}
memset(map, 0, sizeof(*map));
INIT_LIST_HEAD(&map->list);
map->map.name = map->map_name;
map->map.phys = map_top;
offset = map_top - window->phys;
map->map.virt = (void __iomem *)
(((unsigned long)(window->virt)) + offset);
map->map.size = 0xffffffffUL - map_top + 1UL;
/* Set the name of the map to the address I am trying */
sprintf(map->map_name, "%s @%08Lx",
MOD_NAME, (unsigned long long)map->map.phys);
/* Firmware hubs only use vpp when being programmed
* in a factory setting. So in-place programming
* needs to use a different method.
*/
for(map->map.bankwidth = 32; map->map.bankwidth;
map->map.bankwidth >>= 1) {
char **probe_type;
/* Skip bankwidths that are not supported */
if (!map_bankwidth_supported(map->map.bankwidth))
continue;
/* Setup the map methods */
simple_map_init(&map->map);
/* Try all of the probe methods */
probe_type = rom_probe_types;
for(; *probe_type; probe_type++) {
map->mtd = do_map_probe(*probe_type, &map->map);
if (map->mtd)
goto found;
}
}
map_top += ROM_PROBE_STEP_SIZE;
continue;
found:
/* Trim the size if we are larger than the map */
if (map->mtd->size > map->map.size) {
printk(KERN_WARNING MOD_NAME
" rom(%llu) larger than window(%lu). fixing...\n",
(unsigned long long)map->mtd->size, map->map.size);
map->mtd->size = map->map.size;
}
if (window->rsrc.parent) {
/*
* Registering the MTD device in iomem may not be possible
* if there is a BIOS "reserved" and BUSY range. If this
* fails then continue anyway.
*/
map->rsrc.name = map->map_name;
map->rsrc.start = map->map.phys;
map->rsrc.end = map->map.phys + map->mtd->size - 1;
map->rsrc.flags = IORESOURCE_MEM | IORESOURCE_BUSY;
if (request_resource(&window->rsrc, &map->rsrc)) {
printk(KERN_ERR MOD_NAME
": cannot reserve MTD resource\n");
map->rsrc.parent = NULL;
}
}
/* Make the whole region visible in the map */
map->map.virt = window->virt;
map->map.phys = window->phys;
cfi = map->map.fldrv_priv;
for(i = 0; i < cfi->numchips; i++)
cfi->chips[i].start += offset;
/* Now that the mtd devices is complete claim and export it */
map->mtd->owner = THIS_MODULE;
if (mtd_device_register(map->mtd, NULL, 0)) {
map_destroy(map->mtd);
map->mtd = NULL;
goto out;
}
/* Calculate the new value of map_top */
map_top += map->mtd->size;
/* File away the map structure */
list_add(&map->list, &window->maps);
map = NULL;
}
out:
/* Free any left over map structures */
kfree(map);
/* See if I have any map structures */
if (list_empty(&window->maps)) {
esb2rom_cleanup(window);
return -ENODEV;
}
return 0;
}
static void esb2rom_remove_one(struct pci_dev *pdev)
{
struct esb2rom_window *window = &esb2rom_window;
esb2rom_cleanup(window);
}
static struct pci_device_id esb2rom_pci_tbl[] = {
{ PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801BA_0,
PCI_ANY_ID, PCI_ANY_ID, },
{ PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801CA_0,
PCI_ANY_ID, PCI_ANY_ID, },
{ PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801DB_0,
PCI_ANY_ID, PCI_ANY_ID, },
{ PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_82801EB_0,
PCI_ANY_ID, PCI_ANY_ID, },
{ PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ESB_1,
PCI_ANY_ID, PCI_ANY_ID, },
{ PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_INTEL_ESB2_0,
PCI_ANY_ID, PCI_ANY_ID, },
{ 0, },
};
#if 0
MODULE_DEVICE_TABLE(pci, esb2rom_pci_tbl);
static struct pci_driver esb2rom_driver = {
.name = MOD_NAME,
.id_table = esb2rom_pci_tbl,
.probe = esb2rom_init_one,
.remove = esb2rom_remove_one,
};
#endif
static int __init init_esb2rom(void)
{
struct pci_dev *pdev;
struct pci_device_id *id;
int retVal;
pdev = NULL;
for (id = esb2rom_pci_tbl; id->vendor; id++) {
printk(KERN_DEBUG "device id = %x\n", id->device);
pdev = pci_get_device(id->vendor, id->device, NULL);
if (pdev) {
printk(KERN_DEBUG "matched device = %x\n", id->device);
break;
}
}
if (pdev) {
printk(KERN_DEBUG "matched device id %x\n", id->device);
retVal = esb2rom_init_one(pdev, &esb2rom_pci_tbl[0]);
pci_dev_put(pdev);
printk(KERN_DEBUG "retVal = %d\n", retVal);
return retVal;
}
return -ENXIO;
#if 0
return pci_register_driver(&esb2rom_driver);
#endif
}
static void __exit cleanup_esb2rom(void)
{
esb2rom_remove_one(esb2rom_window.pdev);
}
module_init(init_esb2rom);
module_exit(cleanup_esb2rom);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Lew Glendenning <lglendenning@lnxi.com>");
MODULE_DESCRIPTION("MTD map driver for BIOS chips on the ESB2 southbridge");
| gpl-2.0 |
GeyerA/kernel_flo | arch/arm/mach-kirkwood/netxbig_v2-setup.c | 4961 | 12809 | /*
* arch/arm/mach-kirkwood/netxbig_v2-setup.c
*
* LaCie 2Big and 5Big Network v2 board setup
*
* Copyright (C) 2010 Simon Guinot <sguinot@lacie.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/ata_platform.h>
#include <linux/mv643xx_eth.h>
#include <linux/input.h>
#include <linux/gpio.h>
#include <linux/gpio_keys.h>
#include <linux/leds.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <mach/kirkwood.h>
#include <mach/leds-netxbig.h>
#include "common.h"
#include "mpp.h"
#include "lacie_v2-common.h"
/*****************************************************************************
* Ethernet
****************************************************************************/
static struct mv643xx_eth_platform_data netxbig_v2_ge00_data = {
.phy_addr = MV643XX_ETH_PHY_ADDR(8),
};
static struct mv643xx_eth_platform_data netxbig_v2_ge01_data = {
.phy_addr = MV643XX_ETH_PHY_ADDR(0),
};
/*****************************************************************************
* SATA
****************************************************************************/
static struct mv_sata_platform_data netxbig_v2_sata_data = {
.n_ports = 2,
};
/*****************************************************************************
* GPIO keys
****************************************************************************/
#define NETXBIG_V2_GPIO_SWITCH_POWER_ON 13
#define NETXBIG_V2_GPIO_SWITCH_POWER_OFF 15
#define NETXBIG_V2_GPIO_FUNC_BUTTON 34
#define NETXBIG_V2_SWITCH_POWER_ON 0x1
#define NETXBIG_V2_SWITCH_POWER_OFF 0x2
static struct gpio_keys_button netxbig_v2_buttons[] = {
[0] = {
.type = EV_SW,
.code = NETXBIG_V2_SWITCH_POWER_ON,
.gpio = NETXBIG_V2_GPIO_SWITCH_POWER_ON,
.desc = "Back power switch (on|auto)",
.active_low = 1,
},
[1] = {
.type = EV_SW,
.code = NETXBIG_V2_SWITCH_POWER_OFF,
.gpio = NETXBIG_V2_GPIO_SWITCH_POWER_OFF,
.desc = "Back power switch (auto|off)",
.active_low = 1,
},
[2] = {
.code = KEY_OPTION,
.gpio = NETXBIG_V2_GPIO_FUNC_BUTTON,
.desc = "Function button",
.active_low = 1,
},
};
static struct gpio_keys_platform_data netxbig_v2_button_data = {
.buttons = netxbig_v2_buttons,
.nbuttons = ARRAY_SIZE(netxbig_v2_buttons),
};
static struct platform_device netxbig_v2_gpio_buttons = {
.name = "gpio-keys",
.id = -1,
.dev = {
.platform_data = &netxbig_v2_button_data,
},
};
/*****************************************************************************
* GPIO extension LEDs
****************************************************************************/
/*
* The LEDs are controlled by a CPLD and can be configured through a GPIO
* extension bus:
*
* - address register : bit [0-2] -> GPIO [47-49]
* - data register : bit [0-2] -> GPIO [44-46]
* - enable register : GPIO 29
*/
static int netxbig_v2_gpio_ext_addr[] = { 47, 48, 49 };
static int netxbig_v2_gpio_ext_data[] = { 44, 45, 46 };
static struct netxbig_gpio_ext netxbig_v2_gpio_ext = {
.addr = netxbig_v2_gpio_ext_addr,
.num_addr = ARRAY_SIZE(netxbig_v2_gpio_ext_addr),
.data = netxbig_v2_gpio_ext_data,
.num_data = ARRAY_SIZE(netxbig_v2_gpio_ext_data),
.enable = 29,
};
/*
* Address register selection:
*
* addr | register
* ----------------------------
* 0 | front LED
* 1 | front LED brightness
* 2 | SATA LED brightness
* 3 | SATA0 LED
* 4 | SATA1 LED
* 5 | SATA2 LED
* 6 | SATA3 LED
* 7 | SATA4 LED
*
* Data register configuration:
*
* data | LED brightness
* -------------------------------------------------
* 0 | min (off)
* - | -
* 7 | max
*
* data | front LED mode
* -------------------------------------------------
* 0 | fix off
* 1 | fix blue on
* 2 | fix red on
* 3 | blink blue on=1 sec and blue off=1 sec
* 4 | blink red on=1 sec and red off=1 sec
* 5 | blink blue on=2.5 sec and red on=0.5 sec
* 6 | blink blue on=1 sec and red on=1 sec
* 7 | blink blue on=0.5 sec and blue off=2.5 sec
*
* data | SATA LED mode
* -------------------------------------------------
* 0 | fix off
* 1 | SATA activity blink
* 2 | fix red on
* 3 | blink blue on=1 sec and blue off=1 sec
* 4 | blink red on=1 sec and red off=1 sec
* 5 | blink blue on=2.5 sec and red on=0.5 sec
* 6 | blink blue on=1 sec and red on=1 sec
* 7 | fix blue on
*/
static int netxbig_v2_red_mled[NETXBIG_LED_MODE_NUM] = {
[NETXBIG_LED_OFF] = 0,
[NETXBIG_LED_ON] = 2,
[NETXBIG_LED_SATA] = NETXBIG_LED_INVALID_MODE,
[NETXBIG_LED_TIMER1] = 4,
[NETXBIG_LED_TIMER2] = NETXBIG_LED_INVALID_MODE,
};
static int netxbig_v2_blue_pwr_mled[NETXBIG_LED_MODE_NUM] = {
[NETXBIG_LED_OFF] = 0,
[NETXBIG_LED_ON] = 1,
[NETXBIG_LED_SATA] = NETXBIG_LED_INVALID_MODE,
[NETXBIG_LED_TIMER1] = 3,
[NETXBIG_LED_TIMER2] = 7,
};
static int netxbig_v2_blue_sata_mled[NETXBIG_LED_MODE_NUM] = {
[NETXBIG_LED_OFF] = 0,
[NETXBIG_LED_ON] = 7,
[NETXBIG_LED_SATA] = 1,
[NETXBIG_LED_TIMER1] = 3,
[NETXBIG_LED_TIMER2] = NETXBIG_LED_INVALID_MODE,
};
static struct netxbig_led_timer netxbig_v2_led_timer[] = {
[0] = {
.delay_on = 500,
.delay_off = 500,
.mode = NETXBIG_LED_TIMER1,
},
[1] = {
.delay_on = 500,
.delay_off = 1000,
.mode = NETXBIG_LED_TIMER2,
},
};
#define NETXBIG_LED(_name, maddr, mval, baddr) \
{ .name = _name, \
.mode_addr = maddr, \
.mode_val = mval, \
.bright_addr = baddr }
static struct netxbig_led net2big_v2_leds_ctrl[] = {
NETXBIG_LED("net2big-v2:blue:power", 0, netxbig_v2_blue_pwr_mled, 1),
NETXBIG_LED("net2big-v2:red:power", 0, netxbig_v2_red_mled, 1),
NETXBIG_LED("net2big-v2:blue:sata0", 3, netxbig_v2_blue_sata_mled, 2),
NETXBIG_LED("net2big-v2:red:sata0", 3, netxbig_v2_red_mled, 2),
NETXBIG_LED("net2big-v2:blue:sata1", 4, netxbig_v2_blue_sata_mled, 2),
NETXBIG_LED("net2big-v2:red:sata1", 4, netxbig_v2_red_mled, 2),
};
static struct netxbig_led_platform_data net2big_v2_leds_data = {
.gpio_ext = &netxbig_v2_gpio_ext,
.timer = netxbig_v2_led_timer,
.num_timer = ARRAY_SIZE(netxbig_v2_led_timer),
.leds = net2big_v2_leds_ctrl,
.num_leds = ARRAY_SIZE(net2big_v2_leds_ctrl),
};
static struct netxbig_led net5big_v2_leds_ctrl[] = {
NETXBIG_LED("net5big-v2:blue:power", 0, netxbig_v2_blue_pwr_mled, 1),
NETXBIG_LED("net5big-v2:red:power", 0, netxbig_v2_red_mled, 1),
NETXBIG_LED("net5big-v2:blue:sata0", 3, netxbig_v2_blue_sata_mled, 2),
NETXBIG_LED("net5big-v2:red:sata0", 3, netxbig_v2_red_mled, 2),
NETXBIG_LED("net5big-v2:blue:sata1", 4, netxbig_v2_blue_sata_mled, 2),
NETXBIG_LED("net5big-v2:red:sata1", 4, netxbig_v2_red_mled, 2),
NETXBIG_LED("net5big-v2:blue:sata2", 5, netxbig_v2_blue_sata_mled, 2),
NETXBIG_LED("net5big-v2:red:sata2", 5, netxbig_v2_red_mled, 2),
NETXBIG_LED("net5big-v2:blue:sata3", 6, netxbig_v2_blue_sata_mled, 2),
NETXBIG_LED("net5big-v2:red:sata3", 6, netxbig_v2_red_mled, 2),
NETXBIG_LED("net5big-v2:blue:sata4", 7, netxbig_v2_blue_sata_mled, 2),
NETXBIG_LED("net5big-v2:red:sata5", 7, netxbig_v2_red_mled, 2),
};
static struct netxbig_led_platform_data net5big_v2_leds_data = {
.gpio_ext = &netxbig_v2_gpio_ext,
.timer = netxbig_v2_led_timer,
.num_timer = ARRAY_SIZE(netxbig_v2_led_timer),
.leds = net5big_v2_leds_ctrl,
.num_leds = ARRAY_SIZE(net5big_v2_leds_ctrl),
};
static struct platform_device netxbig_v2_leds = {
.name = "leds-netxbig",
.id = -1,
.dev = {
.platform_data = &net2big_v2_leds_data,
},
};
/*****************************************************************************
* General Setup
****************************************************************************/
static unsigned int net2big_v2_mpp_config[] __initdata = {
MPP0_SPI_SCn,
MPP1_SPI_MOSI,
MPP2_SPI_SCK,
MPP3_SPI_MISO,
MPP6_SYSRST_OUTn,
MPP7_GPO, /* Request power-off */
MPP8_TW0_SDA,
MPP9_TW0_SCK,
MPP10_UART0_TXD,
MPP11_UART0_RXD,
MPP13_GPIO, /* Rear power switch (on|auto) */
MPP14_GPIO, /* USB fuse alarm */
MPP15_GPIO, /* Rear power switch (auto|off) */
MPP16_GPIO, /* SATA HDD1 power */
MPP17_GPIO, /* SATA HDD2 power */
MPP20_SATA1_ACTn,
MPP21_SATA0_ACTn,
MPP24_GPIO, /* USB mode select */
MPP26_GPIO, /* USB device vbus */
MPP28_GPIO, /* USB enable host vbus */
MPP29_GPIO, /* GPIO extension ALE */
MPP34_GPIO, /* Rear Push button */
MPP35_GPIO, /* Inhibit switch power-off */
MPP36_GPIO, /* SATA HDD1 presence */
MPP37_GPIO, /* SATA HDD2 presence */
MPP40_GPIO, /* eSATA presence */
MPP44_GPIO, /* GPIO extension (data 0) */
MPP45_GPIO, /* GPIO extension (data 1) */
MPP46_GPIO, /* GPIO extension (data 2) */
MPP47_GPIO, /* GPIO extension (addr 0) */
MPP48_GPIO, /* GPIO extension (addr 1) */
MPP49_GPIO, /* GPIO extension (addr 2) */
0
};
static unsigned int net5big_v2_mpp_config[] __initdata = {
MPP0_SPI_SCn,
MPP1_SPI_MOSI,
MPP2_SPI_SCK,
MPP3_SPI_MISO,
MPP6_SYSRST_OUTn,
MPP7_GPO, /* Request power-off */
MPP8_TW0_SDA,
MPP9_TW0_SCK,
MPP10_UART0_TXD,
MPP11_UART0_RXD,
MPP13_GPIO, /* Rear power switch (on|auto) */
MPP14_GPIO, /* USB fuse alarm */
MPP15_GPIO, /* Rear power switch (auto|off) */
MPP16_GPIO, /* SATA HDD1 power */
MPP17_GPIO, /* SATA HDD2 power */
MPP20_GE1_TXD0,
MPP21_GE1_TXD1,
MPP22_GE1_TXD2,
MPP23_GE1_TXD3,
MPP24_GE1_RXD0,
MPP25_GE1_RXD1,
MPP26_GE1_RXD2,
MPP27_GE1_RXD3,
MPP28_GPIO, /* USB enable host vbus */
MPP29_GPIO, /* GPIO extension ALE */
MPP30_GE1_RXCTL,
MPP31_GE1_RXCLK,
MPP32_GE1_TCLKOUT,
MPP33_GE1_TXCTL,
MPP34_GPIO, /* Rear Push button */
MPP35_GPIO, /* Inhibit switch power-off */
MPP36_GPIO, /* SATA HDD1 presence */
MPP37_GPIO, /* SATA HDD2 presence */
MPP38_GPIO, /* SATA HDD3 presence */
MPP39_GPIO, /* SATA HDD4 presence */
MPP40_GPIO, /* SATA HDD5 presence */
MPP41_GPIO, /* SATA HDD3 power */
MPP42_GPIO, /* SATA HDD4 power */
MPP43_GPIO, /* SATA HDD5 power */
MPP44_GPIO, /* GPIO extension (data 0) */
MPP45_GPIO, /* GPIO extension (data 1) */
MPP46_GPIO, /* GPIO extension (data 2) */
MPP47_GPIO, /* GPIO extension (addr 0) */
MPP48_GPIO, /* GPIO extension (addr 1) */
MPP49_GPIO, /* GPIO extension (addr 2) */
0
};
#define NETXBIG_V2_GPIO_POWER_OFF 7
static void netxbig_v2_power_off(void)
{
gpio_set_value(NETXBIG_V2_GPIO_POWER_OFF, 1);
}
static void __init netxbig_v2_init(void)
{
/*
* Basic setup. Needs to be called early.
*/
kirkwood_init();
if (machine_is_net2big_v2())
kirkwood_mpp_conf(net2big_v2_mpp_config);
else
kirkwood_mpp_conf(net5big_v2_mpp_config);
if (machine_is_net2big_v2())
lacie_v2_hdd_power_init(2);
else
lacie_v2_hdd_power_init(5);
kirkwood_ehci_init();
kirkwood_ge00_init(&netxbig_v2_ge00_data);
if (machine_is_net5big_v2())
kirkwood_ge01_init(&netxbig_v2_ge01_data);
kirkwood_sata_init(&netxbig_v2_sata_data);
kirkwood_uart0_init();
lacie_v2_register_flash();
lacie_v2_register_i2c_devices();
if (machine_is_net5big_v2())
netxbig_v2_leds.dev.platform_data = &net5big_v2_leds_data;
platform_device_register(&netxbig_v2_leds);
platform_device_register(&netxbig_v2_gpio_buttons);
if (gpio_request(NETXBIG_V2_GPIO_POWER_OFF, "power-off") == 0 &&
gpio_direction_output(NETXBIG_V2_GPIO_POWER_OFF, 0) == 0)
pm_power_off = netxbig_v2_power_off;
else
pr_err("netxbig_v2: failed to configure power-off GPIO\n");
}
#ifdef CONFIG_MACH_NET2BIG_V2
MACHINE_START(NET2BIG_V2, "LaCie 2Big Network v2")
.atag_offset = 0x100,
.init_machine = netxbig_v2_init,
.map_io = kirkwood_map_io,
.init_early = kirkwood_init_early,
.init_irq = kirkwood_init_irq,
.timer = &kirkwood_timer,
.restart = kirkwood_restart,
MACHINE_END
#endif
#ifdef CONFIG_MACH_NET5BIG_V2
MACHINE_START(NET5BIG_V2, "LaCie 5Big Network v2")
.atag_offset = 0x100,
.init_machine = netxbig_v2_init,
.map_io = kirkwood_map_io,
.init_early = kirkwood_init_early,
.init_irq = kirkwood_init_irq,
.timer = &kirkwood_timer,
.restart = kirkwood_restart,
MACHINE_END
#endif
| gpl-2.0 |
garwynn/android_kernel_samsung_klte | arch/arm/mach-kirkwood/rd88f6281-setup.c | 4961 | 2975 | /*
* arch/arm/mach-kirkwood/rd88f6281-setup.c
*
* Marvell RD-88F6281 Reference Board Setup
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/irq.h>
#include <linux/mtd/partitions.h>
#include <linux/ata_platform.h>
#include <linux/mv643xx_eth.h>
#include <linux/ethtool.h>
#include <net/dsa.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <mach/kirkwood.h>
#include <plat/mvsdio.h>
#include "common.h"
#include "mpp.h"
static struct mtd_partition rd88f6281_nand_parts[] = {
{
.name = "u-boot",
.offset = 0,
.size = SZ_1M
}, {
.name = "uImage",
.offset = MTDPART_OFS_NXTBLK,
.size = SZ_2M
}, {
.name = "root",
.offset = MTDPART_OFS_NXTBLK,
.size = MTDPART_SIZ_FULL
},
};
static struct mv643xx_eth_platform_data rd88f6281_ge00_data = {
.phy_addr = MV643XX_ETH_PHY_NONE,
.speed = SPEED_1000,
.duplex = DUPLEX_FULL,
};
static struct dsa_chip_data rd88f6281_switch_chip_data = {
.port_names[0] = "lan1",
.port_names[1] = "lan2",
.port_names[2] = "lan3",
.port_names[3] = "lan4",
.port_names[5] = "cpu",
};
static struct dsa_platform_data rd88f6281_switch_plat_data = {
.nr_chips = 1,
.chip = &rd88f6281_switch_chip_data,
};
static struct mv643xx_eth_platform_data rd88f6281_ge01_data = {
.phy_addr = MV643XX_ETH_PHY_ADDR(11),
};
static struct mv_sata_platform_data rd88f6281_sata_data = {
.n_ports = 2,
};
static struct mvsdio_platform_data rd88f6281_mvsdio_data = {
.gpio_card_detect = 28,
};
static unsigned int rd88f6281_mpp_config[] __initdata = {
MPP28_GPIO,
0
};
static void __init rd88f6281_init(void)
{
u32 dev, rev;
/*
* Basic setup. Needs to be called early.
*/
kirkwood_init();
kirkwood_mpp_conf(rd88f6281_mpp_config);
kirkwood_nand_init(ARRAY_AND_SIZE(rd88f6281_nand_parts), 25);
kirkwood_ehci_init();
kirkwood_ge00_init(&rd88f6281_ge00_data);
kirkwood_pcie_id(&dev, &rev);
if (rev == MV88F6281_REV_A0) {
rd88f6281_switch_chip_data.sw_addr = 10;
kirkwood_ge01_init(&rd88f6281_ge01_data);
} else {
rd88f6281_switch_chip_data.port_names[4] = "wan";
}
kirkwood_ge00_switch_init(&rd88f6281_switch_plat_data, NO_IRQ);
kirkwood_sata_init(&rd88f6281_sata_data);
kirkwood_sdio_init(&rd88f6281_mvsdio_data);
kirkwood_uart0_init();
}
static int __init rd88f6281_pci_init(void)
{
if (machine_is_rd88f6281())
kirkwood_pcie_init(KW_PCIE0);
return 0;
}
subsys_initcall(rd88f6281_pci_init);
MACHINE_START(RD88F6281, "Marvell RD-88F6281 Reference Board")
/* Maintainer: Saeed Bishara <saeed@marvell.com> */
.atag_offset = 0x100,
.init_machine = rd88f6281_init,
.map_io = kirkwood_map_io,
.init_early = kirkwood_init_early,
.init_irq = kirkwood_init_irq,
.timer = &kirkwood_timer,
.restart = kirkwood_restart,
MACHINE_END
| gpl-2.0 |
mahirkukreja/delos3geurkernel | arch/powerpc/sysdev/xics/ics-rtas.c | 7521 | 6014 | #include <linux/types.h>
#include <linux/kernel.h>
#include <linux/irq.h>
#include <linux/smp.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/cpu.h>
#include <linux/of.h>
#include <linux/spinlock.h>
#include <linux/msi.h>
#include <asm/prom.h>
#include <asm/smp.h>
#include <asm/machdep.h>
#include <asm/irq.h>
#include <asm/errno.h>
#include <asm/xics.h>
#include <asm/rtas.h>
/* RTAS service tokens */
static int ibm_get_xive;
static int ibm_set_xive;
static int ibm_int_on;
static int ibm_int_off;
static int ics_rtas_map(struct ics *ics, unsigned int virq);
static void ics_rtas_mask_unknown(struct ics *ics, unsigned long vec);
static long ics_rtas_get_server(struct ics *ics, unsigned long vec);
static int ics_rtas_host_match(struct ics *ics, struct device_node *node);
/* Only one global & state struct ics */
static struct ics ics_rtas = {
.map = ics_rtas_map,
.mask_unknown = ics_rtas_mask_unknown,
.get_server = ics_rtas_get_server,
.host_match = ics_rtas_host_match,
};
static void ics_rtas_unmask_irq(struct irq_data *d)
{
unsigned int hw_irq = (unsigned int)irqd_to_hwirq(d);
int call_status;
int server;
pr_devel("xics: unmask virq %d [hw 0x%x]\n", d->irq, hw_irq);
if (hw_irq == XICS_IPI || hw_irq == XICS_IRQ_SPURIOUS)
return;
server = xics_get_irq_server(d->irq, d->affinity, 0);
call_status = rtas_call(ibm_set_xive, 3, 1, NULL, hw_irq, server,
DEFAULT_PRIORITY);
if (call_status != 0) {
printk(KERN_ERR
"%s: ibm_set_xive irq %u server %x returned %d\n",
__func__, hw_irq, server, call_status);
return;
}
/* Now unmask the interrupt (often a no-op) */
call_status = rtas_call(ibm_int_on, 1, 1, NULL, hw_irq);
if (call_status != 0) {
printk(KERN_ERR "%s: ibm_int_on irq=%u returned %d\n",
__func__, hw_irq, call_status);
return;
}
}
static unsigned int ics_rtas_startup(struct irq_data *d)
{
#ifdef CONFIG_PCI_MSI
/*
* The generic MSI code returns with the interrupt disabled on the
* card, using the MSI mask bits. Firmware doesn't appear to unmask
* at that level, so we do it here by hand.
*/
if (d->msi_desc)
unmask_msi_irq(d);
#endif
/* unmask it */
ics_rtas_unmask_irq(d);
return 0;
}
static void ics_rtas_mask_real_irq(unsigned int hw_irq)
{
int call_status;
if (hw_irq == XICS_IPI)
return;
call_status = rtas_call(ibm_int_off, 1, 1, NULL, hw_irq);
if (call_status != 0) {
printk(KERN_ERR "%s: ibm_int_off irq=%u returned %d\n",
__func__, hw_irq, call_status);
return;
}
/* Have to set XIVE to 0xff to be able to remove a slot */
call_status = rtas_call(ibm_set_xive, 3, 1, NULL, hw_irq,
xics_default_server, 0xff);
if (call_status != 0) {
printk(KERN_ERR "%s: ibm_set_xive(0xff) irq=%u returned %d\n",
__func__, hw_irq, call_status);
return;
}
}
static void ics_rtas_mask_irq(struct irq_data *d)
{
unsigned int hw_irq = (unsigned int)irqd_to_hwirq(d);
pr_devel("xics: mask virq %d [hw 0x%x]\n", d->irq, hw_irq);
if (hw_irq == XICS_IPI || hw_irq == XICS_IRQ_SPURIOUS)
return;
ics_rtas_mask_real_irq(hw_irq);
}
static int ics_rtas_set_affinity(struct irq_data *d,
const struct cpumask *cpumask,
bool force)
{
unsigned int hw_irq = (unsigned int)irqd_to_hwirq(d);
int status;
int xics_status[2];
int irq_server;
if (hw_irq == XICS_IPI || hw_irq == XICS_IRQ_SPURIOUS)
return -1;
status = rtas_call(ibm_get_xive, 1, 3, xics_status, hw_irq);
if (status) {
printk(KERN_ERR "%s: ibm,get-xive irq=%u returns %d\n",
__func__, hw_irq, status);
return -1;
}
irq_server = xics_get_irq_server(d->irq, cpumask, 1);
if (irq_server == -1) {
char cpulist[128];
cpumask_scnprintf(cpulist, sizeof(cpulist), cpumask);
printk(KERN_WARNING
"%s: No online cpus in the mask %s for irq %d\n",
__func__, cpulist, d->irq);
return -1;
}
status = rtas_call(ibm_set_xive, 3, 1, NULL,
hw_irq, irq_server, xics_status[1]);
if (status) {
printk(KERN_ERR "%s: ibm,set-xive irq=%u returns %d\n",
__func__, hw_irq, status);
return -1;
}
return IRQ_SET_MASK_OK;
}
static struct irq_chip ics_rtas_irq_chip = {
.name = "XICS",
.irq_startup = ics_rtas_startup,
.irq_mask = ics_rtas_mask_irq,
.irq_unmask = ics_rtas_unmask_irq,
.irq_eoi = NULL, /* Patched at init time */
.irq_set_affinity = ics_rtas_set_affinity
};
static int ics_rtas_map(struct ics *ics, unsigned int virq)
{
unsigned int hw_irq = (unsigned int)virq_to_hw(virq);
int status[2];
int rc;
if (WARN_ON(hw_irq == XICS_IPI || hw_irq == XICS_IRQ_SPURIOUS))
return -EINVAL;
/* Check if RTAS knows about this interrupt */
rc = rtas_call(ibm_get_xive, 1, 3, status, hw_irq);
if (rc)
return -ENXIO;
irq_set_chip_and_handler(virq, &ics_rtas_irq_chip, handle_fasteoi_irq);
irq_set_chip_data(virq, &ics_rtas);
return 0;
}
static void ics_rtas_mask_unknown(struct ics *ics, unsigned long vec)
{
ics_rtas_mask_real_irq(vec);
}
static long ics_rtas_get_server(struct ics *ics, unsigned long vec)
{
int rc, status[2];
rc = rtas_call(ibm_get_xive, 1, 3, status, vec);
if (rc)
return -1;
return status[0];
}
static int ics_rtas_host_match(struct ics *ics, struct device_node *node)
{
/* IBM machines have interrupt parents of various funky types for things
* like vdevices, events, etc... The trick we use here is to match
* everything here except the legacy 8259 which is compatible "chrp,iic"
*/
return !of_device_is_compatible(node, "chrp,iic");
}
int ics_rtas_init(void)
{
ibm_get_xive = rtas_token("ibm,get-xive");
ibm_set_xive = rtas_token("ibm,set-xive");
ibm_int_on = rtas_token("ibm,int-on");
ibm_int_off = rtas_token("ibm,int-off");
/* We enable the RTAS "ICS" if RTAS is present with the
* appropriate tokens
*/
if (ibm_get_xive == RTAS_UNKNOWN_SERVICE ||
ibm_set_xive == RTAS_UNKNOWN_SERVICE)
return -ENODEV;
/* We need to patch our irq chip's EOI to point to the
* right ICP
*/
ics_rtas_irq_chip.irq_eoi = icp_ops->eoi;
/* Register ourselves */
xics_register_ics(&ics_rtas);
return 0;
}
| gpl-2.0 |
SlimDevs/kernel_lge_hammerhead | drivers/media/dvb/frontends/tda10086.c | 8801 | 19210 | /*
Driver for Philips tda10086 DVBS Demodulator
(c) 2006 Andrew de Quincey
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/module.h>
#include <linux/device.h>
#include <linux/jiffies.h>
#include <linux/string.h>
#include <linux/slab.h>
#include "dvb_frontend.h"
#include "tda10086.h"
#define SACLK 96000000
struct tda10086_state {
struct i2c_adapter* i2c;
const struct tda10086_config* config;
struct dvb_frontend frontend;
/* private demod data */
u32 frequency;
u32 symbol_rate;
bool has_lock;
};
static int debug;
#define dprintk(args...) \
do { \
if (debug) printk(KERN_DEBUG "tda10086: " args); \
} while (0)
static int tda10086_write_byte(struct tda10086_state *state, int reg, int data)
{
int ret;
u8 b0[] = { reg, data };
struct i2c_msg msg = { .flags = 0, .buf = b0, .len = 2 };
msg.addr = state->config->demod_address;
ret = i2c_transfer(state->i2c, &msg, 1);
if (ret != 1)
dprintk("%s: error reg=0x%x, data=0x%x, ret=%i\n",
__func__, reg, data, ret);
return (ret != 1) ? ret : 0;
}
static int tda10086_read_byte(struct tda10086_state *state, int reg)
{
int ret;
u8 b0[] = { reg };
u8 b1[] = { 0 };
struct i2c_msg msg[] = {{ .flags = 0, .buf = b0, .len = 1 },
{ .flags = I2C_M_RD, .buf = b1, .len = 1 }};
msg[0].addr = state->config->demod_address;
msg[1].addr = state->config->demod_address;
ret = i2c_transfer(state->i2c, msg, 2);
if (ret != 2) {
dprintk("%s: error reg=0x%x, ret=%i\n", __func__, reg,
ret);
return ret;
}
return b1[0];
}
static int tda10086_write_mask(struct tda10086_state *state, int reg, int mask, int data)
{
int val;
/* read a byte and check */
val = tda10086_read_byte(state, reg);
if (val < 0)
return val;
/* mask if off */
val = val & ~mask;
val |= data & 0xff;
/* write it out again */
return tda10086_write_byte(state, reg, val);
}
static int tda10086_init(struct dvb_frontend* fe)
{
struct tda10086_state* state = fe->demodulator_priv;
u8 t22k_off = 0x80;
dprintk ("%s\n", __func__);
if (state->config->diseqc_tone)
t22k_off = 0;
/* reset */
tda10086_write_byte(state, 0x00, 0x00);
msleep(10);
/* misc setup */
tda10086_write_byte(state, 0x01, 0x94);
tda10086_write_byte(state, 0x02, 0x35); /* NOTE: TT drivers appear to disable CSWP */
tda10086_write_byte(state, 0x03, 0xe4);
tda10086_write_byte(state, 0x04, 0x43);
tda10086_write_byte(state, 0x0c, 0x0c);
tda10086_write_byte(state, 0x1b, 0xb0); /* noise threshold */
tda10086_write_byte(state, 0x20, 0x89); /* misc */
tda10086_write_byte(state, 0x30, 0x04); /* acquisition period length */
tda10086_write_byte(state, 0x32, 0x00); /* irq off */
tda10086_write_byte(state, 0x31, 0x56); /* setup AFC */
/* setup PLL (this assumes SACLK = 96MHz) */
tda10086_write_byte(state, 0x55, 0x2c); /* misc PLL setup */
if (state->config->xtal_freq == TDA10086_XTAL_16M) {
tda10086_write_byte(state, 0x3a, 0x0b); /* M=12 */
tda10086_write_byte(state, 0x3b, 0x01); /* P=2 */
} else {
tda10086_write_byte(state, 0x3a, 0x17); /* M=24 */
tda10086_write_byte(state, 0x3b, 0x00); /* P=1 */
}
tda10086_write_mask(state, 0x55, 0x20, 0x00); /* powerup PLL */
/* setup TS interface */
tda10086_write_byte(state, 0x11, 0x81);
tda10086_write_byte(state, 0x12, 0x81);
tda10086_write_byte(state, 0x19, 0x40); /* parallel mode A + MSBFIRST */
tda10086_write_byte(state, 0x56, 0x80); /* powerdown WPLL - unused in the mode we use */
tda10086_write_byte(state, 0x57, 0x08); /* bypass WPLL - unused in the mode we use */
tda10086_write_byte(state, 0x10, 0x2a);
/* setup ADC */
tda10086_write_byte(state, 0x58, 0x61); /* ADC setup */
tda10086_write_mask(state, 0x58, 0x01, 0x00); /* powerup ADC */
/* setup AGC */
tda10086_write_byte(state, 0x05, 0x0B);
tda10086_write_byte(state, 0x37, 0x63);
tda10086_write_byte(state, 0x3f, 0x0a); /* NOTE: flydvb varies it */
tda10086_write_byte(state, 0x40, 0x64);
tda10086_write_byte(state, 0x41, 0x4f);
tda10086_write_byte(state, 0x42, 0x43);
/* setup viterbi */
tda10086_write_byte(state, 0x1a, 0x11); /* VBER 10^6, DVB, QPSK */
/* setup carrier recovery */
tda10086_write_byte(state, 0x3d, 0x80);
/* setup SEC */
tda10086_write_byte(state, 0x36, t22k_off); /* all SEC off, 22k tone */
tda10086_write_byte(state, 0x34, (((1<<19) * (22000/1000)) / (SACLK/1000)));
tda10086_write_byte(state, 0x35, (((1<<19) * (22000/1000)) / (SACLK/1000)) >> 8);
return 0;
}
static void tda10086_diseqc_wait(struct tda10086_state *state)
{
unsigned long timeout = jiffies + msecs_to_jiffies(200);
while (!(tda10086_read_byte(state, 0x50) & 0x01)) {
if(time_after(jiffies, timeout)) {
printk("%s: diseqc queue not ready, command may be lost.\n", __func__);
break;
}
msleep(10);
}
}
static int tda10086_set_tone (struct dvb_frontend* fe, fe_sec_tone_mode_t tone)
{
struct tda10086_state* state = fe->demodulator_priv;
u8 t22k_off = 0x80;
dprintk ("%s\n", __func__);
if (state->config->diseqc_tone)
t22k_off = 0;
switch (tone) {
case SEC_TONE_OFF:
tda10086_write_byte(state, 0x36, t22k_off);
break;
case SEC_TONE_ON:
tda10086_write_byte(state, 0x36, 0x01 + t22k_off);
break;
}
return 0;
}
static int tda10086_send_master_cmd (struct dvb_frontend* fe,
struct dvb_diseqc_master_cmd* cmd)
{
struct tda10086_state* state = fe->demodulator_priv;
int i;
u8 oldval;
u8 t22k_off = 0x80;
dprintk ("%s\n", __func__);
if (state->config->diseqc_tone)
t22k_off = 0;
if (cmd->msg_len > 6)
return -EINVAL;
oldval = tda10086_read_byte(state, 0x36);
for(i=0; i< cmd->msg_len; i++) {
tda10086_write_byte(state, 0x48+i, cmd->msg[i]);
}
tda10086_write_byte(state, 0x36, (0x08 + t22k_off)
| ((cmd->msg_len - 1) << 4));
tda10086_diseqc_wait(state);
tda10086_write_byte(state, 0x36, oldval);
return 0;
}
static int tda10086_send_burst (struct dvb_frontend* fe, fe_sec_mini_cmd_t minicmd)
{
struct tda10086_state* state = fe->demodulator_priv;
u8 oldval = tda10086_read_byte(state, 0x36);
u8 t22k_off = 0x80;
dprintk ("%s\n", __func__);
if (state->config->diseqc_tone)
t22k_off = 0;
switch(minicmd) {
case SEC_MINI_A:
tda10086_write_byte(state, 0x36, 0x04 + t22k_off);
break;
case SEC_MINI_B:
tda10086_write_byte(state, 0x36, 0x06 + t22k_off);
break;
}
tda10086_diseqc_wait(state);
tda10086_write_byte(state, 0x36, oldval);
return 0;
}
static int tda10086_set_inversion(struct tda10086_state *state,
struct dtv_frontend_properties *fe_params)
{
u8 invval = 0x80;
dprintk ("%s %i %i\n", __func__, fe_params->inversion, state->config->invert);
switch(fe_params->inversion) {
case INVERSION_OFF:
if (state->config->invert)
invval = 0x40;
break;
case INVERSION_ON:
if (!state->config->invert)
invval = 0x40;
break;
case INVERSION_AUTO:
invval = 0x00;
break;
}
tda10086_write_mask(state, 0x0c, 0xc0, invval);
return 0;
}
static int tda10086_set_symbol_rate(struct tda10086_state *state,
struct dtv_frontend_properties *fe_params)
{
u8 dfn = 0;
u8 afs = 0;
u8 byp = 0;
u8 reg37 = 0x43;
u8 reg42 = 0x43;
u64 big;
u32 tmp;
u32 bdr;
u32 bdri;
u32 symbol_rate = fe_params->symbol_rate;
dprintk ("%s %i\n", __func__, symbol_rate);
/* setup the decimation and anti-aliasing filters.. */
if (symbol_rate < (u32) (SACLK * 0.0137)) {
dfn=4;
afs=1;
} else if (symbol_rate < (u32) (SACLK * 0.0208)) {
dfn=4;
afs=0;
} else if (symbol_rate < (u32) (SACLK * 0.0270)) {
dfn=3;
afs=1;
} else if (symbol_rate < (u32) (SACLK * 0.0416)) {
dfn=3;
afs=0;
} else if (symbol_rate < (u32) (SACLK * 0.0550)) {
dfn=2;
afs=1;
} else if (symbol_rate < (u32) (SACLK * 0.0833)) {
dfn=2;
afs=0;
} else if (symbol_rate < (u32) (SACLK * 0.1100)) {
dfn=1;
afs=1;
} else if (symbol_rate < (u32) (SACLK * 0.1666)) {
dfn=1;
afs=0;
} else if (symbol_rate < (u32) (SACLK * 0.2200)) {
dfn=0;
afs=1;
} else if (symbol_rate < (u32) (SACLK * 0.3333)) {
dfn=0;
afs=0;
} else {
reg37 = 0x63;
reg42 = 0x4f;
byp=1;
}
/* calculate BDR */
big = (1ULL<<21) * ((u64) symbol_rate/1000ULL) * (1ULL<<dfn);
big += ((SACLK/1000ULL)-1ULL);
do_div(big, (SACLK/1000ULL));
bdr = big & 0xfffff;
/* calculate BDRI */
tmp = (1<<dfn)*(symbol_rate/1000);
bdri = ((32 * (SACLK/1000)) + (tmp-1)) / tmp;
tda10086_write_byte(state, 0x21, (afs << 7) | dfn);
tda10086_write_mask(state, 0x20, 0x08, byp << 3);
tda10086_write_byte(state, 0x06, bdr);
tda10086_write_byte(state, 0x07, bdr >> 8);
tda10086_write_byte(state, 0x08, bdr >> 16);
tda10086_write_byte(state, 0x09, bdri);
tda10086_write_byte(state, 0x37, reg37);
tda10086_write_byte(state, 0x42, reg42);
return 0;
}
static int tda10086_set_fec(struct tda10086_state *state,
struct dtv_frontend_properties *fe_params)
{
u8 fecval;
dprintk("%s %i\n", __func__, fe_params->fec_inner);
switch (fe_params->fec_inner) {
case FEC_1_2:
fecval = 0x00;
break;
case FEC_2_3:
fecval = 0x01;
break;
case FEC_3_4:
fecval = 0x02;
break;
case FEC_4_5:
fecval = 0x03;
break;
case FEC_5_6:
fecval = 0x04;
break;
case FEC_6_7:
fecval = 0x05;
break;
case FEC_7_8:
fecval = 0x06;
break;
case FEC_8_9:
fecval = 0x07;
break;
case FEC_AUTO:
fecval = 0x08;
break;
default:
return -1;
}
tda10086_write_byte(state, 0x0d, fecval);
return 0;
}
static int tda10086_set_frontend(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *fe_params = &fe->dtv_property_cache;
struct tda10086_state *state = fe->demodulator_priv;
int ret;
u32 freq = 0;
int freqoff;
dprintk ("%s\n", __func__);
/* modify parameters for tuning */
tda10086_write_byte(state, 0x02, 0x35);
state->has_lock = false;
/* set params */
if (fe->ops.tuner_ops.set_params) {
fe->ops.tuner_ops.set_params(fe);
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 0);
if (fe->ops.tuner_ops.get_frequency)
fe->ops.tuner_ops.get_frequency(fe, &freq);
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 0);
}
/* calcluate the frequency offset (in *Hz* not kHz) */
freqoff = fe_params->frequency - freq;
freqoff = ((1<<16) * freqoff) / (SACLK/1000);
tda10086_write_byte(state, 0x3d, 0x80 | ((freqoff >> 8) & 0x7f));
tda10086_write_byte(state, 0x3e, freqoff);
if ((ret = tda10086_set_inversion(state, fe_params)) < 0)
return ret;
if ((ret = tda10086_set_symbol_rate(state, fe_params)) < 0)
return ret;
if ((ret = tda10086_set_fec(state, fe_params)) < 0)
return ret;
/* soft reset + disable TS output until lock */
tda10086_write_mask(state, 0x10, 0x40, 0x40);
tda10086_write_mask(state, 0x00, 0x01, 0x00);
state->symbol_rate = fe_params->symbol_rate;
state->frequency = fe_params->frequency;
return 0;
}
static int tda10086_get_frontend(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *fe_params = &fe->dtv_property_cache;
struct tda10086_state* state = fe->demodulator_priv;
u8 val;
int tmp;
u64 tmp64;
dprintk ("%s\n", __func__);
/* check for invalid symbol rate */
if (fe_params->symbol_rate < 500000)
return -EINVAL;
/* calculate the updated frequency (note: we convert from Hz->kHz) */
tmp64 = tda10086_read_byte(state, 0x52);
tmp64 |= (tda10086_read_byte(state, 0x51) << 8);
if (tmp64 & 0x8000)
tmp64 |= 0xffffffffffff0000ULL;
tmp64 = (tmp64 * (SACLK/1000ULL));
do_div(tmp64, (1ULL<<15) * (1ULL<<1));
fe_params->frequency = (int) state->frequency + (int) tmp64;
/* the inversion */
val = tda10086_read_byte(state, 0x0c);
if (val & 0x80) {
switch(val & 0x40) {
case 0x00:
fe_params->inversion = INVERSION_OFF;
if (state->config->invert)
fe_params->inversion = INVERSION_ON;
break;
default:
fe_params->inversion = INVERSION_ON;
if (state->config->invert)
fe_params->inversion = INVERSION_OFF;
break;
}
} else {
tda10086_read_byte(state, 0x0f);
switch(val & 0x02) {
case 0x00:
fe_params->inversion = INVERSION_OFF;
if (state->config->invert)
fe_params->inversion = INVERSION_ON;
break;
default:
fe_params->inversion = INVERSION_ON;
if (state->config->invert)
fe_params->inversion = INVERSION_OFF;
break;
}
}
/* calculate the updated symbol rate */
tmp = tda10086_read_byte(state, 0x1d);
if (tmp & 0x80)
tmp |= 0xffffff00;
tmp = (tmp * 480 * (1<<1)) / 128;
tmp = ((state->symbol_rate/1000) * tmp) / (1000000/1000);
fe_params->symbol_rate = state->symbol_rate + tmp;
/* the FEC */
val = (tda10086_read_byte(state, 0x0d) & 0x70) >> 4;
switch(val) {
case 0x00:
fe_params->fec_inner = FEC_1_2;
break;
case 0x01:
fe_params->fec_inner = FEC_2_3;
break;
case 0x02:
fe_params->fec_inner = FEC_3_4;
break;
case 0x03:
fe_params->fec_inner = FEC_4_5;
break;
case 0x04:
fe_params->fec_inner = FEC_5_6;
break;
case 0x05:
fe_params->fec_inner = FEC_6_7;
break;
case 0x06:
fe_params->fec_inner = FEC_7_8;
break;
case 0x07:
fe_params->fec_inner = FEC_8_9;
break;
}
return 0;
}
static int tda10086_read_status(struct dvb_frontend* fe, fe_status_t *fe_status)
{
struct tda10086_state* state = fe->demodulator_priv;
u8 val;
dprintk ("%s\n", __func__);
val = tda10086_read_byte(state, 0x0e);
*fe_status = 0;
if (val & 0x01)
*fe_status |= FE_HAS_SIGNAL;
if (val & 0x02)
*fe_status |= FE_HAS_CARRIER;
if (val & 0x04)
*fe_status |= FE_HAS_VITERBI;
if (val & 0x08)
*fe_status |= FE_HAS_SYNC;
if (val & 0x10) {
*fe_status |= FE_HAS_LOCK;
if (!state->has_lock) {
state->has_lock = true;
/* modify parameters for stable reception */
tda10086_write_byte(state, 0x02, 0x00);
}
}
return 0;
}
static int tda10086_read_signal_strength(struct dvb_frontend* fe, u16 * signal)
{
struct tda10086_state* state = fe->demodulator_priv;
u8 _str;
dprintk ("%s\n", __func__);
_str = 0xff - tda10086_read_byte(state, 0x43);
*signal = (_str << 8) | _str;
return 0;
}
static int tda10086_read_snr(struct dvb_frontend* fe, u16 * snr)
{
struct tda10086_state* state = fe->demodulator_priv;
u8 _snr;
dprintk ("%s\n", __func__);
_snr = 0xff - tda10086_read_byte(state, 0x1c);
*snr = (_snr << 8) | _snr;
return 0;
}
static int tda10086_read_ucblocks(struct dvb_frontend* fe, u32* ucblocks)
{
struct tda10086_state* state = fe->demodulator_priv;
dprintk ("%s\n", __func__);
/* read it */
*ucblocks = tda10086_read_byte(state, 0x18) & 0x7f;
/* reset counter */
tda10086_write_byte(state, 0x18, 0x00);
tda10086_write_byte(state, 0x18, 0x80);
return 0;
}
static int tda10086_read_ber(struct dvb_frontend* fe, u32* ber)
{
struct tda10086_state* state = fe->demodulator_priv;
dprintk ("%s\n", __func__);
/* read it */
*ber = 0;
*ber |= tda10086_read_byte(state, 0x15);
*ber |= tda10086_read_byte(state, 0x16) << 8;
*ber |= (tda10086_read_byte(state, 0x17) & 0xf) << 16;
return 0;
}
static int tda10086_sleep(struct dvb_frontend* fe)
{
struct tda10086_state* state = fe->demodulator_priv;
dprintk ("%s\n", __func__);
tda10086_write_mask(state, 0x00, 0x08, 0x08);
return 0;
}
static int tda10086_i2c_gate_ctrl(struct dvb_frontend* fe, int enable)
{
struct tda10086_state* state = fe->demodulator_priv;
dprintk ("%s\n", __func__);
if (enable) {
tda10086_write_mask(state, 0x00, 0x10, 0x10);
} else {
tda10086_write_mask(state, 0x00, 0x10, 0x00);
}
return 0;
}
static int tda10086_get_tune_settings(struct dvb_frontend* fe, struct dvb_frontend_tune_settings* fesettings)
{
struct dtv_frontend_properties *p = &fe->dtv_property_cache;
if (p->symbol_rate > 20000000) {
fesettings->min_delay_ms = 50;
fesettings->step_size = 2000;
fesettings->max_drift = 8000;
} else if (p->symbol_rate > 12000000) {
fesettings->min_delay_ms = 100;
fesettings->step_size = 1500;
fesettings->max_drift = 9000;
} else if (p->symbol_rate > 8000000) {
fesettings->min_delay_ms = 100;
fesettings->step_size = 1000;
fesettings->max_drift = 8000;
} else if (p->symbol_rate > 4000000) {
fesettings->min_delay_ms = 100;
fesettings->step_size = 500;
fesettings->max_drift = 7000;
} else if (p->symbol_rate > 2000000) {
fesettings->min_delay_ms = 200;
fesettings->step_size = p->symbol_rate / 8000;
fesettings->max_drift = 14 * fesettings->step_size;
} else {
fesettings->min_delay_ms = 200;
fesettings->step_size = p->symbol_rate / 8000;
fesettings->max_drift = 18 * fesettings->step_size;
}
return 0;
}
static void tda10086_release(struct dvb_frontend* fe)
{
struct tda10086_state *state = fe->demodulator_priv;
tda10086_sleep(fe);
kfree(state);
}
static struct dvb_frontend_ops tda10086_ops = {
.delsys = { SYS_DVBS },
.info = {
.name = "Philips TDA10086 DVB-S",
.frequency_min = 950000,
.frequency_max = 2150000,
.frequency_stepsize = 125, /* kHz for QPSK frontends */
.symbol_rate_min = 1000000,
.symbol_rate_max = 45000000,
.caps = FE_CAN_INVERSION_AUTO |
FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 | FE_CAN_FEC_3_4 |
FE_CAN_FEC_5_6 | FE_CAN_FEC_6_7 | FE_CAN_FEC_7_8 | FE_CAN_FEC_AUTO |
FE_CAN_QPSK
},
.release = tda10086_release,
.init = tda10086_init,
.sleep = tda10086_sleep,
.i2c_gate_ctrl = tda10086_i2c_gate_ctrl,
.set_frontend = tda10086_set_frontend,
.get_frontend = tda10086_get_frontend,
.get_tune_settings = tda10086_get_tune_settings,
.read_status = tda10086_read_status,
.read_ber = tda10086_read_ber,
.read_signal_strength = tda10086_read_signal_strength,
.read_snr = tda10086_read_snr,
.read_ucblocks = tda10086_read_ucblocks,
.diseqc_send_master_cmd = tda10086_send_master_cmd,
.diseqc_send_burst = tda10086_send_burst,
.set_tone = tda10086_set_tone,
};
struct dvb_frontend* tda10086_attach(const struct tda10086_config* config,
struct i2c_adapter* i2c)
{
struct tda10086_state *state;
dprintk ("%s\n", __func__);
/* allocate memory for the internal state */
state = kzalloc(sizeof(struct tda10086_state), GFP_KERNEL);
if (!state)
return NULL;
/* setup the state */
state->config = config;
state->i2c = i2c;
/* check if the demod is there */
if (tda10086_read_byte(state, 0x1e) != 0xe1) {
kfree(state);
return NULL;
}
/* create dvb_frontend */
memcpy(&state->frontend.ops, &tda10086_ops, sizeof(struct dvb_frontend_ops));
state->frontend.demodulator_priv = state;
return &state->frontend;
}
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Turn on/off frontend debugging (default:off).");
MODULE_DESCRIPTION("Philips TDA10086 DVB-S Demodulator");
MODULE_AUTHOR("Andrew de Quincey");
MODULE_LICENSE("GPL");
EXPORT_SYMBOL(tda10086_attach);
| gpl-2.0 |
LorDClockaN/LorDNeo_2639 | drivers/video/vgastate.c | 13409 | 13638 | /*
* linux/drivers/video/vgastate.c -- VGA state save/restore
*
* Copyright 2002 James Simmons
*
* Copyright history from vga16fb.c:
* Copyright 1999 Ben Pfaff and Petr Vandrovec
* Based on VGA info at http://www.goodnet.com/~tinara/FreeVGA/home.htm
* Based on VESA framebuffer (c) 1998 Gerd Knorr
*
* This file is subject to the terms and conditions of the GNU General
* Public License. See the file COPYING in the main directory of this
* archive for more details.
*
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/fb.h>
#include <linux/vmalloc.h>
#include <video/vga.h>
struct regstate {
__u8 *vga_font0;
__u8 *vga_font1;
__u8 *vga_text;
__u8 *vga_cmap;
__u8 *attr;
__u8 *crtc;
__u8 *gfx;
__u8 *seq;
__u8 misc;
};
static inline unsigned char vga_rcrtcs(void __iomem *regbase, unsigned short iobase,
unsigned char reg)
{
vga_w(regbase, iobase + 0x4, reg);
return vga_r(regbase, iobase + 0x5);
}
static inline void vga_wcrtcs(void __iomem *regbase, unsigned short iobase,
unsigned char reg, unsigned char val)
{
vga_w(regbase, iobase + 0x4, reg);
vga_w(regbase, iobase + 0x5, val);
}
static void save_vga_text(struct vgastate *state, void __iomem *fbbase)
{
struct regstate *saved = (struct regstate *) state->vidstate;
int i;
u8 misc, attr10, gr4, gr5, gr6, seq1, seq2, seq4;
unsigned short iobase;
/* if in graphics mode, no need to save */
misc = vga_r(state->vgabase, VGA_MIS_R);
iobase = (misc & 1) ? 0x3d0 : 0x3b0;
vga_r(state->vgabase, iobase + 0xa);
vga_w(state->vgabase, VGA_ATT_W, 0x00);
attr10 = vga_rattr(state->vgabase, 0x10);
vga_r(state->vgabase, iobase + 0xa);
vga_w(state->vgabase, VGA_ATT_W, 0x20);
if (attr10 & 1)
return;
/* save regs */
gr4 = vga_rgfx(state->vgabase, VGA_GFX_PLANE_READ);
gr5 = vga_rgfx(state->vgabase, VGA_GFX_MODE);
gr6 = vga_rgfx(state->vgabase, VGA_GFX_MISC);
seq2 = vga_rseq(state->vgabase, VGA_SEQ_PLANE_WRITE);
seq4 = vga_rseq(state->vgabase, VGA_SEQ_MEMORY_MODE);
/* blank screen */
seq1 = vga_rseq(state->vgabase, VGA_SEQ_CLOCK_MODE);
vga_wseq(state->vgabase, VGA_SEQ_RESET, 0x1);
vga_wseq(state->vgabase, VGA_SEQ_CLOCK_MODE, seq1 | 1 << 5);
vga_wseq(state->vgabase, VGA_SEQ_RESET, 0x3);
/* save font at plane 2 */
if (state->flags & VGA_SAVE_FONT0) {
vga_wseq(state->vgabase, VGA_SEQ_PLANE_WRITE, 0x4);
vga_wseq(state->vgabase, VGA_SEQ_MEMORY_MODE, 0x6);
vga_wgfx(state->vgabase, VGA_GFX_PLANE_READ, 0x2);
vga_wgfx(state->vgabase, VGA_GFX_MODE, 0x0);
vga_wgfx(state->vgabase, VGA_GFX_MISC, 0x5);
for (i = 0; i < 4 * 8192; i++)
saved->vga_font0[i] = vga_r(fbbase, i);
}
/* save font at plane 3 */
if (state->flags & VGA_SAVE_FONT1) {
vga_wseq(state->vgabase, VGA_SEQ_PLANE_WRITE, 0x8);
vga_wseq(state->vgabase, VGA_SEQ_MEMORY_MODE, 0x6);
vga_wgfx(state->vgabase, VGA_GFX_PLANE_READ, 0x3);
vga_wgfx(state->vgabase, VGA_GFX_MODE, 0x0);
vga_wgfx(state->vgabase, VGA_GFX_MISC, 0x5);
for (i = 0; i < state->memsize; i++)
saved->vga_font1[i] = vga_r(fbbase, i);
}
/* save font at plane 0/1 */
if (state->flags & VGA_SAVE_TEXT) {
vga_wseq(state->vgabase, VGA_SEQ_PLANE_WRITE, 0x1);
vga_wseq(state->vgabase, VGA_SEQ_MEMORY_MODE, 0x6);
vga_wgfx(state->vgabase, VGA_GFX_PLANE_READ, 0x0);
vga_wgfx(state->vgabase, VGA_GFX_MODE, 0x0);
vga_wgfx(state->vgabase, VGA_GFX_MISC, 0x5);
for (i = 0; i < 8192; i++)
saved->vga_text[i] = vga_r(fbbase, i);
vga_wseq(state->vgabase, VGA_SEQ_PLANE_WRITE, 0x2);
vga_wseq(state->vgabase, VGA_SEQ_MEMORY_MODE, 0x6);
vga_wgfx(state->vgabase, VGA_GFX_PLANE_READ, 0x1);
vga_wgfx(state->vgabase, VGA_GFX_MODE, 0x0);
vga_wgfx(state->vgabase, VGA_GFX_MISC, 0x5);
for (i = 0; i < 8192; i++)
saved->vga_text[8192+i] = vga_r(fbbase + 2 * 8192, i);
}
/* restore regs */
vga_wseq(state->vgabase, VGA_SEQ_PLANE_WRITE, seq2);
vga_wseq(state->vgabase, VGA_SEQ_MEMORY_MODE, seq4);
vga_wgfx(state->vgabase, VGA_GFX_PLANE_READ, gr4);
vga_wgfx(state->vgabase, VGA_GFX_MODE, gr5);
vga_wgfx(state->vgabase, VGA_GFX_MISC, gr6);
/* unblank screen */
vga_wseq(state->vgabase, VGA_SEQ_RESET, 0x1);
vga_wseq(state->vgabase, VGA_SEQ_CLOCK_MODE, seq1 & ~(1 << 5));
vga_wseq(state->vgabase, VGA_SEQ_RESET, 0x3);
vga_wseq(state->vgabase, VGA_SEQ_CLOCK_MODE, seq1);
}
static void restore_vga_text(struct vgastate *state, void __iomem *fbbase)
{
struct regstate *saved = (struct regstate *) state->vidstate;
int i;
u8 gr1, gr3, gr4, gr5, gr6, gr8;
u8 seq1, seq2, seq4;
/* save regs */
gr1 = vga_rgfx(state->vgabase, VGA_GFX_SR_ENABLE);
gr3 = vga_rgfx(state->vgabase, VGA_GFX_DATA_ROTATE);
gr4 = vga_rgfx(state->vgabase, VGA_GFX_PLANE_READ);
gr5 = vga_rgfx(state->vgabase, VGA_GFX_MODE);
gr6 = vga_rgfx(state->vgabase, VGA_GFX_MISC);
gr8 = vga_rgfx(state->vgabase, VGA_GFX_BIT_MASK);
seq2 = vga_rseq(state->vgabase, VGA_SEQ_PLANE_WRITE);
seq4 = vga_rseq(state->vgabase, VGA_SEQ_MEMORY_MODE);
/* blank screen */
seq1 = vga_rseq(state->vgabase, VGA_SEQ_CLOCK_MODE);
vga_wseq(state->vgabase, VGA_SEQ_RESET, 0x1);
vga_wseq(state->vgabase, VGA_SEQ_CLOCK_MODE, seq1 | 1 << 5);
vga_wseq(state->vgabase, VGA_SEQ_RESET, 0x3);
if (state->depth == 4) {
vga_wgfx(state->vgabase, VGA_GFX_DATA_ROTATE, 0x0);
vga_wgfx(state->vgabase, VGA_GFX_BIT_MASK, 0xff);
vga_wgfx(state->vgabase, VGA_GFX_SR_ENABLE, 0x00);
}
/* restore font at plane 2 */
if (state->flags & VGA_SAVE_FONT0) {
vga_wseq(state->vgabase, VGA_SEQ_PLANE_WRITE, 0x4);
vga_wseq(state->vgabase, VGA_SEQ_MEMORY_MODE, 0x6);
vga_wgfx(state->vgabase, VGA_GFX_PLANE_READ, 0x2);
vga_wgfx(state->vgabase, VGA_GFX_MODE, 0x0);
vga_wgfx(state->vgabase, VGA_GFX_MISC, 0x5);
for (i = 0; i < 4 * 8192; i++)
vga_w(fbbase, i, saved->vga_font0[i]);
}
/* restore font at plane 3 */
if (state->flags & VGA_SAVE_FONT1) {
vga_wseq(state->vgabase, VGA_SEQ_PLANE_WRITE, 0x8);
vga_wseq(state->vgabase, VGA_SEQ_MEMORY_MODE, 0x6);
vga_wgfx(state->vgabase, VGA_GFX_PLANE_READ, 0x3);
vga_wgfx(state->vgabase, VGA_GFX_MODE, 0x0);
vga_wgfx(state->vgabase, VGA_GFX_MISC, 0x5);
for (i = 0; i < state->memsize; i++)
vga_w(fbbase, i, saved->vga_font1[i]);
}
/* restore font at plane 0/1 */
if (state->flags & VGA_SAVE_TEXT) {
vga_wseq(state->vgabase, VGA_SEQ_PLANE_WRITE, 0x1);
vga_wseq(state->vgabase, VGA_SEQ_MEMORY_MODE, 0x6);
vga_wgfx(state->vgabase, VGA_GFX_PLANE_READ, 0x0);
vga_wgfx(state->vgabase, VGA_GFX_MODE, 0x0);
vga_wgfx(state->vgabase, VGA_GFX_MISC, 0x5);
for (i = 0; i < 8192; i++)
vga_w(fbbase, i, saved->vga_text[i]);
vga_wseq(state->vgabase, VGA_SEQ_PLANE_WRITE, 0x2);
vga_wseq(state->vgabase, VGA_SEQ_MEMORY_MODE, 0x6);
vga_wgfx(state->vgabase, VGA_GFX_PLANE_READ, 0x1);
vga_wgfx(state->vgabase, VGA_GFX_MODE, 0x0);
vga_wgfx(state->vgabase, VGA_GFX_MISC, 0x5);
for (i = 0; i < 8192; i++)
vga_w(fbbase, i, saved->vga_text[8192+i]);
}
/* unblank screen */
vga_wseq(state->vgabase, VGA_SEQ_RESET, 0x1);
vga_wseq(state->vgabase, VGA_SEQ_CLOCK_MODE, seq1 & ~(1 << 5));
vga_wseq(state->vgabase, VGA_SEQ_RESET, 0x3);
/* restore regs */
vga_wgfx(state->vgabase, VGA_GFX_SR_ENABLE, gr1);
vga_wgfx(state->vgabase, VGA_GFX_DATA_ROTATE, gr3);
vga_wgfx(state->vgabase, VGA_GFX_PLANE_READ, gr4);
vga_wgfx(state->vgabase, VGA_GFX_MODE, gr5);
vga_wgfx(state->vgabase, VGA_GFX_MISC, gr6);
vga_wgfx(state->vgabase, VGA_GFX_BIT_MASK, gr8);
vga_wseq(state->vgabase, VGA_SEQ_CLOCK_MODE, seq1);
vga_wseq(state->vgabase, VGA_SEQ_PLANE_WRITE, seq2);
vga_wseq(state->vgabase, VGA_SEQ_MEMORY_MODE, seq4);
}
static void save_vga_mode(struct vgastate *state)
{
struct regstate *saved = (struct regstate *) state->vidstate;
unsigned short iobase;
int i;
saved->misc = vga_r(state->vgabase, VGA_MIS_R);
if (saved->misc & 1)
iobase = 0x3d0;
else
iobase = 0x3b0;
for (i = 0; i < state->num_crtc; i++)
saved->crtc[i] = vga_rcrtcs(state->vgabase, iobase, i);
vga_r(state->vgabase, iobase + 0xa);
vga_w(state->vgabase, VGA_ATT_W, 0x00);
for (i = 0; i < state->num_attr; i++) {
vga_r(state->vgabase, iobase + 0xa);
saved->attr[i] = vga_rattr(state->vgabase, i);
}
vga_r(state->vgabase, iobase + 0xa);
vga_w(state->vgabase, VGA_ATT_W, 0x20);
for (i = 0; i < state->num_gfx; i++)
saved->gfx[i] = vga_rgfx(state->vgabase, i);
for (i = 0; i < state->num_seq; i++)
saved->seq[i] = vga_rseq(state->vgabase, i);
}
static void restore_vga_mode(struct vgastate *state)
{
struct regstate *saved = (struct regstate *) state->vidstate;
unsigned short iobase;
int i;
vga_w(state->vgabase, VGA_MIS_W, saved->misc);
if (saved->misc & 1)
iobase = 0x3d0;
else
iobase = 0x3b0;
/* turn off display */
vga_wseq(state->vgabase, VGA_SEQ_CLOCK_MODE,
saved->seq[VGA_SEQ_CLOCK_MODE] | 0x20);
/* disable sequencer */
vga_wseq(state->vgabase, VGA_SEQ_RESET, 0x01);
/* enable palette addressing */
vga_r(state->vgabase, iobase + 0xa);
vga_w(state->vgabase, VGA_ATT_W, 0x00);
for (i = 2; i < state->num_seq; i++)
vga_wseq(state->vgabase, i, saved->seq[i]);
/* unprotect vga regs */
vga_wcrtcs(state->vgabase, iobase, 17, saved->crtc[17] & ~0x80);
for (i = 0; i < state->num_crtc; i++)
vga_wcrtcs(state->vgabase, iobase, i, saved->crtc[i]);
for (i = 0; i < state->num_gfx; i++)
vga_wgfx(state->vgabase, i, saved->gfx[i]);
for (i = 0; i < state->num_attr; i++) {
vga_r(state->vgabase, iobase + 0xa);
vga_wattr(state->vgabase, i, saved->attr[i]);
}
/* reenable sequencer */
vga_wseq(state->vgabase, VGA_SEQ_RESET, 0x03);
/* turn display on */
vga_wseq(state->vgabase, VGA_SEQ_CLOCK_MODE,
saved->seq[VGA_SEQ_CLOCK_MODE] & ~(1 << 5));
/* disable video/palette source */
vga_r(state->vgabase, iobase + 0xa);
vga_w(state->vgabase, VGA_ATT_W, 0x20);
}
static void save_vga_cmap(struct vgastate *state)
{
struct regstate *saved = (struct regstate *) state->vidstate;
int i;
vga_w(state->vgabase, VGA_PEL_MSK, 0xff);
/* assumes DAC is readable and writable */
vga_w(state->vgabase, VGA_PEL_IR, 0x00);
for (i = 0; i < 768; i++)
saved->vga_cmap[i] = vga_r(state->vgabase, VGA_PEL_D);
}
static void restore_vga_cmap(struct vgastate *state)
{
struct regstate *saved = (struct regstate *) state->vidstate;
int i;
vga_w(state->vgabase, VGA_PEL_MSK, 0xff);
/* assumes DAC is readable and writable */
vga_w(state->vgabase, VGA_PEL_IW, 0x00);
for (i = 0; i < 768; i++)
vga_w(state->vgabase, VGA_PEL_D, saved->vga_cmap[i]);
}
static void vga_cleanup(struct vgastate *state)
{
if (state->vidstate != NULL) {
struct regstate *saved = (struct regstate *) state->vidstate;
vfree(saved->vga_font0);
vfree(saved->vga_font1);
vfree(saved->vga_text);
vfree(saved->vga_cmap);
vfree(saved->attr);
kfree(saved);
state->vidstate = NULL;
}
}
int save_vga(struct vgastate *state)
{
struct regstate *saved;
saved = kzalloc(sizeof(struct regstate), GFP_KERNEL);
if (saved == NULL)
return 1;
state->vidstate = (void *)saved;
if (state->flags & VGA_SAVE_CMAP) {
saved->vga_cmap = vmalloc(768);
if (!saved->vga_cmap) {
vga_cleanup(state);
return 1;
}
save_vga_cmap(state);
}
if (state->flags & VGA_SAVE_MODE) {
int total;
if (state->num_attr < 21)
state->num_attr = 21;
if (state->num_crtc < 25)
state->num_crtc = 25;
if (state->num_gfx < 9)
state->num_gfx = 9;
if (state->num_seq < 5)
state->num_seq = 5;
total = state->num_attr + state->num_crtc +
state->num_gfx + state->num_seq;
saved->attr = vmalloc(total);
if (!saved->attr) {
vga_cleanup(state);
return 1;
}
saved->crtc = saved->attr + state->num_attr;
saved->gfx = saved->crtc + state->num_crtc;
saved->seq = saved->gfx + state->num_gfx;
save_vga_mode(state);
}
if (state->flags & VGA_SAVE_FONTS) {
void __iomem *fbbase;
/* exit if window is less than 32K */
if (state->memsize && state->memsize < 4 * 8192) {
vga_cleanup(state);
return 1;
}
if (!state->memsize)
state->memsize = 8 * 8192;
if (!state->membase)
state->membase = 0xA0000;
fbbase = ioremap(state->membase, state->memsize);
if (!fbbase) {
vga_cleanup(state);
return 1;
}
/*
* save only first 32K used by vgacon
*/
if (state->flags & VGA_SAVE_FONT0) {
saved->vga_font0 = vmalloc(4 * 8192);
if (!saved->vga_font0) {
iounmap(fbbase);
vga_cleanup(state);
return 1;
}
}
/*
* largely unused, but if required by the caller
* we'll just save everything.
*/
if (state->flags & VGA_SAVE_FONT1) {
saved->vga_font1 = vmalloc(state->memsize);
if (!saved->vga_font1) {
iounmap(fbbase);
vga_cleanup(state);
return 1;
}
}
/*
* Save 8K at plane0[0], and 8K at plane1[16K]
*/
if (state->flags & VGA_SAVE_TEXT) {
saved->vga_text = vmalloc(8192 * 2);
if (!saved->vga_text) {
iounmap(fbbase);
vga_cleanup(state);
return 1;
}
}
save_vga_text(state, fbbase);
iounmap(fbbase);
}
return 0;
}
int restore_vga (struct vgastate *state)
{
if (state->vidstate == NULL)
return 1;
if (state->flags & VGA_SAVE_MODE)
restore_vga_mode(state);
if (state->flags & VGA_SAVE_FONTS) {
void __iomem *fbbase = ioremap(state->membase, state->memsize);
if (!fbbase) {
vga_cleanup(state);
return 1;
}
restore_vga_text(state, fbbase);
iounmap(fbbase);
}
if (state->flags & VGA_SAVE_CMAP)
restore_vga_cmap(state);
vga_cleanup(state);
return 0;
}
EXPORT_SYMBOL(save_vga);
EXPORT_SYMBOL(restore_vga);
MODULE_AUTHOR("James Simmons <jsimmons@users.sf.net>");
MODULE_DESCRIPTION("VGA State Save/Restore");
MODULE_LICENSE("GPL");
| gpl-2.0 |
TheStrix/android_kernel_xiaomi_armani_OLD | arch/alpha/math-emu/math.c | 13665 | 9859 | #include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <asm/uaccess.h>
#include "sfp-util.h"
#include <math-emu/soft-fp.h>
#include <math-emu/single.h>
#include <math-emu/double.h>
#define OPC_PAL 0x00
#define OPC_INTA 0x10
#define OPC_INTL 0x11
#define OPC_INTS 0x12
#define OPC_INTM 0x13
#define OPC_FLTC 0x14
#define OPC_FLTV 0x15
#define OPC_FLTI 0x16
#define OPC_FLTL 0x17
#define OPC_MISC 0x18
#define OPC_JSR 0x1a
#define FOP_SRC_S 0
#define FOP_SRC_T 2
#define FOP_SRC_Q 3
#define FOP_FNC_ADDx 0
#define FOP_FNC_CVTQL 0
#define FOP_FNC_SUBx 1
#define FOP_FNC_MULx 2
#define FOP_FNC_DIVx 3
#define FOP_FNC_CMPxUN 4
#define FOP_FNC_CMPxEQ 5
#define FOP_FNC_CMPxLT 6
#define FOP_FNC_CMPxLE 7
#define FOP_FNC_SQRTx 11
#define FOP_FNC_CVTxS 12
#define FOP_FNC_CVTxT 14
#define FOP_FNC_CVTxQ 15
#define MISC_TRAPB 0x0000
#define MISC_EXCB 0x0400
extern unsigned long alpha_read_fp_reg (unsigned long reg);
extern void alpha_write_fp_reg (unsigned long reg, unsigned long val);
extern unsigned long alpha_read_fp_reg_s (unsigned long reg);
extern void alpha_write_fp_reg_s (unsigned long reg, unsigned long val);
#ifdef MODULE
MODULE_DESCRIPTION("FP Software completion module");
extern long (*alpha_fp_emul_imprecise)(struct pt_regs *, unsigned long);
extern long (*alpha_fp_emul) (unsigned long pc);
static long (*save_emul_imprecise)(struct pt_regs *, unsigned long);
static long (*save_emul) (unsigned long pc);
long do_alpha_fp_emul_imprecise(struct pt_regs *, unsigned long);
long do_alpha_fp_emul(unsigned long);
int init_module(void)
{
save_emul_imprecise = alpha_fp_emul_imprecise;
save_emul = alpha_fp_emul;
alpha_fp_emul_imprecise = do_alpha_fp_emul_imprecise;
alpha_fp_emul = do_alpha_fp_emul;
return 0;
}
void cleanup_module(void)
{
alpha_fp_emul_imprecise = save_emul_imprecise;
alpha_fp_emul = save_emul;
}
#undef alpha_fp_emul_imprecise
#define alpha_fp_emul_imprecise do_alpha_fp_emul_imprecise
#undef alpha_fp_emul
#define alpha_fp_emul do_alpha_fp_emul
#endif /* MODULE */
/*
* Emulate the floating point instruction at address PC. Returns -1 if the
* instruction to be emulated is illegal (such as with the opDEC trap), else
* the SI_CODE for a SIGFPE signal, else 0 if everything's ok.
*
* Notice that the kernel does not and cannot use FP regs. This is good
* because it means that instead of saving/restoring all fp regs, we simply
* stick the result of the operation into the appropriate register.
*/
long
alpha_fp_emul (unsigned long pc)
{
FP_DECL_EX;
FP_DECL_S(SA); FP_DECL_S(SB); FP_DECL_S(SR);
FP_DECL_D(DA); FP_DECL_D(DB); FP_DECL_D(DR);
unsigned long fa, fb, fc, func, mode, src;
unsigned long res, va, vb, vc, swcr, fpcr;
__u32 insn;
long si_code;
get_user(insn, (__u32 __user *)pc);
fc = (insn >> 0) & 0x1f; /* destination register */
fb = (insn >> 16) & 0x1f;
fa = (insn >> 21) & 0x1f;
func = (insn >> 5) & 0xf;
src = (insn >> 9) & 0x3;
mode = (insn >> 11) & 0x3;
fpcr = rdfpcr();
swcr = swcr_update_status(current_thread_info()->ieee_state, fpcr);
if (mode == 3) {
/* Dynamic -- get rounding mode from fpcr. */
mode = (fpcr >> FPCR_DYN_SHIFT) & 3;
}
switch (src) {
case FOP_SRC_S:
va = alpha_read_fp_reg_s(fa);
vb = alpha_read_fp_reg_s(fb);
FP_UNPACK_SP(SA, &va);
FP_UNPACK_SP(SB, &vb);
switch (func) {
case FOP_FNC_SUBx:
FP_SUB_S(SR, SA, SB);
goto pack_s;
case FOP_FNC_ADDx:
FP_ADD_S(SR, SA, SB);
goto pack_s;
case FOP_FNC_MULx:
FP_MUL_S(SR, SA, SB);
goto pack_s;
case FOP_FNC_DIVx:
FP_DIV_S(SR, SA, SB);
goto pack_s;
case FOP_FNC_SQRTx:
FP_SQRT_S(SR, SB);
goto pack_s;
}
goto bad_insn;
case FOP_SRC_T:
va = alpha_read_fp_reg(fa);
vb = alpha_read_fp_reg(fb);
if ((func & ~3) == FOP_FNC_CMPxUN) {
FP_UNPACK_RAW_DP(DA, &va);
FP_UNPACK_RAW_DP(DB, &vb);
if (!DA_e && !_FP_FRAC_ZEROP_1(DA)) {
FP_SET_EXCEPTION(FP_EX_DENORM);
if (FP_DENORM_ZERO)
_FP_FRAC_SET_1(DA, _FP_ZEROFRAC_1);
}
if (!DB_e && !_FP_FRAC_ZEROP_1(DB)) {
FP_SET_EXCEPTION(FP_EX_DENORM);
if (FP_DENORM_ZERO)
_FP_FRAC_SET_1(DB, _FP_ZEROFRAC_1);
}
FP_CMP_D(res, DA, DB, 3);
vc = 0x4000000000000000UL;
/* CMPTEQ, CMPTUN don't trap on QNaN,
while CMPTLT and CMPTLE do */
if (res == 3
&& ((func & 3) >= 2
|| FP_ISSIGNAN_D(DA)
|| FP_ISSIGNAN_D(DB))) {
FP_SET_EXCEPTION(FP_EX_INVALID);
}
switch (func) {
case FOP_FNC_CMPxUN: if (res != 3) vc = 0; break;
case FOP_FNC_CMPxEQ: if (res) vc = 0; break;
case FOP_FNC_CMPxLT: if (res != -1) vc = 0; break;
case FOP_FNC_CMPxLE: if ((long)res > 0) vc = 0; break;
}
goto done_d;
}
FP_UNPACK_DP(DA, &va);
FP_UNPACK_DP(DB, &vb);
switch (func) {
case FOP_FNC_SUBx:
FP_SUB_D(DR, DA, DB);
goto pack_d;
case FOP_FNC_ADDx:
FP_ADD_D(DR, DA, DB);
goto pack_d;
case FOP_FNC_MULx:
FP_MUL_D(DR, DA, DB);
goto pack_d;
case FOP_FNC_DIVx:
FP_DIV_D(DR, DA, DB);
goto pack_d;
case FOP_FNC_SQRTx:
FP_SQRT_D(DR, DB);
goto pack_d;
case FOP_FNC_CVTxS:
/* It is irritating that DEC encoded CVTST with
SRC == T_floating. It is also interesting that
the bit used to tell the two apart is /U... */
if (insn & 0x2000) {
FP_CONV(S,D,1,1,SR,DB);
goto pack_s;
} else {
vb = alpha_read_fp_reg_s(fb);
FP_UNPACK_SP(SB, &vb);
DR_c = DB_c;
DR_s = DB_s;
DR_e = DB_e + (1024 - 128);
DR_f = SB_f << (52 - 23);
goto pack_d;
}
case FOP_FNC_CVTxQ:
if (DB_c == FP_CLS_NAN
&& (_FP_FRAC_HIGH_RAW_D(DB) & _FP_QNANBIT_D)) {
/* AAHB Table B-2 says QNaN should not trigger INV */
vc = 0;
} else
FP_TO_INT_ROUND_D(vc, DB, 64, 2);
goto done_d;
}
goto bad_insn;
case FOP_SRC_Q:
vb = alpha_read_fp_reg(fb);
switch (func) {
case FOP_FNC_CVTQL:
/* Notice: We can get here only due to an integer
overflow. Such overflows are reported as invalid
ops. We return the result the hw would have
computed. */
vc = ((vb & 0xc0000000) << 32 | /* sign and msb */
(vb & 0x3fffffff) << 29); /* rest of the int */
FP_SET_EXCEPTION (FP_EX_INVALID);
goto done_d;
case FOP_FNC_CVTxS:
FP_FROM_INT_S(SR, ((long)vb), 64, long);
goto pack_s;
case FOP_FNC_CVTxT:
FP_FROM_INT_D(DR, ((long)vb), 64, long);
goto pack_d;
}
goto bad_insn;
}
goto bad_insn;
pack_s:
FP_PACK_SP(&vc, SR);
if ((_fex & FP_EX_UNDERFLOW) && (swcr & IEEE_MAP_UMZ))
vc = 0;
alpha_write_fp_reg_s(fc, vc);
goto done;
pack_d:
FP_PACK_DP(&vc, DR);
if ((_fex & FP_EX_UNDERFLOW) && (swcr & IEEE_MAP_UMZ))
vc = 0;
done_d:
alpha_write_fp_reg(fc, vc);
goto done;
/*
* Take the appropriate action for each possible
* floating-point result:
*
* - Set the appropriate bits in the FPCR
* - If the specified exception is enabled in the FPCR,
* return. The caller (entArith) will dispatch
* the appropriate signal to the translated program.
*
* In addition, properly track the exception state in software
* as described in the Alpha Architecture Handbook section 4.7.7.3.
*/
done:
if (_fex) {
/* Record exceptions in software control word. */
swcr |= (_fex << IEEE_STATUS_TO_EXCSUM_SHIFT);
current_thread_info()->ieee_state
|= (_fex << IEEE_STATUS_TO_EXCSUM_SHIFT);
/* Update hardware control register. */
fpcr &= (~FPCR_MASK | FPCR_DYN_MASK);
fpcr |= ieee_swcr_to_fpcr(swcr);
wrfpcr(fpcr);
/* Do we generate a signal? */
_fex = _fex & swcr & IEEE_TRAP_ENABLE_MASK;
si_code = 0;
if (_fex) {
if (_fex & IEEE_TRAP_ENABLE_DNO) si_code = FPE_FLTUND;
if (_fex & IEEE_TRAP_ENABLE_INE) si_code = FPE_FLTRES;
if (_fex & IEEE_TRAP_ENABLE_UNF) si_code = FPE_FLTUND;
if (_fex & IEEE_TRAP_ENABLE_OVF) si_code = FPE_FLTOVF;
if (_fex & IEEE_TRAP_ENABLE_DZE) si_code = FPE_FLTDIV;
if (_fex & IEEE_TRAP_ENABLE_INV) si_code = FPE_FLTINV;
}
return si_code;
}
/* We used to write the destination register here, but DEC FORTRAN
requires that the result *always* be written... so we do the write
immediately after the operations above. */
return 0;
bad_insn:
printk(KERN_ERR "alpha_fp_emul: Invalid FP insn %#x at %#lx\n",
insn, pc);
return -1;
}
long
alpha_fp_emul_imprecise (struct pt_regs *regs, unsigned long write_mask)
{
unsigned long trigger_pc = regs->pc - 4;
unsigned long insn, opcode, rc, si_code = 0;
/*
* Turn off the bits corresponding to registers that are the
* target of instructions that set bits in the exception
* summary register. We have some slack doing this because a
* register that is the target of a trapping instruction can
* be written at most once in the trap shadow.
*
* Branches, jumps, TRAPBs, EXCBs and calls to PALcode all
* bound the trap shadow, so we need not look any further than
* up to the first occurrence of such an instruction.
*/
while (write_mask) {
get_user(insn, (__u32 __user *)(trigger_pc));
opcode = insn >> 26;
rc = insn & 0x1f;
switch (opcode) {
case OPC_PAL:
case OPC_JSR:
case 0x30 ... 0x3f: /* branches */
goto egress;
case OPC_MISC:
switch (insn & 0xffff) {
case MISC_TRAPB:
case MISC_EXCB:
goto egress;
default:
break;
}
break;
case OPC_INTA:
case OPC_INTL:
case OPC_INTS:
case OPC_INTM:
write_mask &= ~(1UL << rc);
break;
case OPC_FLTC:
case OPC_FLTV:
case OPC_FLTI:
case OPC_FLTL:
write_mask &= ~(1UL << (rc + 32));
break;
}
if (!write_mask) {
/* Re-execute insns in the trap-shadow. */
regs->pc = trigger_pc + 4;
si_code = alpha_fp_emul(trigger_pc);
goto egress;
}
trigger_pc -= 4;
}
egress:
return si_code;
}
| gpl-2.0 |
psyke83/android_kernel_samsung_msm | drivers/video/console/font_pearl_8x8.c | 14689 | 55726 | /**********************************************/
/* */
/* Font file generated by cpi2fnt */
/* ------------------------------ */
/* Combined with the alpha-numeric */
/* portion of Greg Harp's old PEARL */
/* font (from earlier versions of */
/* linux-m86k) by John Shifflett */
/* */
/**********************************************/
#include <linux/font.h>
#define FONTDATAMAX 2048
static const unsigned char fontdata_pearl8x8[FONTDATAMAX] = {
/* 0 0x00 '^@' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 1 0x01 '^A' */
0x7e, /* 01111110 */
0x81, /* 10000001 */
0xa5, /* 10100101 */
0x81, /* 10000001 */
0xbd, /* 10111101 */
0x99, /* 10011001 */
0x81, /* 10000001 */
0x7e, /* 01111110 */
/* 2 0x02 '^B' */
0x7e, /* 01111110 */
0xff, /* 11111111 */
0xdb, /* 11011011 */
0xff, /* 11111111 */
0xc3, /* 11000011 */
0xe7, /* 11100111 */
0xff, /* 11111111 */
0x7e, /* 01111110 */
/* 3 0x03 '^C' */
0x6c, /* 01101100 */
0xfe, /* 11111110 */
0xfe, /* 11111110 */
0xfe, /* 11111110 */
0x7c, /* 01111100 */
0x38, /* 00111000 */
0x10, /* 00010000 */
0x00, /* 00000000 */
/* 4 0x04 '^D' */
0x10, /* 00010000 */
0x38, /* 00111000 */
0x7c, /* 01111100 */
0xfe, /* 11111110 */
0x7c, /* 01111100 */
0x38, /* 00111000 */
0x10, /* 00010000 */
0x00, /* 00000000 */
/* 5 0x05 '^E' */
0x38, /* 00111000 */
0x7c, /* 01111100 */
0x38, /* 00111000 */
0xfe, /* 11111110 */
0xfe, /* 11111110 */
0xd6, /* 11010110 */
0x10, /* 00010000 */
0x38, /* 00111000 */
/* 6 0x06 '^F' */
0x10, /* 00010000 */
0x38, /* 00111000 */
0x7c, /* 01111100 */
0xfe, /* 11111110 */
0xfe, /* 11111110 */
0x7c, /* 01111100 */
0x10, /* 00010000 */
0x38, /* 00111000 */
/* 7 0x07 '^G' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 8 0x08 '^H' */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xe7, /* 11100111 */
0xc3, /* 11000011 */
0xc3, /* 11000011 */
0xe7, /* 11100111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
/* 9 0x09 '^I' */
0x00, /* 00000000 */
0x3c, /* 00111100 */
0x66, /* 01100110 */
0x42, /* 01000010 */
0x42, /* 01000010 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 10 0x0a '^J' */
0xff, /* 11111111 */
0xc3, /* 11000011 */
0x99, /* 10011001 */
0xbd, /* 10111101 */
0xbd, /* 10111101 */
0x99, /* 10011001 */
0xc3, /* 11000011 */
0xff, /* 11111111 */
/* 11 0x0b '^K' */
0x0f, /* 00001111 */
0x07, /* 00000111 */
0x0f, /* 00001111 */
0x7d, /* 01111101 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0x78, /* 01111000 */
/* 12 0x0c '^L' */
0x3c, /* 00111100 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
/* 13 0x0d '^M' */
0x3f, /* 00111111 */
0x33, /* 00110011 */
0x3f, /* 00111111 */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x70, /* 01110000 */
0xf0, /* 11110000 */
0xe0, /* 11100000 */
/* 14 0x0e '^N' */
0x7f, /* 01111111 */
0x63, /* 01100011 */
0x7f, /* 01111111 */
0x63, /* 01100011 */
0x63, /* 01100011 */
0x67, /* 01100111 */
0xe6, /* 11100110 */
0xc0, /* 11000000 */
/* 15 0x0f '^O' */
0x18, /* 00011000 */
0xdb, /* 11011011 */
0x3c, /* 00111100 */
0xe7, /* 11100111 */
0xe7, /* 11100111 */
0x3c, /* 00111100 */
0xdb, /* 11011011 */
0x18, /* 00011000 */
/* 16 0x10 '^P' */
0x80, /* 10000000 */
0xe0, /* 11100000 */
0xf8, /* 11111000 */
0xfe, /* 11111110 */
0xf8, /* 11111000 */
0xe0, /* 11100000 */
0x80, /* 10000000 */
0x00, /* 00000000 */
/* 17 0x11 '^Q' */
0x02, /* 00000010 */
0x0e, /* 00001110 */
0x3e, /* 00111110 */
0xfe, /* 11111110 */
0x3e, /* 00111110 */
0x0e, /* 00001110 */
0x02, /* 00000010 */
0x00, /* 00000000 */
/* 18 0x12 '^R' */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
/* 19 0x13 '^S' */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x00, /* 00000000 */
0x66, /* 01100110 */
0x00, /* 00000000 */
/* 20 0x14 '^T' */
0x7f, /* 01111111 */
0xdb, /* 11011011 */
0xdb, /* 11011011 */
0x7b, /* 01111011 */
0x1b, /* 00011011 */
0x1b, /* 00011011 */
0x1b, /* 00011011 */
0x00, /* 00000000 */
/* 21 0x15 '^U' */
0x3e, /* 00111110 */
0x61, /* 01100001 */
0x3c, /* 00111100 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x86, /* 10000110 */
0x7c, /* 01111100 */
/* 22 0x16 '^V' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x7e, /* 01111110 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
/* 23 0x17 '^W' */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0xff, /* 11111111 */
/* 24 0x18 '^X' */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 25 0x19 '^Y' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 26 0x1a '^Z' */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0xfe, /* 11111110 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 27 0x1b '^[' */
0x00, /* 00000000 */
0x30, /* 00110000 */
0x60, /* 01100000 */
0xfe, /* 11111110 */
0x60, /* 01100000 */
0x30, /* 00110000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 28 0x1c '^\' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 29 0x1d '^]' */
0x00, /* 00000000 */
0x24, /* 00100100 */
0x66, /* 01100110 */
0xff, /* 11111111 */
0x66, /* 01100110 */
0x24, /* 00100100 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 30 0x1e '^^' */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x7e, /* 01111110 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 31 0x1f '^_' */
0x00, /* 00000000 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0x7e, /* 01111110 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 32 0x20 ' ' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 33 0x21 '!' */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x3c, /* 00111100 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 34 0x22 '"' */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 35 0x23 '#' */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0xfe, /* 11111110 */
0x6c, /* 01101100 */
0xfe, /* 11111110 */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0x00, /* 00000000 */
/* 36 0x24 '$' */
0x18, /* 00011000 */
0x3e, /* 00111110 */
0x60, /* 01100000 */
0x3c, /* 00111100 */
0x06, /* 00000110 */
0x7c, /* 01111100 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 37 0x25 '%' */
0x00, /* 00000000 */
0xc6, /* 11000110 */
0xcc, /* 11001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x66, /* 01100110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 38 0x26 '&' */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0x68, /* 01101000 */
0x76, /* 01110110 */
0xdc, /* 11011100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 39 0x27 ''' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 40 0x28 '(' */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x00, /* 00000000 */
/* 41 0x29 ')' */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x00, /* 00000000 */
/* 42 0x2a '*' */
0x00, /* 00000000 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0xff, /* 11111111 */
0x3c, /* 00111100 */
0x66, /* 01100110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 43 0x2b '+' */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 44 0x2c ',' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x30, /* 00110000 */
/* 45 0x2d '-' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 46 0x2e '.' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 47 0x2f '/' */
0x03, /* 00000011 */
0x06, /* 00000110 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x60, /* 01100000 */
0xc0, /* 11000000 */
0x00, /* 00000000 */
/* 48 0x30 '0' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xde, /* 11011110 */
0xfe, /* 11111110 */
0xf6, /* 11110110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 49 0x31 '1' */
0x18, /* 00011000 */
0x78, /* 01111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 50 0x32 '2' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x60, /* 01100000 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
/* 51 0x33 '3' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0x06, /* 00000110 */
0x1c, /* 00011100 */
0x06, /* 00000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 52 0x34 '4' */
0x1c, /* 00011100 */
0x3c, /* 00111100 */
0x6c, /* 01101100 */
0xcc, /* 11001100 */
0xfe, /* 11111110 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0x00, /* 00000000 */
/* 53 0x35 '5' */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0xfc, /* 11111100 */
0x06, /* 00000110 */
0x06, /* 00000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 54 0x36 '6' */
0x38, /* 00111000 */
0x60, /* 01100000 */
0xc0, /* 11000000 */
0xfc, /* 11111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 55 0x37 '7' */
0xfe, /* 11111110 */
0x06, /* 00000110 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x60, /* 01100000 */
0x60, /* 01100000 */
0x00, /* 00000000 */
/* 56 0x38 '8' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 57 0x39 '9' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7e, /* 01111110 */
0x06, /* 00000110 */
0x0c, /* 00001100 */
0x38, /* 00111000 */
0x00, /* 00000000 */
/* 58 0x3a ':' */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 59 0x3b ';' */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x30, /* 00110000 */
/* 60 0x3c '<' */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x60, /* 01100000 */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x00, /* 00000000 */
/* 61 0x3d '=' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 62 0x3e '>' */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x06, /* 00000110 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x00, /* 00000000 */
/* 63 0x3f '?' */
0x3c, /* 00111100 */
0x66, /* 01100110 */
0x06, /* 00000110 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 64 0x40 '@' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xde, /* 11011110 */
0xde, /* 11011110 */
0xde, /* 11011110 */
0xc0, /* 11000000 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 65 0x41 'A' */
0x10, /* 00010000 */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 66 0x42 'B' */
0xfc, /* 11111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xfc, /* 11111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xfc, /* 11111100 */
0x00, /* 00000000 */
/* 67 0x43 'C' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 68 0x44 'D' */
0xfc, /* 11111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xfc, /* 11111100 */
0x00, /* 00000000 */
/* 69 0x45 'E' */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xf8, /* 11111000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
/* 70 0x46 'F' */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xf8, /* 11111000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0x00, /* 00000000 */
/* 71 0x47 'G' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc0, /* 11000000 */
0xce, /* 11001110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 72 0x48 'H' */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 73 0x49 'I' */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
/* 74 0x4a 'J' */
0x06, /* 00000110 */
0x06, /* 00000110 */
0x06, /* 00000110 */
0x06, /* 00000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 75 0x4b 'K' */
0xc6, /* 11000110 */
0xcc, /* 11001100 */
0xd8, /* 11011000 */
0xf0, /* 11110000 */
0xd8, /* 11011000 */
0xcc, /* 11001100 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 76 0x4c 'L' */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
/* 77 0x4d 'M' */
0x82, /* 10000010 */
0xc6, /* 11000110 */
0xee, /* 11101110 */
0xfe, /* 11111110 */
0xd6, /* 11010110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 78 0x4e 'N' */
0xc6, /* 11000110 */
0xe6, /* 11100110 */
0xf6, /* 11110110 */
0xde, /* 11011110 */
0xce, /* 11001110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 79 0x4f 'O' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 80 0x50 'P' */
0xfc, /* 11111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xfc, /* 11111100 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0x00, /* 00000000 */
/* 81 0x51 'Q' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xf6, /* 11110110 */
0xde, /* 11011110 */
0x7c, /* 01111100 */
0x06, /* 00000110 */
/* 82 0x52 'R' */
0xfc, /* 11111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xfc, /* 11111100 */
0xd8, /* 11011000 */
0xcc, /* 11001100 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 83 0x53 'S' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0x60, /* 01100000 */
0x38, /* 00111000 */
0x0c, /* 00001100 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 84 0x54 'T' */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 85 0x55 'U' */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 86 0x56 'V' */
0xc3, /* 11000011 */
0xc3, /* 11000011 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 87 0x57 'W' */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xd6, /* 11010110 */
0xfe, /* 11111110 */
0xee, /* 11101110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 88 0x58 'X' */
0xc3, /* 11000011 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x66, /* 01100110 */
0xc3, /* 11000011 */
0x00, /* 00000000 */
/* 89 0x59 'Y' */
0xc3, /* 11000011 */
0xc3, /* 11000011 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 90 0x5a 'Z' */
0xfe, /* 11111110 */
0x06, /* 00000110 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x60, /* 01100000 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
/* 91 0x5b '[' */
0x3c, /* 00111100 */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 92 0x5c '\' */
0xc0, /* 11000000 */
0x60, /* 01100000 */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x06, /* 00000110 */
0x03, /* 00000011 */
0x00, /* 00000000 */
/* 93 0x5d ']' */
0x3c, /* 00111100 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 94 0x5e '^' */
0x10, /* 00010000 */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 95 0x5f '_' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xfe, /* 11111110 */
/* 96 0x60 '`' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 97 0x61 'a' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7c, /* 01111100 */
0x06, /* 00000110 */
0x7e, /* 01111110 */
0xc6, /* 11000110 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
/* 98 0x62 'b' */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xfc, /* 11111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xfc, /* 11111100 */
0x00, /* 00000000 */
/* 99 0x63 'c' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc0, /* 11000000 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 100 0x64 'd' */
0x06, /* 00000110 */
0x06, /* 00000110 */
0x7e, /* 01111110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
/* 101 0x65 'e' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 102 0x66 'f' */
0x3c, /* 00111100 */
0x66, /* 01100110 */
0x60, /* 01100000 */
0xf0, /* 11110000 */
0x60, /* 01100000 */
0x60, /* 01100000 */
0x60, /* 01100000 */
0x00, /* 00000000 */
/* 103 0x67 'g' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7e, /* 01111110 */
0x06, /* 00000110 */
0x7c, /* 01111100 */
/* 104 0x68 'h' */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xfc, /* 11111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 105 0x69 'i' */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x38, /* 00111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 106 0x6a 'j' */
0x06, /* 00000110 */
0x00, /* 00000000 */
0x06, /* 00000110 */
0x06, /* 00000110 */
0x06, /* 00000110 */
0x06, /* 00000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
/* 107 0x6b 'k' */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xcc, /* 11001100 */
0xd8, /* 11011000 */
0xf0, /* 11110000 */
0xd8, /* 11011000 */
0xcc, /* 11001100 */
0x00, /* 00000000 */
/* 108 0x6c 'l' */
0x38, /* 00111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 109 0x6d 'm' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xec, /* 11101100 */
0xfe, /* 11111110 */
0xd6, /* 11010110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 110 0x6e 'n' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xfc, /* 11111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 111 0x6f 'o' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 112 0x70 'p' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xfc, /* 11111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xfc, /* 11111100 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
/* 113 0x71 'q' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7e, /* 01111110 */
0x06, /* 00000110 */
0x06, /* 00000110 */
/* 114 0x72 'r' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xdc, /* 11011100 */
0xe6, /* 11100110 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0x00, /* 00000000 */
/* 115 0x73 's' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0xc0, /* 11000000 */
0x7c, /* 01111100 */
0x06, /* 00000110 */
0xfc, /* 11111100 */
0x00, /* 00000000 */
/* 116 0x74 't' */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x7c, /* 01111100 */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x36, /* 00110110 */
0x1c, /* 00011100 */
0x00, /* 00000000 */
/* 117 0x75 'u' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 118 0x76 'v' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x6c, /* 01101100 */
0x38, /* 00111000 */
0x00, /* 00000000 */
/* 119 0x77 'w' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xd6, /* 11010110 */
0xfe, /* 11111110 */
0x6c, /* 01101100 */
0x00, /* 00000000 */
/* 120 0x78 'x' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xc6, /* 11000110 */
0x6c, /* 01101100 */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 121 0x79 'y' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xc3, /* 11000011 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x60, /* 01100000 */
/* 122 0x7a 'z' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xfe, /* 11111110 */
0x0c, /* 00001100 */
0x38, /* 00111000 */
0x60, /* 01100000 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
/* 123 0x7b '{' */
0x0e, /* 00001110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x70, /* 01110000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x0e, /* 00001110 */
0x00, /* 00000000 */
/* 124 0x7c '|' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 125 0x7d '}' */
0x70, /* 01110000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x0e, /* 00001110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x70, /* 01110000 */
0x00, /* 00000000 */
/* 126 0x7e '~' */
0x72, /* 01110010 */
0x9c, /* 10011100 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 127 0x7f '' */
0x00, /* 00000000 */
0x10, /* 00010000 */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
/* 128 0x80 '' */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x0c, /* 00001100 */
0x78, /* 01111000 */
/* 129 0x81 '' */
0xcc, /* 11001100 */
0x00, /* 00000000 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 130 0x82 '' */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 131 0x83 '' */
0x7c, /* 01111100 */
0x82, /* 10000010 */
0x78, /* 01111000 */
0x0c, /* 00001100 */
0x7c, /* 01111100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 132 0x84 '' */
0xc6, /* 11000110 */
0x00, /* 00000000 */
0x78, /* 01111000 */
0x0c, /* 00001100 */
0x7c, /* 01111100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 133 0x85 '
' */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x78, /* 01111000 */
0x0c, /* 00001100 */
0x7c, /* 01111100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 134 0x86 '' */
0x30, /* 00110000 */
0x30, /* 00110000 */
0x78, /* 01111000 */
0x0c, /* 00001100 */
0x7c, /* 01111100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 135 0x87 '' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0x7e, /* 01111110 */
0x0c, /* 00001100 */
0x38, /* 00111000 */
/* 136 0x88 '' */
0x7c, /* 01111100 */
0x82, /* 10000010 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 137 0x89 '' */
0xc6, /* 11000110 */
0x00, /* 00000000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 138 0x8a '' */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 139 0x8b '' */
0x66, /* 01100110 */
0x00, /* 00000000 */
0x38, /* 00111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 140 0x8c '' */
0x7c, /* 01111100 */
0x82, /* 10000010 */
0x38, /* 00111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 141 0x8d '' */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x38, /* 00111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 142 0x8e '' */
0xc6, /* 11000110 */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 143 0x8f '' */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 144 0x90 '' */
0x18, /* 00011000 */
0x30, /* 00110000 */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0xf8, /* 11111000 */
0xc0, /* 11000000 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
/* 145 0x91 '' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0xd8, /* 11011000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
/* 146 0x92 '' */
0x3e, /* 00111110 */
0x6c, /* 01101100 */
0xcc, /* 11001100 */
0xfe, /* 11111110 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xce, /* 11001110 */
0x00, /* 00000000 */
/* 147 0x93 '' */
0x7c, /* 01111100 */
0x82, /* 10000010 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 148 0x94 '' */
0xc6, /* 11000110 */
0x00, /* 00000000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 149 0x95 '' */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 150 0x96 '' */
0x78, /* 01111000 */
0x84, /* 10000100 */
0x00, /* 00000000 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 151 0x97 '' */
0x60, /* 01100000 */
0x30, /* 00110000 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 152 0x98 '' */
0xc6, /* 11000110 */
0x00, /* 00000000 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7e, /* 01111110 */
0x06, /* 00000110 */
0xfc, /* 11111100 */
/* 153 0x99 '' */
0xc6, /* 11000110 */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x6c, /* 01101100 */
0x38, /* 00111000 */
0x00, /* 00000000 */
/* 154 0x9a '' */
0xc6, /* 11000110 */
0x00, /* 00000000 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 155 0x9b '' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 156 0x9c '' */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0x64, /* 01100100 */
0xf0, /* 11110000 */
0x60, /* 01100000 */
0x66, /* 01100110 */
0xfc, /* 11111100 */
0x00, /* 00000000 */
/* 157 0x9d '' */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 158 0x9e '' */
0xf8, /* 11111000 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xfa, /* 11111010 */
0xc6, /* 11000110 */
0xcf, /* 11001111 */
0xc6, /* 11000110 */
0xc7, /* 11000111 */
/* 159 0x9f '' */
0x0e, /* 00001110 */
0x1b, /* 00011011 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0xd8, /* 11011000 */
0x70, /* 01110000 */
0x00, /* 00000000 */
/* 160 0xa0 ' ' */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x78, /* 01111000 */
0x0c, /* 00001100 */
0x7c, /* 01111100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 161 0xa1 '¡' */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x38, /* 00111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 162 0xa2 '¢' */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
/* 163 0xa3 '£' */
0x18, /* 00011000 */
0x30, /* 00110000 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 164 0xa4 '¤' */
0x76, /* 01110110 */
0xdc, /* 11011100 */
0x00, /* 00000000 */
0xdc, /* 11011100 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x00, /* 00000000 */
/* 165 0xa5 '¥' */
0x76, /* 01110110 */
0xdc, /* 11011100 */
0x00, /* 00000000 */
0xe6, /* 11100110 */
0xf6, /* 11110110 */
0xde, /* 11011110 */
0xce, /* 11001110 */
0x00, /* 00000000 */
/* 166 0xa6 '¦' */
0x3c, /* 00111100 */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0x3e, /* 00111110 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 167 0xa7 '§' */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0x38, /* 00111000 */
0x00, /* 00000000 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 168 0xa8 '¨' */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x63, /* 01100011 */
0x3e, /* 00111110 */
0x00, /* 00000000 */
/* 169 0xa9 '©' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xfe, /* 11111110 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 170 0xaa 'ª' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xfe, /* 11111110 */
0x06, /* 00000110 */
0x06, /* 00000110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 171 0xab '«' */
0x63, /* 01100011 */
0xe6, /* 11100110 */
0x6c, /* 01101100 */
0x7e, /* 01111110 */
0x33, /* 00110011 */
0x66, /* 01100110 */
0xcc, /* 11001100 */
0x0f, /* 00001111 */
/* 172 0xac '¬' */
0x63, /* 01100011 */
0xe6, /* 11100110 */
0x6c, /* 01101100 */
0x7a, /* 01111010 */
0x36, /* 00110110 */
0x6a, /* 01101010 */
0xdf, /* 11011111 */
0x06, /* 00000110 */
/* 173 0xad '' */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 174 0xae '®' */
0x00, /* 00000000 */
0x33, /* 00110011 */
0x66, /* 01100110 */
0xcc, /* 11001100 */
0x66, /* 01100110 */
0x33, /* 00110011 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 175 0xaf '¯' */
0x00, /* 00000000 */
0xcc, /* 11001100 */
0x66, /* 01100110 */
0x33, /* 00110011 */
0x66, /* 01100110 */
0xcc, /* 11001100 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 176 0xb0 '°' */
0x22, /* 00100010 */
0x88, /* 10001000 */
0x22, /* 00100010 */
0x88, /* 10001000 */
0x22, /* 00100010 */
0x88, /* 10001000 */
0x22, /* 00100010 */
0x88, /* 10001000 */
/* 177 0xb1 '±' */
0x55, /* 01010101 */
0xaa, /* 10101010 */
0x55, /* 01010101 */
0xaa, /* 10101010 */
0x55, /* 01010101 */
0xaa, /* 10101010 */
0x55, /* 01010101 */
0xaa, /* 10101010 */
/* 178 0xb2 '²' */
0x77, /* 01110111 */
0xdd, /* 11011101 */
0x77, /* 01110111 */
0xdd, /* 11011101 */
0x77, /* 01110111 */
0xdd, /* 11011101 */
0x77, /* 01110111 */
0xdd, /* 11011101 */
/* 179 0xb3 '³' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 180 0xb4 '´' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0xf8, /* 11111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 181 0xb5 'µ' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0xf8, /* 11111000 */
0x18, /* 00011000 */
0xf8, /* 11111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 182 0xb6 '¶' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0xf6, /* 11110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 183 0xb7 '·' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xfe, /* 11111110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 184 0xb8 '¸' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xf8, /* 11111000 */
0x18, /* 00011000 */
0xf8, /* 11111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 185 0xb9 '¹' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0xf6, /* 11110110 */
0x06, /* 00000110 */
0xf6, /* 11110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 186 0xba 'º' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 187 0xbb '»' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xfe, /* 11111110 */
0x06, /* 00000110 */
0xf6, /* 11110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 188 0xbc '¼' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0xf6, /* 11110110 */
0x06, /* 00000110 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 189 0xbd '½' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 190 0xbe '¾' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0xf8, /* 11111000 */
0x18, /* 00011000 */
0xf8, /* 11111000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 191 0xbf '¿' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xf8, /* 11111000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 192 0xc0 'À' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x1f, /* 00011111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 193 0xc1 'Á' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 194 0xc2 'Â' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 195 0xc3 'Ã' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x1f, /* 00011111 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 196 0xc4 'Ä' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 197 0xc5 'Å' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0xff, /* 11111111 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 198 0xc6 'Æ' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x1f, /* 00011111 */
0x18, /* 00011000 */
0x1f, /* 00011111 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 199 0xc7 'Ç' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x37, /* 00110111 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 200 0xc8 'È' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x37, /* 00110111 */
0x30, /* 00110000 */
0x3f, /* 00111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 201 0xc9 'É' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x3f, /* 00111111 */
0x30, /* 00110000 */
0x37, /* 00110111 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 202 0xca 'Ê' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0xf7, /* 11110111 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 203 0xcb 'Ë' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0xf7, /* 11110111 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 204 0xcc 'Ì' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x37, /* 00110111 */
0x30, /* 00110000 */
0x37, /* 00110111 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 205 0xcd 'Í' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 206 0xce 'Î' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0xf7, /* 11110111 */
0x00, /* 00000000 */
0xf7, /* 11110111 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 207 0xcf 'Ï' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 208 0xd0 'Ð' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 209 0xd1 'Ñ' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 210 0xd2 'Ò' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 211 0xd3 'Ó' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x3f, /* 00111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 212 0xd4 'Ô' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x1f, /* 00011111 */
0x18, /* 00011000 */
0x1f, /* 00011111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 213 0xd5 'Õ' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x1f, /* 00011111 */
0x18, /* 00011000 */
0x1f, /* 00011111 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 214 0xd6 'Ö' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x3f, /* 00111111 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 215 0xd7 '×' */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0xff, /* 11111111 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
/* 216 0xd8 'Ø' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0xff, /* 11111111 */
0x18, /* 00011000 */
0xff, /* 11111111 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 217 0xd9 'Ù' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0xf8, /* 11111000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 218 0xda 'Ú' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x1f, /* 00011111 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 219 0xdb 'Û' */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
/* 220 0xdc 'Ü' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
/* 221 0xdd 'Ý' */
0xf0, /* 11110000 */
0xf0, /* 11110000 */
0xf0, /* 11110000 */
0xf0, /* 11110000 */
0xf0, /* 11110000 */
0xf0, /* 11110000 */
0xf0, /* 11110000 */
0xf0, /* 11110000 */
/* 222 0xde 'Þ' */
0x0f, /* 00001111 */
0x0f, /* 00001111 */
0x0f, /* 00001111 */
0x0f, /* 00001111 */
0x0f, /* 00001111 */
0x0f, /* 00001111 */
0x0f, /* 00001111 */
0x0f, /* 00001111 */
/* 223 0xdf 'ß' */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0xff, /* 11111111 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 224 0xe0 'à' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x76, /* 01110110 */
0xdc, /* 11011100 */
0xc8, /* 11001000 */
0xdc, /* 11011100 */
0x76, /* 01110110 */
0x00, /* 00000000 */
/* 225 0xe1 'á' */
0x78, /* 01111000 */
0xcc, /* 11001100 */
0xcc, /* 11001100 */
0xd8, /* 11011000 */
0xcc, /* 11001100 */
0xc6, /* 11000110 */
0xcc, /* 11001100 */
0x00, /* 00000000 */
/* 226 0xe2 'â' */
0xfe, /* 11111110 */
0xc6, /* 11000110 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0xc0, /* 11000000 */
0x00, /* 00000000 */
/* 227 0xe3 'ã' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0xfe, /* 11111110 */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0x00, /* 00000000 */
/* 228 0xe4 'ä' */
0xfe, /* 11111110 */
0xc6, /* 11000110 */
0x60, /* 01100000 */
0x30, /* 00110000 */
0x60, /* 01100000 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
/* 229 0xe5 'å' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0xd8, /* 11011000 */
0xd8, /* 11011000 */
0xd8, /* 11011000 */
0x70, /* 01110000 */
0x00, /* 00000000 */
/* 230 0xe6 'æ' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x7c, /* 01111100 */
0xc0, /* 11000000 */
/* 231 0xe7 'ç' */
0x00, /* 00000000 */
0x76, /* 01110110 */
0xdc, /* 11011100 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
/* 232 0xe8 'è' */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x3c, /* 00111100 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
/* 233 0xe9 'é' */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0xc6, /* 11000110 */
0xfe, /* 11111110 */
0xc6, /* 11000110 */
0x6c, /* 01101100 */
0x38, /* 00111000 */
0x00, /* 00000000 */
/* 234 0xea 'ê' */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0xee, /* 11101110 */
0x00, /* 00000000 */
/* 235 0xeb 'ë' */
0x0e, /* 00001110 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x3e, /* 00111110 */
0x66, /* 01100110 */
0x66, /* 01100110 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
/* 236 0xec 'ì' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0xdb, /* 11011011 */
0xdb, /* 11011011 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 237 0xed 'í' */
0x06, /* 00000110 */
0x0c, /* 00001100 */
0x7e, /* 01111110 */
0xdb, /* 11011011 */
0xdb, /* 11011011 */
0x7e, /* 01111110 */
0x60, /* 01100000 */
0xc0, /* 11000000 */
/* 238 0xee 'î' */
0x1e, /* 00011110 */
0x30, /* 00110000 */
0x60, /* 01100000 */
0x7e, /* 01111110 */
0x60, /* 01100000 */
0x30, /* 00110000 */
0x1e, /* 00011110 */
0x00, /* 00000000 */
/* 239 0xef 'ï' */
0x00, /* 00000000 */
0x7c, /* 01111100 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0xc6, /* 11000110 */
0x00, /* 00000000 */
/* 240 0xf0 'ð' */
0x00, /* 00000000 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
0xfe, /* 11111110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 241 0xf1 'ñ' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x7e, /* 01111110 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
/* 242 0xf2 'ò' */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
/* 243 0xf3 'ó' */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x18, /* 00011000 */
0x0c, /* 00001100 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
/* 244 0xf4 'ô' */
0x0e, /* 00001110 */
0x1b, /* 00011011 */
0x1b, /* 00011011 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
/* 245 0xf5 'õ' */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0xd8, /* 11011000 */
0xd8, /* 11011000 */
0x70, /* 01110000 */
/* 246 0xf6 'ö' */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x7e, /* 01111110 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 247 0xf7 '÷' */
0x00, /* 00000000 */
0x76, /* 01110110 */
0xdc, /* 11011100 */
0x00, /* 00000000 */
0x76, /* 01110110 */
0xdc, /* 11011100 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 248 0xf8 'ø' */
0x38, /* 00111000 */
0x6c, /* 01101100 */
0x6c, /* 01101100 */
0x38, /* 00111000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 249 0xf9 'ù' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 250 0xfa 'ú' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x18, /* 00011000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 251 0xfb 'û' */
0x0f, /* 00001111 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0x0c, /* 00001100 */
0xec, /* 11101100 */
0x6c, /* 01101100 */
0x3c, /* 00111100 */
0x1c, /* 00011100 */
/* 252 0xfc 'ü' */
0x6c, /* 01101100 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x36, /* 00110110 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 253 0xfd 'ý' */
0x78, /* 01111000 */
0x0c, /* 00001100 */
0x18, /* 00011000 */
0x30, /* 00110000 */
0x7c, /* 01111100 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 254 0xfe 'þ' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x3c, /* 00111100 */
0x3c, /* 00111100 */
0x3c, /* 00111100 */
0x3c, /* 00111100 */
0x00, /* 00000000 */
0x00, /* 00000000 */
/* 255 0xff 'ÿ' */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
0x00, /* 00000000 */
};
const struct font_desc font_pearl_8x8 = {
.idx = PEARL8x8_IDX,
.name = "PEARL8x8",
.width = 8,
.height = 8,
.data = fontdata_pearl8x8,
.pref = 2,
};
| gpl-2.0 |
marcOcram/Acer-Liquid-MT-Kernel | drivers/md/dm-io.c | 98 | 11166 | /*
* Copyright (C) 2003 Sistina Software
* Copyright (C) 2006 Red Hat GmbH
*
* This file is released under the GPL.
*/
#include <linux/device-mapper.h>
#include <linux/bio.h>
#include <linux/mempool.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/dm-io.h>
struct dm_io_client {
mempool_t *pool;
struct bio_set *bios;
};
/* FIXME: can we shrink this ? */
struct io {
unsigned long error_bits;
atomic_t count;
struct task_struct *sleeper;
struct dm_io_client *client;
io_notify_fn callback;
void *context;
};
/*
* io contexts are only dynamically allocated for asynchronous
* io. Since async io is likely to be the majority of io we'll
* have the same number of io contexts as bios! (FIXME: must reduce this).
*/
static unsigned int pages_to_ios(unsigned int pages)
{
return 4 * pages; /* too many ? */
}
/*
* Create a client with mempool and bioset.
*/
struct dm_io_client *dm_io_client_create(unsigned num_pages)
{
unsigned ios = pages_to_ios(num_pages);
struct dm_io_client *client;
client = kmalloc(sizeof(*client), GFP_KERNEL);
if (!client)
return ERR_PTR(-ENOMEM);
client->pool = mempool_create_kmalloc_pool(ios, sizeof(struct io));
if (!client->pool)
goto bad;
client->bios = bioset_create(16, 0);
if (!client->bios)
goto bad;
return client;
bad:
if (client->pool)
mempool_destroy(client->pool);
kfree(client);
return ERR_PTR(-ENOMEM);
}
EXPORT_SYMBOL(dm_io_client_create);
int dm_io_client_resize(unsigned num_pages, struct dm_io_client *client)
{
return mempool_resize(client->pool, pages_to_ios(num_pages),
GFP_KERNEL);
}
EXPORT_SYMBOL(dm_io_client_resize);
void dm_io_client_destroy(struct dm_io_client *client)
{
mempool_destroy(client->pool);
bioset_free(client->bios);
kfree(client);
}
EXPORT_SYMBOL(dm_io_client_destroy);
/*-----------------------------------------------------------------
* We need to keep track of which region a bio is doing io for.
* In order to save a memory allocation we store this the last
* bvec which we know is unused (blech).
* XXX This is ugly and can OOPS with some configs... find another way.
*---------------------------------------------------------------*/
static inline void bio_set_region(struct bio *bio, unsigned region)
{
bio->bi_io_vec[bio->bi_max_vecs].bv_len = region;
}
static inline unsigned bio_get_region(struct bio *bio)
{
return bio->bi_io_vec[bio->bi_max_vecs].bv_len;
}
/*-----------------------------------------------------------------
* We need an io object to keep track of the number of bios that
* have been dispatched for a particular io.
*---------------------------------------------------------------*/
static void dec_count(struct io *io, unsigned int region, int error)
{
if (error)
set_bit(region, &io->error_bits);
if (atomic_dec_and_test(&io->count)) {
if (io->sleeper)
wake_up_process(io->sleeper);
else {
unsigned long r = io->error_bits;
io_notify_fn fn = io->callback;
void *context = io->context;
mempool_free(io, io->client->pool);
fn(r, context);
}
}
}
static void endio(struct bio *bio, int error)
{
struct io *io;
unsigned region;
if (error && bio_data_dir(bio) == READ)
zero_fill_bio(bio);
/*
* The bio destructor in bio_put() may use the io object.
*/
io = bio->bi_private;
region = bio_get_region(bio);
bio->bi_max_vecs++;
bio_put(bio);
dec_count(io, region, error);
}
/*-----------------------------------------------------------------
* These little objects provide an abstraction for getting a new
* destination page for io.
*---------------------------------------------------------------*/
struct dpages {
void (*get_page)(struct dpages *dp,
struct page **p, unsigned long *len, unsigned *offset);
void (*next_page)(struct dpages *dp);
unsigned context_u;
void *context_ptr;
};
/*
* Functions for getting the pages from a list.
*/
static void list_get_page(struct dpages *dp,
struct page **p, unsigned long *len, unsigned *offset)
{
unsigned o = dp->context_u;
struct page_list *pl = (struct page_list *) dp->context_ptr;
*p = pl->page;
*len = PAGE_SIZE - o;
*offset = o;
}
static void list_next_page(struct dpages *dp)
{
struct page_list *pl = (struct page_list *) dp->context_ptr;
dp->context_ptr = pl->next;
dp->context_u = 0;
}
static void list_dp_init(struct dpages *dp, struct page_list *pl, unsigned offset)
{
dp->get_page = list_get_page;
dp->next_page = list_next_page;
dp->context_u = offset;
dp->context_ptr = pl;
}
/*
* Functions for getting the pages from a bvec.
*/
static void bvec_get_page(struct dpages *dp,
struct page **p, unsigned long *len, unsigned *offset)
{
struct bio_vec *bvec = (struct bio_vec *) dp->context_ptr;
*p = bvec->bv_page;
*len = bvec->bv_len;
*offset = bvec->bv_offset;
}
static void bvec_next_page(struct dpages *dp)
{
struct bio_vec *bvec = (struct bio_vec *) dp->context_ptr;
dp->context_ptr = bvec + 1;
}
static void bvec_dp_init(struct dpages *dp, struct bio_vec *bvec)
{
dp->get_page = bvec_get_page;
dp->next_page = bvec_next_page;
dp->context_ptr = bvec;
}
/*
* Functions for getting the pages from a VMA.
*/
static void vm_get_page(struct dpages *dp,
struct page **p, unsigned long *len, unsigned *offset)
{
*p = vmalloc_to_page(dp->context_ptr);
*offset = dp->context_u;
*len = PAGE_SIZE - dp->context_u;
}
static void vm_next_page(struct dpages *dp)
{
dp->context_ptr += PAGE_SIZE - dp->context_u;
dp->context_u = 0;
}
static void vm_dp_init(struct dpages *dp, void *data)
{
dp->get_page = vm_get_page;
dp->next_page = vm_next_page;
dp->context_u = ((unsigned long) data) & (PAGE_SIZE - 1);
dp->context_ptr = data;
}
static void dm_bio_destructor(struct bio *bio)
{
struct io *io = bio->bi_private;
bio_free(bio, io->client->bios);
}
/*
* Functions for getting the pages from kernel memory.
*/
static void km_get_page(struct dpages *dp, struct page **p, unsigned long *len,
unsigned *offset)
{
*p = virt_to_page(dp->context_ptr);
*offset = dp->context_u;
*len = PAGE_SIZE - dp->context_u;
}
static void km_next_page(struct dpages *dp)
{
dp->context_ptr += PAGE_SIZE - dp->context_u;
dp->context_u = 0;
}
static void km_dp_init(struct dpages *dp, void *data)
{
dp->get_page = km_get_page;
dp->next_page = km_next_page;
dp->context_u = ((unsigned long) data) & (PAGE_SIZE - 1);
dp->context_ptr = data;
}
/*-----------------------------------------------------------------
* IO routines that accept a list of pages.
*---------------------------------------------------------------*/
static void do_region(int rw, unsigned region, struct dm_io_region *where,
struct dpages *dp, struct io *io)
{
struct bio *bio;
struct page *page;
unsigned long len;
unsigned offset;
unsigned num_bvecs;
sector_t remaining = where->count;
while (remaining) {
/*
* Allocate a suitably sized-bio: we add an extra
* bvec for bio_get/set_region() and decrement bi_max_vecs
* to hide it from bio_add_page().
*/
num_bvecs = dm_sector_div_up(remaining,
(PAGE_SIZE >> SECTOR_SHIFT));
num_bvecs = 1 + min_t(int, bio_get_nr_vecs(where->bdev),
num_bvecs);
if (unlikely(num_bvecs > BIO_MAX_PAGES))
num_bvecs = BIO_MAX_PAGES;
bio = bio_alloc_bioset(GFP_NOIO, num_bvecs, io->client->bios);
bio->bi_sector = where->sector + (where->count - remaining);
bio->bi_bdev = where->bdev;
bio->bi_end_io = endio;
bio->bi_private = io;
bio->bi_destructor = dm_bio_destructor;
bio->bi_max_vecs--;
bio_set_region(bio, region);
/*
* Try and add as many pages as possible.
*/
while (remaining) {
dp->get_page(dp, &page, &len, &offset);
len = min(len, to_bytes(remaining));
if (!bio_add_page(bio, page, len, offset))
break;
offset = 0;
remaining -= to_sector(len);
dp->next_page(dp);
}
atomic_inc(&io->count);
submit_bio(rw, bio);
}
}
static void dispatch_io(int rw, unsigned int num_regions,
struct dm_io_region *where, struct dpages *dp,
struct io *io, int sync)
{
int i;
struct dpages old_pages = *dp;
if (sync)
rw |= (1 << BIO_RW_SYNCIO) | (1 << BIO_RW_UNPLUG);
/*
* For multiple regions we need to be careful to rewind
* the dp object for each call to do_region.
*/
for (i = 0; i < num_regions; i++) {
*dp = old_pages;
if (where[i].count)
do_region(rw, i, where + i, dp, io);
}
/*
* Drop the extra reference that we were holding to avoid
* the io being completed too early.
*/
dec_count(io, 0, 0);
}
static int sync_io(struct dm_io_client *client, unsigned int num_regions,
struct dm_io_region *where, int rw, struct dpages *dp,
unsigned long *error_bits)
{
struct io io;
if (num_regions > 1 && (rw & RW_MASK) != WRITE) {
WARN_ON(1);
return -EIO;
}
io.error_bits = 0;
atomic_set(&io.count, 1); /* see dispatch_io() */
io.sleeper = current;
io.client = client;
dispatch_io(rw, num_regions, where, dp, &io, 1);
while (1) {
set_current_state(TASK_UNINTERRUPTIBLE);
if (!atomic_read(&io.count) || signal_pending(current))
break;
io_schedule();
}
set_current_state(TASK_RUNNING);
if (atomic_read(&io.count))
return -EINTR;
if (error_bits)
*error_bits = io.error_bits;
return io.error_bits ? -EIO : 0;
}
static int async_io(struct dm_io_client *client, unsigned int num_regions,
struct dm_io_region *where, int rw, struct dpages *dp,
io_notify_fn fn, void *context)
{
struct io *io;
if (num_regions > 1 && (rw & RW_MASK) != WRITE) {
WARN_ON(1);
fn(1, context);
return -EIO;
}
io = mempool_alloc(client->pool, GFP_NOIO);
io->error_bits = 0;
atomic_set(&io->count, 1); /* see dispatch_io() */
io->sleeper = NULL;
io->client = client;
io->callback = fn;
io->context = context;
dispatch_io(rw, num_regions, where, dp, io, 0);
return 0;
}
static int dp_init(struct dm_io_request *io_req, struct dpages *dp)
{
/* Set up dpages based on memory type */
switch (io_req->mem.type) {
case DM_IO_PAGE_LIST:
list_dp_init(dp, io_req->mem.ptr.pl, io_req->mem.offset);
break;
case DM_IO_BVEC:
bvec_dp_init(dp, io_req->mem.ptr.bvec);
break;
case DM_IO_VMA:
vm_dp_init(dp, io_req->mem.ptr.vma);
break;
case DM_IO_KMEM:
km_dp_init(dp, io_req->mem.ptr.addr);
break;
default:
return -EINVAL;
}
return 0;
}
/*
* New collapsed (a)synchronous interface.
*
* If the IO is asynchronous (i.e. it has notify.fn), you must either unplug
* the queue with blk_unplug() some time later or set the BIO_RW_SYNC bit in
* io_req->bi_rw. If you fail to do one of these, the IO will be submitted to
* the disk after q->unplug_delay, which defaults to 3ms in blk-settings.c.
*/
int dm_io(struct dm_io_request *io_req, unsigned num_regions,
struct dm_io_region *where, unsigned long *sync_error_bits)
{
int r;
struct dpages dp;
r = dp_init(io_req, &dp);
if (r)
return r;
if (!io_req->notify.fn)
return sync_io(io_req->client, num_regions, where,
io_req->bi_rw, &dp, sync_error_bits);
return async_io(io_req->client, num_regions, where, io_req->bi_rw,
&dp, io_req->notify.fn, io_req->notify.context);
}
EXPORT_SYMBOL(dm_io);
| gpl-2.0 |
robclark/kernel-omap4 | drivers/spi/spi-bfin-sport.c | 98 | 23534 | /*
* SPI bus via the Blackfin SPORT peripheral
*
* Enter bugs at http://blackfin.uclinux.org/
*
* Copyright 2009-2011 Analog Devices Inc.
*
* Licensed under the GPL-2 or later.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/gpio.h>
#include <linux/io.h>
#include <linux/ioport.h>
#include <linux/irq.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/spi/spi.h>
#include <linux/workqueue.h>
#include <asm/portmux.h>
#include <asm/bfin5xx_spi.h>
#include <asm/blackfin.h>
#include <asm/bfin_sport.h>
#include <asm/cacheflush.h>
#define DRV_NAME "bfin-sport-spi"
#define DRV_DESC "SPI bus via the Blackfin SPORT"
MODULE_AUTHOR("Cliff Cai");
MODULE_DESCRIPTION(DRV_DESC);
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:bfin-sport-spi");
enum bfin_sport_spi_state {
START_STATE,
RUNNING_STATE,
DONE_STATE,
ERROR_STATE,
};
struct bfin_sport_spi_master_data;
struct bfin_sport_transfer_ops {
void (*write) (struct bfin_sport_spi_master_data *);
void (*read) (struct bfin_sport_spi_master_data *);
void (*duplex) (struct bfin_sport_spi_master_data *);
};
struct bfin_sport_spi_master_data {
/* Driver model hookup */
struct device *dev;
/* SPI framework hookup */
struct spi_master *master;
/* Regs base of SPI controller */
struct sport_register __iomem *regs;
int err_irq;
/* Pin request list */
u16 *pin_req;
/* Driver message queue */
struct workqueue_struct *workqueue;
struct work_struct pump_messages;
spinlock_t lock;
struct list_head queue;
int busy;
bool run;
/* Message Transfer pump */
struct tasklet_struct pump_transfers;
/* Current message transfer state info */
enum bfin_sport_spi_state state;
struct spi_message *cur_msg;
struct spi_transfer *cur_transfer;
struct bfin_sport_spi_slave_data *cur_chip;
union {
void *tx;
u8 *tx8;
u16 *tx16;
};
void *tx_end;
union {
void *rx;
u8 *rx8;
u16 *rx16;
};
void *rx_end;
int cs_change;
struct bfin_sport_transfer_ops *ops;
};
struct bfin_sport_spi_slave_data {
u16 ctl_reg;
u16 baud;
u16 cs_chg_udelay; /* Some devices require > 255usec delay */
u32 cs_gpio;
u16 idle_tx_val;
struct bfin_sport_transfer_ops *ops;
};
static void
bfin_sport_spi_enable(struct bfin_sport_spi_master_data *drv_data)
{
bfin_write_or(&drv_data->regs->tcr1, TSPEN);
bfin_write_or(&drv_data->regs->rcr1, TSPEN);
SSYNC();
}
static void
bfin_sport_spi_disable(struct bfin_sport_spi_master_data *drv_data)
{
bfin_write_and(&drv_data->regs->tcr1, ~TSPEN);
bfin_write_and(&drv_data->regs->rcr1, ~TSPEN);
SSYNC();
}
/* Caculate the SPI_BAUD register value based on input HZ */
static u16
bfin_sport_hz_to_spi_baud(u32 speed_hz)
{
u_long clk, sclk = get_sclk();
int div = (sclk / (2 * speed_hz)) - 1;
if (div < 0)
div = 0;
clk = sclk / (2 * (div + 1));
if (clk > speed_hz)
div++;
return div;
}
/* Chip select operation functions for cs_change flag */
static void
bfin_sport_spi_cs_active(struct bfin_sport_spi_slave_data *chip)
{
gpio_direction_output(chip->cs_gpio, 0);
}
static void
bfin_sport_spi_cs_deactive(struct bfin_sport_spi_slave_data *chip)
{
gpio_direction_output(chip->cs_gpio, 1);
/* Move delay here for consistency */
if (chip->cs_chg_udelay)
udelay(chip->cs_chg_udelay);
}
static void
bfin_sport_spi_stat_poll_complete(struct bfin_sport_spi_master_data *drv_data)
{
unsigned long timeout = jiffies + HZ;
while (!(bfin_read(&drv_data->regs->stat) & RXNE)) {
if (!time_before(jiffies, timeout))
break;
}
}
static void
bfin_sport_spi_u8_writer(struct bfin_sport_spi_master_data *drv_data)
{
u16 dummy;
while (drv_data->tx < drv_data->tx_end) {
bfin_write(&drv_data->regs->tx16, *drv_data->tx8++);
bfin_sport_spi_stat_poll_complete(drv_data);
dummy = bfin_read(&drv_data->regs->rx16);
}
}
static void
bfin_sport_spi_u8_reader(struct bfin_sport_spi_master_data *drv_data)
{
u16 tx_val = drv_data->cur_chip->idle_tx_val;
while (drv_data->rx < drv_data->rx_end) {
bfin_write(&drv_data->regs->tx16, tx_val);
bfin_sport_spi_stat_poll_complete(drv_data);
*drv_data->rx8++ = bfin_read(&drv_data->regs->rx16);
}
}
static void
bfin_sport_spi_u8_duplex(struct bfin_sport_spi_master_data *drv_data)
{
while (drv_data->rx < drv_data->rx_end) {
bfin_write(&drv_data->regs->tx16, *drv_data->tx8++);
bfin_sport_spi_stat_poll_complete(drv_data);
*drv_data->rx8++ = bfin_read(&drv_data->regs->rx16);
}
}
static struct bfin_sport_transfer_ops bfin_sport_transfer_ops_u8 = {
.write = bfin_sport_spi_u8_writer,
.read = bfin_sport_spi_u8_reader,
.duplex = bfin_sport_spi_u8_duplex,
};
static void
bfin_sport_spi_u16_writer(struct bfin_sport_spi_master_data *drv_data)
{
u16 dummy;
while (drv_data->tx < drv_data->tx_end) {
bfin_write(&drv_data->regs->tx16, *drv_data->tx16++);
bfin_sport_spi_stat_poll_complete(drv_data);
dummy = bfin_read(&drv_data->regs->rx16);
}
}
static void
bfin_sport_spi_u16_reader(struct bfin_sport_spi_master_data *drv_data)
{
u16 tx_val = drv_data->cur_chip->idle_tx_val;
while (drv_data->rx < drv_data->rx_end) {
bfin_write(&drv_data->regs->tx16, tx_val);
bfin_sport_spi_stat_poll_complete(drv_data);
*drv_data->rx16++ = bfin_read(&drv_data->regs->rx16);
}
}
static void
bfin_sport_spi_u16_duplex(struct bfin_sport_spi_master_data *drv_data)
{
while (drv_data->rx < drv_data->rx_end) {
bfin_write(&drv_data->regs->tx16, *drv_data->tx16++);
bfin_sport_spi_stat_poll_complete(drv_data);
*drv_data->rx16++ = bfin_read(&drv_data->regs->rx16);
}
}
static struct bfin_sport_transfer_ops bfin_sport_transfer_ops_u16 = {
.write = bfin_sport_spi_u16_writer,
.read = bfin_sport_spi_u16_reader,
.duplex = bfin_sport_spi_u16_duplex,
};
/* stop controller and re-config current chip */
static void
bfin_sport_spi_restore_state(struct bfin_sport_spi_master_data *drv_data)
{
struct bfin_sport_spi_slave_data *chip = drv_data->cur_chip;
bfin_sport_spi_disable(drv_data);
dev_dbg(drv_data->dev, "restoring spi ctl state\n");
bfin_write(&drv_data->regs->tcr1, chip->ctl_reg);
bfin_write(&drv_data->regs->tclkdiv, chip->baud);
SSYNC();
bfin_write(&drv_data->regs->rcr1, chip->ctl_reg & ~(ITCLK | ITFS));
SSYNC();
bfin_sport_spi_cs_active(chip);
}
/* test if there is more transfer to be done */
static enum bfin_sport_spi_state
bfin_sport_spi_next_transfer(struct bfin_sport_spi_master_data *drv_data)
{
struct spi_message *msg = drv_data->cur_msg;
struct spi_transfer *trans = drv_data->cur_transfer;
/* Move to next transfer */
if (trans->transfer_list.next != &msg->transfers) {
drv_data->cur_transfer =
list_entry(trans->transfer_list.next,
struct spi_transfer, transfer_list);
return RUNNING_STATE;
}
return DONE_STATE;
}
/*
* caller already set message->status;
* dma and pio irqs are blocked give finished message back
*/
static void
bfin_sport_spi_giveback(struct bfin_sport_spi_master_data *drv_data)
{
struct bfin_sport_spi_slave_data *chip = drv_data->cur_chip;
unsigned long flags;
struct spi_message *msg;
spin_lock_irqsave(&drv_data->lock, flags);
msg = drv_data->cur_msg;
drv_data->state = START_STATE;
drv_data->cur_msg = NULL;
drv_data->cur_transfer = NULL;
drv_data->cur_chip = NULL;
queue_work(drv_data->workqueue, &drv_data->pump_messages);
spin_unlock_irqrestore(&drv_data->lock, flags);
if (!drv_data->cs_change)
bfin_sport_spi_cs_deactive(chip);
if (msg->complete)
msg->complete(msg->context);
}
static irqreturn_t
sport_err_handler(int irq, void *dev_id)
{
struct bfin_sport_spi_master_data *drv_data = dev_id;
u16 status;
dev_dbg(drv_data->dev, "%s enter\n", __func__);
status = bfin_read(&drv_data->regs->stat) & (TOVF | TUVF | ROVF | RUVF);
if (status) {
bfin_write(&drv_data->regs->stat, status);
SSYNC();
bfin_sport_spi_disable(drv_data);
dev_err(drv_data->dev, "status error:%s%s%s%s\n",
status & TOVF ? " TOVF" : "",
status & TUVF ? " TUVF" : "",
status & ROVF ? " ROVF" : "",
status & RUVF ? " RUVF" : "");
}
return IRQ_HANDLED;
}
static void
bfin_sport_spi_pump_transfers(unsigned long data)
{
struct bfin_sport_spi_master_data *drv_data = (void *)data;
struct spi_message *message = NULL;
struct spi_transfer *transfer = NULL;
struct spi_transfer *previous = NULL;
struct bfin_sport_spi_slave_data *chip = NULL;
unsigned int bits_per_word;
u32 tranf_success = 1;
u32 transfer_speed;
u8 full_duplex = 0;
/* Get current state information */
message = drv_data->cur_msg;
transfer = drv_data->cur_transfer;
chip = drv_data->cur_chip;
if (transfer->speed_hz)
transfer_speed = bfin_sport_hz_to_spi_baud(transfer->speed_hz);
else
transfer_speed = chip->baud;
bfin_write(&drv_data->regs->tclkdiv, transfer_speed);
SSYNC();
/*
* if msg is error or done, report it back using complete() callback
*/
/* Handle for abort */
if (drv_data->state == ERROR_STATE) {
dev_dbg(drv_data->dev, "transfer: we've hit an error\n");
message->status = -EIO;
bfin_sport_spi_giveback(drv_data);
return;
}
/* Handle end of message */
if (drv_data->state == DONE_STATE) {
dev_dbg(drv_data->dev, "transfer: all done!\n");
message->status = 0;
bfin_sport_spi_giveback(drv_data);
return;
}
/* Delay if requested at end of transfer */
if (drv_data->state == RUNNING_STATE) {
dev_dbg(drv_data->dev, "transfer: still running ...\n");
previous = list_entry(transfer->transfer_list.prev,
struct spi_transfer, transfer_list);
if (previous->delay_usecs)
udelay(previous->delay_usecs);
}
if (transfer->len == 0) {
/* Move to next transfer of this msg */
drv_data->state = bfin_sport_spi_next_transfer(drv_data);
/* Schedule next transfer tasklet */
tasklet_schedule(&drv_data->pump_transfers);
}
if (transfer->tx_buf != NULL) {
drv_data->tx = (void *)transfer->tx_buf;
drv_data->tx_end = drv_data->tx + transfer->len;
dev_dbg(drv_data->dev, "tx_buf is %p, tx_end is %p\n",
transfer->tx_buf, drv_data->tx_end);
} else
drv_data->tx = NULL;
if (transfer->rx_buf != NULL) {
full_duplex = transfer->tx_buf != NULL;
drv_data->rx = transfer->rx_buf;
drv_data->rx_end = drv_data->rx + transfer->len;
dev_dbg(drv_data->dev, "rx_buf is %p, rx_end is %p\n",
transfer->rx_buf, drv_data->rx_end);
} else
drv_data->rx = NULL;
drv_data->cs_change = transfer->cs_change;
/* Bits per word setup */
bits_per_word = transfer->bits_per_word ? :
message->spi->bits_per_word ? : 8;
if (bits_per_word % 16 == 0)
drv_data->ops = &bfin_sport_transfer_ops_u16;
else
drv_data->ops = &bfin_sport_transfer_ops_u8;
bfin_write(&drv_data->regs->tcr2, bits_per_word - 1);
bfin_write(&drv_data->regs->tfsdiv, bits_per_word - 1);
bfin_write(&drv_data->regs->rcr2, bits_per_word - 1);
drv_data->state = RUNNING_STATE;
if (drv_data->cs_change)
bfin_sport_spi_cs_active(chip);
dev_dbg(drv_data->dev,
"now pumping a transfer: width is %d, len is %d\n",
bits_per_word, transfer->len);
/* PIO mode write then read */
dev_dbg(drv_data->dev, "doing IO transfer\n");
bfin_sport_spi_enable(drv_data);
if (full_duplex) {
/* full duplex mode */
BUG_ON((drv_data->tx_end - drv_data->tx) !=
(drv_data->rx_end - drv_data->rx));
drv_data->ops->duplex(drv_data);
if (drv_data->tx != drv_data->tx_end)
tranf_success = 0;
} else if (drv_data->tx != NULL) {
/* write only half duplex */
drv_data->ops->write(drv_data);
if (drv_data->tx != drv_data->tx_end)
tranf_success = 0;
} else if (drv_data->rx != NULL) {
/* read only half duplex */
drv_data->ops->read(drv_data);
if (drv_data->rx != drv_data->rx_end)
tranf_success = 0;
}
bfin_sport_spi_disable(drv_data);
if (!tranf_success) {
dev_dbg(drv_data->dev, "IO write error!\n");
drv_data->state = ERROR_STATE;
} else {
/* Update total byte transferred */
message->actual_length += transfer->len;
/* Move to next transfer of this msg */
drv_data->state = bfin_sport_spi_next_transfer(drv_data);
if (drv_data->cs_change)
bfin_sport_spi_cs_deactive(chip);
}
/* Schedule next transfer tasklet */
tasklet_schedule(&drv_data->pump_transfers);
}
/* pop a msg from queue and kick off real transfer */
static void
bfin_sport_spi_pump_messages(struct work_struct *work)
{
struct bfin_sport_spi_master_data *drv_data;
unsigned long flags;
struct spi_message *next_msg;
drv_data = container_of(work, struct bfin_sport_spi_master_data, pump_messages);
/* Lock queue and check for queue work */
spin_lock_irqsave(&drv_data->lock, flags);
if (list_empty(&drv_data->queue) || !drv_data->run) {
/* pumper kicked off but no work to do */
drv_data->busy = 0;
spin_unlock_irqrestore(&drv_data->lock, flags);
return;
}
/* Make sure we are not already running a message */
if (drv_data->cur_msg) {
spin_unlock_irqrestore(&drv_data->lock, flags);
return;
}
/* Extract head of queue */
next_msg = list_entry(drv_data->queue.next,
struct spi_message, queue);
drv_data->cur_msg = next_msg;
/* Setup the SSP using the per chip configuration */
drv_data->cur_chip = spi_get_ctldata(drv_data->cur_msg->spi);
list_del_init(&drv_data->cur_msg->queue);
/* Initialize message state */
drv_data->cur_msg->state = START_STATE;
drv_data->cur_transfer = list_entry(drv_data->cur_msg->transfers.next,
struct spi_transfer, transfer_list);
bfin_sport_spi_restore_state(drv_data);
dev_dbg(drv_data->dev, "got a message to pump, "
"state is set to: baud %d, cs_gpio %i, ctl 0x%x\n",
drv_data->cur_chip->baud, drv_data->cur_chip->cs_gpio,
drv_data->cur_chip->ctl_reg);
dev_dbg(drv_data->dev,
"the first transfer len is %d\n",
drv_data->cur_transfer->len);
/* Mark as busy and launch transfers */
tasklet_schedule(&drv_data->pump_transfers);
drv_data->busy = 1;
spin_unlock_irqrestore(&drv_data->lock, flags);
}
/*
* got a msg to transfer, queue it in drv_data->queue.
* And kick off message pumper
*/
static int
bfin_sport_spi_transfer(struct spi_device *spi, struct spi_message *msg)
{
struct bfin_sport_spi_master_data *drv_data = spi_master_get_devdata(spi->master);
unsigned long flags;
spin_lock_irqsave(&drv_data->lock, flags);
if (!drv_data->run) {
spin_unlock_irqrestore(&drv_data->lock, flags);
return -ESHUTDOWN;
}
msg->actual_length = 0;
msg->status = -EINPROGRESS;
msg->state = START_STATE;
dev_dbg(&spi->dev, "adding an msg in transfer()\n");
list_add_tail(&msg->queue, &drv_data->queue);
if (drv_data->run && !drv_data->busy)
queue_work(drv_data->workqueue, &drv_data->pump_messages);
spin_unlock_irqrestore(&drv_data->lock, flags);
return 0;
}
/* Called every time common spi devices change state */
static int
bfin_sport_spi_setup(struct spi_device *spi)
{
struct bfin_sport_spi_slave_data *chip, *first = NULL;
int ret;
/* Only alloc (or use chip_info) on first setup */
chip = spi_get_ctldata(spi);
if (chip == NULL) {
struct bfin5xx_spi_chip *chip_info;
chip = first = kzalloc(sizeof(*chip), GFP_KERNEL);
if (!chip)
return -ENOMEM;
/* platform chip_info isn't required */
chip_info = spi->controller_data;
if (chip_info) {
/*
* DITFS and TDTYPE are only thing we don't set, but
* they probably shouldn't be changed by people.
*/
if (chip_info->ctl_reg || chip_info->enable_dma) {
ret = -EINVAL;
dev_err(&spi->dev, "don't set ctl_reg/enable_dma fields");
goto error;
}
chip->cs_chg_udelay = chip_info->cs_chg_udelay;
chip->idle_tx_val = chip_info->idle_tx_val;
}
}
if (spi->bits_per_word % 8) {
dev_err(&spi->dev, "%d bits_per_word is not supported\n",
spi->bits_per_word);
ret = -EINVAL;
goto error;
}
/* translate common spi framework into our register
* following configure contents are same for tx and rx.
*/
if (spi->mode & SPI_CPHA)
chip->ctl_reg &= ~TCKFE;
else
chip->ctl_reg |= TCKFE;
if (spi->mode & SPI_LSB_FIRST)
chip->ctl_reg |= TLSBIT;
else
chip->ctl_reg &= ~TLSBIT;
/* Sport in master mode */
chip->ctl_reg |= ITCLK | ITFS | TFSR | LATFS | LTFS;
chip->baud = bfin_sport_hz_to_spi_baud(spi->max_speed_hz);
chip->cs_gpio = spi->chip_select;
ret = gpio_request(chip->cs_gpio, spi->modalias);
if (ret)
goto error;
dev_dbg(&spi->dev, "setup spi chip %s, width is %d\n",
spi->modalias, spi->bits_per_word);
dev_dbg(&spi->dev, "ctl_reg is 0x%x, GPIO is %i\n",
chip->ctl_reg, spi->chip_select);
spi_set_ctldata(spi, chip);
bfin_sport_spi_cs_deactive(chip);
return ret;
error:
kfree(first);
return ret;
}
/*
* callback for spi framework.
* clean driver specific data
*/
static void
bfin_sport_spi_cleanup(struct spi_device *spi)
{
struct bfin_sport_spi_slave_data *chip = spi_get_ctldata(spi);
if (!chip)
return;
gpio_free(chip->cs_gpio);
kfree(chip);
}
static int
bfin_sport_spi_init_queue(struct bfin_sport_spi_master_data *drv_data)
{
INIT_LIST_HEAD(&drv_data->queue);
spin_lock_init(&drv_data->lock);
drv_data->run = false;
drv_data->busy = 0;
/* init transfer tasklet */
tasklet_init(&drv_data->pump_transfers,
bfin_sport_spi_pump_transfers, (unsigned long)drv_data);
/* init messages workqueue */
INIT_WORK(&drv_data->pump_messages, bfin_sport_spi_pump_messages);
drv_data->workqueue =
create_singlethread_workqueue(dev_name(drv_data->master->dev.parent));
if (drv_data->workqueue == NULL)
return -EBUSY;
return 0;
}
static int
bfin_sport_spi_start_queue(struct bfin_sport_spi_master_data *drv_data)
{
unsigned long flags;
spin_lock_irqsave(&drv_data->lock, flags);
if (drv_data->run || drv_data->busy) {
spin_unlock_irqrestore(&drv_data->lock, flags);
return -EBUSY;
}
drv_data->run = true;
drv_data->cur_msg = NULL;
drv_data->cur_transfer = NULL;
drv_data->cur_chip = NULL;
spin_unlock_irqrestore(&drv_data->lock, flags);
queue_work(drv_data->workqueue, &drv_data->pump_messages);
return 0;
}
static inline int
bfin_sport_spi_stop_queue(struct bfin_sport_spi_master_data *drv_data)
{
unsigned long flags;
unsigned limit = 500;
int status = 0;
spin_lock_irqsave(&drv_data->lock, flags);
/*
* This is a bit lame, but is optimized for the common execution path.
* A wait_queue on the drv_data->busy could be used, but then the common
* execution path (pump_messages) would be required to call wake_up or
* friends on every SPI message. Do this instead
*/
drv_data->run = false;
while (!list_empty(&drv_data->queue) && drv_data->busy && limit--) {
spin_unlock_irqrestore(&drv_data->lock, flags);
msleep(10);
spin_lock_irqsave(&drv_data->lock, flags);
}
if (!list_empty(&drv_data->queue) || drv_data->busy)
status = -EBUSY;
spin_unlock_irqrestore(&drv_data->lock, flags);
return status;
}
static inline int
bfin_sport_spi_destroy_queue(struct bfin_sport_spi_master_data *drv_data)
{
int status;
status = bfin_sport_spi_stop_queue(drv_data);
if (status)
return status;
destroy_workqueue(drv_data->workqueue);
return 0;
}
static int bfin_sport_spi_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct bfin5xx_spi_master *platform_info;
struct spi_master *master;
struct resource *res, *ires;
struct bfin_sport_spi_master_data *drv_data;
int status;
platform_info = dev->platform_data;
/* Allocate master with space for drv_data */
master = spi_alloc_master(dev, sizeof(*master) + 16);
if (!master) {
dev_err(dev, "cannot alloc spi_master\n");
return -ENOMEM;
}
drv_data = spi_master_get_devdata(master);
drv_data->master = master;
drv_data->dev = dev;
drv_data->pin_req = platform_info->pin_req;
master->mode_bits = SPI_CPOL | SPI_CPHA | SPI_LSB_FIRST;
master->bus_num = pdev->id;
master->num_chipselect = platform_info->num_chipselect;
master->cleanup = bfin_sport_spi_cleanup;
master->setup = bfin_sport_spi_setup;
master->transfer = bfin_sport_spi_transfer;
/* Find and map our resources */
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (res == NULL) {
dev_err(dev, "cannot get IORESOURCE_MEM\n");
status = -ENOENT;
goto out_error_get_res;
}
drv_data->regs = ioremap(res->start, resource_size(res));
if (drv_data->regs == NULL) {
dev_err(dev, "cannot map registers\n");
status = -ENXIO;
goto out_error_ioremap;
}
ires = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (!ires) {
dev_err(dev, "cannot get IORESOURCE_IRQ\n");
status = -ENODEV;
goto out_error_get_ires;
}
drv_data->err_irq = ires->start;
/* Initial and start queue */
status = bfin_sport_spi_init_queue(drv_data);
if (status) {
dev_err(dev, "problem initializing queue\n");
goto out_error_queue_alloc;
}
status = bfin_sport_spi_start_queue(drv_data);
if (status) {
dev_err(dev, "problem starting queue\n");
goto out_error_queue_alloc;
}
status = request_irq(drv_data->err_irq, sport_err_handler,
0, "sport_spi_err", drv_data);
if (status) {
dev_err(dev, "unable to request sport err irq\n");
goto out_error_irq;
}
status = peripheral_request_list(drv_data->pin_req, DRV_NAME);
if (status) {
dev_err(dev, "requesting peripherals failed\n");
goto out_error_peripheral;
}
/* Register with the SPI framework */
platform_set_drvdata(pdev, drv_data);
status = spi_register_master(master);
if (status) {
dev_err(dev, "problem registering spi master\n");
goto out_error_master;
}
dev_info(dev, "%s, regs_base@%p\n", DRV_DESC, drv_data->regs);
return 0;
out_error_master:
peripheral_free_list(drv_data->pin_req);
out_error_peripheral:
free_irq(drv_data->err_irq, drv_data);
out_error_irq:
out_error_queue_alloc:
bfin_sport_spi_destroy_queue(drv_data);
out_error_get_ires:
iounmap(drv_data->regs);
out_error_ioremap:
out_error_get_res:
spi_master_put(master);
return status;
}
/* stop hardware and remove the driver */
static int bfin_sport_spi_remove(struct platform_device *pdev)
{
struct bfin_sport_spi_master_data *drv_data = platform_get_drvdata(pdev);
int status = 0;
if (!drv_data)
return 0;
/* Remove the queue */
status = bfin_sport_spi_destroy_queue(drv_data);
if (status)
return status;
/* Disable the SSP at the peripheral and SOC level */
bfin_sport_spi_disable(drv_data);
/* Disconnect from the SPI framework */
spi_unregister_master(drv_data->master);
peripheral_free_list(drv_data->pin_req);
/* Prevent double remove */
platform_set_drvdata(pdev, NULL);
return 0;
}
#ifdef CONFIG_PM
static int
bfin_sport_spi_suspend(struct platform_device *pdev, pm_message_t state)
{
struct bfin_sport_spi_master_data *drv_data = platform_get_drvdata(pdev);
int status;
status = bfin_sport_spi_stop_queue(drv_data);
if (status)
return status;
/* stop hardware */
bfin_sport_spi_disable(drv_data);
return status;
}
static int
bfin_sport_spi_resume(struct platform_device *pdev)
{
struct bfin_sport_spi_master_data *drv_data = platform_get_drvdata(pdev);
int status;
/* Enable the SPI interface */
bfin_sport_spi_enable(drv_data);
/* Start the queue running */
status = bfin_sport_spi_start_queue(drv_data);
if (status)
dev_err(drv_data->dev, "problem resuming queue\n");
return status;
}
#else
# define bfin_sport_spi_suspend NULL
# define bfin_sport_spi_resume NULL
#endif
static struct platform_driver bfin_sport_spi_driver = {
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
},
.probe = bfin_sport_spi_probe,
.remove = bfin_sport_spi_remove,
.suspend = bfin_sport_spi_suspend,
.resume = bfin_sport_spi_resume,
};
module_platform_driver(bfin_sport_spi_driver);
| gpl-2.0 |
aospan/linux-stable-netup-universal-dvb-1.4 | arch/x86/mm/pgtable.c | 98 | 15423 | #include <linux/mm.h>
#include <linux/gfp.h>
#include <asm/pgalloc.h>
#include <asm/pgtable.h>
#include <asm/tlb.h>
#include <asm/fixmap.h>
#include <asm/mtrr.h>
#define PGALLOC_GFP GFP_KERNEL | __GFP_NOTRACK | __GFP_REPEAT | __GFP_ZERO
#ifdef CONFIG_HIGHPTE
#define PGALLOC_USER_GFP __GFP_HIGHMEM
#else
#define PGALLOC_USER_GFP 0
#endif
gfp_t __userpte_alloc_gfp = PGALLOC_GFP | PGALLOC_USER_GFP;
pte_t *pte_alloc_one_kernel(struct mm_struct *mm, unsigned long address)
{
return (pte_t *)__get_free_page(PGALLOC_GFP);
}
pgtable_t pte_alloc_one(struct mm_struct *mm, unsigned long address)
{
struct page *pte;
pte = alloc_pages(__userpte_alloc_gfp, 0);
if (!pte)
return NULL;
if (!pgtable_page_ctor(pte)) {
__free_page(pte);
return NULL;
}
return pte;
}
static int __init setup_userpte(char *arg)
{
if (!arg)
return -EINVAL;
/*
* "userpte=nohigh" disables allocation of user pagetables in
* high memory.
*/
if (strcmp(arg, "nohigh") == 0)
__userpte_alloc_gfp &= ~__GFP_HIGHMEM;
else
return -EINVAL;
return 0;
}
early_param("userpte", setup_userpte);
void ___pte_free_tlb(struct mmu_gather *tlb, struct page *pte)
{
pgtable_page_dtor(pte);
paravirt_release_pte(page_to_pfn(pte));
tlb_remove_page(tlb, pte);
}
#if CONFIG_PGTABLE_LEVELS > 2
void ___pmd_free_tlb(struct mmu_gather *tlb, pmd_t *pmd)
{
struct page *page = virt_to_page(pmd);
paravirt_release_pmd(__pa(pmd) >> PAGE_SHIFT);
/*
* NOTE! For PAE, any changes to the top page-directory-pointer-table
* entries need a full cr3 reload to flush.
*/
#ifdef CONFIG_X86_PAE
tlb->need_flush_all = 1;
#endif
pgtable_pmd_page_dtor(page);
tlb_remove_page(tlb, page);
}
#if CONFIG_PGTABLE_LEVELS > 3
void ___pud_free_tlb(struct mmu_gather *tlb, pud_t *pud)
{
paravirt_release_pud(__pa(pud) >> PAGE_SHIFT);
tlb_remove_page(tlb, virt_to_page(pud));
}
#endif /* CONFIG_PGTABLE_LEVELS > 3 */
#endif /* CONFIG_PGTABLE_LEVELS > 2 */
static inline void pgd_list_add(pgd_t *pgd)
{
struct page *page = virt_to_page(pgd);
list_add(&page->lru, &pgd_list);
}
static inline void pgd_list_del(pgd_t *pgd)
{
struct page *page = virt_to_page(pgd);
list_del(&page->lru);
}
#define UNSHARED_PTRS_PER_PGD \
(SHARED_KERNEL_PMD ? KERNEL_PGD_BOUNDARY : PTRS_PER_PGD)
static void pgd_set_mm(pgd_t *pgd, struct mm_struct *mm)
{
BUILD_BUG_ON(sizeof(virt_to_page(pgd)->index) < sizeof(mm));
virt_to_page(pgd)->index = (pgoff_t)mm;
}
struct mm_struct *pgd_page_get_mm(struct page *page)
{
return (struct mm_struct *)page->index;
}
static void pgd_ctor(struct mm_struct *mm, pgd_t *pgd)
{
/* If the pgd points to a shared pagetable level (either the
ptes in non-PAE, or shared PMD in PAE), then just copy the
references from swapper_pg_dir. */
if (CONFIG_PGTABLE_LEVELS == 2 ||
(CONFIG_PGTABLE_LEVELS == 3 && SHARED_KERNEL_PMD) ||
CONFIG_PGTABLE_LEVELS == 4) {
clone_pgd_range(pgd + KERNEL_PGD_BOUNDARY,
swapper_pg_dir + KERNEL_PGD_BOUNDARY,
KERNEL_PGD_PTRS);
}
/* list required to sync kernel mapping updates */
if (!SHARED_KERNEL_PMD) {
pgd_set_mm(pgd, mm);
pgd_list_add(pgd);
}
}
static void pgd_dtor(pgd_t *pgd)
{
if (SHARED_KERNEL_PMD)
return;
spin_lock(&pgd_lock);
pgd_list_del(pgd);
spin_unlock(&pgd_lock);
}
/*
* List of all pgd's needed for non-PAE so it can invalidate entries
* in both cached and uncached pgd's; not needed for PAE since the
* kernel pmd is shared. If PAE were not to share the pmd a similar
* tactic would be needed. This is essentially codepath-based locking
* against pageattr.c; it is the unique case in which a valid change
* of kernel pagetables can't be lazily synchronized by vmalloc faults.
* vmalloc faults work because attached pagetables are never freed.
* -- nyc
*/
#ifdef CONFIG_X86_PAE
/*
* In PAE mode, we need to do a cr3 reload (=tlb flush) when
* updating the top-level pagetable entries to guarantee the
* processor notices the update. Since this is expensive, and
* all 4 top-level entries are used almost immediately in a
* new process's life, we just pre-populate them here.
*
* Also, if we're in a paravirt environment where the kernel pmd is
* not shared between pagetables (!SHARED_KERNEL_PMDS), we allocate
* and initialize the kernel pmds here.
*/
#define PREALLOCATED_PMDS UNSHARED_PTRS_PER_PGD
void pud_populate(struct mm_struct *mm, pud_t *pudp, pmd_t *pmd)
{
paravirt_alloc_pmd(mm, __pa(pmd) >> PAGE_SHIFT);
/* Note: almost everything apart from _PAGE_PRESENT is
reserved at the pmd (PDPT) level. */
set_pud(pudp, __pud(__pa(pmd) | _PAGE_PRESENT));
/*
* According to Intel App note "TLBs, Paging-Structure Caches,
* and Their Invalidation", April 2007, document 317080-001,
* section 8.1: in PAE mode we explicitly have to flush the
* TLB via cr3 if the top-level pgd is changed...
*/
flush_tlb_mm(mm);
}
#else /* !CONFIG_X86_PAE */
/* No need to prepopulate any pagetable entries in non-PAE modes. */
#define PREALLOCATED_PMDS 0
#endif /* CONFIG_X86_PAE */
static void free_pmds(struct mm_struct *mm, pmd_t *pmds[])
{
int i;
for(i = 0; i < PREALLOCATED_PMDS; i++)
if (pmds[i]) {
pgtable_pmd_page_dtor(virt_to_page(pmds[i]));
free_page((unsigned long)pmds[i]);
mm_dec_nr_pmds(mm);
}
}
static int preallocate_pmds(struct mm_struct *mm, pmd_t *pmds[])
{
int i;
bool failed = false;
for(i = 0; i < PREALLOCATED_PMDS; i++) {
pmd_t *pmd = (pmd_t *)__get_free_page(PGALLOC_GFP);
if (!pmd)
failed = true;
if (pmd && !pgtable_pmd_page_ctor(virt_to_page(pmd))) {
free_page((unsigned long)pmd);
pmd = NULL;
failed = true;
}
if (pmd)
mm_inc_nr_pmds(mm);
pmds[i] = pmd;
}
if (failed) {
free_pmds(mm, pmds);
return -ENOMEM;
}
return 0;
}
/*
* Mop up any pmd pages which may still be attached to the pgd.
* Normally they will be freed by munmap/exit_mmap, but any pmd we
* preallocate which never got a corresponding vma will need to be
* freed manually.
*/
static void pgd_mop_up_pmds(struct mm_struct *mm, pgd_t *pgdp)
{
int i;
for(i = 0; i < PREALLOCATED_PMDS; i++) {
pgd_t pgd = pgdp[i];
if (pgd_val(pgd) != 0) {
pmd_t *pmd = (pmd_t *)pgd_page_vaddr(pgd);
pgdp[i] = native_make_pgd(0);
paravirt_release_pmd(pgd_val(pgd) >> PAGE_SHIFT);
pmd_free(mm, pmd);
mm_dec_nr_pmds(mm);
}
}
}
static void pgd_prepopulate_pmd(struct mm_struct *mm, pgd_t *pgd, pmd_t *pmds[])
{
pud_t *pud;
int i;
if (PREALLOCATED_PMDS == 0) /* Work around gcc-3.4.x bug */
return;
pud = pud_offset(pgd, 0);
for (i = 0; i < PREALLOCATED_PMDS; i++, pud++) {
pmd_t *pmd = pmds[i];
if (i >= KERNEL_PGD_BOUNDARY)
memcpy(pmd, (pmd_t *)pgd_page_vaddr(swapper_pg_dir[i]),
sizeof(pmd_t) * PTRS_PER_PMD);
pud_populate(mm, pud, pmd);
}
}
/*
* Xen paravirt assumes pgd table should be in one page. 64 bit kernel also
* assumes that pgd should be in one page.
*
* But kernel with PAE paging that is not running as a Xen domain
* only needs to allocate 32 bytes for pgd instead of one page.
*/
#ifdef CONFIG_X86_PAE
#include <linux/slab.h>
#define PGD_SIZE (PTRS_PER_PGD * sizeof(pgd_t))
#define PGD_ALIGN 32
static struct kmem_cache *pgd_cache;
static int __init pgd_cache_init(void)
{
/*
* When PAE kernel is running as a Xen domain, it does not use
* shared kernel pmd. And this requires a whole page for pgd.
*/
if (!SHARED_KERNEL_PMD)
return 0;
/*
* when PAE kernel is not running as a Xen domain, it uses
* shared kernel pmd. Shared kernel pmd does not require a whole
* page for pgd. We are able to just allocate a 32-byte for pgd.
* During boot time, we create a 32-byte slab for pgd table allocation.
*/
pgd_cache = kmem_cache_create("pgd_cache", PGD_SIZE, PGD_ALIGN,
SLAB_PANIC, NULL);
if (!pgd_cache)
return -ENOMEM;
return 0;
}
core_initcall(pgd_cache_init);
static inline pgd_t *_pgd_alloc(void)
{
/*
* If no SHARED_KERNEL_PMD, PAE kernel is running as a Xen domain.
* We allocate one page for pgd.
*/
if (!SHARED_KERNEL_PMD)
return (pgd_t *)__get_free_page(PGALLOC_GFP);
/*
* Now PAE kernel is not running as a Xen domain. We can allocate
* a 32-byte slab for pgd to save memory space.
*/
return kmem_cache_alloc(pgd_cache, PGALLOC_GFP);
}
static inline void _pgd_free(pgd_t *pgd)
{
if (!SHARED_KERNEL_PMD)
free_page((unsigned long)pgd);
else
kmem_cache_free(pgd_cache, pgd);
}
#else
static inline pgd_t *_pgd_alloc(void)
{
return (pgd_t *)__get_free_page(PGALLOC_GFP);
}
static inline void _pgd_free(pgd_t *pgd)
{
free_page((unsigned long)pgd);
}
#endif /* CONFIG_X86_PAE */
pgd_t *pgd_alloc(struct mm_struct *mm)
{
pgd_t *pgd;
pmd_t *pmds[PREALLOCATED_PMDS];
pgd = _pgd_alloc();
if (pgd == NULL)
goto out;
mm->pgd = pgd;
if (preallocate_pmds(mm, pmds) != 0)
goto out_free_pgd;
if (paravirt_pgd_alloc(mm) != 0)
goto out_free_pmds;
/*
* Make sure that pre-populating the pmds is atomic with
* respect to anything walking the pgd_list, so that they
* never see a partially populated pgd.
*/
spin_lock(&pgd_lock);
pgd_ctor(mm, pgd);
pgd_prepopulate_pmd(mm, pgd, pmds);
spin_unlock(&pgd_lock);
return pgd;
out_free_pmds:
free_pmds(mm, pmds);
out_free_pgd:
_pgd_free(pgd);
out:
return NULL;
}
void pgd_free(struct mm_struct *mm, pgd_t *pgd)
{
pgd_mop_up_pmds(mm, pgd);
pgd_dtor(pgd);
paravirt_pgd_free(mm, pgd);
_pgd_free(pgd);
}
/*
* Used to set accessed or dirty bits in the page table entries
* on other architectures. On x86, the accessed and dirty bits
* are tracked by hardware. However, do_wp_page calls this function
* to also make the pte writeable at the same time the dirty bit is
* set. In that case we do actually need to write the PTE.
*/
int ptep_set_access_flags(struct vm_area_struct *vma,
unsigned long address, pte_t *ptep,
pte_t entry, int dirty)
{
int changed = !pte_same(*ptep, entry);
if (changed && dirty) {
*ptep = entry;
pte_update(vma->vm_mm, address, ptep);
}
return changed;
}
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
int pmdp_set_access_flags(struct vm_area_struct *vma,
unsigned long address, pmd_t *pmdp,
pmd_t entry, int dirty)
{
int changed = !pmd_same(*pmdp, entry);
VM_BUG_ON(address & ~HPAGE_PMD_MASK);
if (changed && dirty) {
*pmdp = entry;
/*
* We had a write-protection fault here and changed the pmd
* to to more permissive. No need to flush the TLB for that,
* #PF is architecturally guaranteed to do that and in the
* worst-case we'll generate a spurious fault.
*/
}
return changed;
}
#endif
int ptep_test_and_clear_young(struct vm_area_struct *vma,
unsigned long addr, pte_t *ptep)
{
int ret = 0;
if (pte_young(*ptep))
ret = test_and_clear_bit(_PAGE_BIT_ACCESSED,
(unsigned long *) &ptep->pte);
if (ret)
pte_update(vma->vm_mm, addr, ptep);
return ret;
}
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
int pmdp_test_and_clear_young(struct vm_area_struct *vma,
unsigned long addr, pmd_t *pmdp)
{
int ret = 0;
if (pmd_young(*pmdp))
ret = test_and_clear_bit(_PAGE_BIT_ACCESSED,
(unsigned long *)pmdp);
return ret;
}
#endif
int ptep_clear_flush_young(struct vm_area_struct *vma,
unsigned long address, pte_t *ptep)
{
/*
* On x86 CPUs, clearing the accessed bit without a TLB flush
* doesn't cause data corruption. [ It could cause incorrect
* page aging and the (mistaken) reclaim of hot pages, but the
* chance of that should be relatively low. ]
*
* So as a performance optimization don't flush the TLB when
* clearing the accessed bit, it will eventually be flushed by
* a context switch or a VM operation anyway. [ In the rare
* event of it not getting flushed for a long time the delay
* shouldn't really matter because there's no real memory
* pressure for swapout to react to. ]
*/
return ptep_test_and_clear_young(vma, address, ptep);
}
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
int pmdp_clear_flush_young(struct vm_area_struct *vma,
unsigned long address, pmd_t *pmdp)
{
int young;
VM_BUG_ON(address & ~HPAGE_PMD_MASK);
young = pmdp_test_and_clear_young(vma, address, pmdp);
if (young)
flush_tlb_range(vma, address, address + HPAGE_PMD_SIZE);
return young;
}
#endif
/**
* reserve_top_address - reserves a hole in the top of kernel address space
* @reserve - size of hole to reserve
*
* Can be used to relocate the fixmap area and poke a hole in the top
* of kernel address space to make room for a hypervisor.
*/
void __init reserve_top_address(unsigned long reserve)
{
#ifdef CONFIG_X86_32
BUG_ON(fixmaps_set > 0);
__FIXADDR_TOP = round_down(-reserve, 1 << PMD_SHIFT) - PAGE_SIZE;
printk(KERN_INFO "Reserving virtual address space above 0x%08lx (rounded to 0x%08lx)\n",
-reserve, __FIXADDR_TOP + PAGE_SIZE);
#endif
}
int fixmaps_set;
void __native_set_fixmap(enum fixed_addresses idx, pte_t pte)
{
unsigned long address = __fix_to_virt(idx);
if (idx >= __end_of_fixed_addresses) {
BUG();
return;
}
set_pte_vaddr(address, pte);
fixmaps_set++;
}
void native_set_fixmap(enum fixed_addresses idx, phys_addr_t phys,
pgprot_t flags)
{
__native_set_fixmap(idx, pfn_pte(phys >> PAGE_SHIFT, flags));
}
#ifdef CONFIG_HAVE_ARCH_HUGE_VMAP
/**
* pud_set_huge - setup kernel PUD mapping
*
* MTRRs can override PAT memory types with 4KiB granularity. Therefore, this
* function sets up a huge page only if any of the following conditions are met:
*
* - MTRRs are disabled, or
*
* - MTRRs are enabled and the range is completely covered by a single MTRR, or
*
* - MTRRs are enabled and the corresponding MTRR memory type is WB, which
* has no effect on the requested PAT memory type.
*
* Callers should try to decrease page size (1GB -> 2MB -> 4K) if the bigger
* page mapping attempt fails.
*
* Returns 1 on success and 0 on failure.
*/
int pud_set_huge(pud_t *pud, phys_addr_t addr, pgprot_t prot)
{
u8 mtrr, uniform;
mtrr = mtrr_type_lookup(addr, addr + PUD_SIZE, &uniform);
if ((mtrr != MTRR_TYPE_INVALID) && (!uniform) &&
(mtrr != MTRR_TYPE_WRBACK))
return 0;
prot = pgprot_4k_2_large(prot);
set_pte((pte_t *)pud, pfn_pte(
(u64)addr >> PAGE_SHIFT,
__pgprot(pgprot_val(prot) | _PAGE_PSE)));
return 1;
}
/**
* pmd_set_huge - setup kernel PMD mapping
*
* See text over pud_set_huge() above.
*
* Returns 1 on success and 0 on failure.
*/
int pmd_set_huge(pmd_t *pmd, phys_addr_t addr, pgprot_t prot)
{
u8 mtrr, uniform;
mtrr = mtrr_type_lookup(addr, addr + PMD_SIZE, &uniform);
if ((mtrr != MTRR_TYPE_INVALID) && (!uniform) &&
(mtrr != MTRR_TYPE_WRBACK)) {
pr_warn_once("%s: Cannot satisfy [mem %#010llx-%#010llx] with a huge-page mapping due to MTRR override.\n",
__func__, addr, addr + PMD_SIZE);
return 0;
}
prot = pgprot_4k_2_large(prot);
set_pte((pte_t *)pmd, pfn_pte(
(u64)addr >> PAGE_SHIFT,
__pgprot(pgprot_val(prot) | _PAGE_PSE)));
return 1;
}
/**
* pud_clear_huge - clear kernel PUD mapping when it is set
*
* Returns 1 on success and 0 on failure (no PUD map is found).
*/
int pud_clear_huge(pud_t *pud)
{
if (pud_large(*pud)) {
pud_clear(pud);
return 1;
}
return 0;
}
/**
* pmd_clear_huge - clear kernel PMD mapping when it is set
*
* Returns 1 on success and 0 on failure (no PMD map is found).
*/
int pmd_clear_huge(pmd_t *pmd)
{
if (pmd_large(*pmd)) {
pmd_clear(pmd);
return 1;
}
return 0;
}
#endif /* CONFIG_HAVE_ARCH_HUGE_VMAP */
| gpl-2.0 |
wenhulove333/LinuxKernelStable | drivers/ata/sata_rcar.c | 354 | 27259 | /*
* Renesas R-Car SATA driver
*
* Author: Vladimir Barinov <source@cogentembedded.com>
* Copyright (C) 2013-2015 Cogent Embedded, Inc.
* Copyright (C) 2013-2015 Renesas Solutions Corp.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/ata.h>
#include <linux/libata.h>
#include <linux/of_device.h>
#include <linux/platform_device.h>
#include <linux/clk.h>
#include <linux/err.h>
#define DRV_NAME "sata_rcar"
/* SH-Navi2G/ATAPI-ATA compatible task registers */
#define DATA_REG 0x100
#define SDEVCON_REG 0x138
/* SH-Navi2G/ATAPI module compatible control registers */
#define ATAPI_CONTROL1_REG 0x180
#define ATAPI_STATUS_REG 0x184
#define ATAPI_INT_ENABLE_REG 0x188
#define ATAPI_DTB_ADR_REG 0x198
#define ATAPI_DMA_START_ADR_REG 0x19C
#define ATAPI_DMA_TRANS_CNT_REG 0x1A0
#define ATAPI_CONTROL2_REG 0x1A4
#define ATAPI_SIG_ST_REG 0x1B0
#define ATAPI_BYTE_SWAP_REG 0x1BC
/* ATAPI control 1 register (ATAPI_CONTROL1) bits */
#define ATAPI_CONTROL1_ISM BIT(16)
#define ATAPI_CONTROL1_DTA32M BIT(11)
#define ATAPI_CONTROL1_RESET BIT(7)
#define ATAPI_CONTROL1_DESE BIT(3)
#define ATAPI_CONTROL1_RW BIT(2)
#define ATAPI_CONTROL1_STOP BIT(1)
#define ATAPI_CONTROL1_START BIT(0)
/* ATAPI status register (ATAPI_STATUS) bits */
#define ATAPI_STATUS_SATAINT BIT(11)
#define ATAPI_STATUS_DNEND BIT(6)
#define ATAPI_STATUS_DEVTRM BIT(5)
#define ATAPI_STATUS_DEVINT BIT(4)
#define ATAPI_STATUS_ERR BIT(2)
#define ATAPI_STATUS_NEND BIT(1)
#define ATAPI_STATUS_ACT BIT(0)
/* Interrupt enable register (ATAPI_INT_ENABLE) bits */
#define ATAPI_INT_ENABLE_SATAINT BIT(11)
#define ATAPI_INT_ENABLE_DNEND BIT(6)
#define ATAPI_INT_ENABLE_DEVTRM BIT(5)
#define ATAPI_INT_ENABLE_DEVINT BIT(4)
#define ATAPI_INT_ENABLE_ERR BIT(2)
#define ATAPI_INT_ENABLE_NEND BIT(1)
#define ATAPI_INT_ENABLE_ACT BIT(0)
/* Access control registers for physical layer control register */
#define SATAPHYADDR_REG 0x200
#define SATAPHYWDATA_REG 0x204
#define SATAPHYACCEN_REG 0x208
#define SATAPHYRESET_REG 0x20C
#define SATAPHYRDATA_REG 0x210
#define SATAPHYACK_REG 0x214
/* Physical layer control address command register (SATAPHYADDR) bits */
#define SATAPHYADDR_PHYRATEMODE BIT(10)
#define SATAPHYADDR_PHYCMD_READ BIT(9)
#define SATAPHYADDR_PHYCMD_WRITE BIT(8)
/* Physical layer control enable register (SATAPHYACCEN) bits */
#define SATAPHYACCEN_PHYLANE BIT(0)
/* Physical layer control reset register (SATAPHYRESET) bits */
#define SATAPHYRESET_PHYRST BIT(1)
#define SATAPHYRESET_PHYSRES BIT(0)
/* Physical layer control acknowledge register (SATAPHYACK) bits */
#define SATAPHYACK_PHYACK BIT(0)
/* Serial-ATA HOST control registers */
#define BISTCONF_REG 0x102C
#define SDATA_REG 0x1100
#define SSDEVCON_REG 0x1204
#define SCRSSTS_REG 0x1400
#define SCRSERR_REG 0x1404
#define SCRSCON_REG 0x1408
#define SCRSACT_REG 0x140C
#define SATAINTSTAT_REG 0x1508
#define SATAINTMASK_REG 0x150C
/* SATA INT status register (SATAINTSTAT) bits */
#define SATAINTSTAT_SERR BIT(3)
#define SATAINTSTAT_ATA BIT(0)
/* SATA INT mask register (SATAINTSTAT) bits */
#define SATAINTMASK_SERRMSK BIT(3)
#define SATAINTMASK_ERRMSK BIT(2)
#define SATAINTMASK_ERRCRTMSK BIT(1)
#define SATAINTMASK_ATAMSK BIT(0)
#define SATA_RCAR_INT_MASK (SATAINTMASK_SERRMSK | \
SATAINTMASK_ATAMSK)
/* Physical Layer Control Registers */
#define SATAPCTLR1_REG 0x43
#define SATAPCTLR2_REG 0x52
#define SATAPCTLR3_REG 0x5A
#define SATAPCTLR4_REG 0x60
/* Descriptor table word 0 bit (when DTA32M = 1) */
#define SATA_RCAR_DTEND BIT(0)
#define SATA_RCAR_DMA_BOUNDARY 0x1FFFFFFEUL
/* Gen2 Physical Layer Control Registers */
#define RCAR_GEN2_PHY_CTL1_REG 0x1704
#define RCAR_GEN2_PHY_CTL1 0x34180002
#define RCAR_GEN2_PHY_CTL1_SS 0xC180 /* Spread Spectrum */
#define RCAR_GEN2_PHY_CTL2_REG 0x170C
#define RCAR_GEN2_PHY_CTL2 0x00002303
#define RCAR_GEN2_PHY_CTL3_REG 0x171C
#define RCAR_GEN2_PHY_CTL3 0x000B0194
#define RCAR_GEN2_PHY_CTL4_REG 0x1724
#define RCAR_GEN2_PHY_CTL4 0x00030994
#define RCAR_GEN2_PHY_CTL5_REG 0x1740
#define RCAR_GEN2_PHY_CTL5 0x03004001
#define RCAR_GEN2_PHY_CTL5_DC BIT(1) /* DC connection */
#define RCAR_GEN2_PHY_CTL5_TR BIT(2) /* Termination Resistor */
enum sata_rcar_type {
RCAR_GEN1_SATA,
RCAR_GEN2_SATA,
RCAR_R8A7790_ES1_SATA,
};
struct sata_rcar_priv {
void __iomem *base;
struct clk *clk;
enum sata_rcar_type type;
};
static void sata_rcar_gen1_phy_preinit(struct sata_rcar_priv *priv)
{
void __iomem *base = priv->base;
/* idle state */
iowrite32(0, base + SATAPHYADDR_REG);
/* reset */
iowrite32(SATAPHYRESET_PHYRST, base + SATAPHYRESET_REG);
udelay(10);
/* deassert reset */
iowrite32(0, base + SATAPHYRESET_REG);
}
static void sata_rcar_gen1_phy_write(struct sata_rcar_priv *priv, u16 reg,
u32 val, int group)
{
void __iomem *base = priv->base;
int timeout;
/* deassert reset */
iowrite32(0, base + SATAPHYRESET_REG);
/* lane 1 */
iowrite32(SATAPHYACCEN_PHYLANE, base + SATAPHYACCEN_REG);
/* write phy register value */
iowrite32(val, base + SATAPHYWDATA_REG);
/* set register group */
if (group)
reg |= SATAPHYADDR_PHYRATEMODE;
/* write command */
iowrite32(SATAPHYADDR_PHYCMD_WRITE | reg, base + SATAPHYADDR_REG);
/* wait for ack */
for (timeout = 0; timeout < 100; timeout++) {
val = ioread32(base + SATAPHYACK_REG);
if (val & SATAPHYACK_PHYACK)
break;
}
if (timeout >= 100)
pr_err("%s timeout\n", __func__);
/* idle state */
iowrite32(0, base + SATAPHYADDR_REG);
}
static void sata_rcar_gen1_phy_init(struct sata_rcar_priv *priv)
{
sata_rcar_gen1_phy_preinit(priv);
sata_rcar_gen1_phy_write(priv, SATAPCTLR1_REG, 0x00200188, 0);
sata_rcar_gen1_phy_write(priv, SATAPCTLR1_REG, 0x00200188, 1);
sata_rcar_gen1_phy_write(priv, SATAPCTLR3_REG, 0x0000A061, 0);
sata_rcar_gen1_phy_write(priv, SATAPCTLR2_REG, 0x20000000, 0);
sata_rcar_gen1_phy_write(priv, SATAPCTLR2_REG, 0x20000000, 1);
sata_rcar_gen1_phy_write(priv, SATAPCTLR4_REG, 0x28E80000, 0);
}
static void sata_rcar_gen2_phy_init(struct sata_rcar_priv *priv)
{
void __iomem *base = priv->base;
iowrite32(RCAR_GEN2_PHY_CTL1, base + RCAR_GEN2_PHY_CTL1_REG);
iowrite32(RCAR_GEN2_PHY_CTL2, base + RCAR_GEN2_PHY_CTL2_REG);
iowrite32(RCAR_GEN2_PHY_CTL3, base + RCAR_GEN2_PHY_CTL3_REG);
iowrite32(RCAR_GEN2_PHY_CTL4, base + RCAR_GEN2_PHY_CTL4_REG);
iowrite32(RCAR_GEN2_PHY_CTL5 | RCAR_GEN2_PHY_CTL5_DC |
RCAR_GEN2_PHY_CTL5_TR, base + RCAR_GEN2_PHY_CTL5_REG);
}
static void sata_rcar_freeze(struct ata_port *ap)
{
struct sata_rcar_priv *priv = ap->host->private_data;
/* mask */
iowrite32(0x7ff, priv->base + SATAINTMASK_REG);
ata_sff_freeze(ap);
}
static void sata_rcar_thaw(struct ata_port *ap)
{
struct sata_rcar_priv *priv = ap->host->private_data;
void __iomem *base = priv->base;
/* ack */
iowrite32(~(u32)SATA_RCAR_INT_MASK, base + SATAINTSTAT_REG);
ata_sff_thaw(ap);
/* unmask */
iowrite32(0x7ff & ~SATA_RCAR_INT_MASK, base + SATAINTMASK_REG);
}
static void sata_rcar_ioread16_rep(void __iomem *reg, void *buffer, int count)
{
u16 *ptr = buffer;
while (count--) {
u16 data = ioread32(reg);
*ptr++ = data;
}
}
static void sata_rcar_iowrite16_rep(void __iomem *reg, void *buffer, int count)
{
const u16 *ptr = buffer;
while (count--)
iowrite32(*ptr++, reg);
}
static u8 sata_rcar_check_status(struct ata_port *ap)
{
return ioread32(ap->ioaddr.status_addr);
}
static u8 sata_rcar_check_altstatus(struct ata_port *ap)
{
return ioread32(ap->ioaddr.altstatus_addr);
}
static void sata_rcar_set_devctl(struct ata_port *ap, u8 ctl)
{
iowrite32(ctl, ap->ioaddr.ctl_addr);
}
static void sata_rcar_dev_select(struct ata_port *ap, unsigned int device)
{
iowrite32(ATA_DEVICE_OBS, ap->ioaddr.device_addr);
ata_sff_pause(ap); /* needed; also flushes, for mmio */
}
static unsigned int sata_rcar_ata_devchk(struct ata_port *ap,
unsigned int device)
{
struct ata_ioports *ioaddr = &ap->ioaddr;
u8 nsect, lbal;
sata_rcar_dev_select(ap, device);
iowrite32(0x55, ioaddr->nsect_addr);
iowrite32(0xaa, ioaddr->lbal_addr);
iowrite32(0xaa, ioaddr->nsect_addr);
iowrite32(0x55, ioaddr->lbal_addr);
iowrite32(0x55, ioaddr->nsect_addr);
iowrite32(0xaa, ioaddr->lbal_addr);
nsect = ioread32(ioaddr->nsect_addr);
lbal = ioread32(ioaddr->lbal_addr);
if (nsect == 0x55 && lbal == 0xaa)
return 1; /* found a device */
return 0; /* nothing found */
}
static int sata_rcar_wait_after_reset(struct ata_link *link,
unsigned long deadline)
{
struct ata_port *ap = link->ap;
ata_msleep(ap, ATA_WAIT_AFTER_RESET);
return ata_sff_wait_ready(link, deadline);
}
static int sata_rcar_bus_softreset(struct ata_port *ap, unsigned long deadline)
{
struct ata_ioports *ioaddr = &ap->ioaddr;
DPRINTK("ata%u: bus reset via SRST\n", ap->print_id);
/* software reset. causes dev0 to be selected */
iowrite32(ap->ctl, ioaddr->ctl_addr);
udelay(20);
iowrite32(ap->ctl | ATA_SRST, ioaddr->ctl_addr);
udelay(20);
iowrite32(ap->ctl, ioaddr->ctl_addr);
ap->last_ctl = ap->ctl;
/* wait the port to become ready */
return sata_rcar_wait_after_reset(&ap->link, deadline);
}
static int sata_rcar_softreset(struct ata_link *link, unsigned int *classes,
unsigned long deadline)
{
struct ata_port *ap = link->ap;
unsigned int devmask = 0;
int rc;
u8 err;
/* determine if device 0 is present */
if (sata_rcar_ata_devchk(ap, 0))
devmask |= 1 << 0;
/* issue bus reset */
DPRINTK("about to softreset, devmask=%x\n", devmask);
rc = sata_rcar_bus_softreset(ap, deadline);
/* if link is occupied, -ENODEV too is an error */
if (rc && (rc != -ENODEV || sata_scr_valid(link))) {
ata_link_err(link, "SRST failed (errno=%d)\n", rc);
return rc;
}
/* determine by signature whether we have ATA or ATAPI devices */
classes[0] = ata_sff_dev_classify(&link->device[0], devmask, &err);
DPRINTK("classes[0]=%u\n", classes[0]);
return 0;
}
static void sata_rcar_tf_load(struct ata_port *ap,
const struct ata_taskfile *tf)
{
struct ata_ioports *ioaddr = &ap->ioaddr;
unsigned int is_addr = tf->flags & ATA_TFLAG_ISADDR;
if (tf->ctl != ap->last_ctl) {
iowrite32(tf->ctl, ioaddr->ctl_addr);
ap->last_ctl = tf->ctl;
ata_wait_idle(ap);
}
if (is_addr && (tf->flags & ATA_TFLAG_LBA48)) {
iowrite32(tf->hob_feature, ioaddr->feature_addr);
iowrite32(tf->hob_nsect, ioaddr->nsect_addr);
iowrite32(tf->hob_lbal, ioaddr->lbal_addr);
iowrite32(tf->hob_lbam, ioaddr->lbam_addr);
iowrite32(tf->hob_lbah, ioaddr->lbah_addr);
VPRINTK("hob: feat 0x%X nsect 0x%X, lba 0x%X 0x%X 0x%X\n",
tf->hob_feature,
tf->hob_nsect,
tf->hob_lbal,
tf->hob_lbam,
tf->hob_lbah);
}
if (is_addr) {
iowrite32(tf->feature, ioaddr->feature_addr);
iowrite32(tf->nsect, ioaddr->nsect_addr);
iowrite32(tf->lbal, ioaddr->lbal_addr);
iowrite32(tf->lbam, ioaddr->lbam_addr);
iowrite32(tf->lbah, ioaddr->lbah_addr);
VPRINTK("feat 0x%X nsect 0x%X lba 0x%X 0x%X 0x%X\n",
tf->feature,
tf->nsect,
tf->lbal,
tf->lbam,
tf->lbah);
}
if (tf->flags & ATA_TFLAG_DEVICE) {
iowrite32(tf->device, ioaddr->device_addr);
VPRINTK("device 0x%X\n", tf->device);
}
ata_wait_idle(ap);
}
static void sata_rcar_tf_read(struct ata_port *ap, struct ata_taskfile *tf)
{
struct ata_ioports *ioaddr = &ap->ioaddr;
tf->command = sata_rcar_check_status(ap);
tf->feature = ioread32(ioaddr->error_addr);
tf->nsect = ioread32(ioaddr->nsect_addr);
tf->lbal = ioread32(ioaddr->lbal_addr);
tf->lbam = ioread32(ioaddr->lbam_addr);
tf->lbah = ioread32(ioaddr->lbah_addr);
tf->device = ioread32(ioaddr->device_addr);
if (tf->flags & ATA_TFLAG_LBA48) {
iowrite32(tf->ctl | ATA_HOB, ioaddr->ctl_addr);
tf->hob_feature = ioread32(ioaddr->error_addr);
tf->hob_nsect = ioread32(ioaddr->nsect_addr);
tf->hob_lbal = ioread32(ioaddr->lbal_addr);
tf->hob_lbam = ioread32(ioaddr->lbam_addr);
tf->hob_lbah = ioread32(ioaddr->lbah_addr);
iowrite32(tf->ctl, ioaddr->ctl_addr);
ap->last_ctl = tf->ctl;
}
}
static void sata_rcar_exec_command(struct ata_port *ap,
const struct ata_taskfile *tf)
{
DPRINTK("ata%u: cmd 0x%X\n", ap->print_id, tf->command);
iowrite32(tf->command, ap->ioaddr.command_addr);
ata_sff_pause(ap);
}
static unsigned int sata_rcar_data_xfer(struct ata_device *dev,
unsigned char *buf,
unsigned int buflen, int rw)
{
struct ata_port *ap = dev->link->ap;
void __iomem *data_addr = ap->ioaddr.data_addr;
unsigned int words = buflen >> 1;
/* Transfer multiple of 2 bytes */
if (rw == READ)
sata_rcar_ioread16_rep(data_addr, buf, words);
else
sata_rcar_iowrite16_rep(data_addr, buf, words);
/* Transfer trailing byte, if any. */
if (unlikely(buflen & 0x01)) {
unsigned char pad[2] = { };
/* Point buf to the tail of buffer */
buf += buflen - 1;
/*
* Use io*16_rep() accessors here as well to avoid pointlessly
* swapping bytes to and from on the big endian machines...
*/
if (rw == READ) {
sata_rcar_ioread16_rep(data_addr, pad, 1);
*buf = pad[0];
} else {
pad[0] = *buf;
sata_rcar_iowrite16_rep(data_addr, pad, 1);
}
words++;
}
return words << 1;
}
static void sata_rcar_drain_fifo(struct ata_queued_cmd *qc)
{
int count;
struct ata_port *ap;
/* We only need to flush incoming data when a command was running */
if (qc == NULL || qc->dma_dir == DMA_TO_DEVICE)
return;
ap = qc->ap;
/* Drain up to 64K of data before we give up this recovery method */
for (count = 0; (ap->ops->sff_check_status(ap) & ATA_DRQ) &&
count < 65536; count += 2)
ioread32(ap->ioaddr.data_addr);
/* Can become DEBUG later */
if (count)
ata_port_dbg(ap, "drained %d bytes to clear DRQ\n", count);
}
static int sata_rcar_scr_read(struct ata_link *link, unsigned int sc_reg,
u32 *val)
{
if (sc_reg > SCR_ACTIVE)
return -EINVAL;
*val = ioread32(link->ap->ioaddr.scr_addr + (sc_reg << 2));
return 0;
}
static int sata_rcar_scr_write(struct ata_link *link, unsigned int sc_reg,
u32 val)
{
if (sc_reg > SCR_ACTIVE)
return -EINVAL;
iowrite32(val, link->ap->ioaddr.scr_addr + (sc_reg << 2));
return 0;
}
static void sata_rcar_bmdma_fill_sg(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct ata_bmdma_prd *prd = ap->bmdma_prd;
struct scatterlist *sg;
unsigned int si;
for_each_sg(qc->sg, sg, qc->n_elem, si) {
u32 addr, sg_len;
/*
* Note: h/w doesn't support 64-bit, so we unconditionally
* truncate dma_addr_t to u32.
*/
addr = (u32)sg_dma_address(sg);
sg_len = sg_dma_len(sg);
prd[si].addr = cpu_to_le32(addr);
prd[si].flags_len = cpu_to_le32(sg_len);
VPRINTK("PRD[%u] = (0x%X, 0x%X)\n", si, addr, sg_len);
}
/* end-of-table flag */
prd[si - 1].addr |= cpu_to_le32(SATA_RCAR_DTEND);
}
static void sata_rcar_qc_prep(struct ata_queued_cmd *qc)
{
if (!(qc->flags & ATA_QCFLAG_DMAMAP))
return;
sata_rcar_bmdma_fill_sg(qc);
}
static void sata_rcar_bmdma_setup(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
unsigned int rw = qc->tf.flags & ATA_TFLAG_WRITE;
struct sata_rcar_priv *priv = ap->host->private_data;
void __iomem *base = priv->base;
u32 dmactl;
/* load PRD table addr. */
mb(); /* make sure PRD table writes are visible to controller */
iowrite32(ap->bmdma_prd_dma, base + ATAPI_DTB_ADR_REG);
/* specify data direction, triple-check start bit is clear */
dmactl = ioread32(base + ATAPI_CONTROL1_REG);
dmactl &= ~(ATAPI_CONTROL1_RW | ATAPI_CONTROL1_STOP);
if (dmactl & ATAPI_CONTROL1_START) {
dmactl &= ~ATAPI_CONTROL1_START;
dmactl |= ATAPI_CONTROL1_STOP;
}
if (!rw)
dmactl |= ATAPI_CONTROL1_RW;
iowrite32(dmactl, base + ATAPI_CONTROL1_REG);
/* issue r/w command */
ap->ops->sff_exec_command(ap, &qc->tf);
}
static void sata_rcar_bmdma_start(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct sata_rcar_priv *priv = ap->host->private_data;
void __iomem *base = priv->base;
u32 dmactl;
/* start host DMA transaction */
dmactl = ioread32(base + ATAPI_CONTROL1_REG);
dmactl &= ~ATAPI_CONTROL1_STOP;
dmactl |= ATAPI_CONTROL1_START;
iowrite32(dmactl, base + ATAPI_CONTROL1_REG);
}
static void sata_rcar_bmdma_stop(struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
struct sata_rcar_priv *priv = ap->host->private_data;
void __iomem *base = priv->base;
u32 dmactl;
/* force termination of DMA transfer if active */
dmactl = ioread32(base + ATAPI_CONTROL1_REG);
if (dmactl & ATAPI_CONTROL1_START) {
dmactl &= ~ATAPI_CONTROL1_START;
dmactl |= ATAPI_CONTROL1_STOP;
iowrite32(dmactl, base + ATAPI_CONTROL1_REG);
}
/* one-PIO-cycle guaranteed wait, per spec, for HDMA1:0 transition */
ata_sff_dma_pause(ap);
}
static u8 sata_rcar_bmdma_status(struct ata_port *ap)
{
struct sata_rcar_priv *priv = ap->host->private_data;
u8 host_stat = 0;
u32 status;
status = ioread32(priv->base + ATAPI_STATUS_REG);
if (status & ATAPI_STATUS_DEVINT)
host_stat |= ATA_DMA_INTR;
if (status & ATAPI_STATUS_ACT)
host_stat |= ATA_DMA_ACTIVE;
return host_stat;
}
static struct scsi_host_template sata_rcar_sht = {
ATA_BASE_SHT(DRV_NAME),
/*
* This controller allows transfer chunks up to 512MB which cross 64KB
* boundaries, therefore the DMA limits are more relaxed than standard
* ATA SFF.
*/
.sg_tablesize = ATA_MAX_PRD,
.dma_boundary = SATA_RCAR_DMA_BOUNDARY,
};
static struct ata_port_operations sata_rcar_port_ops = {
.inherits = &ata_bmdma_port_ops,
.freeze = sata_rcar_freeze,
.thaw = sata_rcar_thaw,
.softreset = sata_rcar_softreset,
.scr_read = sata_rcar_scr_read,
.scr_write = sata_rcar_scr_write,
.sff_dev_select = sata_rcar_dev_select,
.sff_set_devctl = sata_rcar_set_devctl,
.sff_check_status = sata_rcar_check_status,
.sff_check_altstatus = sata_rcar_check_altstatus,
.sff_tf_load = sata_rcar_tf_load,
.sff_tf_read = sata_rcar_tf_read,
.sff_exec_command = sata_rcar_exec_command,
.sff_data_xfer = sata_rcar_data_xfer,
.sff_drain_fifo = sata_rcar_drain_fifo,
.qc_prep = sata_rcar_qc_prep,
.bmdma_setup = sata_rcar_bmdma_setup,
.bmdma_start = sata_rcar_bmdma_start,
.bmdma_stop = sata_rcar_bmdma_stop,
.bmdma_status = sata_rcar_bmdma_status,
};
static void sata_rcar_serr_interrupt(struct ata_port *ap)
{
struct sata_rcar_priv *priv = ap->host->private_data;
struct ata_eh_info *ehi = &ap->link.eh_info;
int freeze = 0;
u32 serror;
serror = ioread32(priv->base + SCRSERR_REG);
if (!serror)
return;
DPRINTK("SError @host_intr: 0x%x\n", serror);
/* first, analyze and record host port events */
ata_ehi_clear_desc(ehi);
if (serror & (SERR_DEV_XCHG | SERR_PHYRDY_CHG)) {
/* Setup a soft-reset EH action */
ata_ehi_hotplugged(ehi);
ata_ehi_push_desc(ehi, "%s", "hotplug");
freeze = serror & SERR_COMM_WAKE ? 0 : 1;
}
/* freeze or abort */
if (freeze)
ata_port_freeze(ap);
else
ata_port_abort(ap);
}
static void sata_rcar_ata_interrupt(struct ata_port *ap)
{
struct ata_queued_cmd *qc;
int handled = 0;
qc = ata_qc_from_tag(ap, ap->link.active_tag);
if (qc)
handled |= ata_bmdma_port_intr(ap, qc);
/* be sure to clear ATA interrupt */
if (!handled)
sata_rcar_check_status(ap);
}
static irqreturn_t sata_rcar_interrupt(int irq, void *dev_instance)
{
struct ata_host *host = dev_instance;
struct sata_rcar_priv *priv = host->private_data;
void __iomem *base = priv->base;
unsigned int handled = 0;
struct ata_port *ap;
u32 sataintstat;
unsigned long flags;
spin_lock_irqsave(&host->lock, flags);
sataintstat = ioread32(base + SATAINTSTAT_REG);
sataintstat &= SATA_RCAR_INT_MASK;
if (!sataintstat)
goto done;
/* ack */
iowrite32(~sataintstat & 0x7ff, base + SATAINTSTAT_REG);
ap = host->ports[0];
if (sataintstat & SATAINTSTAT_ATA)
sata_rcar_ata_interrupt(ap);
if (sataintstat & SATAINTSTAT_SERR)
sata_rcar_serr_interrupt(ap);
handled = 1;
done:
spin_unlock_irqrestore(&host->lock, flags);
return IRQ_RETVAL(handled);
}
static void sata_rcar_setup_port(struct ata_host *host)
{
struct ata_port *ap = host->ports[0];
struct ata_ioports *ioaddr = &ap->ioaddr;
struct sata_rcar_priv *priv = host->private_data;
void __iomem *base = priv->base;
ap->ops = &sata_rcar_port_ops;
ap->pio_mask = ATA_PIO4;
ap->udma_mask = ATA_UDMA6;
ap->flags |= ATA_FLAG_SATA;
if (priv->type == RCAR_R8A7790_ES1_SATA)
ap->flags |= ATA_FLAG_NO_DIPM;
ioaddr->cmd_addr = base + SDATA_REG;
ioaddr->ctl_addr = base + SSDEVCON_REG;
ioaddr->scr_addr = base + SCRSSTS_REG;
ioaddr->altstatus_addr = ioaddr->ctl_addr;
ioaddr->data_addr = ioaddr->cmd_addr + (ATA_REG_DATA << 2);
ioaddr->error_addr = ioaddr->cmd_addr + (ATA_REG_ERR << 2);
ioaddr->feature_addr = ioaddr->cmd_addr + (ATA_REG_FEATURE << 2);
ioaddr->nsect_addr = ioaddr->cmd_addr + (ATA_REG_NSECT << 2);
ioaddr->lbal_addr = ioaddr->cmd_addr + (ATA_REG_LBAL << 2);
ioaddr->lbam_addr = ioaddr->cmd_addr + (ATA_REG_LBAM << 2);
ioaddr->lbah_addr = ioaddr->cmd_addr + (ATA_REG_LBAH << 2);
ioaddr->device_addr = ioaddr->cmd_addr + (ATA_REG_DEVICE << 2);
ioaddr->status_addr = ioaddr->cmd_addr + (ATA_REG_STATUS << 2);
ioaddr->command_addr = ioaddr->cmd_addr + (ATA_REG_CMD << 2);
}
static void sata_rcar_init_controller(struct ata_host *host)
{
struct sata_rcar_priv *priv = host->private_data;
void __iomem *base = priv->base;
u32 val;
/* reset and setup phy */
switch (priv->type) {
case RCAR_GEN1_SATA:
sata_rcar_gen1_phy_init(priv);
break;
case RCAR_GEN2_SATA:
case RCAR_R8A7790_ES1_SATA:
sata_rcar_gen2_phy_init(priv);
break;
default:
dev_warn(host->dev, "SATA phy is not initialized\n");
break;
}
/* SATA-IP reset state */
val = ioread32(base + ATAPI_CONTROL1_REG);
val |= ATAPI_CONTROL1_RESET;
iowrite32(val, base + ATAPI_CONTROL1_REG);
/* ISM mode, PRD mode, DTEND flag at bit 0 */
val = ioread32(base + ATAPI_CONTROL1_REG);
val |= ATAPI_CONTROL1_ISM;
val |= ATAPI_CONTROL1_DESE;
val |= ATAPI_CONTROL1_DTA32M;
iowrite32(val, base + ATAPI_CONTROL1_REG);
/* Release the SATA-IP from the reset state */
val = ioread32(base + ATAPI_CONTROL1_REG);
val &= ~ATAPI_CONTROL1_RESET;
iowrite32(val, base + ATAPI_CONTROL1_REG);
/* ack and mask */
iowrite32(0, base + SATAINTSTAT_REG);
iowrite32(0x7ff, base + SATAINTMASK_REG);
/* enable interrupts */
iowrite32(ATAPI_INT_ENABLE_SATAINT, base + ATAPI_INT_ENABLE_REG);
}
static struct of_device_id sata_rcar_match[] = {
{
/* Deprecated by "renesas,sata-r8a7779" */
.compatible = "renesas,rcar-sata",
.data = (void *)RCAR_GEN1_SATA,
},
{
.compatible = "renesas,sata-r8a7779",
.data = (void *)RCAR_GEN1_SATA,
},
{
.compatible = "renesas,sata-r8a7790",
.data = (void *)RCAR_GEN2_SATA
},
{
.compatible = "renesas,sata-r8a7790-es1",
.data = (void *)RCAR_R8A7790_ES1_SATA
},
{
.compatible = "renesas,sata-r8a7791",
.data = (void *)RCAR_GEN2_SATA
},
{
.compatible = "renesas,sata-r8a7793",
.data = (void *)RCAR_GEN2_SATA
},
{ },
};
MODULE_DEVICE_TABLE(of, sata_rcar_match);
static const struct platform_device_id sata_rcar_id_table[] = {
{ "sata_rcar", RCAR_GEN1_SATA }, /* Deprecated by "sata-r8a7779" */
{ "sata-r8a7779", RCAR_GEN1_SATA },
{ },
};
MODULE_DEVICE_TABLE(platform, sata_rcar_id_table);
static int sata_rcar_probe(struct platform_device *pdev)
{
const struct of_device_id *of_id;
struct ata_host *host;
struct sata_rcar_priv *priv;
struct resource *mem;
int irq;
int ret = 0;
irq = platform_get_irq(pdev, 0);
if (irq <= 0)
return -EINVAL;
priv = devm_kzalloc(&pdev->dev, sizeof(struct sata_rcar_priv),
GFP_KERNEL);
if (!priv)
return -ENOMEM;
of_id = of_match_device(sata_rcar_match, &pdev->dev);
if (of_id)
priv->type = (enum sata_rcar_type)of_id->data;
else
priv->type = platform_get_device_id(pdev)->driver_data;
priv->clk = devm_clk_get(&pdev->dev, NULL);
if (IS_ERR(priv->clk)) {
dev_err(&pdev->dev, "failed to get access to sata clock\n");
return PTR_ERR(priv->clk);
}
clk_prepare_enable(priv->clk);
host = ata_host_alloc(&pdev->dev, 1);
if (!host) {
dev_err(&pdev->dev, "ata_host_alloc failed\n");
ret = -ENOMEM;
goto cleanup;
}
host->private_data = priv;
mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
priv->base = devm_ioremap_resource(&pdev->dev, mem);
if (IS_ERR(priv->base)) {
ret = PTR_ERR(priv->base);
goto cleanup;
}
/* setup port */
sata_rcar_setup_port(host);
/* initialize host controller */
sata_rcar_init_controller(host);
ret = ata_host_activate(host, irq, sata_rcar_interrupt, 0,
&sata_rcar_sht);
if (!ret)
return 0;
cleanup:
clk_disable_unprepare(priv->clk);
return ret;
}
static int sata_rcar_remove(struct platform_device *pdev)
{
struct ata_host *host = platform_get_drvdata(pdev);
struct sata_rcar_priv *priv = host->private_data;
void __iomem *base = priv->base;
ata_host_detach(host);
/* disable interrupts */
iowrite32(0, base + ATAPI_INT_ENABLE_REG);
/* ack and mask */
iowrite32(0, base + SATAINTSTAT_REG);
iowrite32(0x7ff, base + SATAINTMASK_REG);
clk_disable_unprepare(priv->clk);
return 0;
}
#ifdef CONFIG_PM_SLEEP
static int sata_rcar_suspend(struct device *dev)
{
struct ata_host *host = dev_get_drvdata(dev);
struct sata_rcar_priv *priv = host->private_data;
void __iomem *base = priv->base;
int ret;
ret = ata_host_suspend(host, PMSG_SUSPEND);
if (!ret) {
/* disable interrupts */
iowrite32(0, base + ATAPI_INT_ENABLE_REG);
/* mask */
iowrite32(0x7ff, base + SATAINTMASK_REG);
clk_disable_unprepare(priv->clk);
}
return ret;
}
static int sata_rcar_resume(struct device *dev)
{
struct ata_host *host = dev_get_drvdata(dev);
struct sata_rcar_priv *priv = host->private_data;
void __iomem *base = priv->base;
clk_prepare_enable(priv->clk);
/* ack and mask */
iowrite32(0, base + SATAINTSTAT_REG);
iowrite32(0x7ff, base + SATAINTMASK_REG);
/* enable interrupts */
iowrite32(ATAPI_INT_ENABLE_SATAINT, base + ATAPI_INT_ENABLE_REG);
ata_host_resume(host);
return 0;
}
static int sata_rcar_restore(struct device *dev)
{
struct ata_host *host = dev_get_drvdata(dev);
struct sata_rcar_priv *priv = host->private_data;
clk_prepare_enable(priv->clk);
sata_rcar_setup_port(host);
/* initialize host controller */
sata_rcar_init_controller(host);
ata_host_resume(host);
return 0;
}
static const struct dev_pm_ops sata_rcar_pm_ops = {
.suspend = sata_rcar_suspend,
.resume = sata_rcar_resume,
.freeze = sata_rcar_suspend,
.thaw = sata_rcar_resume,
.poweroff = sata_rcar_suspend,
.restore = sata_rcar_restore,
};
#endif
static struct platform_driver sata_rcar_driver = {
.probe = sata_rcar_probe,
.remove = sata_rcar_remove,
.id_table = sata_rcar_id_table,
.driver = {
.name = DRV_NAME,
.of_match_table = sata_rcar_match,
#ifdef CONFIG_PM_SLEEP
.pm = &sata_rcar_pm_ops,
#endif
},
};
module_platform_driver(sata_rcar_driver);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Vladimir Barinov");
MODULE_DESCRIPTION("Renesas R-Car SATA controller low level driver");
| gpl-2.0 |
jamesjjliao/linux | sound/pci/hda/hda_sysfs.c | 610 | 19425 | /*
* sysfs interface for HD-audio codec
*
* Copyright (c) 2014 Takashi Iwai <tiwai@suse.de>
*
* split from hda_hwdep.c
*/
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/compat.h>
#include <linux/mutex.h>
#include <linux/ctype.h>
#include <linux/string.h>
#include <linux/export.h>
#include <sound/core.h>
#include "hda_codec.h"
#include "hda_local.h"
#include <sound/hda_hwdep.h>
#include <sound/minors.h>
/* hint string pair */
struct hda_hint {
const char *key;
const char *val; /* contained in the same alloc as key */
};
#ifdef CONFIG_PM
static ssize_t power_on_acct_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct hda_codec *codec = dev_get_drvdata(dev);
snd_hda_update_power_acct(codec);
return sprintf(buf, "%u\n", jiffies_to_msecs(codec->power_on_acct));
}
static ssize_t power_off_acct_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct hda_codec *codec = dev_get_drvdata(dev);
snd_hda_update_power_acct(codec);
return sprintf(buf, "%u\n", jiffies_to_msecs(codec->power_off_acct));
}
static DEVICE_ATTR_RO(power_on_acct);
static DEVICE_ATTR_RO(power_off_acct);
#endif /* CONFIG_PM */
#define CODEC_INFO_SHOW(type, field) \
static ssize_t type##_show(struct device *dev, \
struct device_attribute *attr, \
char *buf) \
{ \
struct hda_codec *codec = dev_get_drvdata(dev); \
return sprintf(buf, "0x%x\n", codec->field); \
}
#define CODEC_INFO_STR_SHOW(type, field) \
static ssize_t type##_show(struct device *dev, \
struct device_attribute *attr, \
char *buf) \
{ \
struct hda_codec *codec = dev_get_drvdata(dev); \
return sprintf(buf, "%s\n", \
codec->field ? codec->field : ""); \
}
CODEC_INFO_SHOW(vendor_id, core.vendor_id);
CODEC_INFO_SHOW(subsystem_id, core.subsystem_id);
CODEC_INFO_SHOW(revision_id, core.revision_id);
CODEC_INFO_SHOW(afg, core.afg);
CODEC_INFO_SHOW(mfg, core.mfg);
CODEC_INFO_STR_SHOW(vendor_name, core.vendor_name);
CODEC_INFO_STR_SHOW(chip_name, core.chip_name);
CODEC_INFO_STR_SHOW(modelname, modelname);
static ssize_t pin_configs_show(struct hda_codec *codec,
struct snd_array *list,
char *buf)
{
int i, len = 0;
mutex_lock(&codec->user_mutex);
for (i = 0; i < list->used; i++) {
struct hda_pincfg *pin = snd_array_elem(list, i);
len += sprintf(buf + len, "0x%02x 0x%08x\n",
pin->nid, pin->cfg);
}
mutex_unlock(&codec->user_mutex);
return len;
}
static ssize_t init_pin_configs_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct hda_codec *codec = dev_get_drvdata(dev);
return pin_configs_show(codec, &codec->init_pins, buf);
}
static ssize_t driver_pin_configs_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct hda_codec *codec = dev_get_drvdata(dev);
return pin_configs_show(codec, &codec->driver_pins, buf);
}
#ifdef CONFIG_SND_HDA_RECONFIG
/*
* sysfs interface
*/
static int clear_codec(struct hda_codec *codec)
{
int err;
err = snd_hda_codec_reset(codec);
if (err < 0) {
codec_err(codec, "The codec is being used, can't free.\n");
return err;
}
snd_hda_sysfs_clear(codec);
return 0;
}
static int reconfig_codec(struct hda_codec *codec)
{
int err;
snd_hda_power_up(codec);
codec_info(codec, "hda-codec: reconfiguring\n");
err = snd_hda_codec_reset(codec);
if (err < 0) {
codec_err(codec,
"The codec is being used, can't reconfigure.\n");
goto error;
}
err = snd_hda_codec_configure(codec);
if (err < 0)
goto error;
/* rebuild PCMs */
err = snd_hda_codec_build_pcms(codec);
if (err < 0)
goto error;
/* rebuild mixers */
err = snd_hda_codec_build_controls(codec);
if (err < 0)
goto error;
err = snd_card_register(codec->card);
error:
snd_hda_power_down(codec);
return err;
}
/*
* allocate a string at most len chars, and remove the trailing EOL
*/
static char *kstrndup_noeol(const char *src, size_t len)
{
char *s = kstrndup(src, len, GFP_KERNEL);
char *p;
if (!s)
return NULL;
p = strchr(s, '\n');
if (p)
*p = 0;
return s;
}
#define CODEC_INFO_STORE(type, field) \
static ssize_t type##_store(struct device *dev, \
struct device_attribute *attr, \
const char *buf, size_t count) \
{ \
struct hda_codec *codec = dev_get_drvdata(dev); \
unsigned long val; \
int err = kstrtoul(buf, 0, &val); \
if (err < 0) \
return err; \
codec->field = val; \
return count; \
}
#define CODEC_INFO_STR_STORE(type, field) \
static ssize_t type##_store(struct device *dev, \
struct device_attribute *attr, \
const char *buf, size_t count) \
{ \
struct hda_codec *codec = dev_get_drvdata(dev); \
char *s = kstrndup_noeol(buf, 64); \
if (!s) \
return -ENOMEM; \
kfree(codec->field); \
codec->field = s; \
return count; \
}
CODEC_INFO_STORE(vendor_id, core.vendor_id);
CODEC_INFO_STORE(subsystem_id, core.subsystem_id);
CODEC_INFO_STORE(revision_id, core.revision_id);
CODEC_INFO_STR_STORE(vendor_name, core.vendor_name);
CODEC_INFO_STR_STORE(chip_name, core.chip_name);
CODEC_INFO_STR_STORE(modelname, modelname);
#define CODEC_ACTION_STORE(type) \
static ssize_t type##_store(struct device *dev, \
struct device_attribute *attr, \
const char *buf, size_t count) \
{ \
struct hda_codec *codec = dev_get_drvdata(dev); \
int err = 0; \
if (*buf) \
err = type##_codec(codec); \
return err < 0 ? err : count; \
}
CODEC_ACTION_STORE(reconfig);
CODEC_ACTION_STORE(clear);
static ssize_t init_verbs_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct hda_codec *codec = dev_get_drvdata(dev);
int i, len = 0;
mutex_lock(&codec->user_mutex);
for (i = 0; i < codec->init_verbs.used; i++) {
struct hda_verb *v = snd_array_elem(&codec->init_verbs, i);
len += snprintf(buf + len, PAGE_SIZE - len,
"0x%02x 0x%03x 0x%04x\n",
v->nid, v->verb, v->param);
}
mutex_unlock(&codec->user_mutex);
return len;
}
static int parse_init_verbs(struct hda_codec *codec, const char *buf)
{
struct hda_verb *v;
int nid, verb, param;
if (sscanf(buf, "%i %i %i", &nid, &verb, ¶m) != 3)
return -EINVAL;
if (!nid || !verb)
return -EINVAL;
mutex_lock(&codec->user_mutex);
v = snd_array_new(&codec->init_verbs);
if (!v) {
mutex_unlock(&codec->user_mutex);
return -ENOMEM;
}
v->nid = nid;
v->verb = verb;
v->param = param;
mutex_unlock(&codec->user_mutex);
return 0;
}
static ssize_t init_verbs_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct hda_codec *codec = dev_get_drvdata(dev);
int err = parse_init_verbs(codec, buf);
if (err < 0)
return err;
return count;
}
static ssize_t hints_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct hda_codec *codec = dev_get_drvdata(dev);
int i, len = 0;
mutex_lock(&codec->user_mutex);
for (i = 0; i < codec->hints.used; i++) {
struct hda_hint *hint = snd_array_elem(&codec->hints, i);
len += snprintf(buf + len, PAGE_SIZE - len,
"%s = %s\n", hint->key, hint->val);
}
mutex_unlock(&codec->user_mutex);
return len;
}
static struct hda_hint *get_hint(struct hda_codec *codec, const char *key)
{
int i;
for (i = 0; i < codec->hints.used; i++) {
struct hda_hint *hint = snd_array_elem(&codec->hints, i);
if (!strcmp(hint->key, key))
return hint;
}
return NULL;
}
static void remove_trail_spaces(char *str)
{
char *p;
if (!*str)
return;
p = str + strlen(str) - 1;
for (; isspace(*p); p--) {
*p = 0;
if (p == str)
return;
}
}
#define MAX_HINTS 1024
static int parse_hints(struct hda_codec *codec, const char *buf)
{
char *key, *val;
struct hda_hint *hint;
int err = 0;
buf = skip_spaces(buf);
if (!*buf || *buf == '#' || *buf == '\n')
return 0;
if (*buf == '=')
return -EINVAL;
key = kstrndup_noeol(buf, 1024);
if (!key)
return -ENOMEM;
/* extract key and val */
val = strchr(key, '=');
if (!val) {
kfree(key);
return -EINVAL;
}
*val++ = 0;
val = skip_spaces(val);
remove_trail_spaces(key);
remove_trail_spaces(val);
mutex_lock(&codec->user_mutex);
hint = get_hint(codec, key);
if (hint) {
/* replace */
kfree(hint->key);
hint->key = key;
hint->val = val;
goto unlock;
}
/* allocate a new hint entry */
if (codec->hints.used >= MAX_HINTS)
hint = NULL;
else
hint = snd_array_new(&codec->hints);
if (hint) {
hint->key = key;
hint->val = val;
} else {
err = -ENOMEM;
}
unlock:
mutex_unlock(&codec->user_mutex);
if (err)
kfree(key);
return err;
}
static ssize_t hints_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct hda_codec *codec = dev_get_drvdata(dev);
int err = parse_hints(codec, buf);
if (err < 0)
return err;
return count;
}
static ssize_t user_pin_configs_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct hda_codec *codec = dev_get_drvdata(dev);
return pin_configs_show(codec, &codec->user_pins, buf);
}
#define MAX_PIN_CONFIGS 32
static int parse_user_pin_configs(struct hda_codec *codec, const char *buf)
{
int nid, cfg, err;
if (sscanf(buf, "%i %i", &nid, &cfg) != 2)
return -EINVAL;
if (!nid)
return -EINVAL;
mutex_lock(&codec->user_mutex);
err = snd_hda_add_pincfg(codec, &codec->user_pins, nid, cfg);
mutex_unlock(&codec->user_mutex);
return err;
}
static ssize_t user_pin_configs_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct hda_codec *codec = dev_get_drvdata(dev);
int err = parse_user_pin_configs(codec, buf);
if (err < 0)
return err;
return count;
}
/* sysfs attributes exposed only when CONFIG_SND_HDA_RECONFIG=y */
static DEVICE_ATTR_RW(init_verbs);
static DEVICE_ATTR_RW(hints);
static DEVICE_ATTR_RW(user_pin_configs);
static DEVICE_ATTR_WO(reconfig);
static DEVICE_ATTR_WO(clear);
/**
* snd_hda_get_hint - Look for hint string
* @codec: the HDA codec
* @key: the hint key string
*
* Look for a hint key/value pair matching with the given key string
* and returns the value string. If nothing found, returns NULL.
*/
const char *snd_hda_get_hint(struct hda_codec *codec, const char *key)
{
struct hda_hint *hint = get_hint(codec, key);
return hint ? hint->val : NULL;
}
EXPORT_SYMBOL_GPL(snd_hda_get_hint);
/**
* snd_hda_get_bool_hint - Get a boolean hint value
* @codec: the HDA codec
* @key: the hint key string
*
* Look for a hint key/value pair matching with the given key string
* and returns a boolean value parsed from the value. If no matching
* key is found, return a negative value.
*/
int snd_hda_get_bool_hint(struct hda_codec *codec, const char *key)
{
const char *p;
int ret;
mutex_lock(&codec->user_mutex);
p = snd_hda_get_hint(codec, key);
if (!p || !*p)
ret = -ENOENT;
else {
switch (toupper(*p)) {
case 'T': /* true */
case 'Y': /* yes */
case '1':
ret = 1;
break;
default:
ret = 0;
break;
}
}
mutex_unlock(&codec->user_mutex);
return ret;
}
EXPORT_SYMBOL_GPL(snd_hda_get_bool_hint);
/**
* snd_hda_get_int_hint - Get an integer hint value
* @codec: the HDA codec
* @key: the hint key string
* @valp: pointer to store a value
*
* Look for a hint key/value pair matching with the given key string
* and stores the integer value to @valp. If no matching key is found,
* return a negative error code. Otherwise it returns zero.
*/
int snd_hda_get_int_hint(struct hda_codec *codec, const char *key, int *valp)
{
const char *p;
unsigned long val;
int ret;
mutex_lock(&codec->user_mutex);
p = snd_hda_get_hint(codec, key);
if (!p)
ret = -ENOENT;
else if (kstrtoul(p, 0, &val))
ret = -EINVAL;
else {
*valp = val;
ret = 0;
}
mutex_unlock(&codec->user_mutex);
return ret;
}
EXPORT_SYMBOL_GPL(snd_hda_get_int_hint);
#endif /* CONFIG_SND_HDA_RECONFIG */
/*
* common sysfs attributes
*/
#ifdef CONFIG_SND_HDA_RECONFIG
#define RECONFIG_DEVICE_ATTR(name) DEVICE_ATTR_RW(name)
#else
#define RECONFIG_DEVICE_ATTR(name) DEVICE_ATTR_RO(name)
#endif
static RECONFIG_DEVICE_ATTR(vendor_id);
static RECONFIG_DEVICE_ATTR(subsystem_id);
static RECONFIG_DEVICE_ATTR(revision_id);
static DEVICE_ATTR_RO(afg);
static DEVICE_ATTR_RO(mfg);
static RECONFIG_DEVICE_ATTR(vendor_name);
static RECONFIG_DEVICE_ATTR(chip_name);
static RECONFIG_DEVICE_ATTR(modelname);
static DEVICE_ATTR_RO(init_pin_configs);
static DEVICE_ATTR_RO(driver_pin_configs);
#ifdef CONFIG_SND_HDA_PATCH_LOADER
/* parser mode */
enum {
LINE_MODE_NONE,
LINE_MODE_CODEC,
LINE_MODE_MODEL,
LINE_MODE_PINCFG,
LINE_MODE_VERB,
LINE_MODE_HINT,
LINE_MODE_VENDOR_ID,
LINE_MODE_SUBSYSTEM_ID,
LINE_MODE_REVISION_ID,
LINE_MODE_CHIP_NAME,
NUM_LINE_MODES,
};
static inline int strmatch(const char *a, const char *b)
{
return strncasecmp(a, b, strlen(b)) == 0;
}
/* parse the contents after the line "[codec]"
* accept only the line with three numbers, and assign the current codec
*/
static void parse_codec_mode(char *buf, struct hda_bus *bus,
struct hda_codec **codecp)
{
int vendorid, subid, caddr;
struct hda_codec *codec;
*codecp = NULL;
if (sscanf(buf, "%i %i %i", &vendorid, &subid, &caddr) == 3) {
list_for_each_codec(codec, bus) {
if ((vendorid <= 0 || codec->core.vendor_id == vendorid) &&
(subid <= 0 || codec->core.subsystem_id == subid) &&
codec->core.addr == caddr) {
*codecp = codec;
break;
}
}
}
}
/* parse the contents after the other command tags, [pincfg], [verb],
* [vendor_id], [subsystem_id], [revision_id], [chip_name], [hint] and [model]
* just pass to the sysfs helper (only when any codec was specified)
*/
static void parse_pincfg_mode(char *buf, struct hda_bus *bus,
struct hda_codec **codecp)
{
parse_user_pin_configs(*codecp, buf);
}
static void parse_verb_mode(char *buf, struct hda_bus *bus,
struct hda_codec **codecp)
{
parse_init_verbs(*codecp, buf);
}
static void parse_hint_mode(char *buf, struct hda_bus *bus,
struct hda_codec **codecp)
{
parse_hints(*codecp, buf);
}
static void parse_model_mode(char *buf, struct hda_bus *bus,
struct hda_codec **codecp)
{
kfree((*codecp)->modelname);
(*codecp)->modelname = kstrdup(buf, GFP_KERNEL);
}
static void parse_chip_name_mode(char *buf, struct hda_bus *bus,
struct hda_codec **codecp)
{
kfree((*codecp)->core.chip_name);
(*codecp)->core.chip_name = kstrdup(buf, GFP_KERNEL);
}
#define DEFINE_PARSE_ID_MODE(name) \
static void parse_##name##_mode(char *buf, struct hda_bus *bus, \
struct hda_codec **codecp) \
{ \
unsigned long val; \
if (!kstrtoul(buf, 0, &val)) \
(*codecp)->core.name = val; \
}
DEFINE_PARSE_ID_MODE(vendor_id);
DEFINE_PARSE_ID_MODE(subsystem_id);
DEFINE_PARSE_ID_MODE(revision_id);
struct hda_patch_item {
const char *tag;
const char *alias;
void (*parser)(char *buf, struct hda_bus *bus, struct hda_codec **retc);
};
static struct hda_patch_item patch_items[NUM_LINE_MODES] = {
[LINE_MODE_CODEC] = {
.tag = "[codec]",
.parser = parse_codec_mode,
},
[LINE_MODE_MODEL] = {
.tag = "[model]",
.parser = parse_model_mode,
},
[LINE_MODE_VERB] = {
.tag = "[verb]",
.alias = "[init_verbs]",
.parser = parse_verb_mode,
},
[LINE_MODE_PINCFG] = {
.tag = "[pincfg]",
.alias = "[user_pin_configs]",
.parser = parse_pincfg_mode,
},
[LINE_MODE_HINT] = {
.tag = "[hint]",
.alias = "[hints]",
.parser = parse_hint_mode
},
[LINE_MODE_VENDOR_ID] = {
.tag = "[vendor_id]",
.parser = parse_vendor_id_mode,
},
[LINE_MODE_SUBSYSTEM_ID] = {
.tag = "[subsystem_id]",
.parser = parse_subsystem_id_mode,
},
[LINE_MODE_REVISION_ID] = {
.tag = "[revision_id]",
.parser = parse_revision_id_mode,
},
[LINE_MODE_CHIP_NAME] = {
.tag = "[chip_name]",
.parser = parse_chip_name_mode,
},
};
/* check the line starting with '[' -- change the parser mode accodingly */
static int parse_line_mode(char *buf, struct hda_bus *bus)
{
int i;
for (i = 0; i < ARRAY_SIZE(patch_items); i++) {
if (!patch_items[i].tag)
continue;
if (strmatch(buf, patch_items[i].tag))
return i;
if (patch_items[i].alias && strmatch(buf, patch_items[i].alias))
return i;
}
return LINE_MODE_NONE;
}
/* copy one line from the buffer in fw, and update the fields in fw
* return zero if it reaches to the end of the buffer, or non-zero
* if successfully copied a line
*
* the spaces at the beginning and the end of the line are stripped
*/
static int get_line_from_fw(char *buf, int size, size_t *fw_size_p,
const void **fw_data_p)
{
int len;
size_t fw_size = *fw_size_p;
const char *p = *fw_data_p;
while (isspace(*p) && fw_size) {
p++;
fw_size--;
}
if (!fw_size)
return 0;
for (len = 0; len < fw_size; len++) {
if (!*p)
break;
if (*p == '\n') {
p++;
len++;
break;
}
if (len < size)
*buf++ = *p++;
}
*buf = 0;
*fw_size_p = fw_size - len;
*fw_data_p = p;
remove_trail_spaces(buf);
return 1;
}
/**
* snd_hda_load_patch - load a "patch" firmware file and parse it
* @bus: HD-audio bus
* @fw_size: the firmware byte size
* @fw_buf: the firmware data
*/
int snd_hda_load_patch(struct hda_bus *bus, size_t fw_size, const void *fw_buf)
{
char buf[128];
struct hda_codec *codec;
int line_mode;
line_mode = LINE_MODE_NONE;
codec = NULL;
while (get_line_from_fw(buf, sizeof(buf) - 1, &fw_size, &fw_buf)) {
if (!*buf || *buf == '#' || *buf == '\n')
continue;
if (*buf == '[')
line_mode = parse_line_mode(buf, bus);
else if (patch_items[line_mode].parser &&
(codec || line_mode <= LINE_MODE_CODEC))
patch_items[line_mode].parser(buf, bus, &codec);
}
return 0;
}
EXPORT_SYMBOL_GPL(snd_hda_load_patch);
#endif /* CONFIG_SND_HDA_PATCH_LOADER */
/*
* sysfs entries
*/
static struct attribute *hda_dev_attrs[] = {
&dev_attr_vendor_id.attr,
&dev_attr_subsystem_id.attr,
&dev_attr_revision_id.attr,
&dev_attr_afg.attr,
&dev_attr_mfg.attr,
&dev_attr_vendor_name.attr,
&dev_attr_chip_name.attr,
&dev_attr_modelname.attr,
&dev_attr_init_pin_configs.attr,
&dev_attr_driver_pin_configs.attr,
#ifdef CONFIG_PM
&dev_attr_power_on_acct.attr,
&dev_attr_power_off_acct.attr,
#endif
#ifdef CONFIG_SND_HDA_RECONFIG
&dev_attr_init_verbs.attr,
&dev_attr_hints.attr,
&dev_attr_user_pin_configs.attr,
&dev_attr_reconfig.attr,
&dev_attr_clear.attr,
#endif
NULL
};
static struct attribute_group hda_dev_attr_group = {
.attrs = hda_dev_attrs,
};
const struct attribute_group *snd_hda_dev_attr_groups[] = {
&hda_dev_attr_group,
NULL
};
void snd_hda_sysfs_init(struct hda_codec *codec)
{
mutex_init(&codec->user_mutex);
#ifdef CONFIG_SND_HDA_RECONFIG
snd_array_init(&codec->init_verbs, sizeof(struct hda_verb), 32);
snd_array_init(&codec->hints, sizeof(struct hda_hint), 32);
snd_array_init(&codec->user_pins, sizeof(struct hda_pincfg), 16);
#endif
}
void snd_hda_sysfs_clear(struct hda_codec *codec)
{
#ifdef CONFIG_SND_HDA_RECONFIG
int i;
/* clear init verbs */
snd_array_free(&codec->init_verbs);
/* clear hints */
for (i = 0; i < codec->hints.used; i++) {
struct hda_hint *hint = snd_array_elem(&codec->hints, i);
kfree(hint->key); /* we don't need to free hint->val */
}
snd_array_free(&codec->hints);
snd_array_free(&codec->user_pins);
#endif
}
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.