code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
/*
* Copyright (C) 2013 Invensense, Inc.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include <linux/err.h>
#include <linux/delay.h>
#include <linux/sysfs.h>
#include <linux/jiffies.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/kfifo.h>
#include <linux/poll.h>
#include <linux/miscdevice.h>
#include <linux/spinlock.h>
#include "inv_ak09911_iio.h"
#include <linux/iio/sysfs.h>
#include "inv_test/inv_counters.h"
static s64 get_time_ns(void)
{
struct timespec ts;
ktime_get_ts(&ts);
return timespec_to_ns(&ts);
}
/**
* inv_serial_read() - Read one or more bytes from the device registers.
* @st: Device driver instance.
* @reg: First device register to be read from.
* @length: Number of bytes to read.
* @data: Data read from device.
* NOTE: The slave register will not increment when reading from the FIFO.
*/
int inv_serial_read(struct inv_ak09911_state_s *st, u8 reg, u16 length, u8 *data)
{
int result;
INV_I2C_INC_COMPASSWRITE(3);
INV_I2C_INC_COMPASSREAD(length);
result = i2c_smbus_read_i2c_block_data(st->i2c, reg, length, data);
if (result != length) {
if (result < 0)
return result;
else
return -EINVAL;
} else {
return 0;
}
}
/**
* inv_serial_single_write() - Write a byte to a device register.
* @st: Device driver instance.
* @reg: Device register to be written to.
* @data: Byte to write to device.
*/
int inv_serial_single_write(struct inv_ak09911_state_s *st, u8 reg, u8 data)
{
u8 d[1];
d[0] = data;
INV_I2C_INC_COMPASSWRITE(3);
return i2c_smbus_write_i2c_block_data(st->i2c, reg, 1, d);
}
static int ak09911_init(struct inv_ak09911_state_s *st)
{
int result = 0;
unsigned char serial_data[3];
result = inv_serial_single_write(st, AK09911_REG_CNTL,
AK09911_CNTL_MODE_POWER_DOWN);
if (result) {
pr_err("%s, line=%d\n", __func__, __LINE__);
return result;
}
/* Wait at least 100us */
udelay(100);
result = inv_serial_single_write(st, AK09911_REG_CNTL,
AK09911_CNTL_MODE_FUSE_ACCESS);
if (result) {
pr_err("%s, line=%d\n", __func__, __LINE__);
return result;
}
/* Wait at least 200us */
udelay(200);
result = inv_serial_read(st, AK09911_FUSE_ASAX, 3, serial_data);
if (result) {
pr_err("%s, line=%d\n", __func__, __LINE__);
return result;
}
st->asa[0] = serial_data[0];
st->asa[1] = serial_data[1];
st->asa[2] = serial_data[2];
result = inv_serial_single_write(st, AK09911_REG_CNTL,
AK09911_CNTL_MODE_POWER_DOWN);
if (result) {
pr_err("%s, line=%d\n", __func__, __LINE__);
return result;
}
udelay(100);
return result;
}
int ak09911_read(struct inv_ak09911_state_s *st, short rawfixed[3])
{
unsigned char regs[8];
unsigned char *stat = ®s[0];
unsigned char *stat2 = ®s[8];
int result = 0;
int status = 0;
result = inv_serial_read(st, AK09911_REG_ST1, 9, regs);
if (result) {
pr_err("%s, line=%d\n", __func__, __LINE__);
return result;
}
rawfixed[0] = (short)((regs[2]<<8) | regs[1]);
rawfixed[1] = (short)((regs[4]<<8) | regs[3]);
rawfixed[2] = (short)((regs[6]<<8) | regs[5]);
/*
* ST : data ready -
* Measurement has been completed and data is ready to be read.
*/
if (*stat & 0x01)
status = 0;
/*
* ST2 : overflow -
* the sum of the absolute values of all axis |X|+|Y|+|Z| < 2400uT.
* This is likely to happen in presence of an external magnetic
* disturbance; it indicates, the sensor data is incorrect and should
* be ignored.
* An error is returned.
* HOFL bit clears when a new measurement starts.
*/
if (*stat2 & 0x08)
status = 0x08;
/*
* ST : overrun -
* the previous sample was not fetched and lost.
* Valid in continuous measurement mode only.
* In single measurement mode this error should not occour and we
* don't consider this condition an error.
* DOR bit is self-clearing when ST2 or any meas. data register is
* read.
*/
if (*stat & 0x02) {
/* status = INV_ERROR_COMPASS_DATA_UNDERFLOW; */
status = 0;
}
/*
* trigger next measurement if:
* - stat is non zero;
* - if stat is zero and stat2 is non zero.
* Won't trigger if data is not ready and there was no error.
*/
result = inv_serial_single_write(st, AK09911_REG_CNTL,
AK09911_CNTL_MODE_SNG_MEASURE);
if (result) {
pr_err("%s, line=%d\n", __func__, __LINE__);
return result;
}
if (status)
pr_err("%s, line=%d, status=%d\n", __func__, __LINE__, status);
return status;
}
/**
* ak09911_read_raw() - read raw method.
*/
static int ak09911_read_raw(struct iio_dev *indio_dev,
struct iio_chan_spec const *chan,
int *val,
int *val2,
long mask) {
struct inv_ak09911_state_s *st = iio_priv(indio_dev);
int scale = 0;
switch (mask) {
case 0:
if (!(iio_buffer_enabled(indio_dev)))
return -EINVAL;
if (chan->type == IIO_MAGN) {
*val = st->compass_data[chan->channel2 - IIO_MOD_X];
return IIO_VAL_INT;
}
return -EINVAL;
case IIO_CHAN_INFO_SCALE:
scale = 19661;
scale *= (1L << 15);
*val = scale;
return IIO_VAL_INT;
return -EINVAL;
default:
return -EINVAL;
}
}
static ssize_t ak09911_value_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct iio_dev *indio_dev = dev_get_drvdata(dev);
struct inv_ak09911_state_s *st = iio_priv(indio_dev);
short c[3];
mutex_lock(&indio_dev->mlock);
c[0] = st->compass_data[0];
c[1] = st->compass_data[1];
c[2] = st->compass_data[2];
mutex_unlock(&indio_dev->mlock);
return sprintf(buf, "%d, %d, %d\n", c[0], c[1], c[2]);
}
static ssize_t ak09911_rate_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct iio_dev *indio_dev = dev_get_drvdata(dev);
struct inv_ak09911_state_s *st = iio_priv(indio_dev);
/* transform delay in ms to rate */
return sprintf(buf, "%d\n", (1000 / st->delay));
}
/**
* ak09911_matrix_show() - show orientation matrix
*/
static ssize_t ak09911_matrix_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct iio_dev *indio_dev = dev_get_drvdata(dev);
signed char *m;
struct inv_ak09911_state_s *st = iio_priv(indio_dev);
m = st->plat_data.orientation;
return sprintf(buf,
"%d,%d,%d,%d,%d,%d,%d,%d,%d\n",
m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8]);
}
void set_ak09911_enable(struct iio_dev *indio_dev, bool enable)
{
struct inv_ak09911_state_s *st = iio_priv(indio_dev);
int result = 0;
if (enable) {
result = inv_serial_single_write(st, AK09911_REG_CNTL,
AK09911_CNTL_MODE_SNG_MEASURE);
if (result)
pr_err("%s, line=%d\n", __func__, __LINE__);
schedule_delayed_work(&st->work,
msecs_to_jiffies(st->delay));
} else {
cancel_delayed_work_sync(&st->work);
result = inv_serial_single_write(st, AK09911_REG_CNTL,
AK09911_CNTL_MODE_POWER_DOWN);
if (result)
pr_err("%s, line=%d\n", __func__, __LINE__);
mdelay(1); /* wait at least 100us */
}
}
static ssize_t ak09911_rate_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
unsigned long data;
int error;
struct iio_dev *indio_dev = dev_get_drvdata(dev);
struct inv_ak09911_state_s *st = iio_priv(indio_dev);
error = kstrtoul(buf, 10, &data);
if (error)
return error;
/* transform rate to delay in ms */
data = 1000 / data;
if (data > AK09911_MAX_DELAY)
data = AK09911_MAX_DELAY;
if (data < AK09911_MIN_DELAY)
data = AK09911_MIN_DELAY;
st->delay = (unsigned int) data;
return count;
}
static void ak09911_work_func(struct work_struct *work)
{
struct inv_ak09911_state_s *st =
container_of((struct delayed_work *)work,
struct inv_ak09911_state_s, work);
struct iio_dev *indio_dev = iio_priv_to_dev(st);
unsigned long delay = msecs_to_jiffies(st->delay);
mutex_lock(&indio_dev->mlock);
if (!(iio_buffer_enabled(indio_dev)))
goto error_ret;
st->timestamp = get_time_ns();
schedule_delayed_work(&st->work, delay);
inv_read_ak09911_fifo(indio_dev);
INV_I2C_INC_COMPASSIRQ();
error_ret:
mutex_unlock(&indio_dev->mlock);
}
static const struct iio_chan_spec compass_channels[] = {
{
.type = IIO_MAGN,
.modified = 1,
.channel2 = IIO_MOD_X,
.info_mask = IIO_CHAN_INFO_SCALE_SHARED_BIT,
.scan_index = INV_AK09911_SCAN_MAGN_X,
.scan_type = IIO_ST('s', 16, 16, 0)
}, {
.type = IIO_MAGN,
.modified = 1,
.channel2 = IIO_MOD_Y,
.info_mask = IIO_CHAN_INFO_SCALE_SHARED_BIT,
.scan_index = INV_AK09911_SCAN_MAGN_Y,
.scan_type = IIO_ST('s', 16, 16, 0)
}, {
.type = IIO_MAGN,
.modified = 1,
.channel2 = IIO_MOD_Z,
.info_mask = IIO_CHAN_INFO_SCALE_SHARED_BIT,
.scan_index = INV_AK09911_SCAN_MAGN_Z,
.scan_type = IIO_ST('s', 16, 16, 0)
},
IIO_CHAN_SOFT_TIMESTAMP(INV_AK09911_SCAN_TIMESTAMP)
};
static DEVICE_ATTR(value, S_IRUGO, ak09911_value_show, NULL);
static DEVICE_ATTR(sampling_frequency, S_IRUGO | S_IWUSR, ak09911_rate_show,
ak09911_rate_store);
static DEVICE_ATTR(compass_matrix, S_IRUGO, ak09911_matrix_show, NULL);
static struct attribute *inv_ak09911_attributes[] = {
&dev_attr_value.attr,
&dev_attr_sampling_frequency.attr,
&dev_attr_compass_matrix.attr,
NULL,
};
static const struct attribute_group inv_attribute_group = {
.name = "ak09911",
.attrs = inv_ak09911_attributes
};
static const struct iio_info ak09911_info = {
.driver_module = THIS_MODULE,
.read_raw = &ak09911_read_raw,
.attrs = &inv_attribute_group,
};
/*constant IIO attribute */
/**
* inv_ak09911_probe() - probe function.
*/
static int inv_ak09911_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct inv_ak09911_state_s *st;
struct iio_dev *indio_dev;
int result;
if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
result = -ENODEV;
goto out_no_free;
}
indio_dev = iio_device_alloc(sizeof(*st));
if (indio_dev == NULL) {
result = -ENOMEM;
goto out_no_free;
}
st = iio_priv(indio_dev);
st->i2c = client;
st->sl_handle = client->adapter;
st->plat_data =
*(struct mpu_platform_data *)dev_get_platdata(&client->dev);
st->i2c_addr = client->addr;
st->delay = AK09911_DEFAULT_DELAY;
st->compass_id = id->driver_data;
i2c_set_clientdata(client, indio_dev);
result = ak09911_init(st);
if (result)
goto out_free;
indio_dev->dev.parent = &client->dev;
indio_dev->name = id->name;
indio_dev->channels = compass_channels;
indio_dev->num_channels = ARRAY_SIZE(compass_channels);
indio_dev->info = &ak09911_info;
indio_dev->modes = INDIO_DIRECT_MODE;
indio_dev->currentmode = INDIO_DIRECT_MODE;
result = inv_ak09911_configure_ring(indio_dev);
if (result)
goto out_free;
result = iio_buffer_register(indio_dev, indio_dev->channels,
indio_dev->num_channels);
if (result)
goto out_unreg_ring;
result = inv_ak09911_probe_trigger(indio_dev);
if (result)
goto out_remove_ring;
result = iio_device_register(indio_dev);
if (result)
goto out_remove_trigger;
INIT_DELAYED_WORK(&st->work, ak09911_work_func);
pr_info("%s: Probe name %s\n", __func__, id->name);
return 0;
out_remove_trigger:
if (indio_dev->modes & INDIO_BUFFER_TRIGGERED)
inv_ak09911_remove_trigger(indio_dev);
out_remove_ring:
iio_buffer_unregister(indio_dev);
out_unreg_ring:
inv_ak09911_unconfigure_ring(indio_dev);
out_free:
iio_device_free(indio_dev);
out_no_free:
dev_err(&client->adapter->dev, "%s failed %d\n", __func__, result);
return -EIO;
}
/**
* inv_ak09911_remove() - remove function.
*/
static int inv_ak09911_remove(struct i2c_client *client)
{
struct iio_dev *indio_dev = i2c_get_clientdata(client);
struct inv_ak09911_state_s *st = iio_priv(indio_dev);
cancel_delayed_work_sync(&st->work);
iio_device_unregister(indio_dev);
inv_ak09911_remove_trigger(indio_dev);
iio_buffer_unregister(indio_dev);
inv_ak09911_unconfigure_ring(indio_dev);
iio_device_free(indio_dev);
dev_info(&client->adapter->dev, "inv-ak09911-iio module removed.\n");
return 0;
}
static const unsigned short normal_i2c[] = { I2C_CLIENT_END };
/* device id table is used to identify what device can be
* supported by this driver
*/
static const struct i2c_device_id inv_ak09911_id[] = {
{"akm9911", COMPASS_ID_AK09911},
{}
};
MODULE_DEVICE_TABLE(i2c, inv_ak09911_id);
static struct i2c_driver inv_ak09911_driver = {
.class = I2C_CLASS_HWMON,
.probe = inv_ak09911_probe,
.remove = inv_ak09911_remove,
.id_table = inv_ak09911_id,
.driver = {
.owner = THIS_MODULE,
.name = "inv-ak09911-iio",
},
.address_list = normal_i2c,
};
static int __init inv_ak09911_init(void)
{
int result = i2c_add_driver(&inv_ak09911_driver);
if (result) {
pr_err("%s failed\n", __func__);
return result;
}
return 0;
}
static void __exit inv_ak09911_exit(void)
{
i2c_del_driver(&inv_ak09911_driver);
}
module_init(inv_ak09911_init);
module_exit(inv_ak09911_exit);
MODULE_AUTHOR("Invensense Corporation");
MODULE_DESCRIPTION("Invensense device driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("inv-ak09911-iio");
|
gromaudio/linux-imx6-31053
|
drivers/staging/iio/magnetometer/inv_compass/inv_ak09911_core.c
|
C
|
gpl-2.0
| 13,357
|
using UnityEngine;
using System;
using LuaInterface;
using SLua;
using System.Collections.Generic;
public class Lua_UnityEngine_MaterialPropertyBlock : LuaObject {
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int constructor(IntPtr l) {
try {
UnityEngine.MaterialPropertyBlock o;
o=new UnityEngine.MaterialPropertyBlock();
pushValue(l,true);
pushValue(l,o);
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int SetFloat(IntPtr l) {
try {
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(int),typeof(float))){
UnityEngine.MaterialPropertyBlock self=(UnityEngine.MaterialPropertyBlock)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
System.Single a2;
checkType(l,3,out a2);
self.SetFloat(a1,a2);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(string),typeof(float))){
UnityEngine.MaterialPropertyBlock self=(UnityEngine.MaterialPropertyBlock)checkSelf(l);
System.String a1;
checkType(l,2,out a1);
System.Single a2;
checkType(l,3,out a2);
self.SetFloat(a1,a2);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int SetVector(IntPtr l) {
try {
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(int),typeof(UnityEngine.Vector4))){
UnityEngine.MaterialPropertyBlock self=(UnityEngine.MaterialPropertyBlock)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
UnityEngine.Vector4 a2;
checkType(l,3,out a2);
self.SetVector(a1,a2);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(string),typeof(UnityEngine.Vector4))){
UnityEngine.MaterialPropertyBlock self=(UnityEngine.MaterialPropertyBlock)checkSelf(l);
System.String a1;
checkType(l,2,out a1);
UnityEngine.Vector4 a2;
checkType(l,3,out a2);
self.SetVector(a1,a2);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int SetColor(IntPtr l) {
try {
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(int),typeof(UnityEngine.Color))){
UnityEngine.MaterialPropertyBlock self=(UnityEngine.MaterialPropertyBlock)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
UnityEngine.Color a2;
checkType(l,3,out a2);
self.SetColor(a1,a2);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(string),typeof(UnityEngine.Color))){
UnityEngine.MaterialPropertyBlock self=(UnityEngine.MaterialPropertyBlock)checkSelf(l);
System.String a1;
checkType(l,2,out a1);
UnityEngine.Color a2;
checkType(l,3,out a2);
self.SetColor(a1,a2);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int SetMatrix(IntPtr l) {
try {
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(int),typeof(UnityEngine.Matrix4x4))){
UnityEngine.MaterialPropertyBlock self=(UnityEngine.MaterialPropertyBlock)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
UnityEngine.Matrix4x4 a2;
checkValueType(l,3,out a2);
self.SetMatrix(a1,a2);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(string),typeof(UnityEngine.Matrix4x4))){
UnityEngine.MaterialPropertyBlock self=(UnityEngine.MaterialPropertyBlock)checkSelf(l);
System.String a1;
checkType(l,2,out a1);
UnityEngine.Matrix4x4 a2;
checkValueType(l,3,out a2);
self.SetMatrix(a1,a2);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int SetTexture(IntPtr l) {
try {
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(int),typeof(UnityEngine.Texture))){
UnityEngine.MaterialPropertyBlock self=(UnityEngine.MaterialPropertyBlock)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
UnityEngine.Texture a2;
checkType(l,3,out a2);
self.SetTexture(a1,a2);
pushValue(l,true);
return 1;
}
else if(matchType(l,argc,2,typeof(string),typeof(UnityEngine.Texture))){
UnityEngine.MaterialPropertyBlock self=(UnityEngine.MaterialPropertyBlock)checkSelf(l);
System.String a1;
checkType(l,2,out a1);
UnityEngine.Texture a2;
checkType(l,3,out a2);
self.SetTexture(a1,a2);
pushValue(l,true);
return 1;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int GetFloat(IntPtr l) {
try {
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(int))){
UnityEngine.MaterialPropertyBlock self=(UnityEngine.MaterialPropertyBlock)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
var ret=self.GetFloat(a1);
pushValue(l,true);
pushValue(l,ret);
return 2;
}
else if(matchType(l,argc,2,typeof(string))){
UnityEngine.MaterialPropertyBlock self=(UnityEngine.MaterialPropertyBlock)checkSelf(l);
System.String a1;
checkType(l,2,out a1);
var ret=self.GetFloat(a1);
pushValue(l,true);
pushValue(l,ret);
return 2;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int GetVector(IntPtr l) {
try {
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(int))){
UnityEngine.MaterialPropertyBlock self=(UnityEngine.MaterialPropertyBlock)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
var ret=self.GetVector(a1);
pushValue(l,true);
pushValue(l,ret);
return 2;
}
else if(matchType(l,argc,2,typeof(string))){
UnityEngine.MaterialPropertyBlock self=(UnityEngine.MaterialPropertyBlock)checkSelf(l);
System.String a1;
checkType(l,2,out a1);
var ret=self.GetVector(a1);
pushValue(l,true);
pushValue(l,ret);
return 2;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int GetMatrix(IntPtr l) {
try {
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(int))){
UnityEngine.MaterialPropertyBlock self=(UnityEngine.MaterialPropertyBlock)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
var ret=self.GetMatrix(a1);
pushValue(l,true);
pushValue(l,ret);
return 2;
}
else if(matchType(l,argc,2,typeof(string))){
UnityEngine.MaterialPropertyBlock self=(UnityEngine.MaterialPropertyBlock)checkSelf(l);
System.String a1;
checkType(l,2,out a1);
var ret=self.GetMatrix(a1);
pushValue(l,true);
pushValue(l,ret);
return 2;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int GetTexture(IntPtr l) {
try {
int argc = LuaDLL.lua_gettop(l);
if(matchType(l,argc,2,typeof(int))){
UnityEngine.MaterialPropertyBlock self=(UnityEngine.MaterialPropertyBlock)checkSelf(l);
System.Int32 a1;
checkType(l,2,out a1);
var ret=self.GetTexture(a1);
pushValue(l,true);
pushValue(l,ret);
return 2;
}
else if(matchType(l,argc,2,typeof(string))){
UnityEngine.MaterialPropertyBlock self=(UnityEngine.MaterialPropertyBlock)checkSelf(l);
System.String a1;
checkType(l,2,out a1);
var ret=self.GetTexture(a1);
pushValue(l,true);
pushValue(l,ret);
return 2;
}
pushValue(l,false);
LuaDLL.lua_pushstring(l,"No matched override function to call");
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int Clear(IntPtr l) {
try {
UnityEngine.MaterialPropertyBlock self=(UnityEngine.MaterialPropertyBlock)checkSelf(l);
self.Clear();
pushValue(l,true);
return 1;
}
catch(Exception e) {
return error(l,e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int get_isEmpty(IntPtr l) {
try {
UnityEngine.MaterialPropertyBlock self=(UnityEngine.MaterialPropertyBlock)checkSelf(l);
pushValue(l,true);
pushValue(l,self.isEmpty);
return 2;
}
catch(Exception e) {
return error(l,e);
}
}
static public void reg(IntPtr l) {
getTypeTable(l,"UnityEngine.MaterialPropertyBlock");
addMember(l,SetFloat);
addMember(l,SetVector);
addMember(l,SetColor);
addMember(l,SetMatrix);
addMember(l,SetTexture);
addMember(l,GetFloat);
addMember(l,GetVector);
addMember(l,GetMatrix);
addMember(l,GetTexture);
addMember(l,Clear);
addMember(l,"isEmpty",get_isEmpty,null,true);
createTypeMetatable(l,constructor, typeof(UnityEngine.MaterialPropertyBlock));
}
}
|
xclouder/godbattle
|
Assets/Slua/LuaObject/Unity/Lua_UnityEngine_MaterialPropertyBlock.cs
|
C#
|
gpl-2.0
| 9,839
|
using SoftwareKobo.CnblogsAPI.Model;
using SoftwareKobo.CnblogsAPI.Service;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace SoftwareKobo.CnblogsAPI.Extension
{
/// <summary>
/// 文章扩展。
/// </summary>
public static class ArticleExtension
{
/// <summary>
/// 获取文章评论。
/// </summary>
/// <param name="article">文章。</param>
/// <param name="pageIndex">第几页,从 1 开始。</param>
/// <param name="pageSize">每页条数。</param>
/// <returns>评论列表。</returns>
/// <exception cref="ArgumentNullException">文章为 null。</exception>
public static async Task<IEnumerable<ArticleComment>> CommentAsync(this Article article, int pageIndex, int pageSize)
{
if (article == null)
{
throw new ArgumentNullException(nameof(article));
}
return await BlogService.CommentAsync(article.Id, pageIndex, pageSize);
}
}
}
|
h82258652/SoftwareKobo.CnblogsAPI
|
SoftwareKobo.CnblogsAPI/SoftwareKobo.CnblogsAPI/Extension/ArticleExtension.cs
|
C#
|
gpl-2.0
| 1,067
|
<?php
/**
* ahis ahisuser Class
*
* ahis user class
*
* PHP version 5
*
* 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.
*
* @category Chisimba
* @package ahis
* @author Nic Appleby <nappleby@uwc.ac.za>
* @copyright 2009 AVOIR
* @license http://www.gnu.org/licenses/gpl-2.0.txt The GNU General Public License
* @version $Id: ahisuser_class_inc.php 13811 2009-06-30 14:38:44Z nic $
* @link http://avoir.uwc.ac.za
*/
// security check - must be included in all scripts
if (!
/**
* Description for $GLOBALS
* @global entry point $GLOBALS['kewl_entry_point_run']
* @name $kewl_entry_point_run
*/
$GLOBALS['kewl_entry_point_run']) {
die("You cannot view this page directly");
}
// end security check
/**
* ahis ahisuser Class
*
* class to access additional user info table
*
* @category Chisimba
* @package ahis
* @author Nic Appleby <nappleby@uwc.ac.za>
* @copyright 2009 AVOIR
* @license http://www.gnu.org/licenses/gpl-2.0.txt The GNU General Public License
* @version $Id: ahisuser_class_inc.php 13811 2009-06-30 14:38:44Z nic $
* @link http://avoir.uwc.ac.za
*/
class ahisuser extends dbtable {
/**
* Standard Chisimba init method
*
* @return void
* @access public
*/
public function init() {
try {
parent::init('tbl_ahis_users');
$this->objUser = $this->getObject('user','security');
$this->objTerritory = $this->getObject('territory');
}
catch (customException $e)
{
customException::cleanUp();
exit;
}
}
/**
* Method to return a user's territory
*
* @param string $userId the id of the user, leave out for current user
* @return string the id of the territory
*/
public function getGeo2Id($userId = NULL) {
$id = $this->objUser->PKId($userId);
$row = $this->getRow('id', $id);
$locationRow = $this->objTerritory->getRow('id', $row['locationid']);
return $locationRow['geo2id'];
}
/**
* Method to return a list of all ARIS users
*
* @return array ARIS users
*/
public function getList() {
$sql = "SELECT u.userid AS userid, CONCAT(u.firstname,' ',u.surname) AS name
FROM tbl_users AS u, tbl_ahis_users AS au
WHERE u.id = au.id
ORDER BY name";
return $this->objUser->getArray($sql);
}
/**
* Method to return a list of all ARIS users of a certain role
*
* @param string $role The role to be searched for
* @return array ARIS users
*/
public function getListByRole($role) {
$sql = "SELECT u.userid AS userid, CONCAT(u.firstname,' ',u.surname) AS name
FROM tbl_users AS u, tbl_ahis_users AS au
WHERE u.id = au.id AND au.roleid = '$role'
ORDER BY name";
return $this->objUser->getArray($sql);
}
/**
* Method to get contact info for user
*
* @param string $userId The id of the user
* @return array of contact details
*/
public function getUserContact($userId) {
$sql = "SELECT fax, phone, email
FROM tbl_ahis_users AS au, tbl_users AS u
WHERE u.id = au.id AND u.userid = '$userId'";
return $this->getArray($sql);
}
/**
* Method to check whether a user is a asuperuser
*
* @param string $userId The user id of the user to check
* @return true|false
*/
public function isSuperUser($userId) {
$id = $this->objUser->PKId($userId);
$row = $this->getRow('id', $id);
return ($row['superuser'] == 1) || ($userId == 1);
}
}
|
chisimba/modules
|
openaris/classes/ahisuser_class_inc.php
|
PHP
|
gpl-2.0
| 4,051
|
using System;
using System.Runtime.Serialization;
namespace Nexus.Client.ModRepositories
{
/// <summary>
/// The exception that is thrown if a repository is not available.
/// </summary>
[Serializable]
public class RepositoryUnavailableException : Exception
{
/// <summary>
/// The default constructor.
/// </summary>
public RepositoryUnavailableException()
{
}
/// <summary>
/// A simple contructor that sets the exception's message.
/// </summary>
/// <param name="message">The exception's message.</param>
public RepositoryUnavailableException(string message)
: base(message)
{
}
/// <summary>
/// A simple constructor the sets the exception's message and inner exception.
/// </summary>
/// <param name="message">The exception's message.</param>
/// <param name="inner">The ineer exception.</param>
public RepositoryUnavailableException(string message, Exception inner)
: base(message, inner)
{
}
/// <summary>
/// The serializing constructor.
/// </summary>
/// <param name="info">The info from which to deserialize the object.</param>
/// <param name="context">The context from which to deserialize.</param>
protected RepositoryUnavailableException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
}
|
reactormonk/nmm
|
NexusClient/ModRepositories/RepositoryUnavailableException.cs
|
C#
|
gpl-2.0
| 1,366
|
/*******************************************************************************
Intel 10 Gigabit PCI Express Linux driver
Copyright(c) 1999 - 2011 Intel Corporation.
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Contact Information:
e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
#include <linux/pci.h>
#include <linux/delay.h>
#include <linux/sched.h>
#include <linux/netdevice.h>
#include "ixgbe.h"
#include "ixgbe_common.h"
#include "ixgbe_phy.h"
static s32 ixgbe_acquire_eeprom(struct ixgbe_hw *hw);
static s32 ixgbe_get_eeprom_semaphore(struct ixgbe_hw *hw);
static void ixgbe_release_eeprom_semaphore(struct ixgbe_hw *hw);
static s32 ixgbe_ready_eeprom(struct ixgbe_hw *hw);
static void ixgbe_standby_eeprom(struct ixgbe_hw *hw);
static void ixgbe_shift_out_eeprom_bits(struct ixgbe_hw *hw, u16 data,
u16 count);
static u16 ixgbe_shift_in_eeprom_bits(struct ixgbe_hw *hw, u16 count);
static void ixgbe_raise_eeprom_clk(struct ixgbe_hw *hw, u32 *eec);
static void ixgbe_lower_eeprom_clk(struct ixgbe_hw *hw, u32 *eec);
static void ixgbe_release_eeprom(struct ixgbe_hw *hw);
static s32 ixgbe_mta_vector(struct ixgbe_hw *hw, u8 *mc_addr);
static s32 ixgbe_fc_autoneg_fiber(struct ixgbe_hw *hw);
static s32 ixgbe_fc_autoneg_backplane(struct ixgbe_hw *hw);
static s32 ixgbe_fc_autoneg_copper(struct ixgbe_hw *hw);
static s32 ixgbe_device_supports_autoneg_fc(struct ixgbe_hw *hw);
static s32 ixgbe_negotiate_fc(struct ixgbe_hw *hw, u32 adv_reg, u32 lp_reg,
u32 adv_sym, u32 adv_asm, u32 lp_sym, u32 lp_asm);
static s32 ixgbe_setup_fc(struct ixgbe_hw *hw, s32 packetbuf_num);
static s32 ixgbe_poll_eerd_eewr_done(struct ixgbe_hw *hw, u32 ee_reg);
static s32 ixgbe_read_eeprom_buffer_bit_bang(struct ixgbe_hw *hw, u16 offset,
u16 words, u16 *data);
static s32 ixgbe_write_eeprom_buffer_bit_bang(struct ixgbe_hw *hw, u16 offset,
u16 words, u16 *data);
static s32 ixgbe_detect_eeprom_page_size_generic(struct ixgbe_hw *hw,
u16 offset);
/**
* ixgbe_start_hw_generic - Prepare hardware for Tx/Rx
* @hw: pointer to hardware structure
*
* Starts the hardware by filling the bus info structure and media type, clears
* all on chip counters, initializes receive address registers, multicast
* table, VLAN filter table, calls routine to set up link and flow control
* settings, and leaves transmit and receive units disabled and uninitialized
**/
s32 ixgbe_start_hw_generic(struct ixgbe_hw *hw)
{
u32 ctrl_ext;
/* Set the media type */
hw->phy.media_type = hw->mac.ops.get_media_type(hw);
/* Identify the PHY */
hw->phy.ops.identify(hw);
/* Clear the VLAN filter table */
hw->mac.ops.clear_vfta(hw);
/* Clear statistics registers */
hw->mac.ops.clear_hw_cntrs(hw);
/* Set No Snoop Disable */
ctrl_ext = IXGBE_READ_REG(hw, IXGBE_CTRL_EXT);
ctrl_ext |= IXGBE_CTRL_EXT_NS_DIS;
IXGBE_WRITE_REG(hw, IXGBE_CTRL_EXT, ctrl_ext);
IXGBE_WRITE_FLUSH(hw);
/* Setup flow control */
ixgbe_setup_fc(hw, 0);
/* Clear adapter stopped flag */
hw->adapter_stopped = false;
return 0;
}
/**
* ixgbe_start_hw_gen2 - Init sequence for common device family
* @hw: pointer to hw structure
*
* Performs the init sequence common to the second generation
* of 10 GbE devices.
* Devices in the second generation:
* 82599
* X540
**/
s32 ixgbe_start_hw_gen2(struct ixgbe_hw *hw)
{
u32 i;
u32 regval;
/* Clear the rate limiters */
for (i = 0; i < hw->mac.max_tx_queues; i++) {
IXGBE_WRITE_REG(hw, IXGBE_RTTDQSEL, i);
IXGBE_WRITE_REG(hw, IXGBE_RTTBCNRC, 0);
}
IXGBE_WRITE_FLUSH(hw);
/* Disable relaxed ordering */
for (i = 0; i < hw->mac.max_tx_queues; i++) {
regval = IXGBE_READ_REG(hw, IXGBE_DCA_TXCTRL_82599(i));
regval &= ~IXGBE_DCA_TXCTRL_TX_WB_RO_EN;
IXGBE_WRITE_REG(hw, IXGBE_DCA_TXCTRL_82599(i), regval);
}
for (i = 0; i < hw->mac.max_rx_queues; i++) {
regval = IXGBE_READ_REG(hw, IXGBE_DCA_RXCTRL(i));
regval &= ~(IXGBE_DCA_RXCTRL_DESC_WRO_EN |
IXGBE_DCA_RXCTRL_DESC_HSRO_EN);
IXGBE_WRITE_REG(hw, IXGBE_DCA_RXCTRL(i), regval);
}
return 0;
}
/**
* ixgbe_init_hw_generic - Generic hardware initialization
* @hw: pointer to hardware structure
*
* Initialize the hardware by resetting the hardware, filling the bus info
* structure and media type, clears all on chip counters, initializes receive
* address registers, multicast table, VLAN filter table, calls routine to set
* up link and flow control settings, and leaves transmit and receive units
* disabled and uninitialized
**/
s32 ixgbe_init_hw_generic(struct ixgbe_hw *hw)
{
s32 status;
/* Reset the hardware */
status = hw->mac.ops.reset_hw(hw);
if (status == 0) {
/* Start the HW */
status = hw->mac.ops.start_hw(hw);
}
return status;
}
/**
* ixgbe_clear_hw_cntrs_generic - Generic clear hardware counters
* @hw: pointer to hardware structure
*
* Clears all hardware statistics counters by reading them from the hardware
* Statistics counters are clear on read.
**/
s32 ixgbe_clear_hw_cntrs_generic(struct ixgbe_hw *hw)
{
u16 i = 0;
IXGBE_READ_REG(hw, IXGBE_CRCERRS);
IXGBE_READ_REG(hw, IXGBE_ILLERRC);
IXGBE_READ_REG(hw, IXGBE_ERRBC);
IXGBE_READ_REG(hw, IXGBE_MSPDC);
for (i = 0; i < 8; i++)
IXGBE_READ_REG(hw, IXGBE_MPC(i));
IXGBE_READ_REG(hw, IXGBE_MLFC);
IXGBE_READ_REG(hw, IXGBE_MRFC);
IXGBE_READ_REG(hw, IXGBE_RLEC);
IXGBE_READ_REG(hw, IXGBE_LXONTXC);
IXGBE_READ_REG(hw, IXGBE_LXOFFTXC);
if (hw->mac.type >= ixgbe_mac_82599EB) {
IXGBE_READ_REG(hw, IXGBE_LXONRXCNT);
IXGBE_READ_REG(hw, IXGBE_LXOFFRXCNT);
} else {
IXGBE_READ_REG(hw, IXGBE_LXONRXC);
IXGBE_READ_REG(hw, IXGBE_LXOFFRXC);
}
for (i = 0; i < 8; i++) {
IXGBE_READ_REG(hw, IXGBE_PXONTXC(i));
IXGBE_READ_REG(hw, IXGBE_PXOFFTXC(i));
if (hw->mac.type >= ixgbe_mac_82599EB) {
IXGBE_READ_REG(hw, IXGBE_PXONRXCNT(i));
IXGBE_READ_REG(hw, IXGBE_PXOFFRXCNT(i));
} else {
IXGBE_READ_REG(hw, IXGBE_PXONRXC(i));
IXGBE_READ_REG(hw, IXGBE_PXOFFRXC(i));
}
}
if (hw->mac.type >= ixgbe_mac_82599EB)
for (i = 0; i < 8; i++)
IXGBE_READ_REG(hw, IXGBE_PXON2OFFCNT(i));
IXGBE_READ_REG(hw, IXGBE_PRC64);
IXGBE_READ_REG(hw, IXGBE_PRC127);
IXGBE_READ_REG(hw, IXGBE_PRC255);
IXGBE_READ_REG(hw, IXGBE_PRC511);
IXGBE_READ_REG(hw, IXGBE_PRC1023);
IXGBE_READ_REG(hw, IXGBE_PRC1522);
IXGBE_READ_REG(hw, IXGBE_GPRC);
IXGBE_READ_REG(hw, IXGBE_BPRC);
IXGBE_READ_REG(hw, IXGBE_MPRC);
IXGBE_READ_REG(hw, IXGBE_GPTC);
IXGBE_READ_REG(hw, IXGBE_GORCL);
IXGBE_READ_REG(hw, IXGBE_GORCH);
IXGBE_READ_REG(hw, IXGBE_GOTCL);
IXGBE_READ_REG(hw, IXGBE_GOTCH);
for (i = 0; i < 8; i++)
IXGBE_READ_REG(hw, IXGBE_RNBC(i));
IXGBE_READ_REG(hw, IXGBE_RUC);
IXGBE_READ_REG(hw, IXGBE_RFC);
IXGBE_READ_REG(hw, IXGBE_ROC);
IXGBE_READ_REG(hw, IXGBE_RJC);
IXGBE_READ_REG(hw, IXGBE_MNGPRC);
IXGBE_READ_REG(hw, IXGBE_MNGPDC);
IXGBE_READ_REG(hw, IXGBE_MNGPTC);
IXGBE_READ_REG(hw, IXGBE_TORL);
IXGBE_READ_REG(hw, IXGBE_TORH);
IXGBE_READ_REG(hw, IXGBE_TPR);
IXGBE_READ_REG(hw, IXGBE_TPT);
IXGBE_READ_REG(hw, IXGBE_PTC64);
IXGBE_READ_REG(hw, IXGBE_PTC127);
IXGBE_READ_REG(hw, IXGBE_PTC255);
IXGBE_READ_REG(hw, IXGBE_PTC511);
IXGBE_READ_REG(hw, IXGBE_PTC1023);
IXGBE_READ_REG(hw, IXGBE_PTC1522);
IXGBE_READ_REG(hw, IXGBE_MPTC);
IXGBE_READ_REG(hw, IXGBE_BPTC);
for (i = 0; i < 16; i++) {
IXGBE_READ_REG(hw, IXGBE_QPRC(i));
IXGBE_READ_REG(hw, IXGBE_QPTC(i));
if (hw->mac.type >= ixgbe_mac_82599EB) {
IXGBE_READ_REG(hw, IXGBE_QBRC_L(i));
IXGBE_READ_REG(hw, IXGBE_QBRC_H(i));
IXGBE_READ_REG(hw, IXGBE_QBTC_L(i));
IXGBE_READ_REG(hw, IXGBE_QBTC_H(i));
IXGBE_READ_REG(hw, IXGBE_QPRDC(i));
} else {
IXGBE_READ_REG(hw, IXGBE_QBRC(i));
IXGBE_READ_REG(hw, IXGBE_QBTC(i));
}
}
if (hw->mac.type == ixgbe_mac_X540) {
if (hw->phy.id == 0)
hw->phy.ops.identify(hw);
hw->phy.ops.read_reg(hw, 0x3, IXGBE_PCRC8ECL, &i);
hw->phy.ops.read_reg(hw, 0x3, IXGBE_PCRC8ECH, &i);
hw->phy.ops.read_reg(hw, 0x3, IXGBE_LDPCECL, &i);
hw->phy.ops.read_reg(hw, 0x3, IXGBE_LDPCECH, &i);
}
return 0;
}
/**
* ixgbe_read_pba_string_generic - Reads part number string from EEPROM
* @hw: pointer to hardware structure
* @pba_num: stores the part number string from the EEPROM
* @pba_num_size: part number string buffer length
*
* Reads the part number string from the EEPROM.
**/
s32 ixgbe_read_pba_string_generic(struct ixgbe_hw *hw, u8 *pba_num,
u32 pba_num_size)
{
s32 ret_val;
u16 data;
u16 pba_ptr;
u16 offset;
u16 length;
if (pba_num == NULL) {
hw_dbg(hw, "PBA string buffer was null\n");
return IXGBE_ERR_INVALID_ARGUMENT;
}
ret_val = hw->eeprom.ops.read(hw, IXGBE_PBANUM0_PTR, &data);
if (ret_val) {
hw_dbg(hw, "NVM Read Error\n");
return ret_val;
}
ret_val = hw->eeprom.ops.read(hw, IXGBE_PBANUM1_PTR, &pba_ptr);
if (ret_val) {
hw_dbg(hw, "NVM Read Error\n");
return ret_val;
}
/*
* if data is not ptr guard the PBA must be in legacy format which
* means pba_ptr is actually our second data word for the PBA number
* and we can decode it into an ascii string
*/
if (data != IXGBE_PBANUM_PTR_GUARD) {
hw_dbg(hw, "NVM PBA number is not stored as string\n");
/* we will need 11 characters to store the PBA */
if (pba_num_size < 11) {
hw_dbg(hw, "PBA string buffer too small\n");
return IXGBE_ERR_NO_SPACE;
}
/* extract hex string from data and pba_ptr */
pba_num[0] = (data >> 12) & 0xF;
pba_num[1] = (data >> 8) & 0xF;
pba_num[2] = (data >> 4) & 0xF;
pba_num[3] = data & 0xF;
pba_num[4] = (pba_ptr >> 12) & 0xF;
pba_num[5] = (pba_ptr >> 8) & 0xF;
pba_num[6] = '-';
pba_num[7] = 0;
pba_num[8] = (pba_ptr >> 4) & 0xF;
pba_num[9] = pba_ptr & 0xF;
/* put a null character on the end of our string */
pba_num[10] = '\0';
/* switch all the data but the '-' to hex char */
for (offset = 0; offset < 10; offset++) {
if (pba_num[offset] < 0xA)
pba_num[offset] += '0';
else if (pba_num[offset] < 0x10)
pba_num[offset] += 'A' - 0xA;
}
return 0;
}
ret_val = hw->eeprom.ops.read(hw, pba_ptr, &length);
if (ret_val) {
hw_dbg(hw, "NVM Read Error\n");
return ret_val;
}
if (length == 0xFFFF || length == 0) {
hw_dbg(hw, "NVM PBA number section invalid length\n");
return IXGBE_ERR_PBA_SECTION;
}
/* check if pba_num buffer is big enough */
if (pba_num_size < (((u32)length * 2) - 1)) {
hw_dbg(hw, "PBA string buffer too small\n");
return IXGBE_ERR_NO_SPACE;
}
/* trim pba length from start of string */
pba_ptr++;
length--;
for (offset = 0; offset < length; offset++) {
ret_val = hw->eeprom.ops.read(hw, pba_ptr + offset, &data);
if (ret_val) {
hw_dbg(hw, "NVM Read Error\n");
return ret_val;
}
pba_num[offset * 2] = (u8)(data >> 8);
pba_num[(offset * 2) + 1] = (u8)(data & 0xFF);
}
pba_num[offset * 2] = '\0';
return 0;
}
/**
* ixgbe_get_mac_addr_generic - Generic get MAC address
* @hw: pointer to hardware structure
* @mac_addr: Adapter MAC address
*
* Reads the adapter's MAC address from first Receive Address Register (RAR0)
* A reset of the adapter must be performed prior to calling this function
* in order for the MAC address to have been loaded from the EEPROM into RAR0
**/
s32 ixgbe_get_mac_addr_generic(struct ixgbe_hw *hw, u8 *mac_addr)
{
u32 rar_high;
u32 rar_low;
u16 i;
rar_high = IXGBE_READ_REG(hw, IXGBE_RAH(0));
rar_low = IXGBE_READ_REG(hw, IXGBE_RAL(0));
for (i = 0; i < 4; i++)
mac_addr[i] = (u8)(rar_low >> (i*8));
for (i = 0; i < 2; i++)
mac_addr[i+4] = (u8)(rar_high >> (i*8));
return 0;
}
/**
* ixgbe_get_bus_info_generic - Generic set PCI bus info
* @hw: pointer to hardware structure
*
* Sets the PCI bus info (speed, width, type) within the ixgbe_hw structure
**/
s32 ixgbe_get_bus_info_generic(struct ixgbe_hw *hw)
{
struct ixgbe_adapter *adapter = hw->back;
struct ixgbe_mac_info *mac = &hw->mac;
u16 link_status;
hw->bus.type = ixgbe_bus_type_pci_express;
/* Get the negotiated link width and speed from PCI config space */
pci_read_config_word(adapter->pdev, IXGBE_PCI_LINK_STATUS,
&link_status);
switch (link_status & IXGBE_PCI_LINK_WIDTH) {
case IXGBE_PCI_LINK_WIDTH_1:
hw->bus.width = ixgbe_bus_width_pcie_x1;
break;
case IXGBE_PCI_LINK_WIDTH_2:
hw->bus.width = ixgbe_bus_width_pcie_x2;
break;
case IXGBE_PCI_LINK_WIDTH_4:
hw->bus.width = ixgbe_bus_width_pcie_x4;
break;
case IXGBE_PCI_LINK_WIDTH_8:
hw->bus.width = ixgbe_bus_width_pcie_x8;
break;
default:
hw->bus.width = ixgbe_bus_width_unknown;
break;
}
switch (link_status & IXGBE_PCI_LINK_SPEED) {
case IXGBE_PCI_LINK_SPEED_2500:
hw->bus.speed = ixgbe_bus_speed_2500;
break;
case IXGBE_PCI_LINK_SPEED_5000:
hw->bus.speed = ixgbe_bus_speed_5000;
break;
default:
hw->bus.speed = ixgbe_bus_speed_unknown;
break;
}
mac->ops.set_lan_id(hw);
return 0;
}
/**
* ixgbe_set_lan_id_multi_port_pcie - Set LAN id for PCIe multiple port devices
* @hw: pointer to the HW structure
*
* Determines the LAN function id by reading memory-mapped registers
* and swaps the port value if requested.
**/
void ixgbe_set_lan_id_multi_port_pcie(struct ixgbe_hw *hw)
{
struct ixgbe_bus_info *bus = &hw->bus;
u32 reg;
reg = IXGBE_READ_REG(hw, IXGBE_STATUS);
bus->func = (reg & IXGBE_STATUS_LAN_ID) >> IXGBE_STATUS_LAN_ID_SHIFT;
bus->lan_id = bus->func;
/* check for a port swap */
reg = IXGBE_READ_REG(hw, IXGBE_FACTPS);
if (reg & IXGBE_FACTPS_LFS)
bus->func ^= 0x1;
}
/**
* ixgbe_stop_adapter_generic - Generic stop Tx/Rx units
* @hw: pointer to hardware structure
*
* Sets the adapter_stopped flag within ixgbe_hw struct. Clears interrupts,
* disables transmit and receive units. The adapter_stopped flag is used by
* the shared code and drivers to determine if the adapter is in a stopped
* state and should not touch the hardware.
**/
s32 ixgbe_stop_adapter_generic(struct ixgbe_hw *hw)
{
u32 number_of_queues;
u32 reg_val;
u16 i;
/*
* Set the adapter_stopped flag so other driver functions stop touching
* the hardware
*/
hw->adapter_stopped = true;
/* Disable the receive unit */
reg_val = IXGBE_READ_REG(hw, IXGBE_RXCTRL);
reg_val &= ~(IXGBE_RXCTRL_RXEN);
IXGBE_WRITE_REG(hw, IXGBE_RXCTRL, reg_val);
IXGBE_WRITE_FLUSH(hw);
usleep_range(2000, 4000);
/* Clear interrupt mask to stop from interrupts being generated */
IXGBE_WRITE_REG(hw, IXGBE_EIMC, IXGBE_IRQ_CLEAR_MASK);
/* Clear any pending interrupts */
IXGBE_READ_REG(hw, IXGBE_EICR);
/* Disable the transmit unit. Each queue must be disabled. */
number_of_queues = hw->mac.max_tx_queues;
for (i = 0; i < number_of_queues; i++) {
reg_val = IXGBE_READ_REG(hw, IXGBE_TXDCTL(i));
if (reg_val & IXGBE_TXDCTL_ENABLE) {
reg_val &= ~IXGBE_TXDCTL_ENABLE;
IXGBE_WRITE_REG(hw, IXGBE_TXDCTL(i), reg_val);
}
}
/*
* Prevent the PCI-E bus from from hanging by disabling PCI-E master
* access and verify no pending requests
*/
ixgbe_disable_pcie_master(hw);
return 0;
}
/**
* ixgbe_led_on_generic - Turns on the software controllable LEDs.
* @hw: pointer to hardware structure
* @index: led number to turn on
**/
s32 ixgbe_led_on_generic(struct ixgbe_hw *hw, u32 index)
{
u32 led_reg = IXGBE_READ_REG(hw, IXGBE_LEDCTL);
/* To turn on the LED, set mode to ON. */
led_reg &= ~IXGBE_LED_MODE_MASK(index);
led_reg |= IXGBE_LED_ON << IXGBE_LED_MODE_SHIFT(index);
IXGBE_WRITE_REG(hw, IXGBE_LEDCTL, led_reg);
IXGBE_WRITE_FLUSH(hw);
return 0;
}
/**
* ixgbe_led_off_generic - Turns off the software controllable LEDs.
* @hw: pointer to hardware structure
* @index: led number to turn off
**/
s32 ixgbe_led_off_generic(struct ixgbe_hw *hw, u32 index)
{
u32 led_reg = IXGBE_READ_REG(hw, IXGBE_LEDCTL);
/* To turn off the LED, set mode to OFF. */
led_reg &= ~IXGBE_LED_MODE_MASK(index);
led_reg |= IXGBE_LED_OFF << IXGBE_LED_MODE_SHIFT(index);
IXGBE_WRITE_REG(hw, IXGBE_LEDCTL, led_reg);
IXGBE_WRITE_FLUSH(hw);
return 0;
}
/**
* ixgbe_init_eeprom_params_generic - Initialize EEPROM params
* @hw: pointer to hardware structure
*
* Initializes the EEPROM parameters ixgbe_eeprom_info within the
* ixgbe_hw struct in order to set up EEPROM access.
**/
s32 ixgbe_init_eeprom_params_generic(struct ixgbe_hw *hw)
{
struct ixgbe_eeprom_info *eeprom = &hw->eeprom;
u32 eec;
u16 eeprom_size;
if (eeprom->type == ixgbe_eeprom_uninitialized) {
eeprom->type = ixgbe_eeprom_none;
/* Set default semaphore delay to 10ms which is a well
* tested value */
eeprom->semaphore_delay = 10;
/* Clear EEPROM page size, it will be initialized as needed */
eeprom->word_page_size = 0;
/*
* Check for EEPROM present first.
* If not present leave as none
*/
eec = IXGBE_READ_REG(hw, IXGBE_EEC);
if (eec & IXGBE_EEC_PRES) {
eeprom->type = ixgbe_eeprom_spi;
/*
* SPI EEPROM is assumed here. This code would need to
* change if a future EEPROM is not SPI.
*/
eeprom_size = (u16)((eec & IXGBE_EEC_SIZE) >>
IXGBE_EEC_SIZE_SHIFT);
eeprom->word_size = 1 << (eeprom_size +
IXGBE_EEPROM_WORD_SIZE_SHIFT);
}
if (eec & IXGBE_EEC_ADDR_SIZE)
eeprom->address_bits = 16;
else
eeprom->address_bits = 8;
hw_dbg(hw, "Eeprom params: type = %d, size = %d, address bits: "
"%d\n", eeprom->type, eeprom->word_size,
eeprom->address_bits);
}
return 0;
}
/**
* ixgbe_write_eeprom_buffer_bit_bang_generic - Write EEPROM using bit-bang
* @hw: pointer to hardware structure
* @offset: offset within the EEPROM to write
* @words: number of words
* @data: 16 bit word(s) to write to EEPROM
*
* Reads 16 bit word(s) from EEPROM through bit-bang method
**/
s32 ixgbe_write_eeprom_buffer_bit_bang_generic(struct ixgbe_hw *hw, u16 offset,
u16 words, u16 *data)
{
s32 status = 0;
u16 i, count;
hw->eeprom.ops.init_params(hw);
if (words == 0) {
status = IXGBE_ERR_INVALID_ARGUMENT;
goto out;
}
if (offset + words > hw->eeprom.word_size) {
status = IXGBE_ERR_EEPROM;
goto out;
}
/*
* The EEPROM page size cannot be queried from the chip. We do lazy
* initialization. It is worth to do that when we write large buffer.
*/
if ((hw->eeprom.word_page_size == 0) &&
(words > IXGBE_EEPROM_PAGE_SIZE_MAX))
ixgbe_detect_eeprom_page_size_generic(hw, offset);
/*
* We cannot hold synchronization semaphores for too long
* to avoid other entity starvation. However it is more efficient
* to read in bursts than synchronizing access for each word.
*/
for (i = 0; i < words; i += IXGBE_EEPROM_RD_BUFFER_MAX_COUNT) {
count = (words - i) / IXGBE_EEPROM_RD_BUFFER_MAX_COUNT > 0 ?
IXGBE_EEPROM_RD_BUFFER_MAX_COUNT : (words - i);
status = ixgbe_write_eeprom_buffer_bit_bang(hw, offset + i,
count, &data[i]);
if (status != 0)
break;
}
out:
return status;
}
/**
* ixgbe_write_eeprom_buffer_bit_bang - Writes 16 bit word(s) to EEPROM
* @hw: pointer to hardware structure
* @offset: offset within the EEPROM to be written to
* @words: number of word(s)
* @data: 16 bit word(s) to be written to the EEPROM
*
* If ixgbe_eeprom_update_checksum is not called after this function, the
* EEPROM will most likely contain an invalid checksum.
**/
static s32 ixgbe_write_eeprom_buffer_bit_bang(struct ixgbe_hw *hw, u16 offset,
u16 words, u16 *data)
{
s32 status;
u16 word;
u16 page_size;
u16 i;
u8 write_opcode = IXGBE_EEPROM_WRITE_OPCODE_SPI;
/* Prepare the EEPROM for writing */
status = ixgbe_acquire_eeprom(hw);
if (status == 0) {
if (ixgbe_ready_eeprom(hw) != 0) {
ixgbe_release_eeprom(hw);
status = IXGBE_ERR_EEPROM;
}
}
if (status == 0) {
for (i = 0; i < words; i++) {
ixgbe_standby_eeprom(hw);
/* Send the WRITE ENABLE command (8 bit opcode ) */
ixgbe_shift_out_eeprom_bits(hw,
IXGBE_EEPROM_WREN_OPCODE_SPI,
IXGBE_EEPROM_OPCODE_BITS);
ixgbe_standby_eeprom(hw);
/*
* Some SPI eeproms use the 8th address bit embedded
* in the opcode
*/
if ((hw->eeprom.address_bits == 8) &&
((offset + i) >= 128))
write_opcode |= IXGBE_EEPROM_A8_OPCODE_SPI;
/* Send the Write command (8-bit opcode + addr) */
ixgbe_shift_out_eeprom_bits(hw, write_opcode,
IXGBE_EEPROM_OPCODE_BITS);
ixgbe_shift_out_eeprom_bits(hw, (u16)((offset + i) * 2),
hw->eeprom.address_bits);
page_size = hw->eeprom.word_page_size;
/* Send the data in burst via SPI*/
do {
word = data[i];
word = (word >> 8) | (word << 8);
ixgbe_shift_out_eeprom_bits(hw, word, 16);
if (page_size == 0)
break;
/* do not wrap around page */
if (((offset + i) & (page_size - 1)) ==
(page_size - 1))
break;
} while (++i < words);
ixgbe_standby_eeprom(hw);
usleep_range(10000, 20000);
}
/* Done with writing - release the EEPROM */
ixgbe_release_eeprom(hw);
}
return status;
}
/**
* ixgbe_write_eeprom_generic - Writes 16 bit value to EEPROM
* @hw: pointer to hardware structure
* @offset: offset within the EEPROM to be written to
* @data: 16 bit word to be written to the EEPROM
*
* If ixgbe_eeprom_update_checksum is not called after this function, the
* EEPROM will most likely contain an invalid checksum.
**/
s32 ixgbe_write_eeprom_generic(struct ixgbe_hw *hw, u16 offset, u16 data)
{
s32 status;
hw->eeprom.ops.init_params(hw);
if (offset >= hw->eeprom.word_size) {
status = IXGBE_ERR_EEPROM;
goto out;
}
status = ixgbe_write_eeprom_buffer_bit_bang(hw, offset, 1, &data);
out:
return status;
}
/**
* ixgbe_read_eeprom_buffer_bit_bang_generic - Read EEPROM using bit-bang
* @hw: pointer to hardware structure
* @offset: offset within the EEPROM to be read
* @words: number of word(s)
* @data: read 16 bit words(s) from EEPROM
*
* Reads 16 bit word(s) from EEPROM through bit-bang method
**/
s32 ixgbe_read_eeprom_buffer_bit_bang_generic(struct ixgbe_hw *hw, u16 offset,
u16 words, u16 *data)
{
s32 status = 0;
u16 i, count;
hw->eeprom.ops.init_params(hw);
if (words == 0) {
status = IXGBE_ERR_INVALID_ARGUMENT;
goto out;
}
if (offset + words > hw->eeprom.word_size) {
status = IXGBE_ERR_EEPROM;
goto out;
}
/*
* We cannot hold synchronization semaphores for too long
* to avoid other entity starvation. However it is more efficient
* to read in bursts than synchronizing access for each word.
*/
for (i = 0; i < words; i += IXGBE_EEPROM_RD_BUFFER_MAX_COUNT) {
count = (words - i) / IXGBE_EEPROM_RD_BUFFER_MAX_COUNT > 0 ?
IXGBE_EEPROM_RD_BUFFER_MAX_COUNT : (words - i);
status = ixgbe_read_eeprom_buffer_bit_bang(hw, offset + i,
count, &data[i]);
if (status != 0)
break;
}
out:
return status;
}
/**
* ixgbe_read_eeprom_buffer_bit_bang - Read EEPROM using bit-bang
* @hw: pointer to hardware structure
* @offset: offset within the EEPROM to be read
* @words: number of word(s)
* @data: read 16 bit word(s) from EEPROM
*
* Reads 16 bit word(s) from EEPROM through bit-bang method
**/
static s32 ixgbe_read_eeprom_buffer_bit_bang(struct ixgbe_hw *hw, u16 offset,
u16 words, u16 *data)
{
s32 status;
u16 word_in;
u8 read_opcode = IXGBE_EEPROM_READ_OPCODE_SPI;
u16 i;
/* Prepare the EEPROM for reading */
status = ixgbe_acquire_eeprom(hw);
if (status == 0) {
if (ixgbe_ready_eeprom(hw) != 0) {
ixgbe_release_eeprom(hw);
status = IXGBE_ERR_EEPROM;
}
}
if (status == 0) {
for (i = 0; i < words; i++) {
ixgbe_standby_eeprom(hw);
/*
* Some SPI eeproms use the 8th address bit embedded
* in the opcode
*/
if ((hw->eeprom.address_bits == 8) &&
((offset + i) >= 128))
read_opcode |= IXGBE_EEPROM_A8_OPCODE_SPI;
/* Send the READ command (opcode + addr) */
ixgbe_shift_out_eeprom_bits(hw, read_opcode,
IXGBE_EEPROM_OPCODE_BITS);
ixgbe_shift_out_eeprom_bits(hw, (u16)((offset + i) * 2),
hw->eeprom.address_bits);
/* Read the data. */
word_in = ixgbe_shift_in_eeprom_bits(hw, 16);
data[i] = (word_in >> 8) | (word_in << 8);
}
/* End this read operation */
ixgbe_release_eeprom(hw);
}
return status;
}
/**
* ixgbe_read_eeprom_bit_bang_generic - Read EEPROM word using bit-bang
* @hw: pointer to hardware structure
* @offset: offset within the EEPROM to be read
* @data: read 16 bit value from EEPROM
*
* Reads 16 bit value from EEPROM through bit-bang method
**/
s32 ixgbe_read_eeprom_bit_bang_generic(struct ixgbe_hw *hw, u16 offset,
u16 *data)
{
s32 status;
hw->eeprom.ops.init_params(hw);
if (offset >= hw->eeprom.word_size) {
status = IXGBE_ERR_EEPROM;
goto out;
}
status = ixgbe_read_eeprom_buffer_bit_bang(hw, offset, 1, data);
out:
return status;
}
/**
* ixgbe_read_eerd_buffer_generic - Read EEPROM word(s) using EERD
* @hw: pointer to hardware structure
* @offset: offset of word in the EEPROM to read
* @words: number of word(s)
* @data: 16 bit word(s) from the EEPROM
*
* Reads a 16 bit word(s) from the EEPROM using the EERD register.
**/
s32 ixgbe_read_eerd_buffer_generic(struct ixgbe_hw *hw, u16 offset,
u16 words, u16 *data)
{
u32 eerd;
s32 status = 0;
u32 i;
hw->eeprom.ops.init_params(hw);
if (words == 0) {
status = IXGBE_ERR_INVALID_ARGUMENT;
goto out;
}
if (offset >= hw->eeprom.word_size) {
status = IXGBE_ERR_EEPROM;
goto out;
}
for (i = 0; i < words; i++) {
eerd = ((offset + i) << IXGBE_EEPROM_RW_ADDR_SHIFT) +
IXGBE_EEPROM_RW_REG_START;
IXGBE_WRITE_REG(hw, IXGBE_EERD, eerd);
status = ixgbe_poll_eerd_eewr_done(hw, IXGBE_NVM_POLL_READ);
if (status == 0) {
data[i] = (IXGBE_READ_REG(hw, IXGBE_EERD) >>
IXGBE_EEPROM_RW_REG_DATA);
} else {
hw_dbg(hw, "Eeprom read timed out\n");
goto out;
}
}
out:
return status;
}
/**
* ixgbe_detect_eeprom_page_size_generic - Detect EEPROM page size
* @hw: pointer to hardware structure
* @offset: offset within the EEPROM to be used as a scratch pad
*
* Discover EEPROM page size by writing marching data at given offset.
* This function is called only when we are writing a new large buffer
* at given offset so the data would be overwritten anyway.
**/
static s32 ixgbe_detect_eeprom_page_size_generic(struct ixgbe_hw *hw,
u16 offset)
{
u16 data[IXGBE_EEPROM_PAGE_SIZE_MAX];
s32 status = 0;
u16 i;
for (i = 0; i < IXGBE_EEPROM_PAGE_SIZE_MAX; i++)
data[i] = i;
hw->eeprom.word_page_size = IXGBE_EEPROM_PAGE_SIZE_MAX;
status = ixgbe_write_eeprom_buffer_bit_bang(hw, offset,
IXGBE_EEPROM_PAGE_SIZE_MAX, data);
hw->eeprom.word_page_size = 0;
if (status != 0)
goto out;
status = ixgbe_read_eeprom_buffer_bit_bang(hw, offset, 1, data);
if (status != 0)
goto out;
/*
* When writing in burst more than the actual page size
* EEPROM address wraps around current page.
*/
hw->eeprom.word_page_size = IXGBE_EEPROM_PAGE_SIZE_MAX - data[0];
hw_dbg(hw, "Detected EEPROM page size = %d words.",
hw->eeprom.word_page_size);
out:
return status;
}
/**
* ixgbe_read_eerd_generic - Read EEPROM word using EERD
* @hw: pointer to hardware structure
* @offset: offset of word in the EEPROM to read
* @data: word read from the EEPROM
*
* Reads a 16 bit word from the EEPROM using the EERD register.
**/
s32 ixgbe_read_eerd_generic(struct ixgbe_hw *hw, u16 offset, u16 *data)
{
return ixgbe_read_eerd_buffer_generic(hw, offset, 1, data);
}
/**
* ixgbe_write_eewr_buffer_generic - Write EEPROM word(s) using EEWR
* @hw: pointer to hardware structure
* @offset: offset of word in the EEPROM to write
* @words: number of words
* @data: word(s) write to the EEPROM
*
* Write a 16 bit word(s) to the EEPROM using the EEWR register.
**/
s32 ixgbe_write_eewr_buffer_generic(struct ixgbe_hw *hw, u16 offset,
u16 words, u16 *data)
{
u32 eewr;
s32 status = 0;
u16 i;
hw->eeprom.ops.init_params(hw);
if (words == 0) {
status = IXGBE_ERR_INVALID_ARGUMENT;
goto out;
}
if (offset >= hw->eeprom.word_size) {
status = IXGBE_ERR_EEPROM;
goto out;
}
for (i = 0; i < words; i++) {
eewr = ((offset + i) << IXGBE_EEPROM_RW_ADDR_SHIFT) |
(data[i] << IXGBE_EEPROM_RW_REG_DATA) |
IXGBE_EEPROM_RW_REG_START;
status = ixgbe_poll_eerd_eewr_done(hw, IXGBE_NVM_POLL_WRITE);
if (status != 0) {
hw_dbg(hw, "Eeprom write EEWR timed out\n");
goto out;
}
IXGBE_WRITE_REG(hw, IXGBE_EEWR, eewr);
status = ixgbe_poll_eerd_eewr_done(hw, IXGBE_NVM_POLL_WRITE);
if (status != 0) {
hw_dbg(hw, "Eeprom write EEWR timed out\n");
goto out;
}
}
out:
return status;
}
/**
* ixgbe_write_eewr_generic - Write EEPROM word using EEWR
* @hw: pointer to hardware structure
* @offset: offset of word in the EEPROM to write
* @data: word write to the EEPROM
*
* Write a 16 bit word to the EEPROM using the EEWR register.
**/
s32 ixgbe_write_eewr_generic(struct ixgbe_hw *hw, u16 offset, u16 data)
{
return ixgbe_write_eewr_buffer_generic(hw, offset, 1, &data);
}
/**
* ixgbe_poll_eerd_eewr_done - Poll EERD read or EEWR write status
* @hw: pointer to hardware structure
* @ee_reg: EEPROM flag for polling
*
* Polls the status bit (bit 1) of the EERD or EEWR to determine when the
* read or write is done respectively.
**/
static s32 ixgbe_poll_eerd_eewr_done(struct ixgbe_hw *hw, u32 ee_reg)
{
u32 i;
u32 reg;
s32 status = IXGBE_ERR_EEPROM;
for (i = 0; i < IXGBE_EERD_EEWR_ATTEMPTS; i++) {
if (ee_reg == IXGBE_NVM_POLL_READ)
reg = IXGBE_READ_REG(hw, IXGBE_EERD);
else
reg = IXGBE_READ_REG(hw, IXGBE_EEWR);
if (reg & IXGBE_EEPROM_RW_REG_DONE) {
status = 0;
break;
}
udelay(5);
}
return status;
}
/**
* ixgbe_acquire_eeprom - Acquire EEPROM using bit-bang
* @hw: pointer to hardware structure
*
* Prepares EEPROM for access using bit-bang method. This function should
* be called before issuing a command to the EEPROM.
**/
static s32 ixgbe_acquire_eeprom(struct ixgbe_hw *hw)
{
s32 status = 0;
u32 eec;
u32 i;
if (hw->mac.ops.acquire_swfw_sync(hw, IXGBE_GSSR_EEP_SM) != 0)
status = IXGBE_ERR_SWFW_SYNC;
if (status == 0) {
eec = IXGBE_READ_REG(hw, IXGBE_EEC);
/* Request EEPROM Access */
eec |= IXGBE_EEC_REQ;
IXGBE_WRITE_REG(hw, IXGBE_EEC, eec);
for (i = 0; i < IXGBE_EEPROM_GRANT_ATTEMPTS; i++) {
eec = IXGBE_READ_REG(hw, IXGBE_EEC);
if (eec & IXGBE_EEC_GNT)
break;
udelay(5);
}
/* Release if grant not acquired */
if (!(eec & IXGBE_EEC_GNT)) {
eec &= ~IXGBE_EEC_REQ;
IXGBE_WRITE_REG(hw, IXGBE_EEC, eec);
hw_dbg(hw, "Could not acquire EEPROM grant\n");
hw->mac.ops.release_swfw_sync(hw, IXGBE_GSSR_EEP_SM);
status = IXGBE_ERR_EEPROM;
}
/* Setup EEPROM for Read/Write */
if (status == 0) {
/* Clear CS and SK */
eec &= ~(IXGBE_EEC_CS | IXGBE_EEC_SK);
IXGBE_WRITE_REG(hw, IXGBE_EEC, eec);
IXGBE_WRITE_FLUSH(hw);
udelay(1);
}
}
return status;
}
/**
* ixgbe_get_eeprom_semaphore - Get hardware semaphore
* @hw: pointer to hardware structure
*
* Sets the hardware semaphores so EEPROM access can occur for bit-bang method
**/
static s32 ixgbe_get_eeprom_semaphore(struct ixgbe_hw *hw)
{
s32 status = IXGBE_ERR_EEPROM;
u32 timeout = 2000;
u32 i;
u32 swsm;
/* Get SMBI software semaphore between device drivers first */
for (i = 0; i < timeout; i++) {
/*
* If the SMBI bit is 0 when we read it, then the bit will be
* set and we have the semaphore
*/
swsm = IXGBE_READ_REG(hw, IXGBE_SWSM);
if (!(swsm & IXGBE_SWSM_SMBI)) {
status = 0;
break;
}
udelay(50);
}
if (i == timeout) {
hw_dbg(hw, "Driver can't access the Eeprom - SMBI Semaphore "
"not granted.\n");
/*
* this release is particularly important because our attempts
* above to get the semaphore may have succeeded, and if there
* was a timeout, we should unconditionally clear the semaphore
* bits to free the driver to make progress
*/
ixgbe_release_eeprom_semaphore(hw);
udelay(50);
/*
* one last try
* If the SMBI bit is 0 when we read it, then the bit will be
* set and we have the semaphore
*/
swsm = IXGBE_READ_REG(hw, IXGBE_SWSM);
if (!(swsm & IXGBE_SWSM_SMBI))
status = 0;
}
/* Now get the semaphore between SW/FW through the SWESMBI bit */
if (status == 0) {
for (i = 0; i < timeout; i++) {
swsm = IXGBE_READ_REG(hw, IXGBE_SWSM);
/* Set the SW EEPROM semaphore bit to request access */
swsm |= IXGBE_SWSM_SWESMBI;
IXGBE_WRITE_REG(hw, IXGBE_SWSM, swsm);
/*
* If we set the bit successfully then we got the
* semaphore.
*/
swsm = IXGBE_READ_REG(hw, IXGBE_SWSM);
if (swsm & IXGBE_SWSM_SWESMBI)
break;
udelay(50);
}
/*
* Release semaphores and return error if SW EEPROM semaphore
* was not granted because we don't have access to the EEPROM
*/
if (i >= timeout) {
hw_dbg(hw, "SWESMBI Software EEPROM semaphore "
"not granted.\n");
ixgbe_release_eeprom_semaphore(hw);
status = IXGBE_ERR_EEPROM;
}
} else {
hw_dbg(hw, "Software semaphore SMBI between device drivers "
"not granted.\n");
}
return status;
}
/**
* ixgbe_release_eeprom_semaphore - Release hardware semaphore
* @hw: pointer to hardware structure
*
* This function clears hardware semaphore bits.
**/
static void ixgbe_release_eeprom_semaphore(struct ixgbe_hw *hw)
{
u32 swsm;
swsm = IXGBE_READ_REG(hw, IXGBE_SWSM);
/* Release both semaphores by writing 0 to the bits SWESMBI and SMBI */
swsm &= ~(IXGBE_SWSM_SWESMBI | IXGBE_SWSM_SMBI);
IXGBE_WRITE_REG(hw, IXGBE_SWSM, swsm);
IXGBE_WRITE_FLUSH(hw);
}
/**
* ixgbe_ready_eeprom - Polls for EEPROM ready
* @hw: pointer to hardware structure
**/
static s32 ixgbe_ready_eeprom(struct ixgbe_hw *hw)
{
s32 status = 0;
u16 i;
u8 spi_stat_reg;
/*
* Read "Status Register" repeatedly until the LSB is cleared. The
* EEPROM will signal that the command has been completed by clearing
* bit 0 of the internal status register. If it's not cleared within
* 5 milliseconds, then error out.
*/
for (i = 0; i < IXGBE_EEPROM_MAX_RETRY_SPI; i += 5) {
ixgbe_shift_out_eeprom_bits(hw, IXGBE_EEPROM_RDSR_OPCODE_SPI,
IXGBE_EEPROM_OPCODE_BITS);
spi_stat_reg = (u8)ixgbe_shift_in_eeprom_bits(hw, 8);
if (!(spi_stat_reg & IXGBE_EEPROM_STATUS_RDY_SPI))
break;
udelay(5);
ixgbe_standby_eeprom(hw);
}
/*
* On some parts, SPI write time could vary from 0-20mSec on 3.3V
* devices (and only 0-5mSec on 5V devices)
*/
if (i >= IXGBE_EEPROM_MAX_RETRY_SPI) {
hw_dbg(hw, "SPI EEPROM Status error\n");
status = IXGBE_ERR_EEPROM;
}
return status;
}
/**
* ixgbe_standby_eeprom - Returns EEPROM to a "standby" state
* @hw: pointer to hardware structure
**/
static void ixgbe_standby_eeprom(struct ixgbe_hw *hw)
{
u32 eec;
eec = IXGBE_READ_REG(hw, IXGBE_EEC);
/* Toggle CS to flush commands */
eec |= IXGBE_EEC_CS;
IXGBE_WRITE_REG(hw, IXGBE_EEC, eec);
IXGBE_WRITE_FLUSH(hw);
udelay(1);
eec &= ~IXGBE_EEC_CS;
IXGBE_WRITE_REG(hw, IXGBE_EEC, eec);
IXGBE_WRITE_FLUSH(hw);
udelay(1);
}
/**
* ixgbe_shift_out_eeprom_bits - Shift data bits out to the EEPROM.
* @hw: pointer to hardware structure
* @data: data to send to the EEPROM
* @count: number of bits to shift out
**/
static void ixgbe_shift_out_eeprom_bits(struct ixgbe_hw *hw, u16 data,
u16 count)
{
u32 eec;
u32 mask;
u32 i;
eec = IXGBE_READ_REG(hw, IXGBE_EEC);
/*
* Mask is used to shift "count" bits of "data" out to the EEPROM
* one bit at a time. Determine the starting bit based on count
*/
mask = 0x01 << (count - 1);
for (i = 0; i < count; i++) {
/*
* A "1" is shifted out to the EEPROM by setting bit "DI" to a
* "1", and then raising and then lowering the clock (the SK
* bit controls the clock input to the EEPROM). A "0" is
* shifted out to the EEPROM by setting "DI" to "0" and then
* raising and then lowering the clock.
*/
if (data & mask)
eec |= IXGBE_EEC_DI;
else
eec &= ~IXGBE_EEC_DI;
IXGBE_WRITE_REG(hw, IXGBE_EEC, eec);
IXGBE_WRITE_FLUSH(hw);
udelay(1);
ixgbe_raise_eeprom_clk(hw, &eec);
ixgbe_lower_eeprom_clk(hw, &eec);
/*
* Shift mask to signify next bit of data to shift in to the
* EEPROM
*/
mask = mask >> 1;
}
/* We leave the "DI" bit set to "0" when we leave this routine. */
eec &= ~IXGBE_EEC_DI;
IXGBE_WRITE_REG(hw, IXGBE_EEC, eec);
IXGBE_WRITE_FLUSH(hw);
}
/**
* ixgbe_shift_in_eeprom_bits - Shift data bits in from the EEPROM
* @hw: pointer to hardware structure
**/
static u16 ixgbe_shift_in_eeprom_bits(struct ixgbe_hw *hw, u16 count)
{
u32 eec;
u32 i;
u16 data = 0;
/*
* In order to read a register from the EEPROM, we need to shift
* 'count' bits in from the EEPROM. Bits are "shifted in" by raising
* the clock input to the EEPROM (setting the SK bit), and then reading
* the value of the "DO" bit. During this "shifting in" process the
* "DI" bit should always be clear.
*/
eec = IXGBE_READ_REG(hw, IXGBE_EEC);
eec &= ~(IXGBE_EEC_DO | IXGBE_EEC_DI);
for (i = 0; i < count; i++) {
data = data << 1;
ixgbe_raise_eeprom_clk(hw, &eec);
eec = IXGBE_READ_REG(hw, IXGBE_EEC);
eec &= ~(IXGBE_EEC_DI);
if (eec & IXGBE_EEC_DO)
data |= 1;
ixgbe_lower_eeprom_clk(hw, &eec);
}
return data;
}
/**
* ixgbe_raise_eeprom_clk - Raises the EEPROM's clock input.
* @hw: pointer to hardware structure
* @eec: EEC register's current value
**/
static void ixgbe_raise_eeprom_clk(struct ixgbe_hw *hw, u32 *eec)
{
/*
* Raise the clock input to the EEPROM
* (setting the SK bit), then delay
*/
*eec = *eec | IXGBE_EEC_SK;
IXGBE_WRITE_REG(hw, IXGBE_EEC, *eec);
IXGBE_WRITE_FLUSH(hw);
udelay(1);
}
/**
* ixgbe_lower_eeprom_clk - Lowers the EEPROM's clock input.
* @hw: pointer to hardware structure
* @eecd: EECD's current value
**/
static void ixgbe_lower_eeprom_clk(struct ixgbe_hw *hw, u32 *eec)
{
/*
* Lower the clock input to the EEPROM (clearing the SK bit), then
* delay
*/
*eec = *eec & ~IXGBE_EEC_SK;
IXGBE_WRITE_REG(hw, IXGBE_EEC, *eec);
IXGBE_WRITE_FLUSH(hw);
udelay(1);
}
/**
* ixgbe_release_eeprom - Release EEPROM, release semaphores
* @hw: pointer to hardware structure
**/
static void ixgbe_release_eeprom(struct ixgbe_hw *hw)
{
u32 eec;
eec = IXGBE_READ_REG(hw, IXGBE_EEC);
eec |= IXGBE_EEC_CS; /* Pull CS high */
eec &= ~IXGBE_EEC_SK; /* Lower SCK */
IXGBE_WRITE_REG(hw, IXGBE_EEC, eec);
IXGBE_WRITE_FLUSH(hw);
udelay(1);
/* Stop requesting EEPROM access */
eec &= ~IXGBE_EEC_REQ;
IXGBE_WRITE_REG(hw, IXGBE_EEC, eec);
hw->mac.ops.release_swfw_sync(hw, IXGBE_GSSR_EEP_SM);
/*
* Delay before attempt to obtain semaphore again to allow FW
* access. semaphore_delay is in ms we need us for usleep_range
*/
usleep_range(hw->eeprom.semaphore_delay * 1000,
hw->eeprom.semaphore_delay * 2000);
}
/**
* ixgbe_calc_eeprom_checksum_generic - Calculates and returns the checksum
* @hw: pointer to hardware structure
**/
u16 ixgbe_calc_eeprom_checksum_generic(struct ixgbe_hw *hw)
{
u16 i;
u16 j;
u16 checksum = 0;
u16 length = 0;
u16 pointer = 0;
u16 word = 0;
/* Include 0x0-0x3F in the checksum */
for (i = 0; i < IXGBE_EEPROM_CHECKSUM; i++) {
if (hw->eeprom.ops.read(hw, i, &word) != 0) {
hw_dbg(hw, "EEPROM read failed\n");
break;
}
checksum += word;
}
/* Include all data from pointers except for the fw pointer */
for (i = IXGBE_PCIE_ANALOG_PTR; i < IXGBE_FW_PTR; i++) {
hw->eeprom.ops.read(hw, i, &pointer);
/* Make sure the pointer seems valid */
if (pointer != 0xFFFF && pointer != 0) {
hw->eeprom.ops.read(hw, pointer, &length);
if (length != 0xFFFF && length != 0) {
for (j = pointer+1; j <= pointer+length; j++) {
hw->eeprom.ops.read(hw, j, &word);
checksum += word;
}
}
}
}
checksum = (u16)IXGBE_EEPROM_SUM - checksum;
return checksum;
}
/**
* ixgbe_validate_eeprom_checksum_generic - Validate EEPROM checksum
* @hw: pointer to hardware structure
* @checksum_val: calculated checksum
*
* Performs checksum calculation and validates the EEPROM checksum. If the
* caller does not need checksum_val, the value can be NULL.
**/
s32 ixgbe_validate_eeprom_checksum_generic(struct ixgbe_hw *hw,
u16 *checksum_val)
{
s32 status;
u16 checksum;
u16 read_checksum = 0;
/*
* Read the first word from the EEPROM. If this times out or fails, do
* not continue or we could be in for a very long wait while every
* EEPROM read fails
*/
status = hw->eeprom.ops.read(hw, 0, &checksum);
if (status == 0) {
checksum = hw->eeprom.ops.calc_checksum(hw);
hw->eeprom.ops.read(hw, IXGBE_EEPROM_CHECKSUM, &read_checksum);
/*
* Verify read checksum from EEPROM is the same as
* calculated checksum
*/
if (read_checksum != checksum)
status = IXGBE_ERR_EEPROM_CHECKSUM;
/* If the user cares, return the calculated checksum */
if (checksum_val)
*checksum_val = checksum;
} else {
hw_dbg(hw, "EEPROM read failed\n");
}
return status;
}
/**
* ixgbe_update_eeprom_checksum_generic - Updates the EEPROM checksum
* @hw: pointer to hardware structure
**/
s32 ixgbe_update_eeprom_checksum_generic(struct ixgbe_hw *hw)
{
s32 status;
u16 checksum;
/*
* Read the first word from the EEPROM. If this times out or fails, do
* not continue or we could be in for a very long wait while every
* EEPROM read fails
*/
status = hw->eeprom.ops.read(hw, 0, &checksum);
if (status == 0) {
checksum = hw->eeprom.ops.calc_checksum(hw);
status = hw->eeprom.ops.write(hw, IXGBE_EEPROM_CHECKSUM,
checksum);
} else {
hw_dbg(hw, "EEPROM read failed\n");
}
return status;
}
/**
* ixgbe_validate_mac_addr - Validate MAC address
* @mac_addr: pointer to MAC address.
*
* Tests a MAC address to ensure it is a valid Individual Address
**/
s32 ixgbe_validate_mac_addr(u8 *mac_addr)
{
s32 status = 0;
/* Make sure it is not a multicast address */
if (IXGBE_IS_MULTICAST(mac_addr))
status = IXGBE_ERR_INVALID_MAC_ADDR;
/* Not a broadcast address */
else if (IXGBE_IS_BROADCAST(mac_addr))
status = IXGBE_ERR_INVALID_MAC_ADDR;
/* Reject the zero address */
else if (mac_addr[0] == 0 && mac_addr[1] == 0 && mac_addr[2] == 0 &&
mac_addr[3] == 0 && mac_addr[4] == 0 && mac_addr[5] == 0)
status = IXGBE_ERR_INVALID_MAC_ADDR;
return status;
}
/**
* ixgbe_set_rar_generic - Set Rx address register
* @hw: pointer to hardware structure
* @index: Receive address register to write
* @addr: Address to put into receive address register
* @vmdq: VMDq "set" or "pool" index
* @enable_addr: set flag that address is active
*
* Puts an ethernet address into a receive address register.
**/
s32 ixgbe_set_rar_generic(struct ixgbe_hw *hw, u32 index, u8 *addr, u32 vmdq,
u32 enable_addr)
{
u32 rar_low, rar_high;
u32 rar_entries = hw->mac.num_rar_entries;
/* Make sure we are using a valid rar index range */
if (index >= rar_entries) {
hw_dbg(hw, "RAR index %d is out of range.\n", index);
return IXGBE_ERR_INVALID_ARGUMENT;
}
/* setup VMDq pool selection before this RAR gets enabled */
hw->mac.ops.set_vmdq(hw, index, vmdq);
/*
* HW expects these in little endian so we reverse the byte
* order from network order (big endian) to little endian
*/
rar_low = ((u32)addr[0] |
((u32)addr[1] << 8) |
((u32)addr[2] << 16) |
((u32)addr[3] << 24));
/*
* Some parts put the VMDq setting in the extra RAH bits,
* so save everything except the lower 16 bits that hold part
* of the address and the address valid bit.
*/
rar_high = IXGBE_READ_REG(hw, IXGBE_RAH(index));
rar_high &= ~(0x0000FFFF | IXGBE_RAH_AV);
rar_high |= ((u32)addr[4] | ((u32)addr[5] << 8));
if (enable_addr != 0)
rar_high |= IXGBE_RAH_AV;
IXGBE_WRITE_REG(hw, IXGBE_RAL(index), rar_low);
IXGBE_WRITE_REG(hw, IXGBE_RAH(index), rar_high);
return 0;
}
/**
* ixgbe_clear_rar_generic - Remove Rx address register
* @hw: pointer to hardware structure
* @index: Receive address register to write
*
* Clears an ethernet address from a receive address register.
**/
s32 ixgbe_clear_rar_generic(struct ixgbe_hw *hw, u32 index)
{
u32 rar_high;
u32 rar_entries = hw->mac.num_rar_entries;
/* Make sure we are using a valid rar index range */
if (index >= rar_entries) {
hw_dbg(hw, "RAR index %d is out of range.\n", index);
return IXGBE_ERR_INVALID_ARGUMENT;
}
/*
* Some parts put the VMDq setting in the extra RAH bits,
* so save everything except the lower 16 bits that hold part
* of the address and the address valid bit.
*/
rar_high = IXGBE_READ_REG(hw, IXGBE_RAH(index));
rar_high &= ~(0x0000FFFF | IXGBE_RAH_AV);
IXGBE_WRITE_REG(hw, IXGBE_RAL(index), 0);
IXGBE_WRITE_REG(hw, IXGBE_RAH(index), rar_high);
/* clear VMDq pool/queue selection for this RAR */
hw->mac.ops.clear_vmdq(hw, index, IXGBE_CLEAR_VMDQ_ALL);
return 0;
}
/**
* ixgbe_init_rx_addrs_generic - Initializes receive address filters.
* @hw: pointer to hardware structure
*
* Places the MAC address in receive address register 0 and clears the rest
* of the receive address registers. Clears the multicast table. Assumes
* the receiver is in reset when the routine is called.
**/
s32 ixgbe_init_rx_addrs_generic(struct ixgbe_hw *hw)
{
u32 i;
u32 rar_entries = hw->mac.num_rar_entries;
/*
* If the current mac address is valid, assume it is a software override
* to the permanent address.
* Otherwise, use the permanent address from the eeprom.
*/
if (ixgbe_validate_mac_addr(hw->mac.addr) ==
IXGBE_ERR_INVALID_MAC_ADDR) {
/* Get the MAC address from the RAR0 for later reference */
hw->mac.ops.get_mac_addr(hw, hw->mac.addr);
hw_dbg(hw, " Keeping Current RAR0 Addr =%pM\n", hw->mac.addr);
} else {
/* Setup the receive address. */
hw_dbg(hw, "Overriding MAC Address in RAR[0]\n");
hw_dbg(hw, " New MAC Addr =%pM\n", hw->mac.addr);
hw->mac.ops.set_rar(hw, 0, hw->mac.addr, 0, IXGBE_RAH_AV);
/* clear VMDq pool/queue selection for RAR 0 */
hw->mac.ops.clear_vmdq(hw, 0, IXGBE_CLEAR_VMDQ_ALL);
}
hw->addr_ctrl.overflow_promisc = 0;
hw->addr_ctrl.rar_used_count = 1;
/* Zero out the other receive addresses. */
hw_dbg(hw, "Clearing RAR[1-%d]\n", rar_entries - 1);
for (i = 1; i < rar_entries; i++) {
IXGBE_WRITE_REG(hw, IXGBE_RAL(i), 0);
IXGBE_WRITE_REG(hw, IXGBE_RAH(i), 0);
}
/* Clear the MTA */
hw->addr_ctrl.mta_in_use = 0;
IXGBE_WRITE_REG(hw, IXGBE_MCSTCTRL, hw->mac.mc_filter_type);
hw_dbg(hw, " Clearing MTA\n");
for (i = 0; i < hw->mac.mcft_size; i++)
IXGBE_WRITE_REG(hw, IXGBE_MTA(i), 0);
if (hw->mac.ops.init_uta_tables)
hw->mac.ops.init_uta_tables(hw);
return 0;
}
/**
* ixgbe_mta_vector - Determines bit-vector in multicast table to set
* @hw: pointer to hardware structure
* @mc_addr: the multicast address
*
* Extracts the 12 bits, from a multicast address, to determine which
* bit-vector to set in the multicast table. The hardware uses 12 bits, from
* incoming rx multicast addresses, to determine the bit-vector to check in
* the MTA. Which of the 4 combination, of 12-bits, the hardware uses is set
* by the MO field of the MCSTCTRL. The MO field is set during initialization
* to mc_filter_type.
**/
static s32 ixgbe_mta_vector(struct ixgbe_hw *hw, u8 *mc_addr)
{
u32 vector = 0;
switch (hw->mac.mc_filter_type) {
case 0: /* use bits [47:36] of the address */
vector = ((mc_addr[4] >> 4) | (((u16)mc_addr[5]) << 4));
break;
case 1: /* use bits [46:35] of the address */
vector = ((mc_addr[4] >> 3) | (((u16)mc_addr[5]) << 5));
break;
case 2: /* use bits [45:34] of the address */
vector = ((mc_addr[4] >> 2) | (((u16)mc_addr[5]) << 6));
break;
case 3: /* use bits [43:32] of the address */
vector = ((mc_addr[4]) | (((u16)mc_addr[5]) << 8));
break;
default: /* Invalid mc_filter_type */
hw_dbg(hw, "MC filter type param set incorrectly\n");
break;
}
/* vector can only be 12-bits or boundary will be exceeded */
vector &= 0xFFF;
return vector;
}
/**
* ixgbe_set_mta - Set bit-vector in multicast table
* @hw: pointer to hardware structure
* @hash_value: Multicast address hash value
*
* Sets the bit-vector in the multicast table.
**/
static void ixgbe_set_mta(struct ixgbe_hw *hw, u8 *mc_addr)
{
u32 vector;
u32 vector_bit;
u32 vector_reg;
hw->addr_ctrl.mta_in_use++;
vector = ixgbe_mta_vector(hw, mc_addr);
hw_dbg(hw, " bit-vector = 0x%03X\n", vector);
/*
* The MTA is a register array of 128 32-bit registers. It is treated
* like an array of 4096 bits. We want to set bit
* BitArray[vector_value]. So we figure out what register the bit is
* in, read it, OR in the new bit, then write back the new value. The
* register is determined by the upper 7 bits of the vector value and
* the bit within that register are determined by the lower 5 bits of
* the value.
*/
vector_reg = (vector >> 5) & 0x7F;
vector_bit = vector & 0x1F;
hw->mac.mta_shadow[vector_reg] |= (1 << vector_bit);
}
/**
* ixgbe_update_mc_addr_list_generic - Updates MAC list of multicast addresses
* @hw: pointer to hardware structure
* @netdev: pointer to net device structure
*
* The given list replaces any existing list. Clears the MC addrs from receive
* address registers and the multicast table. Uses unused receive address
* registers for the first multicast addresses, and hashes the rest into the
* multicast table.
**/
s32 ixgbe_update_mc_addr_list_generic(struct ixgbe_hw *hw,
struct net_device *netdev)
{
struct netdev_hw_addr *ha;
u32 i;
/*
* Set the new number of MC addresses that we are being requested to
* use.
*/
hw->addr_ctrl.num_mc_addrs = netdev_mc_count(netdev);
hw->addr_ctrl.mta_in_use = 0;
/* Clear mta_shadow */
hw_dbg(hw, " Clearing MTA\n");
memset(&hw->mac.mta_shadow, 0, sizeof(hw->mac.mta_shadow));
/* Update mta shadow */
netdev_for_each_mc_addr(ha, netdev) {
hw_dbg(hw, " Adding the multicast addresses:\n");
ixgbe_set_mta(hw, ha->addr);
}
/* Enable mta */
for (i = 0; i < hw->mac.mcft_size; i++)
IXGBE_WRITE_REG_ARRAY(hw, IXGBE_MTA(0), i,
hw->mac.mta_shadow[i]);
if (hw->addr_ctrl.mta_in_use > 0)
IXGBE_WRITE_REG(hw, IXGBE_MCSTCTRL,
IXGBE_MCSTCTRL_MFE | hw->mac.mc_filter_type);
hw_dbg(hw, "ixgbe_update_mc_addr_list_generic Complete\n");
return 0;
}
/**
* ixgbe_enable_mc_generic - Enable multicast address in RAR
* @hw: pointer to hardware structure
*
* Enables multicast address in RAR and the use of the multicast hash table.
**/
s32 ixgbe_enable_mc_generic(struct ixgbe_hw *hw)
{
struct ixgbe_addr_filter_info *a = &hw->addr_ctrl;
if (a->mta_in_use > 0)
IXGBE_WRITE_REG(hw, IXGBE_MCSTCTRL, IXGBE_MCSTCTRL_MFE |
hw->mac.mc_filter_type);
return 0;
}
/**
* ixgbe_disable_mc_generic - Disable multicast address in RAR
* @hw: pointer to hardware structure
*
* Disables multicast address in RAR and the use of the multicast hash table.
**/
s32 ixgbe_disable_mc_generic(struct ixgbe_hw *hw)
{
struct ixgbe_addr_filter_info *a = &hw->addr_ctrl;
if (a->mta_in_use > 0)
IXGBE_WRITE_REG(hw, IXGBE_MCSTCTRL, hw->mac.mc_filter_type);
return 0;
}
/**
* ixgbe_fc_enable_generic - Enable flow control
* @hw: pointer to hardware structure
* @packetbuf_num: packet buffer number (0-7)
*
* Enable flow control according to the current settings.
**/
s32 ixgbe_fc_enable_generic(struct ixgbe_hw *hw, s32 packetbuf_num)
{
s32 ret_val = 0;
u32 mflcn_reg, fccfg_reg;
u32 reg;
u32 rx_pba_size;
u32 fcrtl, fcrth;
#ifdef CONFIG_DCB
if (hw->fc.requested_mode == ixgbe_fc_pfc)
goto out;
#endif /* CONFIG_DCB */
/* Negotiate the fc mode to use */
ret_val = ixgbe_fc_autoneg(hw);
if (ret_val == IXGBE_ERR_FLOW_CONTROL)
goto out;
/* Disable any previous flow control settings */
mflcn_reg = IXGBE_READ_REG(hw, IXGBE_MFLCN);
mflcn_reg &= ~(IXGBE_MFLCN_RFCE | IXGBE_MFLCN_RPFCE);
fccfg_reg = IXGBE_READ_REG(hw, IXGBE_FCCFG);
fccfg_reg &= ~(IXGBE_FCCFG_TFCE_802_3X | IXGBE_FCCFG_TFCE_PRIORITY);
/*
* The possible values of fc.current_mode are:
* 0: Flow control is completely disabled
* 1: Rx flow control is enabled (we can receive pause frames,
* but not send pause frames).
* 2: Tx flow control is enabled (we can send pause frames but
* we do not support receiving pause frames).
* 3: Both Rx and Tx flow control (symmetric) are enabled.
#ifdef CONFIG_DCB
* 4: Priority Flow Control is enabled.
#endif
* other: Invalid.
*/
switch (hw->fc.current_mode) {
case ixgbe_fc_none:
/*
* Flow control is disabled by software override or autoneg.
* The code below will actually disable it in the HW.
*/
break;
case ixgbe_fc_rx_pause:
/*
* Rx Flow control is enabled and Tx Flow control is
* disabled by software override. Since there really
* isn't a way to advertise that we are capable of RX
* Pause ONLY, we will advertise that we support both
* symmetric and asymmetric Rx PAUSE. Later, we will
* disable the adapter's ability to send PAUSE frames.
*/
mflcn_reg |= IXGBE_MFLCN_RFCE;
break;
case ixgbe_fc_tx_pause:
/*
* Tx Flow control is enabled, and Rx Flow control is
* disabled by software override.
*/
fccfg_reg |= IXGBE_FCCFG_TFCE_802_3X;
break;
case ixgbe_fc_full:
/* Flow control (both Rx and Tx) is enabled by SW override. */
mflcn_reg |= IXGBE_MFLCN_RFCE;
fccfg_reg |= IXGBE_FCCFG_TFCE_802_3X;
break;
#ifdef CONFIG_DCB
case ixgbe_fc_pfc:
goto out;
break;
#endif /* CONFIG_DCB */
default:
hw_dbg(hw, "Flow control param set incorrectly\n");
ret_val = IXGBE_ERR_CONFIG;
goto out;
break;
}
/* Set 802.3x based flow control settings. */
mflcn_reg |= IXGBE_MFLCN_DPF;
IXGBE_WRITE_REG(hw, IXGBE_MFLCN, mflcn_reg);
IXGBE_WRITE_REG(hw, IXGBE_FCCFG, fccfg_reg);
rx_pba_size = IXGBE_READ_REG(hw, IXGBE_RXPBSIZE(packetbuf_num));
rx_pba_size >>= IXGBE_RXPBSIZE_SHIFT;
fcrth = (rx_pba_size - hw->fc.high_water) << 10;
fcrtl = (rx_pba_size - hw->fc.low_water) << 10;
if (hw->fc.current_mode & ixgbe_fc_tx_pause) {
fcrth |= IXGBE_FCRTH_FCEN;
if (hw->fc.send_xon)
fcrtl |= IXGBE_FCRTL_XONE;
}
IXGBE_WRITE_REG(hw, IXGBE_FCRTH_82599(packetbuf_num), fcrth);
IXGBE_WRITE_REG(hw, IXGBE_FCRTL_82599(packetbuf_num), fcrtl);
/* Configure pause time (2 TCs per register) */
reg = IXGBE_READ_REG(hw, IXGBE_FCTTV(packetbuf_num / 2));
if ((packetbuf_num & 1) == 0)
reg = (reg & 0xFFFF0000) | hw->fc.pause_time;
else
reg = (reg & 0x0000FFFF) | (hw->fc.pause_time << 16);
IXGBE_WRITE_REG(hw, IXGBE_FCTTV(packetbuf_num / 2), reg);
IXGBE_WRITE_REG(hw, IXGBE_FCRTV, (hw->fc.pause_time >> 1));
out:
return ret_val;
}
/**
* ixgbe_fc_autoneg - Configure flow control
* @hw: pointer to hardware structure
*
* Compares our advertised flow control capabilities to those advertised by
* our link partner, and determines the proper flow control mode to use.
**/
s32 ixgbe_fc_autoneg(struct ixgbe_hw *hw)
{
s32 ret_val = IXGBE_ERR_FC_NOT_NEGOTIATED;
ixgbe_link_speed speed;
bool link_up;
if (hw->fc.disable_fc_autoneg)
goto out;
/*
* AN should have completed when the cable was plugged in.
* Look for reasons to bail out. Bail out if:
* - FC autoneg is disabled, or if
* - link is not up.
*
* Since we're being called from an LSC, link is already known to be up.
* So use link_up_wait_to_complete=false.
*/
hw->mac.ops.check_link(hw, &speed, &link_up, false);
if (!link_up) {
ret_val = IXGBE_ERR_FLOW_CONTROL;
goto out;
}
switch (hw->phy.media_type) {
/* Autoneg flow control on fiber adapters */
case ixgbe_media_type_fiber:
if (speed == IXGBE_LINK_SPEED_1GB_FULL)
ret_val = ixgbe_fc_autoneg_fiber(hw);
break;
/* Autoneg flow control on backplane adapters */
case ixgbe_media_type_backplane:
ret_val = ixgbe_fc_autoneg_backplane(hw);
break;
/* Autoneg flow control on copper adapters */
case ixgbe_media_type_copper:
if (ixgbe_device_supports_autoneg_fc(hw) == 0)
ret_val = ixgbe_fc_autoneg_copper(hw);
break;
default:
break;
}
out:
if (ret_val == 0) {
hw->fc.fc_was_autonegged = true;
} else {
hw->fc.fc_was_autonegged = false;
hw->fc.current_mode = hw->fc.requested_mode;
}
return ret_val;
}
/**
* ixgbe_fc_autoneg_fiber - Enable flow control on 1 gig fiber
* @hw: pointer to hardware structure
*
* Enable flow control according on 1 gig fiber.
**/
static s32 ixgbe_fc_autoneg_fiber(struct ixgbe_hw *hw)
{
u32 pcs_anadv_reg, pcs_lpab_reg, linkstat;
s32 ret_val;
/*
* On multispeed fiber at 1g, bail out if
* - link is up but AN did not complete, or if
* - link is up and AN completed but timed out
*/
linkstat = IXGBE_READ_REG(hw, IXGBE_PCS1GLSTA);
if (((linkstat & IXGBE_PCS1GLSTA_AN_COMPLETE) == 0) ||
((linkstat & IXGBE_PCS1GLSTA_AN_TIMED_OUT) == 1)) {
ret_val = IXGBE_ERR_FC_NOT_NEGOTIATED;
goto out;
}
pcs_anadv_reg = IXGBE_READ_REG(hw, IXGBE_PCS1GANA);
pcs_lpab_reg = IXGBE_READ_REG(hw, IXGBE_PCS1GANLP);
ret_val = ixgbe_negotiate_fc(hw, pcs_anadv_reg,
pcs_lpab_reg, IXGBE_PCS1GANA_SYM_PAUSE,
IXGBE_PCS1GANA_ASM_PAUSE,
IXGBE_PCS1GANA_SYM_PAUSE,
IXGBE_PCS1GANA_ASM_PAUSE);
out:
return ret_val;
}
/**
* ixgbe_fc_autoneg_backplane - Enable flow control IEEE clause 37
* @hw: pointer to hardware structure
*
* Enable flow control according to IEEE clause 37.
**/
static s32 ixgbe_fc_autoneg_backplane(struct ixgbe_hw *hw)
{
u32 links2, anlp1_reg, autoc_reg, links;
s32 ret_val;
/*
* On backplane, bail out if
* - backplane autoneg was not completed, or if
* - we are 82599 and link partner is not AN enabled
*/
links = IXGBE_READ_REG(hw, IXGBE_LINKS);
if ((links & IXGBE_LINKS_KX_AN_COMP) == 0) {
hw->fc.fc_was_autonegged = false;
hw->fc.current_mode = hw->fc.requested_mode;
ret_val = IXGBE_ERR_FC_NOT_NEGOTIATED;
goto out;
}
if (hw->mac.type == ixgbe_mac_82599EB) {
links2 = IXGBE_READ_REG(hw, IXGBE_LINKS2);
if ((links2 & IXGBE_LINKS2_AN_SUPPORTED) == 0) {
hw->fc.fc_was_autonegged = false;
hw->fc.current_mode = hw->fc.requested_mode;
ret_val = IXGBE_ERR_FC_NOT_NEGOTIATED;
goto out;
}
}
/*
* Read the 10g AN autoc and LP ability registers and resolve
* local flow control settings accordingly
*/
autoc_reg = IXGBE_READ_REG(hw, IXGBE_AUTOC);
anlp1_reg = IXGBE_READ_REG(hw, IXGBE_ANLP1);
ret_val = ixgbe_negotiate_fc(hw, autoc_reg,
anlp1_reg, IXGBE_AUTOC_SYM_PAUSE, IXGBE_AUTOC_ASM_PAUSE,
IXGBE_ANLP1_SYM_PAUSE, IXGBE_ANLP1_ASM_PAUSE);
out:
return ret_val;
}
/**
* ixgbe_fc_autoneg_copper - Enable flow control IEEE clause 37
* @hw: pointer to hardware structure
*
* Enable flow control according to IEEE clause 37.
**/
static s32 ixgbe_fc_autoneg_copper(struct ixgbe_hw *hw)
{
u16 technology_ability_reg = 0;
u16 lp_technology_ability_reg = 0;
hw->phy.ops.read_reg(hw, MDIO_AN_ADVERTISE,
MDIO_MMD_AN,
&technology_ability_reg);
hw->phy.ops.read_reg(hw, MDIO_AN_LPA,
MDIO_MMD_AN,
&lp_technology_ability_reg);
return ixgbe_negotiate_fc(hw, (u32)technology_ability_reg,
(u32)lp_technology_ability_reg,
IXGBE_TAF_SYM_PAUSE, IXGBE_TAF_ASM_PAUSE,
IXGBE_TAF_SYM_PAUSE, IXGBE_TAF_ASM_PAUSE);
}
/**
* ixgbe_negotiate_fc - Negotiate flow control
* @hw: pointer to hardware structure
* @adv_reg: flow control advertised settings
* @lp_reg: link partner's flow control settings
* @adv_sym: symmetric pause bit in advertisement
* @adv_asm: asymmetric pause bit in advertisement
* @lp_sym: symmetric pause bit in link partner advertisement
* @lp_asm: asymmetric pause bit in link partner advertisement
*
* Find the intersection between advertised settings and link partner's
* advertised settings
**/
static s32 ixgbe_negotiate_fc(struct ixgbe_hw *hw, u32 adv_reg, u32 lp_reg,
u32 adv_sym, u32 adv_asm, u32 lp_sym, u32 lp_asm)
{
if ((!(adv_reg)) || (!(lp_reg)))
return IXGBE_ERR_FC_NOT_NEGOTIATED;
if ((adv_reg & adv_sym) && (lp_reg & lp_sym)) {
/*
* Now we need to check if the user selected Rx ONLY
* of pause frames. In this case, we had to advertise
* FULL flow control because we could not advertise RX
* ONLY. Hence, we must now check to see if we need to
* turn OFF the TRANSMISSION of PAUSE frames.
*/
if (hw->fc.requested_mode == ixgbe_fc_full) {
hw->fc.current_mode = ixgbe_fc_full;
hw_dbg(hw, "Flow Control = FULL.\n");
} else {
hw->fc.current_mode = ixgbe_fc_rx_pause;
hw_dbg(hw, "Flow Control=RX PAUSE frames only\n");
}
} else if (!(adv_reg & adv_sym) && (adv_reg & adv_asm) &&
(lp_reg & lp_sym) && (lp_reg & lp_asm)) {
hw->fc.current_mode = ixgbe_fc_tx_pause;
hw_dbg(hw, "Flow Control = TX PAUSE frames only.\n");
} else if ((adv_reg & adv_sym) && (adv_reg & adv_asm) &&
!(lp_reg & lp_sym) && (lp_reg & lp_asm)) {
hw->fc.current_mode = ixgbe_fc_rx_pause;
hw_dbg(hw, "Flow Control = RX PAUSE frames only.\n");
} else {
hw->fc.current_mode = ixgbe_fc_none;
hw_dbg(hw, "Flow Control = NONE.\n");
}
return 0;
}
/**
* ixgbe_setup_fc - Set up flow control
* @hw: pointer to hardware structure
*
* Called at init time to set up flow control.
**/
static s32 ixgbe_setup_fc(struct ixgbe_hw *hw, s32 packetbuf_num)
{
s32 ret_val = 0;
u32 reg = 0, reg_bp = 0;
u16 reg_cu = 0;
#ifdef CONFIG_DCB
if (hw->fc.requested_mode == ixgbe_fc_pfc) {
hw->fc.current_mode = hw->fc.requested_mode;
goto out;
}
#endif /* CONFIG_DCB */
/* Validate the packetbuf configuration */
if (packetbuf_num < 0 || packetbuf_num > 7) {
hw_dbg(hw, "Invalid packet buffer number [%d], expected range "
"is 0-7\n", packetbuf_num);
ret_val = IXGBE_ERR_INVALID_LINK_SETTINGS;
goto out;
}
/*
* Validate the water mark configuration. Zero water marks are invalid
* because it causes the controller to just blast out fc packets.
*/
if (!hw->fc.low_water || !hw->fc.high_water || !hw->fc.pause_time) {
hw_dbg(hw, "Invalid water mark configuration\n");
ret_val = IXGBE_ERR_INVALID_LINK_SETTINGS;
goto out;
}
/*
* Validate the requested mode. Strict IEEE mode does not allow
* ixgbe_fc_rx_pause because it will cause us to fail at UNH.
*/
if (hw->fc.strict_ieee && hw->fc.requested_mode == ixgbe_fc_rx_pause) {
hw_dbg(hw, "ixgbe_fc_rx_pause not valid in strict "
"IEEE mode\n");
ret_val = IXGBE_ERR_INVALID_LINK_SETTINGS;
goto out;
}
/*
* 10gig parts do not have a word in the EEPROM to determine the
* default flow control setting, so we explicitly set it to full.
*/
if (hw->fc.requested_mode == ixgbe_fc_default)
hw->fc.requested_mode = ixgbe_fc_full;
/*
* Set up the 1G and 10G flow control advertisement registers so the
* HW will be able to do fc autoneg once the cable is plugged in. If
* we link at 10G, the 1G advertisement is harmless and vice versa.
*/
switch (hw->phy.media_type) {
case ixgbe_media_type_fiber:
case ixgbe_media_type_backplane:
reg = IXGBE_READ_REG(hw, IXGBE_PCS1GANA);
reg_bp = IXGBE_READ_REG(hw, IXGBE_AUTOC);
break;
case ixgbe_media_type_copper:
hw->phy.ops.read_reg(hw, MDIO_AN_ADVERTISE,
MDIO_MMD_AN, ®_cu);
break;
default:
;
}
/*
* The possible values of fc.requested_mode are:
* 0: Flow control is completely disabled
* 1: Rx flow control is enabled (we can receive pause frames,
* but not send pause frames).
* 2: Tx flow control is enabled (we can send pause frames but
* we do not support receiving pause frames).
* 3: Both Rx and Tx flow control (symmetric) are enabled.
#ifdef CONFIG_DCB
* 4: Priority Flow Control is enabled.
#endif
* other: Invalid.
*/
switch (hw->fc.requested_mode) {
case ixgbe_fc_none:
/* Flow control completely disabled by software override. */
reg &= ~(IXGBE_PCS1GANA_SYM_PAUSE | IXGBE_PCS1GANA_ASM_PAUSE);
if (hw->phy.media_type == ixgbe_media_type_backplane)
reg_bp &= ~(IXGBE_AUTOC_SYM_PAUSE |
IXGBE_AUTOC_ASM_PAUSE);
else if (hw->phy.media_type == ixgbe_media_type_copper)
reg_cu &= ~(IXGBE_TAF_SYM_PAUSE | IXGBE_TAF_ASM_PAUSE);
break;
case ixgbe_fc_rx_pause:
/*
* Rx Flow control is enabled and Tx Flow control is
* disabled by software override. Since there really
* isn't a way to advertise that we are capable of RX
* Pause ONLY, we will advertise that we support both
* symmetric and asymmetric Rx PAUSE. Later, we will
* disable the adapter's ability to send PAUSE frames.
*/
reg |= (IXGBE_PCS1GANA_SYM_PAUSE | IXGBE_PCS1GANA_ASM_PAUSE);
if (hw->phy.media_type == ixgbe_media_type_backplane)
reg_bp |= (IXGBE_AUTOC_SYM_PAUSE |
IXGBE_AUTOC_ASM_PAUSE);
else if (hw->phy.media_type == ixgbe_media_type_copper)
reg_cu |= (IXGBE_TAF_SYM_PAUSE | IXGBE_TAF_ASM_PAUSE);
break;
case ixgbe_fc_tx_pause:
/*
* Tx Flow control is enabled, and Rx Flow control is
* disabled by software override.
*/
reg |= (IXGBE_PCS1GANA_ASM_PAUSE);
reg &= ~(IXGBE_PCS1GANA_SYM_PAUSE);
if (hw->phy.media_type == ixgbe_media_type_backplane) {
reg_bp |= (IXGBE_AUTOC_ASM_PAUSE);
reg_bp &= ~(IXGBE_AUTOC_SYM_PAUSE);
} else if (hw->phy.media_type == ixgbe_media_type_copper) {
reg_cu |= (IXGBE_TAF_ASM_PAUSE);
reg_cu &= ~(IXGBE_TAF_SYM_PAUSE);
}
break;
case ixgbe_fc_full:
/* Flow control (both Rx and Tx) is enabled by SW override. */
reg |= (IXGBE_PCS1GANA_SYM_PAUSE | IXGBE_PCS1GANA_ASM_PAUSE);
if (hw->phy.media_type == ixgbe_media_type_backplane)
reg_bp |= (IXGBE_AUTOC_SYM_PAUSE |
IXGBE_AUTOC_ASM_PAUSE);
else if (hw->phy.media_type == ixgbe_media_type_copper)
reg_cu |= (IXGBE_TAF_SYM_PAUSE | IXGBE_TAF_ASM_PAUSE);
break;
#ifdef CONFIG_DCB
case ixgbe_fc_pfc:
goto out;
break;
#endif /* CONFIG_DCB */
default:
hw_dbg(hw, "Flow control param set incorrectly\n");
ret_val = IXGBE_ERR_CONFIG;
goto out;
break;
}
if (hw->mac.type != ixgbe_mac_X540) {
/*
* Enable auto-negotiation between the MAC & PHY;
* the MAC will advertise clause 37 flow control.
*/
IXGBE_WRITE_REG(hw, IXGBE_PCS1GANA, reg);
reg = IXGBE_READ_REG(hw, IXGBE_PCS1GLCTL);
/* Disable AN timeout */
if (hw->fc.strict_ieee)
reg &= ~IXGBE_PCS1GLCTL_AN_1G_TIMEOUT_EN;
IXGBE_WRITE_REG(hw, IXGBE_PCS1GLCTL, reg);
hw_dbg(hw, "Set up FC; PCS1GLCTL = 0x%08X\n", reg);
}
/*
* AUTOC restart handles negotiation of 1G and 10G on backplane
* and copper. There is no need to set the PCS1GCTL register.
*
*/
if (hw->phy.media_type == ixgbe_media_type_backplane) {
reg_bp |= IXGBE_AUTOC_AN_RESTART;
IXGBE_WRITE_REG(hw, IXGBE_AUTOC, reg_bp);
} else if ((hw->phy.media_type == ixgbe_media_type_copper) &&
(ixgbe_device_supports_autoneg_fc(hw) == 0)) {
hw->phy.ops.write_reg(hw, MDIO_AN_ADVERTISE,
MDIO_MMD_AN, reg_cu);
}
hw_dbg(hw, "Set up FC; IXGBE_AUTOC = 0x%08X\n", reg);
out:
return ret_val;
}
/**
* ixgbe_disable_pcie_master - Disable PCI-express master access
* @hw: pointer to hardware structure
*
* Disables PCI-Express master access and verifies there are no pending
* requests. IXGBE_ERR_MASTER_REQUESTS_PENDING is returned if master disable
* bit hasn't caused the master requests to be disabled, else 0
* is returned signifying master requests disabled.
**/
s32 ixgbe_disable_pcie_master(struct ixgbe_hw *hw)
{
struct ixgbe_adapter *adapter = hw->back;
u32 i;
u32 reg_val;
u32 number_of_queues;
s32 status = 0;
u16 dev_status = 0;
/* Just jump out if bus mastering is already disabled */
if (!(IXGBE_READ_REG(hw, IXGBE_STATUS) & IXGBE_STATUS_GIO))
goto out;
/* Disable the receive unit by stopping each queue */
number_of_queues = hw->mac.max_rx_queues;
for (i = 0; i < number_of_queues; i++) {
reg_val = IXGBE_READ_REG(hw, IXGBE_RXDCTL(i));
if (reg_val & IXGBE_RXDCTL_ENABLE) {
reg_val &= ~IXGBE_RXDCTL_ENABLE;
IXGBE_WRITE_REG(hw, IXGBE_RXDCTL(i), reg_val);
}
}
reg_val = IXGBE_READ_REG(hw, IXGBE_CTRL);
reg_val |= IXGBE_CTRL_GIO_DIS;
IXGBE_WRITE_REG(hw, IXGBE_CTRL, reg_val);
for (i = 0; i < IXGBE_PCI_MASTER_DISABLE_TIMEOUT; i++) {
if (!(IXGBE_READ_REG(hw, IXGBE_STATUS) & IXGBE_STATUS_GIO))
goto check_device_status;
udelay(100);
}
hw_dbg(hw, "GIO Master Disable bit didn't clear - requesting resets\n");
status = IXGBE_ERR_MASTER_REQUESTS_PENDING;
/*
* Before proceeding, make sure that the PCIe block does not have
* transactions pending.
*/
check_device_status:
for (i = 0; i < IXGBE_PCI_MASTER_DISABLE_TIMEOUT; i++) {
pci_read_config_word(adapter->pdev, IXGBE_PCI_DEVICE_STATUS,
&dev_status);
if (!(dev_status & IXGBE_PCI_DEVICE_STATUS_TRANSACTION_PENDING))
break;
udelay(100);
}
if (i == IXGBE_PCI_MASTER_DISABLE_TIMEOUT)
hw_dbg(hw, "PCIe transaction pending bit also did not clear.\n");
else
goto out;
/*
* Two consecutive resets are required via CTRL.RST per datasheet
* 5.2.5.3.2 Master Disable. We set a flag to inform the reset routine
* of this need. The first reset prevents new master requests from
* being issued by our device. We then must wait 1usec for any
* remaining completions from the PCIe bus to trickle in, and then reset
* again to clear out any effects they may have had on our device.
*/
hw->mac.flags |= IXGBE_FLAGS_DOUBLE_RESET_REQUIRED;
out:
return status;
}
/**
* ixgbe_acquire_swfw_sync - Acquire SWFW semaphore
* @hw: pointer to hardware structure
* @mask: Mask to specify which semaphore to acquire
*
* Acquires the SWFW semaphore through the GSSR register for the specified
* function (CSR, PHY0, PHY1, EEPROM, Flash)
**/
s32 ixgbe_acquire_swfw_sync(struct ixgbe_hw *hw, u16 mask)
{
u32 gssr;
u32 swmask = mask;
u32 fwmask = mask << 5;
s32 timeout = 200;
while (timeout) {
/*
* SW EEPROM semaphore bit is used for access to all
* SW_FW_SYNC/GSSR bits (not just EEPROM)
*/
if (ixgbe_get_eeprom_semaphore(hw))
return IXGBE_ERR_SWFW_SYNC;
gssr = IXGBE_READ_REG(hw, IXGBE_GSSR);
if (!(gssr & (fwmask | swmask)))
break;
/*
* Firmware currently using resource (fwmask) or other software
* thread currently using resource (swmask)
*/
ixgbe_release_eeprom_semaphore(hw);
usleep_range(5000, 10000);
timeout--;
}
if (!timeout) {
hw_dbg(hw, "Driver can't access resource, SW_FW_SYNC timeout.\n");
return IXGBE_ERR_SWFW_SYNC;
}
gssr |= swmask;
IXGBE_WRITE_REG(hw, IXGBE_GSSR, gssr);
ixgbe_release_eeprom_semaphore(hw);
return 0;
}
/**
* ixgbe_release_swfw_sync - Release SWFW semaphore
* @hw: pointer to hardware structure
* @mask: Mask to specify which semaphore to release
*
* Releases the SWFW semaphore through the GSSR register for the specified
* function (CSR, PHY0, PHY1, EEPROM, Flash)
**/
void ixgbe_release_swfw_sync(struct ixgbe_hw *hw, u16 mask)
{
u32 gssr;
u32 swmask = mask;
ixgbe_get_eeprom_semaphore(hw);
gssr = IXGBE_READ_REG(hw, IXGBE_GSSR);
gssr &= ~swmask;
IXGBE_WRITE_REG(hw, IXGBE_GSSR, gssr);
ixgbe_release_eeprom_semaphore(hw);
}
/**
* ixgbe_enable_rx_dma_generic - Enable the Rx DMA unit
* @hw: pointer to hardware structure
* @regval: register value to write to RXCTRL
*
* Enables the Rx DMA unit
**/
s32 ixgbe_enable_rx_dma_generic(struct ixgbe_hw *hw, u32 regval)
{
IXGBE_WRITE_REG(hw, IXGBE_RXCTRL, regval);
return 0;
}
/**
* ixgbe_blink_led_start_generic - Blink LED based on index.
* @hw: pointer to hardware structure
* @index: led number to blink
**/
s32 ixgbe_blink_led_start_generic(struct ixgbe_hw *hw, u32 index)
{
ixgbe_link_speed speed = 0;
bool link_up = 0;
u32 autoc_reg = IXGBE_READ_REG(hw, IXGBE_AUTOC);
u32 led_reg = IXGBE_READ_REG(hw, IXGBE_LEDCTL);
/*
* Link must be up to auto-blink the LEDs;
* Force it if link is down.
*/
hw->mac.ops.check_link(hw, &speed, &link_up, false);
if (!link_up) {
autoc_reg |= IXGBE_AUTOC_AN_RESTART;
autoc_reg |= IXGBE_AUTOC_FLU;
IXGBE_WRITE_REG(hw, IXGBE_AUTOC, autoc_reg);
usleep_range(10000, 20000);
}
led_reg &= ~IXGBE_LED_MODE_MASK(index);
led_reg |= IXGBE_LED_BLINK(index);
IXGBE_WRITE_REG(hw, IXGBE_LEDCTL, led_reg);
IXGBE_WRITE_FLUSH(hw);
return 0;
}
/**
* ixgbe_blink_led_stop_generic - Stop blinking LED based on index.
* @hw: pointer to hardware structure
* @index: led number to stop blinking
**/
s32 ixgbe_blink_led_stop_generic(struct ixgbe_hw *hw, u32 index)
{
u32 autoc_reg = IXGBE_READ_REG(hw, IXGBE_AUTOC);
u32 led_reg = IXGBE_READ_REG(hw, IXGBE_LEDCTL);
autoc_reg &= ~IXGBE_AUTOC_FLU;
autoc_reg |= IXGBE_AUTOC_AN_RESTART;
IXGBE_WRITE_REG(hw, IXGBE_AUTOC, autoc_reg);
led_reg &= ~IXGBE_LED_MODE_MASK(index);
led_reg &= ~IXGBE_LED_BLINK(index);
led_reg |= IXGBE_LED_LINK_ACTIVE << IXGBE_LED_MODE_SHIFT(index);
IXGBE_WRITE_REG(hw, IXGBE_LEDCTL, led_reg);
IXGBE_WRITE_FLUSH(hw);
return 0;
}
/**
* ixgbe_get_san_mac_addr_offset - Get SAN MAC address offset from the EEPROM
* @hw: pointer to hardware structure
* @san_mac_offset: SAN MAC address offset
*
* This function will read the EEPROM location for the SAN MAC address
* pointer, and returns the value at that location. This is used in both
* get and set mac_addr routines.
**/
static s32 ixgbe_get_san_mac_addr_offset(struct ixgbe_hw *hw,
u16 *san_mac_offset)
{
/*
* First read the EEPROM pointer to see if the MAC addresses are
* available.
*/
hw->eeprom.ops.read(hw, IXGBE_SAN_MAC_ADDR_PTR, san_mac_offset);
return 0;
}
/**
* ixgbe_get_san_mac_addr_generic - SAN MAC address retrieval from the EEPROM
* @hw: pointer to hardware structure
* @san_mac_addr: SAN MAC address
*
* Reads the SAN MAC address from the EEPROM, if it's available. This is
* per-port, so set_lan_id() must be called before reading the addresses.
* set_lan_id() is called by identify_sfp(), but this cannot be relied
* upon for non-SFP connections, so we must call it here.
**/
s32 ixgbe_get_san_mac_addr_generic(struct ixgbe_hw *hw, u8 *san_mac_addr)
{
u16 san_mac_data, san_mac_offset;
u8 i;
/*
* First read the EEPROM pointer to see if the MAC addresses are
* available. If they're not, no point in calling set_lan_id() here.
*/
ixgbe_get_san_mac_addr_offset(hw, &san_mac_offset);
if ((san_mac_offset == 0) || (san_mac_offset == 0xFFFF)) {
/*
* No addresses available in this EEPROM. It's not an
* error though, so just wipe the local address and return.
*/
for (i = 0; i < 6; i++)
san_mac_addr[i] = 0xFF;
goto san_mac_addr_out;
}
/* make sure we know which port we need to program */
hw->mac.ops.set_lan_id(hw);
/* apply the port offset to the address offset */
(hw->bus.func) ? (san_mac_offset += IXGBE_SAN_MAC_ADDR_PORT1_OFFSET) :
(san_mac_offset += IXGBE_SAN_MAC_ADDR_PORT0_OFFSET);
for (i = 0; i < 3; i++) {
hw->eeprom.ops.read(hw, san_mac_offset, &san_mac_data);
san_mac_addr[i * 2] = (u8)(san_mac_data);
san_mac_addr[i * 2 + 1] = (u8)(san_mac_data >> 8);
san_mac_offset++;
}
san_mac_addr_out:
return 0;
}
/**
* ixgbe_get_pcie_msix_count_generic - Gets MSI-X vector count
* @hw: pointer to hardware structure
*
* Read PCIe configuration space, and get the MSI-X vector count from
* the capabilities table.
**/
u32 ixgbe_get_pcie_msix_count_generic(struct ixgbe_hw *hw)
{
struct ixgbe_adapter *adapter = hw->back;
u16 msix_count;
pci_read_config_word(adapter->pdev, IXGBE_PCIE_MSIX_82599_CAPS,
&msix_count);
msix_count &= IXGBE_PCIE_MSIX_TBL_SZ_MASK;
/* MSI-X count is zero-based in HW, so increment to give proper value */
msix_count++;
return msix_count;
}
/**
* ixgbe_clear_vmdq_generic - Disassociate a VMDq pool index from a rx address
* @hw: pointer to hardware struct
* @rar: receive address register index to disassociate
* @vmdq: VMDq pool index to remove from the rar
**/
s32 ixgbe_clear_vmdq_generic(struct ixgbe_hw *hw, u32 rar, u32 vmdq)
{
u32 mpsar_lo, mpsar_hi;
u32 rar_entries = hw->mac.num_rar_entries;
/* Make sure we are using a valid rar index range */
if (rar >= rar_entries) {
hw_dbg(hw, "RAR index %d is out of range.\n", rar);
return IXGBE_ERR_INVALID_ARGUMENT;
}
mpsar_lo = IXGBE_READ_REG(hw, IXGBE_MPSAR_LO(rar));
mpsar_hi = IXGBE_READ_REG(hw, IXGBE_MPSAR_HI(rar));
if (!mpsar_lo && !mpsar_hi)
goto done;
if (vmdq == IXGBE_CLEAR_VMDQ_ALL) {
if (mpsar_lo) {
IXGBE_WRITE_REG(hw, IXGBE_MPSAR_LO(rar), 0);
mpsar_lo = 0;
}
if (mpsar_hi) {
IXGBE_WRITE_REG(hw, IXGBE_MPSAR_HI(rar), 0);
mpsar_hi = 0;
}
} else if (vmdq < 32) {
mpsar_lo &= ~(1 << vmdq);
IXGBE_WRITE_REG(hw, IXGBE_MPSAR_LO(rar), mpsar_lo);
} else {
mpsar_hi &= ~(1 << (vmdq - 32));
IXGBE_WRITE_REG(hw, IXGBE_MPSAR_HI(rar), mpsar_hi);
}
/* was that the last pool using this rar? */
if (mpsar_lo == 0 && mpsar_hi == 0 && rar != 0)
hw->mac.ops.clear_rar(hw, rar);
done:
return 0;
}
/**
* ixgbe_set_vmdq_generic - Associate a VMDq pool index with a rx address
* @hw: pointer to hardware struct
* @rar: receive address register index to associate with a VMDq index
* @vmdq: VMDq pool index
**/
s32 ixgbe_set_vmdq_generic(struct ixgbe_hw *hw, u32 rar, u32 vmdq)
{
u32 mpsar;
u32 rar_entries = hw->mac.num_rar_entries;
/* Make sure we are using a valid rar index range */
if (rar >= rar_entries) {
hw_dbg(hw, "RAR index %d is out of range.\n", rar);
return IXGBE_ERR_INVALID_ARGUMENT;
}
if (vmdq < 32) {
mpsar = IXGBE_READ_REG(hw, IXGBE_MPSAR_LO(rar));
mpsar |= 1 << vmdq;
IXGBE_WRITE_REG(hw, IXGBE_MPSAR_LO(rar), mpsar);
} else {
mpsar = IXGBE_READ_REG(hw, IXGBE_MPSAR_HI(rar));
mpsar |= 1 << (vmdq - 32);
IXGBE_WRITE_REG(hw, IXGBE_MPSAR_HI(rar), mpsar);
}
return 0;
}
/**
* ixgbe_init_uta_tables_generic - Initialize the Unicast Table Array
* @hw: pointer to hardware structure
**/
s32 ixgbe_init_uta_tables_generic(struct ixgbe_hw *hw)
{
int i;
for (i = 0; i < 128; i++)
IXGBE_WRITE_REG(hw, IXGBE_UTA(i), 0);
return 0;
}
/**
* ixgbe_find_vlvf_slot - find the vlanid or the first empty slot
* @hw: pointer to hardware structure
* @vlan: VLAN id to write to VLAN filter
*
* return the VLVF index where this VLAN id should be placed
*
**/
static s32 ixgbe_find_vlvf_slot(struct ixgbe_hw *hw, u32 vlan)
{
u32 bits = 0;
u32 first_empty_slot = 0;
s32 regindex;
/* short cut the special case */
if (vlan == 0)
return 0;
/*
* Search for the vlan id in the VLVF entries. Save off the first empty
* slot found along the way
*/
for (regindex = 1; regindex < IXGBE_VLVF_ENTRIES; regindex++) {
bits = IXGBE_READ_REG(hw, IXGBE_VLVF(regindex));
if (!bits && !(first_empty_slot))
first_empty_slot = regindex;
else if ((bits & 0x0FFF) == vlan)
break;
}
/*
* If regindex is less than IXGBE_VLVF_ENTRIES, then we found the vlan
* in the VLVF. Else use the first empty VLVF register for this
* vlan id.
*/
if (regindex >= IXGBE_VLVF_ENTRIES) {
if (first_empty_slot)
regindex = first_empty_slot;
else {
hw_dbg(hw, "No space in VLVF.\n");
regindex = IXGBE_ERR_NO_SPACE;
}
}
return regindex;
}
/**
* ixgbe_set_vfta_generic - Set VLAN filter table
* @hw: pointer to hardware structure
* @vlan: VLAN id to write to VLAN filter
* @vind: VMDq output index that maps queue to VLAN id in VFVFB
* @vlan_on: boolean flag to turn on/off VLAN in VFVF
*
* Turn on/off specified VLAN in the VLAN filter table.
**/
s32 ixgbe_set_vfta_generic(struct ixgbe_hw *hw, u32 vlan, u32 vind,
bool vlan_on)
{
s32 regindex;
u32 bitindex;
u32 vfta;
u32 bits;
u32 vt;
u32 targetbit;
bool vfta_changed = false;
if (vlan > 4095)
return IXGBE_ERR_PARAM;
/*
* this is a 2 part operation - first the VFTA, then the
* VLVF and VLVFB if VT Mode is set
* We don't write the VFTA until we know the VLVF part succeeded.
*/
/* Part 1
* The VFTA is a bitstring made up of 128 32-bit registers
* that enable the particular VLAN id, much like the MTA:
* bits[11-5]: which register
* bits[4-0]: which bit in the register
*/
regindex = (vlan >> 5) & 0x7F;
bitindex = vlan & 0x1F;
targetbit = (1 << bitindex);
vfta = IXGBE_READ_REG(hw, IXGBE_VFTA(regindex));
if (vlan_on) {
if (!(vfta & targetbit)) {
vfta |= targetbit;
vfta_changed = true;
}
} else {
if ((vfta & targetbit)) {
vfta &= ~targetbit;
vfta_changed = true;
}
}
/* Part 2
* If VT Mode is set
* Either vlan_on
* make sure the vlan is in VLVF
* set the vind bit in the matching VLVFB
* Or !vlan_on
* clear the pool bit and possibly the vind
*/
vt = IXGBE_READ_REG(hw, IXGBE_VT_CTL);
if (vt & IXGBE_VT_CTL_VT_ENABLE) {
s32 vlvf_index;
vlvf_index = ixgbe_find_vlvf_slot(hw, vlan);
if (vlvf_index < 0)
return vlvf_index;
if (vlan_on) {
/* set the pool bit */
if (vind < 32) {
bits = IXGBE_READ_REG(hw,
IXGBE_VLVFB(vlvf_index*2));
bits |= (1 << vind);
IXGBE_WRITE_REG(hw,
IXGBE_VLVFB(vlvf_index*2),
bits);
} else {
bits = IXGBE_READ_REG(hw,
IXGBE_VLVFB((vlvf_index*2)+1));
bits |= (1 << (vind-32));
IXGBE_WRITE_REG(hw,
IXGBE_VLVFB((vlvf_index*2)+1),
bits);
}
} else {
/* clear the pool bit */
if (vind < 32) {
bits = IXGBE_READ_REG(hw,
IXGBE_VLVFB(vlvf_index*2));
bits &= ~(1 << vind);
IXGBE_WRITE_REG(hw,
IXGBE_VLVFB(vlvf_index*2),
bits);
bits |= IXGBE_READ_REG(hw,
IXGBE_VLVFB((vlvf_index*2)+1));
} else {
bits = IXGBE_READ_REG(hw,
IXGBE_VLVFB((vlvf_index*2)+1));
bits &= ~(1 << (vind-32));
IXGBE_WRITE_REG(hw,
IXGBE_VLVFB((vlvf_index*2)+1),
bits);
bits |= IXGBE_READ_REG(hw,
IXGBE_VLVFB(vlvf_index*2));
}
}
/*
* If there are still bits set in the VLVFB registers
* for the VLAN ID indicated we need to see if the
* caller is requesting that we clear the VFTA entry bit.
* If the caller has requested that we clear the VFTA
* entry bit but there are still pools/VFs using this VLAN
* ID entry then ignore the request. We're not worried
* about the case where we're turning the VFTA VLAN ID
* entry bit on, only when requested to turn it off as
* there may be multiple pools and/or VFs using the
* VLAN ID entry. In that case we cannot clear the
* VFTA bit until all pools/VFs using that VLAN ID have also
* been cleared. This will be indicated by "bits" being
* zero.
*/
if (bits) {
IXGBE_WRITE_REG(hw, IXGBE_VLVF(vlvf_index),
(IXGBE_VLVF_VIEN | vlan));
if (!vlan_on) {
/* someone wants to clear the vfta entry
* but some pools/VFs are still using it.
* Ignore it. */
vfta_changed = false;
}
}
else
IXGBE_WRITE_REG(hw, IXGBE_VLVF(vlvf_index), 0);
}
if (vfta_changed)
IXGBE_WRITE_REG(hw, IXGBE_VFTA(regindex), vfta);
return 0;
}
/**
* ixgbe_clear_vfta_generic - Clear VLAN filter table
* @hw: pointer to hardware structure
*
* Clears the VLAN filer table, and the VMDq index associated with the filter
**/
s32 ixgbe_clear_vfta_generic(struct ixgbe_hw *hw)
{
u32 offset;
for (offset = 0; offset < hw->mac.vft_size; offset++)
IXGBE_WRITE_REG(hw, IXGBE_VFTA(offset), 0);
for (offset = 0; offset < IXGBE_VLVF_ENTRIES; offset++) {
IXGBE_WRITE_REG(hw, IXGBE_VLVF(offset), 0);
IXGBE_WRITE_REG(hw, IXGBE_VLVFB(offset*2), 0);
IXGBE_WRITE_REG(hw, IXGBE_VLVFB((offset*2)+1), 0);
}
return 0;
}
/**
* ixgbe_check_mac_link_generic - Determine link and speed status
* @hw: pointer to hardware structure
* @speed: pointer to link speed
* @link_up: true when link is up
* @link_up_wait_to_complete: bool used to wait for link up or not
*
* Reads the links register to determine if link is up and the current speed
**/
s32 ixgbe_check_mac_link_generic(struct ixgbe_hw *hw, ixgbe_link_speed *speed,
bool *link_up, bool link_up_wait_to_complete)
{
u32 links_reg, links_orig;
u32 i;
/* clear the old state */
links_orig = IXGBE_READ_REG(hw, IXGBE_LINKS);
links_reg = IXGBE_READ_REG(hw, IXGBE_LINKS);
if (links_orig != links_reg) {
hw_dbg(hw, "LINKS changed from %08X to %08X\n",
links_orig, links_reg);
}
if (link_up_wait_to_complete) {
for (i = 0; i < IXGBE_LINK_UP_TIME; i++) {
if (links_reg & IXGBE_LINKS_UP) {
*link_up = true;
break;
} else {
*link_up = false;
}
msleep(100);
links_reg = IXGBE_READ_REG(hw, IXGBE_LINKS);
}
} else {
if (links_reg & IXGBE_LINKS_UP)
*link_up = true;
else
*link_up = false;
}
if ((links_reg & IXGBE_LINKS_SPEED_82599) ==
IXGBE_LINKS_SPEED_10G_82599)
*speed = IXGBE_LINK_SPEED_10GB_FULL;
else if ((links_reg & IXGBE_LINKS_SPEED_82599) ==
IXGBE_LINKS_SPEED_1G_82599)
*speed = IXGBE_LINK_SPEED_1GB_FULL;
else if ((links_reg & IXGBE_LINKS_SPEED_82599) ==
IXGBE_LINKS_SPEED_100_82599)
*speed = IXGBE_LINK_SPEED_100_FULL;
else
*speed = IXGBE_LINK_SPEED_UNKNOWN;
/* if link is down, zero out the current_mode */
if (*link_up == false) {
hw->fc.current_mode = ixgbe_fc_none;
hw->fc.fc_was_autonegged = false;
}
return 0;
}
/**
* ixgbe_get_wwn_prefix_generic Get alternative WWNN/WWPN prefix from
* the EEPROM
* @hw: pointer to hardware structure
* @wwnn_prefix: the alternative WWNN prefix
* @wwpn_prefix: the alternative WWPN prefix
*
* This function will read the EEPROM from the alternative SAN MAC address
* block to check the support for the alternative WWNN/WWPN prefix support.
**/
s32 ixgbe_get_wwn_prefix_generic(struct ixgbe_hw *hw, u16 *wwnn_prefix,
u16 *wwpn_prefix)
{
u16 offset, caps;
u16 alt_san_mac_blk_offset;
/* clear output first */
*wwnn_prefix = 0xFFFF;
*wwpn_prefix = 0xFFFF;
/* check if alternative SAN MAC is supported */
hw->eeprom.ops.read(hw, IXGBE_ALT_SAN_MAC_ADDR_BLK_PTR,
&alt_san_mac_blk_offset);
if ((alt_san_mac_blk_offset == 0) ||
(alt_san_mac_blk_offset == 0xFFFF))
goto wwn_prefix_out;
/* check capability in alternative san mac address block */
offset = alt_san_mac_blk_offset + IXGBE_ALT_SAN_MAC_ADDR_CAPS_OFFSET;
hw->eeprom.ops.read(hw, offset, &caps);
if (!(caps & IXGBE_ALT_SAN_MAC_ADDR_CAPS_ALTWWN))
goto wwn_prefix_out;
/* get the corresponding prefix for WWNN/WWPN */
offset = alt_san_mac_blk_offset + IXGBE_ALT_SAN_MAC_ADDR_WWNN_OFFSET;
hw->eeprom.ops.read(hw, offset, wwnn_prefix);
offset = alt_san_mac_blk_offset + IXGBE_ALT_SAN_MAC_ADDR_WWPN_OFFSET;
hw->eeprom.ops.read(hw, offset, wwpn_prefix);
wwn_prefix_out:
return 0;
}
/**
* ixgbe_device_supports_autoneg_fc - Check if phy supports autoneg flow
* control
* @hw: pointer to hardware structure
*
* There are several phys that do not support autoneg flow control. This
* function check the device id to see if the associated phy supports
* autoneg flow control.
**/
static s32 ixgbe_device_supports_autoneg_fc(struct ixgbe_hw *hw)
{
switch (hw->device_id) {
case IXGBE_DEV_ID_X540T:
case IXGBE_DEV_ID_X540T1:
return 0;
case IXGBE_DEV_ID_82599_T3_LOM:
return 0;
default:
return IXGBE_ERR_FC_NOT_SUPPORTED;
}
}
/**
* ixgbe_set_mac_anti_spoofing - Enable/Disable MAC anti-spoofing
* @hw: pointer to hardware structure
* @enable: enable or disable switch for anti-spoofing
* @pf: Physical Function pool - do not enable anti-spoofing for the PF
*
**/
void ixgbe_set_mac_anti_spoofing(struct ixgbe_hw *hw, bool enable, int pf)
{
int j;
int pf_target_reg = pf >> 3;
int pf_target_shift = pf % 8;
u32 pfvfspoof = 0;
if (hw->mac.type == ixgbe_mac_82598EB)
return;
if (enable)
pfvfspoof = IXGBE_SPOOF_MACAS_MASK;
/*
* PFVFSPOOF register array is size 8 with 8 bits assigned to
* MAC anti-spoof enables in each register array element.
*/
for (j = 0; j < IXGBE_PFVFSPOOF_REG_COUNT; j++)
IXGBE_WRITE_REG(hw, IXGBE_PFVFSPOOF(j), pfvfspoof);
/* If not enabling anti-spoofing then done */
if (!enable)
return;
/*
* The PF should be allowed to spoof so that it can support
* emulation mode NICs. Reset the bit assigned to the PF
*/
pfvfspoof = IXGBE_READ_REG(hw, IXGBE_PFVFSPOOF(pf_target_reg));
pfvfspoof ^= (1 << pf_target_shift);
IXGBE_WRITE_REG(hw, IXGBE_PFVFSPOOF(pf_target_reg), pfvfspoof);
}
/**
* ixgbe_set_vlan_anti_spoofing - Enable/Disable VLAN anti-spoofing
* @hw: pointer to hardware structure
* @enable: enable or disable switch for VLAN anti-spoofing
* @pf: Virtual Function pool - VF Pool to set for VLAN anti-spoofing
*
**/
void ixgbe_set_vlan_anti_spoofing(struct ixgbe_hw *hw, bool enable, int vf)
{
int vf_target_reg = vf >> 3;
int vf_target_shift = vf % 8 + IXGBE_SPOOF_VLANAS_SHIFT;
u32 pfvfspoof;
if (hw->mac.type == ixgbe_mac_82598EB)
return;
pfvfspoof = IXGBE_READ_REG(hw, IXGBE_PFVFSPOOF(vf_target_reg));
if (enable)
pfvfspoof |= (1 << vf_target_shift);
else
pfvfspoof &= ~(1 << vf_target_shift);
IXGBE_WRITE_REG(hw, IXGBE_PFVFSPOOF(vf_target_reg), pfvfspoof);
}
/**
* ixgbe_get_device_caps_generic - Get additional device capabilities
* @hw: pointer to hardware structure
* @device_caps: the EEPROM word with the extra device capabilities
*
* This function will read the EEPROM location for the device capabilities,
* and return the word through device_caps.
**/
s32 ixgbe_get_device_caps_generic(struct ixgbe_hw *hw, u16 *device_caps)
{
hw->eeprom.ops.read(hw, IXGBE_DEVICE_CAPS, device_caps);
return 0;
}
|
AstroProfundis/android_kernel_samsung_sc03e
|
drivers/net/ixgbe/ixgbe_common.c
|
C
|
gpl-2.0
| 90,586
|
Webster
========
A stupid simple HTTP server, built mainly to play with sockets and threads in Python.
Author
------
toost
License
--------
[GPL/v2](LICENSE.md)
Installation
-------------
None! Provided you have Python 2.7 or higher, this should work just fine. Development and testing was done with Python 3.2.3.
Try it out with:
python3 webster.py
Currently very useless - it will only send 400, 404, or 501 replies.
|
toost/webster
|
README.md
|
Markdown
|
gpl-2.0
| 437
|
<?php
use oat\taoLti\models\classes\LtiProvider\FeatureFlagFormPropertyMapper;
use oat\taoLti\models\classes\LtiProvider\RdfLtiProviderRepository;
return new FeatureFlagFormPropertyMapper(
[
FeatureFlagFormPropertyMapper::OPTION_FEATURE_FLAG_FORM_FIELDS => [
RdfLtiProviderRepository::LTI_TOOL_IDENTIFIER => [
'FEATURE_FLAG_LTI1P3'
],
RdfLtiProviderRepository::LTI_TOOL_PUBLIC_KEY => [
'FEATURE_FLAG_LTI1P3'
],
RdfLtiProviderRepository::LTI_TOOL_JWKS_URL => [
'FEATURE_FLAG_LTI1P3'
],
RdfLtiProviderRepository::LTI_TOOL_LAUNCH_URL => [
'FEATURE_FLAG_LTI1P3'
],
RdfLtiProviderRepository::LTI_TOOL_OIDC_LOGIN_INITATION_URL => [
'FEATURE_FLAG_LTI1P3'
],
RdfLtiProviderRepository::LTI_TOOL_DEPLOYMENT_IDS => [
'FEATURE_FLAG_LTI1P3'
],
RdfLtiProviderRepository::LTI_TOOL_AUDIENCE => [
'FEATURE_FLAG_LTI1P3'
],
RdfLtiProviderRepository::LTI_TOOL_CLIENT_ID => [
'FEATURE_FLAG_LTI1P3'
],
RdfLtiProviderRepository::LTI_TOOL_NAME => [
'FEATURE_FLAG_LTI1P3'
],
RdfLtiProviderRepository::LTI_VERSION => [
'FEATURE_FLAG_LTI1P3'
],
]
]
);
|
oat-sa/extension-tao-lti
|
config/default/FeatureFlagFormPropertyMapper.conf.php
|
PHP
|
gpl-2.0
| 1,451
|
/*
*************************************************************************
* Ralink Tech Inc.
* 5F., No.36, Taiyuan St., Jhubei City,
* Hsinchu County 302,
* Taiwan, R.O.C.
*
* (c) Copyright 2002-2007, Ralink Technology, 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., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
*************************************************************************
Module Name:
oid.h
Abstract:
Revision History:
Who When What
-------- ---------- ----------------------------------------------
Name Date Modification logs
*/
#ifndef _OID_H_
#define _OID_H_
#define TRUE 1
#define FALSE 0
//
// IEEE 802.11 Structures and definitions
//
#define MAX_TX_POWER_LEVEL 100 /* mW */
#define MAX_RSSI_TRIGGER -10 /* dBm */
#define MIN_RSSI_TRIGGER -200 /* dBm */
#define MAX_FRAG_THRESHOLD 2346 /* byte count */
#define MIN_FRAG_THRESHOLD 256 /* byte count */
#define MAX_RTS_THRESHOLD 2347 /* byte count */
// new types for Media Specific Indications
// Extension channel offset
#define EXTCHA_NONE 0
#define EXTCHA_ABOVE 0x1
#define EXTCHA_BELOW 0x3
// BW
#define BAND_WIDTH_20 0
#define BAND_WIDTH_40 1
#define BAND_WIDTH_BOTH 2
#define BAND_WIDTH_10 3 // 802.11j has 10MHz. This definition is for internal usage. doesn't fill in the IE or other field.
// SHORTGI
#define GAP_INTERVAL_400 1 // only support in HT mode
#define GAP_INTERVAL_800 0
#define GAP_INTERVAL_BOTH 2
#define NdisMediaStateConnected 1
#define NdisMediaStateDisconnected 0
#define NDIS_802_11_LENGTH_SSID 32
#define NDIS_802_11_LENGTH_RATES 8
#define NDIS_802_11_LENGTH_RATES_EX 16
#define MAC_ADDR_LENGTH 6
#define MAX_NUM_OF_CHS 49 // 14 channels @2.4G + 12@UNII + 4 @MMAC + 11 @HiperLAN2 + 7 @Japan + 1 as NULL terminationc
#define MAX_NUMBER_OF_EVENT 10 // entry # in EVENT table
#define MAX_NUMBER_OF_MAC 32 // if MAX_MBSSID_NUM is 8, this value can't be larger than 211
#define MAX_NUMBER_OF_ACL 64
#define MAX_LENGTH_OF_SUPPORT_RATES 12 // 1, 2, 5.5, 11, 6, 9, 12, 18, 24, 36, 48, 54
#define MAX_NUMBER_OF_DLS_ENTRY 4
#define OID_GEN_MACHINE_NAME 0x0001021A
#define RT_QUERY_SIGNAL_CONTEXT 0x0402
#define RT_SET_IAPP_PID 0x0404
#define RT_SET_APD_PID 0x0405
#define RT_SET_DEL_MAC_ENTRY 0x0406
//
// IEEE 802.11 OIDs
//
#define OID_GET_SET_TOGGLE 0x8000
#define OID_802_11_NETWORK_TYPES_SUPPORTED 0x0103
#define OID_802_11_NETWORK_TYPE_IN_USE 0x0104
#define OID_802_11_RSSI_TRIGGER 0x0107
#define RT_OID_802_11_RSSI 0x0108 //rt2860 only , kathy
#define RT_OID_802_11_RSSI_1 0x0109 //rt2860 only , kathy
#define RT_OID_802_11_RSSI_2 0x010A //rt2860 only , kathy
#define OID_802_11_NUMBER_OF_ANTENNAS 0x010B
#define OID_802_11_RX_ANTENNA_SELECTED 0x010C
#define OID_802_11_TX_ANTENNA_SELECTED 0x010D
#define OID_802_11_SUPPORTED_RATES 0x010E
#define OID_802_11_ADD_WEP 0x0112
#define OID_802_11_REMOVE_WEP 0x0113
#define OID_802_11_DISASSOCIATE 0x0114
#define OID_802_11_PRIVACY_FILTER 0x0118
#define OID_802_11_ASSOCIATION_INFORMATION 0x011E
#define OID_802_11_TEST 0x011F
#define RT_OID_802_11_COUNTRY_REGION 0x0507
#define OID_802_11_BSSID_LIST_SCAN 0x0508
#define OID_802_11_SSID 0x0509
#define OID_802_11_BSSID 0x050A
#define RT_OID_802_11_RADIO 0x050B
#define RT_OID_802_11_PHY_MODE 0x050C
#define RT_OID_802_11_STA_CONFIG 0x050D
#define OID_802_11_DESIRED_RATES 0x050E
#define RT_OID_802_11_PREAMBLE 0x050F
#define OID_802_11_WEP_STATUS 0x0510
#define OID_802_11_AUTHENTICATION_MODE 0x0511
#define OID_802_11_INFRASTRUCTURE_MODE 0x0512
#define RT_OID_802_11_RESET_COUNTERS 0x0513
#define OID_802_11_RTS_THRESHOLD 0x0514
#define OID_802_11_FRAGMENTATION_THRESHOLD 0x0515
#define OID_802_11_POWER_MODE 0x0516
#define OID_802_11_TX_POWER_LEVEL 0x0517
#define RT_OID_802_11_ADD_WPA 0x0518
#define OID_802_11_REMOVE_KEY 0x0519
#define OID_802_11_ADD_KEY 0x0520
#define OID_802_11_CONFIGURATION 0x0521
#define OID_802_11_TX_PACKET_BURST 0x0522
#define RT_OID_802_11_QUERY_NOISE_LEVEL 0x0523
#define RT_OID_802_11_EXTRA_INFO 0x0524
#ifdef DBG
#define RT_OID_802_11_HARDWARE_REGISTER 0x0525
#endif
#define OID_802_11_ENCRYPTION_STATUS OID_802_11_WEP_STATUS
#define OID_802_11_DEAUTHENTICATION 0x0526
#define OID_802_11_DROP_UNENCRYPTED 0x0527
#define OID_802_11_MIC_FAILURE_REPORT_FRAME 0x0528
// For 802.1x daemin using to require current driver configuration
#define OID_802_11_RADIUS_QUERY_SETTING 0x0540
#define RT_OID_DEVICE_NAME 0x0607
#define RT_OID_VERSION_INFO 0x0608
#define OID_802_11_BSSID_LIST 0x0609
#define OID_802_3_CURRENT_ADDRESS 0x060A
#define OID_GEN_MEDIA_CONNECT_STATUS 0x060B
#define RT_OID_802_11_QUERY_LINK_STATUS 0x060C
#define OID_802_11_RSSI 0x060D
#define OID_802_11_STATISTICS 0x060E
#define OID_GEN_RCV_OK 0x060F
#define OID_GEN_RCV_NO_BUFFER 0x0610
#define RT_OID_802_11_QUERY_EEPROM_VERSION 0x0611
#define RT_OID_802_11_QUERY_FIRMWARE_VERSION 0x0612
#define RT_OID_802_11_QUERY_LAST_RX_RATE 0x0613
#define RT_OID_802_11_TX_POWER_LEVEL_1 0x0614
#define RT_OID_802_11_QUERY_PIDVID 0x0615
#define OID_SET_COUNTERMEASURES 0x0616
#define OID_802_11_SET_IEEE8021X 0x0617
#define OID_802_11_SET_IEEE8021X_REQUIRE_KEY 0x0618
#define OID_802_11_PMKID 0x0620
#define RT_OID_WPA_SUPPLICANT_SUPPORT 0x0621
#define RT_OID_WE_VERSION_COMPILED 0x0622
#define RT_OID_NEW_DRIVER 0x0623
//rt2860 , kathy
#define RT_OID_802_11_SNR_0 0x0630
#define RT_OID_802_11_SNR_1 0x0631
#define RT_OID_802_11_QUERY_LAST_TX_RATE 0x0632
#define RT_OID_802_11_QUERY_HT_PHYMODE 0x0633
#define RT_OID_802_11_SET_HT_PHYMODE 0x0634
#define OID_802_11_RELOAD_DEFAULTS 0x0635
#define RT_OID_802_11_QUERY_APSD_SETTING 0x0636
#define RT_OID_802_11_SET_APSD_SETTING 0x0637
#define RT_OID_802_11_QUERY_APSD_PSM 0x0638
#define RT_OID_802_11_SET_APSD_PSM 0x0639
#define RT_OID_802_11_QUERY_DLS 0x063A
#define RT_OID_802_11_SET_DLS 0x063B
#define RT_OID_802_11_QUERY_DLS_PARAM 0x063C
#define RT_OID_802_11_SET_DLS_PARAM 0x063D
#define RT_OID_802_11_QUERY_WMM 0x063E
#define RT_OID_802_11_SET_WMM 0x063F
#define RT_OID_802_11_QUERY_IMME_BA_CAP 0x0640
#define RT_OID_802_11_SET_IMME_BA_CAP 0x0641
#define RT_OID_802_11_QUERY_BATABLE 0x0642
#define RT_OID_802_11_ADD_IMME_BA 0x0643
#define RT_OID_802_11_TEAR_IMME_BA 0x0644
#define RT_OID_DRIVER_DEVICE_NAME 0x0645
#define RT_OID_802_11_QUERY_DAT_HT_PHYMODE 0x0646
#define RT_OID_QUERY_MULTIPLE_CARD_SUPPORT 0x0647
// Ralink defined OIDs
// Dennis Lee move to platform specific
#define RT_OID_802_11_BSSID (OID_GET_SET_TOGGLE | OID_802_11_BSSID)
#define RT_OID_802_11_SSID (OID_GET_SET_TOGGLE | OID_802_11_SSID)
#define RT_OID_802_11_INFRASTRUCTURE_MODE (OID_GET_SET_TOGGLE | OID_802_11_INFRASTRUCTURE_MODE)
#define RT_OID_802_11_ADD_WEP (OID_GET_SET_TOGGLE | OID_802_11_ADD_WEP)
#define RT_OID_802_11_ADD_KEY (OID_GET_SET_TOGGLE | OID_802_11_ADD_KEY)
#define RT_OID_802_11_REMOVE_WEP (OID_GET_SET_TOGGLE | OID_802_11_REMOVE_WEP)
#define RT_OID_802_11_REMOVE_KEY (OID_GET_SET_TOGGLE | OID_802_11_REMOVE_KEY)
#define RT_OID_802_11_DISASSOCIATE (OID_GET_SET_TOGGLE | OID_802_11_DISASSOCIATE)
#define RT_OID_802_11_AUTHENTICATION_MODE (OID_GET_SET_TOGGLE | OID_802_11_AUTHENTICATION_MODE)
#define RT_OID_802_11_PRIVACY_FILTER (OID_GET_SET_TOGGLE | OID_802_11_PRIVACY_FILTER)
#define RT_OID_802_11_BSSID_LIST_SCAN (OID_GET_SET_TOGGLE | OID_802_11_BSSID_LIST_SCAN)
#define RT_OID_802_11_WEP_STATUS (OID_GET_SET_TOGGLE | OID_802_11_WEP_STATUS)
#define RT_OID_802_11_RELOAD_DEFAULTS (OID_GET_SET_TOGGLE | OID_802_11_RELOAD_DEFAULTS)
#define RT_OID_802_11_NETWORK_TYPE_IN_USE (OID_GET_SET_TOGGLE | OID_802_11_NETWORK_TYPE_IN_USE)
#define RT_OID_802_11_TX_POWER_LEVEL (OID_GET_SET_TOGGLE | OID_802_11_TX_POWER_LEVEL)
#define RT_OID_802_11_RSSI_TRIGGER (OID_GET_SET_TOGGLE | OID_802_11_RSSI_TRIGGER)
#define RT_OID_802_11_FRAGMENTATION_THRESHOLD (OID_GET_SET_TOGGLE | OID_802_11_FRAGMENTATION_THRESHOLD)
#define RT_OID_802_11_RTS_THRESHOLD (OID_GET_SET_TOGGLE | OID_802_11_RTS_THRESHOLD)
#define RT_OID_802_11_RX_ANTENNA_SELECTED (OID_GET_SET_TOGGLE | OID_802_11_RX_ANTENNA_SELECTED)
#define RT_OID_802_11_TX_ANTENNA_SELECTED (OID_GET_SET_TOGGLE | OID_802_11_TX_ANTENNA_SELECTED)
#define RT_OID_802_11_SUPPORTED_RATES (OID_GET_SET_TOGGLE | OID_802_11_SUPPORTED_RATES)
#define RT_OID_802_11_DESIRED_RATES (OID_GET_SET_TOGGLE | OID_802_11_DESIRED_RATES)
#define RT_OID_802_11_CONFIGURATION (OID_GET_SET_TOGGLE | OID_802_11_CONFIGURATION)
#define RT_OID_802_11_POWER_MODE (OID_GET_SET_TOGGLE | OID_802_11_POWER_MODE)
typedef enum _NDIS_802_11_STATUS_TYPE
{
Ndis802_11StatusType_Authentication,
Ndis802_11StatusType_MediaStreamMode,
Ndis802_11StatusType_PMKID_CandidateList,
Ndis802_11StatusTypeMax // not a real type, defined as an upper bound
} NDIS_802_11_STATUS_TYPE, *PNDIS_802_11_STATUS_TYPE;
typedef UCHAR NDIS_802_11_MAC_ADDRESS[6];
typedef struct _NDIS_802_11_STATUS_INDICATION
{
NDIS_802_11_STATUS_TYPE StatusType;
} NDIS_802_11_STATUS_INDICATION, *PNDIS_802_11_STATUS_INDICATION;
// mask for authentication/integrity fields
#define NDIS_802_11_AUTH_REQUEST_AUTH_FIELDS 0x0f
#define NDIS_802_11_AUTH_REQUEST_REAUTH 0x01
#define NDIS_802_11_AUTH_REQUEST_KEYUPDATE 0x02
#define NDIS_802_11_AUTH_REQUEST_PAIRWISE_ERROR 0x06
#define NDIS_802_11_AUTH_REQUEST_GROUP_ERROR 0x0E
typedef struct _NDIS_802_11_AUTHENTICATION_REQUEST
{
ULONG Length; // Length of structure
NDIS_802_11_MAC_ADDRESS Bssid;
ULONG Flags;
} NDIS_802_11_AUTHENTICATION_REQUEST, *PNDIS_802_11_AUTHENTICATION_REQUEST;
//Added new types for PMKID Candidate lists.
typedef struct _PMKID_CANDIDATE {
NDIS_802_11_MAC_ADDRESS BSSID;
ULONG Flags;
} PMKID_CANDIDATE, *PPMKID_CANDIDATE;
typedef struct _NDIS_802_11_PMKID_CANDIDATE_LIST
{
ULONG Version; // Version of the structure
ULONG NumCandidates; // No. of pmkid candidates
PMKID_CANDIDATE CandidateList[1];
} NDIS_802_11_PMKID_CANDIDATE_LIST, *PNDIS_802_11_PMKID_CANDIDATE_LIST;
//Flags for PMKID Candidate list structure
#define NDIS_802_11_PMKID_CANDIDATE_PREAUTH_ENABLED 0x01
// Added new types for OFDM 5G and 2.4G
typedef enum _NDIS_802_11_NETWORK_TYPE
{
Ndis802_11FH,
Ndis802_11DS,
Ndis802_11OFDM5,
Ndis802_11OFDM5_N,
Ndis802_11OFDM24,
Ndis802_11OFDM24_N,
Ndis802_11Automode,
Ndis802_11NetworkTypeMax // not a real type, defined as an upper bound
} NDIS_802_11_NETWORK_TYPE, *PNDIS_802_11_NETWORK_TYPE;
typedef struct _NDIS_802_11_NETWORK_TYPE_LIST
{
UINT NumberOfItems; // in list below, at least 1
NDIS_802_11_NETWORK_TYPE NetworkType [1];
} NDIS_802_11_NETWORK_TYPE_LIST, *PNDIS_802_11_NETWORK_TYPE_LIST;
typedef enum _NDIS_802_11_POWER_MODE
{
Ndis802_11PowerModeCAM,
Ndis802_11PowerModeMAX_PSP,
Ndis802_11PowerModeFast_PSP,
Ndis802_11PowerModeLegacy_PSP,
Ndis802_11PowerModeMax // not a real mode, defined as an upper bound
} NDIS_802_11_POWER_MODE, *PNDIS_802_11_POWER_MODE;
typedef ULONG NDIS_802_11_TX_POWER_LEVEL; // in milliwatts
//
// Received Signal Strength Indication
//
typedef LONG NDIS_802_11_RSSI; // in dBm
typedef struct _NDIS_802_11_CONFIGURATION_FH
{
ULONG Length; // Length of structure
ULONG HopPattern; // As defined by 802.11, MSB set
ULONG HopSet; // to one if non-802.11
ULONG DwellTime; // units are Kusec
} NDIS_802_11_CONFIGURATION_FH, *PNDIS_802_11_CONFIGURATION_FH;
typedef struct _NDIS_802_11_CONFIGURATION
{
ULONG Length; // Length of structure
ULONG BeaconPeriod; // units are Kusec
ULONG ATIMWindow; // units are Kusec
ULONG DSConfig; // Frequency, units are kHz
NDIS_802_11_CONFIGURATION_FH FHConfig;
} NDIS_802_11_CONFIGURATION, *PNDIS_802_11_CONFIGURATION;
typedef struct _NDIS_802_11_STATISTICS
{
ULONG Length; // Length of structure
LARGE_INTEGER TransmittedFragmentCount;
LARGE_INTEGER MulticastTransmittedFrameCount;
LARGE_INTEGER FailedCount;
LARGE_INTEGER RetryCount;
LARGE_INTEGER MultipleRetryCount;
LARGE_INTEGER RTSSuccessCount;
LARGE_INTEGER RTSFailureCount;
LARGE_INTEGER ACKFailureCount;
LARGE_INTEGER FrameDuplicateCount;
LARGE_INTEGER ReceivedFragmentCount;
LARGE_INTEGER MulticastReceivedFrameCount;
LARGE_INTEGER FCSErrorCount;
LARGE_INTEGER TKIPLocalMICFailures;
LARGE_INTEGER TKIPRemoteMICErrors;
LARGE_INTEGER TKIPICVErrors;
LARGE_INTEGER TKIPCounterMeasuresInvoked;
LARGE_INTEGER TKIPReplays;
LARGE_INTEGER CCMPFormatErrors;
LARGE_INTEGER CCMPReplays;
LARGE_INTEGER CCMPDecryptErrors;
LARGE_INTEGER FourWayHandshakeFailures;
} NDIS_802_11_STATISTICS, *PNDIS_802_11_STATISTICS;
typedef ULONG NDIS_802_11_KEY_INDEX;
typedef ULONGLONG NDIS_802_11_KEY_RSC;
#define MAX_RADIUS_SRV_NUM 2 // 802.1x failover number
typedef struct PACKED _RADIUS_SRV_INFO {
UINT32 radius_ip;
UINT32 radius_port;
UCHAR radius_key[64];
UCHAR radius_key_len;
} RADIUS_SRV_INFO, *PRADIUS_SRV_INFO;
typedef struct PACKED _RADIUS_KEY_INFO
{
UCHAR radius_srv_num;
RADIUS_SRV_INFO radius_srv_info[MAX_RADIUS_SRV_NUM];
UCHAR ieee8021xWEP; // dynamic WEP
UCHAR key_index;
UCHAR key_length; // length of key in bytes
UCHAR key_material[13];
} RADIUS_KEY_INFO, *PRADIUS_KEY_INFO;
// It's used by 802.1x daemon to require relative configuration
typedef struct PACKED _RADIUS_CONF
{
UINT32 Length; // Length of this structure
UCHAR mbss_num; // indicate multiple BSS number
UINT32 own_ip_addr;
UINT32 retry_interval;
UINT32 session_timeout_interval;
UCHAR EAPifname[IFNAMSIZ];
UCHAR EAPifname_len;
UCHAR PreAuthifname[IFNAMSIZ];
UCHAR PreAuthifname_len;
RADIUS_KEY_INFO RadiusInfo[8/*MAX_MBSSID_NUM*/];
} RADIUS_CONF, *PRADIUS_CONF;
// Key mapping keys require a BSSID
typedef struct _NDIS_802_11_KEY
{
UINT Length; // Length of this structure
UINT KeyIndex;
UINT KeyLength; // length of key in bytes
NDIS_802_11_MAC_ADDRESS BSSID;
NDIS_802_11_KEY_RSC KeyRSC;
UCHAR KeyMaterial[1]; // variable length depending on above field
} NDIS_802_11_KEY, *PNDIS_802_11_KEY;
typedef struct _NDIS_802_11_REMOVE_KEY
{
UINT Length; // Length of this structure
UINT KeyIndex;
NDIS_802_11_MAC_ADDRESS BSSID;
} NDIS_802_11_REMOVE_KEY, *PNDIS_802_11_REMOVE_KEY;
typedef struct _NDIS_802_11_WEP
{
UINT Length; // Length of this structure
UINT KeyIndex; // 0 is the per-client key, 1-N are the
// global keys
UINT KeyLength; // length of key in bytes
UCHAR KeyMaterial[1];// variable length depending on above field
} NDIS_802_11_WEP, *PNDIS_802_11_WEP;
typedef enum _NDIS_802_11_NETWORK_INFRASTRUCTURE
{
Ndis802_11IBSS,
Ndis802_11Infrastructure,
Ndis802_11AutoUnknown,
Ndis802_11Monitor,
Ndis802_11InfrastructureMax // Not a real value, defined as upper bound
} NDIS_802_11_NETWORK_INFRASTRUCTURE, *PNDIS_802_11_NETWORK_INFRASTRUCTURE;
// Add new authentication modes
typedef enum _NDIS_802_11_AUTHENTICATION_MODE
{
Ndis802_11AuthModeOpen,
Ndis802_11AuthModeShared,
Ndis802_11AuthModeAutoSwitch,
Ndis802_11AuthModeWPA,
Ndis802_11AuthModeWPAPSK,
Ndis802_11AuthModeWPANone,
Ndis802_11AuthModeWPA2,
Ndis802_11AuthModeWPA2PSK,
Ndis802_11AuthModeWPA1WPA2,
Ndis802_11AuthModeWPA1PSKWPA2PSK,
Ndis802_11AuthModeMax // Not a real mode, defined as upper bound
} NDIS_802_11_AUTHENTICATION_MODE, *PNDIS_802_11_AUTHENTICATION_MODE;
typedef UCHAR NDIS_802_11_RATES[NDIS_802_11_LENGTH_RATES]; // Set of 8 data rates
typedef UCHAR NDIS_802_11_RATES_EX[NDIS_802_11_LENGTH_RATES_EX]; // Set of 16 data rates
typedef struct PACKED _NDIS_802_11_SSID
{
UINT SsidLength; // length of SSID field below, in bytes;
// this can be zero.
UCHAR Ssid[NDIS_802_11_LENGTH_SSID]; // SSID information field
} NDIS_802_11_SSID, *PNDIS_802_11_SSID;
typedef struct PACKED _NDIS_WLAN_BSSID
{
ULONG Length; // Length of this structure
NDIS_802_11_MAC_ADDRESS MacAddress; // BSSID
UCHAR Reserved[2];
NDIS_802_11_SSID Ssid; // SSID
ULONG Privacy; // WEP encryption requirement
NDIS_802_11_RSSI Rssi; // receive signal strength in dBm
NDIS_802_11_NETWORK_TYPE NetworkTypeInUse;
NDIS_802_11_CONFIGURATION Configuration;
NDIS_802_11_NETWORK_INFRASTRUCTURE InfrastructureMode;
NDIS_802_11_RATES SupportedRates;
} NDIS_WLAN_BSSID, *PNDIS_WLAN_BSSID;
typedef struct PACKED _NDIS_802_11_BSSID_LIST
{
UINT NumberOfItems; // in list below, at least 1
NDIS_WLAN_BSSID Bssid[1];
} NDIS_802_11_BSSID_LIST, *PNDIS_802_11_BSSID_LIST;
// Added Capabilities, IELength and IEs for each BSSID
typedef struct PACKED _NDIS_WLAN_BSSID_EX
{
ULONG Length; // Length of this structure
NDIS_802_11_MAC_ADDRESS MacAddress; // BSSID
UCHAR Reserved[2];
NDIS_802_11_SSID Ssid; // SSID
UINT Privacy; // WEP encryption requirement
NDIS_802_11_RSSI Rssi; // receive signal
// strength in dBm
NDIS_802_11_NETWORK_TYPE NetworkTypeInUse;
NDIS_802_11_CONFIGURATION Configuration;
NDIS_802_11_NETWORK_INFRASTRUCTURE InfrastructureMode;
NDIS_802_11_RATES_EX SupportedRates;
ULONG IELength;
UCHAR IEs[1];
} NDIS_WLAN_BSSID_EX, *PNDIS_WLAN_BSSID_EX;
typedef struct PACKED _NDIS_802_11_BSSID_LIST_EX
{
UINT NumberOfItems; // in list below, at least 1
NDIS_WLAN_BSSID_EX Bssid[1];
} NDIS_802_11_BSSID_LIST_EX, *PNDIS_802_11_BSSID_LIST_EX;
typedef struct PACKED _NDIS_802_11_FIXED_IEs
{
UCHAR Timestamp[8];
USHORT BeaconInterval;
USHORT Capabilities;
} NDIS_802_11_FIXED_IEs, *PNDIS_802_11_FIXED_IEs;
typedef struct _NDIS_802_11_VARIABLE_IEs
{
UCHAR ElementID;
UCHAR Length; // Number of bytes in data field
UCHAR data[1];
} NDIS_802_11_VARIABLE_IEs, *PNDIS_802_11_VARIABLE_IEs;
typedef ULONG NDIS_802_11_FRAGMENTATION_THRESHOLD;
typedef ULONG NDIS_802_11_RTS_THRESHOLD;
typedef ULONG NDIS_802_11_ANTENNA;
typedef enum _NDIS_802_11_PRIVACY_FILTER
{
Ndis802_11PrivFilterAcceptAll,
Ndis802_11PrivFilter8021xWEP
} NDIS_802_11_PRIVACY_FILTER, *PNDIS_802_11_PRIVACY_FILTER;
// Added new encryption types
// Also aliased typedef to new name
typedef enum _NDIS_802_11_WEP_STATUS
{
Ndis802_11WEPEnabled,
Ndis802_11Encryption1Enabled = Ndis802_11WEPEnabled,
Ndis802_11WEPDisabled,
Ndis802_11EncryptionDisabled = Ndis802_11WEPDisabled,
Ndis802_11WEPKeyAbsent,
Ndis802_11Encryption1KeyAbsent = Ndis802_11WEPKeyAbsent,
Ndis802_11WEPNotSupported,
Ndis802_11EncryptionNotSupported = Ndis802_11WEPNotSupported,
Ndis802_11Encryption2Enabled,
Ndis802_11Encryption2KeyAbsent,
Ndis802_11Encryption3Enabled,
Ndis802_11Encryption3KeyAbsent,
Ndis802_11Encryption4Enabled, // TKIP or AES mix
Ndis802_11Encryption4KeyAbsent,
Ndis802_11GroupWEP40Enabled,
Ndis802_11GroupWEP104Enabled,
} NDIS_802_11_WEP_STATUS, *PNDIS_802_11_WEP_STATUS,
NDIS_802_11_ENCRYPTION_STATUS, *PNDIS_802_11_ENCRYPTION_STATUS;
typedef enum _NDIS_802_11_RELOAD_DEFAULTS
{
Ndis802_11ReloadWEPKeys
} NDIS_802_11_RELOAD_DEFAULTS, *PNDIS_802_11_RELOAD_DEFAULTS;
#define NDIS_802_11_AI_REQFI_CAPABILITIES 1
#define NDIS_802_11_AI_REQFI_LISTENINTERVAL 2
#define NDIS_802_11_AI_REQFI_CURRENTAPADDRESS 4
#define NDIS_802_11_AI_RESFI_CAPABILITIES 1
#define NDIS_802_11_AI_RESFI_STATUSCODE 2
#define NDIS_802_11_AI_RESFI_ASSOCIATIONID 4
typedef struct _NDIS_802_11_AI_REQFI
{
USHORT Capabilities;
USHORT ListenInterval;
NDIS_802_11_MAC_ADDRESS CurrentAPAddress;
} NDIS_802_11_AI_REQFI, *PNDIS_802_11_AI_REQFI;
typedef struct _NDIS_802_11_AI_RESFI
{
USHORT Capabilities;
USHORT StatusCode;
USHORT AssociationId;
} NDIS_802_11_AI_RESFI, *PNDIS_802_11_AI_RESFI;
typedef struct _NDIS_802_11_ASSOCIATION_INFORMATION
{
ULONG Length;
USHORT AvailableRequestFixedIEs;
NDIS_802_11_AI_REQFI RequestFixedIEs;
ULONG RequestIELength;
ULONG OffsetRequestIEs;
USHORT AvailableResponseFixedIEs;
NDIS_802_11_AI_RESFI ResponseFixedIEs;
ULONG ResponseIELength;
ULONG OffsetResponseIEs;
} NDIS_802_11_ASSOCIATION_INFORMATION, *PNDIS_802_11_ASSOCIATION_INFORMATION;
typedef struct _NDIS_802_11_AUTHENTICATION_EVENT
{
NDIS_802_11_STATUS_INDICATION Status;
NDIS_802_11_AUTHENTICATION_REQUEST Request[1];
} NDIS_802_11_AUTHENTICATION_EVENT, *PNDIS_802_11_AUTHENTICATION_EVENT;
// 802.11 Media stream constraints, associated with OID_802_11_MEDIA_STREAM_MODE
typedef enum _NDIS_802_11_MEDIA_STREAM_MODE
{
Ndis802_11MediaStreamOff,
Ndis802_11MediaStreamOn,
} NDIS_802_11_MEDIA_STREAM_MODE, *PNDIS_802_11_MEDIA_STREAM_MODE;
// PMKID Structures
typedef UCHAR NDIS_802_11_PMKID_VALUE[16];
typedef struct _BSSID_INFO
{
NDIS_802_11_MAC_ADDRESS BSSID;
NDIS_802_11_PMKID_VALUE PMKID;
} BSSID_INFO, *PBSSID_INFO;
typedef struct _NDIS_802_11_PMKID
{
UINT Length;
UINT BSSIDInfoCount;
BSSID_INFO BSSIDInfo[1];
} NDIS_802_11_PMKID, *PNDIS_802_11_PMKID;
typedef struct _NDIS_802_11_AUTHENTICATION_ENCRYPTION
{
NDIS_802_11_AUTHENTICATION_MODE AuthModeSupported;
NDIS_802_11_ENCRYPTION_STATUS EncryptStatusSupported;
} NDIS_802_11_AUTHENTICATION_ENCRYPTION, *PNDIS_802_11_AUTHENTICATION_ENCRYPTION;
typedef struct _NDIS_802_11_CAPABILITY
{
ULONG Length;
ULONG Version;
ULONG NoOfPMKIDs;
ULONG NoOfAuthEncryptPairsSupported;
NDIS_802_11_AUTHENTICATION_ENCRYPTION AuthenticationEncryptionSupported[1];
} NDIS_802_11_CAPABILITY, *PNDIS_802_11_CAPABILITY;
#if WIRELESS_EXT <= 11
#ifndef SIOCDEVPRIVATE
#define SIOCDEVPRIVATE 0x8BE0
#endif
#define SIOCIWFIRSTPRIV SIOCDEVPRIVATE
#endif
#define RT_PRIV_IOCTL_EXT (SIOCIWFIRSTPRIV + 0x01) // Sync. with AP for wsc upnp daemon
#define RTPRIV_IOCTL_SET (SIOCIWFIRSTPRIV + 0x02)
#ifdef DBG
#define RTPRIV_IOCTL_BBP (SIOCIWFIRSTPRIV + 0x03)
#define RTPRIV_IOCTL_MAC (SIOCIWFIRSTPRIV + 0x05)
#define RTPRIV_IOCTL_RF (SIOCIWFIRSTPRIV + 0x13)
#define RTPRIV_IOCTL_E2P (SIOCIWFIRSTPRIV + 0x07)
#endif
#define RTPRIV_IOCTL_STATISTICS (SIOCIWFIRSTPRIV + 0x09)
#define RTPRIV_IOCTL_ADD_PMKID_CACHE (SIOCIWFIRSTPRIV + 0x0A)
#define RTPRIV_IOCTL_RADIUS_DATA (SIOCIWFIRSTPRIV + 0x0C)
#define RTPRIV_IOCTL_GSITESURVEY (SIOCIWFIRSTPRIV + 0x0D)
#define RT_PRIV_IOCTL (SIOCIWFIRSTPRIV + 0x0E) // Sync. with RT61 (for wpa_supplicant)
#define RTPRIV_IOCTL_GET_MAC_TABLE (SIOCIWFIRSTPRIV + 0x0F)
#define RTPRIV_IOCTL_SHOW (SIOCIWFIRSTPRIV + 0x11)
enum {
SHOW_CONN_STATUS = 4,
SHOW_DRVIER_VERION = 5,
SHOW_BA_INFO = 6,
SHOW_DESC_INFO = 7,
#ifdef RT2870
SHOW_RXBULK_INFO = 8,
SHOW_TXBULK_INFO = 9,
#endif // RT2870 //
RAIO_OFF = 10,
RAIO_ON = 11,
SHOW_CFG_VALUE = 20,
#if !defined(RT2860)
SHOW_ADHOC_ENTRY_INFO = 21,
#endif
};
#define OID_802_11_BUILD_CHANNEL_EX 0x0714
#define OID_802_11_GET_CH_LIST 0x0715
#define OID_802_11_GET_COUNTRY_CODE 0x0716
#define OID_802_11_GET_CHANNEL_GEOGRAPHY 0x0717
#ifdef RT30xx
#define RT_OID_WSC_SET_PASSPHRASE 0x0740 // passphrase for wpa(2)-psk
#define RT_OID_WSC_DRIVER_AUTO_CONNECT 0x0741
#define RT_OID_WSC_QUERY_DEFAULT_PROFILE 0x0742
#define RT_OID_WSC_SET_CONN_BY_PROFILE_INDEX 0x0743
#define RT_OID_WSC_SET_ACTION 0x0744
#define RT_OID_WSC_SET_SSID 0x0745
#define RT_OID_WSC_SET_PIN_CODE 0x0746
#define RT_OID_WSC_SET_MODE 0x0747 // PIN or PBC
#define RT_OID_WSC_SET_CONF_MODE 0x0748 // Enrollee or Registrar
#define RT_OID_WSC_SET_PROFILE 0x0749
#define RT_OID_802_11_WSC_QUERY_PROFILE 0x0750
// for consistency with RT61
#define RT_OID_WSC_QUERY_STATUS 0x0751
#define RT_OID_WSC_PIN_CODE 0x0752
#define RT_OID_WSC_UUID 0x0753
#define RT_OID_WSC_SET_SELECTED_REGISTRAR 0x0754
#define RT_OID_WSC_EAPMSG 0x0755
#define RT_OID_WSC_MANUFACTURER 0x0756
#define RT_OID_WSC_MODEL_NAME 0x0757
#define RT_OID_WSC_MODEL_NO 0x0758
#define RT_OID_WSC_SERIAL_NO 0x0759
#define RT_OID_WSC_MAC_ADDRESS 0x0760
#endif
#ifdef LLTD_SUPPORT
// for consistency with RT61
#define RT_OID_GET_PHY_MODE 0x761
#endif // LLTD_SUPPORT //
#if defined(RT2860) || defined(RT30xx)
// New for MeetingHouse Api support
#define OID_MH_802_1X_SUPPORTED 0xFFEDC100
#endif
// MIMO Tx parameter, ShortGI, MCS, STBC, etc. these are fields in TXWI. Don't change this definition!!!
typedef union _HTTRANSMIT_SETTING {
struct {
USHORT MCS:7; // MCS
USHORT BW:1; //channel bandwidth 20MHz or 40 MHz
USHORT ShortGI:1;
USHORT STBC:2; //SPACE
USHORT rsv:2;
USHORT TxBF:1;
USHORT MODE:2; // Use definition MODE_xxx.
} field;
USHORT word;
} HTTRANSMIT_SETTING, *PHTTRANSMIT_SETTING;
typedef enum _RT_802_11_PREAMBLE {
Rt802_11PreambleLong,
Rt802_11PreambleShort,
Rt802_11PreambleAuto
} RT_802_11_PREAMBLE, *PRT_802_11_PREAMBLE;
// Only for STA, need to sync with AP
typedef enum _RT_802_11_PHY_MODE {
PHY_11BG_MIXED = 0,
PHY_11B,
PHY_11A,
PHY_11ABG_MIXED,
PHY_11G,
PHY_11ABGN_MIXED, // both band 5
PHY_11N_2_4G, // 11n-only with 2.4G band 6
PHY_11GN_MIXED, // 2.4G band 7
PHY_11AN_MIXED, // 5G band 8
PHY_11BGN_MIXED, // if check 802.11b. 9
PHY_11AGN_MIXED, // if check 802.11b. 10
PHY_11N_5G, // 11n-only with 5G band 11
} RT_802_11_PHY_MODE;
// put all proprietery for-query objects here to reduce # of Query_OID
typedef struct _RT_802_11_LINK_STATUS {
ULONG CurrTxRate; // in units of 0.5Mbps
ULONG ChannelQuality; // 0..100 %
ULONG TxByteCount; // both ok and fail
ULONG RxByteCount; // both ok and fail
ULONG CentralChannel; // 40MHz central channel number
} RT_802_11_LINK_STATUS, *PRT_802_11_LINK_STATUS;
typedef struct _RT_802_11_EVENT_LOG {
LARGE_INTEGER SystemTime; // timestammp via NdisGetCurrentSystemTime()
UCHAR Addr[MAC_ADDR_LENGTH];
USHORT Event; // EVENT_xxx
} RT_802_11_EVENT_LOG, *PRT_802_11_EVENT_LOG;
typedef struct _RT_802_11_EVENT_TABLE {
ULONG Num;
ULONG Rsv; // to align Log[] at LARGE_INEGER boundary
RT_802_11_EVENT_LOG Log[MAX_NUMBER_OF_EVENT];
} RT_802_11_EVENT_TABLE, PRT_802_11_EVENT_TABLE;
// MIMO Tx parameter, ShortGI, MCS, STBC, etc. these are fields in TXWI. Don't change this definition!!!
typedef union _MACHTTRANSMIT_SETTING {
struct {
USHORT MCS:7; // MCS
USHORT BW:1; //channel bandwidth 20MHz or 40 MHz
USHORT ShortGI:1;
USHORT STBC:2; //SPACE
USHORT rsv:3;
USHORT MODE:2; // Use definition MODE_xxx.
} field;
USHORT word;
} MACHTTRANSMIT_SETTING, *PMACHTTRANSMIT_SETTING;
typedef struct _RT_802_11_MAC_ENTRY {
UCHAR Addr[MAC_ADDR_LENGTH];
UCHAR Aid;
UCHAR Psm; // 0:PWR_ACTIVE, 1:PWR_SAVE
UCHAR MimoPs; // 0:MMPS_STATIC, 1:MMPS_DYNAMIC, 3:MMPS_Enabled
CHAR AvgRssi0;
CHAR AvgRssi1;
CHAR AvgRssi2;
UINT32 ConnectedTime;
MACHTTRANSMIT_SETTING TxRate;
} RT_802_11_MAC_ENTRY, *PRT_802_11_MAC_ENTRY;
typedef struct _RT_802_11_MAC_TABLE {
ULONG Num;
RT_802_11_MAC_ENTRY Entry[MAX_NUMBER_OF_MAC];
} RT_802_11_MAC_TABLE, *PRT_802_11_MAC_TABLE;
// structure for query/set hardware register - MAC, BBP, RF register
typedef struct _RT_802_11_HARDWARE_REGISTER {
ULONG HardwareType; // 0:MAC, 1:BBP, 2:RF register, 3:EEPROM
ULONG Offset; // Q/S register offset addr
ULONG Data; // R/W data buffer
} RT_802_11_HARDWARE_REGISTER, *PRT_802_11_HARDWARE_REGISTER;
typedef struct _RT_802_11_AP_CONFIG {
ULONG EnableTxBurst; // 0-disable, 1-enable
ULONG EnableTurboRate; // 0-disable, 1-enable 72/100mbps turbo rate
ULONG IsolateInterStaTraffic; // 0-disable, 1-enable isolation
ULONG HideSsid; // 0-disable, 1-enable hiding
ULONG UseBGProtection; // 0-AUTO, 1-always ON, 2-always OFF
ULONG UseShortSlotTime; // 0-no use, 1-use 9-us short slot time
ULONG Rsv1; // must be 0
ULONG SystemErrorBitmap; // ignore upon SET, return system error upon QUERY
} RT_802_11_AP_CONFIG, *PRT_802_11_AP_CONFIG;
// structure to query/set STA_CONFIG
typedef struct _RT_802_11_STA_CONFIG {
ULONG EnableTxBurst; // 0-disable, 1-enable
ULONG EnableTurboRate; // 0-disable, 1-enable 72/100mbps turbo rate
ULONG UseBGProtection; // 0-AUTO, 1-always ON, 2-always OFF
ULONG UseShortSlotTime; // 0-no use, 1-use 9-us short slot time when applicable
ULONG AdhocMode; // 0-11b rates only (WIFI spec), 1 - b/g mixed, 2 - g only
ULONG HwRadioStatus; // 0-OFF, 1-ON, default is 1, Read-Only
ULONG Rsv1; // must be 0
ULONG SystemErrorBitmap; // ignore upon SET, return system error upon QUERY
} RT_802_11_STA_CONFIG, *PRT_802_11_STA_CONFIG;
//
// For OID Query or Set about BA structure
//
typedef struct _OID_BACAP_STRUC {
UCHAR RxBAWinLimit;
UCHAR TxBAWinLimit;
UCHAR Policy; // 0: DELAY_BA 1:IMMED_BA (//BA Policy subfiled value in ADDBA frame) 2:BA-not use. other value invalid
UCHAR MpduDensity; // 0: DELAY_BA 1:IMMED_BA (//BA Policy subfiled value in ADDBA frame) 2:BA-not use. other value invalid
UCHAR AmsduEnable; //Enable AMSDU transmisstion
UCHAR AmsduSize; // 0:3839, 1:7935 bytes. UINT MSDUSizeToBytes[] = { 3839, 7935};
UCHAR MMPSmode; // MIMO power save more, 0:static, 1:dynamic, 2:rsv, 3:mimo enable
BOOLEAN AutoBA; // Auto BA will automatically
} OID_BACAP_STRUC, *POID_BACAP_STRUC;
typedef struct _RT_802_11_ACL_ENTRY {
UCHAR Addr[MAC_ADDR_LENGTH];
USHORT Rsv;
} RT_802_11_ACL_ENTRY, *PRT_802_11_ACL_ENTRY;
typedef struct PACKED _RT_802_11_ACL {
ULONG Policy; // 0-disable, 1-positive list, 2-negative list
ULONG Num;
RT_802_11_ACL_ENTRY Entry[MAX_NUMBER_OF_ACL];
} RT_802_11_ACL, *PRT_802_11_ACL;
typedef struct _RT_802_11_WDS {
ULONG Num;
NDIS_802_11_MAC_ADDRESS Entry[24/*MAX_NUM_OF_WDS_LINK*/];
ULONG KeyLength;
UCHAR KeyMaterial[32];
} RT_802_11_WDS, *PRT_802_11_WDS;
typedef struct _RT_802_11_TX_RATES_ {
UCHAR SupRateLen;
UCHAR SupRate[MAX_LENGTH_OF_SUPPORT_RATES];
UCHAR ExtRateLen;
UCHAR ExtRate[MAX_LENGTH_OF_SUPPORT_RATES];
} RT_802_11_TX_RATES, *PRT_802_11_TX_RATES;
// Definition of extra information code
#define GENERAL_LINK_UP 0x0 // Link is Up
#define GENERAL_LINK_DOWN 0x1 // Link is Down
#define HW_RADIO_OFF 0x2 // Hardware radio off
#define SW_RADIO_OFF 0x3 // Software radio off
#define AUTH_FAIL 0x4 // Open authentication fail
#define AUTH_FAIL_KEYS 0x5 // Shared authentication fail
#define ASSOC_FAIL 0x6 // Association failed
#define EAP_MIC_FAILURE 0x7 // Deauthencation because MIC failure
#define EAP_4WAY_TIMEOUT 0x8 // Deauthencation on 4-way handshake timeout
#define EAP_GROUP_KEY_TIMEOUT 0x9 // Deauthencation on group key handshake timeout
#define EAP_SUCCESS 0xa // EAP succeed
#define DETECT_RADAR_SIGNAL 0xb // Radar signal occur in current channel
#define EXTRA_INFO_MAX 0xb // Indicate Last OID
#define EXTRA_INFO_CLEAR 0xffffffff
// This is OID setting structure. So only GF or MM as Mode. This is valid when our wirelss mode has 802.11n in use.
typedef struct {
RT_802_11_PHY_MODE PhyMode; //
UCHAR TransmitNo;
UCHAR HtMode; //HTMODE_GF or HTMODE_MM
UCHAR ExtOffset; //extension channel above or below
UCHAR MCS;
UCHAR BW;
UCHAR STBC;
UCHAR SHORTGI;
UCHAR rsv;
} OID_SET_HT_PHYMODE, *POID_SET_HT_PHYMODE;
#ifdef LLTD_SUPPORT
typedef struct _RT_LLTD_ASSOICATION_ENTRY {
UCHAR Addr[ETH_LENGTH_OF_ADDRESS];
unsigned short MOR; // maximum operational rate
UCHAR phyMode;
} RT_LLTD_ASSOICATION_ENTRY, *PRT_LLTD_ASSOICATION_ENTRY;
typedef struct _RT_LLTD_ASSOICATION_TABLE {
unsigned int Num;
RT_LLTD_ASSOICATION_ENTRY Entry[MAX_NUMBER_OF_MAC];
} RT_LLTD_ASSOICATION_TABLE, *PRT_LLTD_ASSOICATION_TABLE;
#endif // LLTD_SUPPORT //
#define MAX_CUSTOM_LEN 128
typedef enum _RT_802_11_D_CLIENT_MODE
{
Rt802_11_D_None,
Rt802_11_D_Flexible,
Rt802_11_D_Strict,
} RT_802_11_D_CLIENT_MODE, *PRT_802_11_D_CLIENT_MODE;
typedef struct _RT_CHANNEL_LIST_INFO
{
UCHAR ChannelList[MAX_NUM_OF_CHS]; // list all supported channels for site survey
UCHAR ChannelListNum; // number of channel in ChannelList[]
} RT_CHANNEL_LIST_INFO, *PRT_CHANNEL_LIST_INFO;
#ifdef RT2870
// WSC configured credential
typedef struct _WSC_CREDENTIAL
{
NDIS_802_11_SSID SSID; // mandatory
USHORT AuthType; // mandatory, 1: open, 2: wpa-psk, 4: shared, 8:wpa, 0x10: wpa2, 0x20: wpa2-psk
USHORT EncrType; // mandatory, 1: none, 2: wep, 4: tkip, 8: aes
UCHAR Key[64]; // mandatory, Maximum 64 byte
USHORT KeyLength;
UCHAR MacAddr[6]; // mandatory, AP MAC address
UCHAR KeyIndex; // optional, default is 1
UCHAR Rsvd[3]; // Make alignment
} WSC_CREDENTIAL, *PWSC_CREDENTIAL;
// WSC configured profiles
typedef struct _WSC_PROFILE
{
UINT ProfileCnt;
WSC_CREDENTIAL Profile[8]; // Support up to 8 profiles
} WSC_PROFILE, *PWSC_PROFILE;
#endif
#endif // _OID_H_
|
ingmar-k/2.6.31.14_OXNAS_kernel
|
drivers/staging/rt2860/oid.h
|
C
|
gpl-2.0
| 36,704
|
/***************************************************************************
*
* Author: "Sjors H.W. Scheres"
* MRC Laboratory of Molecular Biology
*
* 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.
*
* This complete copyright notice must be included in any revised version of the
* source code. Additional authorship citations may be added, but existing
* author citations must be preserved.
***************************************************************************/
#include <src/image.h>
#include <src/metadata_table.h>
#include <src/filename.h>
class star_compare_parameters
{
public:
FileName fn1, fn2, fn_both, fn_only1, fn_only2, fn_label1, fn_label2, fn_label3;
RFLOAT eps;
MetaDataTable MD1, MD2, MDonly1, MDonly2, MDboth;
// I/O Parser
IOParser parser;
void usage()
{
parser.writeUsage(std::cerr);
}
void read(int argc, char **argv)
{
parser.setCommandLine(argc, argv);
int general_section = parser.addSection("General options");
fn1 = parser.getOption("--i1", "1st input STAR file ");
fn2 = parser.getOption("--i2", "2nd input STAR file ");
fn_both = parser.getOption("--both", "Output STAR file with entries from both input STAR files ", "");
fn_only1 = parser.getOption("--only1", "Output STAR file with entries that only occur in the 1st input STAR files ", "");
fn_only2 = parser.getOption("--only2", "Output STAR file with entries that only occur in the 2nd input STAR files ", "");
fn_label1 = parser.getOption("--label1", "1st metadata label for the comparison (may be string, int or RFLOAT)", "");
fn_label2 = parser.getOption("--label2", "2nd metadata label for the comparison (RFLOAT only) for 2D/3D-distance)", "");
fn_label3 = parser.getOption("--label3", "3rd metadata label for the comparison (RFLOAT only) for 3D-distance)", "");
eps = textToFloat(parser.getOption("--max_dist", "Maximum distance to consider a match (for int and RFLOAT only)", "0."));
// Check for errors in the command-line option
if (parser.checkForErrors())
REPORT_ERROR("Errors encountered on the command line, exiting...");
}
void run()
{
EMDLabel label1, label2, label3;
MD1.read(fn1);
MD2.read(fn2);
label1 = EMDL::str2Label(fn_label1);
label2 = (fn_label2 == "") ? EMDL_UNDEFINED : EMDL::str2Label(fn_label2);
label3 = (fn_label3 == "") ? EMDL_UNDEFINED : EMDL::str2Label(fn_label3);
compareMetaDataTable(MD1, MD2, MDboth, MDonly1, MDonly2, label1, eps, label2, label3);
std::cout << MDboth.numberOfObjects() << " entries occur in both input STAR files." << std::endl;
std::cout << MDonly1.numberOfObjects() << " entries occur only in the 1st input STAR file." << std::endl;
std::cout << MDonly2.numberOfObjects() << " entries occur only in the 2nd input STAR file." << std::endl;
if (fn_both != "")
MDboth.write(fn_both);
if (fn_only1 != "")
MDonly1.write(fn_only1);
if (fn_only2 != "")
MDonly2.write(fn_only2);
}
};
int main(int argc, char *argv[])
{
star_compare_parameters prm;
try
{
prm.read(argc, argv);
prm.run();
}
catch (RelionError XE)
{
std::cerr << XE;
prm.usage();
exit(1);
}
return 0;
}
|
KryoEM/relion2
|
src/apps/star_compare.cpp
|
C++
|
gpl-2.0
| 3,669
|
/**
*
*/
package jsa.compiler.js;
import jsa.compiler.SourceCodeGenerator;
import jsa.compiler.SourceCodeGeneratorFactory;
import jsa.compiler.SourceGenerationContext;
import jsa.compiler.meta.rest.RestAPIPortInspector;
import jsa.compiler.meta.rest.RestPortMeta;
/**
*
* @author <a href="mailto:vesko.georgiev@uniscon.de">Vesko Georgiev</a>
*/
public class JSGeneratorFactory implements SourceCodeGeneratorFactory {
private RestAPIPortInspector restInspector = RestAPIPortInspector.getInstance();
@Override
public SourceCodeGenerator create(final Class<?> apiPort, final SourceGenerationContext context) {
RestPortMeta restMeta = restInspector.inspect(apiPort);
return new JSSourceGenerator(restMeta, context);
}
}
|
veskogeorgiev/jsa
|
jsa-compiler/src/main/java/jsa/compiler/js/JSGeneratorFactory.java
|
Java
|
gpl-2.0
| 735
|
<?php
//==========================================================================
//
//Université de Strasbourg - Direction Informatique
//Auteur : Guilhem BORGHESI
//Création : Février 2008
//
//borghesi@unistra.fr
//
//Ce logiciel est régi par la licence CeCILL-B soumise au droit français et
//respectant les principes de diffusion des logiciels libres. Vous pouvez
//utiliser, modifier et/ou redistribuer ce programme sous les conditions
//de la licence CeCILL-B telle que diffusée par le CEA, le CNRS et l'INRIA
//sur le site "http://www.cecill.info".
//
//Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
//pris connaissance de la licence CeCILL-B, et que vous en avez accepté les
//termes. Vous pouvez trouver une copie de la licence dans le fichier LICENCE.
//
//==========================================================================
//
//Université de Strasbourg - Direction Informatique
//Author : Guilhem BORGHESI
//Creation : Feb 2008
//
//borghesi@unistra.fr
//
//This software is governed by the CeCILL-B license under French law and
//abiding by the rules of distribution of free software. You can use,
//modify and/ or redistribute the software under the terms of the CeCILL-B
//license as circulated by CEA, CNRS and INRIA at the following URL
//"http://www.cecill.info".
//
//The fact that you are presently reading this means that you have had
//knowledge of the CeCILL-B license and that you accept its terms. You can
//find a copy of this license in the file LICENSE.
//
//==========================================================================
include '../bandeaux.php';
echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">'."\n";
echo '<html>'."\n";
echo '<head>'."\n";
echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8">'."\n";
echo '<title>Erreur !</title>'."\n";
echo '<link rel="stylesheet" type="text/css" href="../style.css">'."\n";
echo '</head>'."\n";
echo '<body>'."\n";
logo();
bandeau_tete();
bandeau_titre(_("Make your polls"));
echo '<div class=corpscentre>'."\n";
print "<H2>Vous n'avez pas l'autorisation de voir ce répertoire.<br> </H2>Vous devez, pour cela, initier votre connexion depuis une machine de l'Université.<br> Si vous avez un compte à l'Université, vous pouvez également utiliser le <a href=\"https://www-crc.u-strasbg.fr/osiris/services/vpn\">VPN sécurisé</a>.<br><br>"."\n";
print "Vous pouvez retourner à la page d'accueil de <a href=\"../index.php\"> ".NOMAPPLICATION."</A>."."\n";
echo '<br><br><br>'."\n";
echo '</div>'."\n";
// Affichage du bandeau de pied
sur_bandeau_pied();
bandeau_pied();
echo '</body>'."\n";
echo '</html>'."\n";
|
anidel/orange-sondage
|
php/errors/error-forbidden.php
|
PHP
|
gpl-2.0
| 2,726
|
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <Wingdi.h>
#include <winspool.h>
#include <winuser.h>
#include <mmsystem.h>
#include <commctrl.h>
#include <commdlg.h>
#include <dlgs.h>
#include <process.h>
#include <prsht.h>
#include <richedit.h>
#include <shellapi.h>
#include <Shlobj.h>
#include <shlwapi.h>
#include <ddraw.h>
#include <shobjidl.h>
#include "sysconfig.h"
#include "sysdeps.h"
#include "resource"
#include "registry.h"
#include "win32.h"
#include "win32gui.h"
static int max_w = 800, max_h = 600, mult = 100, pointsize;
#include <pshpack2.h>
typedef struct {
WORD dlgVer;
WORD signature;
DWORD helpID;
DWORD exStyle;
DWORD style;
WORD cDlgItems;
short x;
short y;
short cx;
short cy;
/*
sz_Or_Ord menu;
sz_Or_Ord windowClass;
WCHAR title[titleLen];
*/
} DLGTEMPLATEEX;
typedef struct {
WORD pointsize;
WORD weight;
BYTE italic;
BYTE charset;
WCHAR typeface[1];
} DLGTEMPLATEEX_END;
typedef struct {
DWORD helpID;
DWORD exStyle;
DWORD style;
short x;
short y;
short cx;
short cy;
WORD id;
WORD reserved;
WCHAR windowClass[1];
/* variable data after this */
/* sz_Or_Ord title; */
/* WORD extraCount; */
} DLGITEMTEMPLATEEX;
#include <poppack.h>
static int font_vista_ok;
static wchar_t wfont_vista[] = _T("Segoe UI");
static wchar_t wfont_xp[] = _T("Tahoma");
static wchar_t wfont_old[] = _T("MS Sans Serif");
static TCHAR font_vista[] = _T("Segoe UI");
static TCHAR font_xp[] = _T("Tahoma");
static BYTE *skiptextone (BYTE *s)
{
s -= sizeof (WCHAR);
if (s[0] == 0xff && s[1] == 0xff) {
s += 4;
return s;
}
while (s[0] != 0 || s[1] != 0)
s += 2;
s += 2;
return s;
}
static BYTE *skiptext (BYTE *s)
{
if (s[0] == 0xff && s[1] == 0xff) {
s += 4;
return s;
}
while (s[0] != 0 || s[1] != 0)
s += 2;
s += 2;
return s;
}
static BYTE *todword (BYTE *p)
{
while ((LONG_PTR)p & 3)
p++;
return p;
}
static void modifytemplate (DLGTEMPLATEEX *d, DLGTEMPLATEEX_END *d2, int id, int mult)
{
d->cx = d->cx * mult / 100;
d->cy = d->cy * mult / 100;
}
static void modifytemplatefont (DLGTEMPLATEEX *d, DLGTEMPLATEEX_END *d2)
{
wchar_t *p = NULL;
if (font_vista_ok)
p = wfont_vista;
else
p = wfont_xp;
if (p && !wcscmp (d2->typeface, wfont_old))
wcscpy (d2->typeface, p);
}
static void modifyitem (DLGTEMPLATEEX *d, DLGTEMPLATEEX_END *d2, DLGITEMTEMPLATEEX *dt, int id, int mult)
{
dt->cy = dt->cy * mult / 100;
dt->cx = dt->cx * mult / 100;
dt->y = dt->y * mult / 100;
dt->x = dt->x * mult / 100;
}
static INT_PTR CALLBACK DummyProc (HWND hDlg, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch(msg)
{
case WM_DESTROY:
PostQuitMessage (0);
return TRUE;
case WM_CLOSE:
DestroyWindow(hDlg);
return TRUE;
case WM_INITDIALOG:
return TRUE;
}
return FALSE;
}
struct newresource *scaleresource (struct newresource *res, HWND parent)
{
DLGTEMPLATEEX *d;
DLGTEMPLATEEX_END *d2;
DLGITEMTEMPLATEEX *dt;
BYTE *p, *p2;
int i;
struct newresource *ns;
d = (DLGTEMPLATEEX*)res->resource;
d2 = (DLGTEMPLATEEX_END*)res->resource;
if (d->dlgVer != 1 || d->signature != 0xffff)
return 0;
if (!(d->style & (DS_SETFONT | DS_SHELLFONT)))
return 0;
ns = xcalloc (struct newresource, 1);
ns->inst = res->inst;
ns->size = res->size;
ns->tmpl = res->tmpl;
ns->resource = (LPCDLGTEMPLATEW)xmalloc (uae_u8, ns->size);
memcpy ((void*)ns->resource, res->resource, ns->size);
d = (DLGTEMPLATEEX*)ns->resource;
d2 = (DLGTEMPLATEEX_END*)ns->resource;
p = (BYTE*)d + sizeof (DLGTEMPLATEEX);
p = skiptext (p);
p = skiptext (p);
p = skiptext (p);
d2 = (DLGTEMPLATEEX_END*)p;
p2 = p;
p2 += sizeof (DLGTEMPLATEEX_END);
p2 = skiptextone (p2);
p2 = todword (p2);
modifytemplatefont (d, d2);
p += sizeof (DLGTEMPLATEEX_END);
p = skiptextone (p);
p = todword (p);
if (p != p2)
memmove (p, p2, ns->size - (p2 - (BYTE*)ns->resource));
modifytemplate(d, d2, ns->tmpl, mult);
for (i = 0; i < d->cDlgItems; i++) {
dt = (DLGITEMTEMPLATEEX*)p;
modifyitem (d, d2, dt, ns->tmpl, mult);
p += sizeof (DLGITEMTEMPLATEEX);
p = skiptextone (p);
p = skiptext (p);
p += ((WORD*)p)[0];
p += sizeof (WORD);
p = todword (p);
}
ns->width = d->cx;
ns->height = d->cy;
return ns;
}
void freescaleresource (struct newresource *ns)
{
xfree ((void*)ns->resource);
xfree (ns);
}
void scaleresource_setmaxsize (int w, int h)
{
if (os_vista)
font_vista_ok = 1;
max_w = w;
max_h = h;
mult = 100;
}
|
lunixbochs/fs-uae-gles
|
src/od-win32/win32gui_extra.cpp
|
C++
|
gpl-2.0
| 4,437
|
/**
* This file is part of the Goobi viewer - a content presentation and management application for digitized objects.
*
* Visit these websites for more information.
* - http://www.intranda.com
* - http://digiverso.com
*
* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package io.goobi.viewer.exceptions;
import java.io.Serializable;
/**
* <p>
* IndexUnreachableException class.
* </p>
*/
public class IndexUnreachableException extends Exception implements Serializable {
private static final long serialVersionUID = -5840484445206784670L;
/**
* <p>
* Constructor for IndexUnreachableException.
* </p>
*
* @param string {@link java.lang.String}
*/
public IndexUnreachableException(String string) {
super(string);
}
}
|
intranda/goobi-viewer-core
|
goobi-viewer-core/src/main/java/io/goobi/viewer/exceptions/IndexUnreachableException.java
|
Java
|
gpl-2.0
| 1,389
|
package org.nextprot.api.web;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.filter.OncePerRequestFilter;
import com.brsanthu.googleanalytics.GoogleAnalytics;
import com.brsanthu.googleanalytics.GoogleAnalyticsRequest;
import com.brsanthu.googleanalytics.PageViewHit;
import com.google.common.base.Optional;
public class GoogleAnalyticsFilter extends OncePerRequestFilter {
private GoogleAnalytics ga = null;
private final Log Logger = LogFactory.getLog(GoogleAnalyticsFilter.class);
private String gaTrackingID = null;
private static final String GA_TRACKING_ID_SYS_PROP = "GATrackingId";
@Override
public void initFilterBean() {
if(System.getProperty(GA_TRACKING_ID_SYS_PROP) != null){
gaTrackingID = System.getProperty(GA_TRACKING_ID_SYS_PROP);
}
if(gaTrackingID != null){
ga = new GoogleAnalytics(gaTrackingID);
Logger.info("Google Analytics filter initialized with " + gaTrackingID);
}else {
Logger.info("Google Analytics not initialized because -D" + GA_TRACKING_ID_SYS_PROP + "=UA-17852148-* system property was not found. Place it in the start.ini of the jetty application.");
}
}
private GoogleAnalyticsRequest<?> generateHit(HttpServletRequest request) {
PageViewHit hit = new PageViewHit(request.getRequestURL().toString(), request.getPathInfo());
Logger.debug("Sending hit: " + request.getRequestURL().toString());
hit.clientId(getClientId(request).toString());
// Overriding IP if present from the client
Optional<String> ip = getClientIP(request);
if (ip.isPresent()) {
hit.userIp(ip.get());
}
return hit;
}
private void sendToGoogleAnalytics(HttpServletRequest request) {
try {
ga.postAsync(generateHit(request));
} catch (Exception e) {
Logger.error("Failed to send to GA" + e.getMessage());
}
}
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws ServletException, IOException {
if ((ga != null) && (!"OPTIONS".equals(req.getMethod()))) {
sendToGoogleAnalytics(req);
}
chain.doFilter(req, resp);
}
public UUID getClientId(HttpServletRequest request) {
// Keeping just IP + agent method, because some methods may require
// authentication and others not. And therefore different UUID would be
// generated.
UUID id = getClientUniqueIdentifier(request);
// Logger.debug("Found UUID " + id + " based on custom headers");
return id;
}
/**
* Get a client unique identifier created using the headers
*
* @param request
* @return
*/
public UUID getClientUniqueIdentifier(HttpServletRequest request) {
StringBuilder sb = new StringBuilder();
sb.append(request.getHeader("origin") + "; ");
sb.append(request.getHeader("user-agent") + "; ");
sb.append(request.getHeader("hostname") + "; ");
sb.append(request.getHeader("x-forwarded-for") + "; ");
sb.append(request.getRemoteHost() + "; ");
sb.append(request.getRemoteUser() + "; ");
sb.append(request.getRemoteAddr() + "; ");
Logger.debug("Building Client ID based on string " + sb.toString());
return UUID.nameUUIDFromBytes(sb.toString().getBytes());
}
/**
* Gets the IP of the real client
*
* @param request
* @return
*/
public Optional<String> getClientIP(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for"); // May differ from
// implementations
if (ip != null) {
return Optional.of(ip);
} else {
return Optional.absent();
}
}
}
|
calipho-sib/nextprot-api
|
web/src/main/java/org/nextprot/api/web/GoogleAnalyticsFilter.java
|
Java
|
gpl-2.0
| 3,828
|
<?php
/**
* ---------------------------------------------------------------------
* GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2015-2021 Teclib' and contributors.
*
* http://glpi-project.org
*
* based on GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2003-2014 by the INDEPNET Development Team.
*
* ---------------------------------------------------------------------
*
* LICENSE
*
* This file is part of GLPI.
*
* GLPI 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.
*
* GLPI 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 GLPI. If not, see <http://www.gnu.org/licenses/>.
* ---------------------------------------------------------------------
*/
/// Class DeviceCaseType (Interface is a reserved keyword)
class DeviceCaseType extends CommonDeviceType
{
public static function getTypeName($nb = 0)
{
return _n('Case type', 'Case types', $nb);
}
}
|
flegastelois/glpi
|
src/DeviceCaseType.php
|
PHP
|
gpl-2.0
| 1,386
|
#!/usr/bin/env python3
import os
import shutil
import subprocess
import sys
if os.environ.get('DESTDIR'):
install_root = os.environ.get('DESTDIR') + os.path.abspath(sys.argv[1])
else:
install_root = sys.argv[1]
if not os.environ.get('DESTDIR'):
schemadir = os.path.join(install_root, 'glib-2.0', 'schemas')
print('Compile gsettings schemas...')
subprocess.call(['glib-compile-schemas', schemadir])
# FIXME: Meson is unable to copy a generated target file:
# https://groups.google.com/forum/#!topic/mesonbuild/3iIoYPrN4P0
dst_dir = os.path.join(install_root, 'wayland-sessions')
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
src = os.path.join(install_root, 'xsessions', 'gnome.desktop')
dst = os.path.join(dst_dir, 'gnome.desktop')
shutil.copyfile(src, dst)
|
GNOME/gnome-session
|
meson_post_install.py
|
Python
|
gpl-2.0
| 789
|
var _Sequence = function (onDone) {
this.list = [];
this.onDone = onDone;
};
_Sequence.prototype = {
add: function() {
var args = Array.prototype.slice.call(arguments);
this.list.push(args);
},
next: function() {
if (this.list.length > 0) {
var current = this.list.shift();
setTimeout(function () { (current.shift()).apply(this, current); }, 1);
} else {
if (typeof this.onDone == "function"){
setTimeout(this.onDone, 250);
}
}
}
};
var deferUntilSearchComplete = new _Sequence();
var timeFilter = function() { return true;};
var timeRanges;
var searchN = 0;
var graphColors = d3.scale.category10().domain(d3.range(10));
var gradientExponentScale = 0.3;
var gradientOpacity = d3.scale.pow().exponent(gradientExponentScale).clamp(true).range([1,0]);
var gradientBox, gradientDomain;
var legend, showLegend = 2;
var index = data["INDEX"];
var startDate, endDate;
var activeTopicLabels = [], inactiveTopicLabels = [];
var graph = {};
var indexTerms = d3.keys(index);
var docMetadata = data["DOC_METADATA"],
categorical = data["CATEGORICAL"],
topicCoherence = data["TOPIC_COHERENCE"],
labels = data["TOPIC_LABELS"],
topicProportions,
topicStdevs;
var streaming = true,
stacked = false,
horizon = false,
my,
toggleState = categorical ? 3 : 0,
width = 700/*960*/,
height = 500,
horizonHeight = 40,
legendWidth = 160,
legendLineHeight = 15,
legendLines = 10,
smoothing = "mean",
windowSize = 2,
interpolateType = "monotone",
wordClouds = {};
var graphTypes = {0: "stream", 1: "stacked area", 2: "line (std. dev. from mean)", 3: "categorical", 4: "horizon"};
var maxStdDev = 3;
var intervalType = "year";
var interval = d3.time[intervalType];
function getIntervalName (date) {
return interval.floor(date).toISOString();
}
var origTopicTimeData,
dataSummed,
xAxis,
categories,
legendLabels,
topicLabels = null,
topicLabelsSorted,
sortMetric = 0,
total = 1;
var intervalsObj = {};
function binDocsIntoIntervals() {
var topics_n, timeframe, intervals = [];
for (var itemID in docMetadata) {
var item = docMetadata[itemID],
date_str = item.date,
date_stripped = date_str.split(' ')[0].substring(0,10).replace(/-00/g, '-01'),
date;
if (!item.hasOwnProperty("topics")) continue;
try {
date = new Date(date_stripped);
} catch (e) { console.log(e); }
if (date instanceof Date && isFinite(date)) {
var my_interval = interval.floor(date),
interval_name = getIntervalName(my_interval);
intervals.push(my_interval);
if (!(intervalsObj.hasOwnProperty(interval_name))) {
intervalsObj[interval_name] = [];
}
intervalsObj[interval_name].push(itemID);
}
if (!topics_n) {
topics_n = Object.keys(item.topics).length;
}
}
timeframe = d3.extent(intervals);
var interval_bins = interval.range(timeframe[0], interval.offset(timeframe[1], 1));
var interval_names = interval_bins.map(getIntervalName);
var intervals_n = interval_bins.length;
topicProportions = new Array(topics_n);
topicStdevs = new Array(topics_n);
origTopicTimeData = [];
for (var i = 0, n = topics_n; i < n; i++) {
origTopicTimeData.push(new Array(intervals_n));
for (var j = 0, m = intervals_n; j < m; j++) {
var items = intervalsObj[interval_names[j]];
origTopicTimeData[i][j] = {"topic": i,
"x": interval_bins[j],
"y": []
};
if (items) {
items.forEach(function (itemID) {
origTopicTimeData[i][j].y.push({"itemID": itemID, "ratio": docMetadata[itemID].topics[i] || 0});
});
}
}
}
}
var sortMetrics = {
0: {"text": "most common"},
1: {"text": "most variable"},
2: {"text": "most coherent"}
};
var dateParse = d3.time.format("%Y").parse;
var offsetLeft = 0,
marginVertical = 0;
var x = d3.time.scale()
.range([0, width]);
var xOrdinal = d3.scale.ordinal()
.rangePoints([100, width - 100]);
var y = {"domain": function (range) {
for (var i in graph) {
graph[i].y.domain(range);
}}
};
var y0, y1;
var bars;
var horizonChart = d3.horizon()
.width(width)
.height(horizonHeight)
.bands(1)
.mode("mirror")
.interpolate("basis");
createMenuOfGraphs();
createSortingMenu();
generateTimeSearch();
createGraphObject(0);
var vis = d3.select("#chart")
.append("svg:svg")
.attr("width", width + offsetLeft + 25)
.attr("height", height + 50);
var defs = vis.append("svg:defs");
vis = vis.append("svg:g")
.on("click", getDocs);
var graphGroup = vis.append("svg:g").attr("id", "graphGroup");
var axesGroup = vis.append("svg:g").attr("id", "axesGroup");
var legendGroup = vis.append("svg:g").attr("id", "legendGroup");
var wordCloudGroup = vis.append("svg:g").attr("id", "wordCloudGroup")
.attr("transform", "translate(0," + (height - 100) + ")");
binDocsIntoIntervals();
dataSummed = [];
graph[0].active = true;
sumUpData(0);
y.domain([-maxStdDev, maxStdDev]);
startDate = graph[0].data[0][0].x;
endDate = graph[0].data[0][graph[0].data[0].length - 1].x;
x.domain([startDate, endDate]);
xOrdinal.domain(d3.keys(categories));
topicLabels = {};
for (i in labels) {
// if (labels[i].allocation_ratio > 0.0) {
topicLabels[i] = labels[i];
topicLabels[i]["active"] = true;
// }
}
xAxis = d3.svg.axis()
.scale(x)
// .ticks(interval.range, 10)
.tickSubdivide(1)
.tickSize(-height, -height);
xOrdinalAxis = d3.svg.axis()
.scale(xOrdinal);
mostCommonTopics(1/*5*/);
transition();
setStartParameters();
function onGraphSelect() {
var selectObj = document.getElementById("graphSelector");
var idx = selectObj.selectedIndex;
toggleState = parseInt(selectObj.options[idx].value);
transition();
}
function selectGraphState(state) {
var sel = document.getElementById("graphSelector");
for (var i in sel.options) {
var val = parseInt(sel.options[i].value);
if (val == state) {
sel.selectedIndex = i;
}
}
}
function createMenuOfGraphs () {
var sel = document.createElement("select");
sel.id = "graphSelector";
sel.onchange = onGraphSelect;
var graphTypeKeys = Object.keys(graphTypes);
graphTypeKeys.sort();
graphTypeKeys.forEach(function(type) {
var opt = document.createElement("option");
opt.value = type;
opt.text = graphTypes[type];
sel.add(opt, null);
});
var div = document.createElement("div");
var label = document.createElement("div");
var labeltext = document.createTextNode("Graph type:");
label.style.float = "left";
label.appendChild(labeltext);
div.appendChild(label);
div.appendChild(sel);
document.getElementById("searches").appendChild(div);
}
function onSortSelect() {
var selectObj = document.getElementById("sortSelector");
var idx = selectObj.selectedIndex;
sortMetric = parseInt(selectObj.options[idx].value);
topicLabelsSorted = Object.keys(topicLabels).sort(sortMetrics[sortMetric]["func"]);
updateActiveLabels();
updateLegend();
}
function selectSortMetric(metric) {
var sel = document.getElementById("sortSelector");
for (var i in sel.options) {
var val = parseInt(sel.options[i].value);
if (val == metric) {
sel.selectedIndex = i;
}
}
}
function createSortingMenu () {
var sel = document.createElement("select");
sel.id = "sortSelector";
sel.onchange = onSortSelect;
var sortMetricKeys = Object.keys(sortMetrics);
sortMetricKeys.sort();
sortMetricKeys.forEach(function(type) {
var opt = document.createElement("option");
opt.value = type;
opt.text = sortMetrics[type]["text"];
sel.add(opt, null);
});
var div = document.createElement("div");
var label = document.createElement("div");
var labeltext = document.createTextNode("Sort topics by:");
label.style.float = "left";
label.appendChild(labeltext);
div.appendChild(label);
div.appendChild(sel);
document.getElementById("searches").appendChild(div);
}
function doToggle(state) {
switch(state) {
case 0: // streamgraph
streaming = true;
stacked = false;
categorical = false;
horizon = false;
break;
case 1: // stacked area graph
streaming = true;
stacked = true;
categorical = false;
horizon = false;
break;
case 2: // line graph of standard deviations
streaming = false;
stacked = false;
categorical = false;
horizon = false;
break;
case 3: // bar graph of each subcategory
streaming = false;
stacked = false;
categorical = true;
horizon = false;
break;
case 4: // horizon graph of standard deviations
streaming = false;
stacked = false;
categorical = false;
horizon = true;
break;
}
}
function transition() {
if (toggleState == 3 && d3.keys(categories).length > 50) {
toggleState = 0;
}
doToggle(toggleState);
for (var i in graph) {
if (streaming && !stacked) {
graph[i].layout.offset("silhouette");
}
else if (stacked) {
graph[i].layout.offset("zero");
}
}
if (streaming) {
createGradientScale();
} else {
d3.select("#gradientScale").remove();
}
updateActiveLabels();
var my_graphs = [];
for (var i in graph) {
sumUpData(i);
setGraphPositions();
if (streaming) {
graph[i].streamData = graph[i].layout(graph[i].data);
}
}
if (streaming) {
for (var i in graph) {
if (graph[i].active) {
my_graphs.push(d3.max(graph[i].streamData, function(d) {
return d3.max(d, function(d) {
return d.y0 + d.y;
});
}));
}
}
}
x.domain([startDate, endDate]);
my = d3.max(my_graphs);
if (!streaming) y.domain([-maxStdDev,maxStdDev]);
else if (stacked) y.domain([0,1]);
else y.domain([0, my]);
resetColors();
updateLegend(); // CF update legend before graphs so that graphs know topic ordering
for (i in graph) {
if (graph[i].active) createOrUpdateGraph(i);
else graphGroup.selectAll("path.line.graph" + i.toString()).remove();
}
updateGradient();
graphGroup.select("#density").remove();
if (!categorical) {
graphGroup.append("rect")
.attr("id", "density")
.style("fill", "url(#linearGradientDensity)")
.style("pointer-events", "none")
.attr("width", width)
.attr("height", height);
}
refreshAxes();
//CF updateLegend(); // CF update legend before graphs so that graphs know topic ordering
}
function shuffle(array) {
var tmp, current, top = array.length;
if(top) while(--top) {
current = Math.floor(Math.random() * (top + 1));
tmp = array[current];
array[current] = array[top];
array[top] = tmp;
}
return array;
}
function resetColors(force) {
var currentColors = activeTopicLabels.map(function (d) { return graphColors(d); });
currentColors.sort();
var anyRepeats = false;
for (var i = 0, n = currentColors.length; i < n; i++) {
if (currentColors[i] == currentColors[(i + 1) % n]) {
anyRepeats = true;
}
}
if (!anyRepeats && !force) {
return;
}
// var newLabelColors = shuffle(activeTopicLabels.slice());
var newLabelColors = activeTopicLabels.slice();
if (newLabelColors.length <= 10) {
graphColors = d3.scale.category10();
} else {
graphColors = d3.scale.category20();
}
graphColors.domain(newLabelColors);
for (var i in wordClouds) {
wordCloudGroup.select(".cloud" + i.toString()).transition().duration(250).style("fill", graphColors(i));
}
}
function sumUpData(graphIndex) {
graph[graphIndex].data = [];
graph[graphIndex].categoricalData = [];
categories = {};
origTopicTimeData.forEach(function(d, i) { // for each topic
if (topicLabels == null || i in topicLabels && topicLabels[i]["active"]) {
d.forEach(function(e) { // for each interval
e.y.forEach(function (f) { // for each item within interval
var label = docMetadata[f.itemID]["label"];
if (!categories.hasOwnProperty(label)) {
categories[label] = {};
}
if (!categories[label].hasOwnProperty(i)) {
categories[label][i] = {'x': label, 'topic': i, 'y': 0};
}
});
});
}
});
var firstRun = dataSummed.length == 0;
var ordinalDocs = {};
origTopicTimeData.forEach(function (d, i) { // for each topic
if (topicLabels == null || i in topicLabels && topicLabels[i]["active"]) {
var length = graph[graphIndex].data.push([]);
d.forEach(function (e) { // for each interval
if (timeFilter(e)) {
var datum = {};
datum.x = e.x;
datum.topic = e.topic;
datum.search = graphIndex;
datum.y = 0.0;
graph[graphIndex].contributingDocs[getIntervalName(e.x)] = [];
e.y.forEach(function (f) { // for each item within interval
if (graph[graphIndex].searchFilter(f)) {
graph[graphIndex].contributingDocs[getIntervalName(e.x)].push(f.itemID);
datum.y += f.ratio;
var label = docMetadata[f.itemID]["label"];
categories[label][i].y += f.ratio;
if (!ordinalDocs.hasOwnProperty(label)) {
ordinalDocs[label] = {};
}
ordinalDocs[label][f.itemID] = true;
}
});
// if (!datum.y) console.log(e);
graph[graphIndex].data[length - 1].push(datum);
}
});
}
});
// if (firstRun) {
for (var j in graph[graphIndex].data) {
var i = graph[graphIndex].data[j][0].topic;
findTopicProportionAndStdev(i, graph[graphIndex].contributingDocs, graph[graphIndex].data[j]);
}
// }
for (var label in ordinalDocs) {
graph[graphIndex].contributingDocsOrdinal[label] = d3.keys(ordinalDocs[label]);
}
graph[graphIndex].data.forEach(function (d,i) {
d.forEach(function (e) {
var docsForInterval = graph[graphIndex].contributingDocs[getIntervalName(interval.floor(e.x))];
var s = (docsForInterval ? docsForInterval.length : 0) || 1;
// s is both the total number of docs in a given interval and the sum of all topics
// for that interval
if (!streaming) { // find standard score
e.y /= s;
e.y -= topicProportions[d[0].topic];
e.y /= topicStdevs[d[0].topic];
// e.y is now a z-score for that topic
} else {
e.y /= s;
}
});
});
if (!categorical && smoothing) { // smooth using simple moving average/median
graph[graphIndex].data.forEach(function (d,i) {
var smoothed = [];
for (var j = 0, n = d.length; j < n; j++) {
var sample = [];
for (var k = -windowSize; k <= windowSize; k++) {
if (j+k >= 0 && j+k < n) {
sample.push(d[j + k].y);
} else {
sample.push(d[j].y);
}
}
if (smoothing == "median") {
smoothed.push(d3.median(sample));
} else if (smoothing == "mean") {
smoothed.push(d3.mean(sample));
}
}
d.forEach(function (e, idx) {
e.y = smoothed[idx];
});
});
}
var activeTopics = [];
if (topicLabels != null) {
for (var i in topicLabels) {
if (topicLabels[i]["active"]) activeTopics.push(i);
}
} else {
activeTopics = d3.range(origTopicTimeData.length);
}
for (var i in activeTopics) {
graph[graphIndex].categoricalData.push([]);
}
var categoriesSorted = d3.keys(categories);
categoriesSorted.sort();
categoriesSorted.forEach(function (category) {
var category_docs = graph[graphIndex].contributingDocsOrdinal[category] ? graph[graphIndex].contributingDocsOrdinal[category].length : 0;
var s = category_docs || 1;
for (var i in activeTopics) {
var datum = categories[category][activeTopics[i]];
if (datum) {
datum.y /= s;
graph[graphIndex].categoricalData[i].push(datum);
}
}
});
if (firstRun) dataSummed = graph[graphIndex].data;
}
function showMore() {
var _topics = topicLabelsSorted.slice();
for (i in activeTopicLabels) {
var idx = _topics.indexOf(activeTopicLabels[i]);
_topics.splice(idx, 1);
}
_topics = _topics.slice(0,5);
//console.log(_topics);
for (i in topicLabels) {
topicLabels[i]["active"] = topicLabels[i]["active"] || _topics.indexOf(i) != -1;
}
transition();
}
function createOrUpdateGraph(i) {
if (categorical) {
createCategoricalGraph(i);
return;
}
if (horizon) {
createHorizonGraph(i);
return;
}
graphGroup.selectAll("g.layer").remove();
var graphSelection = graphGroup.selectAll("path.line.graph" + i.toString())
.data(streaming ? graph[i].streamData : graph[i].data, function(d) { return d[0].topic;});
graphSelection
.attr("stroke", function(d) { return !streaming ? graphColors(d[0].topic) : "#000"; })
.style("fill", function(d) { return streaming ? graphColors(d[0].topic) : "none"; })
.style("stroke-width", streaming ? "0.5" : "1.5")
.style("stroke-opacity", streaming ? "0.5" : "1.0")
.transition().duration(500).attr("d", streaming ? graph[i].area : graph[i].line);
graphSelection.style("fill", function(d) { return streaming ? graphColors(d[0].topic) : "none"; });
var graphEntering = graphSelection.enter();
graphEntering.append("svg:path")
.attr("class", function (d) { return "line graph" + i.toString() + " topic"+d[0].topic.toString(); })
.attr("stroke", function(d) { return !streaming ? graphColors(d[0].topic) : "#fff"; })
.style("fill", function(d) { return streaming ? graphColors(d[0].topic) : "none"; })
.style("stroke-width", streaming ? "0.5" : "2")
.style("stroke-opacity", "1")
.style("stroke-dasharray", graph[i].dasharray)
.on("mouseover", function (d) { highlightTopic(d[0]);})
.on("mouseout", unhighlightTopic)
.attr("d", streaming ? graph[i].area : graph[i].line)
.append("svg:title")
.text(function (d) { return topicLabels[d[0].topic]["label"]; });
var graphExiting = graphSelection.exit();
graphExiting.transition().duration(500).style("stroke-opacity", "0").remove();
graph[i].graphCreated = true;
}
function createCategoricalGraph (i) {
d3.layout.stack().offset("expand")(graph[i].categoricalData);
my = d3.max(graph[i].categoricalData, function(d) {
return d3.max(d, function(d) {
return d.y0 + d.y;
});
});
y0 = function(d) { return height - d.y0 * height / my; };
y1 = function(d) { return height - (d.y + d.y0) * height / my; };
var barWidth = (d3.max(xOrdinal.range()) - d3.min(xOrdinal.range())) / xOrdinal.domain().length / 3;
graphGroup.selectAll("*").remove();
var categoricalLayers = graphGroup.selectAll("g.layer").data(graph[i].categoricalData, function (d) { return d[0].topic; });
categoricalLayers.style("fill", function(d) { return graphColors(d[0].topic);});
categoricalLayers.exit().remove();
categoricalLayers.enter().append("g")
.attr("class", "layer")
.style("fill", function(d) { return graphColors(d[0].topic);});
bars = categoricalLayers.selectAll("g.bar.graph" + i.toString())
.data(function (d) { return d;}, function (d) { return d.x + d.topic.toString(); });
bars.selectAll("rect").transition()
.delay(function(d, i) { return i * 10; })
.attr("y", y1)
.attr("height", function(d) { return y0(d) - y1(d); });
bars.exit().remove();
bars.enter().append("g")
.attr("class", "bar graph" + i.toString())
.attr("transform", function(d) { return "translate(" + (xOrdinal(d.x) - (barWidth / 2)) + ",0)"; })
.on("click", getDocsForCategory)
.append("rect")
.attr("width", barWidth)
.attr("x", 0)
.attr("y", height)
.attr("height", 0)
.on("mouseover", function (d) { highlightTopic(d);})
.on("mouseout", unhighlightTopic)
.transition()
.delay(function(d, i) { return i * 10; })
.attr("y", y1)
.attr("height", function(d) { return y0(d) - y1(d); });
}
function createHorizonGraph(i) {
graphGroup.selectAll("*").remove();
var horizonLayers = graphGroup.selectAll("g.layer.horizon" + i.toString()).data(graph[i].data, function (d) { return d[0].topic; });
horizonLayers.exit().remove();
var horizonData = [];
graph[i].data.forEach(function(h){
var _horizonData = [];
h.forEach(function(d,id)
{_horizonData.push( [ d.x, d.y ] );})
horizonData.push(_horizonData);
});
var svg = horizonLayers.enter()
.append("g")
.attr("class", "layer")
.attr("transform",function(d){ return "translate(0,"+(legendLines*legendLineHeight + horizonHeight* activeTopicLabels.indexOf(d[0].topic.toString()))+")"; } )
.append("svg")
svg.append("svg:title")
.text(function(d) { return topicLabels[d[0].topic]['label'];})
svg
.attr("class",function(d){ return "horizon" + i.toString() + " topic"+d[0].topic.toString();})
.attr("width", width)
.attr("height", horizonHeight)
.data(horizonData)
.call(horizonChart)
}
// Enable mode buttons.
d3.selectAll("#horizon-controls input[name=mode]").on("change", function() {
if(horizon){
for (var i in graph) {
var svg = graphGroup.selectAll("g.layer").selectAll("svg");
svg.call(horizonChart.duration(0).mode(this.value));
}
}
});
// Enable bands buttons.
d3.selectAll("#horizon-bands button").data([-1, 1]).on("click", function(d) {
if(horizon){
var n = Math.max(1, horizonChart.bands() + d);
d3.select("#horizon-bands-value").text(n);
for (var i in graph) {
var svg = graphGroup.selectAll("g.layer").selectAll("svg");
svg.call(horizonChart.duration(1000).bands(n).height(horizonHeight / n));
}
}
});
function highlightTopic(e) {
// return;
var topic = e.topic;
if (!topicLabels[topic].active) return;
legend.style("fill-opacity", function (d) { return (d.topic == topic) ? 1.0 : (d.active ? 0.7 : 0.3);})
for (i in graph) {
var series = graphGroup.selectAll("path.line.graph" + i.toString());
series.transition().style(streaming ? "fill-opacity": "stroke-opacity", function (d) {
return (d[0].topic != topic) ? graph[i].defaultOpacity * 0.5 : graph[i].defaultOpacity;
});
if (categorical) {
var bars = graphGroup.selectAll("g.bar.graph" + i.toString());
bars.transition().style("fill-opacity", function (d) {
return (d.topic != topic) ? graph[i].defaultOpacity * 0.5 : graph[i].defaultOpacity;
});
}
}
}
function unhighlightTopic() {
legend.style("fill-opacity", function (d) { return (d.active) ? 1.0 : 0.3;})
for (i in graph) {
var series = graphGroup.selectAll("path.line.graph" + i.toString());
series.transition().style(streaming ? "fill-opacity" : "stroke-opacity", graph[i].defaultOpacity);
if (categorical) {
var bars = graphGroup.selectAll("g.bar.graph" + i.toString());
bars.transition().style("fill-opacity", graph[i].defaultOpacity);
}
}
}
function refreshAxes() {
if (axesGroup.select("g.x.axis").empty()) {
var gXAxis = axesGroup.append("svg:g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(categorical ? xOrdinalAxis : xAxis);
} else {
axesGroup.select("g.x.axis").transition().duration(500).call(categorical ? xOrdinalAxis : xAxis);
}
if (categorical) {
d3.select(".x.axis").selectAll("text")
.attr("transform", function(d) {
return "rotate(90)";
// translate(" + this.getBBox().height/2 + "," +
// this.getBBox().width/2 + ")";
});
} else {
d3.select(".x.axis").selectAll("text")
.attr("transform", "");
}
if (streaming && !stacked) {
axesGroup.selectAll("g.y.axis").transition().duration(500).style("fill-opacity", 0);
axesGroup.selectAll(".y.axis line").style("stroke-opacity", 0);
}
if (categorical || horizon) {
axesGroup.selectAll("g.y.axis").remove();
}
if ((!streaming || (streaming && stacked)) && !categorical && !horizon) {
axesGroup.selectAll("g.y.axis").remove();
for (var i in graph) {
if (axesGroup.selectAll("g.y.axis graph" +i.toString()).empty()) {
axesGroup.append("svg:g")
.attr("class", "y axis graph" +i.toString())
.attr("transform", "translate(-15,0)")
.call(graph[i].yAxis);
} else {
axesGroup.select("g.y.axis graph" +i.toString()).transition().duration(500).style("fill-opacity", 1).call(graph[i].yAxis);
}
}
axesGroup.selectAll(".y.axis line").transition().duration(500).style("stroke-opacity", 1);
}
}
function toggleTopic(d) {
if (d3.event) {
d3.event.preventDefault();
d3.event.stopPropagation();
}
topicLabels[d.topic]["active"] = !topicLabels[d.topic]["active"];
if (!topicLabels[d.topic]["active"] && d.topic in wordClouds) {
delete wordClouds[d.topic];
wordCloudGroup.select(".cloud" + d.topic).remove();
}
transition();
}
function wordCloudPositions (d, i) {
return "translate(" + ((i+1)*310) + ",0)";
}
function displayFullTopic(d) {
if (d3.event) {
d3.event.preventDefault();
d3.event.stopPropagation();
}
if (d.topic in wordClouds) {
wordCloudGroup.selectAll(".cloud" + d.topic).remove();
delete wordClouds[d.topic]
} else {
wordClouds[d.topic] = topicCloud(d.topic, wordCloudGroup);
wordCloudGroup.selectAll("g").attr("transform", wordCloudPositions)
}
}
function updateActiveLabels() {
activeTopicLabels = [], inactiveTopicLabels = [];
if (topicLabelsSorted) {
topicLabelsSorted.forEach(function(k) {
if (topicLabels[k]["active"]) current = activeTopicLabels;
else current = inactiveTopicLabels;
current.push(k);
});
} else {
for (var i in topicLabels) {
if (topicLabels[i]["active"]) activeTopicLabels.push(i);
else inactiveTopicLabels.push(i);
}
}
}
function updateLegend() {
// legendGroup.select("#legend").remove();
if (legendGroup.select("#legend").empty()) {
legend = legendGroup.append("svg:g")
.attr("id", "legend")
// .attr("transform", "translate(" + (width/2 - 230 ) + ", 10)")
.attr("transform", "translate(230,10)")
.style("visibility", showLegend > 1 ? "visible" : "hidden");
}
var topics = [];
var topicLabelsCurrent = activeTopicLabels.concat(inactiveTopicLabels);
topicLabelsCurrent.forEach(function (i) {
topics.push({'topic': i, 'label': topicLabels[i]['label'], 'active': topicLabels[i]["active"]});
});
// legendLabels = vis.select("#legend").selectAll(".legend.label").remove();
legend = legendGroup.select("#legend").selectAll(".legend.label").data(topics, function (d) { return d.topic;});
legend.style("fill", legendLabelColor);
var newLabels = legend.enter().append("svg:g")
.attr("class", "legend label")
.attr("transform", legendLabelPositions)
.style("fill-opacity", function (d) { return (d.active) ? 1.0 : 0.3;})
.style("fill", legendLabelColor)
.on("mouseover", highlightTopic)
.on("mouseout", unhighlightTopic)
.on("click", toggleTopic)
.on("contextmenu", displayFullTopic);
newLabels.append("svg:circle")
.attr("fill", "inherit")
.attr("r", 5);
newLabels.append("svg:text")
.attr("transform", "translate(10, 0)")
.attr("fill", "inherit")
.attr("dy", "0.5em")
.text(function(d) { return d.label})
.append("svg:title")
.text(function(d) { return (topicProportions[d.topic]*100.0).toFixed(2) + "% of corpus";});
legendGroup.selectAll(".legend.label").transition().duration(500).attr("transform", legendLabelPositions)
.style("fill-opacity", function (d) { return (d.active) ? 1.0 : 0.3;});
legend.exit().remove();
}
function legendLabelColor(d) {
return topicLabels[d.topic]["active"] ? graphColors(d.topic) : "#666666";
}
function legendLabelPositions (d) {
var topic = d.topic,
active = activeTopicLabels.indexOf(topic),
i;
if (active != -1) {
i = active;
} else {
i = activeTopicLabels.length + inactiveTopicLabels.indexOf(topic);
}
return "translate(" + (Math.floor(i/legendLines)*legendWidth) + "," + ((i % legendLines)*legendLineHeight) + ")";
}
function legendToggle() {
showLegend = (~~showLegend + 1) % 3; // 0 = all hidden, 1 = show legend, 2 = show legend and supporting docs scale
updateLegend();
var legend = d3.select("#legend");
legend.style("visibility", showLegend > 0 ? "visible" : "hidden");
var gradientScale = d3.select("#gradientScale");
gradientScale.style("visibility", showLegend > 1 ? "visible" : "hidden");
}
function setStartParameters() {
if (window.location.search != "") {
var queryString = window.location.search.slice(1);
var query = queryString.split("&");
var query_obj = {};
query.forEach(function (d) {
var s = d.split("=");
query_obj[s[0]] = decodeURIComponent(s[1]);
});
console.log(query_obj)
for (i in query_obj) {
if (i == "topics") {
var topics = query_obj[i];
topics = (topics.indexOf(",") != -1) ? topics.split(",") : [topics];
for (i in topicLabels) {
topicLabels[i].active = false;
}
for (i in topics) {
topicLabels[topics[i]].active = true;
}
}
else if (i == "legend") {
showLegend = parseInt(query_obj[i]) || 2;
} else if (i == "compare") {
for (var j = 1; j <= query_obj[i]; j++) { generateSearch(searchN++);}
} else if (i == "popup") {
deferUntilSearchComplete.add(getDocsForInterval, query_obj[i]);
} else if (i == "state") {
toggleState = parseInt(query_obj[i]);
selectGraphState(toggleState);
} else if (i == "sort") {
sortMetric = parseInt(query_obj[i]);
selectSortMetric(sortMetric);
} else if (document.getElementById(i)) {
document.getElementById(i).value = query_obj[i];
}
}
// searchAction();
} else {
if (typeof tags === "object") {
var tag_keys = Object.keys(tags);
if (tag_keys && tag_keys.length > 0) {
for (var i in tags) {
index[i] = tags[i];
}
var tagsN = tag_keys.length;
if (tagsN > 0 && tagsN < 5) {
for (var i = 0; i < tagsN; i++) {
generateSearch(searchN++, tag_keys[i]);
}
}
} else {
generateSearch(searchN++);
}
} else {
generateSearch(searchN++);
}
}
selectGraphState(toggleState);
searchAction();
}
function save() {
var url = "?";
url += "&state="+(toggleState.toString());
url += "&compare="+(searchN).toString();
url += "&sort="+(sortMetric).toString();
var fields = document.getElementsByTagName("input");
for (i in fields) {
if (fields[i].id != undefined) {
var val = encodeURIComponent(fields[i].value);
if (val != "") {
url += "&" + fields[i].id+ "=" + val;
}
}
}
url += "&topics=" + Object.keys(topicLabels).filter(function (d) { return topicLabels[d].active;}).join(",");
url += "&legend=" + showLegend;
var popups = d3.selectAll(".popupHolder[display=block]");
if (!popups.empty()) {
url += "&popup=" + popups.attr("data-interval");
}
for (var i in graph) {
if (graph[i].active && graph[i].queryStr != "") {
d3.select("svg").append("text")
.text(graph[i].queryStr)
.attr("x", 0)
.attr("y", graph[i].baseline);
}
}
saveSVG();
window.location.href = url;
}
function reset() {
location.href = window.location.pathname;
}
function compare() {
generateSearch(searchN++);
}
function nMostTopicsByMetric(n, metric) {
topicLabelsSorted = Object.keys(topicLabels).sort(metric);
topicLabelsSorted.forEach(function (d, i) {
topicLabels[d]["active"] = i < n;
});
transition();
}
function mostCoherentTopics(n) {
if (Object.keys(topicCoherence).length > 0) {
nMostTopicsByMetric(n, topicCoherenceSort);
} else {
nMostTopicsByMetric(n, prevalenceSort);
}
}
function mostCommonTopics(n) {
nMostTopicsByMetric(n, prevalenceSort);
}
function mostVariantTopics(n) {
nMostTopicsByMetric(n, stdevSort)
}
sortMetrics[0]["func"] = prevalenceSort;
sortMetrics[1]["func"] = stdevSort;
sortMetrics[2]["func"] = topicCoherenceSort;
function topNCorrelatedTopicPairs(n) {
var keys = d3.keys(topicCorrelations);
var values = d3.values(topicCorrelations);
var key_order = argmax(values, n);
key_order.reverse();
var descriptions = [];
for (i in key_order) {
var pair = keys[key_order[i]],
split_pair = pair.split(','),
a = split_pair[0],
b = split_pair[1];
var corr_str = '"' + topicLabels[a]['label'].join(', ') + '" and "' + topicLabels[b]['label'].join(', ') + '": ' + topicCorrelations[pair];
descriptions.push(corr_str);
}
alert(descriptions.join("\n"));
}
function stdevSort(a, b) {
return d3.max(dataSummed[b].map(function (e) { return e.y; })) - d3.max(dataSummed[a].map(function (e) { return e.y; }));
}
function prevalenceSort(a, b) {
return topicProportions[b] - topicProportions[a];
}
function topicCoherenceSort(a, b) {
if (topicCoherence[a] != 0 && topicCoherence[b] != 0) {
return topicCoherence[b] - topicCoherence[a];
} else {
return topicCoherence[a] == 0 ? (topicCoherence[b] == 0 ? 0 : 1) : -1;
}
}
function argmax(array, n) {
if (n) {
return argsort(array).slice(-n);
} else {
return array.indexOf(d3.max(array));
}
}
function argsort(array) {
var indices = [];
for (i in array) { indices.push(i); }
indices.sort(function (a,b) { return d3.ascending(array[a], array[b]);});
return indices;
}
function getDocs(d, i, p) {
var mouse = [d3.event.pageX, d3.event.pageY];
// var date = d3.time.year.floor(x.invert(mouse[0]));
var intervalName = getIntervalName(x.invert(mouse[0]));
getDocsForInterval(intervalName);
}
function getDocsForCategory(d) {
var category = d.x;
getSpecifiedDocs(category, xOrdinal, function (d) { return d; }, graph[0].contributingDocsOrdinal);
}
function getDocsForInterval(intervalName) {
getSpecifiedDocs(intervalName, x, function (d) { return new Date(d); }, graph[0].contributingDocs);
}
function getSpecifiedDocs(xval, xfunc, xaccessor, contributing) {
var i = 0;
if (contributing.hasOwnProperty(xval)) {
var docs = "";
for (var doc in contributing[xval]) {
var id = contributing[xval][doc];
var title = docMetadata[id]["title"];
if (title == "\t") title = id;
var mainTopic = docMetadata[id]["main_topic"];
var my_color = "#666";
if (topicLabels[mainTopic] && topicLabels[mainTopic]["active"]) {
my_color = graphColors(mainTopic);
}
docs += "<a style='color: " + my_color + ";' id='doc" + id + "' href='";
if (id.indexOf("10.") != -1) {
docs += "http://jstor.org/discover/" + id + "'>"
} else {
docs += "zotero://select/item/" + id + "'>"
}
docs += title + "</a><br/>";
}
d3.select("#popup" + i).html(docs);
d3.select("#popupHolder" + i).style("display", "block");
d3.select("#popupHolder" + i).style("left", xfunc(xaccessor(xval)) + "px");
d3.select("#popupHolder" + i).style("top", height/2 + "px");
d3.select("#popupHolder" + i).attr("data-interval", xval);
}
}
function createPopup(i) {
var closeButton = document.createElement("button");
closeButton.innerText = "x";
closeButton.onclick = function () {
d3.selectAll(".popupHolder").style("display", "none");
};
var popupHolder = document.createElement("div");
popupHolder.id = "popupHolder" + i;
popupHolder.className = "popupHolder";
var popup = document.createElement("div");
popup.id = "popup" + i;
popup.className = "popup";
popupHolder.appendChild(closeButton)
popupHolder.appendChild(popup);
return popupHolder;
}
function generateTimeSearch() {
var form = document.createElement("form");
form.id = "searchFormInitial";
form.className = "search";
form.action = "javascript:void(0);";
var searchTimeLabel = document.createElement("label");
searchTimeLabel.textContent = "Time:";
searchTimeLabel.htmlFor = "searchTime0";
searchTimeLabel.className = "searchLabel";
var searchTime = document.createElement("input");
searchTime.type = "text";
searchTime.id="searchTime0";
searchTime.alt="time";
searchTime.className = "searchText";
searchTime.onchange = searchAction;
form.appendChild(searchTimeLabel);
form.appendChild(searchTime);
document.getElementById("searches").appendChild(form);
}
function generateSearch(i, initialValue) {
var form = document.createElement("form");
form.id = "searchForm" + i;
form.className = "search";
form.action = "javascript:void(0);";
var searchid = "search" + i;
var searchLabel = document.createElement("label");
searchLabel.textContent = "Search " + (i + 1);
searchLabel.htmlFor = searchid;
searchLabel.className = "searchLabel";
var search = document.createElement("input");
search.type = "text";
search.id = searchid;
search.alt="enter to search";
search.className = "searchText";
if (initialValue) search.value = initialValue;
search.onchange = searchAction;
var searchAdd = document.createElement("button");
searchAdd.innerHTML = "+";
searchAdd.className = "searchAddRemove";
searchAdd.type = "button";
searchAdd.onclick = function () { generateSearch(searchN++) };
form.appendChild(searchLabel);
form.appendChild(search);
form.appendChild(searchAdd);
if (i != 0) {
var searchRemove = document.createElement("button");
searchRemove.innerHTML = "-";
searchRemove.className = "searchAddRemove";
searchRemove.type = "button";
searchRemove.onclick = function () {
var my_search = document.getElementById("search" + i);
my_search.parentNode.parentNode.removeChild(my_search.parentNode);
graph[i].active = false;
searchN--;
searchAction();
};
form.appendChild(searchRemove);
}
document.getElementById("searches").appendChild(form);
var popup = createPopup(i);
document.getElementById("popupLayer").appendChild(popup);
createGraphObject(i);
}
function createGraphObject(i) {
graph[i] = {'searchFilter': function() { return true; },
'data': null,
'defaultOpacity': 1.0 - (i/5.0),
'graphCreated': false,
'results': null,
'dasharray': i == 0 ? "" : 12 / (i+1),
'contributingDocs': {},
'contributingDocsOrdinal': {},
'baseline': 0,
'y': d3.scale.linear(),
'layout': d3.layout.stack().offset("silhouette")
};
graph[i].line = (function (me) {
return d3.svg.line()
.interpolate(interpolateType)
.x(function(d) { return x(d.x); })
.y(function(d) { return me.y(d.y); });
})(graph[i]);
graph[i].area = (function (me) {
return d3.svg.area()
.interpolate(interpolateType)
.x(function(d) { return x(d.x); })
.y0(function(d) { return me.y(d.y0); })
.y1(function(d) { return me.y(d.y0 + d.y); });
})(graph[i]);
graph[i].yAxis = (function (me) {
return d3.svg.axis()
.scale(me.y)
.orient("right")
.ticks(5)
.tickSize(width, width);
})(graph[i]);
}
function setGraphPositions() {
var totalHeight = height - (marginVertical * 2.0);
var graphs_active = [];
for (var i in graph) {
if (graph[i].active) graphs_active.push(i);
}
for (var i = 0, n = graphs_active.length; i < n; i++) {
var my_ambit = (totalHeight / n);
var my_top = marginVertical + (my_ambit * i);
var my_bottom = my_top + my_ambit;
graph[graphs_active[i]].y.range([my_bottom, my_top]);
graph[graphs_active[i]].baseline = (my_bottom + my_top)/2.0;
}
}
function highlightItem(itemID) {
getDocsForInterval(docMetadata[itemID]["interval"]);
d3.select("#doc" + itemID.toString()).call(flash);
}
function flash(selection) {
selection.transition().duration(2000)
.ease("linear")
.styleTween("fill-opacity", function (d, i, a) {
return function (t) {
var x = (Math.sin(t * Math.PI * 4)) + 1;
return x.toString();
}
});
}
function searchAction() {
var queryTime = document.getElementById("searchTime0").value;
if (queryTime == "") {
timeFilter = function() { return true; }
startDate = origTopicTimeData[0][0].x;
endDate = origTopicTimeData[0][origTopicTimeData[0].length - 1].x;
}
else {
var times = queryTime.split("-");
startDate = dateParse(times[0]);
endDate = dateParse(times[1]);
timeFilter = function(d) {
return d.x >= startDate && d.x <= endDate;
};
}
var actives = 0;
for (var i in graph) {
if (document.getElementById("search" + i)) {
graph[i].queryStr = document.getElementById("search" + i).value;
if (graph[i].queryStr != "") {
actives++;
}
} else {
graph[i].queryStr = "";
}
}
for (var i in graph) {
if (graph[i].queryStr == "" && actives > 0) {
graph[i].active = false;
} else {
graph[i].active = true;
actives++;
}
}
for (var i = 0; i < searchN; i++ ) {
if (graph[i].queryStr == "") {
graph[i].searchFilter = function() {
return true;
};
} else {
var originalTerms = graph[i].queryStr.split(" ");
var terms = {};
graph[i].results = {};
if (graph[i].queryStr in index) {
terms[graph[i].queryStr] = true;
} else {
for (var j in originalTerms) {
var term = originalTerms[j];
if (term in index) {
terms[term] = true;
} else {
for (var k in indexTerms) {
if (indexTerms[k].match(term)) {
terms[indexTerms[k]] = true;
}
}
}
}
}
for (var term in terms) {
for (var j in index[term]) {
graph[i].results[index[term][j]] = true;
}
}
graph[i].searchFilter = (function (graph) { return function (d) { return graph.results.hasOwnProperty(d.itemID) }; })(graph[i]);
// var element = document.createElement("PaperMachinesDataElement");
// element.setAttribute("query", graph[i].queryStr);
// document.documentElement.appendChild(element);
// me.searchCallback = function (search) {
// me.results = search;
// me.searchFilter = function (d) {
// return me.results.indexOf(parseInt(d.itemID)) != -1;
// };
// };
// document.addEventListener("papermachines-response", function(event) {
// var node = event.target, response = node.getUserData("response");
// document.documentElement.removeChild(node);
// document.removeEventListener("papermachines-response", arguments.callee, false);
// me.searchCallback(JSON.parse(response));
// }, false);
// var evt = document.createEvent("HTMLEvents");
// evt.initEvent("papermachines-request", true, false);
// element.dispatchEvent(evt);
}
}
setTimeout(function () {transition();}, 500);
deferUntilSearchComplete.next();
}
function createGradientScale() {
if (!gradientDomain) return;
var my_range = d3.range(0, gradientDomain[1] + 0.2, 0.2);
var gradientAxis = d3.svg.axis()
.scale(d3.scale.linear().domain([0, gradientDomain[1]]).range([0,200]))
.ticks(4)
.tickFormat(d3.format("d"))
.tickSize(0);
d3.select("#gradientScale").remove();
defs.select("#gradientScaleGradient").remove();
defs.selectAll("#gradientScaleGradient").data([my_range]).enter().append("svg:linearGradient")
.attr("id", "gradientScaleGradient")
.attr("x1", "0%")
.attr("y1", "0%")
.attr("x2", "100%")
.attr("y2", "0%")
.selectAll("stop").data(function (d) { return d; })
.enter().append("svg:stop")
.attr("offset", function (d) { return (d * 100.0 / gradientDomain[1]) + "%"; })
.attr("stop-color", graphColors.range()[0])
.attr("stop-opacity", function (d) { return 1 - gradientOpacity(d); });
gradientBox = d3.select("#legendGroup").append("svg:g")
.attr("id", "gradientScale")
.attr("width", "200")
.attr("height", "30")
.attr("transform", "translate(10, 450)");
// .attr("transform", "translate(" + ((width/2) - 100) + "," + (height - 100) + ")");
gradientBox.append("svg:text")
.attr("x", "100")
.attr("y", "-10")
.style("fill", "#000")
.attr("text-anchor", "middle")
.text("Supporting Documents");
gradientBox.append("svg:rect")
.attr("width", "200")
.attr("height", "20")
.style("stroke", "#666")
.style("fill", "url(#gradientScaleGradient)");
gradientBox.append("svg:g")
.style("fill", "#000")
.style("stroke", "none")
.attr("transform", "translate(0,20)")
.call(gradientAxis);
}
function updateGradient() {
defs.select("#linearGradientDensity").remove();
var docNumbers = [],
intervalsObj = {};
for (var i in graph) {
if (graph[i].active) {
for (var intervalName in graph[i].contributingDocs) {
intervalsObj[intervalName] = {};
graph[i].contributingDocs[intervalName].forEach(function (doc) {
intervalsObj[intervalName][doc] = true;
});
}
}
}
var intervals = d3.keys(intervalsObj);
intervals.sort();
intervals.forEach(function (intervalName) {
var intervalDate = new Date(intervalName);
if (intervalDate >= startDate && intervalDate < endDate) {
var sum = Object.keys(intervalsObj[intervalName]).length;
docNumbers.push({"percentage": 100.0 * (intervalDate - startDate) / (endDate - startDate), "value": sum});
}
});
gradientDomain = d3.extent(docNumbers.map(function(d) { return d.value;}));
gradientOpacity.domain([0, gradientDomain[1]]);
var gradients = defs.selectAll("#linearGradientDensity").data([docNumbers]);
gradients.enter().append("svg:linearGradient")
.attr("id", "linearGradientDensity")
.attr("x1", "0%")
.attr("y1", "0%")
.attr("x2", "100%")
.attr("y2", "0%")
.selectAll("stop").data(function (d) { return d; })
.enter().append("svg:stop")
.attr("offset", function (d, i) { return (d.percentage) + "%"; })
// .attr("offset", function (d, i) { return (i * 100.0 / this.parentNode.__data__.length) + "%"; })
.attr("stop-color", "#fff")
.attr("stop-opacity", function (d) { return gradientOpacity(d.value); });
}
function topicCloud(i, parent) {
var topicWords = topicLabels[i]["fulltopic"]
cloudW = 300,
cloudH = 150,
cloudFontSize = d3.scale.log().domain(d3.extent(topicWords.map(function (d) { return +d.prob; }))).range([8,32]),
cloud = d3.layout.cloud()
.size([cloudW, cloudH])
.padding(5)
.words(topicWords)
.rotate(0)
.fontSize(function(d) { return cloudFontSize(d.prob); })
.on("end", draw)
.start();
function draw(words) {
if (parent.empty()) {
parent = d3.select("body").append("svg")
.attr("width", cloudW)
.attr("height", cloudH);
}
parent.append("g")
.attr("class", "cloud" + i.toString())
.attr("transform", "translate(" + cloudW/2 + "," + cloudH / 2 + ")")
.style("fill", graphColors(i))
.selectAll("text")
.data(words)
.enter().append("text")
.style("font-size", function(d) { return d.size + "px"; })
.attr("text-anchor", "middle")
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.text(function(d) { return d.text; });
}
return parent.select("g.cloud" + i.toString());
}
function findTopicProportionAndStdev(i, contributingDocs, intervals_data) {
var vals = intervals_data.map(function (d) { var total = contributingDocs[getIntervalName(d.x)].length || 1; return d.y / total;});
topicProportions[i] = d3.mean(vals);
var variances = vals.map(function (val) { return Math.pow(val - topicProportions[i], 2); });
topicStdevs[i] = Math.sqrt((1.0 / (vals.length - 1.0)) * d3.sum(variances));
}
function changeGradientScale(val) {
gradientExponentScale = val;
gradientOpacity.exponent(gradientExponentScale);
updateGradient();
createGradientScale();
}
function saveSVG() {
var xml = "<svg xmlns='http://www.w3.org/2000/svg'><style>";
for (i in document.styleSheets)
for (j in document.styleSheets[i].cssRules)
if (typeof(document.styleSheets[i].cssRules[j].cssText) != "undefined")
xml += document.styleSheets[i].cssRules[j].cssText;
xml += "</style>";
xml += d3.select("svg")[0][0].innerHTML;
xml += "</svg>";
window.open("data:image/svg+xml," + encodeURIComponent(xml));
}
|
ChristianFrisson/InfoPhys
|
PaperMachines/support/stream-horizon-works.js
|
JavaScript
|
gpl-2.0
| 53,732
|
package views.ui.gui;
/**
* Created by eunderhi on 08/02/16.
*/
public interface Button {
void onClick();
}
|
emmettu/Installator
|
src/main/java/views/ui/gui/Button.java
|
Java
|
gpl-2.0
| 116
|
//
// UIImage+ColorFinder.h
// ColorFinder
//
// Created by Mert Buran on 13/04/15.
// Copyright (c) 2015 Mert Buran. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIImage (ColorFinder)
- (void)getDominantColorInRect:(CGRect)rect WithCompletionHandler:(void (^)(UIColor* dominantColor))completion;
@end
|
ruuki/ColorFinder
|
ColorFinder/UIImage+ColorFinder.h
|
C
|
gpl-2.0
| 322
|
/* Script Data Start
SDName: Boss cyanigosa
SDAuthor: LordVanMartin
SD%Complete:
SDComment:
SDCategory:
Script Data End */
/*** SQL START ***
update creature_template set scriptname = '' where entry = '';
*** SQL END ***/
#include "precompiled.h"
#include "violet_hold.h"
enum Spells
{
SPELL_ARCANE_VACUUM = 58694,
SPELL_BLIZZARD = 58693,
H_SPELL_BLIZZARD = 59369,
SPELL_MANA_DESTRUCTION = 59374,
SPELL_TAIL_SWEEP = 58690,
H_SPELL_TAIL_SWEEP = 59283,
SPELL_UNCONTROLLABLE_ENERGY = 58688,
H_SPELL_UNCONTROLLABLE_ENERGY = 59281,
SPELL_TRANSFORM = 58668
};
enum Yells
{
SAY_AGGRO = -1608000,
SAY_SLAY_1 = -1608001,
SAY_SLAY_2 = -1608002,
SAY_SLAY_3 = -1608003,
SAY_DEATH = -1608004,
SAY_SPAWN = -1608005,
SAY_DISRUPTION = -1608006,
SAY_BREATH_ATTACK = -1608007,
SAY_SPECIAL_ATTACK_1 = -1608008,
SAY_SPECIAL_ATTACK_2 = -1608009
};
struct TRINITY_DLL_DECL boss_cyanigosaAI : public ScriptedAI
{
boss_cyanigosaAI(Creature *c) : ScriptedAI(c)
{
pInstance = c->GetInstanceData();
}
uint32 uiArcaneVacuumTimer;
uint32 uiBlizzardTimer;
uint32 uiManaDestructionTimer;
uint32 uiTailSweepTimer;
uint32 uiUncontrollableEnergyTimer;
ScriptedInstance* pInstance;
void Reset()
{
uiArcaneVacuumTimer = 10000;
uiBlizzardTimer = 15000;
uiManaDestructionTimer = 30000;
uiTailSweepTimer = 20000;
uiUncontrollableEnergyTimer = 25000;
if (pInstance)
pInstance->SetData(DATA_CYANIGOSA_EVENT, NOT_STARTED);
}
void EnterCombat(Unit* who)
{
DoScriptText(SAY_AGGRO, m_creature);
DoCast(m_creature, SPELL_TRANSFORM);
if (pInstance)
pInstance->SetData(DATA_CYANIGOSA_EVENT, IN_PROGRESS);
}
void MoveInLineOfSight(Unit* who) {}
void UpdateAI(const uint32 diff)
{
if (pInstance && pInstance->GetData(DATA_REMOVE_NPC) == 1)
{
m_creature->ForcedDespawn();
pInstance->SetData(DATA_REMOVE_NPC, 0);
}
//Return since we have no target
if (!UpdateVictim())
return;
if (uiArcaneVacuumTimer <= diff)
{
DoCast(SPELL_ARCANE_VACUUM);
uiArcaneVacuumTimer = 10000;
} else uiArcaneVacuumTimer -= diff;
if (uiBlizzardTimer <= diff)
{
if (Unit *pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true))
DoCast(pTarget, DUNGEON_MODE(SPELL_BLIZZARD, H_SPELL_BLIZZARD));
uiBlizzardTimer = 15000;
} else uiBlizzardTimer -= diff;
if (uiTailSweepTimer <= diff)
{
DoCast(DUNGEON_MODE(SPELL_TAIL_SWEEP, H_SPELL_TAIL_SWEEP));
uiTailSweepTimer = 20000;
} else uiTailSweepTimer -= diff;
if (uiUncontrollableEnergyTimer <= diff)
{
DoCastVictim(DUNGEON_MODE(SPELL_UNCONTROLLABLE_ENERGY,H_SPELL_UNCONTROLLABLE_ENERGY));
uiUncontrollableEnergyTimer = 25000;
} else uiUncontrollableEnergyTimer -= diff;
if (IsHeroic())
if (uiManaDestructionTimer <= diff)
{
if (Unit* pTarget = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true))
DoCast(pTarget, SPELL_MANA_DESTRUCTION);
uiManaDestructionTimer = 30000;
} else uiManaDestructionTimer -= diff;
DoMeleeAttackIfReady();
}
void JustDied(Unit* killer)
{
DoScriptText(SAY_DEATH, m_creature);
if (pInstance)
pInstance->SetData(DATA_CYANIGOSA_EVENT, DONE);
}
void KilledUnit(Unit *victim)
{
if (victim == m_creature)
return;
DoScriptText(RAND(SAY_SLAY_1,SAY_SLAY_2,SAY_SLAY_3), m_creature);
}
};
CreatureAI* GetAI_boss_cyanigosa(Creature* pCreature)
{
return new boss_cyanigosaAI (pCreature);
}
void AddSC_boss_cyanigosa()
{
Script *newscript;
newscript = new Script;
newscript->Name = "boss_cyanigosa";
newscript->GetAI = &GetAI_boss_cyanigosa;
newscript->RegisterSelf();
}
|
kenshinakh/trinity
|
src/bindings/scripts/scripts/northrend/violet_hold/boss_cyanigosa.cpp
|
C++
|
gpl-2.0
| 4,661
|
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the qt3to4 porting application of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "projectporter.h"
#include "proparser.h"
#include "textreplacement.h"
#include "fileporter.h"
#include "logger.h"
#include "translationunit.h"
#include "codemodelattributes.h"
#include <QtDebug>
#include <QFile>
#include <QDir>
#include <QStringList>
#include <QFileInfo>
#include <QBuffer>
QT_BEGIN_NAMESPACE
using namespace TokenEngine;
ProjectPorter::ProjectPorter(QString basePath, QStringList includeDirectories, QStringList qt3HeadersFilenames)
:basePath(basePath)
,includeDirectories(includeDirectories)
,defaultDefinitions(defaultMacros(preprocessorCache))
,filePorter(preprocessorCache)
,qt3HeadersFilenames(qt3HeadersFilenames)
,analyze(true)
,warnings(false)
{}
void ProjectPorter::enableCppParsing(bool enable)
{
analyze = enable;
}
void ProjectPorter::enableMissingFilesWarnings(bool enable)
{
warnings = enable;
}
void ProjectPorter::portProject(QString fileName)
{
QFileInfo fileInfo(fileName);
portProject(fileInfo.path(), fileInfo.fileName());
}
/*
Port a single file
*/
void ProjectPorter::portFile(QString fileName)
{
if (analyze) {
IncludeFiles includeFiles(basePath, includeDirectories);
PreprocessorController preprocessor(includeFiles, preprocessorCache, qt3HeadersFilenames);
connect(&preprocessor, SIGNAL(error(QString,QString)), SLOT(error(QString,QString)));
Rpp::DefineMap definitionsCopy = *defaultDefinitions;
// Preprocess
TokenSectionSequence translationUnit = preprocessor.evaluate(fileName, &definitionsCopy);
// Parse
TranslationUnit translationUnitData = TranslationUnitAnalyzer().analyze(translationUnit);
// Enable attribute generation for this file.
enableAttributes(includeFiles, fileName);
// Generate attributes.
CodeModelAttributes().createAttributes(translationUnitData);
}
portFiles(QString(), QStringList() << fileName);
}
void ProjectPorter::error(QString type, QString text)
{
if (warnings && type == QLatin1String("Error"))
printf("Warning: %s\n", text.toLocal8Bit().constData());
}
void ProjectPorter::portProject(QString basePath, QString proFileName)
{
QString fullInFileName = basePath + QLatin1String("/") + proFileName;
QFileInfo infileInfo(fullInFileName);
if (!infileInfo.exists()) {
printf("Could not open file: %s\n", QDir::toNativeSeparators(fullInFileName).toLocal8Bit().constData());
return;
}
QString proFileContents = loadFile(fullInFileName);
QMap<QString, QString> proFileMap = proFileTagMap(proFileContents, QDir(basePath).absolutePath());
// Check if this is a TEMPLATE = subdirs .pro file, in that case we
// process each subdir (recursively).
QString templateTag = proFileMap[QLatin1String("TEMPLATE")];
if (templateTag == QLatin1String("subdirs")) {
QStringList subdirs = proFileMap[QLatin1String("SUBDIRS")].split(QLatin1String(" "), QString::SkipEmptyParts);
foreach(QString subdir, subdirs) {
QString newBasePath = basePath + QLatin1String("/") + subdir;
QStringList dirsInSubdir = subdir.split(QRegExp(QLatin1String("/|\\\\")), QString::SkipEmptyParts);
QString newProFileName = dirsInSubdir.last() + QLatin1String(".pro");
portProject(newBasePath, newProFileName);
}
return;
}
// Get headers and sources file names from .pro file.
QStringList sources = proFileMap[QLatin1String("SOURCES")].split(QLatin1String(" "), QString::SkipEmptyParts);
QStringList headers = proFileMap[QLatin1String("HEADERS")].split(QLatin1String(" "), QString::SkipEmptyParts);
QStringList forms = proFileMap[QLatin1String("FORMS")].split(QLatin1String(" "), QString::SkipEmptyParts);
QStringList uidoth;
for (int i = 0; i < forms.size(); ++i) {
QString ui_h = forms.at(i) + QLatin1String(".h");
if (QFile::exists(basePath + QLatin1String("/") + ui_h))
uidoth += ui_h;
}
if (analyze) {
printf("Parsing");
// Get include paths from the pro file.
QStringList includeProPaths = proFileMap[QLatin1String("INCLUDEPATH")].split(QLatin1String(" "), QString::SkipEmptyParts);
QStringList dependProPaths = proFileMap[QLatin1String("DEPENDPATH")].split(QLatin1String(" "), QString::SkipEmptyParts);
IncludeFiles includeFiles(basePath, includeDirectories + includeProPaths + dependProPaths);
PreprocessorController preprocessorController(includeFiles, preprocessorCache, qt3HeadersFilenames);
connect(&preprocessorController, SIGNAL(error(QString,QString)), SLOT(error(QString,QString)));
TranslationUnitAnalyzer translationUnitAnalyzer;
CodeModelAttributes codeModelAttributes;
// Enable attribute generation for header files.
foreach(QString headerFile, headers)
enableAttributes(includeFiles, headerFile);
// Enable attribute generation for ui.h files.
foreach(QString headerFile, uidoth)
enableAttributes(includeFiles, headerFile);
// Analyze each translation unit. (one per cpp file)
foreach(QString sourceFile, sources) {
printf(".");
fflush(stdout);
Rpp::DefineMap definitionsCopy = *defaultDefinitions;
TokenSectionSequence translationUnit =
preprocessorController.evaluate(sourceFile, &definitionsCopy);
TranslationUnit translationUnitData =
translationUnitAnalyzer.analyze(translationUnit);
// Enable attribute generation for this file.
enableAttributes(includeFiles, sourceFile);
codeModelAttributes.createAttributes(translationUnitData);
}
puts("");
}
// Port files.
portFiles(basePath, sources);
portFiles(basePath, headers);
if (!uidoth.isEmpty())
portFiles(basePath, uidoth);
Logger::instance()->globalState[QLatin1String("currentFileName")] = proFileName;
Logger::instance()->beginSection();
portProFile(fullInFileName, proFileMap);
}
/*
Port each file given in the fileNames list. If a file name is relative
it is assumed to be relative to basePath.
*/
void ProjectPorter::portFiles(QString basePath, QStringList fileNames)
{
foreach(QString fileName, fileNames) {
QString fullFilePath;
QFileInfo fileInfo(fileName);
if (fileInfo.isAbsolute()) {
fullFilePath = QDir::cleanPath(fileName);
} else {
fullFilePath = QDir::cleanPath(basePath + QLatin1String("/") + fileName);
}
QFileInfo fullFilePathInfo(fullFilePath);
if (!fullFilePathInfo.exists()) {
printf("Could not find file: %s\n", QDir::toNativeSeparators(fullFilePath).toLocal8Bit().constData());
continue;
}
if (!processedFilesSet.contains(fullFilePath)){
Logger::instance()->globalState[QLatin1String("currentFileName")] = fullFilePath;
filePorter.port(fullFilePath);
processedFilesSet.insert(fullFilePath);
}
}
}
void ProjectPorter::portProFile(QString fileName, QMap<QString, QString> tagMap)
{
// Read pro file.
QFile proFile(fileName);
if (!proFile.open(QIODevice::ReadOnly))
return;
const QByteArray contents = proFile.readAll();
const QByteArray lineEnding = detectLineEndings(contents);
proFile.seek(0);
QTextStream proTextStream(&proFile);
QStringList lines;
while (!proTextStream.atEnd())
lines += proTextStream.readLine();
proFile.close();
// Find out what modules we should add to the QT variable.
QSet<QByteArray> qtModules;
// Add qt3support to the Qt tag
qtModules.insert(QByteArray("qt3support"));
// Read CONFIG and add other modules.
QStringList config = tagMap[QLatin1String("CONFIG")].split(QLatin1String(" "), QString::SkipEmptyParts);
if (config.contains(QLatin1String("opengl")))
qtModules.insert(QByteArray("opengl"));
if (config.contains(QLatin1String("xml")))
qtModules.insert(QByteArray("xml"));
if (config.contains(QLatin1String("sql")))
qtModules.insert(QByteArray("sql"));
if (config.contains(QLatin1String("network")))
qtModules.insert(QByteArray("network"));
// Get set of used modules from the file porter.
qtModules += filePorter.usedQtModules();
// Remove gui and core.
qtModules.remove(QByteArray("gui"));
qtModules.remove(QByteArray("core"));
// Qt3Support is already added.
qtModules.remove(QByteArray("3support"));
// Remove modules already present in the QT variable.
QStringList qt = tagMap[QLatin1String("QT")].split(QLatin1String(" "), QString::SkipEmptyParts);
foreach(QString name, qt) {
qtModules.remove(name.toLatin1());
}
Logger *logger = Logger::instance();
bool changesMade = false;
if (!qtModules.isEmpty()) {
changesMade = true;
QString insertText = QLatin1String("QT += ");
foreach(QByteArray module, qtModules) {
insertText += QString::fromLatin1(module) + QLatin1Char(' ');
}
lines += QString(QLatin1String("#The following line was inserted by qt3to4"));
lines += insertText;
QString logText = QLatin1String("In file ")
+ logger->globalState.value(QLatin1String("currentFileName"))
+ QLatin1String(": Added entry ")
+ insertText;
logger->addEntry(new PlainLogEntry(QLatin1String("Info"), QLatin1String("Porting"), logText));
}
// Add uic3 if we have forms, and change FORMS and INTERFACES to FORMS3
if (!tagMap[QLatin1String("FORMS")].isEmpty() || !tagMap[QLatin1String("INTERFACES")].isEmpty()) {
changesMade = true;
lines += QString(QLatin1String("#The following line was inserted by qt3to4"));
QString insertText = QLatin1String("CONFIG += uic3") + QString::fromLatin1(lineEnding.constData());
lines += insertText;
QString logText = QLatin1String("In file ")
+ logger->globalState.value(QLatin1String("currentFileName"))
+ QLatin1String(": Added entry ")
+ insertText;
logger->addEntry(new PlainLogEntry(QLatin1String("Info"), QLatin1String("Porting"), logText));
const QString formsToForms3(QLatin1String("#The following line was changed from FORMS to FORMS3 by qt3to4"));
const QString interfacesToForms3(QLatin1String("#The following line was changed from INTERFACES to FORMS3 by qt3to4"));
for (int i = 0; i < lines.count(); ++i) {
QString cLine = lines.at(i);
cLine = cLine.trimmed();
if (cLine.startsWith(QLatin1String("FORMS"))) {
lines[i].replace(QLatin1String("FORMS"), QLatin1String("FORMS3"));
lines.insert(i, formsToForms3);
++i;
QString logText = QLatin1String("In file ")
+ logger->globalState.value(QLatin1String("currentFileName"))
+ QLatin1String(": Renamed FORMS to FORMS3");
logger->addEntry(new PlainLogEntry(QLatin1String("Info"), QLatin1String("Porting"), logText));
} else if (cLine.startsWith(QLatin1String("INTERFACES"))) {
lines[i].replace(QLatin1String("INTERFACES"), QLatin1String("FORMS3"));
lines.insert(i, interfacesToForms3);
++i;
QString logText = QLatin1String("In file ")
+ logger->globalState.value(QLatin1String("currentFileName"))
+ QLatin1String(": Renamed INTERFACES to FORMS3");
logger->addEntry(new PlainLogEntry(QLatin1String("Info"), QLatin1String("Porting"), logText));
}
}
}
// Comment out any REQUIRES tag.
if (!tagMap[QLatin1String("REQUIRES")].isEmpty()) {
changesMade = true;
QString insertText(QLatin1String("#The following line was commented out by qt3to4"));
for (int i = 0; i < lines.count(); ++i) {
if (lines.at(i).startsWith(QLatin1String("REQUIRES"))) {
QString lineCopy = lines.at(i);
lineCopy.prepend(QLatin1Char('#'));
lines[i] = lineCopy;
lines.insert(i, insertText);
++i; //skip ahead, we just insertet a line at i.
QString logText = QLatin1String("In file ")
+ logger->globalState.value(QLatin1String("currentFileName"))
+ QLatin1String(": Commented out REQUIRES section");
logger->addEntry(new PlainLogEntry(QLatin1String("Info"), QLatin1String("Porting"), logText));
}
}
}
// Check if any changes has been made.
if (!changesMade) {
Logger::instance()->addEntry(
new PlainLogEntry(QLatin1String("Info"), QLatin1String("Porting"), QLatin1String("No changes made to file ") + fileName));
Logger::instance()->commitSection();
return;
}
// Write lines to array.
QByteArray bob;
QTextStream outProFileStream(&bob);
foreach(QString line, lines)
outProFileStream << line << lineEnding;
outProFileStream.flush();
// Write array to file, commit log if write was successful.
FileWriter::WriteResult result = FileWriter::instance()->writeFileVerbously(fileName, bob);
if (result == FileWriter::WriteSucceeded) {
logger->commitSection();
} else if (result == FileWriter::WriteFailed) {
logger->revertSection();
logger->addEntry(
new PlainLogEntry(QLatin1String("Error"), QLatin1String("Porting"), QLatin1String("Error writing to file ") + fileName));
} else if (result == FileWriter::WriteSkipped) {
logger->revertSection();
logger->addEntry(
new PlainLogEntry(QLatin1String("Error"), QLatin1String("Porting"), QLatin1String("User skipped file ") + fileName));
} else {
// Internal error.
logger->revertSection();
const QString errorString = QLatin1String("Internal error in qt3to4 - FileWriter returned invalid result code while writing to ") + fileName;
logger->addEntry(new PlainLogEntry(QLatin1String("Error"), QLatin1String("Porting"), errorString));
}
}
/*
Enables attribute generation for fileName. The file is looked up using the
provied includeFiles object.
*/
void ProjectPorter::enableAttributes(const IncludeFiles &includeFiles, const QString &fileName)
{
QString resolvedFilePath = includeFiles.resolve(fileName);
if (!QFile::exists(resolvedFilePath))
resolvedFilePath = includeFiles.angleBracketLookup(fileName);
if (!QFile::exists(resolvedFilePath))
return;
TokenContainer tokenContainer = preprocessorCache.sourceTokens(resolvedFilePath);
TokenAttributes *attributes = tokenContainer.tokenAttributes();
attributes->addAttribute("CreateAttributes", "True");
}
QT_END_NAMESPACE
|
librelab/qtmoko-test
|
qtopiacore/qt/tools/porting/src/projectporter.cpp
|
C++
|
gpl-2.0
| 17,084
|
<?php
/**
* EDS API Options
*
* PHP version 5
*
* Copyright (C) EBSCO Industries 2013
*
* 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 Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category VuFind
* @package EBSCO
* @author Michelle Milton <mmilton@epnet.com>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Page
*/
namespace VuFind\Search\EDS;
/**
* EDS API Options
*
* @category VuFind
* @package EBSCO
* @author Michelle Milton <mmilton@epnet.com>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Page
*/
class Options extends \VuFind\Search\Base\Options
{
/**
* Available search mode options
*
* @var array
*/
protected $modeOptions = [];
/**
* Default search mode options
*
* @var string
*/
protected $defaultMode = 'all';
/**
* The set search mode
*
* @var string
*/
protected $searchMode;
/**
* Default expanders to apply
*
* @var array
*/
protected $defaultExpanders = [];
/**
* Available expander options
*
* @var unknown
*/
protected $expanderOptions = [];
/**
* Available limiter options
*
* @var unknown
*/
protected $limiterOptions = [];
/**
* Whether or not to return available facets with the search response
*
* @var unknown
*/
protected $includeFacets = 'y';
/**
* Available Search Options from the API
*
* @var array
*/
protected $apiInfo;
/**
* Limiters to display on the basic search screen
*
* @var array
*/
protected $commonLimiters = [];
/**
* Expanders to display on the basic search screen
*
* @var array
*/
protected $commonExpanders = [];
/**
* Constructor
*
* @param \VuFind\Config\PluginManager $configLoader Configuration loader
* @param array $apiInfo API information
*/
public function __construct(\VuFind\Config\PluginManager $configLoader,
$apiInfo = null
) {
$this->searchIni = $this->facetsIni = 'EDS';
$searchSettings = $configLoader->get($this->searchIni);
parent::__construct($configLoader);
// 2015-06-30 RF - Changed to unlimited
//$this->resultLimit = 100;
$this->viewOptions = [
'list|title' => 'Title View', 'list|brief' => 'Brief View',
'list|detailed' => 'Detailed View'
];
$this->apiInfo = $apiInfo;
$this->setOptionsFromApi($searchSettings);
$this->setOptionsFromConfig($searchSettings);
$facetConf = $configLoader->get($this->facetsIni);
if (isset($facetConf->Advanced_Facet_Settings->translated_facets)
&& count($facetConf->Advanced_Facet_Settings->translated_facets) > 0
) {
$this->setTranslatedFacets(
$facetConf->Advanced_Facet_Settings->translated_facets->toArray()
);
}
}
/**
* Get an array of search mode options
*
* @return array
*/
public function getModeOptions()
{
return $this->modeOptions;
}
/**
* Get the default search mode
*
* @return string
*/
public function getDefaultMode()
{
return $this->defaultMode;
}
/**
* Obtain the set searchmode
*
* @return string the search mode
*/
public function getSearchMode()
{
return $this->searchMode;
}
/**
* Set the search mode
*
* @param string $mode Mode
*
* @return void
*/
public function setSearchMode($mode)
{
$this->searchMode = $mode;
}
/**
* Return the route name for the search results action.
*
* @return string
*/
public function getSearchAction()
{
return 'eds-search';
}
/**
* Return the view associated with this configuration
*
* @return string
*/
public function getView()
{
return $this->defaultView;
}
/**
* Return the view associated with this configuration
*
* @return string
*/
public function getEdsView()
{
$viewArr = explode('|', $this->defaultView);
return (1 < count($viewArr)) ? $viewArr[1] : $this->defaultView;
}
/**
* Return the expander ids that have the default on flag set in admin
*
* @return array
*/
public function getDefaultExpanders()
{
return $this->defaultExpanders;
}
/**
* Return the route name of the action used for performing advanced searches.
* Returns false if the feature is not supported.
*
* @return string|bool
*/
public function getAdvancedSearchAction()
{
return 'eds-advanced';
}
/**
* Set the search options from the Eds API Info methods results
*
* @return void
*/
public function setOptionsFromApi()
{
// Set options from the INFO method first. If settings are set in the config
// file, use them as 'overrides', but only if they are available (ie. are
// returned in the INFO method)
$this->populateViewSettings();
$this->populateSearchCriteria();
}
/**
* Apply user settings. All legal values have already been loaded from the API
* at the time this method is called, so we just need to check if the
* user-supplied values are valid, and if so, filter/reorder accordingly.
*
* @param \Zend\Config\Config $searchSettings Configuration
* @param string $section Configuration section to read
* @param string $property Property of this object to read
* and/or modify.
*
* @return void
*/
protected function filterAndReorderProperty($searchSettings, $section, $property)
{
if (!isset($searchSettings->$section)) {
return;
}
// Use a reference to access $this->$property to avoid the awkward/ambiguous
// expression $this->$property[$key] below.
$propertyRef = & $this->$property;
$newPropertyValues = [];
foreach ($searchSettings->$section as $key => $value) {
if (isset($propertyRef[$key])) {
$newPropertyValues[$key] = $value;
}
}
if (!empty($newPropertyValues)) {
$this->$property = $newPropertyValues;
}
}
/**
* Apply user-requested "common" settings.
*
* @param \Zend\Config\Config $searchSettings Configuration
* @param string $setting Name of common setting
* @param string $list Name of property containing valid
* values
* @param string $target Name of property to populate
*
* @return void
*/
protected function setCommonSettings($searchSettings, $setting, $list, $target)
{
if (isset($searchSettings->General->$setting)) {
$userValues = explode(',', $searchSettings->General->$setting);
if (!empty($userValues) && isset($this->$list) && !empty($this->$list)) {
// Reference to property containing API-provided whitelist of values
$listRef = & $this->$list;
// Reference to property containing final common settings
$targetRef = & $this->$target;
foreach ($userValues as $current) {
// Only add values that are valid according to the API's list
if (isset($listRef[$current])) {
$targetRef[] = $current;
}
}
}
}
}
/**
* Load options from the configuration file. These will override the defaults set
* from the values in the Info method. (If the values set in the config files in
* not a 'valid' EDS API value, it will be ignored.
*
* @param \Zend\Config\Config $searchSettings Configuration
*
* @return void
*/
protected function setOptionsFromConfig($searchSettings)
{
if (isset($searchSettings->General->default_limit)) {
$this->defaultLimit = $searchSettings->General->default_limit;
}
if (isset($searchSettings->General->limit_options)) {
$this->limitOptions
= explode(",", $searchSettings->General->limit_options);
}
// Set up highlighting preference
if (isset($searchSettings->General->highlighting)) {
$this->highlight = $searchSettings->General->highlighting;
}
// Set up facet preferences
if (isset($searchSettings->General->include_facets)) {
$this->includeFacets = $searchSettings->General->include_facets;
}
// Load search preferences:
if (isset($searchSettings->General->retain_filters_by_default)) {
$this->retainFiltersByDefault
= $searchSettings->General->retain_filters_by_default;
}
// Search handler setup. Only valid values set in the config files are used.
$this->filterAndReorderProperty(
$searchSettings, 'Basic_Searches', 'basicHandlers'
);
$this->filterAndReorderProperty(
$searchSettings, 'Advanced_Searches', 'advancedHandlers'
);
// Sort preferences:
$this->filterAndReorderProperty($searchSettings, 'Sorting', 'sortOptions');
if (isset($searchSettings->General->default_sort)
&& isset($this->sortOptions[$searchSettings->General->default_sort])
) {
$this->defaultSort = $searchSettings->General->default_sort;
}
if (isset($searchSettings->General->default_amount)
&& isset($this->amountOptions[$searchSettings->General->default_amount])
) {
$this->defaultAmount = $searchSettings->General->default_amount;
}
if (isset($searchSettings->General->default_mode)
&& isset($this->modeOptions[$searchSettings->General->default_mode])
) {
$this->defaultMode = $searchSettings->General->default_mode;
}
//View preferences
if (isset($searchSettings->General->default_view)) {
$this->defaultView = 'list|' . $searchSettings->General->default_view;
}
// Load list view for result (controls AJAX embedding vs. linking)
if (isset($searchSettings->List->view)) {
$this->listviewOption = $searchSettings->List->view;
}
if (isset($searchSettings->Advanced_Facet_Settings->special_facets)) {
$this->specialAdvancedFacets
= $searchSettings->Advanced_Facet_Settings->special_facets;
}
// Set common limiters and expanders.
// Only the values that are valid for this profile will be used.
$this->setCommonSettings(
$searchSettings, 'common_limiters', 'limiterOptions', 'commonLimiters'
);
$this->setCommonSettings(
$searchSettings, 'common_expanders', 'expanderOptions', 'commonExpanders'
);
}
/**
* Map EBSCO sort labels to standard VuFind text.
*
* @param string $label Label to transform
*
* @return string
*/
protected function mapSortLabel($label)
{
switch ($label) {
case 'Date Newest':
return 'sort_year';
case 'Date Oldest':
return 'sort_year asc';
default:
return 'sort_' . strtolower($label);
}
}
/**
* Populate available search criteria from the EDS API Info method
*
* @return void
*/
protected function populateSearchCriteria()
{
if (isset($this->apiInfo)
&& isset($this->apiInfo['AvailableSearchCriteria'])
) {
// Reference for readability:
$availCriteria = & $this->apiInfo['AvailableSearchCriteria'];
//Sort preferences
$this->sortOptions = [];
if (isset($availCriteria['AvailableSorts'])) {
foreach ($availCriteria['AvailableSorts'] as $sort) {
$this->sortOptions[$sort['Id']]
= $this->mapSortLabel($sort['Label']);
}
}
// By default, use all of the available search fields for both
// advanced and basic. Use the values in the config files to filter.
$this->basicHandlers = ['AllFields' => 'All Fields'];
if (isset($availCriteria['AvailableSearchFields'])) {
foreach ($availCriteria['AvailableSearchFields'] as $searchField) {
$this->basicHandlers[$searchField['FieldCode']]
= $searchField['Label'];
}
}
$this->advancedHandlers = $this->basicHandlers;
// Search Mode preferences
$this->modeOptions = [];
if (isset($availCriteria['AvailableSearchModes'])) {
foreach ($availCriteria['AvailableSearchModes'] as $mode) {
$this->modeOptions[$mode['Mode']] = [
'Label' => $mode['Label'], 'Value' => $mode['Mode']
];
if (isset($mode['DefaultOn'])
&& 'y' == $mode['DefaultOn']
) {
$this->defaultMode = $mode['Mode'];
}
}
}
//expanders
$this->expanderOptions = [];
$this->defaultExpanders = [];
if (isset($availCriteria['AvailableExpanders'])) {
foreach ($availCriteria['AvailableExpanders'] as $expander) {
$this->expanderOptions[$expander['Id']] = [
'Label' => $expander['Label'], 'Value' => $expander['Id']
];
if (isset($expander['DefaultOn'])
&& 'y' == $expander['DefaultOn']
) {
$this->defaultExpanders[] = $expander['Id'];
}
}
}
//Limiters
$this->limiterOptions = [];
if (isset($availCriteria['AvailableLimiters'])) {
foreach ($availCriteria['AvailableLimiters'] as $limiter) {
$val = '';
if ('select' == $limiter['Type']) {
$val = 'y';
}
$this->limiterOptions[$limiter['Id']] = [
'Id' => $limiter['Id'],
'Label' => $limiter['Label'],
'Type' => $limiter['Type'],
'LimiterValues' => isset($limiter['LimiterValues'])
? $this->populateLimiterValues(
$limiter['LimiterValues']
)
: [['Value' => $val]],
'DefaultOn' => isset($limiter['DefaultOn'])
? $limiter['DefaultOn'] : 'n',
];
}
}
}
}
/**
* Populate limiter values forom the EDS API INFO method data
*
* @param array $limiterValues Limiter values from the API
*
* @return array
*/
protected function populateLimiterValues($limiterValues)
{
$availableLimiterValues = [];
if (isset($limiterValues)) {
foreach ($limiterValues as $limiterValue) {
$availableLimiterValues[] = [
'Value' => $limiterValue['Value'],
'LimiterValues' => isset($limiterValue['LimiterValues'])
? $this
->populateLimiterValues($limiterValue['LimiterValues'])
: null
];
}
}
return empty($availableLimiterValues) ? null : $availableLimiterValues;
}
/**
* Returns the available limters
*
* @return array
*/
public function getAvailableLimiters()
{
return $this->limiterOptions;
}
/**
* Returns the available expanders
*
* @return array
*/
public function getAvailableExpanders()
{
return $this->expanderOptions;
}
/**
* Sets the view settings from EDS API info method call data
*
* @return number
*/
protected function populateViewSettings()
{
if (isset($this->apiInfo)
&& isset($this->apiInfo['ViewResultSettings'])
) {
//default result Limit
if (isset($this->apiInfo['ViewResultSettings']['ResultsPerPage'])) {
$this->defaultLimit
= $this->apiInfo['ViewResultSettings']['ResultsPerPage'];
} else {
$this->defaultLimit = 20;
}
//default view (amount)
if (isset($this->apiInfo['ViewResultSettings']['ResultListView'])) {
$this->defaultView = 'list|'
. $this->apiInfo['ViewResultSettings']['ResultListView'];
} else {
$this->defaultView = 'list|brief';
}
}
}
/**
* Get a translation string (if available) or else use a default
*
* @param string $label Translation string to look up
* @param string $default Default to use if no translation found
*
* @return string
*/
protected function getLabelForCheckboxFilter($label, $default)
{
// If translation doesn't change the label, we don't want to
// display the non-human-readable version so we should instead
// return the EDS-provided English default.
return ($label == $this->translate($label))
? $default : $label;
}
/**
* Obtain limiters to display on the basic search screen
*
* @return array
*/
public function getSearchScreenLimiters()
{
$ssLimiterOptions = [];
if (isset($this->commonLimiters)) {
foreach ($this->commonLimiters as $key) {
$limiter = $this->limiterOptions[$key];
$ssLimiterOptions[$key] = [
'selectedvalue' => 'LIMIT|' . $key . ':y',
'description' => $this->getLabelForCheckboxFilter(
'eds_limiter_' . $key, $limiter['Label']
),
'selected' => ('y' == $limiter['DefaultOn']) ? true : false
];
}
}
return $ssLimiterOptions;
}
/**
* Obtain expanders to display on the basic search screen
*
* @return array
*/
public function getSearchScreenExpanders()
{
$ssExpanderOptions = [];
if (isset($this->commonExpanders)) {
foreach ($this->commonExpanders as $key) {
$expander = $this->expanderOptions[$key];
$ssExpanderOptions[$key] = [
'selectedvalue' => 'EXPAND:' . $key,
'description' => $this->getLabelForCheckboxFilter(
'eds_expander_' . $key, $expander['Label']
),
];
}
}
return $ssExpanderOptions;
}
/**
* Get default view setting.
*
* @return int
*/
public function getDefaultView()
{
$viewArr = explode('|', $this->defaultView);
return $viewArr[0];
}
/**
* Get default filters to apply to an empty search.
*
* @return array
*/
public function getDefaultFilters()
{
// Populate defaults if not already set:
if (empty($this->defaultFilters)) {
//expanders
$expanders = $this->getDefaultExpanders();
foreach ($expanders as $expander) {
$this->defaultFilters[] = 'EXPAND:' . $expander;
}
//limiters
$limiters = $this->getAvailableLimiters();
foreach ($limiters as $key => $value) {
if ('select' == $value['Type'] && 'y' == $value['DefaultOn']) {
// only select limiters can be defaulted on limiters can be
// defaulted
$val = $value['LimiterValues'][0]['Value'];
$this->defaultFilters[] = 'LIMIT|' . $key . ':' . $val;
}
}
}
return $this->defaultFilters;
}
}
|
johnjung/vufind
|
module/VuFind/src/VuFind/Search/EDS/Options.php
|
PHP
|
gpl-2.0
| 21,437
|
# Makefile.in generated by automake 1.14 from Makefile.am.
# m4/Makefile. Generated from Makefile.in by configure.
# Copyright (C) 1994-2013 Free Software Foundation, Inc.
# This Makefile.in is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
VPATH = ../../m4
am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)'
am__make_running_with_option = \
case $${target_option-} in \
?) ;; \
*) echo "am__make_running_with_option: internal error: invalid" \
"target option '$${target_option-}' specified" >&2; \
exit 1;; \
esac; \
has_opt=no; \
sane_makeflags=$$MAKEFLAGS; \
if $(am__is_gnu_make); then \
sane_makeflags=$$MFLAGS; \
else \
case $$MAKEFLAGS in \
*\\[\ \ ]*) \
bs=\\; \
sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
| sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \
esac; \
fi; \
skip_next=no; \
strip_trailopt () \
{ \
flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
}; \
for flg in $$sane_makeflags; do \
test $$skip_next = yes && { skip_next=no; continue; }; \
case $$flg in \
*=*|--*) continue;; \
-*I) strip_trailopt 'I'; skip_next=yes;; \
-*I?*) strip_trailopt 'I';; \
-*O) strip_trailopt 'O'; skip_next=yes;; \
-*O?*) strip_trailopt 'O';; \
-*l) strip_trailopt 'l'; skip_next=yes;; \
-*l?*) strip_trailopt 'l';; \
-[dEDm]) skip_next=yes;; \
-[JT]) skip_next=yes;; \
esac; \
case $$flg in \
*$$target_option*) has_opt=yes; break;; \
esac; \
done; \
test $$has_opt = yes
am__make_dryrun = (target_option=n; $(am__make_running_with_option))
am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
pkgdatadir = $(datadir)/vlc
pkgincludedir = $(includedir)/vlc
pkglibdir = $(libdir)/vlc
pkglibexecdir = $(libexecdir)/vlc
am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
install_sh_DATA = $(install_sh) -c -m 644
install_sh_PROGRAM = $(install_sh) -c
install_sh_SCRIPT = $(install_sh) -c
INSTALL_HEADER = $(INSTALL_DATA)
transform = $(program_transform_name)
NORMAL_INSTALL = :
PRE_INSTALL = :
POST_INSTALL = :
NORMAL_UNINSTALL = :
PRE_UNINSTALL = :
POST_UNINSTALL = :
build_triplet = x86_64-unknown-linux-gnu
host_triplet = arm-unknown-linux-androideabi
subdir = m4
DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am
ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
am__aclocal_m4_deps = $(top_srcdir)/m4/dolt.m4 \
$(top_srcdir)/m4/flags.m4 $(top_srcdir)/m4/gettext.m4 \
$(top_srcdir)/m4/iconv.m4 $(top_srcdir)/m4/intlmacosx.m4 \
$(top_srcdir)/m4/lib-ld.m4 $(top_srcdir)/m4/lib-link.m4 \
$(top_srcdir)/m4/lib-prefix.m4 $(top_srcdir)/m4/libtool.m4 \
$(top_srcdir)/m4/ltoptions.m4 $(top_srcdir)/m4/ltsugar.m4 \
$(top_srcdir)/m4/ltversion.m4 $(top_srcdir)/m4/lt~obsolete.m4 \
$(top_srcdir)/m4/nls.m4 $(top_srcdir)/m4/po.m4 \
$(top_srcdir)/m4/progtest.m4 $(top_srcdir)/m4/vlc.m4 \
$(top_srcdir)/m4/with_pkg.m4 $(top_srcdir)/configure.ac
am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
$(ACLOCAL_M4)
mkinstalldirs = $(install_sh) -d
CONFIG_HEADER = $(top_builddir)/config.h
CONFIG_CLEAN_FILES =
CONFIG_CLEAN_VPATH_FILES =
AM_V_P = $(am__v_P_$(V))
am__v_P_ = $(am__v_P_$(AM_DEFAULT_VERBOSITY))
am__v_P_0 = false
am__v_P_1 = :
AM_V_GEN = $(am__v_GEN_$(V))
am__v_GEN_ = $(am__v_GEN_$(AM_DEFAULT_VERBOSITY))
am__v_GEN_0 = @echo " GEN " $@;
am__v_GEN_1 =
AM_V_at = $(am__v_at_$(V))
am__v_at_ = $(am__v_at_$(AM_DEFAULT_VERBOSITY))
am__v_at_0 = @
am__v_at_1 =
SOURCES =
DIST_SOURCES =
am__can_run_installinfo = \
case $$AM_UPDATE_INFO_DIR in \
n|no|NO) false;; \
*) (install-info --version) >/dev/null 2>&1;; \
esac
am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
ACLOCAL = ${SHELL} /home/ddt/Documents/VLC0924/android/vlc/autotools/missing aclocal-1.14
ALIASES = cvlc rvlc
ALSA_CFLAGS =
ALSA_LIBS =
AMTAR = $${TAR-tar}
AM_CPPFLAGS =
AM_DEFAULT_VERBOSITY = 0
AR = /home/ddt/Documents/android-sdk/android-ndk-r9/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86_64/bin//arm-linux-androideabi-ar
ARCH = arm
AS = as
ASM =
AUTOCONF = ${SHELL} /home/ddt/Documents/VLC0924/android/vlc/autotools/missing autoconf
AUTOHEADER = ${SHELL} /home/ddt/Documents/VLC0924/android/vlc/autotools/missing autoheader
AUTOMAKE = ${SHELL} /home/ddt/Documents/VLC0924/android/vlc/autotools/missing automake-1.14
AVCODEC_CFLAGS = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include
AVCODEC_LIBS = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -lavcodec -lopenjpeg -lgsm -lz -lavutil -lm
AVFORMAT_CFLAGS = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include
AVFORMAT_LIBS = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -lavformat -lavcodec -lopenjpeg -lgsm -lz -lavutil -lm
AWK = mawk
BLURAY_CFLAGS =
BLURAY_LIBS =
BONJOUR_CFLAGS =
BONJOUR_LIBS =
CACA_CFLAGS =
CACA_LIBS =
CC = /home/ddt/Documents/android-sdk/android-ndk-r9/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86_64/bin//arm-linux-androideabi-gcc --sysroot=/home/ddt/Documents/android-sdk/android-ndk-r9/platforms/android-9/arch-arm -std=gnu99
CCAS = /home/ddt/Documents/android-sdk/android-ndk-r9/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86_64/bin//arm-linux-androideabi-gcc --sysroot=/home/ddt/Documents/android-sdk/android-ndk-r9/platforms/android-9/arch-arm -std=gnu99
CCASDEPMODE = depmode=gcc3
CCASFLAGS = -g -O2 -fstrict-aliasing -funsafe-math-optimizations -mlong-calls -mfpu=vfpv3-d16 -mcpu=cortex-a8 -mthumb -mfloat-abi=softfp -O2 -I/home/ddt/Documents/android-sdk/android-ndk-r9/sources/cxx-stl/gnu-libstdc++/4.8/include -I/home/ddt/Documents/android-sdk/android-ndk-r9/sources/cxx-stl/gnu-libstdc++/4.8/libs/armeabi-v7a/include
CCDEPMODE = depmode=gcc3
CFLAGS = -g -O2 -fstrict-aliasing -funsafe-math-optimizations -mlong-calls -mfpu=vfpv3-d16 -mcpu=cortex-a8 -mthumb -mfloat-abi=softfp -O2 -I/home/ddt/Documents/android-sdk/android-ndk-r9/sources/cxx-stl/gnu-libstdc++/4.8/include -I/home/ddt/Documents/android-sdk/android-ndk-r9/sources/cxx-stl/gnu-libstdc++/4.8/libs/armeabi-v7a/include -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include -Wall -Wextra -Wsign-compare -Wundef -Wpointer-arith -Wbad-function-cast -Wwrite-strings -Wmissing-prototypes -Wvolatile-register-var -Werror-implicit-function-declaration -pipe -fvisibility=hidden -ffast-math -funroll-loops
CFLAGS_access_avio = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include
CFLAGS_access_gnomevfs =
CFLAGS_access_jack =
CFLAGS_access_mtp =
CFLAGS_access_output_shout =
CFLAGS_access_sftp =
CFLAGS_access_smb =
CFLAGS_avcodec = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include
CFLAGS_bonjour =
CFLAGS_caca =
CFLAGS_cdda =
CFLAGS_dc1394 =
CFLAGS_deinterlace =
CFLAGS_dirac =
CFLAGS_dtstofloat32 =
CFLAGS_dv1394 =
CFLAGS_dvdnav =
CFLAGS_dvdread =
CFLAGS_fdkaac =
CFLAGS_flac = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include
CFLAGS_fluidsynth =
CFLAGS_gles1 =
CFLAGS_gles2 =
CFLAGS_goom =
CFLAGS_i420_yuy2_altivec =
CFLAGS_jack =
CFLAGS_kate =
CFLAGS_libass = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include/fribidi -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include/freetype2
CFLAGS_libbluray =
CFLAGS_libmpeg2 = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include/mpeg2dec
CFLAGS_libvlccore =
CFLAGS_libvnc =
CFLAGS_linsys_sdi =
CFLAGS_lua =
CFLAGS_memcpyaltivec =
CFLAGS_motion =
CFLAGS_mtp =
CFLAGS_mux_ogg =
CFLAGS_ncurses =
CFLAGS_notify =
CFLAGS_ogg = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include
CFLAGS_omxil =
CFLAGS_omxil_vout =
CFLAGS_opencv_example =
CFLAGS_opencv_wrapper =
CFLAGS_opus = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include/opus
CFLAGS_postproc = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include
CFLAGS_qsv =
CFLAGS_rdp =
CFLAGS_rotate =
CFLAGS_samplerate =
CFLAGS_schroedinger =
CFLAGS_sdl_image =
CFLAGS_sid =
CFLAGS_speex = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include
CFLAGS_stream_out_chromaprint =
CFLAGS_svg =
CFLAGS_swscale = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include
CFLAGS_theora = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include
CFLAGS_twolame =
CFLAGS_udev =
CFLAGS_upnp =
CFLAGS_vcdx =
CFLAGS_vorbis =
CFLAGS_vout_sdl =
CFLAGS_x264 =
CFLAGS_x26410b =
CFLAGS_xcb_window =
CFLAGS_xml = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include/libxml2
CFLAGS_zvbi =
CHROMAPRINT_CFLAGS =
CHROMAPRINT_LIBS =
CONTRIB_DIR = /home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi
COPYRIGHT_MESSAGE = Copyright © 1996-2013 the VideoLAN team
COPYRIGHT_YEARS = 1996-2013
CPP = /home/ddt/Documents/android-sdk/android-ndk-r9/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86_64/bin//arm-linux-androideabi-gcc --sysroot=/home/ddt/Documents/android-sdk/android-ndk-r9/platforms/android-9/arch-arm -std=gnu99 -E
CPPFLAGS = -I$(top_srcdir)/include -I$(top_builddir)/include -I/home/ddt/Documents/android-sdk/android-ndk-r9/sources/cxx-stl/gnu-libstdc++/4.8/include -I/home/ddt/Documents/android-sdk/android-ndk-r9/sources/cxx-stl/gnu-libstdc++/4.8/libs/armeabi-v7a/include -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include
CPPFLAGS_a52tofloat32 =
CPPFLAGS_access_gnomevfs =
CPPFLAGS_access_mtp =
CPPFLAGS_access_output_shout =
CPPFLAGS_access_sftp =
CPPFLAGS_access_smb =
CPPFLAGS_bonjour =
CPPFLAGS_caca =
CPPFLAGS_dc1394 =
CPPFLAGS_decklink =
CPPFLAGS_decklinkoutput =
CPPFLAGS_dirac =
CPPFLAGS_directfb =
CPPFLAGS_dtstofloat32 =
CPPFLAGS_dv1394 =
CPPFLAGS_dvdread =
CPPFLAGS_faad =
CPPFLAGS_fdkaac =
CPPFLAGS_flac =
CPPFLAGS_fluidsynth =
CPPFLAGS_freetype = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include/freetype2 -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include/fribidi -DHAVE_FRIBIDI
CPPFLAGS_gles1 =
CPPFLAGS_gles2 =
CPPFLAGS_goom =
CPPFLAGS_kate =
CPPFLAGS_libass =
CPPFLAGS_libbluray =
CPPFLAGS_libmpeg2 =
CPPFLAGS_libvnc =
CPPFLAGS_mpgatofixed32 =
CPPFLAGS_mtp =
CPPFLAGS_mux_ogg =
CPPFLAGS_notify =
CPPFLAGS_ogg =
CPPFLAGS_opencv_example =
CPPFLAGS_opencv_wrapper =
CPPFLAGS_opus =
CPPFLAGS_qsv =
CPPFLAGS_rdp =
CPPFLAGS_samplerate =
CPPFLAGS_schroedinger =
CPPFLAGS_skins2 = -I$(top_srcdir)/modules/access/zip/unzip -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include/freetype2 -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include/fribidi -DHAVE_FRIBIDI
CPPFLAGS_speex =
CPPFLAGS_svg =
CPPFLAGS_theora =
CPPFLAGS_twolame =
CPPFLAGS_udev =
CPPFLAGS_upnp =
CPPFLAGS_vcdx =
CPPFLAGS_vorbis =
CPPFLAGS_x264 =
CPPFLAGS_xml =
CXX = /home/ddt/Documents/android-sdk/android-ndk-r9/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86_64/bin//arm-linux-androideabi-g++ --sysroot=/home/ddt/Documents/android-sdk/android-ndk-r9/platforms/android-9/arch-arm
CXXCPP = /home/ddt/Documents/android-sdk/android-ndk-r9/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86_64/bin//arm-linux-androideabi-g++ --sysroot=/home/ddt/Documents/android-sdk/android-ndk-r9/platforms/android-9/arch-arm -E
CXXDEPMODE = depmode=gcc3
CXXFLAGS = -g -O2 -fstrict-aliasing -funsafe-math-optimizations -mlong-calls -mfpu=vfpv3-d16 -mcpu=cortex-a8 -mthumb -mfloat-abi=softfp -O2 -I/home/ddt/Documents/android-sdk/android-ndk-r9/sources/cxx-stl/gnu-libstdc++/4.8/include -I/home/ddt/Documents/android-sdk/android-ndk-r9/sources/cxx-stl/gnu-libstdc++/4.8/libs/armeabi-v7a/include -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include -Wall -Wextra -Wsign-compare -Wundef -Wpointer-arith -Wvolatile-register-var -fvisibility=hidden -ffast-math -funroll-loops
CXXFLAGS_live555 = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include/liveMedia -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include/groupsock -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include/BasicUsageEnvironment -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include/UsageEnvironment
CXXFLAGS_mkv =
CXXFLAGS_mod =
CXXFLAGS_projectm =
CXXFLAGS_skins2 =
CXXFLAGS_taglib = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include/taglib
CXXFLAGS_upnp =
CXXFLAGS_vsxu =
CYGPATH_W = echo
DBUS_CFLAGS =
DBUS_LIBS =
DC1394_CFLAGS =
DC1394_LIBS =
DCA_CFLAGS =
DCA_LIBS =
DEFS = -DHAVE_CONFIG_H
DEFS_BIGENDIAN =
DEPDIR = .deps
DESKTOP_FILE_VALIDATE = desktop-file-validate
DIRAC_CFLAGS =
DIRAC_LIBS =
DIRECTFB_CFLAGS =
DIRECTFB_CONFIG =
DIRECTFB_LIBS =
DLLTOOL = false
DOLT_BASH = /bin/bash
DSYMUTIL =
DUMPBIN =
DV1394_CFLAGS =
DV1394_LIBS =
DVBPSI_CFLAGS = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include
DVBPSI_LIBS = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -ldvbpsi
DVDNAV_CFLAGS =
DVDNAV_LIBS =
DVDREAD_CFLAGS =
DVDREAD_LIBS =
ECHO_C =
ECHO_N = -n
ECHO_T =
EGL_CFLAGS =
EGL_LIBS =
EGREP = /bin/grep -E
EXEEXT =
FDKAAC_CFLAGS =
FDKAAC_LIBS =
FGREP = /bin/grep -F
FILE_LIBVLCCORE_DLL =
FILE_LIBVLC_DLL =
FLAC_CFLAGS = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include
FLAC_LIBS = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -lFLAC -logg
FLUIDSYNTH_CFLAGS =
FLUIDSYNTH_LIBS =
FREETYPE_CFLAGS = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include/freetype2 -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include
FREETYPE_LIBS = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -lfreetype
FRIBIDI_CFLAGS = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include/fribidi
FRIBIDI_LIBS = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -lfribidi
GCRYPT_CFLAGS = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include
GCRYPT_LIBS = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -lgcrypt -lgpg-error
GETTEXT_MACRO_VERSION = 0.18
GLES1_CFLAGS =
GLES1_LIBS =
GLES2_CFLAGS =
GLES2_LIBS =
GL_CFLAGS =
GL_LIBS =
GMSGFMT = /usr/bin/msgfmt
GMSGFMT_015 = /usr/bin/msgfmt
GNOMEVFS_CFLAGS =
GNOMEVFS_LIBS =
GNUGETOPT_LIBS =
GNUTLS_CFLAGS = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include
GNUTLS_LIBS = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -lgnutls -lnettle -lhogweed -lgmp -lz
GOOM_CFLAGS =
GOOM_LIBS =
GREP = /bin/grep
IDN_CFLAGS =
IDN_LIBS =
INSTALL = /usr/bin/install -c
INSTALL_DATA = ${INSTALL} -m 644
INSTALL_PROGRAM = ${INSTALL}
INSTALL_SCRIPT = ${INSTALL}
INSTALL_STRIP_PROGRAM = $(install_sh) -c -s
INTLLIBS =
INTL_MACOSX_LIBS =
JACK_CFLAGS =
JACK_LIBS =
KAI_LIBS =
KATE_CFLAGS =
KATE_LIBS =
KDE4_CONFIG = kde4-config
KVA_LIBS =
LD = /home/ddt/Documents/android-sdk/android-ndk-r9/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86_64/arm-linux-androideabi/bin/ld
LDFLAGS = -Wl,-Bdynamic,-dynamic-linker=/system/bin/linker -Wl,--no-undefined -Wl,--fix-cortex-a8 -L/home/ddt/Documents/android-sdk/android-ndk-r9/sources/cxx-stl/gnu-libstdc++/4.8/libs/armeabi-v7a -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib
LDFLAGS_access_avio = -Wl,-Bsymbolic
LDFLAGS_avformat = -Wl,-Bsymbolic
LDFLAGS_live555 =
LDFLAGS_plugin =
LDFLAGS_vlc =
LDFLAGS_x264 =
LDFLAGS_x26410b =
LIBASS_CFLAGS = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include/fribidi -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include/freetype2
LIBASS_LIBS = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -lass -lm -lfribidi -lfreetype
LIBCDDB_CFLAGS =
LIBCDDB_LIBS =
LIBDL =
LIBEXT = .so
LIBFREERDP_CFLAGS =
LIBFREERDP_LIBS =
LIBICONV = /home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib/libiconv.a
LIBINTL =
LIBM = -lm
LIBMODPLUG_CFLAGS =
LIBMODPLUG_LIBS =
LIBMPEG2_CFLAGS = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include/mpeg2dec
LIBMPEG2_LIBS = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -lmpeg2
LIBOBJS = ${LIBOBJDIR}atof$U.o ${LIBOBJDIR}getdelim$U.o ${LIBOBJDIR}posix_memalign$U.o ${LIBOBJDIR}strtof$U.o ${LIBOBJDIR}swab$U.o ${LIBOBJDIR}tdestroy$U.o ${LIBOBJDIR}strverscmp$U.o
LIBPTHREAD =
LIBS =
LIBS_a52tofloat32 = -la52 -lm
LIBS_aa =
LIBS_access_avio = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -lavformat -lavcodec -lopenjpeg -lgsm -lz -lavutil -lm -lm
LIBS_access_eyetv =
LIBS_access_ftp =
LIBS_access_gnomevfs =
LIBS_access_http = -lz
LIBS_access_imem = -lm
LIBS_access_jack =
LIBS_access_mtp =
LIBS_access_output_shout =
LIBS_access_output_udp =
LIBS_access_rtmp =
LIBS_access_sftp =
LIBS_access_smb =
LIBS_access_tcp =
LIBS_access_udp =
LIBS_adjust = -lm
LIBS_anaglyph = -lm
LIBS_android_surface = -ldl
LIBS_audiobargraph_a = -lm
LIBS_audiobargraph_v = -lm
LIBS_audioqueue =
LIBS_audioscrobbler =
LIBS_audiounit_ios =
LIBS_auhal =
LIBS_avcodec = -Wl,-Bsymbolic -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -lavcodec -lopenjpeg -lgsm -lz -lavutil -lm -lm
LIBS_ball = -lm
LIBS_bonjour =
LIBS_caca =
LIBS_cdda =
LIBS_chorus_flanger = -lm
LIBS_colorthres = -lm
LIBS_compressor = -lm
LIBS_crystalhd =
LIBS_dc1394 =
LIBS_dirac =
LIBS_directfb =
LIBS_dmo = -lm
LIBS_dtstofloat32 = -lm
LIBS_dv1394 =
LIBS_dvdnav =
LIBS_dvdread =
LIBS_equalizer = -lm
LIBS_extract = -lm
LIBS_faad = -lm
LIBS_fdkaac =
LIBS_fingerprinter =
LIBS_flac = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -lFLAC -logg
LIBS_fluidsynth =
LIBS_freetype = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -lfribidi -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -lfreetype -lm -lm
LIBS_gaussianblur = -lm
LIBS_gles1 =
LIBS_gles2 =
LIBS_glspectrum = -lm
LIBS_gme =
LIBS_gnutls =
LIBS_goom = -lm
LIBS_gradient = -lm
LIBS_grain = -lm
LIBS_growl =
LIBS_headphone_channel_mixer = -lm
LIBS_hotkeys = -lm
LIBS_hqdn3d = -lm
LIBS_i420_rgb = -lm
LIBS_i420_rgb_mmx =
LIBS_jack =
LIBS_kate = -lm
LIBS_libass = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -lass -lm -lfribidi -lfreetype
LIBS_libbluray =
LIBS_libmpeg2 = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -lmpeg2
LIBS_libvlc =
LIBS_libvlccore =
LIBS_libvnc =
LIBS_linsys_sdi =
LIBS_lirc =
LIBS_live555 = -lliveMedia -lgroupsock -lBasicUsageEnvironment -lUsageEnvironment
LIBS_lua = -lm
LIBS_macosx =
LIBS_macosx_dialog_provider =
LIBS_memcpyaltivec =
LIBS_minimal_macosx =
LIBS_mkv = -lmatroska -lebml
LIBS_mod =
LIBS_mono = -lm
LIBS_mosaic = -lm
LIBS_motion =
LIBS_mpc = -lm
LIBS_mpgatofixed32 =
LIBS_mtp =
LIBS_mux_ogg =
LIBS_ncurses = -lm
LIBS_netsync =
LIBS_noise = -lm
LIBS_normvol = -lm
LIBS_notify =
LIBS_ogg = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -logg
LIBS_oldmovie = -lm
LIBS_oldrc = -lm
LIBS_opencv_example =
LIBS_opencv_wrapper =
LIBS_opus = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -logg -lopus -lm
LIBS_param_eq = -lm
LIBS_png = -lpng -lz -lm
LIBS_postproc = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -lpostproc -lavutil -lm -lm
LIBS_projectm =
LIBS_psychedelic = -lm
LIBS_qsv =
LIBS_qt4 = -lm
LIBS_quartztext =
LIBS_quicktime = -lm
LIBS_rdp =
LIBS_remoteosd =
LIBS_ripple = -lm
LIBS_rotate = -lm
LIBS_rtp =
LIBS_samplerate = -lm
LIBS_sap = -lz
LIBS_scene = -lm
LIBS_schroedinger =
LIBS_sdl_image =
LIBS_sid =
LIBS_skins2 = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -lfribidi -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -lfreetype $(top_builddir)/modules/access/libunzip.la -lz -lm
LIBS_spatializer = -lm
LIBS_speex = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -logg -lspeex -lm
LIBS_stream_out_chromaprint =
LIBS_stream_out_raop =
LIBS_stream_out_rtp =
LIBS_stream_out_standard =
LIBS_svg =
LIBS_swscale = -Wl,-Bsymbolic -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -lswscale -lavutil -lm -lm
LIBS_taglib = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -ltag -lz
LIBS_theora = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -ltheoraenc -ltheoradec -logg
LIBS_tremor =
LIBS_ts =
LIBS_twolame = -lm
LIBS_udev =
LIBS_unzip = -lz
LIBS_upnp =
LIBS_vcd =
LIBS_vcdx =
LIBS_vlc =
LIBS_vod_rtsp =
LIBS_vorbis =
LIBS_vout_coregraphicslayer =
LIBS_vout_ios =
LIBS_vout_ios2 =
LIBS_vout_macosx =
LIBS_vout_sdl =
LIBS_vsxu =
LIBS_wave = -lm
LIBS_waveout =
LIBS_win32text =
LIBS_x264 = -lm
LIBS_x26410b = -lm
LIBS_xml = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -lxml2
LIBS_zip = -lz
LIBS_zvbi =
LIBTOOL = $(top_builddir)/doltlibtool
LIBVA_CFLAGS =
LIBVA_LIBS =
LIBVNC_CFLAGS =
LIBVNC_LIBS =
LIBXML2_CFLAGS = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include/libxml2
LIBXML2_LIBS = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -lxml2
LINSYS_SDI_CFLAGS =
LINSYS_SDI_LIBS =
LIPO =
LIVE555_CFLAGS =
LIVE555_LIBS =
LN_S = ln -s
LTCOMPILE = $(top_builddir)/doltcompile $(COMPILE)
LTCXXCOMPILE = $(top_builddir)/doltcompile $(CXXCOMPILE)
LTLIBICONV = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -liconv
LTLIBINTL =
LTLIBOBJS = ${LIBOBJDIR}atof$U.lo ${LIBOBJDIR}getdelim$U.lo ${LIBOBJDIR}posix_memalign$U.lo ${LIBOBJDIR}strtof$U.lo ${LIBOBJDIR}swab$U.lo ${LIBOBJDIR}tdestroy$U.lo ${LIBOBJDIR}strverscmp$U.lo
LTLIBa52tofloat32 = liba52tofloat32_plugin.la
LTLIBaa =
LTLIBaccess_avio = libaccess_avio_plugin.la
LTLIBaccess_eyetv =
LTLIBaccess_gnomevfs =
LTLIBaccess_jack =
LTLIBaccess_mtp =
LTLIBaccess_output_shout =
LTLIBaccess_realrtsp = libaccess_realrtsp_plugin.la
LTLIBaccess_sftp =
LTLIBaccess_smb =
LTLIBandroid_surface = libandroid_surface_plugin.la
LTLIBatmo =
LTLIBaudioqueue =
LTLIBaudiounit_ios =
LTLIBauhal =
LTLIBavcapture =
LTLIBavcodec = libavcodec_plugin.la
LTLIBavformat = libavformat_plugin.la
LTLIBbonjour =
LTLIBcaca =
LTLIBcdda =
LTLIBcrystalhd =
LTLIBdc1394 =
LTLIBdirac =
LTLIBdirect2d =
LTLIBdirect3d =
LTLIBdirectfb =
LTLIBdmo =
LTLIBdtstofloat32 =
LTLIBdv1394 =
LTLIBdvdnav =
LTLIBdvdread =
LTLIBegl =
LTLIBfaad =
LTLIBfb = libfb_plugin.la
LTLIBfdkaac =
LTLIBfingerprinter =
LTLIBflac = libflac_plugin.la
LTLIBfluidsynth =
LTLIBfreetype = libfreetype_plugin.la
LTLIBgl =
LTLIBgles1 =
LTLIBgles2 =
LTLIBglobalhotkeys =
LTLIBglspectrum =
LTLIBglwin32 =
LTLIBglx =
LTLIBgme =
LTLIBgnutls = libgnutls_plugin.la
LTLIBgoom =
LTLIBgrowl =
LTLIBjack =
LTLIBkate =
LTLIBlibass = liblibass_plugin.la
LTLIBlibbluray =
LTLIBlibmpeg2 = liblibmpeg2_plugin.la
LTLIBlibvnc =
LTLIBlinsys_hdsdi =
LTLIBlinsys_sdi =
LTLIBlirc =
LTLIBlive555 = liblive555_plugin.la
LTLIBmacosx =
LTLIBmacosx_dialog_provider =
LTLIBminimal_macosx =
LTLIBmkv = libmkv_plugin.la
LTLIBmod =
LTLIBmpc =
LTLIBmpgatofixed32 =
LTLIBmtp =
LTLIBmux_ogg =
LTLIBncurses =
LTLIBnotify =
LTLIBogg = libogg_plugin.la
LTLIBomxil =
LTLIBomxil_vout =
LTLIBopencv_example =
LTLIBopencv_wrapper =
LTLIBopensles_android = libopensles_android_plugin.la
LTLIBopus = libopus_plugin.la
LTLIBpng = libpng_plugin.la
LTLIBpostproc = libpostproc_plugin.la
LTLIBprojectm =
LTLIBqsv =
LTLIBqt4 =
LTLIBqtcapture =
LTLIBqtsound =
LTLIBquartztext =
LTLIBquicktime =
LTLIBrdp =
LTLIBsamplerate =
LTLIBschroedinger =
LTLIBscreen =
LTLIBsdl_image =
LTLIBshine =
LTLIBsid =
LTLIBskins2 =
LTLIBspeex = libspeex_plugin.la
LTLIBstream_out_chromaprint =
LTLIBsvg =
LTLIBswscale = libswscale_plugin.la
LTLIBtaglib = libtaglib_plugin.la
LTLIBtelx = libtelx_plugin.la
LTLIBtheora = libtheora_plugin.la
LTLIBtremor =
LTLIBtwolame =
LTLIBudev =
LTLIBupnp =
LTLIBvcd =
LTLIBvcdx =
LTLIBvorbis =
LTLIBvout_coregraphicslayer =
LTLIBvout_ios =
LTLIBvout_ios2 =
LTLIBvout_macosx =
LTLIBvout_sdl =
LTLIBvsxu =
LTLIBwaveout =
LTLIBwma_fixed =
LTLIBx264 =
LTLIBx26410b =
LTLIBxcb_glx =
LTLIBxcb_xv =
LTLIBxml = libxml_plugin.la
LTLIBxwd =
LTLIBzvbi =
LUAC =
LUA_CFLAGS =
LUA_LIBS =
MACOSX_DEPLOYMENT_TARGET =
MAINT =
MAKEINFO = ${SHELL} /home/ddt/Documents/VLC0924/android/vlc/autotools/missing makeinfo
MANIFEST_TOOL = :
MINIZIP_CFLAGS =
MINIZIP_LIBS =
MKDIR_P = /bin/mkdir -p
MOC =
MSGFMT = /usr/bin/msgfmt
MSGFMT_015 = /usr/bin/msgfmt
MSGMERGE = /usr/bin/msgmerge
MTP_CFLAGS =
MTP_LIBS =
MUX_OGG_CFLAGS =
MUX_OGG_LIBS =
NCURSES_CFLAGS =
NCURSES_LIBS =
NM = /home/ddt/Documents/android-sdk/android-ndk-r9/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86_64/bin//arm-linux-androideabi-nm
NMEDIT =
NOTIFY_CFLAGS =
NOTIFY_LIBS =
OBJC = arm-linux-androideabi-gcc
OBJCDEPMODE = depmode=gcc3
OBJCFLAGS = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include -fvisibility=hidden -ffast-math -funroll-loops
OBJCFLAGS_growl =
OBJCFLAGS_macosx =
OBJCFLAGS_minimal_macosx =
OBJCOPY =
OBJDUMP = arm-linux-androideabi-objdump
OBJEXT = o
OGG_CFLAGS = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include
OGG_LIBS = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -logg
OPENCV_CFLAGS =
OPENCV_LIBS =
OPUS_CFLAGS = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include/opus
OPUS_LIBS = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -logg -lopus
OSS_LIBS =
OTOOL =
OTOOL64 =
PACKAGE = vlc
PACKAGE_BUGREPORT =
PACKAGE_NAME = vlc
PACKAGE_STRING = vlc 2.2.0-git
PACKAGE_TARNAME = vlc
PACKAGE_URL =
PACKAGE_VERSION = 2.2.0-git
PATH_SEPARATOR = :
PKGDIR = vlc
PKG_CONFIG = /home/ddt/Documents/VLC0924/android/vlc/extras/tools/build/bin/pkg-config
PKG_CONFIG_LIBDIR = /home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib/pkgconfig
PKG_CONFIG_PATH =
POSTPROC_CFLAGS = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include
POSTPROC_LIBS = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -lpostproc -lavutil -lm
POSUB =
PROGRAMFILES =
PROJECTM2_CFLAGS =
PROJECTM2_LIBS =
PROJECTM_CFLAGS =
PROJECTM_LIBS =
PULSE_CFLAGS =
PULSE_LIBS =
QT_CFLAGS =
QT_LIBS =
QUICKSYNC_CFLAGS =
QUICKSYNC_LIBS =
RANLIB = /home/ddt/Documents/android-sdk/android-ndk-r9/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86_64/bin//arm-linux-androideabi-ranlib
RC =
RCC =
SAMPLERATE_CFLAGS =
SAMPLERATE_LIBS =
SCHROEDINGER_CFLAGS =
SCHROEDINGER_LIBS =
SDL_CFLAGS =
SDL_IMAGE_CFLAGS =
SDL_IMAGE_LIBS =
SDL_LIBS =
SED = /bin/sed
SET_MAKE =
SFTP_CFLAGS =
SFTP_LIBS =
SHELL = /bin/bash
SHOUT_CFLAGS =
SHOUT_LIBS =
SID_CFLAGS =
SID_LIBS =
SMBCLIENT_CFLAGS =
SMBCLIENT_LIBS =
SOCKET_LIBS =
SPEEXDSP_CFLAGS = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include
SPEEXDSP_LIBS = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -lspeexdsp
SPEEX_CFLAGS = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include
SPEEX_LIBS = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -logg -lspeex
STRIP = /home/ddt/Documents/android-sdk/android-ndk-r9/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86_64/bin//arm-linux-androideabi-strip
SVG_CFLAGS =
SVG_LIBS =
SWSCALE_CFLAGS = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include
SWSCALE_LIBS = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -lswscale -lavutil -lm
SYS = linux
TAGLIB_CFLAGS = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include/taglib
TAGLIB_LIBS = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -ltag
THEORA_CFLAGS = -I/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/include
THEORA_LIBS = -L/home/ddt/Documents/VLC0924/android/vlc/contrib/arm-linux-androideabi/lib -ltheoraenc -ltheoradec -logg
TIGER_CFLAGS =
TIGER_LIBS =
TWOLAME_CFLAGS =
TWOLAME_LIBS =
U2D =
UDEV_CFLAGS =
UDEV_LIBS =
UIC =
UPNP_CFLAGS =
UPNP_LIBS =
USE_NLS = no
VCDX_CFLAGS =
VCDX_LIBS =
VDPAU_CFLAGS =
VDPAU_LIBS =
VERSION = 2.2.0-git
VERSION_EXTRA = 0
VERSION_MAJOR = 2
VERSION_MESSAGE = 2.2.0-git Weatherwax
VERSION_MINOR = 2
VERSION_REVISION = 0
VORBIS_CFLAGS =
VORBIS_LIBS =
VSXU_CFLAGS =
VSXU_LIBS =
WINDOWS_ARCH =
WINDRES =
WINE_SDK_PATH =
X26410B_CFLAGS =
X26410B_LIBS =
X264_CFLAGS =
X264_LIBS =
XCB_CFLAGS =
XCB_COMPOSITE_CFLAGS =
XCB_COMPOSITE_LIBS =
XCB_KEYSYMS_CFLAGS =
XCB_KEYSYMS_LIBS =
XCB_LIBS =
XCB_RANDR_CFLAGS =
XCB_RANDR_LIBS =
XCB_SHM_CFLAGS =
XCB_SHM_LIBS =
XCB_XV_CFLAGS =
XCB_XV_LIBS =
XEXT_CFLAGS =
XEXT_LIBS =
XGETTEXT = /usr/bin/xgettext
XGETTEXT_015 = /usr/bin/xgettext
XGETTEXT_EXTRA_OPTIONS =
XINERAMA_CFLAGS =
XINERAMA_LIBS =
XMKMF =
XPM_CFLAGS =
XPM_LIBS =
XPROTO_CFLAGS =
XPROTO_LIBS =
X_CFLAGS =
X_EXTRA_LIBS =
X_LIBS =
X_PRE_LIBS =
ZVBI_CFLAGS =
ZVBI_LIBS =
abs_builddir = /home/ddt/Documents/VLC0924/android/vlc/android/m4
abs_srcdir = /home/ddt/Documents/VLC0924/android/vlc/android/../m4
abs_top_builddir = /home/ddt/Documents/VLC0924/android/vlc/android
abs_top_srcdir = /home/ddt/Documents/VLC0924/android/vlc/android/..
ac_ct_AR =
ac_ct_CC =
ac_ct_CXX =
ac_ct_DUMPBIN =
ac_ct_OBJC =
am__include = include
am__leading_dot = .
am__quote =
am__tar = tar --format=ustar -chf - "$$tardir"
am__untar = tar -xf -
bindir = ${exec_prefix}/bin
build = x86_64-unknown-linux-gnu
build_alias = x86_64-unknown-linux
build_cpu = x86_64
build_os = linux-gnu
build_vendor = unknown
builddir = .
datadir = ${datarootdir}
datarootdir = ${prefix}/share
docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
dvidir = ${docdir}
exec_prefix = ${prefix}
have_avfoundation = no
host = arm-unknown-linux-androideabi
host_alias = arm-linux-androideabi
host_cpu = arm
host_os = linux-androideabi
host_vendor = unknown
htmldir = ${docdir}
includedir = ${prefix}/include
infodir = ${datarootdir}/info
install_sh = ${SHELL} /home/ddt/Documents/VLC0924/android/vlc/autotools/install-sh
libdir = ${exec_prefix}/lib
libexecdir = ${exec_prefix}/libexec
localedir = ${datarootdir}/locale
localstatedir = ${prefix}/var
mandir = ${datarootdir}/man
mkdir_p = $(MKDIR_P)
oldincludedir = /usr/include
pdfdir = ${docdir}
prefix = /usr/local
program_transform_name = s,x,x,
psdir = ${docdir}
sbindir = ${exec_prefix}/sbin
sharedstatedir = ${prefix}/com
soliddatadir = /usr/share/kde4/apps//solid/actions
srcdir = ../../m4
sysconfdir = ${prefix}/etc
target_alias =
top_build_prefix = ../
top_builddir = ..
top_srcdir = ../..
vlcdatadir = ${datadir}/${PKGDIR}
vlclibdir = ${libdir}/${PKGDIR}
NULL =
EXTRA_DIST = \
codeset.m4 \
flags.m4 \
gettext.m4 \
glibc21.m4 \
glibc2.m4 \
iconv.m4 \
intdiv0.m4 \
intl.m4 \
intldir.m4 \
intlmacosx.m4 \
intmax.m4 \
inttypes-pri.m4 \
inttypes_h.m4 \
lcmessage.m4 \
lib-ld.m4 \
lib-link.m4 \
lib-prefix.m4 \
lock.m4 \
longlong.m4 \
nls.m4 \
po.m4 \
printf-posix.m4 \
private.m4 \
progtest.m4 \
size_max.m4 \
stdint_h.m4 \
uintmax_t.m4 \
visibility.m4 \
vlc.m4 \
wchar_t.m4 \
wint_t.m4 \
xsize.m4 \
$(NULL)
all: all-am
.SUFFIXES:
$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
@for dep in $?; do \
case '$(am__configure_deps)' in \
*$$dep*) \
( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
&& { if test -f $@; then exit 0; else break; fi; }; \
exit 1;; \
esac; \
done; \
echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign m4/Makefile'; \
$(am__cd) $(top_srcdir) && \
$(AUTOMAKE) --foreign m4/Makefile
.PRECIOUS: Makefile
Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
@case '$?' in \
*config.status*) \
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
*) \
echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
esac;
$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(top_srcdir)/configure: $(am__configure_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(ACLOCAL_M4): $(am__aclocal_m4_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(am__aclocal_m4_deps):
mostlyclean-libtool:
-rm -f *.lo
clean-libtool:
-rm -rf .libs _libs
tags TAGS:
ctags CTAGS:
cscope cscopelist:
distdir: $(DISTFILES)
@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
list='$(DISTFILES)'; \
dist_files=`for file in $$list; do echo $$file; done | \
sed -e "s|^$$srcdirstrip/||;t" \
-e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
case $$dist_files in \
*/*) $(MKDIR_P) `echo "$$dist_files" | \
sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
sort -u` ;; \
esac; \
for file in $$dist_files; do \
if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
if test -d $$d/$$file; then \
dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
if test -d "$(distdir)/$$file"; then \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
else \
test -f "$(distdir)/$$file" \
|| cp -p $$d/$$file "$(distdir)/$$file" \
|| exit 1; \
fi; \
done
check-am: all-am
check: check-am
all-am: Makefile
installdirs:
install: install-am
install-exec: install-exec-am
install-data: install-data-am
uninstall: uninstall-am
install-am: all-am
@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
installcheck: installcheck-am
install-strip:
if test -z '$(STRIP)'; then \
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
install; \
else \
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
"INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
fi
mostlyclean-generic:
clean-generic:
distclean-generic:
-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
maintainer-clean-generic:
@echo "This command is intended for maintainers to use"
@echo "it deletes files that may require special tools to rebuild."
clean: clean-am
clean-am: clean-generic clean-libtool mostlyclean-am
distclean: distclean-am
-rm -f Makefile
distclean-am: clean-am distclean-generic
dvi: dvi-am
dvi-am:
html: html-am
html-am:
info: info-am
info-am:
install-data-am:
install-dvi: install-dvi-am
install-dvi-am:
install-exec-am:
install-html: install-html-am
install-html-am:
install-info: install-info-am
install-info-am:
install-man:
install-pdf: install-pdf-am
install-pdf-am:
install-ps: install-ps-am
install-ps-am:
installcheck-am:
maintainer-clean: maintainer-clean-am
-rm -f Makefile
maintainer-clean-am: distclean-am maintainer-clean-generic
mostlyclean: mostlyclean-am
mostlyclean-am: mostlyclean-generic mostlyclean-libtool
pdf: pdf-am
pdf-am:
ps: ps-am
ps-am:
uninstall-am:
.MAKE: install-am install-strip
.PHONY: all all-am check check-am clean clean-generic clean-libtool \
cscopelist-am ctags-am distclean distclean-generic \
distclean-libtool distdir dvi dvi-am html html-am info info-am \
install install-am install-data install-data-am install-dvi \
install-dvi-am install-exec install-exec-am install-html \
install-html-am install-info install-info-am install-man \
install-pdf install-pdf-am install-ps install-ps-am \
install-strip installcheck installcheck-am installdirs \
maintainer-clean maintainer-clean-generic mostlyclean \
mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
tags-am uninstall uninstall-am
# Tell versions [3.59,3.63) of GNU make to not export all variables.
# Otherwise a system limit (for SysV at least) may be exceeded.
.NOEXPORT:
|
DDTChen/CookieVLC
|
vlc/android/m4/Makefile
|
Makefile
|
gpl-2.0
| 38,430
|
/**
* @name initFile
* @description Initializes the file upload widget.
* @return Void
* @param context - The context to use for initialization.
*/
this.initFile = function(context)
{
// when the file types checkbox is checked, hide the file types field, when it is
// unchecked, show the file types field
$('.form-element-file-types :checkbox', context).bond('click', function() {
if (this.checked) {
$('.form-element-file-types span', context).hide();
} else {
$('.form-element-file-types span', context).show();
}
});
};
/**
* @name initRadio
* @description Initializes the radio list widget.
* @return Void
* @param context - The context to use for initialization.
*/
this.initRadio = function(context, showFirst)
{
_initOptions(context, showFirst);
_initOther(context);
};
/**
* @name initSelect
* @description Initializes the select list widget.
* @return Void
* @param context - The context to use for initialization.
*/
this.initSelect = function(context, showFirst)
{
_initOptions(context, showFirst);
};
/**
* @name initSelectCountries
* @description Initializes the country select list variation of the select widget.
* @return Void
* @param context - The context to use for initialization.
*/
this.initSelectCountry = function(context)
{
this.initSelect(context, false);
var fillData = { fieldData : [] };
var countryList = [
'Afghanistan',
'Albania',
'Algeria',
'Andorra',
'Angola',
'Antigua and Barbuda',
'Argentina',
'Armenia',
'Australia',
'Austria',
'Azerbaijan',
'Bahamas',
'Bahrain',
'Bangladesh',
'Barbados',
'Belarus',
'Belgium',
'Belize',
'Benin',
'Bhutan',
'Bolivia',
'Bosnia and Herzegovina',
'Botswana',
'Brazil',
'Brunei',
'Bulgaria',
'Burkina Faso',
'Burundi',
'Cambodia',
'Cameroon',
'Canada',
'Cape Verde',
'Central African Republic',
'Chad',
'Chile',
'China',
'Colombi',
'Comoros',
'Congo (Brazzaville)',
'Congo',
'Costa Rica',
"Cote d'Ivoire",
'Croatia',
'Cuba',
'Cyprus',
'Czech Republic',
'Denmark',
'Djibouti',
'Dominica',
'Dominican Republic',
'East Timor (Timor Timur)',
'Ecuador',
'Egypt',
'El Salvador',
'Equatorial Guinea',
'Eritrea',
'Estonia',
'Ethiopia',
'Fiji',
'Finland',
'France',
'Gabon',
'Gambia, The',
'Georgia',
'Germany',
'Ghana',
'Greece',
'Grenada',
'Guatemala',
'Guinea',
'Guinea-Bissau',
'Guyana',
'Haiti',
'Honduras',
'Hungary',
'Iceland',
'India',
'Indonesia',
'Iran',
'Iraq',
'Ireland',
'Israel',
'Italy',
'Jamaica',
'Japan',
'Jordan',
'Kazakhstan',
'Kenya',
'Kiribati',
'Korea, North',
'Korea, South',
'Kuwait',
'Kyrgyzstan',
'Laos',
'Latvia',
'Lebanon',
'Lesotho',
'Liberia',
'Libya',
'Liechtenstein',
'Lithuania',
'Luxembourg',
'Macedonia',
'Madagascar',
'Malawi',
'Malaysia',
'Maldives',
'Mali',
'Malta',
'Marshall Islands',
'Mauritania',
'Mauritius',
'Mexico',
'Micronesia',
'Moldova',
'Monaco',
'Mongolia',
'Morocco',
'Mozambique',
'Myanmar',
'Namibia',
'Nauru',
'Nepa',
'Netherlands',
'New Zealand',
'Nicaragua',
'Niger',
'Nigeria',
'Norway',
'Oman',
'Pakistan',
'Palau',
'Panama',
'Papua New Guinea',
'Paraguay',
'Peru',
'Philippines',
'Poland',
'Portugal',
'Qatar',
'Romania',
'Russia',
'Rwanda',
'Saint Kitts and Nevis',
'Saint Lucia',
'Saint Vincent',
'Samoa',
'San Marino',
'Sao Tome and Principe',
'Saudi Arabia',
'Senegal',
'Serbia and Montenegro',
'Seychelles',
'Sierra Leone',
'Singapore',
'Slovakia',
'Slovenia',
'Solomon Islands',
'Somalia',
'South Africa',
'Spain',
'Sri Lanka',
'Sudan',
'Suriname',
'Swaziland',
'Sweden',
'Switzerland',
'Syria',
'Taiwan',
'Tajikistan',
'Tanzania',
'Thailand',
'Togo',
'Tonga',
'Trinidad and Tobago',
'Tunisia',
'Turkey',
'Turkmenistan',
'Tuvalu',
'Uganda',
'Ukraine',
'United Arab Emirates',
'United Kingdom',
'United States',
'Uruguay',
'Uzbekistan',
'Vanuatu',
'Vatican City',
'Venezuela',
'Vietnam',
'Yemen',
'Zambia',
'Zimbabwe'
];
for (var i = 0; i < countryList.length; i++) {
fillData.fieldData[i] = {
label : countryList[i]
};
}
_addFields(context, fillData.fieldData);
_fillWidget(context, fillData);
};
/**
* @name initText
* @description Initializes the text widget.
* @return Void
* @param context - The context to use for initialization.
*/
this.initText = function(context)
{
};
/**
* @name initTextarea
* @description Initializes the textarea widget.
* @return Void
* @param context - The context to use for initialization.
*/
this.initTextarea = function(context)
{
};
|
cuong09m/krwe
|
emailmarketer/admin/addons/surveys/js/__temp.js
|
JavaScript
|
gpl-2.0
| 5,345
|
package httpConReq;
public class HttpConReqClientTest {
public static void main(String[] args) {
HttpConReq httpConReq = new HttpConReq();
//String httpUrl = "http://192.168.12.150:20511/VOD/vod_ISA150/m3u8/qinngiu150,00000000000000000000000000010055/bmw_ts.m3u8";
String httpUrl = "http://10.1.254.224/busTerminalVersion/list";//Àý£ºip:¶Ë¿Ú/·ÃÎʵÄÏîÄ¿
int client_num = 200;//¿Í»§¶ËÊý
String requestMethod = "GET";//http·ÃÎʵĵÄÐÎʽGET/Post
httpConReq.sendHttpReq(httpUrl, client_num, requestMethod);
}
}
|
liumeixia/xiaworkspace
|
javahttpclient/HttpClient/src/httpConReq/HttpConReqClientTest.java
|
Java
|
gpl-2.0
| 536
|
// Copyright (C) 2008-2010 Lothar Braun <lothar@lobraun.de>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#include "size_dumper.h"
#include <module_list.h>
#include <tools/pcap-tools.h>
#include <tools/msg.h>
#include <stdlib.h>
#include <string.h>
#define MAX_FILENAME 65535
struct dumping_module* size_dumper_new()
{
struct dumping_module* ret = (struct dumping_module*)malloc(sizeof(struct dumping_module));
ret->dinit = size_dumper_init;
ret->dfunc = size_dumper_run;
ret->dfinish = size_dumper_finish;
return ret;
}
struct size_dumper_data {
char base_filename[MAX_FILENAME];
char dump_filename[MAX_FILENAME];
size_t number;
size_t file_data_count;
size_t max_file_data_count;
struct dumper_tool* dumper;
};
int createNewFile(struct size_dumper_data* data, int linktype)
{
snprintf(data->dump_filename, MAX_FILENAME, "%s.%lu",
data->base_filename, (unsigned long)data->number);
data->dumper = dumper_tool_open_file(data->dump_filename, linktype);
if (!data->dumper) {
return -1;
}
data->number++;
data->file_data_count = 0;
return 0;
}
int size_dumper_init(struct dumping_module* m, struct config* c)
{
struct size_dumper_data* sdata = (struct size_dumper_data*)malloc(
sizeof(struct size_dumper_data));
const char* tmp = config_get_option(c, SIZE_DUMPER_NAME, "file_prefix");
if (tmp == NULL) {
msg(MSG_ERROR, "%s: no filename in config file", SIZE_DUMPER_NAME);
return -1;
}
strncpy(sdata->base_filename, tmp, MAX_FILENAME);
sdata->number = 0;
sdata->file_data_count = 0;
tmp = config_get_option(c, SIZE_DUMPER_NAME, "size");
if (tmp == NULL) {
msg(MSG_ERROR, "%s: no file size in config file", "size");
return -1;
}
sdata->max_file_data_count = atoi(tmp);
if (-1 == createNewFile(sdata, m->linktype))
goto out;
m->module_data = (void*)sdata;
return 0;
out:
free(sdata);
return -1;
}
int size_dumper_finish(struct dumping_module* m)
{
struct size_dumper_data* d = (struct size_dumper_data*)m->module_data;
dumper_tool_close_file(&d->dumper);
free(d);
m->module_data = NULL;
return 0;
}
int size_dumper_run(struct dumping_module* m, struct packet* p)
{
struct size_dumper_data* d = (struct size_dumper_data*)m->module_data;
dumper_tool_dump(d->dumper, &p->header, p->data);
d->file_data_count += p->header.len;
if (d->file_data_count >= d->max_file_data_count) {
dumper_tool_close_file(&d->dumper);
if (-1 == createNewFile(d, m->linktype)) {
return -1;
}
}
return 0;
}
|
constcast/pcapsplit
|
modules/size_dumper.c
|
C
|
gpl-2.0
| 3,082
|
/*
* arch/arm/mach-kirkwood/common.c
*
* Core functions for Marvell Kirkwood SoCs
*
* 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/serial_8250.h>
#include <linux/mbus.h>
#include <linux/mv643xx_eth.h>
#include <linux/mv643xx_i2c.h>
#include <linux/ata_platform.h>
#include <linux/mtd/nand.h>
#include <linux/spi/orion_spi.h>
#include <net/dsa.h>
#include <asm/page.h>
#include <asm/timex.h>
#include <asm/mach/map.h>
#include <asm/mach/time.h>
#include <mach/kirkwood.h>
#include <mach/bridge-regs.h>
#include <plat/cache-feroceon-l2.h>
#include <plat/ehci-orion.h>
#include <plat/mvsdio.h>
#include <plat/mv_xor.h>
#include <plat/orion_nand.h>
#include <plat/orion_wdt.h>
#include <plat/time.h>
#include "common.h"
/*****************************************************************************
* I/O Address Mapping
****************************************************************************/
static struct map_desc kirkwood_io_desc[] __initdata = {
{
.virtual = KIRKWOOD_PCIE_IO_VIRT_BASE,
.pfn = __phys_to_pfn(KIRKWOOD_PCIE_IO_PHYS_BASE),
.length = KIRKWOOD_PCIE_IO_SIZE,
.type = MT_DEVICE,
}, {
.virtual = KIRKWOOD_PCIE1_IO_VIRT_BASE,
.pfn = __phys_to_pfn(KIRKWOOD_PCIE1_IO_PHYS_BASE),
.length = KIRKWOOD_PCIE1_IO_SIZE,
.type = MT_DEVICE,
}, {
.virtual = KIRKWOOD_REGS_VIRT_BASE,
.pfn = __phys_to_pfn(KIRKWOOD_REGS_PHYS_BASE),
.length = KIRKWOOD_REGS_SIZE,
.type = MT_DEVICE,
},
};
void __init kirkwood_map_io(void)
{
iotable_init(kirkwood_io_desc, ARRAY_SIZE(kirkwood_io_desc));
}
/*
* Default clock control bits. Any bit _not_ set in this variable
* will be cleared from the hardware after platform devices have been
* registered. Some reserved bits must be set to 1.
*/
unsigned int kirkwood_clk_ctrl = CGC_DUNIT | CGC_RESERVED;
/*****************************************************************************
* EHCI
****************************************************************************/
static struct orion_ehci_data kirkwood_ehci_data = {
.dram = &kirkwood_mbus_dram_info,
.phy_version = EHCI_PHY_NA,
};
static u64 ehci_dmamask = 0xffffffffUL;
/*****************************************************************************
* EHCI0
****************************************************************************/
static struct resource kirkwood_ehci_resources[] = {
{
.start = USB_PHYS_BASE,
.end = USB_PHYS_BASE + 0x0fff,
.flags = IORESOURCE_MEM,
}, {
.start = IRQ_KIRKWOOD_USB,
.end = IRQ_KIRKWOOD_USB,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device kirkwood_ehci = {
.name = "orion-ehci",
.id = 0,
.dev = {
.dma_mask = &ehci_dmamask,
.coherent_dma_mask = 0xffffffff,
.platform_data = &kirkwood_ehci_data,
},
.resource = kirkwood_ehci_resources,
.num_resources = ARRAY_SIZE(kirkwood_ehci_resources),
};
void __init kirkwood_ehci_init(void)
{
kirkwood_clk_ctrl |= CGC_USB0;
platform_device_register(&kirkwood_ehci);
}
/*****************************************************************************
* GE00
****************************************************************************/
struct mv643xx_eth_shared_platform_data kirkwood_ge00_shared_data = {
.dram = &kirkwood_mbus_dram_info,
};
static struct resource kirkwood_ge00_shared_resources[] = {
{
.name = "ge00 base",
.start = GE00_PHYS_BASE + 0x2000,
.end = GE00_PHYS_BASE + 0x3fff,
.flags = IORESOURCE_MEM,
}, {
.name = "ge00 err irq",
.start = IRQ_KIRKWOOD_GE00_ERR,
.end = IRQ_KIRKWOOD_GE00_ERR,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device kirkwood_ge00_shared = {
.name = MV643XX_ETH_SHARED_NAME,
.id = 0,
.dev = {
.platform_data = &kirkwood_ge00_shared_data,
},
.num_resources = ARRAY_SIZE(kirkwood_ge00_shared_resources),
.resource = kirkwood_ge00_shared_resources,
};
static struct resource kirkwood_ge00_resources[] = {
{
.name = "ge00 irq",
.start = IRQ_KIRKWOOD_GE00_SUM,
.end = IRQ_KIRKWOOD_GE00_SUM,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device kirkwood_ge00 = {
.name = MV643XX_ETH_NAME,
.id = 0,
.num_resources = 1,
.resource = kirkwood_ge00_resources,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
void __init kirkwood_ge00_init(struct mv643xx_eth_platform_data *eth_data)
{
kirkwood_clk_ctrl |= CGC_GE0;
eth_data->shared = &kirkwood_ge00_shared;
kirkwood_ge00.dev.platform_data = eth_data;
platform_device_register(&kirkwood_ge00_shared);
platform_device_register(&kirkwood_ge00);
}
/*****************************************************************************
* GE01
****************************************************************************/
struct mv643xx_eth_shared_platform_data kirkwood_ge01_shared_data = {
.dram = &kirkwood_mbus_dram_info,
.shared_smi = &kirkwood_ge00_shared,
};
static struct resource kirkwood_ge01_shared_resources[] = {
{
.name = "ge01 base",
.start = GE01_PHYS_BASE + 0x2000,
.end = GE01_PHYS_BASE + 0x3fff,
.flags = IORESOURCE_MEM,
}, {
.name = "ge01 err irq",
.start = IRQ_KIRKWOOD_GE01_ERR,
.end = IRQ_KIRKWOOD_GE01_ERR,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device kirkwood_ge01_shared = {
.name = MV643XX_ETH_SHARED_NAME,
.id = 1,
.dev = {
.platform_data = &kirkwood_ge01_shared_data,
},
.num_resources = ARRAY_SIZE(kirkwood_ge01_shared_resources),
.resource = kirkwood_ge01_shared_resources,
};
static struct resource kirkwood_ge01_resources[] = {
{
.name = "ge01 irq",
.start = IRQ_KIRKWOOD_GE01_SUM,
.end = IRQ_KIRKWOOD_GE01_SUM,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device kirkwood_ge01 = {
.name = MV643XX_ETH_NAME,
.id = 1,
.num_resources = 1,
.resource = kirkwood_ge01_resources,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
void __init kirkwood_ge01_init(struct mv643xx_eth_platform_data *eth_data)
{
kirkwood_clk_ctrl |= CGC_GE1;
eth_data->shared = &kirkwood_ge01_shared;
kirkwood_ge01.dev.platform_data = eth_data;
platform_device_register(&kirkwood_ge01_shared);
platform_device_register(&kirkwood_ge01);
}
/*****************************************************************************
* Ethernet switch
****************************************************************************/
static struct resource kirkwood_switch_resources[] = {
{
.start = 0,
.end = 0,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device kirkwood_switch_device = {
.name = "dsa",
.id = 0,
.num_resources = 0,
.resource = kirkwood_switch_resources,
};
void __init kirkwood_ge00_switch_init(struct dsa_platform_data *d, int irq)
{
int i;
if (irq != NO_IRQ) {
kirkwood_switch_resources[0].start = irq;
kirkwood_switch_resources[0].end = irq;
kirkwood_switch_device.num_resources = 1;
}
d->netdev = &kirkwood_ge00.dev;
for (i = 0; i < d->nr_chips; i++)
d->chip[i].mii_bus = &kirkwood_ge00_shared.dev;
kirkwood_switch_device.dev.platform_data = d;
platform_device_register(&kirkwood_switch_device);
}
/*****************************************************************************
* NAND flash
****************************************************************************/
static struct resource kirkwood_nand_resource = {
.flags = IORESOURCE_MEM,
.start = KIRKWOOD_NAND_MEM_PHYS_BASE,
.end = KIRKWOOD_NAND_MEM_PHYS_BASE +
KIRKWOOD_NAND_MEM_SIZE - 1,
};
static struct orion_nand_data kirkwood_nand_data = {
.cle = 0,
.ale = 1,
.width = 8,
};
static struct platform_device kirkwood_nand_flash = {
.name = "orion_nand",
.id = -1,
.dev = {
.platform_data = &kirkwood_nand_data,
},
.resource = &kirkwood_nand_resource,
.num_resources = 1,
};
void __init kirkwood_nand_init(struct mtd_partition *parts, int nr_parts,
int chip_delay)
{
kirkwood_clk_ctrl |= CGC_RUNIT;
kirkwood_nand_data.parts = parts;
kirkwood_nand_data.nr_parts = nr_parts;
kirkwood_nand_data.chip_delay = chip_delay;
platform_device_register(&kirkwood_nand_flash);
}
void __init kirkwood_nand_init_rnb(struct mtd_partition *parts, int nr_parts,
int (*dev_ready)(struct mtd_info *))
{
kirkwood_clk_ctrl |= CGC_RUNIT;
kirkwood_nand_data.parts = parts;
kirkwood_nand_data.nr_parts = nr_parts;
kirkwood_nand_data.dev_ready = dev_ready;
platform_device_register(&kirkwood_nand_flash);
}
/*****************************************************************************
* SoC RTC
****************************************************************************/
static struct resource kirkwood_rtc_resource = {
.start = RTC_PHYS_BASE,
.end = RTC_PHYS_BASE + SZ_16 - 1,
.flags = IORESOURCE_MEM,
};
static void __init kirkwood_rtc_init(void)
{
platform_device_register_simple("rtc-mv", -1, &kirkwood_rtc_resource, 1);
}
/*****************************************************************************
* SATA
****************************************************************************/
static struct resource kirkwood_sata_resources[] = {
{
.name = "sata base",
.start = SATA_PHYS_BASE,
.end = SATA_PHYS_BASE + 0x5000 - 1,
.flags = IORESOURCE_MEM,
}, {
.name = "sata irq",
.start = IRQ_KIRKWOOD_SATA,
.end = IRQ_KIRKWOOD_SATA,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device kirkwood_sata = {
.name = "sata_mv",
.id = 0,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
.num_resources = ARRAY_SIZE(kirkwood_sata_resources),
.resource = kirkwood_sata_resources,
};
void __init kirkwood_sata_init(struct mv_sata_platform_data *sata_data)
{
kirkwood_clk_ctrl |= CGC_SATA0;
if (sata_data->n_ports > 1)
kirkwood_clk_ctrl |= CGC_SATA1;
sata_data->dram = &kirkwood_mbus_dram_info;
kirkwood_sata.dev.platform_data = sata_data;
platform_device_register(&kirkwood_sata);
}
/*****************************************************************************
* SD/SDIO/MMC
****************************************************************************/
static struct resource mvsdio_resources[] = {
[0] = {
.start = SDIO_PHYS_BASE,
.end = SDIO_PHYS_BASE + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = IRQ_KIRKWOOD_SDIO,
.end = IRQ_KIRKWOOD_SDIO,
.flags = IORESOURCE_IRQ,
},
};
static u64 mvsdio_dmamask = 0xffffffffUL;
static struct platform_device kirkwood_sdio = {
.name = "mvsdio",
.id = -1,
.dev = {
.dma_mask = &mvsdio_dmamask,
.coherent_dma_mask = 0xffffffff,
},
.num_resources = ARRAY_SIZE(mvsdio_resources),
.resource = mvsdio_resources,
};
void __init kirkwood_sdio_init(struct mvsdio_platform_data *mvsdio_data)
{
u32 dev, rev;
kirkwood_pcie_id(&dev, &rev);
if (rev == 0 && dev != MV88F6282_DEV_ID) /* catch all Kirkwood Z0's */
mvsdio_data->clock = 100000000;
else
mvsdio_data->clock = 200000000;
mvsdio_data->dram = &kirkwood_mbus_dram_info;
kirkwood_clk_ctrl |= CGC_SDIO;
kirkwood_sdio.dev.platform_data = mvsdio_data;
platform_device_register(&kirkwood_sdio);
}
/*****************************************************************************
* SPI
****************************************************************************/
static struct orion_spi_info kirkwood_spi_plat_data = {
};
static struct resource kirkwood_spi_resources[] = {
{
.start = SPI_PHYS_BASE,
.end = SPI_PHYS_BASE + SZ_512 - 1,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device kirkwood_spi = {
.name = "orion_spi",
.id = 0,
.resource = kirkwood_spi_resources,
.dev = {
.platform_data = &kirkwood_spi_plat_data,
},
.num_resources = ARRAY_SIZE(kirkwood_spi_resources),
};
void __init kirkwood_spi_init()
{
kirkwood_clk_ctrl |= CGC_RUNIT;
platform_device_register(&kirkwood_spi);
}
/*****************************************************************************
* I2C
****************************************************************************/
static struct mv64xxx_i2c_pdata kirkwood_i2c_pdata = {
.freq_m = 8, /* assumes 166 MHz TCLK */
.freq_n = 3,
.timeout = 1000, /* Default timeout of 1 second */
};
static struct resource kirkwood_i2c_resources[] = {
{
.start = I2C_PHYS_BASE,
.end = I2C_PHYS_BASE + 0x1f,
.flags = IORESOURCE_MEM,
}, {
.start = IRQ_KIRKWOOD_TWSI,
.end = IRQ_KIRKWOOD_TWSI,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device kirkwood_i2c = {
.name = MV64XXX_I2C_CTLR_NAME,
.id = 0,
.num_resources = ARRAY_SIZE(kirkwood_i2c_resources),
.resource = kirkwood_i2c_resources,
.dev = {
.platform_data = &kirkwood_i2c_pdata,
},
};
void __init kirkwood_i2c_init(void)
{
platform_device_register(&kirkwood_i2c);
}
/*****************************************************************************
* UART0
****************************************************************************/
static struct plat_serial8250_port kirkwood_uart0_data[] = {
{
.mapbase = UART0_PHYS_BASE,
.membase = (char *)UART0_VIRT_BASE,
.irq = IRQ_KIRKWOOD_UART_0,
.flags = UPF_SKIP_TEST | UPF_BOOT_AUTOCONF,
.iotype = UPIO_MEM,
.regshift = 2,
.uartclk = 0,
}, {
},
};
static struct resource kirkwood_uart0_resources[] = {
{
.start = UART0_PHYS_BASE,
.end = UART0_PHYS_BASE + 0xff,
.flags = IORESOURCE_MEM,
}, {
.start = IRQ_KIRKWOOD_UART_0,
.end = IRQ_KIRKWOOD_UART_0,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device kirkwood_uart0 = {
.name = "serial8250",
.id = 0,
.dev = {
.platform_data = kirkwood_uart0_data,
},
.resource = kirkwood_uart0_resources,
.num_resources = ARRAY_SIZE(kirkwood_uart0_resources),
};
void __init kirkwood_uart0_init(void)
{
platform_device_register(&kirkwood_uart0);
}
/*****************************************************************************
* UART1
****************************************************************************/
static struct plat_serial8250_port kirkwood_uart1_data[] = {
{
.mapbase = UART1_PHYS_BASE,
.membase = (char *)UART1_VIRT_BASE,
.irq = IRQ_KIRKWOOD_UART_1,
.flags = UPF_SKIP_TEST | UPF_BOOT_AUTOCONF,
.iotype = UPIO_MEM,
.regshift = 2,
.uartclk = 0,
}, {
},
};
static struct resource kirkwood_uart1_resources[] = {
{
.start = UART1_PHYS_BASE,
.end = UART1_PHYS_BASE + 0xff,
.flags = IORESOURCE_MEM,
}, {
.start = IRQ_KIRKWOOD_UART_1,
.end = IRQ_KIRKWOOD_UART_1,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device kirkwood_uart1 = {
.name = "serial8250",
.id = 1,
.dev = {
.platform_data = kirkwood_uart1_data,
},
.resource = kirkwood_uart1_resources,
.num_resources = ARRAY_SIZE(kirkwood_uart1_resources),
};
void __init kirkwood_uart1_init(void)
{
platform_device_register(&kirkwood_uart1);
}
/*****************************************************************************
* Cryptographic Engines and Security Accelerator (CESA)
****************************************************************************/
static struct resource kirkwood_crypto_res[] = {
{
.name = "regs",
.start = CRYPTO_PHYS_BASE,
.end = CRYPTO_PHYS_BASE + 0xffff,
.flags = IORESOURCE_MEM,
}, {
.name = "sram",
.start = KIRKWOOD_SRAM_PHYS_BASE,
.end = KIRKWOOD_SRAM_PHYS_BASE + KIRKWOOD_SRAM_SIZE - 1,
.flags = IORESOURCE_MEM,
}, {
.name = "crypto interrupt",
.start = IRQ_KIRKWOOD_CRYPTO,
.end = IRQ_KIRKWOOD_CRYPTO,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device kirkwood_crypto_device = {
.name = "mv_crypto",
.id = -1,
.num_resources = ARRAY_SIZE(kirkwood_crypto_res),
.resource = kirkwood_crypto_res,
};
void __init kirkwood_crypto_init(void)
{
kirkwood_clk_ctrl |= CGC_CRYPTO;
platform_device_register(&kirkwood_crypto_device);
}
/*****************************************************************************
* XOR
****************************************************************************/
static struct mv_xor_platform_shared_data kirkwood_xor_shared_data = {
.dram = &kirkwood_mbus_dram_info,
};
static u64 kirkwood_xor_dmamask = DMA_BIT_MASK(32);
/*****************************************************************************
* XOR0
****************************************************************************/
static struct resource kirkwood_xor0_shared_resources[] = {
{
.name = "xor 0 low",
.start = XOR0_PHYS_BASE,
.end = XOR0_PHYS_BASE + 0xff,
.flags = IORESOURCE_MEM,
}, {
.name = "xor 0 high",
.start = XOR0_HIGH_PHYS_BASE,
.end = XOR0_HIGH_PHYS_BASE + 0xff,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device kirkwood_xor0_shared = {
.name = MV_XOR_SHARED_NAME,
.id = 0,
.dev = {
.platform_data = &kirkwood_xor_shared_data,
},
.num_resources = ARRAY_SIZE(kirkwood_xor0_shared_resources),
.resource = kirkwood_xor0_shared_resources,
};
static struct resource kirkwood_xor00_resources[] = {
[0] = {
.start = IRQ_KIRKWOOD_XOR_00,
.end = IRQ_KIRKWOOD_XOR_00,
.flags = IORESOURCE_IRQ,
},
};
static struct mv_xor_platform_data kirkwood_xor00_data = {
.shared = &kirkwood_xor0_shared,
.hw_id = 0,
.pool_size = PAGE_SIZE,
};
static struct platform_device kirkwood_xor00_channel = {
.name = MV_XOR_NAME,
.id = 0,
.num_resources = ARRAY_SIZE(kirkwood_xor00_resources),
.resource = kirkwood_xor00_resources,
.dev = {
.dma_mask = &kirkwood_xor_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(64),
.platform_data = (void *)&kirkwood_xor00_data,
},
};
static struct resource kirkwood_xor01_resources[] = {
[0] = {
.start = IRQ_KIRKWOOD_XOR_01,
.end = IRQ_KIRKWOOD_XOR_01,
.flags = IORESOURCE_IRQ,
},
};
static struct mv_xor_platform_data kirkwood_xor01_data = {
.shared = &kirkwood_xor0_shared,
.hw_id = 1,
.pool_size = PAGE_SIZE,
};
static struct platform_device kirkwood_xor01_channel = {
.name = MV_XOR_NAME,
.id = 1,
.num_resources = ARRAY_SIZE(kirkwood_xor01_resources),
.resource = kirkwood_xor01_resources,
.dev = {
.dma_mask = &kirkwood_xor_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(64),
.platform_data = (void *)&kirkwood_xor01_data,
},
};
static void __init kirkwood_xor0_init(void)
{
kirkwood_clk_ctrl |= CGC_XOR0;
platform_device_register(&kirkwood_xor0_shared);
/*
* two engines can't do memset simultaneously, this limitation
* satisfied by removing memset support from one of the engines.
*/
dma_cap_set(DMA_MEMCPY, kirkwood_xor00_data.cap_mask);
dma_cap_set(DMA_XOR, kirkwood_xor00_data.cap_mask);
platform_device_register(&kirkwood_xor00_channel);
dma_cap_set(DMA_MEMCPY, kirkwood_xor01_data.cap_mask);
dma_cap_set(DMA_MEMSET, kirkwood_xor01_data.cap_mask);
dma_cap_set(DMA_XOR, kirkwood_xor01_data.cap_mask);
platform_device_register(&kirkwood_xor01_channel);
}
/*****************************************************************************
* XOR1
****************************************************************************/
static struct resource kirkwood_xor1_shared_resources[] = {
{
.name = "xor 1 low",
.start = XOR1_PHYS_BASE,
.end = XOR1_PHYS_BASE + 0xff,
.flags = IORESOURCE_MEM,
}, {
.name = "xor 1 high",
.start = XOR1_HIGH_PHYS_BASE,
.end = XOR1_HIGH_PHYS_BASE + 0xff,
.flags = IORESOURCE_MEM,
},
};
static struct platform_device kirkwood_xor1_shared = {
.name = MV_XOR_SHARED_NAME,
.id = 1,
.dev = {
.platform_data = &kirkwood_xor_shared_data,
},
.num_resources = ARRAY_SIZE(kirkwood_xor1_shared_resources),
.resource = kirkwood_xor1_shared_resources,
};
static struct resource kirkwood_xor10_resources[] = {
[0] = {
.start = IRQ_KIRKWOOD_XOR_10,
.end = IRQ_KIRKWOOD_XOR_10,
.flags = IORESOURCE_IRQ,
},
};
static struct mv_xor_platform_data kirkwood_xor10_data = {
.shared = &kirkwood_xor1_shared,
.hw_id = 0,
.pool_size = PAGE_SIZE,
};
static struct platform_device kirkwood_xor10_channel = {
.name = MV_XOR_NAME,
.id = 2,
.num_resources = ARRAY_SIZE(kirkwood_xor10_resources),
.resource = kirkwood_xor10_resources,
.dev = {
.dma_mask = &kirkwood_xor_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(64),
.platform_data = (void *)&kirkwood_xor10_data,
},
};
static struct resource kirkwood_xor11_resources[] = {
[0] = {
.start = IRQ_KIRKWOOD_XOR_11,
.end = IRQ_KIRKWOOD_XOR_11,
.flags = IORESOURCE_IRQ,
},
};
static struct mv_xor_platform_data kirkwood_xor11_data = {
.shared = &kirkwood_xor1_shared,
.hw_id = 1,
.pool_size = PAGE_SIZE,
};
static struct platform_device kirkwood_xor11_channel = {
.name = MV_XOR_NAME,
.id = 3,
.num_resources = ARRAY_SIZE(kirkwood_xor11_resources),
.resource = kirkwood_xor11_resources,
.dev = {
.dma_mask = &kirkwood_xor_dmamask,
.coherent_dma_mask = DMA_BIT_MASK(64),
.platform_data = (void *)&kirkwood_xor11_data,
},
};
static void __init kirkwood_xor1_init(void)
{
kirkwood_clk_ctrl |= CGC_XOR1;
platform_device_register(&kirkwood_xor1_shared);
/*
* two engines can't do memset simultaneously, this limitation
* satisfied by removing memset support from one of the engines.
*/
dma_cap_set(DMA_MEMCPY, kirkwood_xor10_data.cap_mask);
dma_cap_set(DMA_XOR, kirkwood_xor10_data.cap_mask);
platform_device_register(&kirkwood_xor10_channel);
dma_cap_set(DMA_MEMCPY, kirkwood_xor11_data.cap_mask);
dma_cap_set(DMA_MEMSET, kirkwood_xor11_data.cap_mask);
dma_cap_set(DMA_XOR, kirkwood_xor11_data.cap_mask);
platform_device_register(&kirkwood_xor11_channel);
}
/*****************************************************************************
* Watchdog
****************************************************************************/
static struct orion_wdt_platform_data kirkwood_wdt_data = {
.tclk = 0,
};
static struct platform_device kirkwood_wdt_device = {
.name = "orion_wdt",
.id = -1,
.dev = {
.platform_data = &kirkwood_wdt_data,
},
.num_resources = 0,
};
static void __init kirkwood_wdt_init(void)
{
kirkwood_wdt_data.tclk = kirkwood_tclk;
platform_device_register(&kirkwood_wdt_device);
}
/*****************************************************************************
* Time handling
****************************************************************************/
int kirkwood_tclk;
int __init kirkwood_find_tclk(void)
{
u32 dev, rev;
kirkwood_pcie_id(&dev, &rev);
if ((dev == MV88F6281_DEV_ID && (rev == MV88F6281_REV_A0 ||
rev == MV88F6281_REV_A1)) ||
(dev == MV88F6282_DEV_ID))
return 200000000;
return 166666667;
}
static void __init kirkwood_timer_init(void)
{
kirkwood_tclk = kirkwood_find_tclk();
orion_time_init(IRQ_KIRKWOOD_BRIDGE, kirkwood_tclk);
}
struct sys_timer kirkwood_timer = {
.init = kirkwood_timer_init,
};
/*****************************************************************************
* General
****************************************************************************/
/*
* Identify device ID and revision.
*/
static char * __init kirkwood_id(void)
{
u32 dev, rev;
kirkwood_pcie_id(&dev, &rev);
if (dev == MV88F6281_DEV_ID) {
if (rev == MV88F6281_REV_Z0)
return "MV88F6281-Z0";
else if (rev == MV88F6281_REV_A0)
return "MV88F6281-A0";
else if (rev == MV88F6281_REV_A1)
return "MV88F6281-A1";
else
return "MV88F6281-Rev-Unsupported";
} else if (dev == MV88F6192_DEV_ID) {
if (rev == MV88F6192_REV_Z0)
return "MV88F6192-Z0";
else if (rev == MV88F6192_REV_A0)
return "MV88F6192-A0";
else if (rev == MV88F6192_REV_A1)
return "MV88F6192-A1";
else
return "MV88F6192-Rev-Unsupported";
} else if (dev == MV88F6180_DEV_ID) {
if (rev == MV88F6180_REV_A0)
return "MV88F6180-Rev-A0";
else if (rev == MV88F6180_REV_A1)
return "MV88F6180-Rev-A1";
else
return "MV88F6180-Rev-Unsupported";
} else if (dev == MV88F6282_DEV_ID) {
if (rev == MV88F6282_REV_A0)
return "MV88F6282-Rev-A0";
else
return "MV88F6282-Rev-Unsupported";
} else {
return "Device-Unknown";
}
}
static void __init kirkwood_l2_init(void)
{
#ifdef CONFIG_CACHE_FEROCEON_L2_WRITETHROUGH
writel(readl(L2_CONFIG_REG) | L2_WRITETHROUGH, L2_CONFIG_REG);
feroceon_l2_init(1);
#else
writel(readl(L2_CONFIG_REG) & ~L2_WRITETHROUGH, L2_CONFIG_REG);
feroceon_l2_init(0);
#endif
}
void __init kirkwood_init(void)
{
printk(KERN_INFO "Kirkwood: %s, TCLK=%d.\n",
kirkwood_id(), kirkwood_tclk);
kirkwood_ge00_shared_data.t_clk = kirkwood_tclk;
kirkwood_ge01_shared_data.t_clk = kirkwood_tclk;
kirkwood_spi_plat_data.tclk = kirkwood_tclk;
kirkwood_uart0_data[0].uartclk = kirkwood_tclk;
kirkwood_uart1_data[0].uartclk = kirkwood_tclk;
/*
* Disable propagation of mbus errors to the CPU local bus,
* as this causes mbus errors (which can occur for example
* for PCI aborts) to throw CPU aborts, which we're not set
* up to deal with.
*/
writel(readl(CPU_CONFIG) & ~CPU_CONFIG_ERROR_PROP, CPU_CONFIG);
kirkwood_setup_cpu_mbus();
#ifdef CONFIG_CACHE_FEROCEON_L2
kirkwood_l2_init();
#endif
/* internal devices that every board has */
kirkwood_rtc_init();
kirkwood_wdt_init();
kirkwood_xor0_init();
kirkwood_xor1_init();
kirkwood_crypto_init();
}
static int __init kirkwood_clock_gate(void)
{
unsigned int curr = readl(CLOCK_GATING_CTRL);
u32 dev, rev;
kirkwood_pcie_id(&dev, &rev);
printk(KERN_DEBUG "Gating clock of unused units\n");
printk(KERN_DEBUG "before: 0x%08x\n", curr);
/* Make sure those units are accessible */
writel(curr | CGC_SATA0 | CGC_SATA1 | CGC_PEX0 | CGC_PEX1, CLOCK_GATING_CTRL);
/* For SATA: first shutdown the phy */
if (!(kirkwood_clk_ctrl & CGC_SATA0)) {
/* Disable PLL and IVREF */
writel(readl(SATA0_PHY_MODE_2) & ~0xf, SATA0_PHY_MODE_2);
/* Disable PHY */
writel(readl(SATA0_IF_CTRL) | 0x200, SATA0_IF_CTRL);
}
if (!(kirkwood_clk_ctrl & CGC_SATA1)) {
/* Disable PLL and IVREF */
writel(readl(SATA1_PHY_MODE_2) & ~0xf, SATA1_PHY_MODE_2);
/* Disable PHY */
writel(readl(SATA1_IF_CTRL) | 0x200, SATA1_IF_CTRL);
}
/* For PCIe: first shutdown the phy */
if (!(kirkwood_clk_ctrl & CGC_PEX0)) {
writel(readl(PCIE_LINK_CTRL) | 0x10, PCIE_LINK_CTRL);
while (1)
if (readl(PCIE_STATUS) & 0x1)
break;
writel(readl(PCIE_LINK_CTRL) & ~0x10, PCIE_LINK_CTRL);
}
/* For PCIe 1: first shutdown the phy */
if (dev == MV88F6282_DEV_ID) {
if (!(kirkwood_clk_ctrl & CGC_PEX1)) {
writel(readl(PCIE1_LINK_CTRL) | 0x10, PCIE1_LINK_CTRL);
while (1)
if (readl(PCIE1_STATUS) & 0x1)
break;
writel(readl(PCIE1_LINK_CTRL) & ~0x10, PCIE1_LINK_CTRL);
}
} else /* keep this bit set for devices that don't have PCIe1 */
kirkwood_clk_ctrl |= CGC_PEX1;
/* Now gate clock the required units */
writel(kirkwood_clk_ctrl, CLOCK_GATING_CTRL);
printk(KERN_DEBUG " after: 0x%08x\n", readl(CLOCK_GATING_CTRL));
return 0;
}
late_initcall(kirkwood_clock_gate);
|
ecbtnrt/my-kernel
|
arch/arm/mach-kirkwood/common.c
|
C
|
gpl-2.0
| 26,738
|
/*******************************************************************************
Intel PRO/1000 Linux driver
Copyright(c) 1999 - 2013 Intel Corporation.
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Contact Information:
Linux NICS <linux.nics@intel.com>
e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
/* 82571EB Gigabit Ethernet Controller
* 82571EB Gigabit Ethernet Controller (Copper)
* 82571EB Gigabit Ethernet Controller (Fiber)
* 82571EB Dual Port Gigabit Mezzanine Adapter
* 82571EB Quad Port Gigabit Mezzanine Adapter
* 82571PT Gigabit PT Quad Port Server ExpressModule
* 82572EI Gigabit Ethernet Controller (Copper)
* 82572EI Gigabit Ethernet Controller (Fiber)
* 82572EI Gigabit Ethernet Controller
* 82573V Gigabit Ethernet Controller (Copper)
* 82573E Gigabit Ethernet Controller (Copper)
* 82573L Gigabit Ethernet Controller
* 82574L Gigabit Network Connection
* 82583V Gigabit Network Connection
*/
#include "e1000.h"
static s32 e1000_get_phy_id_82571(struct e1000_hw *hw);
static s32 e1000_setup_copper_link_82571(struct e1000_hw *hw);
static s32 e1000_setup_fiber_serdes_link_82571(struct e1000_hw *hw);
static s32 e1000_check_for_serdes_link_82571(struct e1000_hw *hw);
static s32 e1000_write_nvm_eewr_82571(struct e1000_hw *hw, u16 offset,
u16 words, u16 *data);
static s32 e1000_fix_nvm_checksum_82571(struct e1000_hw *hw);
static void e1000_initialize_hw_bits_82571(struct e1000_hw *hw);
static void e1000_clear_hw_cntrs_82571(struct e1000_hw *hw);
static bool e1000_check_mng_mode_82574(struct e1000_hw *hw);
static s32 e1000_led_on_82574(struct e1000_hw *hw);
static void e1000_put_hw_semaphore_82571(struct e1000_hw *hw);
static void e1000_power_down_phy_copper_82571(struct e1000_hw *hw);
static void e1000_put_hw_semaphore_82573(struct e1000_hw *hw);
static s32 e1000_get_hw_semaphore_82574(struct e1000_hw *hw);
static void e1000_put_hw_semaphore_82574(struct e1000_hw *hw);
static s32 e1000_set_d0_lplu_state_82574(struct e1000_hw *hw, bool active);
static s32 e1000_set_d3_lplu_state_82574(struct e1000_hw *hw, bool active);
/**
* e1000_init_phy_params_82571 - Init PHY func ptrs.
* @hw: pointer to the HW structure
**/
static s32 e1000_init_phy_params_82571(struct e1000_hw *hw)
{
struct e1000_phy_info *phy = &hw->phy;
s32 ret_val;
if (hw->phy.media_type != e1000_media_type_copper) {
phy->type = e1000_phy_none;
return 0;
}
phy->addr = 1;
phy->autoneg_mask = AUTONEG_ADVERTISE_SPEED_DEFAULT;
phy->reset_delay_us = 100;
phy->ops.power_up = e1000_power_up_phy_copper;
phy->ops.power_down = e1000_power_down_phy_copper_82571;
switch (hw->mac.type) {
case e1000_82571:
case e1000_82572:
phy->type = e1000_phy_igp_2;
break;
case e1000_82573:
phy->type = e1000_phy_m88;
break;
case e1000_82574:
case e1000_82583:
phy->type = e1000_phy_bm;
phy->ops.acquire = e1000_get_hw_semaphore_82574;
phy->ops.release = e1000_put_hw_semaphore_82574;
phy->ops.set_d0_lplu_state = e1000_set_d0_lplu_state_82574;
phy->ops.set_d3_lplu_state = e1000_set_d3_lplu_state_82574;
break;
default:
return -E1000_ERR_PHY;
break;
}
/* This can only be done after all function pointers are setup. */
ret_val = e1000_get_phy_id_82571(hw);
if (ret_val) {
e_dbg("Error getting PHY ID\n");
return ret_val;
}
/* Verify phy id */
switch (hw->mac.type) {
case e1000_82571:
case e1000_82572:
if (phy->id != IGP01E1000_I_PHY_ID)
ret_val = -E1000_ERR_PHY;
break;
case e1000_82573:
if (phy->id != M88E1111_I_PHY_ID)
ret_val = -E1000_ERR_PHY;
break;
case e1000_82574:
case e1000_82583:
if (phy->id != BME1000_E_PHY_ID_R2)
ret_val = -E1000_ERR_PHY;
break;
default:
ret_val = -E1000_ERR_PHY;
break;
}
if (ret_val)
e_dbg("PHY ID unknown: type = 0x%08x\n", phy->id);
return ret_val;
}
/**
* e1000_init_nvm_params_82571 - Init NVM func ptrs.
* @hw: pointer to the HW structure
**/
static s32 e1000_init_nvm_params_82571(struct e1000_hw *hw)
{
struct e1000_nvm_info *nvm = &hw->nvm;
u32 eecd = er32(EECD);
u16 size;
nvm->opcode_bits = 8;
nvm->delay_usec = 1;
switch (nvm->override) {
case e1000_nvm_override_spi_large:
nvm->page_size = 32;
nvm->address_bits = 16;
break;
case e1000_nvm_override_spi_small:
nvm->page_size = 8;
nvm->address_bits = 8;
break;
default:
nvm->page_size = eecd & E1000_EECD_ADDR_BITS ? 32 : 8;
nvm->address_bits = eecd & E1000_EECD_ADDR_BITS ? 16 : 8;
break;
}
switch (hw->mac.type) {
case e1000_82573:
case e1000_82574:
case e1000_82583:
if (((eecd >> 15) & 0x3) == 0x3) {
nvm->type = e1000_nvm_flash_hw;
nvm->word_size = 2048;
/* Autonomous Flash update bit must be cleared due
* to Flash update issue.
*/
eecd &= ~E1000_EECD_AUPDEN;
ew32(EECD, eecd);
break;
}
/* Fall Through */
default:
nvm->type = e1000_nvm_eeprom_spi;
size = (u16)((eecd & E1000_EECD_SIZE_EX_MASK) >>
E1000_EECD_SIZE_EX_SHIFT);
/* Added to a constant, "size" becomes the left-shift value
* for setting word_size.
*/
size += NVM_WORD_SIZE_BASE_SHIFT;
/* EEPROM access above 16k is unsupported */
if (size > 14)
size = 14;
nvm->word_size = 1 << size;
break;
}
/* Function Pointers */
switch (hw->mac.type) {
case e1000_82574:
case e1000_82583:
nvm->ops.acquire = e1000_get_hw_semaphore_82574;
nvm->ops.release = e1000_put_hw_semaphore_82574;
break;
default:
break;
}
return 0;
}
/**
* e1000_init_mac_params_82571 - Init MAC func ptrs.
* @hw: pointer to the HW structure
**/
static s32 e1000_init_mac_params_82571(struct e1000_hw *hw)
{
struct e1000_mac_info *mac = &hw->mac;
u32 swsm = 0;
u32 swsm2 = 0;
bool force_clear_smbi = false;
/* Set media type and media-dependent function pointers */
switch (hw->adapter->pdev->device) {
case E1000_DEV_ID_82571EB_FIBER:
case E1000_DEV_ID_82572EI_FIBER:
case E1000_DEV_ID_82571EB_QUAD_FIBER:
hw->phy.media_type = e1000_media_type_fiber;
mac->ops.setup_physical_interface =
e1000_setup_fiber_serdes_link_82571;
mac->ops.check_for_link = e1000e_check_for_fiber_link;
mac->ops.get_link_up_info =
e1000e_get_speed_and_duplex_fiber_serdes;
break;
case E1000_DEV_ID_82571EB_SERDES:
case E1000_DEV_ID_82571EB_SERDES_DUAL:
case E1000_DEV_ID_82571EB_SERDES_QUAD:
case E1000_DEV_ID_82572EI_SERDES:
hw->phy.media_type = e1000_media_type_internal_serdes;
mac->ops.setup_physical_interface =
e1000_setup_fiber_serdes_link_82571;
mac->ops.check_for_link = e1000_check_for_serdes_link_82571;
mac->ops.get_link_up_info =
e1000e_get_speed_and_duplex_fiber_serdes;
break;
default:
hw->phy.media_type = e1000_media_type_copper;
mac->ops.setup_physical_interface =
e1000_setup_copper_link_82571;
mac->ops.check_for_link = e1000e_check_for_copper_link;
mac->ops.get_link_up_info = e1000e_get_speed_and_duplex_copper;
break;
}
/* Set mta register count */
mac->mta_reg_count = 128;
/* Set rar entry count */
mac->rar_entry_count = E1000_RAR_ENTRIES;
/* Adaptive IFS supported */
mac->adaptive_ifs = true;
/* MAC-specific function pointers */
switch (hw->mac.type) {
case e1000_82573:
mac->ops.set_lan_id = e1000_set_lan_id_single_port;
mac->ops.check_mng_mode = e1000e_check_mng_mode_generic;
mac->ops.led_on = e1000e_led_on_generic;
mac->ops.blink_led = e1000e_blink_led_generic;
/* FWSM register */
mac->has_fwsm = true;
/* ARC supported; valid only if manageability features are
* enabled.
*/
mac->arc_subsystem_valid = !!(er32(FWSM) &
E1000_FWSM_MODE_MASK);
break;
case e1000_82574:
case e1000_82583:
mac->ops.set_lan_id = e1000_set_lan_id_single_port;
mac->ops.check_mng_mode = e1000_check_mng_mode_82574;
mac->ops.led_on = e1000_led_on_82574;
break;
default:
mac->ops.check_mng_mode = e1000e_check_mng_mode_generic;
mac->ops.led_on = e1000e_led_on_generic;
mac->ops.blink_led = e1000e_blink_led_generic;
/* FWSM register */
mac->has_fwsm = true;
break;
}
/* Ensure that the inter-port SWSM.SMBI lock bit is clear before
* first NVM or PHY access. This should be done for single-port
* devices, and for one port only on dual-port devices so that
* for those devices we can still use the SMBI lock to synchronize
* inter-port accesses to the PHY & NVM.
*/
switch (hw->mac.type) {
case e1000_82571:
case e1000_82572:
swsm2 = er32(SWSM2);
if (!(swsm2 & E1000_SWSM2_LOCK)) {
/* Only do this for the first interface on this card */
ew32(SWSM2, swsm2 | E1000_SWSM2_LOCK);
force_clear_smbi = true;
} else {
force_clear_smbi = false;
}
break;
default:
force_clear_smbi = true;
break;
}
if (force_clear_smbi) {
/* Make sure SWSM.SMBI is clear */
swsm = er32(SWSM);
if (swsm & E1000_SWSM_SMBI) {
/* This bit should not be set on a first interface, and
* indicates that the bootagent or EFI code has
* improperly left this bit enabled
*/
e_dbg("Please update your 82571 Bootagent\n");
}
ew32(SWSM, swsm & ~E1000_SWSM_SMBI);
}
/* Initialize device specific counter of SMBI acquisition timeouts. */
hw->dev_spec.e82571.smb_counter = 0;
return 0;
}
static s32 e1000_get_variants_82571(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
static int global_quad_port_a; /* global port a indication */
struct pci_dev *pdev = adapter->pdev;
int is_port_b = er32(STATUS) & E1000_STATUS_FUNC_1;
s32 rc;
rc = e1000_init_mac_params_82571(hw);
if (rc)
return rc;
rc = e1000_init_nvm_params_82571(hw);
if (rc)
return rc;
rc = e1000_init_phy_params_82571(hw);
if (rc)
return rc;
/* tag quad port adapters first, it's used below */
switch (pdev->device) {
case E1000_DEV_ID_82571EB_QUAD_COPPER:
case E1000_DEV_ID_82571EB_QUAD_FIBER:
case E1000_DEV_ID_82571EB_QUAD_COPPER_LP:
case E1000_DEV_ID_82571PT_QUAD_COPPER:
adapter->flags |= FLAG_IS_QUAD_PORT;
/* mark the first port */
if (global_quad_port_a == 0)
adapter->flags |= FLAG_IS_QUAD_PORT_A;
/* Reset for multiple quad port adapters */
global_quad_port_a++;
if (global_quad_port_a == 4)
global_quad_port_a = 0;
break;
default:
break;
}
switch (adapter->hw.mac.type) {
case e1000_82571:
/* these dual ports don't have WoL on port B at all */
if (((pdev->device == E1000_DEV_ID_82571EB_FIBER) ||
(pdev->device == E1000_DEV_ID_82571EB_SERDES) ||
(pdev->device == E1000_DEV_ID_82571EB_COPPER)) &&
(is_port_b))
adapter->flags &= ~FLAG_HAS_WOL;
/* quad ports only support WoL on port A */
if (adapter->flags & FLAG_IS_QUAD_PORT &&
(!(adapter->flags & FLAG_IS_QUAD_PORT_A)))
adapter->flags &= ~FLAG_HAS_WOL;
/* Does not support WoL on any port */
if (pdev->device == E1000_DEV_ID_82571EB_SERDES_QUAD)
adapter->flags &= ~FLAG_HAS_WOL;
break;
case e1000_82573:
if (pdev->device == E1000_DEV_ID_82573L) {
adapter->flags |= FLAG_HAS_JUMBO_FRAMES;
adapter->max_hw_frame_size = DEFAULT_JUMBO;
}
break;
default:
break;
}
return 0;
}
/**
* e1000_get_phy_id_82571 - Retrieve the PHY ID and revision
* @hw: pointer to the HW structure
*
* Reads the PHY registers and stores the PHY ID and possibly the PHY
* revision in the hardware structure.
**/
static s32 e1000_get_phy_id_82571(struct e1000_hw *hw)
{
struct e1000_phy_info *phy = &hw->phy;
s32 ret_val;
u16 phy_id = 0;
switch (hw->mac.type) {
case e1000_82571:
case e1000_82572:
/* The 82571 firmware may still be configuring the PHY.
* In this case, we cannot access the PHY until the
* configuration is done. So we explicitly set the
* PHY ID.
*/
phy->id = IGP01E1000_I_PHY_ID;
break;
case e1000_82573:
return e1000e_get_phy_id(hw);
break;
case e1000_82574:
case e1000_82583:
ret_val = e1e_rphy(hw, MII_PHYSID1, &phy_id);
if (ret_val)
return ret_val;
phy->id = (u32)(phy_id << 16);
usleep_range(20, 40);
ret_val = e1e_rphy(hw, MII_PHYSID2, &phy_id);
if (ret_val)
return ret_val;
phy->id |= (u32)(phy_id);
phy->revision = (u32)(phy_id & ~PHY_REVISION_MASK);
break;
default:
return -E1000_ERR_PHY;
break;
}
return 0;
}
/**
* e1000_get_hw_semaphore_82571 - Acquire hardware semaphore
* @hw: pointer to the HW structure
*
* Acquire the HW semaphore to access the PHY or NVM
**/
static s32 e1000_get_hw_semaphore_82571(struct e1000_hw *hw)
{
u32 swsm;
s32 sw_timeout = hw->nvm.word_size + 1;
s32 fw_timeout = hw->nvm.word_size + 1;
s32 i = 0;
/* If we have timedout 3 times on trying to acquire
* the inter-port SMBI semaphore, there is old code
* operating on the other port, and it is not
* releasing SMBI. Modify the number of times that
* we try for the semaphore to interwork with this
* older code.
*/
if (hw->dev_spec.e82571.smb_counter > 2)
sw_timeout = 1;
/* Get the SW semaphore */
while (i < sw_timeout) {
swsm = er32(SWSM);
if (!(swsm & E1000_SWSM_SMBI))
break;
usleep_range(50, 100);
i++;
}
if (i == sw_timeout) {
e_dbg("Driver can't access device - SMBI bit is set.\n");
hw->dev_spec.e82571.smb_counter++;
}
/* Get the FW semaphore. */
for (i = 0; i < fw_timeout; i++) {
swsm = er32(SWSM);
ew32(SWSM, swsm | E1000_SWSM_SWESMBI);
/* Semaphore acquired if bit latched */
if (er32(SWSM) & E1000_SWSM_SWESMBI)
break;
usleep_range(50, 100);
}
if (i == fw_timeout) {
/* Release semaphores */
e1000_put_hw_semaphore_82571(hw);
e_dbg("Driver can't access the NVM\n");
return -E1000_ERR_NVM;
}
return 0;
}
/**
* e1000_put_hw_semaphore_82571 - Release hardware semaphore
* @hw: pointer to the HW structure
*
* Release hardware semaphore used to access the PHY or NVM
**/
static void e1000_put_hw_semaphore_82571(struct e1000_hw *hw)
{
u32 swsm;
swsm = er32(SWSM);
swsm &= ~(E1000_SWSM_SMBI | E1000_SWSM_SWESMBI);
ew32(SWSM, swsm);
}
/**
* e1000_get_hw_semaphore_82573 - Acquire hardware semaphore
* @hw: pointer to the HW structure
*
* Acquire the HW semaphore during reset.
*
**/
static s32 e1000_get_hw_semaphore_82573(struct e1000_hw *hw)
{
u32 extcnf_ctrl;
s32 i = 0;
extcnf_ctrl = er32(EXTCNF_CTRL);
do {
extcnf_ctrl |= E1000_EXTCNF_CTRL_MDIO_SW_OWNERSHIP;
ew32(EXTCNF_CTRL, extcnf_ctrl);
extcnf_ctrl = er32(EXTCNF_CTRL);
if (extcnf_ctrl & E1000_EXTCNF_CTRL_MDIO_SW_OWNERSHIP)
break;
usleep_range(2000, 4000);
i++;
} while (i < MDIO_OWNERSHIP_TIMEOUT);
if (i == MDIO_OWNERSHIP_TIMEOUT) {
/* Release semaphores */
e1000_put_hw_semaphore_82573(hw);
e_dbg("Driver can't access the PHY\n");
return -E1000_ERR_PHY;
}
return 0;
}
/**
* e1000_put_hw_semaphore_82573 - Release hardware semaphore
* @hw: pointer to the HW structure
*
* Release hardware semaphore used during reset.
*
**/
static void e1000_put_hw_semaphore_82573(struct e1000_hw *hw)
{
u32 extcnf_ctrl;
extcnf_ctrl = er32(EXTCNF_CTRL);
extcnf_ctrl &= ~E1000_EXTCNF_CTRL_MDIO_SW_OWNERSHIP;
ew32(EXTCNF_CTRL, extcnf_ctrl);
}
static DEFINE_MUTEX(swflag_mutex);
/**
* e1000_get_hw_semaphore_82574 - Acquire hardware semaphore
* @hw: pointer to the HW structure
*
* Acquire the HW semaphore to access the PHY or NVM.
*
**/
static s32 e1000_get_hw_semaphore_82574(struct e1000_hw *hw)
{
s32 ret_val;
mutex_lock(&swflag_mutex);
ret_val = e1000_get_hw_semaphore_82573(hw);
if (ret_val)
mutex_unlock(&swflag_mutex);
return ret_val;
}
/**
* e1000_put_hw_semaphore_82574 - Release hardware semaphore
* @hw: pointer to the HW structure
*
* Release hardware semaphore used to access the PHY or NVM
*
**/
static void e1000_put_hw_semaphore_82574(struct e1000_hw *hw)
{
e1000_put_hw_semaphore_82573(hw);
mutex_unlock(&swflag_mutex);
}
/**
* e1000_set_d0_lplu_state_82574 - Set Low Power Linkup D0 state
* @hw: pointer to the HW structure
* @active: true to enable LPLU, false to disable
*
* Sets the LPLU D0 state according to the active flag.
* LPLU will not be activated unless the
* device autonegotiation advertisement meets standards of
* either 10 or 10/100 or 10/100/1000 at all duplexes.
* This is a function pointer entry point only called by
* PHY setup routines.
**/
static s32 e1000_set_d0_lplu_state_82574(struct e1000_hw *hw, bool active)
{
u32 data = er32(POEMB);
if (active)
data |= E1000_PHY_CTRL_D0A_LPLU;
else
data &= ~E1000_PHY_CTRL_D0A_LPLU;
ew32(POEMB, data);
return 0;
}
/**
* e1000_set_d3_lplu_state_82574 - Sets low power link up state for D3
* @hw: pointer to the HW structure
* @active: boolean used to enable/disable lplu
*
* The low power link up (lplu) state is set to the power management level D3
* when active is true, else clear lplu for D3. LPLU
* is used during Dx states where the power conservation is most important.
* During driver activity, SmartSpeed should be enabled so performance is
* maintained.
**/
static s32 e1000_set_d3_lplu_state_82574(struct e1000_hw *hw, bool active)
{
u32 data = er32(POEMB);
if (!active) {
data &= ~E1000_PHY_CTRL_NOND0A_LPLU;
} else if ((hw->phy.autoneg_advertised == E1000_ALL_SPEED_DUPLEX) ||
(hw->phy.autoneg_advertised == E1000_ALL_NOT_GIG) ||
(hw->phy.autoneg_advertised == E1000_ALL_10_SPEED)) {
data |= E1000_PHY_CTRL_NOND0A_LPLU;
}
ew32(POEMB, data);
return 0;
}
/**
* e1000_acquire_nvm_82571 - Request for access to the EEPROM
* @hw: pointer to the HW structure
*
* To gain access to the EEPROM, first we must obtain a hardware semaphore.
* Then for non-82573 hardware, set the EEPROM access request bit and wait
* for EEPROM access grant bit. If the access grant bit is not set, release
* hardware semaphore.
**/
static s32 e1000_acquire_nvm_82571(struct e1000_hw *hw)
{
s32 ret_val;
ret_val = e1000_get_hw_semaphore_82571(hw);
if (ret_val)
return ret_val;
switch (hw->mac.type) {
case e1000_82573:
break;
default:
ret_val = e1000e_acquire_nvm(hw);
break;
}
if (ret_val)
e1000_put_hw_semaphore_82571(hw);
return ret_val;
}
/**
* e1000_release_nvm_82571 - Release exclusive access to EEPROM
* @hw: pointer to the HW structure
*
* Stop any current commands to the EEPROM and clear the EEPROM request bit.
**/
static void e1000_release_nvm_82571(struct e1000_hw *hw)
{
e1000e_release_nvm(hw);
e1000_put_hw_semaphore_82571(hw);
}
/**
* e1000_write_nvm_82571 - Write to EEPROM using appropriate interface
* @hw: pointer to the HW structure
* @offset: offset within the EEPROM to be written to
* @words: number of words to write
* @data: 16 bit word(s) to be written to the EEPROM
*
* For non-82573 silicon, write data to EEPROM at offset using SPI interface.
*
* If e1000e_update_nvm_checksum is not called after this function, the
* EEPROM will most likely contain an invalid checksum.
**/
static s32 e1000_write_nvm_82571(struct e1000_hw *hw, u16 offset, u16 words,
u16 *data)
{
s32 ret_val;
switch (hw->mac.type) {
case e1000_82573:
case e1000_82574:
case e1000_82583:
ret_val = e1000_write_nvm_eewr_82571(hw, offset, words, data);
break;
case e1000_82571:
case e1000_82572:
ret_val = e1000e_write_nvm_spi(hw, offset, words, data);
break;
default:
ret_val = -E1000_ERR_NVM;
break;
}
return ret_val;
}
/**
* e1000_update_nvm_checksum_82571 - Update EEPROM checksum
* @hw: pointer to the HW structure
*
* Updates the EEPROM checksum by reading/adding each word of the EEPROM
* up to the checksum. Then calculates the EEPROM checksum and writes the
* value to the EEPROM.
**/
static s32 e1000_update_nvm_checksum_82571(struct e1000_hw *hw)
{
u32 eecd;
s32 ret_val;
u16 i;
ret_val = e1000e_update_nvm_checksum_generic(hw);
if (ret_val)
return ret_val;
/* If our nvm is an EEPROM, then we're done
* otherwise, commit the checksum to the flash NVM.
*/
if (hw->nvm.type != e1000_nvm_flash_hw)
return 0;
/* Check for pending operations. */
for (i = 0; i < E1000_FLASH_UPDATES; i++) {
usleep_range(1000, 2000);
if (!(er32(EECD) & E1000_EECD_FLUPD))
break;
}
if (i == E1000_FLASH_UPDATES)
return -E1000_ERR_NVM;
/* Reset the firmware if using STM opcode. */
if ((er32(FLOP) & 0xFF00) == E1000_STM_OPCODE) {
/* The enabling of and the actual reset must be done
* in two write cycles.
*/
ew32(HICR, E1000_HICR_FW_RESET_ENABLE);
e1e_flush();
ew32(HICR, E1000_HICR_FW_RESET);
}
/* Commit the write to flash */
eecd = er32(EECD) | E1000_EECD_FLUPD;
ew32(EECD, eecd);
for (i = 0; i < E1000_FLASH_UPDATES; i++) {
usleep_range(1000, 2000);
if (!(er32(EECD) & E1000_EECD_FLUPD))
break;
}
if (i == E1000_FLASH_UPDATES)
return -E1000_ERR_NVM;
return 0;
}
/**
* e1000_validate_nvm_checksum_82571 - Validate EEPROM checksum
* @hw: pointer to the HW structure
*
* Calculates the EEPROM checksum by reading/adding each word of the EEPROM
* and then verifies that the sum of the EEPROM is equal to 0xBABA.
**/
static s32 e1000_validate_nvm_checksum_82571(struct e1000_hw *hw)
{
if (hw->nvm.type == e1000_nvm_flash_hw)
e1000_fix_nvm_checksum_82571(hw);
return e1000e_validate_nvm_checksum_generic(hw);
}
/**
* e1000_write_nvm_eewr_82571 - Write to EEPROM for 82573 silicon
* @hw: pointer to the HW structure
* @offset: offset within the EEPROM to be written to
* @words: number of words to write
* @data: 16 bit word(s) to be written to the EEPROM
*
* After checking for invalid values, poll the EEPROM to ensure the previous
* command has completed before trying to write the next word. After write
* poll for completion.
*
* If e1000e_update_nvm_checksum is not called after this function, the
* EEPROM will most likely contain an invalid checksum.
**/
static s32 e1000_write_nvm_eewr_82571(struct e1000_hw *hw, u16 offset,
u16 words, u16 *data)
{
struct e1000_nvm_info *nvm = &hw->nvm;
u32 i, eewr = 0;
s32 ret_val = 0;
/* A check for invalid values: offset too large, too many words,
* and not enough words.
*/
if ((offset >= nvm->word_size) || (words > (nvm->word_size - offset)) ||
(words == 0)) {
e_dbg("nvm parameter(s) out of bounds\n");
return -E1000_ERR_NVM;
}
for (i = 0; i < words; i++) {
eewr = ((data[i] << E1000_NVM_RW_REG_DATA) |
((offset + i) << E1000_NVM_RW_ADDR_SHIFT) |
E1000_NVM_RW_REG_START);
ret_val = e1000e_poll_eerd_eewr_done(hw, E1000_NVM_POLL_WRITE);
if (ret_val)
break;
ew32(EEWR, eewr);
ret_val = e1000e_poll_eerd_eewr_done(hw, E1000_NVM_POLL_WRITE);
if (ret_val)
break;
}
return ret_val;
}
/**
* e1000_get_cfg_done_82571 - Poll for configuration done
* @hw: pointer to the HW structure
*
* Reads the management control register for the config done bit to be set.
**/
static s32 e1000_get_cfg_done_82571(struct e1000_hw *hw)
{
s32 timeout = PHY_CFG_TIMEOUT;
while (timeout) {
if (er32(EEMNGCTL) & E1000_NVM_CFG_DONE_PORT_0)
break;
usleep_range(1000, 2000);
timeout--;
}
if (!timeout) {
e_dbg("MNG configuration cycle has not completed.\n");
return -E1000_ERR_RESET;
}
return 0;
}
/**
* e1000_set_d0_lplu_state_82571 - Set Low Power Linkup D0 state
* @hw: pointer to the HW structure
* @active: true to enable LPLU, false to disable
*
* Sets the LPLU D0 state according to the active flag. When activating LPLU
* this function also disables smart speed and vice versa. LPLU will not be
* activated unless the device autonegotiation advertisement meets standards
* of either 10 or 10/100 or 10/100/1000 at all duplexes. This is a function
* pointer entry point only called by PHY setup routines.
**/
static s32 e1000_set_d0_lplu_state_82571(struct e1000_hw *hw, bool active)
{
struct e1000_phy_info *phy = &hw->phy;
s32 ret_val;
u16 data;
ret_val = e1e_rphy(hw, IGP02E1000_PHY_POWER_MGMT, &data);
if (ret_val)
return ret_val;
if (active) {
data |= IGP02E1000_PM_D0_LPLU;
ret_val = e1e_wphy(hw, IGP02E1000_PHY_POWER_MGMT, data);
if (ret_val)
return ret_val;
/* When LPLU is enabled, we should disable SmartSpeed */
ret_val = e1e_rphy(hw, IGP01E1000_PHY_PORT_CONFIG, &data);
if (ret_val)
return ret_val;
data &= ~IGP01E1000_PSCFR_SMART_SPEED;
ret_val = e1e_wphy(hw, IGP01E1000_PHY_PORT_CONFIG, data);
if (ret_val)
return ret_val;
} else {
data &= ~IGP02E1000_PM_D0_LPLU;
ret_val = e1e_wphy(hw, IGP02E1000_PHY_POWER_MGMT, data);
/* LPLU and SmartSpeed are mutually exclusive. LPLU is used
* during Dx states where the power conservation is most
* important. During driver activity we should enable
* SmartSpeed, so performance is maintained.
*/
if (phy->smart_speed == e1000_smart_speed_on) {
ret_val = e1e_rphy(hw, IGP01E1000_PHY_PORT_CONFIG,
&data);
if (ret_val)
return ret_val;
data |= IGP01E1000_PSCFR_SMART_SPEED;
ret_val = e1e_wphy(hw, IGP01E1000_PHY_PORT_CONFIG,
data);
if (ret_val)
return ret_val;
} else if (phy->smart_speed == e1000_smart_speed_off) {
ret_val = e1e_rphy(hw, IGP01E1000_PHY_PORT_CONFIG,
&data);
if (ret_val)
return ret_val;
data &= ~IGP01E1000_PSCFR_SMART_SPEED;
ret_val = e1e_wphy(hw, IGP01E1000_PHY_PORT_CONFIG,
data);
if (ret_val)
return ret_val;
}
}
return 0;
}
/**
* e1000_reset_hw_82571 - Reset hardware
* @hw: pointer to the HW structure
*
* This resets the hardware into a known state.
**/
static s32 e1000_reset_hw_82571(struct e1000_hw *hw)
{
u32 ctrl, ctrl_ext, eecd, tctl;
s32 ret_val;
/* Prevent the PCI-E bus from sticking if there is no TLP connection
* on the last TLP read/write transaction when MAC is reset.
*/
ret_val = e1000e_disable_pcie_master(hw);
if (ret_val)
e_dbg("PCI-E Master disable polling has failed.\n");
e_dbg("Masking off all interrupts\n");
ew32(IMC, 0xffffffff);
ew32(RCTL, 0);
tctl = er32(TCTL);
tctl &= ~E1000_TCTL_EN;
ew32(TCTL, tctl);
e1e_flush();
usleep_range(10000, 20000);
/* Must acquire the MDIO ownership before MAC reset.
* Ownership defaults to firmware after a reset.
*/
switch (hw->mac.type) {
case e1000_82573:
ret_val = e1000_get_hw_semaphore_82573(hw);
break;
case e1000_82574:
case e1000_82583:
ret_val = e1000_get_hw_semaphore_82574(hw);
break;
default:
break;
}
if (ret_val)
e_dbg("Cannot acquire MDIO ownership\n");
ctrl = er32(CTRL);
e_dbg("Issuing a global reset to MAC\n");
ew32(CTRL, ctrl | E1000_CTRL_RST);
/* Must release MDIO ownership and mutex after MAC reset. */
switch (hw->mac.type) {
case e1000_82574:
case e1000_82583:
e1000_put_hw_semaphore_82574(hw);
break;
default:
break;
}
if (hw->nvm.type == e1000_nvm_flash_hw) {
usleep_range(10, 20);
ctrl_ext = er32(CTRL_EXT);
ctrl_ext |= E1000_CTRL_EXT_EE_RST;
ew32(CTRL_EXT, ctrl_ext);
e1e_flush();
}
ret_val = e1000e_get_auto_rd_done(hw);
if (ret_val)
/* We don't want to continue accessing MAC registers. */
return ret_val;
/* Phy configuration from NVM just starts after EECD_AUTO_RD is set.
* Need to wait for Phy configuration completion before accessing
* NVM and Phy.
*/
switch (hw->mac.type) {
case e1000_82571:
case e1000_82572:
/* REQ and GNT bits need to be cleared when using AUTO_RD
* to access the EEPROM.
*/
eecd = er32(EECD);
eecd &= ~(E1000_EECD_REQ | E1000_EECD_GNT);
ew32(EECD, eecd);
break;
case e1000_82573:
case e1000_82574:
case e1000_82583:
msleep(25);
break;
default:
break;
}
/* Clear any pending interrupt events. */
ew32(IMC, 0xffffffff);
er32(ICR);
if (hw->mac.type == e1000_82571) {
/* Install any alternate MAC address into RAR0 */
ret_val = e1000_check_alt_mac_addr_generic(hw);
if (ret_val)
return ret_val;
e1000e_set_laa_state_82571(hw, true);
}
/* Reinitialize the 82571 serdes link state machine */
if (hw->phy.media_type == e1000_media_type_internal_serdes)
hw->mac.serdes_link_state = e1000_serdes_link_down;
return 0;
}
/**
* e1000_init_hw_82571 - Initialize hardware
* @hw: pointer to the HW structure
*
* This inits the hardware readying it for operation.
**/
static s32 e1000_init_hw_82571(struct e1000_hw *hw)
{
struct e1000_mac_info *mac = &hw->mac;
u32 reg_data;
s32 ret_val;
u16 i, rar_count = mac->rar_entry_count;
e1000_initialize_hw_bits_82571(hw);
/* Initialize identification LED */
ret_val = mac->ops.id_led_init(hw);
/* An error is not fatal and we should not stop init due to this */
if (ret_val)
e_dbg("Error initializing identification LED\n");
/* Disabling VLAN filtering */
e_dbg("Initializing the IEEE VLAN\n");
mac->ops.clear_vfta(hw);
/* Setup the receive address.
* If, however, a locally administered address was assigned to the
* 82571, we must reserve a RAR for it to work around an issue where
* resetting one port will reload the MAC on the other port.
*/
if (e1000e_get_laa_state_82571(hw))
rar_count--;
e1000e_init_rx_addrs(hw, rar_count);
/* Zero out the Multicast HASH table */
e_dbg("Zeroing the MTA\n");
for (i = 0; i < mac->mta_reg_count; i++)
E1000_WRITE_REG_ARRAY(hw, E1000_MTA, i, 0);
/* Setup link and flow control */
ret_val = mac->ops.setup_link(hw);
/* Set the transmit descriptor write-back policy */
reg_data = er32(TXDCTL(0));
reg_data = ((reg_data & ~E1000_TXDCTL_WTHRESH) |
E1000_TXDCTL_FULL_TX_DESC_WB | E1000_TXDCTL_COUNT_DESC);
ew32(TXDCTL(0), reg_data);
/* ...for both queues. */
switch (mac->type) {
case e1000_82573:
e1000e_enable_tx_pkt_filtering(hw);
/* fall through */
case e1000_82574:
case e1000_82583:
reg_data = er32(GCR);
reg_data |= E1000_GCR_L1_ACT_WITHOUT_L0S_RX;
ew32(GCR, reg_data);
break;
default:
reg_data = er32(TXDCTL(1));
reg_data = ((reg_data & ~E1000_TXDCTL_WTHRESH) |
E1000_TXDCTL_FULL_TX_DESC_WB |
E1000_TXDCTL_COUNT_DESC);
ew32(TXDCTL(1), reg_data);
break;
}
/* Clear all of the statistics registers (clear on read). It is
* important that we do this after we have tried to establish link
* because the symbol error count will increment wildly if there
* is no link.
*/
e1000_clear_hw_cntrs_82571(hw);
return ret_val;
}
/**
* e1000_initialize_hw_bits_82571 - Initialize hardware-dependent bits
* @hw: pointer to the HW structure
*
* Initializes required hardware-dependent bits needed for normal operation.
**/
static void e1000_initialize_hw_bits_82571(struct e1000_hw *hw)
{
u32 reg;
/* Transmit Descriptor Control 0 */
reg = er32(TXDCTL(0));
reg |= (1 << 22);
ew32(TXDCTL(0), reg);
/* Transmit Descriptor Control 1 */
reg = er32(TXDCTL(1));
reg |= (1 << 22);
ew32(TXDCTL(1), reg);
/* Transmit Arbitration Control 0 */
reg = er32(TARC(0));
reg &= ~(0xF << 27); /* 30:27 */
switch (hw->mac.type) {
case e1000_82571:
case e1000_82572:
reg |= (1 << 23) | (1 << 24) | (1 << 25) | (1 << 26);
break;
case e1000_82574:
case e1000_82583:
reg |= (1 << 26);
break;
default:
break;
}
ew32(TARC(0), reg);
/* Transmit Arbitration Control 1 */
reg = er32(TARC(1));
switch (hw->mac.type) {
case e1000_82571:
case e1000_82572:
reg &= ~((1 << 29) | (1 << 30));
reg |= (1 << 22) | (1 << 24) | (1 << 25) | (1 << 26);
if (er32(TCTL) & E1000_TCTL_MULR)
reg &= ~(1 << 28);
else
reg |= (1 << 28);
ew32(TARC(1), reg);
break;
default:
break;
}
/* Device Control */
switch (hw->mac.type) {
case e1000_82573:
case e1000_82574:
case e1000_82583:
reg = er32(CTRL);
reg &= ~(1 << 29);
ew32(CTRL, reg);
break;
default:
break;
}
/* Extended Device Control */
switch (hw->mac.type) {
case e1000_82573:
case e1000_82574:
case e1000_82583:
reg = er32(CTRL_EXT);
reg &= ~(1 << 23);
reg |= (1 << 22);
ew32(CTRL_EXT, reg);
break;
default:
break;
}
if (hw->mac.type == e1000_82571) {
reg = er32(PBA_ECC);
reg |= E1000_PBA_ECC_CORR_EN;
ew32(PBA_ECC, reg);
}
/* Workaround for hardware errata.
* Ensure that DMA Dynamic Clock gating is disabled on 82571 and 82572
*/
if ((hw->mac.type == e1000_82571) || (hw->mac.type == e1000_82572)) {
reg = er32(CTRL_EXT);
reg &= ~E1000_CTRL_EXT_DMA_DYN_CLK_EN;
ew32(CTRL_EXT, reg);
}
/* Disable IPv6 extension header parsing because some malformed
* IPv6 headers can hang the Rx.
*/
if (hw->mac.type <= e1000_82573) {
reg = er32(RFCTL);
reg |= (E1000_RFCTL_IPV6_EX_DIS | E1000_RFCTL_NEW_IPV6_EXT_DIS);
ew32(RFCTL, reg);
}
/* PCI-Ex Control Registers */
switch (hw->mac.type) {
case e1000_82574:
case e1000_82583:
reg = er32(GCR);
reg |= (1 << 22);
ew32(GCR, reg);
/* Workaround for hardware errata.
* apply workaround for hardware errata documented in errata
* docs Fixes issue where some error prone or unreliable PCIe
* completions are occurring, particularly with ASPM enabled.
* Without fix, issue can cause Tx timeouts.
*/
reg = er32(GCR2);
reg |= 1;
ew32(GCR2, reg);
break;
default:
break;
}
}
/**
* e1000_clear_vfta_82571 - Clear VLAN filter table
* @hw: pointer to the HW structure
*
* Clears the register array which contains the VLAN filter table by
* setting all the values to 0.
**/
static void e1000_clear_vfta_82571(struct e1000_hw *hw)
{
u32 offset;
u32 vfta_value = 0;
u32 vfta_offset = 0;
u32 vfta_bit_in_reg = 0;
switch (hw->mac.type) {
case e1000_82573:
case e1000_82574:
case e1000_82583:
if (hw->mng_cookie.vlan_id != 0) {
/* The VFTA is a 4096b bit-field, each identifying
* a single VLAN ID. The following operations
* determine which 32b entry (i.e. offset) into the
* array we want to set the VLAN ID (i.e. bit) of
* the manageability unit.
*/
vfta_offset = (hw->mng_cookie.vlan_id >>
E1000_VFTA_ENTRY_SHIFT) &
E1000_VFTA_ENTRY_MASK;
vfta_bit_in_reg =
1 << (hw->mng_cookie.vlan_id &
E1000_VFTA_ENTRY_BIT_SHIFT_MASK);
}
break;
default:
break;
}
for (offset = 0; offset < E1000_VLAN_FILTER_TBL_SIZE; offset++) {
/* If the offset we want to clear is the same offset of the
* manageability VLAN ID, then clear all bits except that of
* the manageability unit.
*/
vfta_value = (offset == vfta_offset) ? vfta_bit_in_reg : 0;
E1000_WRITE_REG_ARRAY(hw, E1000_VFTA, offset, vfta_value);
e1e_flush();
}
}
/**
* e1000_check_mng_mode_82574 - Check manageability is enabled
* @hw: pointer to the HW structure
*
* Reads the NVM Initialization Control Word 2 and returns true
* (>0) if any manageability is enabled, else false (0).
**/
static bool e1000_check_mng_mode_82574(struct e1000_hw *hw)
{
u16 data;
e1000_read_nvm(hw, NVM_INIT_CONTROL2_REG, 1, &data);
return (data & E1000_NVM_INIT_CTRL2_MNGM) != 0;
}
/**
* e1000_led_on_82574 - Turn LED on
* @hw: pointer to the HW structure
*
* Turn LED on.
**/
static s32 e1000_led_on_82574(struct e1000_hw *hw)
{
u32 ctrl;
u32 i;
ctrl = hw->mac.ledctl_mode2;
if (!(E1000_STATUS_LU & er32(STATUS))) {
/* If no link, then turn LED on by setting the invert bit
* for each LED that's "on" (0x0E) in ledctl_mode2.
*/
for (i = 0; i < 4; i++)
if (((hw->mac.ledctl_mode2 >> (i * 8)) & 0xFF) ==
E1000_LEDCTL_MODE_LED_ON)
ctrl |= (E1000_LEDCTL_LED0_IVRT << (i * 8));
}
ew32(LEDCTL, ctrl);
return 0;
}
/**
* e1000_check_phy_82574 - check 82574 phy hung state
* @hw: pointer to the HW structure
*
* Returns whether phy is hung or not
**/
bool e1000_check_phy_82574(struct e1000_hw *hw)
{
u16 status_1kbt = 0;
u16 receive_errors = 0;
s32 ret_val;
/* Read PHY Receive Error counter first, if its is max - all F's then
* read the Base1000T status register If both are max then PHY is hung.
*/
ret_val = e1e_rphy(hw, E1000_RECEIVE_ERROR_COUNTER, &receive_errors);
if (ret_val)
return false;
if (receive_errors == E1000_RECEIVE_ERROR_MAX) {
ret_val = e1e_rphy(hw, E1000_BASE1000T_STATUS, &status_1kbt);
if (ret_val)
return false;
if ((status_1kbt & E1000_IDLE_ERROR_COUNT_MASK) ==
E1000_IDLE_ERROR_COUNT_MASK)
return true;
}
return false;
}
/**
* e1000_setup_link_82571 - Setup flow control and link settings
* @hw: pointer to the HW structure
*
* Determines which flow control settings to use, then configures flow
* control. Calls the appropriate media-specific link configuration
* function. Assuming the adapter has a valid link partner, a valid link
* should be established. Assumes the hardware has previously been reset
* and the transmitter and receiver are not enabled.
**/
static s32 e1000_setup_link_82571(struct e1000_hw *hw)
{
/* 82573 does not have a word in the NVM to determine
* the default flow control setting, so we explicitly
* set it to full.
*/
switch (hw->mac.type) {
case e1000_82573:
case e1000_82574:
case e1000_82583:
if (hw->fc.requested_mode == e1000_fc_default)
hw->fc.requested_mode = e1000_fc_full;
break;
default:
break;
}
return e1000e_setup_link_generic(hw);
}
/**
* e1000_setup_copper_link_82571 - Configure copper link settings
* @hw: pointer to the HW structure
*
* Configures the link for auto-neg or forced speed and duplex. Then we check
* for link, once link is established calls to configure collision distance
* and flow control are called.
**/
static s32 e1000_setup_copper_link_82571(struct e1000_hw *hw)
{
u32 ctrl;
s32 ret_val;
ctrl = er32(CTRL);
ctrl |= E1000_CTRL_SLU;
ctrl &= ~(E1000_CTRL_FRCSPD | E1000_CTRL_FRCDPX);
ew32(CTRL, ctrl);
switch (hw->phy.type) {
case e1000_phy_m88:
case e1000_phy_bm:
ret_val = e1000e_copper_link_setup_m88(hw);
break;
case e1000_phy_igp_2:
ret_val = e1000e_copper_link_setup_igp(hw);
break;
default:
return -E1000_ERR_PHY;
break;
}
if (ret_val)
return ret_val;
return e1000e_setup_copper_link(hw);
}
/**
* e1000_setup_fiber_serdes_link_82571 - Setup link for fiber/serdes
* @hw: pointer to the HW structure
*
* Configures collision distance and flow control for fiber and serdes links.
* Upon successful setup, poll for link.
**/
static s32 e1000_setup_fiber_serdes_link_82571(struct e1000_hw *hw)
{
switch (hw->mac.type) {
case e1000_82571:
case e1000_82572:
/* If SerDes loopback mode is entered, there is no form
* of reset to take the adapter out of that mode. So we
* have to explicitly take the adapter out of loopback
* mode. This prevents drivers from twiddling their thumbs
* if another tool failed to take it out of loopback mode.
*/
ew32(SCTL, E1000_SCTL_DISABLE_SERDES_LOOPBACK);
break;
default:
break;
}
return e1000e_setup_fiber_serdes_link(hw);
}
/**
* e1000_check_for_serdes_link_82571 - Check for link (Serdes)
* @hw: pointer to the HW structure
*
* Reports the link state as up or down.
*
* If autonegotiation is supported by the link partner, the link state is
* determined by the result of autonegotiation. This is the most likely case.
* If autonegotiation is not supported by the link partner, and the link
* has a valid signal, force the link up.
*
* The link state is represented internally here by 4 states:
*
* 1) down
* 2) autoneg_progress
* 3) autoneg_complete (the link successfully autonegotiated)
* 4) forced_up (the link has been forced up, it did not autonegotiate)
*
**/
static s32 e1000_check_for_serdes_link_82571(struct e1000_hw *hw)
{
struct e1000_mac_info *mac = &hw->mac;
u32 rxcw;
u32 ctrl;
u32 status;
u32 txcw;
u32 i;
s32 ret_val = 0;
ctrl = er32(CTRL);
status = er32(STATUS);
er32(RXCW);
/* SYNCH bit and IV bit are sticky */
usleep_range(10, 20);
rxcw = er32(RXCW);
/* SYNCH bit and IV bit are sticky */
udelay(10);
rxcw = er32(RXCW);
if ((rxcw & E1000_RXCW_SYNCH) && !(rxcw & E1000_RXCW_IV)) {
/* Receiver is synchronized with no invalid bits. */
switch (mac->serdes_link_state) {
case e1000_serdes_link_autoneg_complete:
if (!(status & E1000_STATUS_LU)) {
/* We have lost link, retry autoneg before
* reporting link failure
*/
mac->serdes_link_state =
e1000_serdes_link_autoneg_progress;
mac->serdes_has_link = false;
e_dbg("AN_UP -> AN_PROG\n");
} else {
mac->serdes_has_link = true;
}
break;
case e1000_serdes_link_forced_up:
/* If we are receiving /C/ ordered sets, re-enable
* auto-negotiation in the TXCW register and disable
* forced link in the Device Control register in an
* attempt to auto-negotiate with our link partner.
*/
if (rxcw & E1000_RXCW_C) {
/* Enable autoneg, and unforce link up */
ew32(TXCW, mac->txcw);
ew32(CTRL, (ctrl & ~E1000_CTRL_SLU));
mac->serdes_link_state =
e1000_serdes_link_autoneg_progress;
mac->serdes_has_link = false;
e_dbg("FORCED_UP -> AN_PROG\n");
} else {
mac->serdes_has_link = true;
}
break;
case e1000_serdes_link_autoneg_progress:
if (rxcw & E1000_RXCW_C) {
/* We received /C/ ordered sets, meaning the
* link partner has autonegotiated, and we can
* trust the Link Up (LU) status bit.
*/
if (status & E1000_STATUS_LU) {
mac->serdes_link_state =
e1000_serdes_link_autoneg_complete;
e_dbg("AN_PROG -> AN_UP\n");
mac->serdes_has_link = true;
} else {
/* Autoneg completed, but failed. */
mac->serdes_link_state =
e1000_serdes_link_down;
e_dbg("AN_PROG -> DOWN\n");
}
} else {
/* The link partner did not autoneg.
* Force link up and full duplex, and change
* state to forced.
*/
ew32(TXCW, (mac->txcw & ~E1000_TXCW_ANE));
ctrl |= (E1000_CTRL_SLU | E1000_CTRL_FD);
ew32(CTRL, ctrl);
/* Configure Flow Control after link up. */
ret_val = e1000e_config_fc_after_link_up(hw);
if (ret_val) {
e_dbg("Error config flow control\n");
break;
}
mac->serdes_link_state =
e1000_serdes_link_forced_up;
mac->serdes_has_link = true;
e_dbg("AN_PROG -> FORCED_UP\n");
}
break;
case e1000_serdes_link_down:
default:
/* The link was down but the receiver has now gained
* valid sync, so lets see if we can bring the link
* up.
*/
ew32(TXCW, mac->txcw);
ew32(CTRL, (ctrl & ~E1000_CTRL_SLU));
mac->serdes_link_state =
e1000_serdes_link_autoneg_progress;
mac->serdes_has_link = false;
e_dbg("DOWN -> AN_PROG\n");
break;
}
} else {
if (!(rxcw & E1000_RXCW_SYNCH)) {
mac->serdes_has_link = false;
mac->serdes_link_state = e1000_serdes_link_down;
e_dbg("ANYSTATE -> DOWN\n");
} else {
/* Check several times, if SYNCH bit and CONFIG
* bit both are consistently 1 then simply ignore
* the IV bit and restart Autoneg
*/
for (i = 0; i < AN_RETRY_COUNT; i++) {
usleep_range(10, 20);
rxcw = er32(RXCW);
if ((rxcw & E1000_RXCW_SYNCH) &&
(rxcw & E1000_RXCW_C))
continue;
if (rxcw & E1000_RXCW_IV) {
mac->serdes_has_link = false;
mac->serdes_link_state =
e1000_serdes_link_down;
e_dbg("ANYSTATE -> DOWN\n");
break;
}
}
if (i == AN_RETRY_COUNT) {
txcw = er32(TXCW);
txcw |= E1000_TXCW_ANE;
ew32(TXCW, txcw);
mac->serdes_link_state =
e1000_serdes_link_autoneg_progress;
mac->serdes_has_link = false;
e_dbg("ANYSTATE -> AN_PROG\n");
}
}
}
return ret_val;
}
/**
* e1000_valid_led_default_82571 - Verify a valid default LED config
* @hw: pointer to the HW structure
* @data: pointer to the NVM (EEPROM)
*
* Read the EEPROM for the current default LED configuration. If the
* LED configuration is not valid, set to a valid LED configuration.
**/
static s32 e1000_valid_led_default_82571(struct e1000_hw *hw, u16 *data)
{
s32 ret_val;
ret_val = e1000_read_nvm(hw, NVM_ID_LED_SETTINGS, 1, data);
if (ret_val) {
e_dbg("NVM Read Error\n");
return ret_val;
}
switch (hw->mac.type) {
case e1000_82573:
case e1000_82574:
case e1000_82583:
if (*data == ID_LED_RESERVED_F746)
*data = ID_LED_DEFAULT_82573;
break;
default:
if (*data == ID_LED_RESERVED_0000 ||
*data == ID_LED_RESERVED_FFFF)
*data = ID_LED_DEFAULT;
break;
}
return 0;
}
/**
* e1000e_get_laa_state_82571 - Get locally administered address state
* @hw: pointer to the HW structure
*
* Retrieve and return the current locally administered address state.
**/
bool e1000e_get_laa_state_82571(struct e1000_hw *hw)
{
if (hw->mac.type != e1000_82571)
return false;
return hw->dev_spec.e82571.laa_is_present;
}
/**
* e1000e_set_laa_state_82571 - Set locally administered address state
* @hw: pointer to the HW structure
* @state: enable/disable locally administered address
*
* Enable/Disable the current locally administered address state.
**/
void e1000e_set_laa_state_82571(struct e1000_hw *hw, bool state)
{
if (hw->mac.type != e1000_82571)
return;
hw->dev_spec.e82571.laa_is_present = state;
/* If workaround is activated... */
if (state)
/* Hold a copy of the LAA in RAR[14] This is done so that
* between the time RAR[0] gets clobbered and the time it
* gets fixed, the actual LAA is in one of the RARs and no
* incoming packets directed to this port are dropped.
* Eventually the LAA will be in RAR[0] and RAR[14].
*/
hw->mac.ops.rar_set(hw, hw->mac.addr,
hw->mac.rar_entry_count - 1);
}
/**
* e1000_fix_nvm_checksum_82571 - Fix EEPROM checksum
* @hw: pointer to the HW structure
*
* Verifies that the EEPROM has completed the update. After updating the
* EEPROM, we need to check bit 15 in work 0x23 for the checksum fix. If
* the checksum fix is not implemented, we need to set the bit and update
* the checksum. Otherwise, if bit 15 is set and the checksum is incorrect,
* we need to return bad checksum.
**/
static s32 e1000_fix_nvm_checksum_82571(struct e1000_hw *hw)
{
struct e1000_nvm_info *nvm = &hw->nvm;
s32 ret_val;
u16 data;
if (nvm->type != e1000_nvm_flash_hw)
return 0;
/* Check bit 4 of word 10h. If it is 0, firmware is done updating
* 10h-12h. Checksum may need to be fixed.
*/
ret_val = e1000_read_nvm(hw, 0x10, 1, &data);
if (ret_val)
return ret_val;
if (!(data & 0x10)) {
/* Read 0x23 and check bit 15. This bit is a 1
* when the checksum has already been fixed. If
* the checksum is still wrong and this bit is a
* 1, we need to return bad checksum. Otherwise,
* we need to set this bit to a 1 and update the
* checksum.
*/
ret_val = e1000_read_nvm(hw, 0x23, 1, &data);
if (ret_val)
return ret_val;
if (!(data & 0x8000)) {
data |= 0x8000;
ret_val = e1000_write_nvm(hw, 0x23, 1, &data);
if (ret_val)
return ret_val;
ret_val = e1000e_update_nvm_checksum(hw);
if (ret_val)
return ret_val;
}
}
return 0;
}
/**
* e1000_read_mac_addr_82571 - Read device MAC address
* @hw: pointer to the HW structure
**/
static s32 e1000_read_mac_addr_82571(struct e1000_hw *hw)
{
if (hw->mac.type == e1000_82571) {
s32 ret_val;
/* If there's an alternate MAC address place it in RAR0
* so that it will override the Si installed default perm
* address.
*/
ret_val = e1000_check_alt_mac_addr_generic(hw);
if (ret_val)
return ret_val;
}
return e1000_read_mac_addr_generic(hw);
}
/**
* e1000_power_down_phy_copper_82571 - Remove link during PHY power down
* @hw: pointer to the HW structure
*
* In the case of a PHY power down to save power, or to turn off link during a
* driver unload, or wake on lan is not enabled, remove the link.
**/
static void e1000_power_down_phy_copper_82571(struct e1000_hw *hw)
{
struct e1000_phy_info *phy = &hw->phy;
struct e1000_mac_info *mac = &hw->mac;
if (!phy->ops.check_reset_block)
return;
/* If the management interface is not enabled, then power down */
if (!(mac->ops.check_mng_mode(hw) || phy->ops.check_reset_block(hw)))
e1000_power_down_phy_copper(hw);
}
/**
* e1000_clear_hw_cntrs_82571 - Clear device specific hardware counters
* @hw: pointer to the HW structure
*
* Clears the hardware counters by reading the counter registers.
**/
static void e1000_clear_hw_cntrs_82571(struct e1000_hw *hw)
{
e1000e_clear_hw_cntrs_base(hw);
er32(PRC64);
er32(PRC127);
er32(PRC255);
er32(PRC511);
er32(PRC1023);
er32(PRC1522);
er32(PTC64);
er32(PTC127);
er32(PTC255);
er32(PTC511);
er32(PTC1023);
er32(PTC1522);
er32(ALGNERRC);
er32(RXERRC);
er32(TNCRS);
er32(CEXTERR);
er32(TSCTC);
er32(TSCTFC);
er32(MGTPRC);
er32(MGTPDC);
er32(MGTPTC);
er32(IAC);
er32(ICRXOC);
er32(ICRXPTC);
er32(ICRXATC);
er32(ICTXPTC);
er32(ICTXATC);
er32(ICTXQEC);
er32(ICTXQMTC);
er32(ICRXDMTC);
}
static const struct e1000_mac_operations e82571_mac_ops = {
/* .check_mng_mode: mac type dependent */
/* .check_for_link: media type dependent */
.id_led_init = e1000e_id_led_init_generic,
.cleanup_led = e1000e_cleanup_led_generic,
.clear_hw_cntrs = e1000_clear_hw_cntrs_82571,
.get_bus_info = e1000e_get_bus_info_pcie,
.set_lan_id = e1000_set_lan_id_multi_port_pcie,
/* .get_link_up_info: media type dependent */
/* .led_on: mac type dependent */
.led_off = e1000e_led_off_generic,
.update_mc_addr_list = e1000e_update_mc_addr_list_generic,
.write_vfta = e1000_write_vfta_generic,
.clear_vfta = e1000_clear_vfta_82571,
.reset_hw = e1000_reset_hw_82571,
.init_hw = e1000_init_hw_82571,
.setup_link = e1000_setup_link_82571,
/* .setup_physical_interface: media type dependent */
.setup_led = e1000e_setup_led_generic,
.config_collision_dist = e1000e_config_collision_dist_generic,
.read_mac_addr = e1000_read_mac_addr_82571,
.rar_set = e1000e_rar_set_generic,
};
static const struct e1000_phy_operations e82_phy_ops_igp = {
.acquire = e1000_get_hw_semaphore_82571,
.check_polarity = e1000_check_polarity_igp,
.check_reset_block = e1000e_check_reset_block_generic,
.commit = NULL,
.force_speed_duplex = e1000e_phy_force_speed_duplex_igp,
.get_cfg_done = e1000_get_cfg_done_82571,
.get_cable_length = e1000e_get_cable_length_igp_2,
.get_info = e1000e_get_phy_info_igp,
.read_reg = e1000e_read_phy_reg_igp,
.release = e1000_put_hw_semaphore_82571,
.reset = e1000e_phy_hw_reset_generic,
.set_d0_lplu_state = e1000_set_d0_lplu_state_82571,
.set_d3_lplu_state = e1000e_set_d3_lplu_state,
.write_reg = e1000e_write_phy_reg_igp,
.cfg_on_link_up = NULL,
};
static const struct e1000_phy_operations e82_phy_ops_m88 = {
.acquire = e1000_get_hw_semaphore_82571,
.check_polarity = e1000_check_polarity_m88,
.check_reset_block = e1000e_check_reset_block_generic,
.commit = e1000e_phy_sw_reset,
.force_speed_duplex = e1000e_phy_force_speed_duplex_m88,
.get_cfg_done = e1000e_get_cfg_done_generic,
.get_cable_length = e1000e_get_cable_length_m88,
.get_info = e1000e_get_phy_info_m88,
.read_reg = e1000e_read_phy_reg_m88,
.release = e1000_put_hw_semaphore_82571,
.reset = e1000e_phy_hw_reset_generic,
.set_d0_lplu_state = e1000_set_d0_lplu_state_82571,
.set_d3_lplu_state = e1000e_set_d3_lplu_state,
.write_reg = e1000e_write_phy_reg_m88,
.cfg_on_link_up = NULL,
};
static const struct e1000_phy_operations e82_phy_ops_bm = {
.acquire = e1000_get_hw_semaphore_82571,
.check_polarity = e1000_check_polarity_m88,
.check_reset_block = e1000e_check_reset_block_generic,
.commit = e1000e_phy_sw_reset,
.force_speed_duplex = e1000e_phy_force_speed_duplex_m88,
.get_cfg_done = e1000e_get_cfg_done_generic,
.get_cable_length = e1000e_get_cable_length_m88,
.get_info = e1000e_get_phy_info_m88,
.read_reg = e1000e_read_phy_reg_bm2,
.release = e1000_put_hw_semaphore_82571,
.reset = e1000e_phy_hw_reset_generic,
.set_d0_lplu_state = e1000_set_d0_lplu_state_82571,
.set_d3_lplu_state = e1000e_set_d3_lplu_state,
.write_reg = e1000e_write_phy_reg_bm2,
.cfg_on_link_up = NULL,
};
static const struct e1000_nvm_operations e82571_nvm_ops = {
.acquire = e1000_acquire_nvm_82571,
.read = e1000e_read_nvm_eerd,
.release = e1000_release_nvm_82571,
.reload = e1000e_reload_nvm_generic,
.update = e1000_update_nvm_checksum_82571,
.valid_led_default = e1000_valid_led_default_82571,
.validate = e1000_validate_nvm_checksum_82571,
.write = e1000_write_nvm_82571,
};
const struct e1000_info e1000_82571_info = {
.mac = e1000_82571,
.flags = FLAG_HAS_HW_VLAN_FILTER
| FLAG_HAS_JUMBO_FRAMES
| FLAG_HAS_WOL
| FLAG_APME_IN_CTRL3
| FLAG_HAS_CTRLEXT_ON_LOAD
| FLAG_HAS_SMART_POWER_DOWN
| FLAG_RESET_OVERWRITES_LAA /* errata */
| FLAG_TARC_SPEED_MODE_BIT /* errata */
| FLAG_APME_CHECK_PORT_B,
.flags2 = FLAG2_DISABLE_ASPM_L1 /* errata 13 */
| FLAG2_DMA_BURST,
.pba = 38,
.max_hw_frame_size = DEFAULT_JUMBO,
.get_variants = e1000_get_variants_82571,
.mac_ops = &e82571_mac_ops,
.phy_ops = &e82_phy_ops_igp,
.nvm_ops = &e82571_nvm_ops,
};
const struct e1000_info e1000_82572_info = {
.mac = e1000_82572,
.flags = FLAG_HAS_HW_VLAN_FILTER
| FLAG_HAS_JUMBO_FRAMES
| FLAG_HAS_WOL
| FLAG_APME_IN_CTRL3
| FLAG_HAS_CTRLEXT_ON_LOAD
| FLAG_TARC_SPEED_MODE_BIT, /* errata */
.flags2 = FLAG2_DISABLE_ASPM_L1 /* errata 13 */
| FLAG2_DMA_BURST,
.pba = 38,
.max_hw_frame_size = DEFAULT_JUMBO,
.get_variants = e1000_get_variants_82571,
.mac_ops = &e82571_mac_ops,
.phy_ops = &e82_phy_ops_igp,
.nvm_ops = &e82571_nvm_ops,
};
const struct e1000_info e1000_82573_info = {
.mac = e1000_82573,
.flags = FLAG_HAS_HW_VLAN_FILTER
| FLAG_HAS_WOL
| FLAG_APME_IN_CTRL3
| FLAG_HAS_SMART_POWER_DOWN
| FLAG_HAS_AMT
| FLAG_HAS_SWSM_ON_LOAD,
.flags2 = FLAG2_DISABLE_ASPM_L1
| FLAG2_DISABLE_ASPM_L0S,
.pba = 20,
.max_hw_frame_size = ETH_FRAME_LEN + ETH_FCS_LEN,
.get_variants = e1000_get_variants_82571,
.mac_ops = &e82571_mac_ops,
.phy_ops = &e82_phy_ops_m88,
.nvm_ops = &e82571_nvm_ops,
};
const struct e1000_info e1000_82574_info = {
.mac = e1000_82574,
.flags = FLAG_HAS_HW_VLAN_FILTER
| FLAG_HAS_MSIX
| FLAG_HAS_JUMBO_FRAMES
| FLAG_HAS_WOL
| FLAG_HAS_HW_TIMESTAMP
| FLAG_APME_IN_CTRL3
| FLAG_HAS_SMART_POWER_DOWN
| FLAG_HAS_AMT
| FLAG_HAS_CTRLEXT_ON_LOAD,
<<<<<<< HEAD
.flags2 = FLAG2_CHECK_PHY_HANG
| FLAG2_DISABLE_ASPM_L0S
| FLAG2_DISABLE_ASPM_L1
| FLAG2_NO_DISABLE_RX,
=======
.flags2 = FLAG2_CHECK_PHY_HANG
| FLAG2_DISABLE_ASPM_L0S
| FLAG2_DISABLE_ASPM_L1
| FLAG2_NO_DISABLE_RX
| FLAG2_DMA_BURST,
>>>>>>> common/android-3.10.y
.pba = 32,
.max_hw_frame_size = DEFAULT_JUMBO,
.get_variants = e1000_get_variants_82571,
.mac_ops = &e82571_mac_ops,
.phy_ops = &e82_phy_ops_bm,
.nvm_ops = &e82571_nvm_ops,
};
const struct e1000_info e1000_82583_info = {
.mac = e1000_82583,
.flags = FLAG_HAS_HW_VLAN_FILTER
| FLAG_HAS_WOL
| FLAG_HAS_HW_TIMESTAMP
| FLAG_APME_IN_CTRL3
| FLAG_HAS_SMART_POWER_DOWN
| FLAG_HAS_AMT
| FLAG_HAS_JUMBO_FRAMES
| FLAG_HAS_CTRLEXT_ON_LOAD,
.flags2 = FLAG2_DISABLE_ASPM_L0S
| FLAG2_NO_DISABLE_RX,
.pba = 32,
.max_hw_frame_size = DEFAULT_JUMBO,
.get_variants = e1000_get_variants_82571,
.mac_ops = &e82571_mac_ops,
.phy_ops = &e82_phy_ops_bm,
.nvm_ops = &e82571_nvm_ops,
};
|
javelinanddart/android_kernel_3.10_ville
|
drivers/net/ethernet/intel/e1000e/82571.c
|
C
|
gpl-2.0
| 55,949
|
/*
* Copyright (C) 2010-2011 Simon Andreas Eugster (simon.eu@gmail.com)
* This file is not a Frei0r plugin but a collection of ideas.
*
* 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 "frei0r.hpp"
#include <iostream>
//#define DEBUG
typedef unsigned char uchar;
struct ABGR {
uchar r;
uchar g;
uchar b;
uchar a;
ABGR blend(const ABGR &other, const float opacity)
{
#ifdef DEBUG
if (opacity < 0 || opacity > 1) {
std::cerr << "Timeout indicator: Opacity must be within 0 and 1!" << std::endl;
}
#endif
const float l = opacity;
const float r = 1-opacity;
ABGR ret;
ret.r = l*r + r*other.r;
ret.g = l*g + r*other.g;
ret.b = l*b + r*other.b;
ret.a = other.a;
return ret;
}
};
union ABGRPixel {
ABGR color;
uint32_t value;
};
class Timeout : public frei0r::filter
{
public:
Timeout(unsigned int width, unsigned int height)
{
register_param(m_time, "time", "Current time");
register_param(m_color, "color", "Indicator colour");
register_param(m_transparency, "transparency", "Indicator transparency");
W = std::min(width, height) / 20;
H = W;
x0 = width-2*W;
y0 = height-H;
}
~Timeout()
{
// Delete member variables if necessary.
}
virtual void update(double time,
uint32_t* out,
const uint32_t* in,
const uint32_t* in2,
const uint32_t* in3)
{
std::copy(in, in + width*height, out);
ABGR col;
col.r = 255*m_color.r;
col.g = 255*m_color.g;
col.b = 255*m_color.b;
col.a = 255;
float yt = y0 - (1-m_time)*H;
ABGR *outAsABGR = (ABGR*) out;
#ifdef DEBUG
#define printcol(x) std::cout << #x ": [ " << (int) x.r << " | " << (int) x.g << " | " << (int) x.b << " ]" << std::endl;
std::cout << "r = " << m_color.r << ", g = " << m_color.g << std::endl;
ABGR blended = col.blend(outAsABGR[0], .5);
printcol(col);
printcol(outAsABGR[0]);
printcol(blended);
#undef printcol
#endif
for (int y = y0; y >= int(yt); y--) {
float factor = 1-m_transparency;
if (y == int(yt)) {
factor *= 1 - (yt-int(yt));
}
for (int x = x0; x < x0+W; x++) {
outAsABGR[width*y + x] = col.blend(outAsABGR[width*y + x], factor);
}
}
}
private:
// The various f0r_params are adjustable parameters.
// This one determines the size of the black bar in this example.
f0r_param_double m_time;
f0r_param_color m_color;
f0r_param_double m_transparency;
unsigned int x0, y0;
unsigned int W , H ;
};
frei0r::construct<Timeout> plugin("Timeout indicator",
"Timeout indicators e.g. for slides.",
"Simon A. Eugster",
0,2,
F0R_COLOR_MODEL_RGBA8888);
|
modulexcite/frei0r
|
src/filter/timeout/timeout.cpp
|
C++
|
gpl-2.0
| 3,702
|
/*
* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
//#define USE_ERROR
//#define USE_TRACE
#if USE_PLATFORM_MIDI_IN == TRUE
#include "PLATFORM_API_MacOSX_MidiUtils.h"
char* MIDI_IN_GetErrorStr(INT32 err) {
return (char *) MIDI_Utils_GetErrorMsg((int) err);
}
INT32 MIDI_IN_GetNumDevices() {
return MIDI_Utils_GetNumDevices(MIDI_IN);
}
INT32 MIDI_IN_GetDeviceName(INT32 deviceID, char *name, UINT32 nameLength) {
return MIDI_Utils_GetDeviceName(MIDI_IN, deviceID, name, nameLength);
}
INT32 MIDI_IN_GetDeviceVendor(INT32 deviceID, char *name, UINT32 nameLength) {
return MIDI_Utils_GetDeviceVendor(MIDI_IN, deviceID, name, nameLength);
}
INT32 MIDI_IN_GetDeviceDescription(INT32 deviceID, char *name, UINT32 nameLength) {
return MIDI_Utils_GetDeviceDescription(MIDI_IN, deviceID, name, nameLength);
}
INT32 MIDI_IN_GetDeviceVersion(INT32 deviceID, char *name, UINT32 nameLength) {
return MIDI_Utils_GetDeviceVersion(MIDI_IN, deviceID, name, nameLength);
}
INT32 MIDI_IN_OpenDevice(INT32 deviceID, MidiDeviceHandle** handle) {
TRACE0("MIDI_IN_OpenDevice\n");
return
MIDI_Utils_OpenDevice(MIDI_IN, deviceID, (MacMidiDeviceHandle**) handle,
MIDI_IN_MESSAGE_QUEUE_SIZE,
MIDI_IN_LONG_QUEUE_SIZE,
MIDI_IN_LONG_MESSAGE_SIZE);
}
INT32 MIDI_IN_CloseDevice(MidiDeviceHandle* handle) {
TRACE0("MIDI_IN_CloseDevice\n");
return MIDI_Utils_CloseDevice((MacMidiDeviceHandle*) handle);
}
INT32 MIDI_IN_StartDevice(MidiDeviceHandle* handle) {
TRACE0("MIDI_IN_StartDevice\n");
return MIDI_Utils_StartDevice((MacMidiDeviceHandle*) handle);
}
INT32 MIDI_IN_StopDevice(MidiDeviceHandle* handle) {
TRACE0("MIDI_IN_StopDevice\n");
return MIDI_Utils_StopDevice((MacMidiDeviceHandle*) handle);
}
INT64 MIDI_IN_GetTimeStamp(MidiDeviceHandle* handle) {
return MIDI_Utils_GetTimeStamp((MacMidiDeviceHandle*) handle);
}
/* read the next message from the queue */
MidiMessage* MIDI_IN_GetMessage(MidiDeviceHandle* handle) {
if (handle == NULL) {
return NULL;
}
while (handle->queue != NULL && handle->platformData != NULL) {
MidiMessage* msg = MIDI_QueueRead(handle->queue);
if (msg != NULL) {
//fprintf(stdout, "GetMessage returns index %d\n", msg->data.l.index); fflush(stdout);
return msg;
}
TRACE0("MIDI_IN_GetMessage: before waiting\n");
handle->isWaiting = TRUE;
MIDI_WaitOnConditionVariable(handle->platformData, handle->queue->lock);
handle->isWaiting = FALSE;
TRACE0("MIDI_IN_GetMessage: waiting finished\n");
}
return NULL;
}
void MIDI_IN_ReleaseMessage(MidiDeviceHandle* handle, MidiMessage* msg) {
if (handle == NULL || handle->queue == NULL) {
return;
}
MIDI_QueueRemove(handle->queue, TRUE /*onlyLocked*/);
}
#endif /* USE_PLATFORM_MIDI_IN */
|
kgilmer/openjdk-7-mermaid
|
src/macosx/native/com/sun/media/sound/PLATFORM_API_MacOSX_MidiIn.c
|
C
|
gpl-2.0
| 4,113
|
/*
* Copyright(c) 2012, Analogix Semiconductor. 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.
*
*/
#ifndef __SP_TX_DRV_H
#define __SP_TX_DRV_H
#define FALSE 0
#define TRUE 1
#define MAX_BUF_CNT 16
#define VID_DVI_MODE 0x00
#define VID_HDMI_MODE 0x01
#define VIDEO_STABLE_TH 2
#define AUDIO_STABLE_TH 1
#define SCDT_EXPIRE_TH 10
#define SP_TX_HDCP_FAIL_TH 10
#define SP_TX_DS_VID_STB_TH 20
#define GET_HDMI_CONNECTION_MAX_TRIES 6
/* */
extern unchar bedid_extblock[128];
extern unchar bedid_firstblock[128];
extern unchar slimport_link_bw;
#ifdef SP_REGISTER_SET_TEST
extern unchar val_SP_TX_LT_CTRL_REG[20];
extern bool val_SP_TX_LT_CTRL_REG_write_flag[20];
#endif
enum SP_TX_System_State {
STATE_INIT = 1,
STATE_CABLE_PLUG,
STATE_PARSE_EDID,
STATE_CONFIG_HDMI,
STATE_LINK_TRAINING,
STATE_CONFIG_OUTPUT,
STATE_HDCP_AUTH,
STATE_PLAY_BACK
};
enum HDMI_RX_System_State {
HDMI_CLOCK_DET = 1,
HDMI_SYNC_DET,
HDMI_VIDEO_CONFIG,
HDMI_AUDIO_CONFIG,
HDMI_PLAYBACK
};
enum HDMI_color_depth {
Hdmi_legacy,
Hdmi_24bit,
Hdmi_30bit,
Hdmi_36bit
};
enum SP_TX_POWER_BLOCK {
SP_TX_PWR_REG,
SP_TX_PWR_HDCP,
SP_TX_PWR_AUDIO,
SP_TX_PWR_VIDEO,
SP_TX_PWR_LINK,
SP_TX_PWR_TOTAL
};
enum SP_TX_SEND_MSG {
MSG_INPUT_HDMI,
MSG_INPUT_DVI,
MSG_CLEAR_IRQ,
};
enum PACKETS_TYPE {
AVI_PACKETS,
SPD_PACKETS,
MPEG_PACKETS,
VSI_PACKETS,
AUDIF_PACKETS
};
struct Packet_AVI {
unchar AVI_data[13];
};
struct Packet_SPD {
unchar SPD_data[25];
};
struct Packet_MPEG {
unchar MPEG_data[13];
};
struct AudiInfoframe {
unchar type;
unchar version;
unchar length;
unchar pb_byte[11];
};
enum INTStatus {
COMMON_INT_1 = 0,
COMMON_INT_2 = 1,
COMMON_INT_3 = 2,
COMMON_INT_4 = 3,
SP_INT_STATUS = 6
};
enum SP_LINK_BW {
BW_54G = 0x14,
BW_27G = 0x0A,
BW_162G = 0x06,
BW_NULL = 0x00
};
enum RX_CBL_TYPE {
RX_NULL = 0x00,
RX_HDMI = 0x01,
RX_DP = 0x02,
RX_VGA_GEN = 0x03,
RX_VGA_9832 = 0x04,
};
void sp_tx_variable_init(void);
void sp_tx_initialization(void);
void sp_tx_show_infomation(void);
void hdmi_rx_show_video_info(void);
void sp_tx_power_down(enum SP_TX_POWER_BLOCK sp_tx_pd_block);
void sp_tx_power_on(enum SP_TX_POWER_BLOCK sp_tx_pd_block);
void sp_tx_avi_setup(void);
void sp_tx_clean_hdcp(void);
unchar sp_tx_chip_located(void);
void sp_tx_vbus_poweron(void);
void sp_tx_vbus_powerdown(void);
void sp_tx_rst_aux(void);
void sp_tx_config_packets(enum PACKETS_TYPE bType);
unchar sp_tx_hw_link_training(void);
unchar sp_tx_lt_pre_config(void);
void sp_tx_video_mute(unchar enable);
void sp_tx_aux_polling_enable(bool benable);
void sp_tx_set_colorspace(void);
void sp_tx_int_irq_handler(void);
void sp_tx_send_message(enum SP_TX_SEND_MSG message);
void sp_tx_hdcp_process(void);
void sp_tx_set_sys_state(enum SP_TX_System_State ss);
unchar sp_tx_get_cable_type(bool bdelay);
bool sp_tx_get_dp_connection(void);
bool sp_tx_get_hdmi_connection(void);
bool sp_tx_get_vga_connection(void);
unchar sp_tx_get_downstream_type(void);
unchar sp_tx_get_downstream_connection(enum RX_CBL_TYPE cabletype);
void sp_tx_edid_read(void);
uint sp_tx_link_err_check(void);
void sp_tx_eye_diagram_test(void);
void sp_tx_phy_auto_test(void);
void sp_tx_enable_video_input(unchar enable);
unchar sp_tx_aux_dpcdwrite_bytes(unchar addrh, unchar addrm,
unchar addrl, unchar cCount, unchar *pBuf);
unchar sp_tx_aux_dpcdread_bytes(unchar addrh, unchar addrm,
unchar addrl, unchar cCount, unchar *pBuf);
/* */
/* */
/* */
void sp_tx_config_hdmi_input(void);
void hdmi_rx_set_hpd(unchar enable);
void hdmi_rx_initialization(void);
void hdmi_rx_int_irq_handler(void);
void hdmi_rx_set_termination(unchar enable);
#endif
|
sleekmason/LG-V510-Kitkat
|
drivers/misc/slimport_anx7808/slimport_tx_drv.h
|
C
|
gpl-2.0
| 4,257
|
#undef CONFIG_INPUT_UINPUT
|
vickylinuxer/at91sam9263-kernel
|
include/3g/config/input/uinput.h
|
C
|
gpl-2.0
| 27
|
<?php
/**
* @version $Id: installer.php 19013 2012-11-28 04:48:47Z thailv $
* @package JSNUniform
* @subpackage Controller
* @author JoomlaShine Team <support@joomlashine.com>
* @copyright Copyright (C) 2012 JoomlaShine.com. All Rights Reserved.
* @license GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html
*
* Websites: http://www.joomlashine.com
* Technical Support: Feedback - http://www.joomlashine.com/contact-us/get-support.html
*/
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// Import JSN Installer library
require_once JPATH_COMPONENT_ADMINISTRATOR . '/libraries/joomlashine/installer/controller.php';
/**
* Installer controller
*
* @package JSN_Uniform
* @subpackage Controller
* @since 1.1.0
*/
class JSNUniformControllerInstaller extends JSNInstallerController
{
}
|
ducdongmg/joomla_tut25
|
administrator/components/com_uniform/controllers/installer.php
|
PHP
|
gpl-2.0
| 875
|
/* Copyright (c) 2002,2007-2014, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/module.h>
#include <linux/uaccess.h>
#include <linux/vmalloc.h>
#include <linux/ioctl.h>
#include <linux/sched.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/delay.h>
#include <linux/of_coresight.h>
#include <linux/input.h>
#include <mach/socinfo.h>
#include <mach/msm_bus_board.h>
#include <mach/msm_bus.h>
#include "kgsl.h"
#include "kgsl_pwrscale.h"
#include "kgsl_cffdump.h"
#include "kgsl_sharedmem.h"
#include "kgsl_iommu.h"
#include "adreno.h"
#include "adreno_pm4types.h"
#include "adreno_trace.h"
#include "a2xx_reg.h"
#include "a3xx_reg.h"
#define DRIVER_VERSION_MAJOR 3
#define DRIVER_VERSION_MINOR 1
/* Number of times to try hard reset */
#define NUM_TIMES_RESET_RETRY 5
/* Adreno MH arbiter config*/
#define ADRENO_CFG_MHARB \
(0x10 \
| (0 << MH_ARBITER_CONFIG__SAME_PAGE_GRANULARITY__SHIFT) \
| (1 << MH_ARBITER_CONFIG__L1_ARB_ENABLE__SHIFT) \
| (1 << MH_ARBITER_CONFIG__L1_ARB_HOLD_ENABLE__SHIFT) \
| (0 << MH_ARBITER_CONFIG__L2_ARB_CONTROL__SHIFT) \
| (1 << MH_ARBITER_CONFIG__PAGE_SIZE__SHIFT) \
| (1 << MH_ARBITER_CONFIG__TC_REORDER_ENABLE__SHIFT) \
| (1 << MH_ARBITER_CONFIG__TC_ARB_HOLD_ENABLE__SHIFT) \
| (0 << MH_ARBITER_CONFIG__IN_FLIGHT_LIMIT_ENABLE__SHIFT) \
| (0x8 << MH_ARBITER_CONFIG__IN_FLIGHT_LIMIT__SHIFT) \
| (1 << MH_ARBITER_CONFIG__CP_CLNT_ENABLE__SHIFT) \
| (1 << MH_ARBITER_CONFIG__VGT_CLNT_ENABLE__SHIFT) \
| (1 << MH_ARBITER_CONFIG__TC_CLNT_ENABLE__SHIFT) \
| (1 << MH_ARBITER_CONFIG__RB_CLNT_ENABLE__SHIFT) \
| (1 << MH_ARBITER_CONFIG__PA_CLNT_ENABLE__SHIFT))
#define ADRENO_MMU_CONFIG \
(0x01 \
| (MMU_CONFIG << MH_MMU_CONFIG__RB_W_CLNT_BEHAVIOR__SHIFT) \
| (MMU_CONFIG << MH_MMU_CONFIG__CP_W_CLNT_BEHAVIOR__SHIFT) \
| (MMU_CONFIG << MH_MMU_CONFIG__CP_R0_CLNT_BEHAVIOR__SHIFT) \
| (MMU_CONFIG << MH_MMU_CONFIG__CP_R1_CLNT_BEHAVIOR__SHIFT) \
| (MMU_CONFIG << MH_MMU_CONFIG__CP_R2_CLNT_BEHAVIOR__SHIFT) \
| (MMU_CONFIG << MH_MMU_CONFIG__CP_R3_CLNT_BEHAVIOR__SHIFT) \
| (MMU_CONFIG << MH_MMU_CONFIG__CP_R4_CLNT_BEHAVIOR__SHIFT) \
| (MMU_CONFIG << MH_MMU_CONFIG__VGT_R0_CLNT_BEHAVIOR__SHIFT) \
| (MMU_CONFIG << MH_MMU_CONFIG__VGT_R1_CLNT_BEHAVIOR__SHIFT) \
| (MMU_CONFIG << MH_MMU_CONFIG__TC_R_CLNT_BEHAVIOR__SHIFT) \
| (MMU_CONFIG << MH_MMU_CONFIG__PA_W_CLNT_BEHAVIOR__SHIFT))
#define KGSL_LOG_LEVEL_DEFAULT 3
static void adreno_input_work(struct work_struct *work);
/*
* The default values for the simpleondemand governor are 90 and 5,
* we use different values here.
* They have to be tuned and compare with the tz governor anyway.
*/
static struct devfreq_simple_ondemand_data adreno_ondemand_data = {
.upthreshold = 80,
.downdifferential = 20,
};
static struct devfreq_msm_adreno_tz_data adreno_tz_data = {
.bus = {
.max = 533,
},
.device_id = KGSL_DEVICE_3D0,
};
static struct devfreq_msm_adreno_tz_data adreno_conservative_data = {
.device_id = KGSL_DEVICE_3D0,
};
static const struct devfreq_governor_data adreno_governors[] = {
{ .name = "simple_ondemand", .data = &adreno_ondemand_data },
{ .name = "msm-adreno-tz", .data = &adreno_tz_data },
{ .name = "conservative", .data = &adreno_conservative_data },
};
static const struct kgsl_functable adreno_functable;
static struct adreno_device device_3d0 = {
.dev = {
KGSL_DEVICE_COMMON_INIT(device_3d0.dev),
.pwrscale = KGSL_PWRSCALE_INIT(adreno_governors,
ARRAY_SIZE(adreno_governors)),
.name = DEVICE_3D0_NAME,
.id = KGSL_DEVICE_3D0,
.mh = {
.mharb = ADRENO_CFG_MHARB,
/* Remove 1k boundary check in z470 to avoid a GPU
* hang. Notice that this solution won't work if
* both EBI and SMI are used
*/
.mh_intf_cfg1 = 0x00032f07,
/* turn off memory protection unit by setting
acceptable physical address range to include
all pages. */
.mpu_base = 0x00000000,
.mpu_range = 0xFFFFF000,
},
.mmu = {
.config = ADRENO_MMU_CONFIG,
},
.pwrctrl = {
.irq_name = KGSL_3D0_IRQ,
},
.iomemname = KGSL_3D0_REG_MEMORY,
.shadermemname = KGSL_3D0_SHADER_MEMORY,
.ftbl = &adreno_functable,
.cmd_log = KGSL_LOG_LEVEL_DEFAULT,
.ctxt_log = KGSL_LOG_LEVEL_DEFAULT,
.drv_log = KGSL_LOG_LEVEL_DEFAULT,
.mem_log = KGSL_LOG_LEVEL_DEFAULT,
.pwr_log = KGSL_LOG_LEVEL_DEFAULT,
.pm_dump_enable = 0,
},
.gmem_base = 0,
.gmem_size = SZ_256K,
.pfp_fw = NULL,
.pm4_fw = NULL,
.wait_timeout = 0, /* in milliseconds, 0 means disabled */
.ib_check_level = 0,
.ft_policy = KGSL_FT_DEFAULT_POLICY,
.ft_pf_policy = KGSL_FT_PAGEFAULT_DEFAULT_POLICY,
.fast_hang_detect = 1,
.long_ib_detect = 1,
.input_work = __WORK_INITIALIZER(device_3d0.input_work,
adreno_input_work),
};
unsigned int ft_detect_regs[FT_DETECT_REGS_COUNT];
/*
* This is the master list of all GPU cores that are supported by this
* driver.
*/
#define ANY_ID (~0)
#define NO_VER (~0)
static const struct {
enum adreno_gpurev gpurev;
unsigned int core, major, minor, patchid;
const char *pm4fw;
const char *pfpfw;
struct adreno_gpudev *gpudev;
unsigned int istore_size;
unsigned int pix_shader_start;
/* Size of an instruction in dwords */
unsigned int instruction_size;
/* size of gmem for gpu*/
unsigned int gmem_size;
/* version of pm4 microcode that supports sync_lock
between CPU and GPU for IOMMU-v0 programming */
unsigned int sync_lock_pm4_ver;
/* version of pfp microcode that supports sync_lock
between CPU and GPU for IOMMU-v0 programming */
unsigned int sync_lock_pfp_ver;
/* PM4 jump table index */
unsigned int pm4_jt_idx;
/* PM4 jump table load addr */
unsigned int pm4_jt_addr;
/* PFP jump table index */
unsigned int pfp_jt_idx;
/* PFP jump table load addr */
unsigned int pfp_jt_addr;
/* PM4 bootstrap loader size */
unsigned int pm4_bstrp_size;
/* PFP bootstrap loader size */
unsigned int pfp_bstrp_size;
/* PFP bootstrap loader supported version */
unsigned int pfp_bstrp_ver;
} adreno_gpulist[] = {
{ ADRENO_REV_A200, 0, 2, ANY_ID, ANY_ID,
"yamato_pm4.fw", "yamato_pfp.fw", &adreno_a2xx_gpudev,
512, 384, 3, SZ_256K, NO_VER, NO_VER },
{ ADRENO_REV_A203, 0, 1, 1, ANY_ID,
"yamato_pm4.fw", "yamato_pfp.fw", &adreno_a2xx_gpudev,
512, 384, 3, SZ_256K, NO_VER, NO_VER },
{ ADRENO_REV_A205, 0, 1, 0, ANY_ID,
"yamato_pm4.fw", "yamato_pfp.fw", &adreno_a2xx_gpudev,
512, 384, 3, SZ_256K, NO_VER, NO_VER },
{ ADRENO_REV_A220, 2, 1, ANY_ID, ANY_ID,
"leia_pm4_470.fw", "leia_pfp_470.fw", &adreno_a2xx_gpudev,
512, 384, 3, SZ_512K, NO_VER, NO_VER },
/*
* patchlevel 5 (8960v2) needs special pm4 firmware to work around
* a hardware problem.
*/
{ ADRENO_REV_A225, 2, 2, 0, 5,
"a225p5_pm4.fw", "a225_pfp.fw", &adreno_a2xx_gpudev,
1536, 768, 3, SZ_512K, NO_VER, NO_VER },
{ ADRENO_REV_A225, 2, 2, 0, 6,
"a225_pm4.fw", "a225_pfp.fw", &adreno_a2xx_gpudev,
1536, 768, 3, SZ_512K, 0x225011, 0x225002 },
{ ADRENO_REV_A225, 2, 2, ANY_ID, ANY_ID,
"a225_pm4.fw", "a225_pfp.fw", &adreno_a2xx_gpudev,
1536, 768, 3, SZ_512K, 0x225011, 0x225002 },
/* A3XX doesn't use the pix_shader_start */
{ ADRENO_REV_A305, 3, 0, 5, 0,
"a300_pm4.fw", "a300_pfp.fw", &adreno_a3xx_gpudev,
512, 0, 2, SZ_256K, 0x3FF037, 0x3FF016 },
/* A3XX doesn't use the pix_shader_start */
{ ADRENO_REV_A320, 3, 2, ANY_ID, ANY_ID,
"a300_pm4.fw", "a300_pfp.fw", &adreno_a3xx_gpudev,
512, 0, 2, SZ_512K, 0x3FF037, 0x3FF016 },
{ ADRENO_REV_A330, 3, 3, 0, ANY_ID,
"a330_pm4.fw", "a330_pfp.fw", &adreno_a3xx_gpudev,
512, 0, 2, SZ_1M, NO_VER, NO_VER, 0x8AD, 0x2E4, 0x201, 0x200,
0x6, 0x20, 0x330020 },
{ ADRENO_REV_A305B, 3, 0, 5, 0x10,
"a330_pm4.fw", "a330_pfp.fw", &adreno_a3xx_gpudev,
512, 0, 2, SZ_128K, NO_VER, NO_VER, 0x8AD, 0x2E4,
0x201, 0x200 },
/* 8226v2 */
{ ADRENO_REV_A305B, 3, 0, 5, 0x12,
"a330_pm4.fw", "a330_pfp.fw", &adreno_a3xx_gpudev,
512, 0, 2, SZ_128K, NO_VER, NO_VER, 0x8AD, 0x2E4,
0x201, 0x200 },
{ ADRENO_REV_A305C, 3, 0, 5, 0x20,
"a300_pm4.fw", "a300_pfp.fw", &adreno_a3xx_gpudev,
512, 0, 2, SZ_128K, 0x3FF037, 0x3FF016 },
};
/* Nice level for the higher priority GPU start thread */
static int _wake_nice = -7;
/* Number of milliseconds to stay active active after a wake on touch */
static unsigned int _wake_timeout = 100;
/*
* A workqueue callback responsible for actually turning on the GPU after a
* touch event. kgsl_pwrctrl_wake() is used without any active_count protection
* to avoid the need to maintain state. Either somebody will start using the
* GPU or the idle timer will fire and put the GPU back into slumber
*/
static void adreno_input_work(struct work_struct *work)
{
struct adreno_device *adreno_dev = container_of(work,
struct adreno_device, input_work);
struct kgsl_device *device = &adreno_dev->dev;
kgsl_mutex_lock(&device->mutex, &device->mutex_owner);
device->flags |= KGSL_FLAG_WAKE_ON_TOUCH;
/*
* Don't schedule adreno_start in a high priority workqueue, we are
* already in a workqueue which should be sufficient
*/
kgsl_pwrctrl_wake(device, 0);
/*
* When waking up from a touch event we want to stay active long enough
* for the user to send a draw command. The default idle timer timeout
* is shorter than we want so go ahead and push the idle timer out
* further for this special case
*/
mod_timer(&device->idle_timer,
jiffies + msecs_to_jiffies(_wake_timeout));
kgsl_mutex_unlock(&device->mutex, &device->mutex_owner);
}
/*
* Process input events and schedule work if needed. At this point we are only
* interested in groking EV_ABS touchscreen events
*/
static void adreno_input_event(struct input_handle *handle, unsigned int type,
unsigned int code, int value)
{
struct kgsl_device *device = handle->handler->private;
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
/*
* Only queue the work under certain circumstances: we have to be in
* slumber, the event has to be EV_EBS and we had to have processed an
* IB since the last time we called wake on touch.
*/
if ((type == EV_ABS) &&
!(device->flags & KGSL_FLAG_WAKE_ON_TOUCH) &&
(device->state == KGSL_STATE_SLUMBER))
schedule_work(&adreno_dev->input_work);
}
static int adreno_input_connect(struct input_handler *handler,
struct input_dev *dev, const struct input_device_id *id)
{
struct input_handle *handle;
int ret;
handle = kzalloc(sizeof(*handle), GFP_KERNEL);
if (handle == NULL)
return -ENOMEM;
handle->dev = dev;
handle->handler = handler;
handle->name = handler->name;
ret = input_register_handle(handle);
if (ret) {
kfree(handle);
return ret;
}
ret = input_open_device(handle);
if (ret) {
input_unregister_handle(handle);
kfree(handle);
}
return ret;
}
static void adreno_input_disconnect(struct input_handle *handle)
{
input_close_device(handle);
input_unregister_handle(handle);
kfree(handle);
}
/*
* We are only interested in EV_ABS events so only register handlers for those
* input devices that have EV_ABS events
*/
static const struct input_device_id adreno_input_ids[] = {
{
.flags = INPUT_DEVICE_ID_MATCH_EVBIT,
.evbit = { BIT_MASK(EV_ABS) },
.absbit = { [BIT_WORD(ABS_MT_POSITION_X)] =
BIT_MASK(ABS_MT_POSITION_X) |
BIT_MASK(ABS_MT_POSITION_Y) |
BIT_MASK(ABS_MT_TRACKING_ID) },
},
{ },
};
static struct input_handler adreno_input_handler = {
.event = adreno_input_event,
.connect = adreno_input_connect,
.disconnect = adreno_input_disconnect,
.name = "kgsl",
.id_table = adreno_input_ids,
};
/**
* adreno_perfcounter_init: Reserve kernel performance counters
* @device: device to configure
*
* The kernel needs/wants a certain group of performance counters for
* its own activities. Reserve these performance counters at init time
* to ensure that they are always reserved for the kernel. The performance
* counters used by the kernel can be obtained by the user, but these
* performance counters will remain active as long as the device is alive.
*/
static int adreno_perfcounter_init(struct kgsl_device *device)
{
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
if (adreno_dev->gpudev->perfcounter_init)
return adreno_dev->gpudev->perfcounter_init(adreno_dev);
return 0;
};
/**
* adreno_perfcounter_close: Release counters initialized by
* adreno_perfcounter_init
* @device: device to realease counters for
*
*/
static void adreno_perfcounter_close(struct kgsl_device *device)
{
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
if (adreno_dev->gpudev->perfcounter_close)
return adreno_dev->gpudev->perfcounter_close(adreno_dev);
}
/**
* adreno_perfcounter_start: Enable performance counters
* @adreno_dev: Adreno device to configure
*
* Ensure all performance counters are enabled that are allocated. Since
* the device was most likely stopped, we can't trust that the counters
* are still valid so make it so.
* Returns 0 on success else error code
*/
static int adreno_perfcounter_start(struct adreno_device *adreno_dev)
{
struct adreno_perfcounters *counters = adreno_dev->gpudev->perfcounters;
struct adreno_perfcount_group *group;
unsigned int i, j;
int ret = 0;
if (NULL == counters)
return 0;
/* group id iter */
for (i = 0; i < counters->group_count; i++) {
group = &(counters->groups[i]);
/* countable iter */
for (j = 0; j < group->reg_count; j++) {
if (group->regs[j].countable ==
KGSL_PERFCOUNTER_NOT_USED ||
group->regs[j].countable ==
KGSL_PERFCOUNTER_BROKEN)
continue;
if (adreno_dev->gpudev->perfcounter_enable)
ret = adreno_dev->gpudev->perfcounter_enable(
adreno_dev, i, j,
group->regs[j].countable);
if (ret)
goto done;
}
}
done:
return ret;
}
/**
* adreno_perfcounter_read_group() - Determine which countables are in counters
* @adreno_dev: Adreno device to configure
* @reads: List of kgsl_perfcounter_read_groups
* @count: Length of list
*
* Read the performance counters for the groupid/countable pairs and return
* the 64 bit result for each pair
*/
int adreno_perfcounter_read_group(struct adreno_device *adreno_dev,
struct kgsl_perfcounter_read_group __user *reads, unsigned int count)
{
struct adreno_perfcounters *counters = adreno_dev->gpudev->perfcounters;
struct kgsl_device *device = &adreno_dev->dev;
struct adreno_perfcount_group *group;
struct kgsl_perfcounter_read_group *list = NULL;
unsigned int i, j;
int ret = 0;
if (NULL == counters)
return -EINVAL;
/* sanity check for later */
if (!adreno_dev->gpudev->perfcounter_read)
return -EINVAL;
/* sanity check params passed in */
if (reads == NULL || count == 0 || count > 100)
return -EINVAL;
list = kmalloc(sizeof(struct kgsl_perfcounter_read_group) * count,
GFP_KERNEL);
if (!list)
return -ENOMEM;
if (copy_from_user(list, reads,
sizeof(struct kgsl_perfcounter_read_group) * count)) {
ret = -EFAULT;
goto done;
}
kgsl_mutex_lock(&device->mutex, &device->mutex_owner);
ret = kgsl_active_count_get(device);
if (ret) {
kgsl_mutex_unlock(&device->mutex, &device->mutex_owner);
goto done;
}
/* list iterator */
for (j = 0; j < count; j++) {
list[j].value = 0;
/* Verify that the group ID is within range */
if (list[j].groupid >= counters->group_count) {
ret = -EINVAL;
break;
}
group = &(counters->groups[list[j].groupid]);
/* group/counter iterator */
for (i = 0; i < group->reg_count; i++) {
if (group->regs[i].countable == list[j].countable) {
list[j].value =
adreno_dev->gpudev->perfcounter_read(
adreno_dev, list[j].groupid, i);
break;
}
}
}
kgsl_active_count_put(device);
kgsl_mutex_unlock(&device->mutex, &device->mutex_owner);
/* write the data */
if (ret == 0)
ret = copy_to_user(reads, list,
sizeof(struct kgsl_perfcounter_read_group) * count);
done:
kfree(list);
return ret;
}
/**
* adreno_perfcounter_get_groupid() - Get the performance counter ID
* @adreno_dev: Adreno device
* @name: Performance counter group name string
*
* Get the groupid based on the name and return this ID
*/
int adreno_perfcounter_get_groupid(struct adreno_device *adreno_dev,
const char *name)
{
struct adreno_perfcounters *counters = adreno_dev->gpudev->perfcounters;
struct adreno_perfcount_group *group;
int i;
if (name == NULL)
return -EINVAL;
if (NULL == counters)
return -EINVAL;
for (i = 0; i < counters->group_count; ++i) {
group = &(counters->groups[i]);
if (!strcmp(group->name, name))
return i;
}
return -EINVAL;
}
/**
* adreno_perfcounter_get_name() - Get the group name
* @adreno_dev: Adreno device
* @groupid: Desired performance counter groupid
*
* Get the name based on the groupid and return it
*/
const char *adreno_perfcounter_get_name(struct adreno_device *adreno_dev,
unsigned int groupid)
{
struct adreno_perfcounters *counters = adreno_dev->gpudev->perfcounters;
if (NULL == counters)
return NULL;
if (groupid >= counters->group_count)
return NULL;
return counters->groups[groupid].name;
}
/**
* adreno_perfcounter_query_group: Determine which countables are in counters
* @adreno_dev: Adreno device to configure
* @groupid: Desired performance counter group
* @countables: Return list of all countables in the groups counters
* @count: Max length of the array
* @max_counters: max counters for the groupid
*
* Query the current state of counters for the group.
*/
int adreno_perfcounter_query_group(struct adreno_device *adreno_dev,
unsigned int groupid, unsigned int *countables, unsigned int count,
unsigned int *max_counters)
{
struct adreno_perfcounters *counters = adreno_dev->gpudev->perfcounters;
struct kgsl_device *device = &adreno_dev->dev;
struct adreno_perfcount_group *group;
unsigned int i, t;
int ret;
unsigned int *buf;
*max_counters = 0;
if (NULL == counters)
return -EINVAL;
if (groupid >= counters->group_count)
return -EINVAL;
kgsl_mutex_lock(&device->mutex, &device->mutex_owner);
group = &(counters->groups[groupid]);
*max_counters = group->reg_count;
/*
* if NULL countable or *count of zero, return max reg_count in
* *max_counters and return success
*/
if (countables == NULL || count == 0) {
kgsl_mutex_unlock(&device->mutex, &device->mutex_owner);
return 0;
}
t = min_t(int, group->reg_count, count);
buf = kmalloc(t * sizeof(unsigned int), GFP_KERNEL);
if (buf == NULL) {
kgsl_mutex_unlock(&device->mutex, &device->mutex_owner);
return -ENOMEM;
}
for (i = 0; i < t; i++)
buf[i] = group->regs[i].countable;
kgsl_mutex_unlock(&device->mutex, &device->mutex_owner);
ret = copy_to_user(countables, buf, sizeof(unsigned int) * t);
kfree(buf);
return ret;
}
static inline void refcount_group(struct adreno_perfcount_group *group,
unsigned int reg, unsigned int flags,
unsigned int *lo, unsigned int *hi)
{
if (flags & PERFCOUNTER_FLAG_KERNEL)
group->regs[reg].kernelcount++;
else
group->regs[reg].usercount++;
if (lo)
*lo = group->regs[reg].offset;
if (hi)
*hi = group->regs[reg].offset_hi;
}
/**
* adreno_perfcounter_get: Try to put a countable in an available counter
* @adreno_dev: Adreno device to configure
* @groupid: Desired performance counter group
* @countable: Countable desired to be in a counter
* @offset: Return offset of the LO counter assigned
* @offset_hi: Return offset of the HI counter assigned
* @flags: Used to setup kernel perf counters
*
* Try to place a countable in an available counter. If the countable is
* already in a counter, reference count the counter/countable pair resource
* and return success
*/
int adreno_perfcounter_get(struct adreno_device *adreno_dev,
unsigned int groupid, unsigned int countable, unsigned int *offset,
unsigned int *offset_hi, unsigned int flags)
{
struct adreno_perfcounters *counters = adreno_dev->gpudev->perfcounters;
struct adreno_perfcount_group *group;
unsigned int empty = -1;
int ret = 0;
/* always clear return variables */
if (offset)
*offset = 0;
if (offset_hi)
*offset_hi = 0;
if (NULL == counters)
return -EINVAL;
if (groupid >= counters->group_count)
return -EINVAL;
group = &(counters->groups[groupid]);
if (group->flags & ADRENO_PERFCOUNTER_GROUP_FIXED) {
/*
* In fixed groups the countable equals the fixed register the
* user wants. First make sure it is in range
*/
if (countable >= group->reg_count)
return -EINVAL;
/* If it is already reserved, just increase the refcounts */
if ((group->regs[countable].kernelcount != 0) ||
(group->regs[countable].usercount != 0)) {
refcount_group(group, countable, flags,
offset, offset_hi);
return 0;
}
empty = countable;
} else {
unsigned int i;
/*
* Check if the countable is already associated with a counter.
* Refcount and return the offset, otherwise, try and find an
* empty counter and assign the countable to it.
*/
for (i = 0; i < group->reg_count; i++) {
if (group->regs[i].countable == countable) {
refcount_group(group, i, flags,
offset, offset_hi);
return 0;
} else if (group->regs[i].countable ==
KGSL_PERFCOUNTER_NOT_USED) {
/* keep track of unused counter */
empty = i;
}
}
}
/* no available counters, so do nothing else */
if (empty == -1)
return -EBUSY;
/* enable the new counter */
ret = adreno_dev->gpudev->perfcounter_enable(adreno_dev, groupid, empty,
countable);
if (ret)
return ret;
/* initialize the new counter */
group->regs[empty].countable = countable;
/* set initial kernel and user count */
if (flags & PERFCOUNTER_FLAG_KERNEL) {
group->regs[empty].kernelcount = 1;
group->regs[empty].usercount = 0;
} else {
group->regs[empty].kernelcount = 0;
group->regs[empty].usercount = 1;
}
if (offset)
*offset = group->regs[empty].offset;
if (offset_hi)
*offset_hi = group->regs[empty].offset_hi;
return ret;
}
/**
* adreno_perfcounter_put: Release a countable from counter resource
* @adreno_dev: Adreno device to configure
* @groupid: Desired performance counter group
* @countable: Countable desired to be freed from a counter
* @flags: Flag to determine if kernel or user space request
*
* Put a performance counter/countable pair that was previously received. If
* noone else is using the countable, free up the counter for others.
*/
int adreno_perfcounter_put(struct adreno_device *adreno_dev,
unsigned int groupid, unsigned int countable, unsigned int flags)
{
struct adreno_perfcounters *counters = adreno_dev->gpudev->perfcounters;
struct adreno_perfcount_group *group;
unsigned int i;
if (NULL == counters)
return -EINVAL;
if (groupid >= counters->group_count)
return -EINVAL;
group = &(counters->groups[groupid]);
/*
* Find if the counter/countable pair is used currently.
* Start cycling through registers in the bank.
*/
for (i = 0; i < group->reg_count; i++) {
/* check if countable assigned is what we are looking for */
if (group->regs[i].countable == countable) {
/* found pair, book keep count based on request type */
if (flags & PERFCOUNTER_FLAG_KERNEL &&
group->regs[i].kernelcount > 0)
group->regs[i].kernelcount--;
else if (group->regs[i].usercount > 0)
group->regs[i].usercount--;
else
break;
/* mark available if not used anymore */
if (group->regs[i].kernelcount == 0 &&
group->regs[i].usercount == 0)
group->regs[i].countable =
KGSL_PERFCOUNTER_NOT_USED;
return 0;
}
}
return -EINVAL;
}
/**
* adreno_perfcounter_restore() - Restore performance counters
* @adreno_dev: adreno device to configure
*
* Load the physical performance counters with 64 bit value which are
* saved on GPU power collapse.
*/
static inline void adreno_perfcounter_restore(struct adreno_device *adreno_dev)
{
if (adreno_dev->gpudev->perfcounter_restore)
adreno_dev->gpudev->perfcounter_restore(adreno_dev);
}
/**
* adreno_perfcounter_save() - Save performance counters
* @adreno_dev: adreno device to configure
*
* Save the performance counter values before GPU power collapse.
* The saved values are restored on restart.
* This ensures physical counters are coherent across power-collapse.
*/
static inline void adreno_perfcounter_save(struct adreno_device *adreno_dev)
{
if (adreno_dev->gpudev->perfcounter_save)
adreno_dev->gpudev->perfcounter_save(adreno_dev);
}
static irqreturn_t adreno_irq_handler(struct kgsl_device *device)
{
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
return adreno_dev->gpudev->irq_handler(adreno_dev);
}
static void adreno_cleanup_pt(struct kgsl_device *device,
struct kgsl_pagetable *pagetable)
{
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
struct adreno_ringbuffer *rb = &adreno_dev->ringbuffer;
kgsl_mmu_unmap(pagetable, &rb->buffer_desc);
kgsl_mmu_unmap(pagetable, &device->memstore);
kgsl_mmu_unmap(pagetable, &adreno_dev->pwron_fixup);
kgsl_mmu_unmap(pagetable, &device->mmu.setstate_memory);
kgsl_mmu_unmap(pagetable, &adreno_dev->profile.shared_buffer);
}
static int adreno_setup_pt(struct kgsl_device *device,
struct kgsl_pagetable *pagetable)
{
int result;
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
struct adreno_ringbuffer *rb = &adreno_dev->ringbuffer;
result = kgsl_mmu_map_global(pagetable, &rb->buffer_desc);
/*
* ALERT: Order of these mapping is important to
* Keep the most used entries like memstore
* and mmu setstate memory by TLB prefetcher.
*/
if (!result)
result = kgsl_mmu_map_global(pagetable, &device->memstore);
if (!result)
result = kgsl_mmu_map_global(pagetable,
&adreno_dev->pwron_fixup);
if (!result)
result = kgsl_mmu_map_global(pagetable,
&device->mmu.setstate_memory);
if (!result)
result = kgsl_mmu_map_global(pagetable,
&adreno_dev->profile.shared_buffer);
if (result) {
/* On error clean up what we have wrought */
adreno_cleanup_pt(device, pagetable);
return result;
}
/*
* Set the mpu end to the last "normal" global memory we use.
* For the IOMMU, this will be used to restrict access to the
* mapped registers.
*/
device->mh.mpu_range = adreno_dev->profile.shared_buffer.gpuaddr +
adreno_dev->profile.shared_buffer.size;
return 0;
}
static unsigned int _adreno_iommu_setstate_v0(struct kgsl_device *device,
unsigned int *cmds_orig,
phys_addr_t pt_val,
int num_iommu_units, uint32_t flags)
{
phys_addr_t reg_pt_val;
unsigned int *cmds = cmds_orig;
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
int i;
if (cpu_is_msm8960())
cmds += adreno_add_change_mh_phys_limit_cmds(cmds, 0xFFFFF000,
device->mmu.setstate_memory.gpuaddr +
KGSL_IOMMU_SETSTATE_NOP_OFFSET);
else
cmds += adreno_add_bank_change_cmds(cmds,
KGSL_IOMMU_CONTEXT_USER,
device->mmu.setstate_memory.gpuaddr +
KGSL_IOMMU_SETSTATE_NOP_OFFSET);
cmds += adreno_add_idle_cmds(adreno_dev, cmds);
/* Acquire GPU-CPU sync Lock here */
cmds += kgsl_mmu_sync_lock(&device->mmu, cmds);
if (flags & KGSL_MMUFLAGS_PTUPDATE) {
/*
* We need to perfrom the following operations for all
* IOMMU units
*/
for (i = 0; i < num_iommu_units; i++) {
reg_pt_val = kgsl_mmu_get_default_ttbr0(&device->mmu,
i, KGSL_IOMMU_CONTEXT_USER);
reg_pt_val &= ~KGSL_IOMMU_CTX_TTBR0_ADDR_MASK;
reg_pt_val |= (pt_val & KGSL_IOMMU_CTX_TTBR0_ADDR_MASK);
/*
* Set address of the new pagetable by writng to IOMMU
* TTBR0 register
*/
*cmds++ = cp_type3_packet(CP_MEM_WRITE, 2);
*cmds++ = kgsl_mmu_get_reg_gpuaddr(&device->mmu, i,
KGSL_IOMMU_CONTEXT_USER, KGSL_IOMMU_CTX_TTBR0);
*cmds++ = reg_pt_val;
*cmds++ = cp_type3_packet(CP_WAIT_FOR_IDLE, 1);
*cmds++ = 0x00000000;
/*
* Read back the ttbr0 register as a barrier to ensure
* above writes have completed
*/
cmds += adreno_add_read_cmds(device, cmds,
kgsl_mmu_get_reg_gpuaddr(&device->mmu, i,
KGSL_IOMMU_CONTEXT_USER, KGSL_IOMMU_CTX_TTBR0),
reg_pt_val,
device->mmu.setstate_memory.gpuaddr +
KGSL_IOMMU_SETSTATE_NOP_OFFSET);
}
}
if (flags & KGSL_MMUFLAGS_TLBFLUSH) {
/*
* tlb flush
*/
for (i = 0; i < num_iommu_units; i++) {
reg_pt_val = (pt_val + kgsl_mmu_get_default_ttbr0(
&device->mmu,
i, KGSL_IOMMU_CONTEXT_USER));
reg_pt_val &= ~KGSL_IOMMU_CTX_TTBR0_ADDR_MASK;
reg_pt_val |= (pt_val & KGSL_IOMMU_CTX_TTBR0_ADDR_MASK);
*cmds++ = cp_type3_packet(CP_MEM_WRITE, 2);
*cmds++ = kgsl_mmu_get_reg_gpuaddr(&device->mmu, i,
KGSL_IOMMU_CONTEXT_USER,
KGSL_IOMMU_CTX_TLBIALL);
*cmds++ = 1;
cmds += __adreno_add_idle_indirect_cmds(cmds,
device->mmu.setstate_memory.gpuaddr +
KGSL_IOMMU_SETSTATE_NOP_OFFSET);
cmds += adreno_add_read_cmds(device, cmds,
kgsl_mmu_get_reg_gpuaddr(&device->mmu, i,
KGSL_IOMMU_CONTEXT_USER,
KGSL_IOMMU_CTX_TTBR0),
reg_pt_val,
device->mmu.setstate_memory.gpuaddr +
KGSL_IOMMU_SETSTATE_NOP_OFFSET);
}
}
/* Release GPU-CPU sync Lock here */
cmds += kgsl_mmu_sync_unlock(&device->mmu, cmds);
if (cpu_is_msm8960())
cmds += adreno_add_change_mh_phys_limit_cmds(cmds,
kgsl_mmu_get_reg_gpuaddr(&device->mmu, 0,
0, KGSL_IOMMU_GLOBAL_BASE),
device->mmu.setstate_memory.gpuaddr +
KGSL_IOMMU_SETSTATE_NOP_OFFSET);
else
cmds += adreno_add_bank_change_cmds(cmds,
KGSL_IOMMU_CONTEXT_PRIV,
device->mmu.setstate_memory.gpuaddr +
KGSL_IOMMU_SETSTATE_NOP_OFFSET);
cmds += adreno_add_idle_cmds(adreno_dev, cmds);
return cmds - cmds_orig;
}
static unsigned int _adreno_iommu_setstate_v1(struct kgsl_device *device,
unsigned int *cmds_orig,
phys_addr_t pt_val,
int num_iommu_units, uint32_t flags)
{
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
phys_addr_t ttbr0_val;
unsigned int reg_pt_val;
unsigned int *cmds = cmds_orig;
int i;
unsigned int ttbr0, tlbiall, tlbstatus, tlbsync, mmu_ctrl;
cmds += adreno_add_idle_cmds(adreno_dev, cmds);
for (i = 0; i < num_iommu_units; i++) {
ttbr0_val = kgsl_mmu_get_default_ttbr0(&device->mmu,
i, KGSL_IOMMU_CONTEXT_USER);
ttbr0_val &= ~KGSL_IOMMU_CTX_TTBR0_ADDR_MASK;
ttbr0_val |= (pt_val & KGSL_IOMMU_CTX_TTBR0_ADDR_MASK);
if (flags & KGSL_MMUFLAGS_PTUPDATE) {
mmu_ctrl = kgsl_mmu_get_reg_ahbaddr(
&device->mmu, i,
KGSL_IOMMU_CONTEXT_USER,
KGSL_IOMMU_IMPLDEF_MICRO_MMU_CTRL) >> 2;
ttbr0 = kgsl_mmu_get_reg_ahbaddr(&device->mmu, i,
KGSL_IOMMU_CONTEXT_USER,
KGSL_IOMMU_CTX_TTBR0) >> 2;
if (kgsl_mmu_hw_halt_supported(&device->mmu, i)) {
*cmds++ = cp_type3_packet(CP_WAIT_FOR_IDLE, 1);
*cmds++ = 0;
/*
* glue commands together until next
* WAIT_FOR_ME
*/
cmds += adreno_wait_reg_eq(cmds,
adreno_getreg(adreno_dev,
ADRENO_REG_CP_WFI_PEND_CTR),
1, 0xFFFFFFFF, 0xF);
/* set the iommu lock bit */
*cmds++ = cp_type3_packet(CP_REG_RMW, 3);
*cmds++ = mmu_ctrl;
/* AND to unmask the lock bit */
*cmds++ =
~(KGSL_IOMMU_IMPLDEF_MICRO_MMU_CTRL_HALT);
/* OR to set the IOMMU lock bit */
*cmds++ =
KGSL_IOMMU_IMPLDEF_MICRO_MMU_CTRL_HALT;
/* wait for smmu to lock */
cmds += adreno_wait_reg_eq(cmds, mmu_ctrl,
KGSL_IOMMU_IMPLDEF_MICRO_MMU_CTRL_IDLE,
KGSL_IOMMU_IMPLDEF_MICRO_MMU_CTRL_IDLE, 0xF);
}
/* set ttbr0 */
if (sizeof(phys_addr_t) > sizeof(unsigned long)) {
reg_pt_val = ttbr0_val & 0xFFFFFFFF;
*cmds++ = cp_type0_packet(ttbr0, 1);
*cmds++ = reg_pt_val;
reg_pt_val = (unsigned int)
((ttbr0_val & 0xFFFFFFFF00000000ULL) >> 32);
*cmds++ = cp_type0_packet(ttbr0 + 1, 1);
*cmds++ = reg_pt_val;
} else {
reg_pt_val = ttbr0_val;
*cmds++ = cp_type0_packet(ttbr0, 1);
*cmds++ = reg_pt_val;
}
if (kgsl_mmu_hw_halt_supported(&device->mmu, i)) {
/* unlock the IOMMU lock */
*cmds++ = cp_type3_packet(CP_REG_RMW, 3);
*cmds++ = mmu_ctrl;
/* AND to unmask the lock bit */
*cmds++ =
~(KGSL_IOMMU_IMPLDEF_MICRO_MMU_CTRL_HALT);
/* OR with 0 so lock bit is unset */
*cmds++ = 0;
/* release all commands with wait_for_me */
*cmds++ = cp_type3_packet(CP_WAIT_FOR_ME, 1);
*cmds++ = 0;
}
}
if (flags & KGSL_MMUFLAGS_TLBFLUSH) {
tlbiall = kgsl_mmu_get_reg_ahbaddr(&device->mmu, i,
KGSL_IOMMU_CONTEXT_USER,
KGSL_IOMMU_CTX_TLBIALL) >> 2;
*cmds++ = cp_type0_packet(tlbiall, 1);
*cmds++ = 1;
tlbsync = kgsl_mmu_get_reg_ahbaddr(&device->mmu, i,
KGSL_IOMMU_CONTEXT_USER,
KGSL_IOMMU_CTX_TLBSYNC) >> 2;
*cmds++ = cp_type0_packet(tlbsync, 1);
*cmds++ = 0;
tlbstatus = kgsl_mmu_get_reg_ahbaddr(&device->mmu, i,
KGSL_IOMMU_CONTEXT_USER,
KGSL_IOMMU_CTX_TLBSTATUS) >> 2;
cmds += adreno_wait_reg_eq(cmds, tlbstatus, 0,
KGSL_IOMMU_CTX_TLBSTATUS_SACTIVE, 0xF);
/* release all commands with wait_for_me */
*cmds++ = cp_type3_packet(CP_WAIT_FOR_ME, 1);
*cmds++ = 0;
}
}
cmds += adreno_add_idle_cmds(adreno_dev, cmds);
return cmds - cmds_orig;
}
/**
* adreno_use_default_setstate() - Use CPU instead of the GPU to manage the mmu?
* @adreno_dev: the device
*
* In many cases it is preferable to poke the iommu or gpummu directly rather
* than using the GPU command stream. If we are idle or trying to go to a low
* power state, using the command stream will be slower and asynchronous, which
* needlessly complicates the power state transitions. Additionally,
* the hardware simulators do not support command stream MMU operations so
* the command stream can never be used if we are capturing CFF data.
*
*/
static bool adreno_use_default_setstate(struct adreno_device *adreno_dev)
{
return (adreno_isidle(&adreno_dev->dev) ||
KGSL_STATE_ACTIVE != adreno_dev->dev.state ||
atomic_read(&adreno_dev->dev.active_cnt) == 0 ||
adreno_dev->dev.cff_dump_enable);
}
static int adreno_iommu_setstate(struct kgsl_device *device,
unsigned int context_id,
uint32_t flags)
{
phys_addr_t pt_val;
unsigned int *link = NULL, *cmds;
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
int num_iommu_units;
struct kgsl_context *context;
struct adreno_context *adreno_ctx = NULL;
struct adreno_ringbuffer *rb = &adreno_dev->ringbuffer;
unsigned int result;
if (adreno_use_default_setstate(adreno_dev)) {
kgsl_mmu_device_setstate(&device->mmu, flags);
return 0;
}
num_iommu_units = kgsl_mmu_get_num_iommu_units(&device->mmu);
context = kgsl_context_get(device, context_id);
if (!context) {
kgsl_mmu_device_setstate(&device->mmu, flags);
return 0;
}
adreno_ctx = ADRENO_CONTEXT(context);
link = kmalloc(PAGE_SIZE, GFP_KERNEL);
if (link == NULL) {
result = -ENOMEM;
goto done;
}
cmds = link;
result = kgsl_mmu_enable_clk(&device->mmu, KGSL_IOMMU_CONTEXT_USER);
if (result)
goto done;
pt_val = kgsl_mmu_get_pt_base_addr(&device->mmu,
device->mmu.hwpagetable);
cmds += __adreno_add_idle_indirect_cmds(cmds,
device->mmu.setstate_memory.gpuaddr +
KGSL_IOMMU_SETSTATE_NOP_OFFSET);
if (msm_soc_version_supports_iommu_v0())
cmds += _adreno_iommu_setstate_v0(device, cmds, pt_val,
num_iommu_units, flags);
else
cmds += _adreno_iommu_setstate_v1(device, cmds, pt_val,
num_iommu_units, flags);
/* invalidate all base pointers */
*cmds++ = cp_type3_packet(CP_INVALIDATE_STATE, 1);
*cmds++ = 0x7fff;
if ((unsigned int) (cmds - link) > (PAGE_SIZE / sizeof(unsigned int))) {
KGSL_DRV_ERR(device, "Temp command buffer overflow\n");
BUG();
}
/*
* This returns the per context timestamp but we need to
* use the global timestamp for iommu clock disablement
*/
result = adreno_ringbuffer_issuecmds(device, adreno_ctx,
KGSL_CMD_FLAGS_PMODE, link,
(unsigned int)(cmds - link));
/*
* On error disable the IOMMU clock right away otherwise turn it off
* after the command has been retired
*/
if (result)
kgsl_mmu_disable_clk(&device->mmu,
KGSL_IOMMU_CONTEXT_USER);
else
kgsl_mmu_disable_clk_on_ts(&device->mmu, rb->global_ts,
KGSL_IOMMU_CONTEXT_USER);
done:
kfree(link);
kgsl_context_put(context);
return result;
}
static int adreno_gpummu_setstate(struct kgsl_device *device,
unsigned int context_id,
uint32_t flags)
{
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
unsigned int link[32];
unsigned int *cmds = &link[0];
int sizedwords = 0;
unsigned int mh_mmu_invalidate = 0x00000003; /*invalidate all and tc */
struct kgsl_context *context;
struct adreno_context *adreno_ctx = NULL;
int ret = 0;
/*
* Fix target freeze issue by adding TLB flush for each submit
* on A20X based targets.
*/
if (adreno_is_a20x(adreno_dev))
flags |= KGSL_MMUFLAGS_TLBFLUSH;
/*
* If possible, then set the state via the command stream to avoid
* a CPU idle. Otherwise, use the default setstate which uses register
* writes For CFF dump we must idle and use the registers so that it is
* easier to filter out the mmu accesses from the dump
*/
if (!adreno_use_default_setstate(adreno_dev)) {
context = kgsl_context_get(device, context_id);
if (context == NULL)
return -EINVAL;
adreno_ctx = ADRENO_CONTEXT(context);
if (flags & KGSL_MMUFLAGS_PTUPDATE) {
/* wait for graphics pipe to be idle */
*cmds++ = cp_type3_packet(CP_WAIT_FOR_IDLE, 1);
*cmds++ = 0x00000000;
/* set page table base */
*cmds++ = cp_type0_packet(MH_MMU_PT_BASE, 1);
*cmds++ = kgsl_mmu_get_pt_base_addr(&device->mmu,
device->mmu.hwpagetable);
sizedwords += 4;
}
if (flags & KGSL_MMUFLAGS_TLBFLUSH) {
if (!(flags & KGSL_MMUFLAGS_PTUPDATE)) {
*cmds++ = cp_type3_packet(CP_WAIT_FOR_IDLE,
1);
*cmds++ = 0x00000000;
sizedwords += 2;
}
*cmds++ = cp_type0_packet(MH_MMU_INVALIDATE, 1);
*cmds++ = mh_mmu_invalidate;
sizedwords += 2;
}
if (flags & KGSL_MMUFLAGS_PTUPDATE &&
adreno_is_a20x(adreno_dev)) {
/* HW workaround: to resolve MMU page fault interrupts
* caused by the VGT.It prevents the CP PFP from filling
* the VGT DMA request fifo too early,thereby ensuring
* that the VGT will not fetch vertex/bin data until
* after the page table base register has been updated.
*
* Two null DRAW_INDX_BIN packets are inserted right
* after the page table base update, followed by a
* wait for idle. The null packets will fill up the
* VGT DMA request fifo and prevent any further
* vertex/bin updates from occurring until the wait
* has finished. */
*cmds++ = cp_type3_packet(CP_SET_CONSTANT, 2);
*cmds++ = (0x4 << 16) |
(REG_PA_SU_SC_MODE_CNTL - 0x2000);
*cmds++ = 0; /* disable faceness generation */
*cmds++ = cp_type3_packet(CP_SET_BIN_BASE_OFFSET, 1);
*cmds++ = device->mmu.setstate_memory.gpuaddr;
*cmds++ = cp_type3_packet(CP_DRAW_INDX_BIN, 6);
*cmds++ = 0; /* viz query info */
*cmds++ = 0x0003C004; /* draw indicator */
*cmds++ = 0; /* bin base */
*cmds++ = 3; /* bin size */
*cmds++ =
device->mmu.setstate_memory.gpuaddr; /* dma base */
*cmds++ = 6; /* dma size */
*cmds++ = cp_type3_packet(CP_DRAW_INDX_BIN, 6);
*cmds++ = 0; /* viz query info */
*cmds++ = 0x0003C004; /* draw indicator */
*cmds++ = 0; /* bin base */
*cmds++ = 3; /* bin size */
/* dma base */
*cmds++ = device->mmu.setstate_memory.gpuaddr;
*cmds++ = 6; /* dma size */
*cmds++ = cp_type3_packet(CP_WAIT_FOR_IDLE, 1);
*cmds++ = 0x00000000;
sizedwords += 21;
}
if (flags & (KGSL_MMUFLAGS_PTUPDATE | KGSL_MMUFLAGS_TLBFLUSH)) {
*cmds++ = cp_type3_packet(CP_INVALIDATE_STATE, 1);
*cmds++ = 0x7fff; /* invalidate all base pointers */
sizedwords += 2;
}
ret = adreno_ringbuffer_issuecmds(device, adreno_ctx,
KGSL_CMD_FLAGS_PMODE,
&link[0], sizedwords);
kgsl_context_put(context);
} else {
kgsl_mmu_device_setstate(&device->mmu, flags);
}
return ret;
}
static int adreno_setstate(struct kgsl_device *device,
unsigned int context_id,
uint32_t flags)
{
/* call the mmu specific handler */
if (KGSL_MMU_TYPE_GPU == kgsl_mmu_get_mmutype())
return adreno_gpummu_setstate(device, context_id, flags);
else if (KGSL_MMU_TYPE_IOMMU == kgsl_mmu_get_mmutype())
return adreno_iommu_setstate(device, context_id, flags);
return 0;
}
static unsigned int
a3xx_getchipid(struct kgsl_device *device)
{
struct kgsl_device_platform_data *pdata =
kgsl_device_get_drvdata(device);
/*
* All current A3XX chipids are detected at the SOC level. Leave this
* function here to support any future GPUs that have working
* chip ID registers
*/
return pdata->chipid;
}
static unsigned int
a2xx_getchipid(struct kgsl_device *device)
{
unsigned int chipid = 0;
unsigned int coreid, majorid, minorid, patchid, revid;
struct kgsl_device_platform_data *pdata =
kgsl_device_get_drvdata(device);
/* If the chip id is set at the platform level, then just use that */
if (pdata->chipid != 0)
return pdata->chipid;
kgsl_regread(device, REG_RBBM_PERIPHID1, &coreid);
kgsl_regread(device, REG_RBBM_PERIPHID2, &majorid);
kgsl_regread(device, REG_RBBM_PATCH_RELEASE, &revid);
/*
* adreno 22x gpus are indicated by coreid 2,
* but REG_RBBM_PERIPHID1 always contains 0 for this field
*/
if (cpu_is_msm8x60())
chipid = 2 << 24;
else
chipid = (coreid & 0xF) << 24;
chipid |= ((majorid >> 4) & 0xF) << 16;
minorid = ((revid >> 0) & 0xFF);
patchid = ((revid >> 16) & 0xFF);
/* 8x50 returns 0 for patch release, but it should be 1 */
/* 8x25 returns 0 for minor id, but it should be 1 */
if (cpu_is_qsd8x50())
patchid = 1;
else if ((cpu_is_msm8625() || cpu_is_msm8625q()) && minorid == 0)
minorid = 1;
chipid |= (minorid << 8) | patchid;
return chipid;
}
static unsigned int
adreno_getchipid(struct kgsl_device *device)
{
struct kgsl_device_platform_data *pdata =
kgsl_device_get_drvdata(device);
/*
* All A3XX chipsets will have pdata set, so assume !pdata->chipid is
* an A2XX processor
*/
if (pdata->chipid == 0 || ADRENO_CHIPID_MAJOR(pdata->chipid) == 2)
return a2xx_getchipid(device);
else
return a3xx_getchipid(device);
}
static inline bool _rev_match(unsigned int id, unsigned int entry)
{
return (entry == ANY_ID || entry == id);
}
static void
adreno_identify_gpu(struct adreno_device *adreno_dev)
{
unsigned int i, core, major, minor, patchid;
adreno_dev->chip_id = adreno_getchipid(&adreno_dev->dev);
core = ADRENO_CHIPID_CORE(adreno_dev->chip_id);
major = ADRENO_CHIPID_MAJOR(adreno_dev->chip_id);
minor = ADRENO_CHIPID_MINOR(adreno_dev->chip_id);
patchid = ADRENO_CHIPID_PATCH(adreno_dev->chip_id);
for (i = 0; i < ARRAY_SIZE(adreno_gpulist); i++) {
if (core == adreno_gpulist[i].core &&
_rev_match(major, adreno_gpulist[i].major) &&
_rev_match(minor, adreno_gpulist[i].minor) &&
_rev_match(patchid, adreno_gpulist[i].patchid))
break;
}
if (i == ARRAY_SIZE(adreno_gpulist)) {
adreno_dev->gpurev = ADRENO_REV_UNKNOWN;
return;
}
adreno_dev->gpurev = adreno_gpulist[i].gpurev;
adreno_dev->gpudev = adreno_gpulist[i].gpudev;
adreno_dev->pfp_fwfile = adreno_gpulist[i].pfpfw;
adreno_dev->pm4_fwfile = adreno_gpulist[i].pm4fw;
adreno_dev->istore_size = adreno_gpulist[i].istore_size;
adreno_dev->pix_shader_start = adreno_gpulist[i].pix_shader_start;
adreno_dev->instruction_size = adreno_gpulist[i].instruction_size;
adreno_dev->gmem_size = adreno_gpulist[i].gmem_size;
adreno_dev->pm4_jt_idx = adreno_gpulist[i].pm4_jt_idx;
adreno_dev->pm4_jt_addr = adreno_gpulist[i].pm4_jt_addr;
adreno_dev->pm4_bstrp_size = adreno_gpulist[i].pm4_bstrp_size;
adreno_dev->pfp_jt_idx = adreno_gpulist[i].pfp_jt_idx;
adreno_dev->pfp_jt_addr = adreno_gpulist[i].pfp_jt_addr;
adreno_dev->pfp_bstrp_size = adreno_gpulist[i].pfp_bstrp_size;
adreno_dev->pfp_bstrp_ver = adreno_gpulist[i].pfp_bstrp_ver;
adreno_dev->gpulist_index = i;
/*
* Initialize uninitialzed gpu registers, only needs to be done once
* Make all offsets that are not initialized to ADRENO_REG_UNUSED
*/
for (i = 0; i < ADRENO_REG_REGISTER_MAX; i++) {
if (adreno_dev->gpudev->reg_offsets->offset_0 != i &&
!adreno_dev->gpudev->reg_offsets->offsets[i]) {
adreno_dev->gpudev->reg_offsets->offsets[i] =
ADRENO_REG_UNUSED;
}
}
}
static struct platform_device_id adreno_id_table[] = {
{ DEVICE_3D0_NAME, (kernel_ulong_t)&device_3d0.dev, },
{},
};
MODULE_DEVICE_TABLE(platform, adreno_id_table);
static struct of_device_id adreno_match_table[] = {
{ .compatible = "qcom,kgsl-3d0", },
{}
};
static inline int adreno_of_read_property(struct device_node *node,
const char *prop, unsigned int *ptr)
{
int ret = of_property_read_u32(node, prop, ptr);
if (ret)
KGSL_CORE_ERR("Unable to read '%s'\n", prop);
return ret;
}
static struct device_node *adreno_of_find_subnode(struct device_node *parent,
const char *name)
{
struct device_node *child;
for_each_child_of_node(parent, child) {
if (of_device_is_compatible(child, name))
return child;
}
return NULL;
}
static int adreno_of_get_pwrlevels(struct device_node *parent,
struct kgsl_device_platform_data *pdata)
{
struct device_node *node, *child;
int ret = -EINVAL;
node = adreno_of_find_subnode(parent, "qcom,gpu-pwrlevels");
if (node == NULL) {
KGSL_CORE_ERR("Unable to find 'qcom,gpu-pwrlevels'\n");
return -EINVAL;
}
pdata->num_levels = 0;
for_each_child_of_node(node, child) {
unsigned int index;
struct kgsl_pwrlevel *level;
if (adreno_of_read_property(child, "reg", &index))
goto done;
if (index >= KGSL_MAX_PWRLEVELS) {
KGSL_CORE_ERR("Pwrlevel index %d is out of range\n",
index);
continue;
}
if (index >= pdata->num_levels)
pdata->num_levels = index + 1;
level = &pdata->pwrlevel[index];
if (adreno_of_read_property(child, "qcom,gpu-freq",
&level->gpu_freq))
goto done;
if (adreno_of_read_property(child, "qcom,bus-freq",
&level->bus_freq))
goto done;
if (adreno_of_read_property(child, "qcom,io-fraction",
&level->io_fraction))
level->io_fraction = 0;
}
if (adreno_of_read_property(parent, "qcom,initial-pwrlevel",
&pdata->init_level))
pdata->init_level = 1;
if (pdata->init_level < 0 || pdata->init_level > pdata->num_levels) {
KGSL_CORE_ERR("Initial power level out of range\n");
pdata->init_level = 1;
}
ret = 0;
done:
return ret;
}
static int adreno_of_get_iommu(struct device_node *parent,
struct kgsl_device_platform_data *pdata)
{
struct device_node *node, *child;
struct kgsl_device_iommu_data *data = NULL;
struct kgsl_iommu_ctx *ctxs = NULL;
u32 reg_val[2];
int ctx_index = 0;
node = of_parse_phandle(parent, "iommu", 0);
if (node == NULL)
return -EINVAL;
data = kzalloc(sizeof(*data), GFP_KERNEL);
if (data == NULL) {
KGSL_CORE_ERR("kzalloc(%d) failed\n", sizeof(*data));
goto err;
}
if (of_property_read_u32_array(node, "reg", reg_val, 2))
goto err;
data->physstart = reg_val[0];
data->physend = data->physstart + reg_val[1] - 1;
data->iommu_halt_enable = of_property_read_bool(node,
"qcom,iommu-enable-halt");
data->iommu_ctx_count = 0;
for_each_child_of_node(node, child)
data->iommu_ctx_count++;
ctxs = kzalloc(data->iommu_ctx_count * sizeof(struct kgsl_iommu_ctx),
GFP_KERNEL);
if (ctxs == NULL) {
KGSL_CORE_ERR("kzalloc(%d) failed\n",
data->iommu_ctx_count * sizeof(struct kgsl_iommu_ctx));
goto err;
}
for_each_child_of_node(node, child) {
int ret = of_property_read_string(child, "label",
&ctxs[ctx_index].iommu_ctx_name);
if (ret) {
KGSL_CORE_ERR("Unable to read KGSL IOMMU 'label'\n");
goto err;
}
if (!strcmp("gfx3d_user", ctxs[ctx_index].iommu_ctx_name)) {
ctxs[ctx_index].ctx_id = 0;
} else if (!strcmp("gfx3d_priv",
ctxs[ctx_index].iommu_ctx_name)) {
ctxs[ctx_index].ctx_id = 1;
} else if (!strcmp("gfx3d_spare",
ctxs[ctx_index].iommu_ctx_name)) {
ctxs[ctx_index].ctx_id = 2;
} else {
KGSL_CORE_ERR("dt: IOMMU context %s is invalid\n",
ctxs[ctx_index].iommu_ctx_name);
goto err;
}
ctx_index++;
}
data->iommu_ctxs = ctxs;
pdata->iommu_data = data;
pdata->iommu_count = 1;
return 0;
err:
kfree(ctxs);
kfree(data);
return -EINVAL;
}
static int adreno_of_get_pdata(struct platform_device *pdev)
{
struct kgsl_device_platform_data *pdata = NULL;
struct kgsl_device *device;
int ret = -EINVAL;
pdev->id_entry = adreno_id_table;
pdata = pdev->dev.platform_data;
if (pdata)
return 0;
if (of_property_read_string(pdev->dev.of_node, "label", &pdev->name)) {
KGSL_CORE_ERR("Unable to read 'label'\n");
goto err;
}
if (adreno_of_read_property(pdev->dev.of_node, "qcom,id", &pdev->id))
goto err;
pdata = kzalloc(sizeof(*pdata), GFP_KERNEL);
if (pdata == NULL) {
KGSL_CORE_ERR("kzalloc(%d) failed\n", sizeof(*pdata));
ret = -ENOMEM;
goto err;
}
if (adreno_of_read_property(pdev->dev.of_node, "qcom,chipid",
&pdata->chipid))
goto err;
/* pwrlevel Data */
ret = adreno_of_get_pwrlevels(pdev->dev.of_node, pdata);
if (ret)
goto err;
/* get pm-qos-latency from target, set it to default if not found */
if (adreno_of_read_property(pdev->dev.of_node, "qcom,pm-qos-latency",
&pdata->pm_qos_latency))
pdata->pm_qos_latency = 501;
if (adreno_of_read_property(pdev->dev.of_node, "qcom,idle-timeout",
&pdata->idle_timeout))
pdata->idle_timeout = 80;
pdata->strtstp_sleepwake = of_property_read_bool(pdev->dev.of_node,
"qcom,strtstp-sleepwake");
pdata->bus_control = of_property_read_bool(pdev->dev.of_node,
"qcom,bus-control");
if (adreno_of_read_property(pdev->dev.of_node, "qcom,clk-map",
&pdata->clk_map))
goto err;
device = (struct kgsl_device *)pdev->id_entry->driver_data;
if (device->id != KGSL_DEVICE_3D0)
goto err;
/* Bus Scale Data */
pdata->bus_scale_table = msm_bus_cl_get_pdata(pdev);
if (IS_ERR_OR_NULL(pdata->bus_scale_table)) {
ret = PTR_ERR(pdata->bus_scale_table);
if (!ret)
ret = -EINVAL;
goto err;
}
ret = adreno_of_get_iommu(pdev->dev.of_node, pdata);
if (ret)
goto err;
pdata->coresight_pdata = of_get_coresight_platform_data(&pdev->dev,
pdev->dev.of_node);
pdev->dev.platform_data = pdata;
return 0;
err:
if (pdata) {
if (pdata->iommu_data)
kfree(pdata->iommu_data->iommu_ctxs);
kfree(pdata->iommu_data);
}
kfree(pdata);
return ret;
}
#ifdef CONFIG_MSM_OCMEM
static int
adreno_ocmem_gmem_malloc(struct adreno_device *adreno_dev)
{
if (!(adreno_is_a330(adreno_dev) ||
adreno_is_a305b(adreno_dev)))
return 0;
/* OCMEM is only needed once, do not support consective allocation */
if (adreno_dev->ocmem_hdl != NULL)
return 0;
adreno_dev->ocmem_hdl =
ocmem_allocate(OCMEM_GRAPHICS, adreno_dev->gmem_size);
if (adreno_dev->ocmem_hdl == NULL)
return -ENOMEM;
adreno_dev->gmem_size = adreno_dev->ocmem_hdl->len;
adreno_dev->ocmem_base = adreno_dev->ocmem_hdl->addr;
return 0;
}
static void
adreno_ocmem_gmem_free(struct adreno_device *adreno_dev)
{
if (!(adreno_is_a330(adreno_dev) ||
adreno_is_a305b(adreno_dev)))
return;
if (adreno_dev->ocmem_hdl == NULL)
return;
ocmem_free(OCMEM_GRAPHICS, adreno_dev->ocmem_hdl);
adreno_dev->ocmem_hdl = NULL;
}
#else
static int
adreno_ocmem_gmem_malloc(struct adreno_device *adreno_dev)
{
return 0;
}
static void
adreno_ocmem_gmem_free(struct adreno_device *adreno_dev)
{
}
#endif
static int __devinit
adreno_probe(struct platform_device *pdev)
{
struct kgsl_device *device;
struct kgsl_device_platform_data *pdata = NULL;
struct adreno_device *adreno_dev;
int status = -EINVAL;
bool is_dt;
is_dt = of_match_device(adreno_match_table, &pdev->dev);
if (is_dt && pdev->dev.of_node) {
status = adreno_of_get_pdata(pdev);
if (status)
goto error_return;
}
device = (struct kgsl_device *)pdev->id_entry->driver_data;
adreno_dev = ADRENO_DEVICE(device);
device->parentdev = &pdev->dev;
status = adreno_ringbuffer_init(device);
if (status != 0)
goto error;
status = kgsl_device_platform_probe(device);
if (status)
goto error_close_rb;
status = adreno_dispatcher_init(adreno_dev);
if (status)
goto error_close_device;
adreno_debugfs_init(device);
adreno_profile_init(device);
adreno_ft_init_sysfs(device);
kgsl_pwrscale_init(&pdev->dev, CONFIG_MSM_ADRENO_DEFAULT_GOVERNOR);
device->flags &= ~KGSL_FLAGS_SOFT_RESET;
pdata = kgsl_device_get_drvdata(device);
adreno_coresight_init(pdev);
adreno_input_handler.private = device;
/*
* It isn't fatal if we cannot register the input handler. Sad,
* perhaps, but not fatal
*/
if (input_register_handler(&adreno_input_handler))
KGSL_DRV_ERR(device, "Unable to register the input handler\n");
return 0;
error_close_device:
kgsl_device_platform_remove(device);
error_close_rb:
adreno_ringbuffer_close(&adreno_dev->ringbuffer);
error:
device->parentdev = NULL;
error_return:
return status;
}
static int __devexit adreno_remove(struct platform_device *pdev)
{
struct kgsl_device *device;
struct adreno_device *adreno_dev;
device = (struct kgsl_device *)pdev->id_entry->driver_data;
adreno_dev = ADRENO_DEVICE(device);
input_unregister_handler(&adreno_input_handler);
adreno_coresight_remove(pdev);
adreno_profile_close(device);
kgsl_pwrscale_close(device);
adreno_dispatcher_close(adreno_dev);
adreno_ringbuffer_close(&adreno_dev->ringbuffer);
adreno_perfcounter_close(device);
kgsl_device_platform_remove(device);
clear_bit(ADRENO_DEVICE_INITIALIZED, &adreno_dev->priv);
return 0;
}
static int adreno_init(struct kgsl_device *device)
{
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
int i;
int ret;
kgsl_pwrctrl_set_state(device, KGSL_STATE_INIT);
/*
* initialization only needs to be done once initially until
* device is shutdown
*/
if (test_bit(ADRENO_DEVICE_INITIALIZED, &adreno_dev->priv))
return 0;
/* Power up the device */
kgsl_pwrctrl_enable(device);
/* Identify the specific GPU */
adreno_identify_gpu(adreno_dev);
if (adreno_ringbuffer_read_pm4_ucode(device)) {
KGSL_DRV_ERR(device, "Reading pm4 microcode failed %s\n",
adreno_dev->pm4_fwfile);
BUG_ON(1);
}
if (adreno_ringbuffer_read_pfp_ucode(device)) {
KGSL_DRV_ERR(device, "Reading pfp microcode failed %s\n",
adreno_dev->pfp_fwfile);
BUG_ON(1);
}
if (adreno_dev->gpurev == ADRENO_REV_UNKNOWN) {
KGSL_DRV_ERR(device, "Unknown chip ID %x\n",
adreno_dev->chip_id);
BUG_ON(1);
}
kgsl_pwrctrl_set_state(device, KGSL_STATE_INIT);
/*
* Check if firmware supports the sync lock PM4 packets needed
* for IOMMUv1
*/
if ((adreno_dev->pm4_fw_version >=
adreno_gpulist[adreno_dev->gpulist_index].sync_lock_pm4_ver) &&
(adreno_dev->pfp_fw_version >=
adreno_gpulist[adreno_dev->gpulist_index].sync_lock_pfp_ver))
device->mmu.flags |= KGSL_MMU_FLAGS_IOMMU_SYNC;
/* Initialize ft detection register offsets */
ft_detect_regs[0] = adreno_getreg(adreno_dev,
ADRENO_REG_RBBM_STATUS);
ft_detect_regs[1] = adreno_getreg(adreno_dev,
ADRENO_REG_CP_RB_RPTR);
ft_detect_regs[2] = adreno_getreg(adreno_dev,
ADRENO_REG_CP_IB1_BASE);
ft_detect_regs[3] = adreno_getreg(adreno_dev,
ADRENO_REG_CP_IB1_BUFSZ);
ft_detect_regs[4] = adreno_getreg(adreno_dev,
ADRENO_REG_CP_IB2_BASE);
ft_detect_regs[5] = adreno_getreg(adreno_dev,
ADRENO_REG_CP_IB2_BUFSZ);
for (i = 6; i < FT_DETECT_REGS_COUNT; i++)
ft_detect_regs[i] = 0;
/* turn on hang interrupt for a330v2 by default */
if (adreno_is_a330v2(adreno_dev))
set_bit(ADRENO_DEVICE_HANG_INTR, &adreno_dev->priv);
ret = adreno_perfcounter_init(device);
if (ret)
goto done;
/* Power down the device */
kgsl_pwrctrl_disable(device);
/* Enable the power on shader corruption fix for all A3XX targets */
if (adreno_is_a3xx(adreno_dev))
adreno_a3xx_pwron_fixup_init(adreno_dev);
set_bit(ADRENO_DEVICE_INITIALIZED, &adreno_dev->priv);
done:
return ret;
}
/**
* _adreno_start - Power up the GPU and prepare to accept commands
* @adreno_dev: Pointer to an adreno_device structure
*
* The core function that powers up and initalizes the GPU. This function is
* called at init and after coming out of SLUMBER
*/
static int _adreno_start(struct adreno_device *adreno_dev)
{
struct kgsl_device *device = &adreno_dev->dev;
int status = -EINVAL;
unsigned int state = device->state;
unsigned int regulator_left_on = 0;
kgsl_cffdump_open(device);
kgsl_pwrctrl_set_state(device, KGSL_STATE_INIT);
regulator_left_on = (regulator_is_enabled(device->pwrctrl.gpu_reg) ||
(device->pwrctrl.gpu_cx &&
regulator_is_enabled(device->pwrctrl.gpu_cx)));
/* Clear any GPU faults that might have been left over */
adreno_clear_gpu_fault(adreno_dev);
/* Power up the device */
kgsl_pwrctrl_enable(device);
/* Set the bit to indicate that we've just powered on */
set_bit(ADRENO_DEVICE_PWRON, &adreno_dev->priv);
/* Set up a2xx special case */
if (adreno_is_a2xx(adreno_dev)) {
/*
* the MH_CLNT_INTF_CTRL_CONFIG registers aren't present
* on older gpus
*/
if (adreno_is_a20x(adreno_dev)) {
device->mh.mh_intf_cfg1 = 0;
device->mh.mh_intf_cfg2 = 0;
}
kgsl_mh_start(device);
}
status = kgsl_mmu_start(device);
if (status)
goto error_clk_off;
status = adreno_ocmem_gmem_malloc(adreno_dev);
if (status) {
KGSL_DRV_ERR(device, "OCMEM malloc failed\n");
goto error_mmu_off;
}
if (regulator_left_on && adreno_dev->gpudev->soft_reset) {
/*
* Reset the GPU for A3xx. A2xx does a soft reset in
* the start function.
*/
adreno_dev->gpudev->soft_reset(adreno_dev);
}
/* Restore performance counter registers with saved values */
adreno_perfcounter_restore(adreno_dev);
/* Start the GPU */
adreno_dev->gpudev->start(adreno_dev);
kgsl_pwrctrl_irq(device, KGSL_PWRFLAGS_ON);
device->ftbl->irqctrl(device, 1);
status = adreno_ringbuffer_cold_start(&adreno_dev->ringbuffer);
if (status)
goto error_irq_off;
status = adreno_perfcounter_start(adreno_dev);
if (status)
goto error_rb_stop;
/* Start the dispatcher */
adreno_dispatcher_start(device);
device->reset_counter++;
set_bit(ADRENO_DEVICE_STARTED, &adreno_dev->priv);
return 0;
error_rb_stop:
adreno_ringbuffer_stop(&adreno_dev->ringbuffer);
error_irq_off:
kgsl_pwrctrl_irq(device, KGSL_PWRFLAGS_OFF);
error_mmu_off:
kgsl_mmu_stop(&device->mmu);
error_clk_off:
kgsl_pwrctrl_disable(device);
/* set the state back to original state */
kgsl_pwrctrl_set_state(device, state);
return status;
}
/**
* adreno_start() - Power up and initialize the GPU
* @device: Pointer to the KGSL device to power up
* @priority: Boolean flag to specify of the start should be scheduled in a low
* latency work queue
*
* Power up the GPU and initialize it. If priority is specified then elevate
* the thread priority for the duration of the start operation
*/
static int adreno_start(struct kgsl_device *device, int priority)
{
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
int nice = task_nice(current);
int ret;
if (priority && (_wake_nice < nice))
set_user_nice(current, _wake_nice);
ret = _adreno_start(adreno_dev);
if (priority)
set_user_nice(current, nice);
return ret;
}
static int adreno_stop(struct kgsl_device *device)
{
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
if (!test_bit(ADRENO_DEVICE_STARTED, &adreno_dev->priv))
return 0;
kgsl_pwrctrl_enable(device);
adreno_dev->drawctxt_active = NULL;
adreno_dispatcher_stop(adreno_dev);
adreno_ringbuffer_stop(&adreno_dev->ringbuffer);
kgsl_mmu_stop(&device->mmu);
device->ftbl->irqctrl(device, 0);
kgsl_pwrctrl_irq(device, KGSL_PWRFLAGS_OFF);
del_timer_sync(&device->idle_timer);
adreno_ocmem_gmem_free(adreno_dev);
/* Save physical performance counter values before GPU power down*/
adreno_perfcounter_save(adreno_dev);
/* Power down the device */
kgsl_pwrctrl_disable(device);
kgsl_cffdump_close(device);
clear_bit(ADRENO_DEVICE_STARTED, &adreno_dev->priv);
return 0;
}
/**
* adreno_reset() - Helper function to reset the GPU
* @device: Pointer to the KGSL device structure for the GPU
*
* Try to reset the GPU to recover from a fault. First, try to do a low latency
* soft reset. If the soft reset fails for some reason, then bring out the big
* guns and toggle the footswitch.
*/
int adreno_reset(struct kgsl_device *device)
{
int ret = -EINVAL;
struct kgsl_mmu *mmu = &device->mmu;
int i = 0;
/* Try soft reset first, for non mmu fault case only */
if (!atomic_read(&mmu->fault)) {
ret = adreno_soft_reset(device);
if (ret)
KGSL_DEV_ERR_ONCE(device, "Device soft reset failed\n");
}
if (ret) {
/* If soft reset failed/skipped, then pull the power */
adreno_stop(device);
/* Keep trying to start the device until it works */
for (i = 0; i < NUM_TIMES_RESET_RETRY; i++) {
ret = adreno_start(device, 0);
if (!ret)
break;
msleep(20);
}
}
if (ret)
return ret;
if (0 != i)
KGSL_DRV_WARN(device, "Device hard reset tried %d tries\n", i);
/*
* If active_cnt is non-zero then the system was active before
* going into a reset - put it back in that state
*/
if (atomic_read(&device->active_cnt))
kgsl_pwrctrl_set_state(device, KGSL_STATE_ACTIVE);
/* Set the page table back to the default page table */
kgsl_mmu_setstate(&device->mmu, device->mmu.defaultpagetable,
KGSL_MEMSTORE_GLOBAL);
return ret;
}
/**
* _ft_sysfs_store() - Common routine to write to FT sysfs files
* @buf: value to write
* @count: size of the value to write
* @sysfs_cfg: KGSL FT sysfs config to write
*
* This is a common routine to write to FT sysfs files.
*/
static int _ft_sysfs_store(const char *buf, size_t count, unsigned int *ptr)
{
char temp[20];
unsigned long val;
int rc;
snprintf(temp, sizeof(temp), "%.*s",
(int)min(count, sizeof(temp) - 1), buf);
rc = kstrtoul(temp, 0, &val);
if (rc)
return rc;
*ptr = val;
return count;
}
/**
* _get_adreno_dev() - Routine to get a pointer to adreno dev
* @dev: device ptr
* @attr: Device attribute
* @buf: value to write
* @count: size of the value to write
*/
struct adreno_device *_get_adreno_dev(struct device *dev)
{
struct kgsl_device *device = kgsl_device_from_dev(dev);
return device ? ADRENO_DEVICE(device) : NULL;
}
/**
* _ft_policy_store() - Routine to configure FT policy
* @dev: device ptr
* @attr: Device attribute
* @buf: value to write
* @count: size of the value to write
*
* FT policy can be set to any of the options below.
* KGSL_FT_DISABLE -> BIT(0) Set to disable FT
* KGSL_FT_REPLAY -> BIT(1) Set to enable replay
* KGSL_FT_SKIPIB -> BIT(2) Set to skip IB
* KGSL_FT_SKIPFRAME -> BIT(3) Set to skip frame
* by default set FT policy to KGSL_FT_DEFAULT_POLICY
*/
static int _ft_policy_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct adreno_device *adreno_dev = _get_adreno_dev(dev);
int ret;
if (adreno_dev == NULL)
return 0;
mutex_lock(&adreno_dev->dev.mutex);
ret = _ft_sysfs_store(buf, count, &adreno_dev->ft_policy);
mutex_unlock(&adreno_dev->dev.mutex);
return ret;
}
/**
* _ft_policy_show() - Routine to read FT policy
* @dev: device ptr
* @attr: Device attribute
* @buf: value read
*
* This is a routine to read current FT policy
*/
static int _ft_policy_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct adreno_device *adreno_dev = _get_adreno_dev(dev);
if (adreno_dev == NULL)
return 0;
return snprintf(buf, PAGE_SIZE, "0x%X\n", adreno_dev->ft_policy);
}
/**
* _ft_pagefault_policy_store() - Routine to configure FT
* pagefault policy
* @dev: device ptr
* @attr: Device attribute
* @buf: value to write
* @count: size of the value to write
*
* FT pagefault policy can be set to any of the options below.
* KGSL_FT_PAGEFAULT_INT_ENABLE -> BIT(0) set to enable pagefault INT
* KGSL_FT_PAGEFAULT_GPUHALT_ENABLE -> BIT(1) Set to enable GPU HALT on
* pagefaults. This stalls the GPU on a pagefault on IOMMU v1 HW.
* KGSL_FT_PAGEFAULT_LOG_ONE_PER_PAGE -> BIT(2) Set to log only one
* pagefault per page.
* KGSL_FT_PAGEFAULT_LOG_ONE_PER_INT -> BIT(3) Set to log only one
* pagefault per INT.
*/
static int _ft_pagefault_policy_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct adreno_device *adreno_dev = _get_adreno_dev(dev);
int ret = 0;
unsigned int policy = 0;
if (adreno_dev == NULL)
return 0;
mutex_lock(&adreno_dev->dev.mutex);
/* MMU option changed call function to reset MMU options */
if (count != _ft_sysfs_store(buf, count, &policy))
ret = -EINVAL;
if (!ret) {
policy &= (KGSL_FT_PAGEFAULT_INT_ENABLE |
KGSL_FT_PAGEFAULT_GPUHALT_ENABLE |
KGSL_FT_PAGEFAULT_LOG_ONE_PER_PAGE |
KGSL_FT_PAGEFAULT_LOG_ONE_PER_INT);
ret = kgsl_mmu_set_pagefault_policy(&(adreno_dev->dev.mmu),
adreno_dev->ft_pf_policy);
if (!ret)
adreno_dev->ft_pf_policy = policy;
}
mutex_unlock(&adreno_dev->dev.mutex);
if (!ret)
return count;
else
return 0;
}
/**
* _ft_pagefault_policy_show() - Routine to read FT pagefault
* policy
* @dev: device ptr
* @attr: Device attribute
* @buf: value read
*
* This is a routine to read current FT pagefault policy
*/
static int _ft_pagefault_policy_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct adreno_device *adreno_dev = _get_adreno_dev(dev);
if (adreno_dev == NULL)
return 0;
return snprintf(buf, PAGE_SIZE, "0x%X\n", adreno_dev->ft_pf_policy);
}
/**
* _ft_fast_hang_detect_store() - Routine to configure FT fast
* hang detect policy
* @dev: device ptr
* @attr: Device attribute
* @buf: value to write
* @count: size of the value to write
*
* 0x1 - Enable fast hang detection
* 0x0 - Disable fast hang detection
*/
static int _ft_fast_hang_detect_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct adreno_device *adreno_dev = _get_adreno_dev(dev);
int ret, tmp;
if (adreno_dev == NULL)
return 0;
mutex_lock(&adreno_dev->dev.mutex);
tmp = adreno_dev->fast_hang_detect;
ret = _ft_sysfs_store(buf, count, &adreno_dev->fast_hang_detect);
if (tmp != adreno_dev->fast_hang_detect) {
if (adreno_dev->fast_hang_detect) {
if (adreno_dev->gpudev->fault_detect_start &&
!kgsl_active_count_get(&adreno_dev->dev)) {
adreno_dev->gpudev->fault_detect_start(
adreno_dev);
kgsl_active_count_put(&adreno_dev->dev);
}
} else {
if (adreno_dev->gpudev->fault_detect_stop)
adreno_dev->gpudev->fault_detect_stop(
adreno_dev);
}
}
mutex_unlock(&adreno_dev->dev.mutex);
return ret;
}
/**
* _ft_fast_hang_detect_show() - Routine to read FT fast
* hang detect policy
* @dev: device ptr
* @attr: Device attribute
* @buf: value read
*/
static int _ft_fast_hang_detect_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct adreno_device *adreno_dev = _get_adreno_dev(dev);
if (adreno_dev == NULL)
return 0;
return snprintf(buf, PAGE_SIZE, "%d\n",
(adreno_dev->fast_hang_detect ? 1 : 0));
}
/**
* _ft_long_ib_detect_store() - Routine to configure FT long IB
* detect policy
* @dev: device ptr
* @attr: Device attribute
* @buf: value to write
* @count: size of the value to write
*
* 0x0 - Enable long IB detection
* 0x1 - Disable long IB detection
*/
static int _ft_long_ib_detect_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct adreno_device *adreno_dev = _get_adreno_dev(dev);
int ret;
if (adreno_dev == NULL)
return 0;
mutex_lock(&adreno_dev->dev.mutex);
ret = _ft_sysfs_store(buf, count, &adreno_dev->long_ib_detect);
mutex_unlock(&adreno_dev->dev.mutex);
return ret;
}
/**
* _ft_long_ib_detect_show() - Routine to read FT long IB
* detect policy
* @dev: device ptr
* @attr: Device attribute
* @buf: value read
*/
static int _ft_long_ib_detect_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct adreno_device *adreno_dev = _get_adreno_dev(dev);
if (adreno_dev == NULL)
return 0;
return snprintf(buf, PAGE_SIZE, "%d\n",
(adreno_dev->long_ib_detect ? 1 : 0));
}
/**
* _wake_timeout_store() - Store the amount of time to extend idle check after
* wake on touch
* @dev: device ptr
* @attr: Device attribute
* @buf: value to write
* @count: size of the value to write
*
*/
static ssize_t _wake_timeout_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
return _ft_sysfs_store(buf, count, &_wake_timeout);
}
/**
* _wake_timeout_show() - Show the amount of time idle check gets extended
* after wake on touch
* detect policy
* @dev: device ptr
* @attr: Device attribute
* @buf: value read
*/
static ssize_t _wake_timeout_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
return snprintf(buf, PAGE_SIZE, "%d\n", _wake_timeout);
}
/**
* _ft_hang_intr_status_store - Routine to enable/disable h/w hang interrupt
* @dev: device ptr
* @attr: Device attribute
* @buf: value to write
* @count: size of the value to write
*/
static ssize_t _ft_hang_intr_status_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
unsigned int new_setting, old_setting;
struct kgsl_device *device = kgsl_device_from_dev(dev);
struct adreno_device *adreno_dev;
int ret;
if (device == NULL)
return 0;
adreno_dev = ADRENO_DEVICE(device);
mutex_lock(&device->mutex);
ret = _ft_sysfs_store(buf, count, &new_setting);
if (ret != count)
goto done;
if (new_setting)
new_setting = 1;
old_setting =
(test_bit(ADRENO_DEVICE_HANG_INTR, &adreno_dev->priv) ? 1 : 0);
if (new_setting != old_setting) {
if (new_setting)
set_bit(ADRENO_DEVICE_HANG_INTR, &adreno_dev->priv);
else
clear_bit(ADRENO_DEVICE_HANG_INTR, &adreno_dev->priv);
/* Set the new setting based on device state */
switch (device->state) {
case KGSL_STATE_NAP:
case KGSL_STATE_SLEEP:
kgsl_pwrctrl_wake(device, 0);
case KGSL_STATE_ACTIVE:
adreno_dev->gpudev->irq_control(adreno_dev, 1);
/*
* For following states setting will be picked up on device
* start. Still need them in switch statement to differentiate
* from default
*/
case KGSL_STATE_SLUMBER:
case KGSL_STATE_SUSPEND:
break;
default:
ret = -EACCES;
/* reset back to old setting on error */
if (new_setting)
clear_bit(ADRENO_DEVICE_HANG_INTR,
&adreno_dev->priv);
else
set_bit(ADRENO_DEVICE_HANG_INTR,
&adreno_dev->priv);
goto done;
}
}
done:
mutex_unlock(&device->mutex);
return ret;
}
/**
* _ft_hang_intr_status_show() - Routine to read hardware hang interrupt
* enablement
* @dev: device ptr
* @attr: Device attribute
* @buf: value read
*/
static ssize_t _ft_hang_intr_status_show(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct adreno_device *adreno_dev = _get_adreno_dev(dev);
if (adreno_dev == NULL)
return 0;
return snprintf(buf, PAGE_SIZE, "%d\n",
test_bit(ADRENO_DEVICE_HANG_INTR, &adreno_dev->priv) ? 1 : 0);
}
#define FT_DEVICE_ATTR(name) \
DEVICE_ATTR(name, 0644, _ ## name ## _show, _ ## name ## _store);
FT_DEVICE_ATTR(ft_policy);
FT_DEVICE_ATTR(ft_pagefault_policy);
FT_DEVICE_ATTR(ft_fast_hang_detect);
FT_DEVICE_ATTR(ft_long_ib_detect);
FT_DEVICE_ATTR(ft_hang_intr_status);
static DEVICE_INT_ATTR(wake_nice, 0644, _wake_nice);
static FT_DEVICE_ATTR(wake_timeout);
const struct device_attribute *ft_attr_list[] = {
&dev_attr_ft_policy,
&dev_attr_ft_pagefault_policy,
&dev_attr_ft_fast_hang_detect,
&dev_attr_ft_long_ib_detect,
&dev_attr_wake_nice.attr,
&dev_attr_wake_timeout,
&dev_attr_ft_hang_intr_status,
NULL,
};
int adreno_ft_init_sysfs(struct kgsl_device *device)
{
return kgsl_create_device_sysfs_files(device->dev, ft_attr_list);
}
void adreno_ft_uninit_sysfs(struct kgsl_device *device)
{
kgsl_remove_device_sysfs_files(device->dev, ft_attr_list);
}
static int adreno_getproperty(struct kgsl_device *device,
enum kgsl_property_type type,
void *value,
unsigned int sizebytes)
{
int status = -EINVAL;
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
switch (type) {
case KGSL_PROP_DEVICE_INFO:
{
struct kgsl_devinfo devinfo;
if (sizebytes != sizeof(devinfo)) {
status = -EINVAL;
break;
}
memset(&devinfo, 0, sizeof(devinfo));
devinfo.device_id = device->id+1;
devinfo.chip_id = adreno_dev->chip_id;
devinfo.mmu_enabled = kgsl_mmu_enabled();
devinfo.gpu_id = adreno_dev->gpurev;
devinfo.gmem_gpubaseaddr = adreno_dev->gmem_base;
devinfo.gmem_sizebytes = adreno_dev->gmem_size;
if (copy_to_user(value, &devinfo, sizeof(devinfo)) !=
0) {
status = -EFAULT;
break;
}
status = 0;
}
break;
case KGSL_PROP_DEVICE_SHADOW:
{
struct kgsl_shadowprop shadowprop;
if (sizebytes != sizeof(shadowprop)) {
status = -EINVAL;
break;
}
memset(&shadowprop, 0, sizeof(shadowprop));
if (device->memstore.hostptr) {
/*NOTE: with mmu enabled, gpuaddr doesn't mean
* anything to mmap().
*/
shadowprop.gpuaddr = device->memstore.gpuaddr;
shadowprop.size = device->memstore.size;
/* GSL needs this to be set, even if it
appears to be meaningless */
shadowprop.flags = KGSL_FLAGS_INITIALIZED |
KGSL_FLAGS_PER_CONTEXT_TIMESTAMPS;
}
if (copy_to_user(value, &shadowprop,
sizeof(shadowprop))) {
status = -EFAULT;
break;
}
status = 0;
}
break;
case KGSL_PROP_MMU_ENABLE:
{
int mmu_prop = kgsl_mmu_enabled();
if (sizebytes != sizeof(int)) {
status = -EINVAL;
break;
}
if (copy_to_user(value, &mmu_prop, sizeof(mmu_prop))) {
status = -EFAULT;
break;
}
status = 0;
}
break;
case KGSL_PROP_INTERRUPT_WAITS:
{
int int_waits = 1;
if (sizebytes != sizeof(int)) {
status = -EINVAL;
break;
}
if (copy_to_user(value, &int_waits, sizeof(int))) {
status = -EFAULT;
break;
}
status = 0;
}
break;
default:
status = -EINVAL;
}
return status;
}
static int adreno_set_constraint(struct kgsl_device *device,
struct kgsl_context *context,
struct kgsl_device_constraint *constraint)
{
int status = 0;
switch (constraint->type) {
case KGSL_CONSTRAINT_PWRLEVEL: {
struct kgsl_device_constraint_pwrlevel pwr;
if (constraint->size != sizeof(pwr)) {
status = -EINVAL;
break;
}
if (copy_from_user(&pwr,
(void __user *)constraint->data,
sizeof(pwr))) {
status = -EFAULT;
break;
}
if (pwr.level >= KGSL_CONSTRAINT_PWR_MAXLEVELS) {
status = -EINVAL;
break;
}
context->pwr_constraint.type =
KGSL_CONSTRAINT_PWRLEVEL;
context->pwr_constraint.sub_type = pwr.level;
}
break;
case KGSL_CONSTRAINT_NONE:
context->pwr_constraint.type = KGSL_CONSTRAINT_NONE;
break;
default:
status = -EINVAL;
break;
}
return status;
}
static int adreno_setproperty(struct kgsl_device_private *dev_priv,
enum kgsl_property_type type,
void *value,
unsigned int sizebytes)
{
int status = -EINVAL;
struct kgsl_device *device = dev_priv->device;
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
switch (type) {
case KGSL_PROP_PWRCTRL: {
unsigned int enable;
if (sizebytes != sizeof(enable))
break;
if (copy_from_user(&enable, (void __user *) value,
sizeof(enable))) {
status = -EFAULT;
break;
}
kgsl_mutex_lock(&device->mutex, &device->mutex_owner);
if (enable) {
device->pwrctrl.ctrl_flags = 0;
adreno_dev->fast_hang_detect = 1;
if (adreno_dev->gpudev->fault_detect_start)
adreno_dev->gpudev->fault_detect_start(
adreno_dev);
kgsl_pwrscale_enable(device);
} else {
kgsl_pwrctrl_wake(device, 0);
device->pwrctrl.ctrl_flags = KGSL_PWR_ON;
adreno_dev->fast_hang_detect = 0;
if (adreno_dev->gpudev->fault_detect_stop)
adreno_dev->gpudev->fault_detect_stop(
adreno_dev);
kgsl_pwrscale_disable(device);
}
kgsl_mutex_unlock(&device->mutex, &device->mutex_owner);
status = 0;
}
break;
case KGSL_PROP_PWR_CONSTRAINT: {
struct kgsl_device_constraint constraint;
struct kgsl_context *context;
if (sizebytes != sizeof(constraint))
break;
if (copy_from_user(&constraint, value,
sizeof(constraint))) {
status = -EFAULT;
break;
}
context = kgsl_context_get_owner(dev_priv,
constraint.context_id);
if (context == NULL)
break;
status = adreno_set_constraint(device, context,
&constraint);
kgsl_context_put(context);
}
break;
default:
break;
}
return status;
}
/**
* adreno_hw_isidle() - Check if the GPU core is idle
* @device: Pointer to the KGSL device structure for the GPU
*
* Return true if the RBBM status register for the GPU type indicates that the
* hardware is idle
*/
bool adreno_hw_isidle(struct kgsl_device *device)
{
unsigned int reg_rbbm_status;
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
/* Don't consider ourselves idle if there is an IRQ pending */
if (adreno_dev->gpudev->irq_pending(adreno_dev))
return false;
adreno_readreg(adreno_dev, ADRENO_REG_RBBM_STATUS,
®_rbbm_status);
if (adreno_is_a2xx(adreno_dev)) {
if (reg_rbbm_status == 0x110)
return true;
} else if (adreno_is_a3xx(adreno_dev)) {
if (!(reg_rbbm_status & 0x80000000))
return true;
}
return false;
}
/**
* adreno_soft_reset() - Do a soft reset of the GPU hardware
* @device: KGSL device to soft reset
*
* "soft reset" the GPU hardware - this is a fast path GPU reset
* The GPU hardware is reset but we never pull power so we can skip
* a lot of the standard adreno_stop/adreno_start sequence
*/
int adreno_soft_reset(struct kgsl_device *device)
{
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
int ret;
if (!adreno_dev->gpudev->soft_reset) {
dev_WARN_ONCE(device->dev, 1, "Soft reset not supported");
return -EINVAL;
}
if (adreno_dev->drawctxt_active)
kgsl_context_put(&adreno_dev->drawctxt_active->base);
adreno_dev->drawctxt_active = NULL;
/* Stop the ringbuffer */
adreno_ringbuffer_stop(&adreno_dev->ringbuffer);
if (kgsl_pwrctrl_isenabled(device))
device->ftbl->irqctrl(device, 0);
kgsl_pwrctrl_irq(device, KGSL_PWRFLAGS_OFF);
adreno_clear_gpu_fault(adreno_dev);
/* Delete the idle timer */
del_timer_sync(&device->idle_timer);
/* Make sure we are totally awake */
kgsl_pwrctrl_enable(device);
/* save physical performance counter values before GPU soft reset */
adreno_perfcounter_save(adreno_dev);
/* Reset the GPU */
adreno_dev->gpudev->soft_reset(adreno_dev);
/* Restore physical performance counter values after soft reset */
adreno_perfcounter_restore(adreno_dev);
/* Reinitialize the GPU */
adreno_dev->gpudev->start(adreno_dev);
/* Enable IRQ */
kgsl_pwrctrl_irq(device, KGSL_PWRFLAGS_ON);
device->ftbl->irqctrl(device, 1);
/*
* If we have offsets for the jump tables we can try to do a warm start,
* otherwise do a full ringbuffer restart
*/
if (adreno_dev->pm4_jt_idx)
ret = adreno_ringbuffer_warm_start(&adreno_dev->ringbuffer);
else
ret = adreno_ringbuffer_cold_start(&adreno_dev->ringbuffer);
if (ret)
return ret;
device->reset_counter++;
return 0;
}
/*
* adreno_isidle() - return true if the GPU hardware is idle
* @device: Pointer to the KGSL device structure for the GPU
*
* Return true if the GPU hardware is idle and there are no commands pending in
* the ringbuffer
*/
bool adreno_isidle(struct kgsl_device *device)
{
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
unsigned int rptr;
if (!kgsl_pwrctrl_isenabled(device))
return true;
rptr = adreno_get_rptr(&adreno_dev->ringbuffer);
/*
* wptr is updated when we add commands to ringbuffer, add a barrier
* to make sure updated wptr is compared to rptr
*/
smp_mb();
if (rptr == adreno_dev->ringbuffer.wptr)
return adreno_hw_isidle(device);
return false;
}
/**
* adreno_idle() - wait for the GPU hardware to go idle
* @device: Pointer to the KGSL device structure for the GPU
*
* Wait up to ADRENO_IDLE_TIMEOUT milliseconds for the GPU hardware to go quiet.
*/
int adreno_idle(struct kgsl_device *device)
{
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
unsigned long wait = jiffies + msecs_to_jiffies(ADRENO_IDLE_TIMEOUT);
/*
* Make sure the device mutex is held so the dispatcher can't send any
* more commands to the hardware
*/
BUG_ON(!mutex_is_locked(&device->mutex));
if (adreno_is_a3xx(adreno_dev))
kgsl_cffdump_regpoll(device,
adreno_getreg(adreno_dev, ADRENO_REG_RBBM_STATUS) << 2,
0x00000000, 0x80000000);
else
kgsl_cffdump_regpoll(device,
adreno_getreg(adreno_dev, ADRENO_REG_RBBM_STATUS) << 2,
0x110, 0x110);
while (time_before(jiffies, wait)) {
/*
* If we fault, stop waiting and return an error. The dispatcher
* will clean up the fault from the work queue, but we need to
* make sure we don't block it by waiting for an idle that
* will never come.
*/
if (adreno_gpu_fault(adreno_dev) != 0)
return -EDEADLK;
if (adreno_isidle(device))
return 0;
}
return -ETIMEDOUT;
}
/**
* adreno_drain() - Drain the dispatch queue
* @device: Pointer to the KGSL device structure for the GPU
*
* Drain the dispatcher of existing command batches. This halts
* additional commands from being issued until the gate is completed.
*/
static int adreno_drain(struct kgsl_device *device)
{
INIT_COMPLETION(device->cmdbatch_gate);
return 0;
}
/* Caller must hold the device mutex. */
static int adreno_suspend_context(struct kgsl_device *device)
{
int status = 0;
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
/* process any profiling results that are available */
adreno_profile_process_results(device);
/* switch to NULL ctxt */
if (adreno_dev->drawctxt_active != NULL) {
adreno_drawctxt_switch(adreno_dev, NULL, 0);
status = adreno_idle(device);
}
return status;
}
/* Find a memory structure attached to an adreno context */
struct kgsl_memdesc *adreno_find_ctxtmem(struct kgsl_device *device,
phys_addr_t pt_base, unsigned int gpuaddr, unsigned int size)
{
struct kgsl_context *context;
int next = 0;
struct kgsl_memdesc *desc = NULL;
read_lock(&device->context_lock);
while (1) {
context = idr_get_next(&device->context_idr, &next);
if (context == NULL)
break;
if (kgsl_mmu_pt_equal(&device->mmu,
context->proc_priv->pagetable,
pt_base)) {
struct adreno_context *adreno_context;
adreno_context = ADRENO_CONTEXT(context);
desc = &adreno_context->gpustate;
if (kgsl_gpuaddr_in_memdesc(desc, gpuaddr, size))
break;
desc = &adreno_context->context_gmem_shadow.gmemshadow;
if (kgsl_gpuaddr_in_memdesc(desc, gpuaddr, size))
break;
}
next = next + 1;
desc = NULL;
}
read_unlock(&device->context_lock);
return desc;
}
/*
* adreno_find_region() - Find corresponding allocation for a given address
* @device: Device on which address operates
* @pt_base: The pagetable in which address is mapped
* @gpuaddr: The gpu address
* @size: Size in bytes of the address
* @entry: If the allocation is part of user space allocation then the mem
* entry is returned in this parameter. Caller is supposed to decrement
* refcount on this entry after its done using it.
*
* Finds an allocation descriptor for a given gpu address range
*
* Returns the descriptor on success else NULL
*/
struct kgsl_memdesc *adreno_find_region(struct kgsl_device *device,
phys_addr_t pt_base,
unsigned int gpuaddr,
unsigned int size,
struct kgsl_mem_entry **entry)
{
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
struct adreno_ringbuffer *ringbuffer = &adreno_dev->ringbuffer;
*entry = NULL;
if (kgsl_gpuaddr_in_memdesc(&ringbuffer->buffer_desc, gpuaddr, size))
return &ringbuffer->buffer_desc;
if (kgsl_gpuaddr_in_memdesc(&device->memstore, gpuaddr, size))
return &device->memstore;
if (kgsl_gpuaddr_in_memdesc(&adreno_dev->pwron_fixup, gpuaddr, size))
return &adreno_dev->pwron_fixup;
if (kgsl_gpuaddr_in_memdesc(&device->mmu.setstate_memory, gpuaddr,
size))
return &device->mmu.setstate_memory;
*entry = kgsl_get_mem_entry(device, pt_base, gpuaddr, size);
if (*entry)
return &((*entry)->memdesc);
return adreno_find_ctxtmem(device, pt_base, gpuaddr, size);
}
/*
* adreno_convertaddr() - Convert a gpu address to kernel mapped address
* @device: Device on which the address operates
* @pt_base: The pagetable in which address is mapped
* @gpuaddr: The start address
* @size: The length of address range
* @entry: If the allocation is part of user space allocation then the mem
* entry is returned in this parameter. Caller is supposed to decrement
* refcount on this entry after its done using it.
*
* Returns the converted host pointer on success else NULL
*/
uint8_t *adreno_convertaddr(struct kgsl_device *device, phys_addr_t pt_base,
unsigned int gpuaddr, unsigned int size,
struct kgsl_mem_entry **entry)
{
struct kgsl_memdesc *memdesc;
memdesc = adreno_find_region(device, pt_base, gpuaddr, size, entry);
return memdesc ? kgsl_gpuaddr_to_vaddr(memdesc, gpuaddr) : NULL;
}
/**
* adreno_read - General read function to read adreno device memory
* @device - Pointer to the GPU device struct (for adreno device)
* @base - Base address (kernel virtual) where the device memory is mapped
* @offsetwords - Offset in words from the base address, of the memory that
* is to be read
* @value - Value read from the device memory
* @mem_len - Length of the device memory mapped to the kernel
*/
static void adreno_read(struct kgsl_device *device, void *base,
unsigned int offsetwords, unsigned int *value,
unsigned int mem_len)
{
unsigned int *reg;
BUG_ON(offsetwords*sizeof(uint32_t) >= mem_len);
reg = (unsigned int *)(base + (offsetwords << 2));
if (!in_interrupt())
kgsl_pre_hwaccess(device);
/*ensure this read finishes before the next one.
* i.e. act like normal readl() */
*value = __raw_readl(reg);
rmb();
}
/**
* adreno_regread - Used to read adreno device registers
* @offsetwords - Word (4 Bytes) offset to the register to be read
* @value - Value read from device register
*/
static void adreno_regread(struct kgsl_device *device, unsigned int offsetwords,
unsigned int *value)
{
adreno_read(device, device->reg_virt, offsetwords, value,
device->reg_len);
}
/**
* adreno_shadermem_regread - Used to read GPU (adreno) shader memory
* @device - GPU device whose shader memory is to be read
* @offsetwords - Offset in words, of the shader memory address to be read
* @value - Pointer to where the read shader mem value is to be stored
*/
void adreno_shadermem_regread(struct kgsl_device *device,
unsigned int offsetwords, unsigned int *value)
{
adreno_read(device, device->shader_mem_virt, offsetwords, value,
device->shader_mem_len);
}
static void adreno_regwrite(struct kgsl_device *device,
unsigned int offsetwords,
unsigned int value)
{
unsigned int *reg;
BUG_ON(offsetwords*sizeof(uint32_t) >= device->reg_len);
if (!in_interrupt())
kgsl_pre_hwaccess(device);
kgsl_trace_regwrite(device, offsetwords, value);
kgsl_cffdump_regwrite(device, offsetwords << 2, value);
reg = (unsigned int *)(device->reg_virt + (offsetwords << 2));
/*ensure previous writes post before this one,
* i.e. act like normal writel() */
wmb();
__raw_writel(value, reg);
}
/**
* adreno_waittimestamp - sleep while waiting for the specified timestamp
* @device - pointer to a KGSL device structure
* @context - pointer to the active kgsl context
* @timestamp - GPU timestamp to wait for
* @msecs - amount of time to wait (in milliseconds)
*
* Wait up to 'msecs' milliseconds for the specified timestamp to expire.
*/
static int adreno_waittimestamp(struct kgsl_device *device,
struct kgsl_context *context,
unsigned int timestamp,
unsigned int msecs)
{
int ret;
struct adreno_context *drawctxt;
if (context == NULL) {
/* If they are doing then complain once */
dev_WARN_ONCE(device->dev, 1,
"IOCTL_KGSL_DEVICE_WAITTIMESTAMP is deprecated\n");
return -ENOTTY;
}
/* Return -EINVAL if the context has been detached */
if (kgsl_context_detached(context))
return -EINVAL;
ret = adreno_drawctxt_wait(ADRENO_DEVICE(device), context,
timestamp, msecs);
/* If the context got invalidated then return a specific error */
drawctxt = ADRENO_CONTEXT(context);
if (drawctxt->state == ADRENO_CONTEXT_STATE_INVALID)
ret = -EDEADLK;
/*
* Return -EPROTO if the device has faulted since the last time we
* checked. Userspace uses this as a marker for performing post
* fault activities
*/
if (!ret && test_and_clear_bit(ADRENO_CONTEXT_FAULT, &drawctxt->priv))
ret = -EPROTO;
return ret;
}
static unsigned int adreno_readtimestamp(struct kgsl_device *device,
struct kgsl_context *context, enum kgsl_timestamp_type type)
{
unsigned int timestamp = 0;
unsigned int id = context ? context->id : KGSL_MEMSTORE_GLOBAL;
switch (type) {
case KGSL_TIMESTAMP_QUEUED: {
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
timestamp = adreno_context_timestamp(context,
&adreno_dev->ringbuffer);
break;
}
case KGSL_TIMESTAMP_CONSUMED:
kgsl_sharedmem_readl(&device->memstore, ×tamp,
KGSL_MEMSTORE_OFFSET(id, soptimestamp));
break;
case KGSL_TIMESTAMP_RETIRED:
kgsl_sharedmem_readl(&device->memstore, ×tamp,
KGSL_MEMSTORE_OFFSET(id, eoptimestamp));
break;
}
return timestamp;
}
static long adreno_ioctl(struct kgsl_device_private *dev_priv,
unsigned int cmd, void *data)
{
struct kgsl_device *device = dev_priv->device;
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
int result = 0;
switch (cmd) {
case IOCTL_KGSL_DRAWCTXT_SET_BIN_BASE_OFFSET: {
struct kgsl_drawctxt_set_bin_base_offset *binbase = data;
struct kgsl_context *context;
binbase = data;
context = kgsl_context_get_owner(dev_priv,
binbase->drawctxt_id);
if (context) {
adreno_drawctxt_set_bin_base_offset(
device, context, binbase->offset);
} else {
result = -EINVAL;
KGSL_DRV_ERR(device,
"invalid drawctxt drawctxt_id %d "
"device_id=%d\n",
binbase->drawctxt_id, device->id);
}
kgsl_context_put(context);
break;
}
case IOCTL_KGSL_PERFCOUNTER_GET: {
struct kgsl_perfcounter_get *get = data;
kgsl_mutex_lock(&device->mutex, &device->mutex_owner);
/*
* adreno_perfcounter_get() is called by kernel clients
* during start(), so it is not safe to take an
* active count inside this function.
*/
result = kgsl_active_count_get(device);
if (result == 0) {
result = adreno_perfcounter_get(adreno_dev,
get->groupid, get->countable, &get->offset,
&get->offset_hi, PERFCOUNTER_FLAG_NONE);
kgsl_active_count_put(device);
}
kgsl_mutex_unlock(&device->mutex, &device->mutex_owner);
break;
}
case IOCTL_KGSL_PERFCOUNTER_PUT: {
struct kgsl_perfcounter_put *put = data;
kgsl_mutex_lock(&device->mutex, &device->mutex_owner);
result = adreno_perfcounter_put(adreno_dev, put->groupid,
put->countable, PERFCOUNTER_FLAG_NONE);
kgsl_mutex_unlock(&device->mutex, &device->mutex_owner);
break;
}
case IOCTL_KGSL_PERFCOUNTER_QUERY: {
struct kgsl_perfcounter_query *query = data;
result = adreno_perfcounter_query_group(adreno_dev,
query->groupid, query->countables,
query->count, &query->max_counters);
break;
}
case IOCTL_KGSL_PERFCOUNTER_READ: {
struct kgsl_perfcounter_read *read = data;
result = adreno_perfcounter_read_group(adreno_dev,
read->reads, read->count);
break;
}
default:
KGSL_DRV_INFO(dev_priv->device,
"invalid ioctl code %08x\n", cmd);
result = -ENOIOCTLCMD;
break;
}
return result;
}
static inline s64 adreno_ticks_to_us(u32 ticks, u32 freq)
{
freq /= 1000000;
return ticks / freq;
}
static void adreno_power_stats(struct kgsl_device *device,
struct kgsl_power_stats *stats)
{
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
struct kgsl_pwrctrl *pwr = &device->pwrctrl;
struct adreno_busy_data busy_data;
memset(stats, 0, sizeof(*stats));
/*
* If we're not currently active, there shouldn't have been
* any cycles since the last time this function was called.
*/
if (device->state != KGSL_STATE_ACTIVE)
return;
/* Get the busy cycles counted since the counter was last reset */
adreno_dev->gpudev->busy_cycles(adreno_dev, &busy_data);
stats->busy_time = adreno_ticks_to_us(busy_data.gpu_busy,
kgsl_pwrctrl_active_freq(pwr));
stats->ram_time = busy_data.vbif_ram_cycles;
stats->ram_wait = busy_data.vbif_starved_ram;
}
void adreno_irqctrl(struct kgsl_device *device, int state)
{
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
adreno_dev->gpudev->irq_control(adreno_dev, state);
}
static unsigned int adreno_gpuid(struct kgsl_device *device,
unsigned int *chipid)
{
struct adreno_device *adreno_dev = ADRENO_DEVICE(device);
/* Some applications need to know the chip ID too, so pass
* that as a parameter */
if (chipid != NULL)
*chipid = adreno_dev->chip_id;
/* Standard KGSL gpuid format:
* top word is 0x0002 for 2D or 0x0003 for 3D
* Bottom word is core specific identifer
*/
return (0x0003 << 16) | ((int) adreno_dev->gpurev);
}
static const struct kgsl_functable adreno_functable = {
/* Mandatory functions */
.regread = adreno_regread,
.regwrite = adreno_regwrite,
.idle = adreno_idle,
.isidle = adreno_isidle,
.suspend_context = adreno_suspend_context,
.init = adreno_init,
.start = adreno_start,
.stop = adreno_stop,
.getproperty = adreno_getproperty,
.waittimestamp = adreno_waittimestamp,
.readtimestamp = adreno_readtimestamp,
.issueibcmds = adreno_ringbuffer_issueibcmds,
.ioctl = adreno_ioctl,
.setup_pt = adreno_setup_pt,
.cleanup_pt = adreno_cleanup_pt,
.power_stats = adreno_power_stats,
.irqctrl = adreno_irqctrl,
.gpuid = adreno_gpuid,
.snapshot = adreno_snapshot,
.irq_handler = adreno_irq_handler,
.drain = adreno_drain,
/* Optional functions */
.setstate = adreno_setstate,
.drawctxt_create = adreno_drawctxt_create,
.drawctxt_detach = adreno_drawctxt_detach,
.drawctxt_destroy = adreno_drawctxt_destroy,
.drawctxt_dump = adreno_drawctxt_dump,
.setproperty = adreno_setproperty,
.postmortem_dump = adreno_dump,
.drawctxt_sched = adreno_drawctxt_sched,
.resume = adreno_dispatcher_start,
};
static struct platform_driver adreno_platform_driver = {
.probe = adreno_probe,
.remove = __devexit_p(adreno_remove),
.suspend = kgsl_suspend_driver,
.resume = kgsl_resume_driver,
.id_table = adreno_id_table,
.driver = {
.owner = THIS_MODULE,
.name = DEVICE_3D_NAME,
.pm = &kgsl_pm_ops,
.of_match_table = adreno_match_table,
}
};
static int __init kgsl_3d_init(void)
{
return platform_driver_register(&adreno_platform_driver);
}
static void __exit kgsl_3d_exit(void)
{
platform_driver_unregister(&adreno_platform_driver);
}
module_init(kgsl_3d_init);
module_exit(kgsl_3d_exit);
MODULE_DESCRIPTION("3D Graphics driver");
MODULE_VERSION("1.2");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:kgsl_3d");
|
decipher90/decipher_kernel
|
drivers/gpu/msm/adreno.c
|
C
|
gpl-2.0
| 95,660
|
<?php
/**
*
* The template for displaying the wisdom page
*
* @link https://codex.wordpress.org/Template_Hierarchy
*
* @package humblelion
*/
get_header(); ?>
<div id="primary" class="wisdom-page content-area">
<main id="main" class="site-main" role="main">
<?php // open the WordPress loop
if (have_posts()) : while (have_posts()) : the_post();
// are there any rows within within our flexible content?
if( have_rows('wisdom_page') ):
// loop through all the rows of flexible content
while ( have_rows('wisdom_page') ) : the_row();
// FULL WIDTH TEXT
if( get_row_layout() == 'full_width_text' )
get_template_part('template-parts/section', 'fullwidthtext');
if( get_row_layout() == 'wisdom_wall' )
get_template_part('template-parts/section', 'wisdom');
endwhile; // close the loop of flexible content
endif; // close flexible content conditional
endwhile; endif; // close the WordPress loop ?>
</main><!-- #main -->
</div><!-- #primary -->
<?php
get_sidebar();
get_footer();
|
studiopine/thehumblelion
|
page-wisdom.php
|
PHP
|
gpl-2.0
| 1,063
|
<?php
namespace Telecube;
class CubeAgi extends Agi{
function wait($n){
$this->exec("WAIT ".$n);
}
function answer(){
$this->exec("ANSWER");
}
function playback($file='goodbye',$options=''){
$this->exec("PLAYBACK ".$file.",".$options." ");
}
function progress(){
$this->exec("EXEC PROGRESS");
}
function ringing(){
$this->exec("EXEC RINGING");
}
function busy(){
$this->exec("EXEC BUSY");
}
function dial($callto,$timeout=180,$type='SIP'){
return $this->exec_dial($type, $callto, $timeout);
}
function tc_exec($command) {
global $debug, $stdlog;
fwrite(STDOUT, "$command\n");
fflush(STDOUT);
$result = trim(fgets(STDIN));
$ret = array('code'=> -1, 'result'=> -1, 'timeout'=> false, 'data'=> '');
if (preg_match("/^([0-9]{1,3}) (.*)/", $result, $matches)) {
$ret['code'] = $matches[1];
$ret['result'] = 0;
if (preg_match('/^result=([0-9a-zA-Z]*)\s?(?:\(?(.*?)\)?)?$/', $matches[2], $match)) {
$ret['result'] = $match[1];
$ret['timeout'] = ($match[2] === 'timeout') ? true : false;
$ret['data'] = $match[2];
}
}
if ($debug && !empty($stdlog)) {
$fh = fopen($stdlog, 'a');
if ($fh !== false) {
$res = $ret['result'] . (empty($ret['data']) ? '' : " / $ret[data]");
fwrite($fh, "-------\n>> $command\n<< $result\n<< parsed $res\n");
fclose($fh);
}
}
return $ret;
}
function addheader($hdrStr){
return $this->exec("SIPAddHeader ".$hdrStr);
}
}
?>
|
telecube/telecube-pbx
|
agi-bin/classes/phpagi-telecube.php
|
PHP
|
gpl-2.0
| 1,467
|
// D3D11RenderView.hpp
// KlayGE D3D11äÖȾÊÓͼÀà Í·Îļþ
// Ver 3.8.0
// °æÈ¨ËùÓÐ(C) ¹¨ÃôÃô, 2009
// Homepage: http://www.klayge.org
//
// 3.8.0
// ³õ´Î½¨Á¢ (2009.1.30)
//
// Ð޸ļǼ
/////////////////////////////////////////////////////////////////////////////////
#ifndef _D3D11RENDERVIEW_HPP
#define _D3D11RENDERVIEW_HPP
#pragma once
#include <KlayGE/PreDeclare.hpp>
#include <KlayGE/RenderView.hpp>
#include <KlayGE/Texture.hpp>
#include <KlayGE/D3D11/D3D11Util.hpp>
namespace KlayGE
{
class D3D11Texture1D;
class D3D11Texture2D;
class D3D11Texture3D;
class D3D11TextureCube;
class D3D11GraphicsBuffer;
class D3D11ShaderResourceView : public ShaderResourceView
{
public:
virtual ID3D11ShaderResourceView* RetrieveD3DShaderResourceView() const = 0;
protected:
ID3D11Device1* d3d_device_;
ID3D11DeviceContext1* d3d_imm_ctx_;
mutable ID3D11ShaderResourceViewPtr d3d_sr_view_;
void* sr_src_;
};
class D3D11TextureShaderResourceView final : public D3D11ShaderResourceView
{
public:
D3D11TextureShaderResourceView(TexturePtr const & texture, ElementFormat pf, uint32_t first_array_index, uint32_t array_size,
uint32_t first_level, uint32_t num_levels);
ID3D11ShaderResourceView* RetrieveD3DShaderResourceView() const override;
};
class D3D11CubeTextureFaceShaderResourceView final : public D3D11ShaderResourceView
{
public:
D3D11CubeTextureFaceShaderResourceView(TexturePtr const& texture_cube, ElementFormat pf, int array_index, Texture::CubeFaces face,
uint32_t first_level, uint32_t num_levels);
ID3D11ShaderResourceView* RetrieveD3DShaderResourceView() const override;
};
class D3D11BufferShaderResourceView final : public D3D11ShaderResourceView
{
public:
D3D11BufferShaderResourceView(GraphicsBufferPtr const & gbuffer, ElementFormat pf, uint32_t first_elem, uint32_t num_elems);
ID3D11ShaderResourceView* RetrieveD3DShaderResourceView() const override;
};
class D3D11RenderTargetView : public RenderTargetView
{
public:
D3D11RenderTargetView(void* src, uint32_t first_subres, uint32_t num_subres);
void ClearColor(Color const & clr) override;
void Discard() override;
void OnAttached(FrameBuffer& fb, FrameBuffer::Attachment att) override;
void OnDetached(FrameBuffer& fb, FrameBuffer::Attachment att) override;
virtual ID3D11RenderTargetView* RetrieveD3DRenderTargetView() const = 0;
void* RTSrc() const
{
return rt_src_;
}
uint32_t RTFirstSubRes() const
{
return rt_first_subres_;
}
uint32_t RTNumSubRes() const
{
return rt_num_subres_;
}
protected:
ID3D11Device1* d3d_device_;
ID3D11DeviceContext1* d3d_imm_ctx_;
mutable ID3D11RenderTargetViewPtr d3d_rt_view_;
void* rt_src_;
uint32_t rt_first_subres_;
uint32_t rt_num_subres_;
};
class D3D11Texture1D2DCubeRenderTargetView final : public D3D11RenderTargetView
{
public:
D3D11Texture1D2DCubeRenderTargetView(TexturePtr const & texture_1d_2d_cube, ElementFormat pf, int first_array_index, int array_size,
int level);
ID3D11RenderTargetView* RetrieveD3DRenderTargetView() const override;
};
class D3D11Texture3DRenderTargetView final : public D3D11RenderTargetView
{
public:
D3D11Texture3DRenderTargetView(TexturePtr const & texture_3d, ElementFormat pf, int array_index, uint32_t first_slice,
uint32_t num_slices, int level);
ID3D11RenderTargetView* RetrieveD3DRenderTargetView() const override;
};
class D3D11TextureCubeFaceRenderTargetView final : public D3D11RenderTargetView
{
public:
D3D11TextureCubeFaceRenderTargetView(TexturePtr const & texture_cube, ElementFormat pf, int array_index, Texture::CubeFaces face,
int level);
ID3D11RenderTargetView* RetrieveD3DRenderTargetView() const override;
};
class D3D11BufferRenderTargetView final : public D3D11RenderTargetView
{
public:
D3D11BufferRenderTargetView(GraphicsBufferPtr const & gb, ElementFormat pf, uint32_t first_elem, uint32_t num_elems);
ID3D11RenderTargetView* RetrieveD3DRenderTargetView() const override;
};
class D3D11DepthStencilView : public DepthStencilView
{
public:
D3D11DepthStencilView(void* src, uint32_t first_subres, uint32_t num_subres);
void ClearDepth(float depth) override;
void ClearStencil(int32_t stencil) override;
void ClearDepthStencil(float depth, int32_t stencil) override;
void Discard() override;
void OnAttached(FrameBuffer& fb) override;
void OnDetached(FrameBuffer& fb) override;
virtual ID3D11DepthStencilView* RetrieveD3DDepthStencilView() const = 0;
void* RTSrc() const
{
return rt_src_;
}
uint32_t RTFirstSubRes() const
{
return rt_first_subres_;
}
uint32_t RTNumSubRes() const
{
return rt_num_subres_;
}
protected:
ID3D11Device1* d3d_device_;
ID3D11DeviceContext1* d3d_imm_ctx_;
mutable ID3D11DepthStencilViewPtr d3d_ds_view_;
void* rt_src_;
uint32_t rt_first_subres_;
uint32_t rt_num_subres_;
};
class D3D11Texture1D2DCubeDepthStencilView final : public D3D11DepthStencilView
{
public:
D3D11Texture1D2DCubeDepthStencilView(TexturePtr const & texture_1d_2d_cube, ElementFormat pf, int first_array_index, int array_size,
int level);
D3D11Texture1D2DCubeDepthStencilView(uint32_t width, uint32_t height, ElementFormat pf, uint32_t sample_count,
uint32_t sample_quality);
ID3D11DepthStencilView* RetrieveD3DDepthStencilView() const override;
};
class D3D11Texture3DDepthStencilView final : public D3D11DepthStencilView
{
public:
D3D11Texture3DDepthStencilView(TexturePtr const & texture_3d, ElementFormat pf, int array_index, uint32_t first_slice,
uint32_t num_slices, int level);
ID3D11DepthStencilView* RetrieveD3DDepthStencilView() const override;
};
class D3D11TextureCubeFaceDepthStencilView final : public D3D11DepthStencilView
{
public:
D3D11TextureCubeFaceDepthStencilView(TexturePtr const & texture_cube, ElementFormat pf, int array_index, Texture::CubeFaces face,
int level);
ID3D11DepthStencilView* RetrieveD3DDepthStencilView() const override;
};
class D3D11UnorderedAccessView : public UnorderedAccessView
{
public:
D3D11UnorderedAccessView(void* src, uint32_t first_subres, uint32_t num_subres);
void Clear(float4 const & val) override;
void Clear(uint4 const & val) override;
void Discard() override;
void OnAttached(FrameBuffer& fb, uint32_t index) override;
void OnDetached(FrameBuffer& fb, uint32_t index) override;
virtual ID3D11UnorderedAccessView* RetrieveD3DUnorderedAccessView() const = 0;
void* UASrc() const
{
return ua_src_;
}
uint32_t UAFirstSubRes() const
{
return ua_first_subres_;
}
uint32_t UANumSubRes() const
{
return ua_num_subres_;
}
protected:
ID3D11Device1* d3d_device_;
ID3D11DeviceContext1* d3d_imm_ctx_;
mutable ID3D11UnorderedAccessViewPtr d3d_ua_view_;
void* ua_src_;
uint32_t ua_first_subres_;
uint32_t ua_num_subres_;
};
class D3D11Texture1D2DCubeUnorderedAccessView final : public D3D11UnorderedAccessView
{
public:
D3D11Texture1D2DCubeUnorderedAccessView(TexturePtr const & texture_1d_2d_cube, ElementFormat pf, int first_array_index,
int array_size, int level);
ID3D11UnorderedAccessView* RetrieveD3DUnorderedAccessView() const override;
};
class D3D11Texture3DUnorderedAccessView final : public D3D11UnorderedAccessView
{
public:
D3D11Texture3DUnorderedAccessView(TexturePtr const & texture_3d, ElementFormat pf, int array_index, uint32_t first_slice,
uint32_t num_slices, int level);
ID3D11UnorderedAccessView* RetrieveD3DUnorderedAccessView() const override;
};
class D3D11TextureCubeFaceUnorderedAccessView final : public D3D11UnorderedAccessView
{
public:
D3D11TextureCubeFaceUnorderedAccessView(TexturePtr const & texture_cube, ElementFormat pf, int array_index, Texture::CubeFaces face,
int level);
ID3D11UnorderedAccessView* RetrieveD3DUnorderedAccessView() const override;
};
class D3D11BufferUnorderedAccessView final : public D3D11UnorderedAccessView
{
public:
D3D11BufferUnorderedAccessView(GraphicsBufferPtr const & gb, ElementFormat pf, uint32_t first_elem, uint32_t num_elems);
ID3D11UnorderedAccessView* RetrieveD3DUnorderedAccessView() const override;
};
}
#endif // _D3D11RENDERVIEW_HPP
|
gongminmin/KlayGE
|
KlayGE/Plugins/Include/KlayGE/D3D11/D3D11RenderView.hpp
|
C++
|
gpl-2.0
| 8,503
|
/*
* TUXAUDIO - Firmware for the 'audio' CPU of tuxdroid
* Copyright (C) 2007 C2ME S.A. <tuxdroid@c2me.be>
*
* 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
*/
/* $Id: audio_fifo.c 2994 2008-12-03 13:20:41Z ks156 $ */
#include <inttypes.h>
#include "audio_fifo.h"
uint8_t AudioInIdx = 0;
uint8_t AudioOutIdx = 0;
uint8_t AudioFifoSize = 128;
uint8_t AudioBuffer[128];
/* Empty the buffer by clearing the indexes. */
void AudioFifoClear(void)
{
AudioInIdx = 0;
AudioOutIdx = 0;
}
/* Add one data byte to the fifo buffer.
* param data : Data byte to add to the queue.
* return : Return A_FIFO_OK if the data has been added, A_FIFO_FULL if the buffer
* was full and the data couldn't be added.
*/
int8_t AudioFifoPut(uint8_t const data)
{
if (AudioFifoLength() == AudioFifoSize)
return A_FIFO_FULL;
AudioBuffer[AudioInIdx++ & (AudioFifoSize-1)] = data;
return A_FIFO_OK;
}
/* Pop the oldest byte from the buffer.
* param data : pointer for storing the data read from the queue
* return : A_FIFO_OK if a value has been popped out at the pointer address. If
* the fifo is empty, A_FIFO_EMPTY is returned and the pointed data is left
* unchanged.
*/
int8_t AudioFifoGet(uint8_t *data)
{
if (AudioOutIdx == AudioInIdx)
return A_FIFO_EMPTY;
*data = AudioBuffer[AudioOutIdx++ & (AudioFifoSize - 1)];
return A_FIFO_OK;
}
|
joelmatteotti/tuxfirmware
|
tuxaudio/audio_fifo.c
|
C
|
gpl-2.0
| 2,052
|
<?php
//--------------------------------------------------------------------------
// Kill Script if direct file access
//--------------------------------------------------------------------------
if ( $_SERVER['SCRIPT_FILENAME'] == __FILE__ ) {
header( 'Location: /' );
exit;
}
wp_redirect( bloginfo( 'url' ), 302 );
|
jonathanbardo/WP-Framework
|
wp-content/themes/jb-theme/author.php
|
PHP
|
gpl-2.0
| 320
|
/**
* collectd - src/write_http.c
* Copyright (C) 2009 Paul Sadauskas
* Copyright (C) 2009 Doug MacEachern
* Copyright (C) 2007-2009 Florian octo Forster
*
* 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; only version 2 of the License is applicable.
*
* 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
*
* Authors:
* Florian octo Forster <octo at collectd.org>
* Doug MacEachern <dougm@hyperic.com>
* Paul Sadauskas <psadauskas@gmail.com>
**/
#include "collectd.h"
#include "plugin.h"
#include "common.h"
#include "utils_cache.h"
#include "utils_parse_option.h"
#include "utils_format_json.h"
#if HAVE_PTHREAD_H
# include <pthread.h>
#endif
#include <curl/curl.h>
/*
* Private variables
*/
struct wh_callback_s
{
char *location;
char *user;
char *pass;
char *credentials;
_Bool verify_peer;
_Bool verify_host;
char *cacert;
char *capath;
char *clientkey;
char *clientcert;
char *clientkeypass;
long sslversion;
_Bool store_rates;
#define WH_FORMAT_COMMAND 0
#define WH_FORMAT_JSON 1
int format;
CURL *curl;
char curl_errbuf[CURL_ERROR_SIZE];
char send_buffer[4096];
size_t send_buffer_free;
size_t send_buffer_fill;
cdtime_t send_buffer_init_time;
pthread_mutex_t send_lock;
};
typedef struct wh_callback_s wh_callback_t;
static void wh_reset_buffer (wh_callback_t *cb) /* {{{ */
{
memset (cb->send_buffer, 0, sizeof (cb->send_buffer));
cb->send_buffer_free = sizeof (cb->send_buffer);
cb->send_buffer_fill = 0;
cb->send_buffer_init_time = cdtime ();
if (cb->format == WH_FORMAT_JSON)
{
format_json_initialize (cb->send_buffer,
&cb->send_buffer_fill,
&cb->send_buffer_free);
}
} /* }}} wh_reset_buffer */
static int wh_send_buffer (wh_callback_t *cb) /* {{{ */
{
int status = 0;
curl_easy_setopt (cb->curl, CURLOPT_POSTFIELDS, cb->send_buffer);
status = curl_easy_perform (cb->curl);
if (status != CURLE_OK)
{
ERROR ("write_http plugin: curl_easy_perform failed with "
"status %i: %s",
status, cb->curl_errbuf);
}
return (status);
} /* }}} wh_send_buffer */
static int wh_callback_init (wh_callback_t *cb) /* {{{ */
{
struct curl_slist *headers;
if (cb->curl != NULL)
return (0);
cb->curl = curl_easy_init ();
if (cb->curl == NULL)
{
ERROR ("curl plugin: curl_easy_init failed.");
return (-1);
}
curl_easy_setopt (cb->curl, CURLOPT_NOSIGNAL, 1L);
curl_easy_setopt (cb->curl, CURLOPT_USERAGENT, COLLECTD_USERAGENT);
headers = NULL;
headers = curl_slist_append (headers, "Accept: */*");
if (cb->format == WH_FORMAT_JSON)
headers = curl_slist_append (headers, "Content-Type: application/json");
else
headers = curl_slist_append (headers, "Content-Type: text/plain");
headers = curl_slist_append (headers, "Expect:");
curl_easy_setopt (cb->curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt (cb->curl, CURLOPT_ERRORBUFFER, cb->curl_errbuf);
curl_easy_setopt (cb->curl, CURLOPT_URL, cb->location);
if (cb->user != NULL)
{
size_t credentials_size;
credentials_size = strlen (cb->user) + 2;
if (cb->pass != NULL)
credentials_size += strlen (cb->pass);
cb->credentials = (char *) malloc (credentials_size);
if (cb->credentials == NULL)
{
ERROR ("curl plugin: malloc failed.");
return (-1);
}
ssnprintf (cb->credentials, credentials_size, "%s:%s",
cb->user, (cb->pass == NULL) ? "" : cb->pass);
curl_easy_setopt (cb->curl, CURLOPT_USERPWD, cb->credentials);
curl_easy_setopt (cb->curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
}
curl_easy_setopt (cb->curl, CURLOPT_SSL_VERIFYPEER, (long) cb->verify_peer);
curl_easy_setopt (cb->curl, CURLOPT_SSL_VERIFYHOST,
cb->verify_host ? 2L : 0L);
curl_easy_setopt (cb->curl, CURLOPT_SSLVERSION, cb->sslversion);
if (cb->cacert != NULL)
curl_easy_setopt (cb->curl, CURLOPT_CAINFO, cb->cacert);
if (cb->capath != NULL)
curl_easy_setopt (cb->curl, CURLOPT_CAPATH, cb->capath);
if (cb->clientkey != NULL && cb->clientcert != NULL)
{
curl_easy_setopt (cb->curl, CURLOPT_SSLKEY, cb->clientkey);
curl_easy_setopt (cb->curl, CURLOPT_SSLCERT, cb->clientcert);
if (cb->clientkeypass != NULL)
curl_easy_setopt (cb->curl, CURLOPT_SSLKEYPASSWD, cb->clientkeypass);
}
wh_reset_buffer (cb);
return (0);
} /* }}} int wh_callback_init */
static int wh_flush_nolock (cdtime_t timeout, wh_callback_t *cb) /* {{{ */
{
int status;
DEBUG ("write_http plugin: wh_flush_nolock: timeout = %.3f; "
"send_buffer_fill = %zu;",
CDTIME_T_TO_DOUBLE (timeout),
cb->send_buffer_fill);
/* timeout == 0 => flush unconditionally */
if (timeout > 0)
{
cdtime_t now;
now = cdtime ();
if ((cb->send_buffer_init_time + timeout) > now)
return (0);
}
if (cb->format == WH_FORMAT_COMMAND)
{
if (cb->send_buffer_fill <= 0)
{
cb->send_buffer_init_time = cdtime ();
return (0);
}
status = wh_send_buffer (cb);
wh_reset_buffer (cb);
}
else if (cb->format == WH_FORMAT_JSON)
{
if (cb->send_buffer_fill <= 2)
{
cb->send_buffer_init_time = cdtime ();
return (0);
}
status = format_json_finalize (cb->send_buffer,
&cb->send_buffer_fill,
&cb->send_buffer_free);
if (status != 0)
{
ERROR ("write_http: wh_flush_nolock: "
"format_json_finalize failed.");
wh_reset_buffer (cb);
return (status);
}
status = wh_send_buffer (cb);
wh_reset_buffer (cb);
}
else
{
ERROR ("write_http: wh_flush_nolock: "
"Unknown format: %i",
cb->format);
return (-1);
}
return (status);
} /* }}} wh_flush_nolock */
static int wh_flush (cdtime_t timeout, /* {{{ */
const char *identifier __attribute__((unused)),
user_data_t *user_data)
{
wh_callback_t *cb;
int status;
if (user_data == NULL)
return (-EINVAL);
cb = user_data->data;
pthread_mutex_lock (&cb->send_lock);
if (cb->curl == NULL)
{
status = wh_callback_init (cb);
if (status != 0)
{
ERROR ("write_http plugin: wh_callback_init failed.");
pthread_mutex_unlock (&cb->send_lock);
return (-1);
}
}
status = wh_flush_nolock (timeout, cb);
pthread_mutex_unlock (&cb->send_lock);
return (status);
} /* }}} int wh_flush */
static void wh_callback_free (void *data) /* {{{ */
{
wh_callback_t *cb;
if (data == NULL)
return;
cb = data;
wh_flush_nolock (/* timeout = */ 0, cb);
curl_easy_cleanup (cb->curl);
sfree (cb->location);
sfree (cb->user);
sfree (cb->pass);
sfree (cb->credentials);
sfree (cb->cacert);
sfree (cb->capath);
sfree (cb->clientkey);
sfree (cb->clientcert);
sfree (cb->clientkeypass);
sfree (cb);
} /* }}} void wh_callback_free */
static int wh_write_command (const data_set_t *ds, const value_list_t *vl, /* {{{ */
wh_callback_t *cb)
{
char key[10*DATA_MAX_NAME_LEN];
char values[512];
char command[1024];
size_t command_len;
int status;
if (0 != strcmp (ds->type, vl->type)) {
ERROR ("write_http plugin: DS type does not match "
"value list type");
return -1;
}
/* Copy the identifier to `key' and escape it. */
status = FORMAT_VL (key, sizeof (key), vl);
if (status != 0) {
ERROR ("write_http plugin: error with format_name");
return (status);
}
escape_string (key, sizeof (key));
/* Convert the values to an ASCII representation and put that into
* `values'. */
status = format_values (values, sizeof (values), ds, vl, cb->store_rates);
if (status != 0) {
ERROR ("write_http plugin: error with "
"wh_value_list_to_string");
return (status);
}
command_len = (size_t) ssnprintf (command, sizeof (command),
"PUTVAL %s interval=%.3f %s\r\n",
key,
CDTIME_T_TO_DOUBLE (vl->interval),
values);
if (command_len >= sizeof (command)) {
ERROR ("write_http plugin: Command buffer too small: "
"Need %zu bytes.", command_len + 1);
return (-1);
}
pthread_mutex_lock (&cb->send_lock);
if (cb->curl == NULL)
{
status = wh_callback_init (cb);
if (status != 0)
{
ERROR ("write_http plugin: wh_callback_init failed.");
pthread_mutex_unlock (&cb->send_lock);
return (-1);
}
}
if (command_len >= cb->send_buffer_free)
{
status = wh_flush_nolock (/* timeout = */ 0, cb);
if (status != 0)
{
pthread_mutex_unlock (&cb->send_lock);
return (status);
}
}
assert (command_len < cb->send_buffer_free);
/* `command_len + 1' because `command_len' does not include the
* trailing null byte. Neither does `send_buffer_fill'. */
memcpy (cb->send_buffer + cb->send_buffer_fill,
command, command_len + 1);
cb->send_buffer_fill += command_len;
cb->send_buffer_free -= command_len;
DEBUG ("write_http plugin: <%s> buffer %zu/%zu (%g%%) \"%s\"",
cb->location,
cb->send_buffer_fill, sizeof (cb->send_buffer),
100.0 * ((double) cb->send_buffer_fill) / ((double) sizeof (cb->send_buffer)),
command);
/* Check if we have enough space for this command. */
pthread_mutex_unlock (&cb->send_lock);
return (0);
} /* }}} int wh_write_command */
static int wh_write_json (const data_set_t *ds, const value_list_t *vl, /* {{{ */
wh_callback_t *cb)
{
int status;
pthread_mutex_lock (&cb->send_lock);
if (cb->curl == NULL)
{
status = wh_callback_init (cb);
if (status != 0)
{
ERROR ("write_http plugin: wh_callback_init failed.");
pthread_mutex_unlock (&cb->send_lock);
return (-1);
}
}
status = format_json_value_list (cb->send_buffer,
&cb->send_buffer_fill,
&cb->send_buffer_free,
ds, vl, cb->store_rates);
if (status == (-ENOMEM))
{
status = wh_flush_nolock (/* timeout = */ 0, cb);
if (status != 0)
{
wh_reset_buffer (cb);
pthread_mutex_unlock (&cb->send_lock);
return (status);
}
status = format_json_value_list (cb->send_buffer,
&cb->send_buffer_fill,
&cb->send_buffer_free,
ds, vl, cb->store_rates);
}
if (status != 0)
{
pthread_mutex_unlock (&cb->send_lock);
return (status);
}
DEBUG ("write_http plugin: <%s> buffer %zu/%zu (%g%%)",
cb->location,
cb->send_buffer_fill, sizeof (cb->send_buffer),
100.0 * ((double) cb->send_buffer_fill) / ((double) sizeof (cb->send_buffer)));
/* Check if we have enough space for this command. */
pthread_mutex_unlock (&cb->send_lock);
return (0);
} /* }}} int wh_write_json */
static int wh_write (const data_set_t *ds, const value_list_t *vl, /* {{{ */
user_data_t *user_data)
{
wh_callback_t *cb;
int status;
if (user_data == NULL)
return (-EINVAL);
cb = user_data->data;
if (cb->format == WH_FORMAT_JSON)
status = wh_write_json (ds, vl, cb);
else
status = wh_write_command (ds, vl, cb);
return (status);
} /* }}} int wh_write */
static int config_set_format (wh_callback_t *cb, /* {{{ */
oconfig_item_t *ci)
{
char *string;
if ((ci->values_num != 1)
|| (ci->values[0].type != OCONFIG_TYPE_STRING))
{
WARNING ("write_http plugin: The `%s' config option "
"needs exactly one string argument.", ci->key);
return (-1);
}
string = ci->values[0].value.string;
if (strcasecmp ("Command", string) == 0)
cb->format = WH_FORMAT_COMMAND;
else if (strcasecmp ("JSON", string) == 0)
cb->format = WH_FORMAT_JSON;
else
{
ERROR ("write_http plugin: Invalid format string: %s",
string);
return (-1);
}
return (0);
} /* }}} int config_set_format */
static int wh_config_url (oconfig_item_t *ci) /* {{{ */
{
wh_callback_t *cb;
user_data_t user_data;
int i;
cb = malloc (sizeof (*cb));
if (cb == NULL)
{
ERROR ("write_http plugin: malloc failed.");
return (-1);
}
memset (cb, 0, sizeof (*cb));
cb->verify_peer = 1;
cb->verify_host = 1;
cb->format = WH_FORMAT_COMMAND;
cb->sslversion = CURL_SSLVERSION_DEFAULT;
pthread_mutex_init (&cb->send_lock, /* attr = */ NULL);
cf_util_get_string (ci, &cb->location);
if (cb->location == NULL)
return (-1);
for (i = 0; i < ci->children_num; i++)
{
oconfig_item_t *child = ci->children + i;
if (strcasecmp ("User", child->key) == 0)
cf_util_get_string (child, &cb->user);
else if (strcasecmp ("Password", child->key) == 0)
cf_util_get_string (child, &cb->pass);
else if (strcasecmp ("VerifyPeer", child->key) == 0)
cf_util_get_boolean (child, &cb->verify_peer);
else if (strcasecmp ("VerifyHost", child->key) == 0)
cf_util_get_boolean (child, &cb->verify_host);
else if (strcasecmp ("CACert", child->key) == 0)
cf_util_get_string (child, &cb->cacert);
else if (strcasecmp ("CAPath", child->key) == 0)
cf_util_get_string (child, &cb->capath);
else if (strcasecmp ("ClientKey", child->key) == 0)
cf_util_get_string (child, &cb->clientkey);
else if (strcasecmp ("ClientCert", child->key) == 0)
cf_util_get_string (child, &cb->clientcert);
else if (strcasecmp ("ClientKeyPass", child->key) == 0)
cf_util_get_string (child, &cb->clientkeypass);
else if (strcasecmp ("SSLVersion", child->key) == 0)
{
char *value = NULL;
cf_util_get_string (child, &value);
if (value == NULL || strcasecmp ("default", value) == 0)
cb->sslversion = CURL_SSLVERSION_DEFAULT;
else if (strcasecmp ("SSLv2", value) == 0)
cb->sslversion = CURL_SSLVERSION_SSLv2;
else if (strcasecmp ("SSLv3", value) == 0)
cb->sslversion = CURL_SSLVERSION_SSLv3;
else if (strcasecmp ("TLSv1", value) == 0)
cb->sslversion = CURL_SSLVERSION_TLSv1;
#if (LIBCURL_VERSION_MAJOR > 7) || (LIBCURL_VERSION_MAJOR == 7 && LIBCURL_VERSION_MINOR >= 34)
else if (strcasecmp ("TLSv1_0", value) == 0)
cb->sslversion = CURL_SSLVERSION_TLSv1_0;
else if (strcasecmp ("TLSv1_1", value) == 0)
cb->sslversion = CURL_SSLVERSION_TLSv1_1;
else if (strcasecmp ("TLSv1_2", value) == 0)
cb->sslversion = CURL_SSLVERSION_TLSv1_2;
#endif
else
ERROR ("write_http plugin: Invalid SSLVersion "
"option: %s.", value);
sfree(value);
}
else if (strcasecmp ("Format", child->key) == 0)
config_set_format (cb, child);
else if (strcasecmp ("StoreRates", child->key) == 0)
cf_util_get_boolean (child, &cb->store_rates);
else
{
ERROR ("write_http plugin: Invalid configuration "
"option: %s.", child->key);
}
}
DEBUG ("write_http: Registering write callback with URL %s",
cb->location);
memset (&user_data, 0, sizeof (user_data));
user_data.data = cb;
user_data.free_func = NULL;
plugin_register_flush ("write_http", wh_flush, &user_data);
user_data.free_func = wh_callback_free;
plugin_register_write ("write_http", wh_write, &user_data);
return (0);
} /* }}} int wh_config_url */
static int wh_config (oconfig_item_t *ci) /* {{{ */
{
int i;
for (i = 0; i < ci->children_num; i++)
{
oconfig_item_t *child = ci->children + i;
if (strcasecmp ("URL", child->key) == 0)
wh_config_url (child);
else
{
ERROR ("write_http plugin: Invalid configuration "
"option: %s.", child->key);
}
}
return (0);
} /* }}} int wh_config */
void module_register (void) /* {{{ */
{
plugin_register_complex_config ("write_http", wh_config);
} /* }}} void module_register */
/* vim: set fdm=marker sw=8 ts=8 tw=78 et : */
|
cybem/collectd-iow
|
src/write_http.c
|
C
|
gpl-2.0
| 20,803
|
#include <linux/kernel.h>
#include <linux/jiffies.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/tty.h>
#include <linux/tty_driver.h>
#include <linux/tty_flip.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/mutex.h>
#include <linux/serial.h>
#include <linux/ioctl.h>
#include <linux/firmware.h>
#include <linux/uaccess.h>
#include <linux/usb.h>
#include <linux/usb/serial.h>
#include "io_16654.h"
#include "io_usbvend.h"
#include "io_ti.h"
#define DRIVER_VERSION "v0.7mode043006"
#define DRIVER_AUTHOR "Greg Kroah-Hartman <greg@kroah.com> and David Iacovelli"
#define DRIVER_DESC "Edgeport USB Serial Driver"
#define EPROM_PAGE_SIZE 64
struct edgeport_uart_buf_desc {
__u32 count;
};
#define HARDWARE_TYPE_930 0
#define HARDWARE_TYPE_TIUMP 1
#define TI_MODE_CONFIGURING 0
#define TI_MODE_BOOT 1
#define TI_MODE_DOWNLOAD 2
#define TI_MODE_TRANSITIONING 3
#define EDGE_READ_URB_RUNNING 0
#define EDGE_READ_URB_STOPPING 1
#define EDGE_READ_URB_STOPPED 2
#define EDGE_CLOSING_WAIT 4000
#define EDGE_OUT_BUF_SIZE 1024
struct product_info {
int TiMode;
__u8 hardware_type;
} __attribute__((packed));
struct edge_buf {
unsigned int buf_size;
char *buf_buf;
char *buf_get;
char *buf_put;
};
struct edgeport_port {
__u16 uart_base;
__u16 dma_address;
__u8 shadow_msr;
__u8 shadow_mcr;
__u8 shadow_lsr;
__u8 lsr_mask;
__u32 ump_read_timeout;
int baud_rate;
int close_pending;
int lsr_event;
struct edgeport_uart_buf_desc tx;
struct async_icount icount;
wait_queue_head_t delta_msr_wait;
struct edgeport_serial *edge_serial;
struct usb_serial_port *port;
__u8 bUartMode;
spinlock_t ep_lock;
int ep_read_urb_state;
int ep_write_urb_in_use;
struct edge_buf *ep_out_buf;
};
struct edgeport_serial {
struct product_info product_info;
u8 TI_I2C_Type;
u8 TiReadI2C;
struct mutex es_lock;
int num_ports_open;
struct usb_serial *serial;
};
static struct usb_device_id edgeport_1port_id_table [] = {
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_1) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_TI3410_EDGEPORT_1) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_TI3410_EDGEPORT_1I) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_PROXIMITY) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_MOTION) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_MOISTURE) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_TEMPERATURE) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_HUMIDITY) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_POWER) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_LIGHT) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_RADIATION) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_DISTANCE) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_ACCELERATION) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_PROX_DIST) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_PLUS_PWR_HP4CD) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_PLUS_PWR_PCI) },
{ }
};
static struct usb_device_id edgeport_2port_id_table [] = {
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_2) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_2C) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_2I) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_421) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_21) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_42) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_4) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_4I) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_22I) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_221C) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_22C) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_21C) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_4S) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_8) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_8S) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_416) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_416B) },
{ }
};
static struct usb_device_id id_table_combined [] = {
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_1) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_TI3410_EDGEPORT_1) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_TI3410_EDGEPORT_1I) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_PROXIMITY) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_MOTION) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_MOISTURE) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_TEMPERATURE) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_HUMIDITY) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_POWER) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_LIGHT) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_RADIATION) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_DISTANCE) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_ACCELERATION) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_WP_PROX_DIST) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_PLUS_PWR_HP4CD) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_PLUS_PWR_PCI) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_2) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_2C) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_2I) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_421) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_21) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_42) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_4) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_4I) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_22I) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_221C) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_22C) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_21C) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_4S) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_8) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_8S) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_416) },
{ USB_DEVICE(USB_VENDOR_ID_ION, ION_DEVICE_ID_TI_EDGEPORT_416B) },
{ }
};
MODULE_DEVICE_TABLE(usb, id_table_combined);
static struct usb_driver io_driver = {
.name = "io_ti",
.probe = usb_serial_probe,
.disconnect = usb_serial_disconnect,
.id_table = id_table_combined,
.no_dynamic_id = 1,
};
static unsigned char OperationalMajorVersion;
static unsigned char OperationalMinorVersion;
static unsigned short OperationalBuildNumber;
static int debug;
static int closing_wait = EDGE_CLOSING_WAIT;
static int ignore_cpu_rev;
static int default_uart_mode;
static void edge_tty_recv(struct device *dev, struct tty_struct *tty,
unsigned char *data, int length);
static void stop_read(struct edgeport_port *edge_port);
static int restart_read(struct edgeport_port *edge_port);
static void edge_set_termios(struct tty_struct *tty,
struct usb_serial_port *port, struct ktermios *old_termios);
static void edge_send(struct tty_struct *tty);
static int edge_create_sysfs_attrs(struct usb_serial_port *port);
static int edge_remove_sysfs_attrs(struct usb_serial_port *port);
static struct edge_buf *edge_buf_alloc(unsigned int size);
static void edge_buf_free(struct edge_buf *eb);
static void edge_buf_clear(struct edge_buf *eb);
static unsigned int edge_buf_data_avail(struct edge_buf *eb);
static unsigned int edge_buf_space_avail(struct edge_buf *eb);
static unsigned int edge_buf_put(struct edge_buf *eb, const char *buf,
unsigned int count);
static unsigned int edge_buf_get(struct edge_buf *eb, char *buf,
unsigned int count);
static int ti_vread_sync(struct usb_device *dev, __u8 request,
__u16 value, __u16 index, u8 *data, int size)
{
int status;
status = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0), request,
(USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN),
value, index, data, size, 1000);
if (status < 0)
return status;
if (status != size) {
dbg("%s - wanted to write %d, but only wrote %d",
__func__, size, status);
return -ECOMM;
}
return 0;
}
static int ti_vsend_sync(struct usb_device *dev, __u8 request,
__u16 value, __u16 index, u8 *data, int size)
{
int status;
status = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), request,
(USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT),
value, index, data, size, 1000);
if (status < 0)
return status;
if (status != size) {
dbg("%s - wanted to write %d, but only wrote %d",
__func__, size, status);
return -ECOMM;
}
return 0;
}
static int send_cmd(struct usb_device *dev, __u8 command,
__u8 moduleid, __u16 value, u8 *data,
int size)
{
return ti_vsend_sync(dev, command, value, moduleid, data, size);
}
static int purge_port(struct usb_serial_port *port, __u16 mask)
{
int port_number = port->number - port->serial->minor;
dbg("%s - port %d, mask %x", __func__, port_number, mask);
return send_cmd(port->serial->dev,
UMPC_PURGE_PORT,
(__u8)(UMPM_UART1_PORT + port_number),
mask,
NULL,
0);
}
static int read_download_mem(struct usb_device *dev, int start_address,
int length, __u8 address_type, __u8 *buffer)
{
int status = 0;
__u8 read_length;
__be16 be_start_address;
dbg("%s - @ %x for %d", __func__, start_address, length);
while (length) {
if (length > 64)
read_length = 64;
else
read_length = (__u8)length;
if (read_length > 1) {
dbg("%s - @ %x for %d", __func__,
start_address, read_length);
}
be_start_address = cpu_to_be16(start_address);
status = ti_vread_sync(dev, UMPC_MEMORY_READ,
(__u16)address_type,
(__force __u16)be_start_address,
buffer, read_length);
if (status) {
dbg("%s - ERROR %x", __func__, status);
return status;
}
if (read_length > 1)
usb_serial_debug_data(debug, &dev->dev, __func__,
read_length, buffer);
start_address += read_length;
buffer += read_length;
length -= read_length;
}
return status;
}
static int read_ram(struct usb_device *dev, int start_address,
int length, __u8 *buffer)
{
return read_download_mem(dev, start_address, length,
DTK_ADDR_SPACE_XDATA, buffer);
}
static int read_boot_mem(struct edgeport_serial *serial,
int start_address, int length, __u8 *buffer)
{
int status = 0;
int i;
for (i = 0; i < length; i++) {
status = ti_vread_sync(serial->serial->dev,
UMPC_MEMORY_READ, serial->TI_I2C_Type,
(__u16)(start_address+i), &buffer[i], 0x01);
if (status) {
dbg("%s - ERROR %x", __func__, status);
return status;
}
}
dbg("%s - start_address = %x, length = %d",
__func__, start_address, length);
usb_serial_debug_data(debug, &serial->serial->dev->dev,
__func__, length, buffer);
serial->TiReadI2C = 1;
return status;
}
static int write_boot_mem(struct edgeport_serial *serial,
int start_address, int length, __u8 *buffer)
{
int status = 0;
int i;
__u8 temp;
if (!serial->TiReadI2C) {
status = read_boot_mem(serial, 0, 1, &temp);
if (status)
return status;
}
for (i = 0; i < length; ++i) {
status = ti_vsend_sync(serial->serial->dev,
UMPC_MEMORY_WRITE, buffer[i],
(__u16)(i + start_address), NULL, 0);
if (status)
return status;
}
dbg("%s - start_sddr = %x, length = %d",
__func__, start_address, length);
usb_serial_debug_data(debug, &serial->serial->dev->dev,
__func__, length, buffer);
return status;
}
static int write_i2c_mem(struct edgeport_serial *serial,
int start_address, int length, __u8 address_type, __u8 *buffer)
{
int status = 0;
int write_length;
__be16 be_start_address;
write_length = EPROM_PAGE_SIZE -
(start_address & (EPROM_PAGE_SIZE - 1));
if (write_length > length)
write_length = length;
dbg("%s - BytesInFirstPage Addr = %x, length = %d",
__func__, start_address, write_length);
usb_serial_debug_data(debug, &serial->serial->dev->dev,
__func__, write_length, buffer);
be_start_address = cpu_to_be16(start_address);
status = ti_vsend_sync(serial->serial->dev,
UMPC_MEMORY_WRITE, (__u16)address_type,
(__force __u16)be_start_address,
buffer, write_length);
if (status) {
dbg("%s - ERROR %d", __func__, status);
return status;
}
length -= write_length;
start_address += write_length;
buffer += write_length;
while (length) {
if (length > EPROM_PAGE_SIZE)
write_length = EPROM_PAGE_SIZE;
else
write_length = length;
dbg("%s - Page Write Addr = %x, length = %d",
__func__, start_address, write_length);
usb_serial_debug_data(debug, &serial->serial->dev->dev,
__func__, write_length, buffer);
be_start_address = cpu_to_be16(start_address);
status = ti_vsend_sync(serial->serial->dev, UMPC_MEMORY_WRITE,
(__u16)address_type,
(__force __u16)be_start_address,
buffer, write_length);
if (status) {
dev_err(&serial->serial->dev->dev, "%s - ERROR %d\n",
__func__, status);
return status;
}
length -= write_length;
start_address += write_length;
buffer += write_length;
}
return status;
}
static int tx_active(struct edgeport_port *port)
{
int status;
struct out_endpoint_desc_block *oedb;
__u8 *lsr;
int bytes_left = 0;
oedb = kmalloc(sizeof(*oedb), GFP_KERNEL);
if (!oedb) {
dev_err(&port->port->dev, "%s - out of memory\n", __func__);
return -ENOMEM;
}
lsr = kmalloc(1, GFP_KERNEL);
if (!lsr) {
kfree(oedb);
return -ENOMEM;
}
status = read_ram(port->port->serial->dev, port->dma_address,
sizeof(*oedb), (void *)oedb);
if (status)
goto exit_is_tx_active;
dbg("%s - XByteCount 0x%X", __func__, oedb->XByteCount);
status = read_ram(port->port->serial->dev,
port->uart_base + UMPMEM_OFFS_UART_LSR, 1, lsr);
if (status)
goto exit_is_tx_active;
dbg("%s - LSR = 0x%X", __func__, *lsr);
if ((oedb->XByteCount & 0x80) != 0)
bytes_left += 64;
if ((*lsr & UMP_UART_LSR_TX_MASK) == 0)
bytes_left += 1;
exit_is_tx_active:
dbg("%s - return %d", __func__, bytes_left);
kfree(lsr);
kfree(oedb);
return bytes_left;
}
static void chase_port(struct edgeport_port *port, unsigned long timeout,
int flush)
{
int baud_rate;
struct tty_struct *tty = tty_port_tty_get(&port->port->port);
wait_queue_t wait;
unsigned long flags;
if (!timeout)
timeout = (HZ * EDGE_CLOSING_WAIT)/100;
spin_lock_irqsave(&port->ep_lock, flags);
init_waitqueue_entry(&wait, current);
add_wait_queue(&tty->write_wait, &wait);
for (;;) {
set_current_state(TASK_INTERRUPTIBLE);
if (edge_buf_data_avail(port->ep_out_buf) == 0
|| timeout == 0 || signal_pending(current)
|| !usb_get_intfdata(port->port->serial->interface))
break;
spin_unlock_irqrestore(&port->ep_lock, flags);
timeout = schedule_timeout(timeout);
spin_lock_irqsave(&port->ep_lock, flags);
}
set_current_state(TASK_RUNNING);
remove_wait_queue(&tty->write_wait, &wait);
if (flush)
edge_buf_clear(port->ep_out_buf);
spin_unlock_irqrestore(&port->ep_lock, flags);
tty_kref_put(tty);
timeout += jiffies;
while ((long)(jiffies - timeout) < 0 && !signal_pending(current)
&& usb_get_intfdata(port->port->serial->interface)) {
if (!tx_active(port))
break;
msleep(10);
}
if (!usb_get_intfdata(port->port->serial->interface))
return;
baud_rate = port->baud_rate;
if (baud_rate == 0)
baud_rate = 50;
msleep(max(1, DIV_ROUND_UP(10000, baud_rate)));
}
static int choose_config(struct usb_device *dev)
{
dbg("%s - Number of Interfaces = %d",
__func__, dev->config->desc.bNumInterfaces);
dbg("%s - MAX Power = %d",
__func__, dev->config->desc.bMaxPower * 2);
if (dev->config->desc.bNumInterfaces != 1) {
dev_err(&dev->dev, "%s - bNumInterfaces is not 1, ERROR!\n",
__func__);
return -ENODEV;
}
return 0;
}
static int read_rom(struct edgeport_serial *serial,
int start_address, int length, __u8 *buffer)
{
int status;
if (serial->product_info.TiMode == TI_MODE_DOWNLOAD) {
status = read_download_mem(serial->serial->dev,
start_address,
length,
serial->TI_I2C_Type,
buffer);
} else {
status = read_boot_mem(serial, start_address, length,
buffer);
}
return status;
}
static int write_rom(struct edgeport_serial *serial, int start_address,
int length, __u8 *buffer)
{
if (serial->product_info.TiMode == TI_MODE_BOOT)
return write_boot_mem(serial, start_address, length,
buffer);
if (serial->product_info.TiMode == TI_MODE_DOWNLOAD)
return write_i2c_mem(serial, start_address, length,
serial->TI_I2C_Type, buffer);
return -EINVAL;
}
static int get_descriptor_addr(struct edgeport_serial *serial,
int desc_type, struct ti_i2c_desc *rom_desc)
{
int start_address;
int status;
start_address = 2;
do {
status = read_rom(serial,
start_address,
sizeof(struct ti_i2c_desc),
(__u8 *)rom_desc);
if (status)
return 0;
if (rom_desc->Type == desc_type)
return start_address;
start_address = start_address + sizeof(struct ti_i2c_desc)
+ rom_desc->Size;
} while ((start_address < TI_MAX_I2C_SIZE) && rom_desc->Type);
return 0;
}
static int valid_csum(struct ti_i2c_desc *rom_desc, __u8 *buffer)
{
__u16 i;
__u8 cs = 0;
for (i = 0; i < rom_desc->Size; i++)
cs = (__u8)(cs + buffer[i]);
if (cs != rom_desc->CheckSum) {
dbg("%s - Mismatch %x - %x", __func__, rom_desc->CheckSum, cs);
return -EINVAL;
}
return 0;
}
static int check_i2c_image(struct edgeport_serial *serial)
{
struct device *dev = &serial->serial->dev->dev;
int status = 0;
struct ti_i2c_desc *rom_desc;
int start_address = 2;
__u8 *buffer;
__u16 ttype;
rom_desc = kmalloc(sizeof(*rom_desc), GFP_KERNEL);
if (!rom_desc) {
dev_err(dev, "%s - out of memory\n", __func__);
return -ENOMEM;
}
buffer = kmalloc(TI_MAX_I2C_SIZE, GFP_KERNEL);
if (!buffer) {
dev_err(dev, "%s - out of memory when allocating buffer\n",
__func__);
kfree(rom_desc);
return -ENOMEM;
}
status = read_rom(serial, 0, 1, buffer);
if (status)
goto out;
if (*buffer != UMP5152 && *buffer != UMP3410) {
dev_err(dev, "%s - invalid buffer signature\n", __func__);
status = -ENODEV;
goto out;
}
do {
status = read_rom(serial,
start_address,
sizeof(struct ti_i2c_desc),
(__u8 *)rom_desc);
if (status)
break;
if ((start_address + sizeof(struct ti_i2c_desc) +
rom_desc->Size) > TI_MAX_I2C_SIZE) {
status = -ENODEV;
dbg("%s - structure too big, erroring out.", __func__);
break;
}
dbg("%s Type = 0x%x", __func__, rom_desc->Type);
ttype = rom_desc->Type & 0x0f;
if (ttype != I2C_DESC_TYPE_FIRMWARE_BASIC
&& ttype != I2C_DESC_TYPE_FIRMWARE_AUTO) {
status = read_rom(serial, start_address +
sizeof(struct ti_i2c_desc),
rom_desc->Size, buffer);
if (status)
break;
status = valid_csum(rom_desc, buffer);
if (status)
break;
}
start_address = start_address + sizeof(struct ti_i2c_desc) +
rom_desc->Size;
} while ((rom_desc->Type != I2C_DESC_TYPE_ION) &&
(start_address < TI_MAX_I2C_SIZE));
if ((rom_desc->Type != I2C_DESC_TYPE_ION) ||
(start_address > TI_MAX_I2C_SIZE))
status = -ENODEV;
out:
kfree(buffer);
kfree(rom_desc);
return status;
}
static int get_manuf_info(struct edgeport_serial *serial, __u8 *buffer)
{
int status;
int start_address;
struct ti_i2c_desc *rom_desc;
struct edge_ti_manuf_descriptor *desc;
rom_desc = kmalloc(sizeof(*rom_desc), GFP_KERNEL);
if (!rom_desc) {
dev_err(&serial->serial->dev->dev, "%s - out of memory\n",
__func__);
return -ENOMEM;
}
start_address = get_descriptor_addr(serial, I2C_DESC_TYPE_ION,
rom_desc);
if (!start_address) {
dbg("%s - Edge Descriptor not found in I2C", __func__);
status = -ENODEV;
goto exit;
}
status = read_rom(serial, start_address+sizeof(struct ti_i2c_desc),
rom_desc->Size, buffer);
if (status)
goto exit;
status = valid_csum(rom_desc, buffer);
desc = (struct edge_ti_manuf_descriptor *)buffer;
dbg("%s - IonConfig 0x%x", __func__, desc->IonConfig);
dbg("%s - Version %d", __func__, desc->Version);
dbg("%s - Cpu/Board 0x%x", __func__, desc->CpuRev_BoardRev);
dbg("%s - NumPorts %d", __func__, desc->NumPorts);
dbg("%s - NumVirtualPorts %d", __func__, desc->NumVirtualPorts);
dbg("%s - TotalPorts %d", __func__, desc->TotalPorts);
exit:
kfree(rom_desc);
return status;
}
static int build_i2c_fw_hdr(__u8 *header, struct device *dev)
{
__u8 *buffer;
int buffer_size;
int i;
int err;
__u8 cs = 0;
struct ti_i2c_desc *i2c_header;
struct ti_i2c_image_header *img_header;
struct ti_i2c_firmware_rec *firmware_rec;
const struct firmware *fw;
const char *fw_name = "edgeport/down3.bin";
buffer_size = (((1024 * 16) - 512 ) +
sizeof(struct ti_i2c_firmware_rec));
buffer = kmalloc(buffer_size, GFP_KERNEL);
if (!buffer) {
dev_err(dev, "%s - out of memory\n", __func__);
return -ENOMEM;
}
memset(buffer, 0xff, buffer_size);
err = request_firmware(&fw, fw_name, dev);
if (err) {
printk(KERN_ERR "Failed to load image \"%s\" err %d\n",
fw_name, err);
kfree(buffer);
return err;
}
OperationalMajorVersion = fw->data[0];
OperationalMinorVersion = fw->data[1];
OperationalBuildNumber = fw->data[2] | (fw->data[3] << 8);
firmware_rec = (struct ti_i2c_firmware_rec *)buffer;
firmware_rec->Ver_Major = OperationalMajorVersion;
firmware_rec->Ver_Minor = OperationalMinorVersion;
img_header = (struct ti_i2c_image_header *)&fw->data[4];
memcpy(buffer + sizeof(struct ti_i2c_firmware_rec),
&fw->data[4 + sizeof(struct ti_i2c_image_header)],
le16_to_cpu(img_header->Length));
release_firmware(fw);
for (i=0; i < buffer_size; i++) {
cs = (__u8)(cs + buffer[i]);
}
kfree(buffer);
i2c_header = (struct ti_i2c_desc *)header;
firmware_rec = (struct ti_i2c_firmware_rec*)i2c_header->Data;
i2c_header->Type = I2C_DESC_TYPE_FIRMWARE_BLANK;
i2c_header->Size = (__u16)buffer_size;
i2c_header->CheckSum = cs;
firmware_rec->Ver_Major = OperationalMajorVersion;
firmware_rec->Ver_Minor = OperationalMinorVersion;
return 0;
}
static int i2c_type_bootmode(struct edgeport_serial *serial)
{
int status;
__u8 data;
status = ti_vread_sync(serial->serial->dev, UMPC_MEMORY_READ,
DTK_ADDR_SPACE_I2C_TYPE_II, 0, &data, 0x01);
if (status)
dbg("%s - read 2 status error = %d", __func__, status);
else
dbg("%s - read 2 data = 0x%x", __func__, data);
if ((!status) && (data == UMP5152 || data == UMP3410)) {
dbg("%s - ROM_TYPE_II", __func__);
serial->TI_I2C_Type = DTK_ADDR_SPACE_I2C_TYPE_II;
return 0;
}
status = ti_vread_sync(serial->serial->dev, UMPC_MEMORY_READ,
DTK_ADDR_SPACE_I2C_TYPE_III, 0, &data, 0x01);
if (status)
dbg("%s - read 3 status error = %d", __func__, status);
else
dbg("%s - read 2 data = 0x%x", __func__, data);
if ((!status) && (data == UMP5152 || data == UMP3410)) {
dbg("%s - ROM_TYPE_III", __func__);
serial->TI_I2C_Type = DTK_ADDR_SPACE_I2C_TYPE_III;
return 0;
}
dbg("%s - Unknown", __func__);
serial->TI_I2C_Type = DTK_ADDR_SPACE_I2C_TYPE_II;
return -ENODEV;
}
static int bulk_xfer(struct usb_serial *serial, void *buffer,
int length, int *num_sent)
{
int status;
status = usb_bulk_msg(serial->dev,
usb_sndbulkpipe(serial->dev,
serial->port[0]->bulk_out_endpointAddress),
buffer, length, num_sent, 1000);
return status;
}
static int download_code(struct edgeport_serial *serial, __u8 *image,
int image_length)
{
int status = 0;
int pos;
int transfer;
int done;
for (pos = 0; pos < image_length; ) {
transfer = image_length - pos;
if (transfer > EDGE_FW_BULK_MAX_PACKET_SIZE)
transfer = EDGE_FW_BULK_MAX_PACKET_SIZE;
status = bulk_xfer(serial->serial, &image[pos],
transfer, &done);
if (status)
break;
pos += done;
}
return status;
}
static int config_boot_dev(struct usb_device *dev)
{
return 0;
}
static int ti_cpu_rev(struct edge_ti_manuf_descriptor *desc)
{
return TI_GET_CPU_REVISION(desc->CpuRev_BoardRev);
}
static int download_fw(struct edgeport_serial *serial)
{
struct device *dev = &serial->serial->dev->dev;
int status = 0;
int start_address;
struct edge_ti_manuf_descriptor *ti_manuf_desc;
struct usb_interface_descriptor *interface;
int download_cur_ver;
int download_new_ver;
serial->product_info.hardware_type = HARDWARE_TYPE_TIUMP;
serial->TI_I2C_Type = DTK_ADDR_SPACE_I2C_TYPE_II;
status = choose_config(serial->serial->dev);
if (status)
return status;
interface = &serial->serial->interface->cur_altsetting->desc;
if (!interface) {
dev_err(dev, "%s - no interface set, error!\n", __func__);
return -ENODEV;
}
if (interface->bNumEndpoints > 1)
serial->product_info.TiMode = TI_MODE_DOWNLOAD;
else
serial->product_info.TiMode = TI_MODE_CONFIGURING;
if (serial->product_info.TiMode == TI_MODE_DOWNLOAD) {
struct ti_i2c_desc *rom_desc;
dbg("%s - RUNNING IN DOWNLOAD MODE", __func__);
status = check_i2c_image(serial);
if (status) {
dbg("%s - DOWNLOAD MODE -- BAD I2C", __func__);
return status;
}
ti_manuf_desc = kmalloc(sizeof(*ti_manuf_desc), GFP_KERNEL);
if (!ti_manuf_desc) {
dev_err(dev, "%s - out of memory.\n", __func__);
return -ENOMEM;
}
status = get_manuf_info(serial, (__u8 *)ti_manuf_desc);
if (status) {
kfree(ti_manuf_desc);
return status;
}
if (!ignore_cpu_rev && ti_cpu_rev(ti_manuf_desc) < 2) {
dbg("%s - Wrong CPU Rev %d (Must be 2)",
__func__, ti_cpu_rev(ti_manuf_desc));
kfree(ti_manuf_desc);
return -EINVAL;
}
rom_desc = kmalloc(sizeof(*rom_desc), GFP_KERNEL);
if (!rom_desc) {
dev_err(dev, "%s - out of memory.\n", __func__);
kfree(ti_manuf_desc);
return -ENOMEM;
}
start_address = get_descriptor_addr(serial,
I2C_DESC_TYPE_FIRMWARE_BASIC, rom_desc);
if (start_address != 0) {
struct ti_i2c_firmware_rec *firmware_version;
__u8 record;
dbg("%s - Found Type FIRMWARE (Type 2) record",
__func__);
firmware_version = kmalloc(sizeof(*firmware_version),
GFP_KERNEL);
if (!firmware_version) {
dev_err(dev, "%s - out of memory.\n", __func__);
kfree(rom_desc);
kfree(ti_manuf_desc);
return -ENOMEM;
}
status = read_rom(serial, start_address +
sizeof(struct ti_i2c_desc),
sizeof(struct ti_i2c_firmware_rec),
(__u8 *)firmware_version);
if (status) {
kfree(firmware_version);
kfree(rom_desc);
kfree(ti_manuf_desc);
return status;
}
download_cur_ver = (firmware_version->Ver_Major << 8) +
(firmware_version->Ver_Minor);
download_new_ver = (OperationalMajorVersion << 8) +
(OperationalMinorVersion);
dbg("%s - >> FW Versions Device %d.%d Driver %d.%d",
__func__,
firmware_version->Ver_Major,
firmware_version->Ver_Minor,
OperationalMajorVersion,
OperationalMinorVersion);
if (download_cur_ver != download_new_ver) {
dbg("%s - Update I2C dld from %d.%d to %d.%d",
__func__,
firmware_version->Ver_Major,
firmware_version->Ver_Minor,
OperationalMajorVersion,
OperationalMinorVersion);
record = I2C_DESC_TYPE_FIRMWARE_BLANK;
status = write_rom(serial, start_address,
sizeof(record), &record);
if (status) {
kfree(firmware_version);
kfree(rom_desc);
kfree(ti_manuf_desc);
return status;
}
status = read_rom(serial,
start_address,
sizeof(record),
&record);
if (status) {
kfree(firmware_version);
kfree(rom_desc);
kfree(ti_manuf_desc);
return status;
}
if (record != I2C_DESC_TYPE_FIRMWARE_BLANK) {
dev_err(dev,
"%s - error resetting device\n",
__func__);
kfree(firmware_version);
kfree(rom_desc);
kfree(ti_manuf_desc);
return -ENODEV;
}
dbg("%s - HARDWARE RESET", __func__);
status = ti_vsend_sync(serial->serial->dev,
UMPC_HARDWARE_RESET,
0, 0, NULL, 0);
dbg("%s - HARDWARE RESET return %d",
__func__, status);
kfree(firmware_version);
kfree(rom_desc);
kfree(ti_manuf_desc);
return -ENODEV;
}
kfree(firmware_version);
}
else if ((start_address = get_descriptor_addr(serial, I2C_DESC_TYPE_FIRMWARE_BLANK, rom_desc)) != 0) {
#define HEADER_SIZE (sizeof(struct ti_i2c_desc) + \
sizeof(struct ti_i2c_firmware_rec))
__u8 *header;
__u8 *vheader;
header = kmalloc(HEADER_SIZE, GFP_KERNEL);
if (!header) {
dev_err(dev, "%s - out of memory.\n", __func__);
kfree(rom_desc);
kfree(ti_manuf_desc);
return -ENOMEM;
}
vheader = kmalloc(HEADER_SIZE, GFP_KERNEL);
if (!vheader) {
dev_err(dev, "%s - out of memory.\n", __func__);
kfree(header);
kfree(rom_desc);
kfree(ti_manuf_desc);
return -ENOMEM;
}
dbg("%s - Found Type BLANK FIRMWARE (Type F2) record",
__func__);
status = build_i2c_fw_hdr(header, dev);
if (status) {
kfree(vheader);
kfree(header);
kfree(rom_desc);
kfree(ti_manuf_desc);
return status;
}
status = write_rom(serial,
start_address,
HEADER_SIZE,
header);
if (status) {
kfree(vheader);
kfree(header);
kfree(rom_desc);
kfree(ti_manuf_desc);
return status;
}
status = read_rom(serial, start_address,
HEADER_SIZE, vheader);
if (status) {
dbg("%s - can't read header back", __func__);
kfree(vheader);
kfree(header);
kfree(rom_desc);
kfree(ti_manuf_desc);
return status;
}
if (memcmp(vheader, header, HEADER_SIZE)) {
dbg("%s - write download record failed",
__func__);
kfree(vheader);
kfree(header);
kfree(rom_desc);
kfree(ti_manuf_desc);
return status;
}
kfree(vheader);
kfree(header);
dbg("%s - Start firmware update", __func__);
status = ti_vsend_sync(serial->serial->dev,
UMPC_COPY_DNLD_TO_I2C, 0, 0, NULL, 0);
dbg("%s - Update complete 0x%x", __func__, status);
if (status) {
dev_err(dev,
"%s - UMPC_COPY_DNLD_TO_I2C failed\n",
__func__);
kfree(rom_desc);
kfree(ti_manuf_desc);
return status;
}
}
kfree(rom_desc);
kfree(ti_manuf_desc);
return 0;
}
dbg("%s - RUNNING IN BOOT MODE", __func__);
status = config_boot_dev(serial->serial->dev);
if (status)
return status;
if (le16_to_cpu(serial->serial->dev->descriptor.idVendor)
!= USB_VENDOR_ID_ION) {
dbg("%s - VID = 0x%x", __func__,
le16_to_cpu(serial->serial->dev->descriptor.idVendor));
serial->TI_I2C_Type = DTK_ADDR_SPACE_I2C_TYPE_II;
goto stayinbootmode;
}
if (i2c_type_bootmode(serial))
goto stayinbootmode;
if (!check_i2c_image(serial)) {
struct ti_i2c_image_header *header;
int i;
__u8 cs = 0;
__u8 *buffer;
int buffer_size;
int err;
const struct firmware *fw;
const char *fw_name = "edgeport/down3.bin";
ti_manuf_desc = kmalloc(sizeof(*ti_manuf_desc), GFP_KERNEL);
if (!ti_manuf_desc) {
dev_err(dev, "%s - out of memory.\n", __func__);
return -ENOMEM;
}
status = get_manuf_info(serial, (__u8 *)ti_manuf_desc);
if (status) {
kfree(ti_manuf_desc);
goto stayinbootmode;
}
if (!ignore_cpu_rev && ti_cpu_rev(ti_manuf_desc) < 2) {
dbg("%s - Wrong CPU Rev %d (Must be 2)",
__func__, ti_cpu_rev(ti_manuf_desc));
kfree(ti_manuf_desc);
goto stayinbootmode;
}
kfree(ti_manuf_desc);
buffer_size = (((1024 * 16) - 512) +
sizeof(struct ti_i2c_image_header));
buffer = kmalloc(buffer_size, GFP_KERNEL);
if (!buffer) {
dev_err(dev, "%s - out of memory\n", __func__);
return -ENOMEM;
}
memset(buffer, 0xff, buffer_size);
err = request_firmware(&fw, fw_name, dev);
if (err) {
printk(KERN_ERR "Failed to load image \"%s\" err %d\n",
fw_name, err);
kfree(buffer);
return err;
}
memcpy(buffer, &fw->data[4], fw->size - 4);
release_firmware(fw);
for (i = sizeof(struct ti_i2c_image_header);
i < buffer_size; i++) {
cs = (__u8)(cs + buffer[i]);
}
header = (struct ti_i2c_image_header *)buffer;
header->Length = cpu_to_le16((__u16)(buffer_size -
sizeof(struct ti_i2c_image_header)));
header->CheckSum = cs;
dbg("%s - Downloading operational code image (TI UMP)",
__func__);
status = download_code(serial, buffer, buffer_size);
kfree(buffer);
if (status) {
dbg("%s - Error downloading operational code image",
__func__);
return status;
}
serial->product_info.TiMode = TI_MODE_TRANSITIONING;
dbg("%s - Download successful -- Device rebooting...",
__func__);
return -ENODEV;
}
stayinbootmode:
dbg("%s - STAYING IN BOOT MODE", __func__);
serial->product_info.TiMode = TI_MODE_BOOT;
return 0;
}
static int ti_do_config(struct edgeport_port *port, int feature, int on)
{
int port_number = port->port->number - port->port->serial->minor;
on = !!on;
return send_cmd(port->port->serial->dev,
feature, (__u8)(UMPM_UART1_PORT + port_number),
on, NULL, 0);
}
static int restore_mcr(struct edgeport_port *port, __u8 mcr)
{
int status = 0;
dbg("%s - %x", __func__, mcr);
status = ti_do_config(port, UMPC_SET_CLR_DTR, mcr & MCR_DTR);
if (status)
return status;
status = ti_do_config(port, UMPC_SET_CLR_RTS, mcr & MCR_RTS);
if (status)
return status;
return ti_do_config(port, UMPC_SET_CLR_LOOPBACK, mcr & MCR_LOOPBACK);
}
static __u8 map_line_status(__u8 ti_lsr)
{
__u8 lsr = 0;
#define MAP_FLAG(flagUmp, flagUart) \
if (ti_lsr & flagUmp) \
lsr |= flagUart;
MAP_FLAG(UMP_UART_LSR_OV_MASK, LSR_OVER_ERR)
MAP_FLAG(UMP_UART_LSR_PE_MASK, LSR_PAR_ERR)
MAP_FLAG(UMP_UART_LSR_FE_MASK, LSR_FRM_ERR)
MAP_FLAG(UMP_UART_LSR_BR_MASK, LSR_BREAK)
MAP_FLAG(UMP_UART_LSR_RX_MASK, LSR_RX_AVAIL)
MAP_FLAG(UMP_UART_LSR_TX_MASK, LSR_TX_EMPTY)
#undef MAP_FLAG
return lsr;
}
static void handle_new_msr(struct edgeport_port *edge_port, __u8 msr)
{
struct async_icount *icount;
struct tty_struct *tty;
dbg("%s - %02x", __func__, msr);
if (msr & (EDGEPORT_MSR_DELTA_CTS | EDGEPORT_MSR_DELTA_DSR |
EDGEPORT_MSR_DELTA_RI | EDGEPORT_MSR_DELTA_CD)) {
icount = &edge_port->icount;
if (msr & EDGEPORT_MSR_DELTA_CTS)
icount->cts++;
if (msr & EDGEPORT_MSR_DELTA_DSR)
icount->dsr++;
if (msr & EDGEPORT_MSR_DELTA_CD)
icount->dcd++;
if (msr & EDGEPORT_MSR_DELTA_RI)
icount->rng++;
wake_up_interruptible(&edge_port->delta_msr_wait);
}
edge_port->shadow_msr = msr & 0xf0;
tty = tty_port_tty_get(&edge_port->port->port);
if (tty && C_CRTSCTS(tty)) {
if (msr & EDGEPORT_MSR_CTS) {
tty->hw_stopped = 0;
tty_wakeup(tty);
} else {
tty->hw_stopped = 1;
}
}
tty_kref_put(tty);
return;
}
static void handle_new_lsr(struct edgeport_port *edge_port, int lsr_data,
__u8 lsr, __u8 data)
{
struct async_icount *icount;
__u8 new_lsr = (__u8)(lsr & (__u8)(LSR_OVER_ERR | LSR_PAR_ERR |
LSR_FRM_ERR | LSR_BREAK));
struct tty_struct *tty;
dbg("%s - %02x", __func__, new_lsr);
edge_port->shadow_lsr = lsr;
if (new_lsr & LSR_BREAK)
new_lsr &= (__u8)(LSR_OVER_ERR | LSR_BREAK);
if (lsr_data) {
tty = tty_port_tty_get(&edge_port->port->port);
if (tty) {
edge_tty_recv(&edge_port->port->dev, tty, &data, 1);
tty_kref_put(tty);
}
}
icount = &edge_port->icount;
if (new_lsr & LSR_BREAK)
icount->brk++;
if (new_lsr & LSR_OVER_ERR)
icount->overrun++;
if (new_lsr & LSR_PAR_ERR)
icount->parity++;
if (new_lsr & LSR_FRM_ERR)
icount->frame++;
}
static void edge_interrupt_callback(struct urb *urb)
{
struct edgeport_serial *edge_serial = urb->context;
struct usb_serial_port *port;
struct edgeport_port *edge_port;
unsigned char *data = urb->transfer_buffer;
int length = urb->actual_length;
int port_number;
int function;
int retval;
__u8 lsr;
__u8 msr;
int status = urb->status;
dbg("%s", __func__);
switch (status) {
case 0:
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
dbg("%s - urb shutting down with status: %d",
__func__, status);
return;
default:
dev_err(&urb->dev->dev, "%s - nonzero urb status received: "
"%d\n", __func__, status);
goto exit;
}
if (!length) {
dbg("%s - no data in urb", __func__);
goto exit;
}
usb_serial_debug_data(debug, &edge_serial->serial->dev->dev,
__func__, length, data);
if (length != 2) {
dbg("%s - expecting packet of size 2, got %d",
__func__, length);
goto exit;
}
port_number = TIUMP_GET_PORT_FROM_CODE(data[0]);
function = TIUMP_GET_FUNC_FROM_CODE(data[0]);
dbg("%s - port_number %d, function %d, info 0x%x",
__func__, port_number, function, data[1]);
port = edge_serial->serial->port[port_number];
edge_port = usb_get_serial_port_data(port);
if (!edge_port) {
dbg("%s - edge_port not found", __func__);
return;
}
switch (function) {
case TIUMP_INTERRUPT_CODE_LSR:
lsr = map_line_status(data[1]);
if (lsr & UMP_UART_LSR_DATA_MASK) {
dbg("%s - LSR Event Port %u LSR Status = %02x",
__func__, port_number, lsr);
edge_port->lsr_event = 1;
edge_port->lsr_mask = lsr;
} else {
dbg("%s - ===== Port %d LSR Status = %02x ======",
__func__, port_number, lsr);
handle_new_lsr(edge_port, 0, lsr, 0);
}
break;
case TIUMP_INTERRUPT_CODE_MSR:
msr = data[1];
dbg("%s - ===== Port %u MSR Status = %02x ======\n",
__func__, port_number, msr);
handle_new_msr(edge_port, msr);
break;
default:
dev_err(&urb->dev->dev,
"%s - Unknown Interrupt code from UMP %x\n",
__func__, data[1]);
break;
}
exit:
retval = usb_submit_urb(urb, GFP_ATOMIC);
if (retval)
dev_err(&urb->dev->dev,
"%s - usb_submit_urb failed with result %d\n",
__func__, retval);
}
static void edge_bulk_in_callback(struct urb *urb)
{
struct edgeport_port *edge_port = urb->context;
unsigned char *data = urb->transfer_buffer;
struct tty_struct *tty;
int retval = 0;
int port_number;
int status = urb->status;
dbg("%s", __func__);
switch (status) {
case 0:
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
dbg("%s - urb shutting down with status: %d",
__func__, status);
return;
default:
dev_err(&urb->dev->dev,
"%s - nonzero read bulk status received: %d\n",
__func__, status);
}
if (status == -EPIPE)
goto exit;
if (status) {
dev_err(&urb->dev->dev, "%s - stopping read!\n", __func__);
return;
}
port_number = edge_port->port->number - edge_port->port->serial->minor;
if (edge_port->lsr_event) {
edge_port->lsr_event = 0;
dbg("%s ===== Port %u LSR Status = %02x, Data = %02x ======",
__func__, port_number, edge_port->lsr_mask, *data);
handle_new_lsr(edge_port, 1, edge_port->lsr_mask, *data);
--urb->actual_length;
++data;
}
tty = tty_port_tty_get(&edge_port->port->port);
if (tty && urb->actual_length) {
usb_serial_debug_data(debug, &edge_port->port->dev,
__func__, urb->actual_length, data);
if (edge_port->close_pending)
dbg("%s - close pending, dropping data on the floor",
__func__);
else
edge_tty_recv(&edge_port->port->dev, tty, data,
urb->actual_length);
edge_port->icount.rx += urb->actual_length;
}
tty_kref_put(tty);
exit:
spin_lock(&edge_port->ep_lock);
if (edge_port->ep_read_urb_state == EDGE_READ_URB_RUNNING) {
urb->dev = edge_port->port->serial->dev;
retval = usb_submit_urb(urb, GFP_ATOMIC);
} else if (edge_port->ep_read_urb_state == EDGE_READ_URB_STOPPING) {
edge_port->ep_read_urb_state = EDGE_READ_URB_STOPPED;
}
spin_unlock(&edge_port->ep_lock);
if (retval)
dev_err(&urb->dev->dev,
"%s - usb_submit_urb failed with result %d\n",
__func__, retval);
}
static void edge_tty_recv(struct device *dev, struct tty_struct *tty,
unsigned char *data, int length)
{
int queued;
tty_buffer_request_room(tty, length);
queued = tty_insert_flip_string(tty, data, length);
if (queued < length)
dev_err(dev, "%s - dropping data, %d bytes lost\n",
__func__, length - queued);
tty_flip_buffer_push(tty);
}
static void edge_bulk_out_callback(struct urb *urb)
{
struct usb_serial_port *port = urb->context;
struct edgeport_port *edge_port = usb_get_serial_port_data(port);
int status = urb->status;
struct tty_struct *tty;
dbg("%s - port %d", __func__, port->number);
edge_port->ep_write_urb_in_use = 0;
switch (status) {
case 0:
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
dbg("%s - urb shutting down with status: %d",
__func__, status);
return;
default:
dev_err(&urb->dev->dev, "%s - nonzero write bulk status "
"received: %d\n", __func__, status);
}
tty = tty_port_tty_get(&port->port);
edge_send(tty);
tty_kref_put(tty);
}
static int edge_open(struct tty_struct *tty, struct usb_serial_port *port)
{
struct edgeport_port *edge_port = usb_get_serial_port_data(port);
struct edgeport_serial *edge_serial;
struct usb_device *dev;
struct urb *urb;
int port_number;
int status;
u16 open_settings;
u8 transaction_timeout;
dbg("%s - port %d", __func__, port->number);
if (edge_port == NULL)
return -ENODEV;
port_number = port->number - port->serial->minor;
switch (port_number) {
case 0:
edge_port->uart_base = UMPMEM_BASE_UART1;
edge_port->dma_address = UMPD_OEDB1_ADDRESS;
break;
case 1:
edge_port->uart_base = UMPMEM_BASE_UART2;
edge_port->dma_address = UMPD_OEDB2_ADDRESS;
break;
default:
dev_err(&port->dev, "Unknown port number!!!\n");
return -ENODEV;
}
dbg("%s - port_number = %d, uart_base = %04x, dma_address = %04x",
__func__, port_number, edge_port->uart_base,
edge_port->dma_address);
dev = port->serial->dev;
memset(&(edge_port->icount), 0x00, sizeof(edge_port->icount));
init_waitqueue_head(&edge_port->delta_msr_wait);
status = ti_do_config(edge_port, UMPC_SET_CLR_LOOPBACK, 0);
if (status) {
dev_err(&port->dev,
"%s - cannot send clear loopback command, %d\n",
__func__, status);
return status;
}
if (tty)
edge_set_termios(tty, port, tty->termios);
transaction_timeout = 2;
edge_port->ump_read_timeout =
max(20, ((transaction_timeout * 3) / 2));
open_settings = (u8)(UMP_DMA_MODE_CONTINOUS |
UMP_PIPE_TRANS_TIMEOUT_ENA |
(transaction_timeout << 2));
dbg("%s - Sending UMPC_OPEN_PORT", __func__);
status = send_cmd(dev, UMPC_OPEN_PORT,
(u8)(UMPM_UART1_PORT + port_number), open_settings, NULL, 0);
if (status) {
dev_err(&port->dev, "%s - cannot send open command, %d\n",
__func__, status);
return status;
}
status = send_cmd(dev, UMPC_START_PORT,
(u8)(UMPM_UART1_PORT + port_number), 0, NULL, 0);
if (status) {
dev_err(&port->dev, "%s - cannot send start DMA command, %d\n",
__func__, status);
return status;
}
status = purge_port(port, UMP_PORT_DIR_OUT | UMP_PORT_DIR_IN);
if (status) {
dev_err(&port->dev,
"%s - cannot send clear buffers command, %d\n",
__func__, status);
return status;
}
status = ti_vread_sync(dev, UMPC_READ_MSR, 0,
(__u16)(UMPM_UART1_PORT + port_number),
&edge_port->shadow_msr, 1);
if (status) {
dev_err(&port->dev, "%s - cannot send read MSR command, %d\n",
__func__, status);
return status;
}
dbg("ShadowMSR 0x%X", edge_port->shadow_msr);
edge_port->shadow_mcr = MCR_RTS | MCR_DTR;
dbg("ShadowMCR 0x%X", edge_port->shadow_mcr);
edge_serial = edge_port->edge_serial;
if (mutex_lock_interruptible(&edge_serial->es_lock))
return -ERESTARTSYS;
if (edge_serial->num_ports_open == 0) {
urb = edge_serial->serial->port[0]->interrupt_in_urb;
if (!urb) {
dev_err(&port->dev,
"%s - no interrupt urb present, exiting\n",
__func__);
status = -EINVAL;
goto release_es_lock;
}
urb->complete = edge_interrupt_callback;
urb->context = edge_serial;
urb->dev = dev;
status = usb_submit_urb(urb, GFP_KERNEL);
if (status) {
dev_err(&port->dev,
"%s - usb_submit_urb failed with value %d\n",
__func__, status);
goto release_es_lock;
}
}
usb_clear_halt(dev, port->write_urb->pipe);
usb_clear_halt(dev, port->read_urb->pipe);
urb = port->read_urb;
if (!urb) {
dev_err(&port->dev, "%s - no read urb present, exiting\n",
__func__);
status = -EINVAL;
goto unlink_int_urb;
}
edge_port->ep_read_urb_state = EDGE_READ_URB_RUNNING;
urb->complete = edge_bulk_in_callback;
urb->context = edge_port;
urb->dev = dev;
status = usb_submit_urb(urb, GFP_KERNEL);
if (status) {
dev_err(&port->dev,
"%s - read bulk usb_submit_urb failed with value %d\n",
__func__, status);
goto unlink_int_urb;
}
++edge_serial->num_ports_open;
dbg("%s - exited", __func__);
goto release_es_lock;
unlink_int_urb:
if (edge_port->edge_serial->num_ports_open == 0)
usb_kill_urb(port->serial->port[0]->interrupt_in_urb);
release_es_lock:
mutex_unlock(&edge_serial->es_lock);
return status;
}
static void edge_close(struct usb_serial_port *port)
{
struct edgeport_serial *edge_serial;
struct edgeport_port *edge_port;
int port_number;
int status;
dbg("%s - port %d", __func__, port->number);
edge_serial = usb_get_serial_data(port->serial);
edge_port = usb_get_serial_port_data(port);
if (edge_serial == NULL || edge_port == NULL)
return;
edge_port->close_pending = 1;
chase_port(edge_port, (HZ * closing_wait) / 100, 1);
usb_kill_urb(port->read_urb);
usb_kill_urb(port->write_urb);
edge_port->ep_write_urb_in_use = 0;
dbg("%s - send umpc_close_port", __func__);
port_number = port->number - port->serial->minor;
status = send_cmd(port->serial->dev,
UMPC_CLOSE_PORT,
(__u8)(UMPM_UART1_PORT + port_number),
0,
NULL,
0);
mutex_lock(&edge_serial->es_lock);
--edge_port->edge_serial->num_ports_open;
if (edge_port->edge_serial->num_ports_open <= 0) {
usb_kill_urb(port->serial->port[0]->interrupt_in_urb);
edge_port->edge_serial->num_ports_open = 0;
}
mutex_unlock(&edge_serial->es_lock);
edge_port->close_pending = 0;
dbg("%s - exited", __func__);
}
static int edge_write(struct tty_struct *tty, struct usb_serial_port *port,
const unsigned char *data, int count)
{
struct edgeport_port *edge_port = usb_get_serial_port_data(port);
unsigned long flags;
dbg("%s - port %d", __func__, port->number);
if (count == 0) {
dbg("%s - write request of 0 bytes", __func__);
return 0;
}
if (edge_port == NULL)
return -ENODEV;
if (edge_port->close_pending == 1)
return -ENODEV;
spin_lock_irqsave(&edge_port->ep_lock, flags);
count = edge_buf_put(edge_port->ep_out_buf, data, count);
spin_unlock_irqrestore(&edge_port->ep_lock, flags);
edge_send(tty);
return count;
}
static void edge_send(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
int count, result;
struct edgeport_port *edge_port = usb_get_serial_port_data(port);
unsigned long flags;
dbg("%s - port %d", __func__, port->number);
spin_lock_irqsave(&edge_port->ep_lock, flags);
if (edge_port->ep_write_urb_in_use) {
spin_unlock_irqrestore(&edge_port->ep_lock, flags);
return;
}
count = edge_buf_get(edge_port->ep_out_buf,
port->write_urb->transfer_buffer,
port->bulk_out_size);
if (count == 0) {
spin_unlock_irqrestore(&edge_port->ep_lock, flags);
return;
}
edge_port->ep_write_urb_in_use = 1;
spin_unlock_irqrestore(&edge_port->ep_lock, flags);
usb_serial_debug_data(debug, &port->dev, __func__, count,
port->write_urb->transfer_buffer);
usb_fill_bulk_urb(port->write_urb, port->serial->dev,
usb_sndbulkpipe(port->serial->dev,
port->bulk_out_endpointAddress),
port->write_urb->transfer_buffer, count,
edge_bulk_out_callback,
port);
result = usb_submit_urb(port->write_urb, GFP_ATOMIC);
if (result) {
dev_err(&port->dev,
"%s - failed submitting write urb, error %d\n",
__func__, result);
edge_port->ep_write_urb_in_use = 0;
} else
edge_port->icount.tx += count;
if (tty)
tty_wakeup(tty);
}
static int edge_write_room(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct edgeport_port *edge_port = usb_get_serial_port_data(port);
int room = 0;
unsigned long flags;
dbg("%s - port %d", __func__, port->number);
if (edge_port == NULL)
return 0;
if (edge_port->close_pending == 1)
return 0;
spin_lock_irqsave(&edge_port->ep_lock, flags);
room = edge_buf_space_avail(edge_port->ep_out_buf);
spin_unlock_irqrestore(&edge_port->ep_lock, flags);
dbg("%s - returns %d", __func__, room);
return room;
}
static int edge_chars_in_buffer(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct edgeport_port *edge_port = usb_get_serial_port_data(port);
int chars = 0;
unsigned long flags;
dbg("%s - port %d", __func__, port->number);
if (edge_port == NULL)
return 0;
if (edge_port->close_pending == 1)
return 0;
spin_lock_irqsave(&edge_port->ep_lock, flags);
chars = edge_buf_data_avail(edge_port->ep_out_buf);
spin_unlock_irqrestore(&edge_port->ep_lock, flags);
dbg("%s - returns %d", __func__, chars);
return chars;
}
static void edge_throttle(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct edgeport_port *edge_port = usb_get_serial_port_data(port);
int status;
dbg("%s - port %d", __func__, port->number);
if (edge_port == NULL)
return;
if (I_IXOFF(tty)) {
unsigned char stop_char = STOP_CHAR(tty);
status = edge_write(tty, port, &stop_char, 1);
if (status <= 0) {
dev_err(&port->dev, "%s - failed to write stop character, %d\n", __func__, status);
}
}
if (C_CRTSCTS(tty))
stop_read(edge_port);
}
static void edge_unthrottle(struct tty_struct *tty)
{
struct usb_serial_port *port = tty->driver_data;
struct edgeport_port *edge_port = usb_get_serial_port_data(port);
int status;
dbg("%s - port %d", __func__, port->number);
if (edge_port == NULL)
return;
if (I_IXOFF(tty)) {
unsigned char start_char = START_CHAR(tty);
status = edge_write(tty, port, &start_char, 1);
if (status <= 0) {
dev_err(&port->dev, "%s - failed to write start character, %d\n", __func__, status);
}
}
if (C_CRTSCTS(tty)) {
status = restart_read(edge_port);
if (status)
dev_err(&port->dev,
"%s - read bulk usb_submit_urb failed: %d\n",
__func__, status);
}
}
static void stop_read(struct edgeport_port *edge_port)
{
unsigned long flags;
spin_lock_irqsave(&edge_port->ep_lock, flags);
if (edge_port->ep_read_urb_state == EDGE_READ_URB_RUNNING)
edge_port->ep_read_urb_state = EDGE_READ_URB_STOPPING;
edge_port->shadow_mcr &= ~MCR_RTS;
spin_unlock_irqrestore(&edge_port->ep_lock, flags);
}
static int restart_read(struct edgeport_port *edge_port)
{
struct urb *urb;
int status = 0;
unsigned long flags;
spin_lock_irqsave(&edge_port->ep_lock, flags);
if (edge_port->ep_read_urb_state == EDGE_READ_URB_STOPPED) {
urb = edge_port->port->read_urb;
urb->complete = edge_bulk_in_callback;
urb->context = edge_port;
urb->dev = edge_port->port->serial->dev;
status = usb_submit_urb(urb, GFP_ATOMIC);
}
edge_port->ep_read_urb_state = EDGE_READ_URB_RUNNING;
edge_port->shadow_mcr |= MCR_RTS;
spin_unlock_irqrestore(&edge_port->ep_lock, flags);
return status;
}
static void change_port_settings(struct tty_struct *tty,
struct edgeport_port *edge_port, struct ktermios *old_termios)
{
struct ump_uart_config *config;
int baud;
unsigned cflag;
int status;
int port_number = edge_port->port->number -
edge_port->port->serial->minor;
dbg("%s - port %d", __func__, edge_port->port->number);
config = kmalloc (sizeof (*config), GFP_KERNEL);
if (!config) {
*tty->termios = *old_termios;
dev_err(&edge_port->port->dev, "%s - out of memory\n",
__func__);
return;
}
cflag = tty->termios->c_cflag;
config->wFlags = 0;
config->wFlags |= UMP_MASK_UART_FLAGS_RECEIVE_MS_INT;
config->wFlags |= UMP_MASK_UART_FLAGS_AUTO_START_ON_ERR;
config->bUartMode = (__u8)(edge_port->bUartMode);
switch (cflag & CSIZE) {
case CS5:
config->bDataBits = UMP_UART_CHAR5BITS;
dbg("%s - data bits = 5", __func__);
break;
case CS6:
config->bDataBits = UMP_UART_CHAR6BITS;
dbg("%s - data bits = 6", __func__);
break;
case CS7:
config->bDataBits = UMP_UART_CHAR7BITS;
dbg("%s - data bits = 7", __func__);
break;
default:
case CS8:
config->bDataBits = UMP_UART_CHAR8BITS;
dbg("%s - data bits = 8", __func__);
break;
}
if (cflag & PARENB) {
if (cflag & PARODD) {
config->wFlags |= UMP_MASK_UART_FLAGS_PARITY;
config->bParity = UMP_UART_ODDPARITY;
dbg("%s - parity = odd", __func__);
} else {
config->wFlags |= UMP_MASK_UART_FLAGS_PARITY;
config->bParity = UMP_UART_EVENPARITY;
dbg("%s - parity = even", __func__);
}
} else {
config->bParity = UMP_UART_NOPARITY;
dbg("%s - parity = none", __func__);
}
if (cflag & CSTOPB) {
config->bStopBits = UMP_UART_STOPBIT2;
dbg("%s - stop bits = 2", __func__);
} else {
config->bStopBits = UMP_UART_STOPBIT1;
dbg("%s - stop bits = 1", __func__);
}
if (cflag & CRTSCTS) {
config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X_CTS_FLOW;
config->wFlags |= UMP_MASK_UART_FLAGS_RTS_FLOW;
dbg("%s - RTS/CTS is enabled", __func__);
} else {
dbg("%s - RTS/CTS is disabled", __func__);
tty->hw_stopped = 0;
restart_read(edge_port);
}
config->cXon = START_CHAR(tty);
config->cXoff = STOP_CHAR(tty);
if (I_IXOFF(tty)) {
config->wFlags |= UMP_MASK_UART_FLAGS_IN_X;
dbg("%s - INBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x",
__func__, config->cXon, config->cXoff);
} else
dbg("%s - INBOUND XON/XOFF is disabled", __func__);
if (I_IXON(tty)) {
config->wFlags |= UMP_MASK_UART_FLAGS_OUT_X;
dbg("%s - OUTBOUND XON/XOFF is enabled, XON = %2x, XOFF = %2x",
__func__, config->cXon, config->cXoff);
} else
dbg("%s - OUTBOUND XON/XOFF is disabled", __func__);
tty->termios->c_cflag &= ~CMSPAR;
baud = tty_get_baud_rate(tty);
if (!baud) {
baud = 9600;
} else
tty_encode_baud_rate(tty, baud, baud);
edge_port->baud_rate = baud;
config->wBaudRate = (__u16)((461550L + baud/2) / baud);
dbg("%s - baud rate = %d, wBaudRate = %d", __func__, baud,
config->wBaudRate);
dbg("wBaudRate: %d", (int)(461550L / config->wBaudRate));
dbg("wFlags: 0x%x", config->wFlags);
dbg("bDataBits: %d", config->bDataBits);
dbg("bParity: %d", config->bParity);
dbg("bStopBits: %d", config->bStopBits);
dbg("cXon: %d", config->cXon);
dbg("cXoff: %d", config->cXoff);
dbg("bUartMode: %d", config->bUartMode);
cpu_to_be16s(&config->wFlags);
cpu_to_be16s(&config->wBaudRate);
status = send_cmd(edge_port->port->serial->dev, UMPC_SET_CONFIG,
(__u8)(UMPM_UART1_PORT + port_number),
0, (__u8 *)config, sizeof(*config));
if (status)
dbg("%s - error %d when trying to write config to device",
__func__, status);
kfree(config);
return;
}
static void edge_set_termios(struct tty_struct *tty,
struct usb_serial_port *port, struct ktermios *old_termios)
{
struct edgeport_port *edge_port = usb_get_serial_port_data(port);
unsigned int cflag;
cflag = tty->termios->c_cflag;
dbg("%s - clfag %08x iflag %08x", __func__,
tty->termios->c_cflag, tty->termios->c_iflag);
dbg("%s - old clfag %08x old iflag %08x", __func__,
old_termios->c_cflag, old_termios->c_iflag);
dbg("%s - port %d", __func__, port->number);
if (edge_port == NULL)
return;
change_port_settings(tty, edge_port, old_termios);
return;
}
static int edge_tiocmset(struct tty_struct *tty, struct file *file,
unsigned int set, unsigned int clear)
{
struct usb_serial_port *port = tty->driver_data;
struct edgeport_port *edge_port = usb_get_serial_port_data(port);
unsigned int mcr;
unsigned long flags;
dbg("%s - port %d", __func__, port->number);
spin_lock_irqsave(&edge_port->ep_lock, flags);
mcr = edge_port->shadow_mcr;
if (set & TIOCM_RTS)
mcr |= MCR_RTS;
if (set & TIOCM_DTR)
mcr |= MCR_DTR;
if (set & TIOCM_LOOP)
mcr |= MCR_LOOPBACK;
if (clear & TIOCM_RTS)
mcr &= ~MCR_RTS;
if (clear & TIOCM_DTR)
mcr &= ~MCR_DTR;
if (clear & TIOCM_LOOP)
mcr &= ~MCR_LOOPBACK;
edge_port->shadow_mcr = mcr;
spin_unlock_irqrestore(&edge_port->ep_lock, flags);
restore_mcr(edge_port, mcr);
return 0;
}
static int edge_tiocmget(struct tty_struct *tty, struct file *file)
{
struct usb_serial_port *port = tty->driver_data;
struct edgeport_port *edge_port = usb_get_serial_port_data(port);
unsigned int result = 0;
unsigned int msr;
unsigned int mcr;
unsigned long flags;
dbg("%s - port %d", __func__, port->number);
spin_lock_irqsave(&edge_port->ep_lock, flags);
msr = edge_port->shadow_msr;
mcr = edge_port->shadow_mcr;
result = ((mcr & MCR_DTR) ? TIOCM_DTR: 0)
| ((mcr & MCR_RTS) ? TIOCM_RTS: 0)
| ((msr & EDGEPORT_MSR_CTS) ? TIOCM_CTS: 0)
| ((msr & EDGEPORT_MSR_CD) ? TIOCM_CAR: 0)
| ((msr & EDGEPORT_MSR_RI) ? TIOCM_RI: 0)
| ((msr & EDGEPORT_MSR_DSR) ? TIOCM_DSR: 0);
dbg("%s -- %x", __func__, result);
spin_unlock_irqrestore(&edge_port->ep_lock, flags);
return result;
}
static int get_serial_info(struct edgeport_port *edge_port,
struct serial_struct __user *retinfo)
{
struct serial_struct tmp;
if (!retinfo)
return -EFAULT;
memset(&tmp, 0, sizeof(tmp));
tmp.type = PORT_16550A;
tmp.line = edge_port->port->serial->minor;
tmp.port = edge_port->port->number;
tmp.irq = 0;
tmp.flags = ASYNC_SKIP_TEST | ASYNC_AUTO_IRQ;
tmp.xmit_fifo_size = edge_port->port->bulk_out_size;
tmp.baud_base = 9600;
tmp.close_delay = 5*HZ;
tmp.closing_wait = closing_wait;
if (copy_to_user(retinfo, &tmp, sizeof(*retinfo)))
return -EFAULT;
return 0;
}
static int edge_ioctl(struct tty_struct *tty, struct file *file,
unsigned int cmd, unsigned long arg)
{
struct usb_serial_port *port = tty->driver_data;
struct edgeport_port *edge_port = usb_get_serial_port_data(port);
struct async_icount cnow;
struct async_icount cprev;
dbg("%s - port %d, cmd = 0x%x", __func__, port->number, cmd);
switch (cmd) {
case TIOCGSERIAL:
dbg("%s - (%d) TIOCGSERIAL", __func__, port->number);
return get_serial_info(edge_port,
(struct serial_struct __user *) arg);
case TIOCMIWAIT:
dbg("%s - (%d) TIOCMIWAIT", __func__, port->number);
cprev = edge_port->icount;
while (1) {
interruptible_sleep_on(&edge_port->delta_msr_wait);
if (signal_pending(current))
return -ERESTARTSYS;
cnow = edge_port->icount;
if (cnow.rng == cprev.rng && cnow.dsr == cprev.dsr &&
cnow.dcd == cprev.dcd && cnow.cts == cprev.cts)
return -EIO;
if (((arg & TIOCM_RNG) && (cnow.rng != cprev.rng)) ||
((arg & TIOCM_DSR) && (cnow.dsr != cprev.dsr)) ||
((arg & TIOCM_CD) && (cnow.dcd != cprev.dcd)) ||
((arg & TIOCM_CTS) && (cnow.cts != cprev.cts))) {
return 0;
}
cprev = cnow;
}
break;
case TIOCGICOUNT:
dbg("%s - (%d) TIOCGICOUNT RX=%d, TX=%d", __func__,
port->number, edge_port->icount.rx, edge_port->icount.tx);
if (copy_to_user((void __user *)arg, &edge_port->icount,
sizeof(edge_port->icount)))
return -EFAULT;
return 0;
}
return -ENOIOCTLCMD;
}
static void edge_break(struct tty_struct *tty, int break_state)
{
struct usb_serial_port *port = tty->driver_data;
struct edgeport_port *edge_port = usb_get_serial_port_data(port);
int status;
int bv = 0;
dbg("%s - state = %d", __func__, break_state);
chase_port(edge_port, 0, 0);
if (break_state == -1)
bv = 1;
status = ti_do_config(edge_port, UMPC_SET_CLR_BREAK, bv);
if (status)
dbg("%s - error %d sending break set/clear command.",
__func__, status);
}
static int edge_startup(struct usb_serial *serial)
{
struct edgeport_serial *edge_serial;
struct edgeport_port *edge_port;
struct usb_device *dev;
int status;
int i;
dev = serial->dev;
edge_serial = kzalloc(sizeof(struct edgeport_serial), GFP_KERNEL);
if (edge_serial == NULL) {
dev_err(&serial->dev->dev, "%s - Out of memory\n", __func__);
return -ENOMEM;
}
mutex_init(&edge_serial->es_lock);
edge_serial->serial = serial;
usb_set_serial_data(serial, edge_serial);
status = download_fw(edge_serial);
if (status) {
kfree(edge_serial);
return status;
}
for (i = 0; i < serial->num_ports; ++i) {
edge_port = kzalloc(sizeof(struct edgeport_port), GFP_KERNEL);
if (edge_port == NULL) {
dev_err(&serial->dev->dev, "%s - Out of memory\n",
__func__);
goto cleanup;
}
spin_lock_init(&edge_port->ep_lock);
edge_port->ep_out_buf = edge_buf_alloc(EDGE_OUT_BUF_SIZE);
if (edge_port->ep_out_buf == NULL) {
dev_err(&serial->dev->dev, "%s - Out of memory\n",
__func__);
kfree(edge_port);
goto cleanup;
}
edge_port->port = serial->port[i];
edge_port->edge_serial = edge_serial;
usb_set_serial_port_data(serial->port[i], edge_port);
edge_port->bUartMode = default_uart_mode;
}
return 0;
cleanup:
for (--i; i >= 0; --i) {
edge_port = usb_get_serial_port_data(serial->port[i]);
edge_buf_free(edge_port->ep_out_buf);
kfree(edge_port);
usb_set_serial_port_data(serial->port[i], NULL);
}
kfree(edge_serial);
usb_set_serial_data(serial, NULL);
return -ENOMEM;
}
static void edge_disconnect(struct usb_serial *serial)
{
int i;
struct edgeport_port *edge_port;
dbg("%s", __func__);
for (i = 0; i < serial->num_ports; ++i) {
edge_port = usb_get_serial_port_data(serial->port[i]);
edge_remove_sysfs_attrs(edge_port->port);
}
}
static void edge_release(struct usb_serial *serial)
{
int i;
struct edgeport_port *edge_port;
dbg("%s", __func__);
for (i = 0; i < serial->num_ports; ++i) {
edge_port = usb_get_serial_port_data(serial->port[i]);
edge_buf_free(edge_port->ep_out_buf);
kfree(edge_port);
}
kfree(usb_get_serial_data(serial));
}
static ssize_t show_uart_mode(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct usb_serial_port *port = to_usb_serial_port(dev);
struct edgeport_port *edge_port = usb_get_serial_port_data(port);
return sprintf(buf, "%d\n", edge_port->bUartMode);
}
static ssize_t store_uart_mode(struct device *dev,
struct device_attribute *attr, const char *valbuf, size_t count)
{
struct usb_serial_port *port = to_usb_serial_port(dev);
struct edgeport_port *edge_port = usb_get_serial_port_data(port);
unsigned int v = simple_strtoul(valbuf, NULL, 0);
dbg("%s: setting uart_mode = %d", __func__, v);
if (v < 256)
edge_port->bUartMode = v;
else
dev_err(dev, "%s - uart_mode %d is invalid\n", __func__, v);
return count;
}
static DEVICE_ATTR(uart_mode, S_IWUSR | S_IRUGO, show_uart_mode,
store_uart_mode);
static int edge_create_sysfs_attrs(struct usb_serial_port *port)
{
return device_create_file(&port->dev, &dev_attr_uart_mode);
}
static int edge_remove_sysfs_attrs(struct usb_serial_port *port)
{
device_remove_file(&port->dev, &dev_attr_uart_mode);
return 0;
}
static struct edge_buf *edge_buf_alloc(unsigned int size)
{
struct edge_buf *eb;
if (size == 0)
return NULL;
eb = kmalloc(sizeof(struct edge_buf), GFP_KERNEL);
if (eb == NULL)
return NULL;
eb->buf_buf = kmalloc(size, GFP_KERNEL);
if (eb->buf_buf == NULL) {
kfree(eb);
return NULL;
}
eb->buf_size = size;
eb->buf_get = eb->buf_put = eb->buf_buf;
return eb;
}
static void edge_buf_free(struct edge_buf *eb)
{
if (eb) {
kfree(eb->buf_buf);
kfree(eb);
}
}
static void edge_buf_clear(struct edge_buf *eb)
{
if (eb != NULL)
eb->buf_get = eb->buf_put;
}
static unsigned int edge_buf_data_avail(struct edge_buf *eb)
{
if (eb == NULL)
return 0;
return ((eb->buf_size + eb->buf_put - eb->buf_get) % eb->buf_size);
}
static unsigned int edge_buf_space_avail(struct edge_buf *eb)
{
if (eb == NULL)
return 0;
return ((eb->buf_size + eb->buf_get - eb->buf_put - 1) % eb->buf_size);
}
static unsigned int edge_buf_put(struct edge_buf *eb, const char *buf,
unsigned int count)
{
unsigned int len;
if (eb == NULL)
return 0;
len = edge_buf_space_avail(eb);
if (count > len)
count = len;
if (count == 0)
return 0;
len = eb->buf_buf + eb->buf_size - eb->buf_put;
if (count > len) {
memcpy(eb->buf_put, buf, len);
memcpy(eb->buf_buf, buf+len, count - len);
eb->buf_put = eb->buf_buf + count - len;
} else {
memcpy(eb->buf_put, buf, count);
if (count < len)
eb->buf_put += count;
else
eb->buf_put = eb->buf_buf;
}
return count;
}
static unsigned int edge_buf_get(struct edge_buf *eb, char *buf,
unsigned int count)
{
unsigned int len;
if (eb == NULL)
return 0;
len = edge_buf_data_avail(eb);
if (count > len)
count = len;
if (count == 0)
return 0;
len = eb->buf_buf + eb->buf_size - eb->buf_get;
if (count > len) {
memcpy(buf, eb->buf_get, len);
memcpy(buf+len, eb->buf_buf, count - len);
eb->buf_get = eb->buf_buf + count - len;
} else {
memcpy(buf, eb->buf_get, count);
if (count < len)
eb->buf_get += count;
else
eb->buf_get = eb->buf_buf;
}
return count;
}
static struct usb_serial_driver edgeport_1port_device = {
.driver = {
.owner = THIS_MODULE,
.name = "edgeport_ti_1",
},
.description = "Edgeport TI 1 port adapter",
.usb_driver = &io_driver,
.id_table = edgeport_1port_id_table,
.num_ports = 1,
.open = edge_open,
.close = edge_close,
.throttle = edge_throttle,
.unthrottle = edge_unthrottle,
.attach = edge_startup,
.disconnect = edge_disconnect,
.release = edge_release,
.port_probe = edge_create_sysfs_attrs,
.ioctl = edge_ioctl,
.set_termios = edge_set_termios,
.tiocmget = edge_tiocmget,
.tiocmset = edge_tiocmset,
.write = edge_write,
.write_room = edge_write_room,
.chars_in_buffer = edge_chars_in_buffer,
.break_ctl = edge_break,
.read_int_callback = edge_interrupt_callback,
.read_bulk_callback = edge_bulk_in_callback,
.write_bulk_callback = edge_bulk_out_callback,
};
static struct usb_serial_driver edgeport_2port_device = {
.driver = {
.owner = THIS_MODULE,
.name = "edgeport_ti_2",
},
.description = "Edgeport TI 2 port adapter",
.usb_driver = &io_driver,
.id_table = edgeport_2port_id_table,
.num_ports = 2,
.open = edge_open,
.close = edge_close,
.throttle = edge_throttle,
.unthrottle = edge_unthrottle,
.attach = edge_startup,
.disconnect = edge_disconnect,
.release = edge_release,
.port_probe = edge_create_sysfs_attrs,
.ioctl = edge_ioctl,
.set_termios = edge_set_termios,
.tiocmget = edge_tiocmget,
.tiocmset = edge_tiocmset,
.write = edge_write,
.write_room = edge_write_room,
.chars_in_buffer = edge_chars_in_buffer,
.break_ctl = edge_break,
.read_int_callback = edge_interrupt_callback,
.read_bulk_callback = edge_bulk_in_callback,
.write_bulk_callback = edge_bulk_out_callback,
};
static int __init edgeport_init(void)
{
int retval;
retval = usb_serial_register(&edgeport_1port_device);
if (retval)
goto failed_1port_device_register;
retval = usb_serial_register(&edgeport_2port_device);
if (retval)
goto failed_2port_device_register;
retval = usb_register(&io_driver);
if (retval)
goto failed_usb_register;
printk(KERN_INFO KBUILD_MODNAME ": " DRIVER_VERSION ":"
DRIVER_DESC "\n");
return 0;
failed_usb_register:
usb_serial_deregister(&edgeport_2port_device);
failed_2port_device_register:
usb_serial_deregister(&edgeport_1port_device);
failed_1port_device_register:
return retval;
}
static void __exit edgeport_exit(void)
{
usb_deregister(&io_driver);
usb_serial_deregister(&edgeport_1port_device);
usb_serial_deregister(&edgeport_2port_device);
}
module_init(edgeport_init);
module_exit(edgeport_exit);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
MODULE_FIRMWARE("edgeport/down3.bin");
module_param(debug, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "Debug enabled or not");
module_param(closing_wait, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(closing_wait, "Maximum wait for data to drain, in .01 secs");
module_param(ignore_cpu_rev, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(ignore_cpu_rev,
"Ignore the cpu revision when connecting to a device");
module_param(default_uart_mode, int, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(default_uart_mode, "Default uart_mode, 0=RS232, ...");
|
leemgs/OptimusOneKernel-KandroidCommunity
|
drivers/usb/serial/io_ti.c
|
C
|
gpl-2.0
| 68,884
|
/********************************************************************************/
/* */
/* TPM Key Migration Routines */
/* Written by J. Kravitz */
/* IBM Thomas J. Watson Research Center */
/* $Id: migrate.c 4073 2010-04-30 14:44:14Z kgoldman $ */
/* */
/* (c) Copyright IBM Corporation 2006, 2010. */
/* */
/* All rights reserved. */
/* */
/* Redistribution and use in source and binary forms, with or without */
/* modification, are permitted provided that the following conditions are */
/* met: */
/* */
/* Redistributions of source code must retain the above copyright notice, */
/* this list of conditions and the following disclaimer. */
/* */
/* Redistributions in binary form must reproduce the above copyright */
/* notice, this list of conditions and the following disclaimer in the */
/* documentation and/or other materials provided with the distribution. */
/* */
/* Neither the names of the IBM Corporation nor the names of its */
/* contributors may be used to endorse or promote products derived from */
/* this software without specific prior written permission. */
/* */
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */
/* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */
/* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR */
/* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT */
/* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, */
/* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT */
/* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, */
/* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY */
/* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE */
/* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef TPM_POSIX
#include <netinet/in.h>
#endif
#ifdef TPM_WINDOWS
#include <winsock2.h>
#endif
#include <tpm.h>
#include <tpmutil.h>
#include <tpmkeys.h>
#include <oiaposap.h>
#include <tpmfunc.h>
#include <hmac.h>
/****************************************************************************/
/* */
/* Authorize a Migration Key */
/* */
/* The arguments are... */
/* */
/* ownpass is a pointer to the Owner password (20 bytes) */
/* migtype is an integer containing 1 for normal migration and 2 for */
/* rewrap migration */
/* keyblob is a pointer to an area contining the migration public */
/* encrypted key blob */
/* migblob is a pointer to an area which will receive the migration */
/* key authorization blob */
/* */
/****************************************************************************/
uint32_t
TPM_AuthorizeMigrationKey(unsigned char *ownpass,
int migtype,
struct tpm_buffer *keyblob,
struct tpm_buffer *migblob)
{
uint32_t ret;
STACK_TPM_BUFFER(tpmdata)
unsigned char nonceodd[TPM_NONCE_SIZE];
unsigned char pubauth[TPM_HASH_SIZE];
unsigned char c = 0;
uint32_t ordinal = htonl(TPM_ORD_AuthorizeMigrationKey);
uint16_t migscheme = htons(migtype);
uint32_t size;
session sess;
/* check input arguments */
if (keyblob == NULL || migblob == NULL || ownpass == NULL)
return ERR_NULL_ARG;
/* generate odd nonce */
TSS_gennonce(nonceodd);
/* Open OIAP Session */
ret = TSS_SessionOpen(SESSION_DSAP | SESSION_OSAP | SESSION_OIAP,
&sess, ownpass, TPM_ET_OWNER, 0);
if (ret != 0)
return ret;
/* calculate authorization HMAC value */
ret = TSS_authhmac(pubauth, TSS_Session_GetAuth(&sess), TPM_HASH_SIZE,
TSS_Session_GetENonce(&sess), nonceodd, c,
TPM_U32_SIZE, &ordinal,
TPM_U16_SIZE, &migscheme,
keyblob->used, keyblob->buffer,
0, 0);
if (ret != 0) {
TSS_SessionClose(&sess);
return ret;
}
/* build the request buffer */
ret = TSS_buildbuff("00 c2 T l s % L % o %", &tpmdata,
ordinal,
migscheme,
keyblob->used, keyblob->buffer,
TSS_Session_GetHandle(&sess),
TPM_NONCE_SIZE, nonceodd,
c,
TPM_HASH_SIZE, pubauth);
if ((ret & ERR_MASK) != 0) {
TSS_SessionClose(&sess);
return ret;
}
/* transmit the request buffer to the TPM device and read the reply */
ret = TPM_Transmit(&tpmdata, "AuthorizeMigrationKey - AUTH1");
TSS_SessionClose(&sess);
if (ret != 0) {
return ret;
}
size = TSS_PubKeySize(&tpmdata, TPM_DATA_OFFSET, 0);
if ((size & ERR_MASK)) {
return size;
}
size += TPM_U16_SIZE + TPM_HASH_SIZE; /* size of MigrationKeyAuth blob */
ret = TSS_checkhmac1(&tpmdata, ordinal, nonceodd,
TSS_Session_GetAuth(&sess), TPM_HASH_SIZE, size,
TPM_DATA_OFFSET, 0, 0);
if (ret != 0)
return ret;
SET_TPM_BUFFER(migblob, &tpmdata.buffer[TPM_DATA_OFFSET], size);
return 0;
}
/****************************************************************************/
/* */
/* Create Migration Blob */
/* */
/* The arguments are... */
/* */
/* keyhandle is the handle of the parent key of the key to */
/* be migrated. */
/* keyauth is the authorization data (password) for the parent key */
/* if null, it is assumed that the parent requires no auth */
/* migauth is the authorization data (password) for migration of */
/* the key being migrated */
/* all authorization values must be 20 bytes long */
/* migtype is an integer containing 1 for normal migration and 2 for */
/* rewrap migration */
/* migblob is a pointer to an area to containig the migration key */
/* authorization blob. */
/* migblen is an integer containing the length of the migration key */
/* authorization blob */
/* keyblob is a pointer to an area which contains the */
/* encrypted key blob of the key being migrated */
/* keyblen is an integer containing the length of the encrypted key */
/* blob for the key being migrated */
/* rndblob is a pointer to an area which will receive the random */
/* string for XOR decryption of the migration blob */
/* rndblen is a pointer to an integer which will receive the length */
/* of the random XOR string */
/* outblob is a pointer to an area which will receive the migrated */
/* key */
/* outblen is a pointer to an integer which will receive the length */
/* of the migrated key */
/* */
/****************************************************************************/
uint32_t
TPM_CreateMigrationBlob(unsigned int keyhandle,
unsigned char *keyauth,
unsigned char *migauth,
int migtype,
unsigned char *migblob,
uint32_t migblen,
unsigned char *keyblob,
uint32_t keyblen,
unsigned char *rndblob,
uint32_t *rndblen,
unsigned char *outblob, uint32_t *outblen)
{
uint32_t ret;
ALLOC_TPM_BUFFER(tpmdata, 0)
unsigned char nonceodd[TPM_NONCE_SIZE];
unsigned char c = 0;
uint32_t ordinal = htonl(TPM_ORD_CreateMigrationBlob);
uint32_t keyhndl = htonl(keyhandle);
uint16_t migscheme = htons(migtype);
unsigned char authdata1[TPM_HASH_SIZE];
unsigned char authdata2[TPM_HASH_SIZE];
uint32_t size1;
uint32_t size2;
uint32_t keyblen_no = ntohl(keyblen);
session sess;
/* check input arguments */
if (migauth == NULL || migblob == NULL || keyblob == NULL)
return ERR_NULL_ARG;
if (rndblob == NULL || rndblen == NULL || outblob == NULL ||
outblen == NULL)
return ERR_NULL_ARG;
if (migtype != 1 && migtype != 2)
return ERR_BAD_ARG;
ret = needKeysRoom(keyhandle, 0, 0, 0);
if (ret != 0) {
return ret;
}
/* generate odd nonce */
TSS_gennonce(nonceodd);
if (keyauth != NULL) { /* parent key password is required */
session sess2;
unsigned char nonceodd2[TPM_NONCE_SIZE];
TSS_gennonce(nonceodd2);
/* open TWO OIAP sessions, one for the Parent Key Auth and one for the Migrating Key */
ret = TSS_SessionOpen(SESSION_OSAP | SESSION_OIAP | SESSION_DSAP,
&sess,
keyauth, TPM_ET_KEYHANDLE, keyhandle);
if (ret != 0) {
goto exit;
}
ret = TSS_SessionOpen(SESSION_OIAP, &sess2, migauth, 0, 0);
if (ret != 0) {
TSS_SessionClose(&sess);
goto exit;
}
/* calculate Parent KEY authorization HMAC value */
ret = TSS_authhmac(authdata1, TSS_Session_GetAuth(&sess),
TPM_HASH_SIZE, TSS_Session_GetENonce(&sess),
nonceodd, c,
TPM_U32_SIZE, &ordinal,
TPM_U16_SIZE, &migscheme,
migblen, migblob,
TPM_U32_SIZE, &keyblen_no,
keyblen, keyblob,
0, 0);
if (ret != 0) {
TSS_SessionClose(&sess);
TSS_SessionClose(&sess2);
goto exit;
}
/* calculate Migration authorization HMAC value */
ret = TSS_authhmac(authdata2, TSS_Session_GetAuth(&sess2),
TPM_HASH_SIZE,
TSS_Session_GetENonce(&sess2), nonceodd2, c,
TPM_U32_SIZE, &ordinal,
TPM_U16_SIZE, &migscheme,
migblen, migblob,
TPM_U32_SIZE, &keyblen_no,
keyblen, keyblob,
0, 0);
if (ret != 0) {
TSS_SessionClose(&sess);
TSS_SessionClose(&sess2);
goto exit;
}
/* build the request buffer */
ret = TSS_buildbuff("00 c3 T l l s % @ L % o % L % o %",
tpmdata, ordinal, keyhndl, migscheme,
migblen, migblob, keyblen, keyblob,
TSS_Session_GetHandle(&sess),
TPM_NONCE_SIZE, nonceodd, c, TPM_HASH_SIZE,
authdata1, TSS_Session_GetHandle(&sess2),
TPM_NONCE_SIZE, nonceodd2, c,
TPM_HASH_SIZE, authdata2);
if ((ret & ERR_MASK) != 0) {
TSS_SessionClose(&sess);
TSS_SessionClose(&sess2);
goto exit;
}
/* transmit the request buffer to the TPM device and read the reply */
ret = TPM_Transmit(tpmdata, "CreateMigrationBlob - AUTH2");
TSS_SessionClose(&sess);
TSS_SessionClose(&sess2);
if (ret != 0) {
goto exit;
}
/* validate HMAC in response */
ret = tpm_buffer_load32(tpmdata, TPM_DATA_OFFSET, &size1);
if ((ret & ERR_MASK)) {
return ret;
}
ret = tpm_buffer_load32(tpmdata,
TPM_DATA_OFFSET + TPM_U32_SIZE + size1, &size2);
if ((ret & ERR_MASK)) {
return ret;
}
if (size1 != 0) {
ret = TSS_checkhmac2(tpmdata, ordinal, nonceodd,
TSS_Session_GetAuth(&sess),
TPM_HASH_SIZE,
nonceodd2,
TSS_Session_GetAuth(&sess2),
TPM_HASH_SIZE, TPM_U32_SIZE,
TPM_DATA_OFFSET, size1,
TPM_DATA_OFFSET + TPM_U32_SIZE,
TPM_U32_SIZE,
TPM_DATA_OFFSET + TPM_U32_SIZE +
size1, size2,
TPM_DATA_OFFSET + TPM_U32_SIZE +
size1 + TPM_U32_SIZE, 0, 0);
} else {
ret = TSS_checkhmac2(tpmdata, ordinal, nonceodd,
TSS_Session_GetAuth(&sess),
TPM_HASH_SIZE,
nonceodd2,
TSS_Session_GetAuth(&sess2),
TPM_HASH_SIZE, TPM_U32_SIZE,
TPM_DATA_OFFSET, TPM_U32_SIZE,
TPM_DATA_OFFSET + TPM_U32_SIZE,
size2,
TPM_DATA_OFFSET + TPM_U32_SIZE +
TPM_U32_SIZE, 0, 0);
}
if (ret != 0)
goto exit;
} else { /* no parent key password required */
/* open OIAP session for the Migrating Key */
ret = TSS_SessionOpen(SESSION_OIAP, &sess, migauth, 0, 0);
if (ret != 0) {
goto exit;
}
/* calculate Migration authorization HMAC value */
ret = TSS_authhmac(authdata1, TSS_Session_GetAuth(&sess),
TPM_HASH_SIZE, TSS_Session_GetENonce(&sess),
nonceodd, c, TPM_U32_SIZE, &ordinal,
TPM_U16_SIZE, &migscheme, migblen, migblob,
TPM_U32_SIZE, &keyblen_no, keyblen, keyblob,
0, 0);
if (ret != 0) {
TSS_SessionClose(&sess);
goto exit;
}
/* build the request buffer */
ret = TSS_buildbuff("00 c2 T l l s % @ L % o %", tpmdata,
ordinal,
keyhndl,
migscheme,
migblen, migblob,
keyblen, keyblob,
TSS_Session_GetHandle(&sess),
TPM_NONCE_SIZE, nonceodd,
c, TPM_HASH_SIZE, authdata1);
if ((ret & ERR_MASK) != 0) {
TSS_SessionClose(&sess);
goto exit;
}
/* transmit the request buffer to the TPM device and read the reply */
ret = TPM_Transmit(tpmdata, "CreateMigrationBlob - AUTH1");
TSS_SessionClose(&sess);
if (ret != 0) {
goto exit;
}
/* check HMAC in response */
ret = tpm_buffer_load32(tpmdata, TPM_DATA_OFFSET, &size1);
if ((ret & ERR_MASK)) {
return ret;
}
ret = tpm_buffer_load32(tpmdata,
TPM_DATA_OFFSET + TPM_U32_SIZE + size1, &size2);
if ((ret & ERR_MASK)) {
return ret;
}
if (size1 != 0) {
ret = TSS_checkhmac1(tpmdata, ordinal, nonceodd,
TSS_Session_GetAuth(&sess),
TPM_HASH_SIZE, TPM_U32_SIZE,
TPM_DATA_OFFSET, size1,
TPM_DATA_OFFSET + TPM_U32_SIZE,
TPM_U32_SIZE,
TPM_DATA_OFFSET + TPM_U32_SIZE +
size1, size2,
TPM_DATA_OFFSET + TPM_U32_SIZE +
size1 + TPM_U32_SIZE, 0, 0);
} else {
ret = TSS_checkhmac1(tpmdata, ordinal, nonceodd,
TSS_Session_GetAuth(&sess),
TPM_HASH_SIZE, TPM_U32_SIZE,
TPM_DATA_OFFSET, TPM_U32_SIZE,
TPM_DATA_OFFSET + TPM_U32_SIZE,
size2,
TPM_DATA_OFFSET + TPM_U32_SIZE +
TPM_U32_SIZE, 0, 0);
}
if (ret != 0)
goto exit;
}
memcpy(rndblob,
&tpmdata->buffer[TPM_DATA_OFFSET + TPM_U32_SIZE], size1);
memcpy(outblob,
&tpmdata->buffer[TPM_DATA_OFFSET + TPM_U32_SIZE + size1 +
TPM_U32_SIZE], size2);
*rndblen = size1;
*outblen = size2;
exit:
FREE_TPM_BUFFER(tpmdata);
return ret;
}
/****************************************************************************/
/* */
/* Convert a Migration Blob */
/* */
/* The arguments are... */
/* */
/* keyhandle is the handle of the new parent key of the key */
/* being migrated */
/* keyauth is the authorization data (password) for the parent key */
/* rndblob is a pointer to an area contining the random XOR data */
/* rndblen is an integer containing the length of the random XOR data */
/* keyblob is a pointer to an area contining the migration public */
/* encrypted key blob */
/* keyblen is an integer containing the length of the migration */
/* public key blob */
/* encblob is a pointer to an area which will receive the migrated */
/* key re-encrypted private key blob */
/* endblen is a pointer to an integer which will receive size of */
/* the migrated key re-encrypted private key blob */
/* */
/****************************************************************************/
uint32_t
TPM_ConvertMigrationBlob(unsigned int keyhandle,
unsigned char *keyauth,
unsigned char *rndblob,
uint32_t rndblen,
unsigned char *keyblob,
uint32_t keyblen,
unsigned char *encblob, uint32_t *encblen)
{
uint32_t ret;
STACK_TPM_BUFFER(tpmdata)
unsigned char nonceodd[TPM_NONCE_SIZE];
unsigned char pubauth[TPM_HASH_SIZE];
unsigned char c = 0;
uint32_t ordinal_no = htonl(TPM_ORD_ConvertMigrationBlob);
uint32_t keyhndl;
uint32_t rndsize;
uint32_t datsize;
uint32_t size;
/* check input arguments */
if (rndblob == NULL ||
keyblob == NULL || encblob == NULL || encblen == NULL)
return ERR_NULL_ARG;
keyhndl = htonl(keyhandle);
rndsize = htonl(rndblen);
datsize = htonl(keyblen);
ret = needKeysRoom(keyhandle, 0, 0, 0);
if (ret != 0) {
return ret;
}
if (NULL != keyauth) {
session sess;
/* generate odd nonce */
TSS_gennonce(nonceodd);
/* Open OIAP Session */
ret = TSS_SessionOpen(SESSION_DSAP | SESSION_OSAP | SESSION_OIAP,
&sess,
keyauth, TPM_ET_KEYHANDLE, keyhandle);
if (ret != 0)
return ret;
/* calculate authorization HMAC value */
ret = TSS_authhmac(pubauth, TSS_Session_GetAuth(&sess),
TPM_HASH_SIZE, TSS_Session_GetENonce(&sess),
nonceodd, c, TPM_U32_SIZE, &ordinal_no,
TPM_U32_SIZE, &datsize, keyblen, keyblob,
TPM_U32_SIZE, &rndsize, rndblen, rndblob, 0,
0);
if (ret != 0) {
TSS_SessionClose(&sess);
return ret;
}
/* build the request buffer */
ret = TSS_buildbuff("00 c2 T l l @ @ L % o %", &tpmdata,
ordinal_no,
keyhndl,
keyblen, keyblob,
rndblen, rndblob,
TSS_Session_GetHandle(&sess),
TPM_NONCE_SIZE, nonceodd,
c, TPM_HASH_SIZE, pubauth);
if ((ret & ERR_MASK) != 0) {
TSS_SessionClose(&sess);
return ret;
}
/* transmit the request buffer to the TPM device and read the reply */
ret = TPM_Transmit(&tpmdata, "ConvertMigrationBlob - AUTH1");
TSS_SessionClose(&sess);
if (ret != 0) {
return ret;
}
ret = tpm_buffer_load32(&tpmdata, TPM_DATA_OFFSET, &size);
if ((ret & ERR_MASK)) {
return ret;
}
ret = TSS_checkhmac1(&tpmdata, ordinal_no, nonceodd,
TSS_Session_GetAuth(&sess), TPM_HASH_SIZE,
TPM_U32_SIZE, TPM_DATA_OFFSET, size,
TPM_DATA_OFFSET + TPM_U32_SIZE, 0, 0);
if (ret != 0)
return ret;
memcpy(encblob,
&tpmdata.buffer[TPM_DATA_OFFSET + TPM_U32_SIZE], size);
*encblen = size;
} else {
/* build the request buffer */
ret = TSS_buildbuff("00 c1 T l l @ @", &tpmdata,
ordinal_no,
keyhndl,
keyblen, keyblob, rndblen, rndblob);
/* transmit the request buffer to the TPM device and read the reply */
ret = TPM_Transmit(&tpmdata, "ConvertMigrationBlob - NOAUTH");
if (ret != 0) {
return ret;
}
ret = tpm_buffer_load32(&tpmdata, TPM_DATA_OFFSET, &size);
if ((ret & ERR_MASK)) {
return ret;
}
if (ret != 0)
return ret;
memcpy(encblob,
&tpmdata.buffer[TPM_DATA_OFFSET + TPM_U32_SIZE], size);
*encblen = size;
}
return 0;
}
/****************************************************************************/
/* */
/* Migrate a key by re-encrypting its private key */
/* */
/* The arguments are... */
/* */
/* keyhandle is the handle to the key that can decrypt the private key */
/* keyUsageAuth is the hashed password for using the key, NULL if no the */
/* key does not need a password */
/* pubKeyBlob is the blob of the public key where the 'key to be migrated'*/
/* is supposed to be re-encrypted with */
/* inData is the encrypted private key part of the key pair, currently*/
/* encrypted with the public key of the key pointed to by */
/* keyhandle */
/* inDataSize is the size of the inData blob */
/* outData points to an area sufficiently large to hold the reencrypted*/
/* private key; (should have the size inDataSize) */
/* outDataSize passes the size of outData block on input and returnes the */
/* number of valid bytes on output */
/****************************************************************************/
uint32_t
TPM_MigrateKey(uint32_t keyhandle,
unsigned char *keyUsageAuth,
unsigned char *pubKeyBlob, uint32_t pubKeySize,
unsigned char *inData, uint32_t inDataSize,
unsigned char *outData, uint32_t * outDataSize)
{
STACK_TPM_BUFFER(tpmdata)
unsigned char nonceodd[TPM_NONCE_SIZE];
unsigned char authdata[TPM_NONCE_SIZE];
unsigned char c = 0;
uint32_t ordinal_no = ntohl(TPM_ORD_MigrateKey);
uint32_t ret;
uint32_t keyhandle_no = htonl(keyhandle);
uint32_t inDataSize_no = htonl(inDataSize);
uint32_t len;
/* check input arguments */
if (NULL == pubKeyBlob || NULL == inData || NULL == outData) {
return ERR_NULL_ARG;
}
ret = needKeysRoom(keyhandle, 0, 0, 0);
if (ret != 0) {
return ret;
}
if (NULL != keyUsageAuth) {
/* generate odd nonce */
session sess;
ret = TSS_gennonce(nonceodd);
if (0 == ret)
return ERR_CRYPT_ERR;
/* Open OSAP Session */
ret = TSS_SessionOpen(SESSION_DSAP | SESSION_OSAP | SESSION_OIAP,
&sess,
keyUsageAuth, TPM_ET_KEYHANDLE,
keyhandle);
if (ret != 0)
return ret;
/* calculate encrypted authorization value */
ret = TSS_authhmac(authdata, TSS_Session_GetAuth(&sess),
TPM_HASH_SIZE, TSS_Session_GetENonce(&sess),
nonceodd, c, TPM_U32_SIZE, &ordinal_no,
pubKeySize, pubKeyBlob, TPM_U32_SIZE,
&inDataSize_no, inDataSize, inData, 0, 0);
if (0 != ret) {
TSS_SessionClose(&sess);
return ret;
}
/* build the request buffer */
ret = TSS_buildbuff("00 c2 T l l % @ L % o %", &tpmdata,
ordinal_no,
keyhandle_no,
pubKeySize, pubKeyBlob,
inDataSize, inData,
TSS_Session_GetHandle(&sess),
TPM_NONCE_SIZE, nonceodd,
c, TPM_HASH_SIZE, authdata);
if ((ret & ERR_MASK)) {
TSS_SessionClose(&sess);
return ret;
}
/* transmit the request buffer to the TPM device and read the reply */
ret = TPM_Transmit(&tpmdata, "MigrateKey - AUTH1");
TSS_SessionClose(&sess);
if (ret != 0) {
return ret;
}
ret = tpm_buffer_load32(&tpmdata, TPM_DATA_OFFSET, &len);
if ((ret & ERR_MASK)) {
return ret;
}
/* check the HMAC in the response */
ret = TSS_checkhmac1(&tpmdata, ordinal_no, nonceodd,
TSS_Session_GetAuth(&sess), TPM_HASH_SIZE,
TPM_U32_SIZE + len, TPM_DATA_OFFSET, 0,
0);
if (outData != NULL) {
*outDataSize = MIN(*outDataSize, len);
memcpy(outData,
&tpmdata.buffer[TPM_DATA_OFFSET + TPM_U32_SIZE],
*outDataSize);
}
} else {
/* build the request buffer */
ret = TSS_buildbuff("00 c1 T l l % @", &tpmdata,
ordinal_no,
keyhandle_no,
pubKeySize, pubKeyBlob,
inDataSize, inData);
if ((ret & ERR_MASK)) {
return ret;
}
/* transmit the request buffer to the TPM device and read the reply */
ret = TPM_Transmit(&tpmdata, "MigrateKey - AUTH1");
if (ret != 0) {
return ret;
}
ret = tpm_buffer_load32(&tpmdata, TPM_DATA_OFFSET, &len);
if ((ret & ERR_MASK)) {
return ret;
}
if (outData != NULL) {
*outDataSize = MIN(*outDataSize, len);
memcpy(outData,
&tpmdata.buffer[TPM_DATA_OFFSET + TPM_U32_SIZE],
*outDataSize);
}
}
return ret;
}
/****************************************************************************/
/* */
/* */
/* */
/* The arguments are... */
/* */
uint32_t
TPM_CMK_SetRestrictions(uint32_t restriction, unsigned char *ownerAuth)
{
STACK_TPM_BUFFER(tpmdata)
unsigned char nonceodd[TPM_NONCE_SIZE];
unsigned char authdata[TPM_NONCE_SIZE];
unsigned char c = 0;
uint32_t ordinal_no = htonl(TPM_ORD_CMK_SetRestrictions);
uint32_t ret;
uint32_t restriction_no = htonl(restriction);
session sess;
/* check input arguments */
if (NULL == ownerAuth)
return ERR_NULL_ARG;
/* generate odd nonce */
ret = TSS_gennonce(nonceodd);
if (0 == ret)
return ERR_CRYPT_ERR;
/* Open OSAP Session */
ret = TSS_SessionOpen(SESSION_OSAP | SESSION_OIAP,
&sess, ownerAuth, TPM_ET_OWNER, 0);
if (ret != 0)
return ret;
/* calculate encrypted authorization value */
ret = TSS_authhmac(authdata, TSS_Session_GetAuth(&sess), TPM_HASH_SIZE,
TSS_Session_GetENonce(&sess), nonceodd, c,
TPM_U32_SIZE, &ordinal_no, TPM_U32_SIZE,
&restriction_no, 0, 0);
if (0 != ret) {
TSS_SessionClose(&sess);
return ret;
}
/* build the request buffer */
ret = TSS_buildbuff("00 c2 T l l L % o %", &tpmdata,
ordinal_no,
restriction_no,
TSS_Session_GetHandle(&sess),
TPM_NONCE_SIZE, nonceodd,
c, TPM_HASH_SIZE, authdata);
if ((ret & ERR_MASK)) {
TSS_SessionClose(&sess);
return ret;
}
/* transmit the request buffer to the TPM device and read the reply */
ret = TPM_Transmit(&tpmdata, "CMK_SetRestriction");
TSS_SessionClose(&sess);
if (ret != 0) {
return ret;
}
/* check the HMAC in the response */
ret = TSS_checkhmac1(&tpmdata, ordinal_no, nonceodd,
TSS_Session_GetAuth(&sess), TPM_HASH_SIZE, 0, 0);
return ret;
}
uint32_t
TPM_CMK_ApproveMA(unsigned char *migAuthDigest,
unsigned char *ownerAuth,
unsigned char *hmac)
{
STACK_TPM_BUFFER(tpmdata)
unsigned char nonceodd[TPM_NONCE_SIZE];
unsigned char authdata[TPM_NONCE_SIZE];
unsigned char c = 0;
uint32_t ordinal_no = htonl(TPM_ORD_CMK_ApproveMA);
uint32_t ret;
session sess;
/* check input arguments */
if (NULL == ownerAuth)
return ERR_NULL_ARG;
/* generate odd nonce */
ret = TSS_gennonce(nonceodd);
if (0 == ret)
return ERR_CRYPT_ERR;
/* Open OSAP Session */
ret = TSS_SessionOpen(SESSION_OSAP | SESSION_OIAP,
&sess, ownerAuth, TPM_ET_OWNER, 0);
if (ret != 0)
return ret;
ret = TSS_authhmac(authdata, TSS_Session_GetAuth(&sess), TPM_HASH_SIZE,
TSS_Session_GetENonce(&sess), nonceodd, c,
TPM_U32_SIZE, &ordinal_no, TPM_DIGEST_SIZE,
migAuthDigest, 0, 0);
if (0 != ret) {
TSS_SessionClose(&sess);
return ret;
}
/* build the request buffer */
ret = TSS_buildbuff("00 c2 T l % L % o %", &tpmdata,
ordinal_no,
TPM_DIGEST_SIZE, migAuthDigest,
TSS_Session_GetHandle(&sess),
TPM_NONCE_SIZE, nonceodd,
c, TPM_HASH_SIZE, authdata);
if ((ret & ERR_MASK)) {
TSS_SessionClose(&sess);
return ret;
}
/* transmit the request buffer to the TPM device and read the reply */
ret = TPM_Transmit(&tpmdata, "CMK_ApproveMA - AUTH1");
TSS_SessionClose(&sess);
if (ret != 0) {
return ret;
}
/* check the HMAC in the response */
ret = TSS_checkhmac1(&tpmdata, ordinal_no, nonceodd,
TSS_Session_GetAuth(&sess), TPM_HASH_SIZE,
TPM_HASH_SIZE, TPM_DATA_OFFSET, 0, 0);
if (ret != 0) {
return ret;
}
if (NULL != hmac) {
memcpy(hmac, &tpmdata.buffer[TPM_DATA_OFFSET], TPM_HASH_SIZE);
}
return ret;
}
uint32_t
TPM_CMK_CreateKey(uint32_t parenthandle,
unsigned char *parkeyUsageAuth,
unsigned char *dataUsageAuth,
keydata * keyRequest,
unsigned char *migAuthApproval,
unsigned char *migAuthDigest,
keydata * key, unsigned char *blob, uint32_t * bloblen)
{
uint32_t ret = 0;
uint32_t ordinal_no = htonl(TPM_ORD_CMK_CreateKey);
unsigned char c = 0;
STACK_TPM_BUFFER(tpmdata)
unsigned char nonceodd[TPM_NONCE_SIZE];
unsigned char authdata[TPM_NONCE_SIZE];
unsigned char encauth[TPM_NONCE_SIZE];
STACK_TPM_BUFFER(kparmbuf)
unsigned char dummy[TPM_HASH_SIZE];
uint32_t parenthandle_no = htonl(parenthandle);
session sess;
unsigned char *usagehashptr = NULL;
uint32_t keylen;
uint16_t keytype;
uint32_t kparmbufsize;
if (NULL == parkeyUsageAuth ||
NULL == keyRequest ||
NULL == migAuthApproval || NULL == migAuthDigest) {
return ERR_NULL_ARG;
}
memset(dummy, 0x0, sizeof (dummy));
if (parenthandle == 0x40000000)
keytype = TPM_ET_SRK;
else
keytype = TPM_ET_KEYHANDLE;
ret = needKeysRoom(parenthandle, 0, 0, 0);
if (ret != 0) {
return ret;
}
TSS_gennonce(nonceodd);
ret = TPM_WriteKey(&kparmbuf, keyRequest);
if ((ret & ERR_MASK)) {
return ret;
}
kparmbufsize = ret;
/*
* Open OSAP session
*/
ret = TSS_SessionOpen(SESSION_DSAP|SESSION_OSAP,&sess, parkeyUsageAuth, keytype, parenthandle);
if (0 != ret) {
return ret;
}
/* Generate the encrytped usage authorization */
if (NULL != dataUsageAuth) {
usagehashptr = dataUsageAuth;
} else {
usagehashptr = dummy;
}
TPM_CreateEncAuth(&sess, usagehashptr, encauth, 0);
ret = TSS_authhmac(authdata, TSS_Session_GetAuth(&sess), TPM_HASH_SIZE, TSS_Session_GetENonce(&sess),
nonceodd, c,
TPM_U32_SIZE, &ordinal_no,
TPM_HASH_SIZE, encauth,
kparmbufsize, kparmbuf.buffer,
TPM_DIGEST_SIZE, migAuthApproval,
TPM_DIGEST_SIZE, migAuthDigest,
0, 0);
if (0 != ret) {
TSS_SessionClose(&sess);
return ret;
}
ret = TSS_buildbuff("00 c2 T l l % % % % L % o %", &tpmdata,
ordinal_no,
parenthandle_no,
TPM_HASH_SIZE, encauth,
kparmbufsize, kparmbuf.buffer,
TPM_DIGEST_SIZE, migAuthApproval,
TPM_DIGEST_SIZE, migAuthDigest,
TSS_Session_GetHandle(&sess),
TPM_NONCE_SIZE, nonceodd,
c, TPM_HASH_SIZE, authdata);
if (ret <= 0) {
TSS_SessionClose(&sess);
return ret;
}
ret = TPM_Transmit(&tpmdata, "CMK_CreateKey - AUTH1");
TSS_SessionClose(&sess);
if (0 != ret) {
return ret;
}
keylen = TSS_KeyExtract(&tpmdata, TPM_DATA_OFFSET, key);
ret = TSS_checkhmac1(&tpmdata, ordinal_no, nonceodd, TSS_Session_GetAuth(&sess),
TPM_HASH_SIZE, keylen, TPM_DATA_OFFSET, 0, 0);
if (0 != ret) {
return ret;
}
/*
* Have to deserialize the key
*/
if (NULL != blob) {
*bloblen = MIN(*bloblen, keylen);
memcpy(blob, &tpmdata.buffer[TPM_DATA_OFFSET], *bloblen);
}
return ret;
}
uint32_t
TPM_CMK_CreateTicket(keydata * key,
unsigned char *signedData,
unsigned char *signatureValue, uint32_t signatureValueSize,
unsigned char *ownerAuth,
unsigned char *ticketBuf)
{
STACK_TPM_BUFFER(tpmdata)
unsigned char nonceodd[TPM_NONCE_SIZE];
unsigned char authdata[TPM_NONCE_SIZE];
unsigned char c = 0;
uint32_t ordinal_no = htonl(TPM_ORD_CMK_CreateTicket);
uint32_t ret;
uint32_t signatureValueSize_no = htonl(signatureValueSize);
STACK_TPM_BUFFER(serPubKey)
uint32_t serPubKeySize;
session sess;
/* check input arguments */
if (NULL == ownerAuth ||
NULL == signedData || NULL == signatureValue || NULL == key)
return ERR_NULL_ARG;
ret = TPM_WriteKeyPub(&serPubKey, key);
if ((ret & ERR_MASK) != 0) {
return ret;
}
serPubKeySize = ret;
/* generate odd nonce */
ret = TSS_gennonce(nonceodd);
if (0 == ret) {
return ERR_CRYPT_ERR;
}
/* Open OSAP Session */
ret = TSS_SessionOpen(SESSION_DSAP | SESSION_OSAP | SESSION_OIAP,
&sess, ownerAuth, TPM_ET_OWNER, 0);
if (ret != 0) {
return ret;
}
ret = TSS_authhmac(authdata, TSS_Session_GetAuth(&sess), TPM_HASH_SIZE,
TSS_Session_GetENonce(&sess), nonceodd, c,
TPM_U32_SIZE, &ordinal_no,
serPubKeySize, serPubKey.buffer,
TPM_DIGEST_SIZE, signedData,
TPM_U32_SIZE, &signatureValueSize_no,
signatureValueSize, signatureValue,
0, 0);
if (0 != ret) {
TSS_SessionClose(&sess);
return ret;
}
/* build the request buffer */
ret = TSS_buildbuff("00 c2 T l % % @ L % o %", &tpmdata,
ordinal_no,
serPubKeySize, serPubKey.buffer,
TPM_DIGEST_SIZE, signedData,
signatureValueSize, signatureValue,
TSS_Session_GetHandle(&sess),
TPM_NONCE_SIZE, nonceodd,
c,
TPM_HASH_SIZE, authdata);
if ((ret & ERR_MASK)) {
TSS_SessionClose(&sess);
return ret;
}
/* transmit the request buffer to the TPM device and read the reply */
ret = TPM_Transmit(&tpmdata, "CMK_CreateTicket - AUTH1");
TSS_SessionClose(&sess);
if (ret != 0) {
return ret;
}
/* check the HMAC in the response */
ret = TSS_checkhmac1(&tpmdata, ordinal_no, nonceodd,
TSS_Session_GetAuth(&sess), TPM_HASH_SIZE,
TPM_DIGEST_SIZE, TPM_DATA_OFFSET, 0, 0);
if (NULL != ticketBuf) {
memcpy(ticketBuf,
&tpmdata.buffer[TPM_DATA_OFFSET], TPM_DIGEST_SIZE);
}
return ret;
}
uint32_t
TPM_CMK_CreateBlob(uint32_t parenthandle,
unsigned char *parkeyUsageAuth,
uint16_t migScheme,
const struct tpm_buffer *migblob,
unsigned char *sourceKeyDigest,
TPM_MSA_COMPOSITE * msaList,
TPM_CMK_AUTH * resTicket,
unsigned char *sigTicket, uint32_t sigTicketSize,
unsigned char *encData, uint32_t encDataSize,
unsigned char *random, uint32_t * randomSize,
unsigned char *outData, uint32_t * outDataSize)
{
STACK_TPM_BUFFER(tpmdata)
unsigned char nonceodd[TPM_NONCE_SIZE];
unsigned char authdata[TPM_NONCE_SIZE];
unsigned char c = 0;
uint32_t ordinal_no = htonl(TPM_ORD_CMK_CreateBlob);
uint32_t ret;
uint32_t parenthandle_no = htonl(parenthandle);
uint16_t migScheme_no = htons(migScheme);
uint32_t sigTicketSize_no = htonl(sigTicketSize);
uint32_t encDataSize_no = htonl(encDataSize);
uint32_t len1;
uint32_t len2;
uint32_t serMsaListSize = 0;
uint32_t serMsaListSize_no;
struct tpm_buffer *serMsaList;
session sess;
unsigned char dummyauth[TPM_HASH_SIZE];
memset(dummyauth,0,sizeof dummyauth);
STACK_TPM_BUFFER(serResTicket)
uint32_t serResTicketSize = 0;
uint32_t serResTicketSize_no = 0;
if (parkeyUsageAuth == NULL)
parkeyUsageAuth = dummyauth;
/* check input arguments */
if (encData == NULL ||
outData == NULL ||
(sigTicket == NULL && sigTicketSize != 0) || msaList == NULL)
return ERR_NULL_ARG;
/* TPM_MS_RESTRICT_APPROVE needs restrictTicket, TPM_MS_RESTRICT_MIGRATE does not */
if ((migScheme == TPM_MS_RESTRICT_APPROVE) &&
(resTicket == NULL)) {
return ERR_NULL_ARG;
}
ret = needKeysRoom(parenthandle, 0, 0, 0);
if (ret != 0) {
return ret;
}
serMsaList =
TSS_AllocTPMBuffer(msaList->MSAlist * TPM_HASH_SIZE +
TPM_U32_SIZE);
serMsaListSize = TPM_WriteMSAComposite(serMsaList, msaList);
serMsaListSize_no = htonl(serMsaListSize);
if (NULL != resTicket) {
ret = TPM_WriteCMKAuth(&serResTicket, resTicket);
if ((ret & ERR_MASK) != 0) {
return ret;
}
serResTicketSize = ret;
serResTicketSize_no = htonl(serResTicketSize);
}
/* generate odd nonce */
ret = TSS_gennonce(nonceodd);
if (0 == ret) {
TSS_FreeTPMBuffer(serMsaList);
return ERR_CRYPT_ERR;
}
/* Open OIAP Session */
ret = TSS_SessionOpen(SESSION_OSAP | SESSION_OIAP | SESSION_DSAP,
&sess, parkeyUsageAuth, TPM_ET_KEYHANDLE, parenthandle);
if (ret != 0) {
TSS_FreeTPMBuffer(serMsaList);
return ret;
}
/* move Network byte order data to variable for hmac calcualtion */
if (0 != serResTicketSize && 0 != sigTicketSize) {
ret = TSS_authhmac(authdata, TSS_Session_GetAuth(&sess),
TPM_HASH_SIZE, TSS_Session_GetENonce(&sess),
nonceodd, c, TPM_U32_SIZE, &ordinal_no,
TPM_U16_SIZE, &migScheme_no, migblob->used,
migblob->buffer, TPM_DIGEST_SIZE, sourceKeyDigest,
TPM_U32_SIZE, &serMsaListSize_no,
serMsaListSize, serMsaList->buffer,
TPM_U32_SIZE, &serResTicketSize_no,
serResTicketSize, serResTicket.buffer,
TPM_U32_SIZE, &sigTicketSize_no,
sigTicketSize, sigTicket, TPM_U32_SIZE,
&encDataSize_no, encDataSize, encData, 0,
0);
} else {
if (0 == serResTicketSize && 0 == sigTicketSize) {
ret = TSS_authhmac(authdata,
TSS_Session_GetAuth(&sess),
TPM_HASH_SIZE,
TSS_Session_GetENonce(&sess),
nonceodd, c, TPM_U32_SIZE,
&ordinal_no, TPM_U16_SIZE,
&migScheme_no, migblob->used, migblob->buffer,
TPM_DIGEST_SIZE, sourceKeyDigest,
TPM_U32_SIZE, &serMsaListSize_no,
serMsaListSize, serMsaList->buffer,
TPM_U32_SIZE, &serResTicketSize_no,
// would be 0,0 resTicketSize, resTicket,
TPM_U32_SIZE, &sigTicketSize_no,
// would be 0,0 sigTicketSize, sigTicket,
TPM_U32_SIZE, &encDataSize_no,
encDataSize, encData, 0, 0);
} else if (0 != sigTicketSize) {
ret = TSS_authhmac(authdata,
TSS_Session_GetAuth(&sess),
TPM_HASH_SIZE,
TSS_Session_GetENonce(&sess),
nonceodd, c, TPM_U32_SIZE,
&ordinal_no, TPM_U16_SIZE,
&migScheme_no, migblob->used, migblob->buffer,
TPM_DIGEST_SIZE, sourceKeyDigest,
TPM_U32_SIZE, &serMsaListSize_no,
serMsaListSize, serMsaList->buffer,
TPM_U32_SIZE, &serResTicketSize_no,
// would be 0,0 resTicketSize, resTicket,
TPM_U32_SIZE, &sigTicketSize_no,
sigTicketSize, sigTicket,
TPM_U32_SIZE, &encDataSize_no,
encDataSize, encData, 0, 0);
} else if (0 != serResTicketSize) {
ret = TSS_authhmac(authdata,
TSS_Session_GetAuth(&sess),
TPM_HASH_SIZE,
TSS_Session_GetENonce(&sess),
nonceodd, c, TPM_U32_SIZE,
&ordinal_no, TPM_U16_SIZE,
&migScheme_no, migblob->used, migblob->buffer,
TPM_DIGEST_SIZE, sourceKeyDigest,
TPM_U32_SIZE, &serMsaListSize_no,
serMsaListSize, serMsaList->buffer,
TPM_U32_SIZE, &serResTicketSize_no,
serResTicketSize,
serResTicket.buffer, TPM_U32_SIZE,
&sigTicketSize_no,
// would be 0,0 sigTicketSize, sigTicket,
TPM_U32_SIZE, &encDataSize_no,
encDataSize, encData, 0, 0);
}
}
if (0 != ret) {
TSS_FreeTPMBuffer(serMsaList);
TSS_SessionClose(&sess);
return ret;
}
/* build the request buffer */
ret = TSS_buildbuff("00 c2 T l l s % % @ @ @ @ L % o %", &tpmdata,
ordinal_no,
parenthandle_no,
migScheme_no,
migblob->used, migblob->buffer,
TPM_DIGEST_SIZE, sourceKeyDigest,
serMsaListSize, serMsaList->buffer,
serResTicketSize, serResTicket.buffer,
sigTicketSize, sigTicket,
encDataSize, encData,
TSS_Session_GetHandle(&sess),
TPM_NONCE_SIZE, nonceodd,
c, TPM_HASH_SIZE, authdata);
if ((ret & ERR_MASK)) {
TSS_FreeTPMBuffer(serMsaList);
return ret;
}
ret = TPM_Transmit(&tpmdata, "CMK_CreateBlob - AUTH1");
TSS_FreeTPMBuffer(serMsaList);
TSS_SessionClose(&sess);
if (0 != ret) {
return ret;
}
ret = tpm_buffer_load32(&tpmdata, TPM_DATA_OFFSET, &len1);
if ((ret & ERR_MASK)) {
return ret;
}
ret = tpm_buffer_load32(&tpmdata, TPM_DATA_OFFSET + TPM_U32_SIZE + len1, &len2);
if ((ret & ERR_MASK)) {
return ret;
}
ret = TSS_checkhmac1(&tpmdata, ordinal_no, nonceodd,
TSS_Session_GetAuth(&sess), TPM_HASH_SIZE,
TPM_U32_SIZE + len1 + TPM_U32_SIZE + len2,
TPM_DATA_OFFSET, 0, 0);
if (0 != ret) {
return ret;
}
if (NULL != random) {
*randomSize = MIN(*randomSize, len1);
memcpy(random,
&tpmdata.buffer[TPM_DATA_OFFSET + TPM_U32_SIZE],
*randomSize);
}
if (NULL != outData) {
*outDataSize = MIN(*outDataSize, len2);
memcpy(outData,
&tpmdata.buffer[TPM_DATA_OFFSET + TPM_U32_SIZE + len1 +
TPM_U32_SIZE], *outDataSize);
}
return ret;
}
uint32_t
TPM_CMK_ConvertMigration(uint32_t parenthandle,
unsigned char *parkeyUsageAuth,
TPM_CMK_AUTH * resTicket,
unsigned char *sigTicket,
keydata * migratedKey,
TPM_MSA_COMPOSITE * msaList,
unsigned char *random, uint32_t randomSize,
unsigned char *outData, uint32_t * outDataSize)
{
STACK_TPM_BUFFER(tpmdata)
unsigned char nonceodd[TPM_NONCE_SIZE];
unsigned char authdata[TPM_NONCE_SIZE];
unsigned char c = 0;
uint32_t ordinal_no = htonl(TPM_ORD_CMK_ConvertMigration);
uint32_t ret;
uint32_t parenthandle_no = htonl(parenthandle);
uint32_t randomSize_no = htonl(randomSize);
uint32_t len1;
STACK_TPM_BUFFER(serResTicket)
uint32_t serResTicketSize = sizeof (serResTicket);
uint32_t serMsaListSize =
TPM_U32_SIZE + msaList->MSAlist * TPM_HASH_SIZE;
uint32_t serMsaListSize_no = htonl(serMsaListSize);
struct tpm_buffer *serMsaList;
session sess;
STACK_TPM_BUFFER(serMigratedKey)
uint32_t serMigratedKeySize;
unsigned char dummyauth[TPM_HASH_SIZE];
memset(dummyauth,0,sizeof dummyauth);
if (parkeyUsageAuth == NULL)
parkeyUsageAuth = dummyauth;
/* check input arguments */
if (NULL == migratedKey || NULL == msaList || NULL == sigTicket)
return ERR_NULL_ARG;
ret = needKeysRoom(parenthandle, 0, 0, 0);
if (ret != 0) {
return ret;
}
ret = TPM_WriteKey(&serMigratedKey, migratedKey);
if ((ret & ERR_MASK) != 0) {
return ret;
}
serMigratedKeySize = ret;
ret = TPM_WriteCMKAuth(&serResTicket, resTicket);
if ((ret & ERR_MASK) != 0) {
return ret;
}
serResTicketSize = ret;
serMsaList = TSS_AllocTPMBuffer(serMsaListSize);
if (NULL == serMsaList)
return ERR_MEM_ERR;
/*
* Serialize the MSA list
*/
ret = TPM_WriteMSAComposite(serMsaList, msaList);
if ((ret & ERR_MASK) != 0) {
TSS_FreeTPMBuffer(serMsaList);
return ret;
}
serMsaListSize = ret;
serMsaListSize_no = htonl(serMsaListSize);
/* generate odd nonce */
ret = TSS_gennonce(nonceodd);
if (0 == ret) {
TSS_FreeTPMBuffer(serMsaList);
return ERR_CRYPT_ERR;
}
/* Open OIAP Session */
ret = TSS_SessionOpen(SESSION_OSAP | SESSION_OIAP,
&sess,
parkeyUsageAuth, TPM_ET_KEYHANDLE, parenthandle);
if (ret != 0) {
TSS_FreeTPMBuffer(serMsaList);
return ret;
}
/* move Network byte order data to variable for hmac calcualtion */
ret = TSS_authhmac(authdata, TSS_Session_GetAuth(&sess), TPM_HASH_SIZE,
TSS_Session_GetENonce(&sess), nonceodd, c,
TPM_U32_SIZE, &ordinal_no, serResTicketSize,
serResTicket.buffer, TPM_HASH_SIZE, sigTicket,
serMigratedKeySize, serMigratedKey.buffer,
TPM_U32_SIZE, &serMsaListSize_no, serMsaListSize,
serMsaList->buffer, TPM_U32_SIZE, &randomSize_no,
randomSize, random, 0, 0);
if (0 != ret) {
TSS_FreeTPMBuffer(serMsaList);
TSS_SessionClose(&sess);
return ret;
}
/* build the request buffer */
ret = TSS_buildbuff("00 c2 T l l % % % @ @ L % o %", &tpmdata,
ordinal_no,
parenthandle_no,
serResTicketSize, serResTicket.buffer,
TPM_DIGEST_SIZE, sigTicket,
serMigratedKeySize, serMigratedKey.buffer,
serMsaListSize, serMsaList->buffer,
randomSize, random,
TSS_Session_GetHandle(&sess),
TPM_NONCE_SIZE, nonceodd,
c, TPM_HASH_SIZE, authdata);
TSS_FreeTPMBuffer(serMsaList);
if ((ret & ERR_MASK)) {
return ret;
}
ret = TPM_Transmit(&tpmdata, "CMK_ConvertMigration - AUTH1");
if (0 != ret) {
TSS_SessionClose(&sess);
return ret;
}
ret = tpm_buffer_load32(&tpmdata, TPM_DATA_OFFSET, &len1);
if ((ret & ERR_MASK)) {
return ret;
}
ret = TSS_checkhmac1(&tpmdata, ordinal_no, nonceodd,
TSS_Session_GetAuth(&sess), TPM_HASH_SIZE,
TPM_U32_SIZE + len1, TPM_DATA_OFFSET, 0, 0);
if (0 != ret) {
return ret;
}
if (NULL != outData) {
*outDataSize = MIN(*outDataSize, len1);
memcpy(outData,
&tpmdata.buffer[TPM_DATA_OFFSET + TPM_U32_SIZE],
*outDataSize);
}
return ret;
}
|
Nexor-OSS/tpm-luks
|
swtpm-utils/lib/migrate.c
|
C
|
gpl-2.0
| 45,089
|
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
namespace System
{
public static class ListExtensions
{
/// <summary>
/// How many times a specific character occured in a string
/// </summary>
public static int FrequencyCount(this string str, char ch)
{
int count = 0;
int lastPos = -1;
while ((lastPos = str.IndexOf(ch, lastPos + 1)) != -1)
count++;
return count;
}
/// <summary>
/// Performs the specified action on each element of the IEnumerable.
/// </summary>
public static void ForEachAction<T>(this IEnumerable<T> enumerable, Action<T> action)
{
if (action == null || enumerable == null)
{
throw new ArgumentNullException();
}
foreach (var item in enumerable)
{
action.Invoke(item);
}
}
/// <summary>
/// Removes the all the elements that match the conditions defined by the specified predicate.
/// </summary>
public static void RemoveFromIList<TSource>(this IList<TSource> source, Func<TSource, bool> predicate)
{
if (source == null || predicate == null)
{
throw new ArgumentNullException();
}
for (int i = source.Count - 1; i >= 0; i--)
if (predicate.Invoke(source[i]))
{
source.RemoveAt(i);
}
}
/// <summary>
/// Adds range of items to the collection
/// </summary>
public static void AddRange<T>(this ICollection<T> collection, IEnumerable<T> enumerable)
{
foreach (var item in enumerable)
{
collection.Add(item);
}
}
/// <summary>
/// Convertion to ObservableCollection
/// </summary>
public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
return new ObservableCollection<T>(source);
}
/// <summary>
/// For a large list (say 100000 records) this method is one or two seconds faster
/// </summary>
public static TSource FirstOrDefaultFast<TSource>(this IList<TSource> list, Func<TSource, bool> predicate)
{
if (list == null || (predicate == null))
{
throw new ArgumentNullException();
}
for (int i = 0; i < list.Count; i++)
{
var item = list[i];
if (predicate(item))
{
return item;
}
}
return default(TSource);
}
public static int CountFast<TSource>(this IList<TSource> list, Func<TSource, bool> predicate)
{
if (list == null)
{
throw new ArgumentNullException("list");
}
if (predicate == null)
{
throw new ArgumentNullException("predicate");
}
int num = 0;
for (int i = 0; i < list.Count; i++)
{
var item = list[i];
if (predicate(item))
{
num++;
}
}
return num;
}
/// <summary>
/// Index of an item according to the specified predicate
/// </summary>
public static int FirstIndexOf<T>(this IList<T> list, Func<T, bool> predicate)
{
for (int i = 0; i < list.Count; i++)
{
if (predicate.Invoke(list[i]))
{
return i;
}
}
return -1;
}
/// <summary>
/// Removes first item found
/// </summary>
public static void RemoveFirst<T>(this IList<T> list, Func<T, bool> predicate)
{
for (int i = 0; i < list.Count; i++)
{
if (predicate.Invoke(list[i]))
{
list.RemoveAt(i);
return;
}
}
}
/// <summary>
/// Removes last item found
/// </summary>
public static void RemoveLast<T>(this IList<T> list, Func<T, bool> predicate)
{
for (int i = list.Count - 1; i >= 0; i--)
{
if (predicate.Invoke(list[i]))
{
list.RemoveAt(i);
return;
}
}
}
/// <summary>
/// Finds an item which has minimum value based on the specified function. For a list.
/// </summary>
public static T MinValue<T>(this IList<T> list, Func<T, int> function)
{
if (function == null || list == null)
{
throw new ArgumentNullException();
}
int minValue = int.MaxValue;
T result = default(T);
for (int i = 0; i < list.Count; i++)
{
var item = list[i];
var val = function.Invoke(item);
if (val < minValue)
{
result = item;
minValue = val;
}
}
return result;
}
/// <summary>
/// Finds an item which has minimum value based on the specified function. For enumerables.
/// </summary>
public static T MinValue<T>(this IEnumerable<T> enumerable, Func<T, int> function)
{
if (function == null || enumerable == null)
{
throw new ArgumentNullException();
}
int minValue = int.MaxValue;
T result = default(T);
foreach (var item in enumerable)
{
var val = function.Invoke(item);
if (val < minValue)
{
result = item;
minValue = val;
}
}
return result;
}
/// <summary>
/// Finds an item which has maximum value based on the specified function. For enumerables.
/// </summary>
public static T MaxValue<T>(this IList<T> list, Func<T, int> function)
{
if (function == null || list == null)
{
throw new ArgumentNullException();
}
int maxValue = int.MinValue;
T result = default(T);
for (int i = 0; i < list.Count; i++)
{
var item = list[i];
var val = function.Invoke(item);
if (val > maxValue)
{
result = item;
maxValue = val;
}
}
return result;
}
/// <summary>
/// Finds an item which has maximum value based on the specified function. For enumerables.
/// </summary>
public static T MaxValue<T>(this IEnumerable<T> enumerable, Func<T, int> function)
{
if (function == null || enumerable == null)
{
throw new ArgumentNullException();
}
int maxValue = int.MinValue;
T result = default(T);
foreach (var item in enumerable)
{
var val = function.Invoke(item);
if (val > maxValue)
{
result = item;
maxValue = val;
}
}
return result;
}
}
}
|
salarcode/SalarDbCodeGenerator
|
SalarDbCodeGenerator/DbProject/ListExtensions.cs
|
C#
|
gpl-2.0
| 5,894
|
<head>
<title> log </title>
</head>
<body bgcolor="#ffffff">
<a href="../xgremlin.html"> <b>Top level</b> </a><b>.....</b>
<a href="alphalist.html"> <b>Alphabetical list</b> </a><b>.....</b>
<a href="categorylist.html"> <b>Command categories</b> </a>
<hr>
<h2>log</h2><p>
<b>Syntax:</b> <kbd>log</kbd> <i> [ < n > ] [ < errval > ]</i><p>
n - base of logarithm.
errval - if r(i) < 0.0, this will be substituted for log(r)
Log with no arguments takes a natural logarithm of the contents
of the <b>r</b> array. An integer argument causes the log to the
base <b>n</b> to be taken. The optional parameter <b>errval</b> is
substituted for log(r) if r(i) < 0.0. <p><br>
<h3>Example</h3>
<dl>
<dt> <kbd>log 10</kbd>
<dd> calculate the log base 10 of the data in the <b>r</b> array:<br>
<pre>
r(i) = log ( r(i) ) for i = 1, ... ,nop
10
</pre>
</dl>
<p><br>
<h3>Related commands:</h3>
<menu>
<li><a href="derivative.html"> derivative </a>
<li><a href="exp.html"> exp </a>
<li><a href="sinc.html"> sinc </a>
<li><a href="sincos.html"> sincos </a>
<li><a href="planck.html"> planck </a>
<li><a href="voigt.html"> voigt </a>
<li><a href="clear.html"> clear </a>
<li><a href="data.html"> data </a>
<li><a href="decimate.html"> decimate </a>
<li><a href="noise.html"> noise </a>
</menu>
</body>
|
gnave/Xgremlin
|
doc/html/commands/log.html
|
HTML
|
gpl-2.0
| 1,332
|
/*---------------------------------------------------------------------------
FT1000 driver for Flarion Flash OFDM NIC Device
Copyright (C) 2002 Flarion Technologies, All rights reserved.
Copyright (C) 2006 Patrik Ostrihon, All rights reserved.
Copyright (C) 2006 ProWeb Consulting, a.s, All rights reserved.
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your option) any
later version. This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details. You should have received a copy of the GNU General Public
License along with this program; if not, write to the
Free Software Foundation, Inc., 59 Temple Place -
Suite 330, Boston, MA 02111-1307, USA.
-------------------------------------------------------------------------*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/ptrace.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/timer.h>
#include <linux/interrupt.h>
#include <linux/in.h>
#include <asm/io.h>
#include <asm/bitops.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/if_arp.h>
#include <linux/ioport.h>
#include <linux/wait.h>
#include <linux/vmalloc.h>
#include <linux/firmware.h>
#include <linux/ethtool.h>
#include <pcmcia/cistpl.h>
#include <pcmcia/cisreg.h>
#include <pcmcia/ds.h>
#ifdef FT_DEBUG
#define DEBUG(n, args...) printk(KERN_DEBUG args);
#else
#define DEBUG(n, args...)
#endif
#include <linux/delay.h>
#include "ft1000.h"
static const struct firmware *fw_entry;
static void ft1000_hbchk(u_long data);
static struct timer_list poll_timer = {
.function = ft1000_hbchk
};
static u16 cmdbuffer[1024];
static u8 tempbuffer[1600];
static u8 ft1000_card_present;
static u8 flarion_ft1000_cnt;
static irqreturn_t ft1000_interrupt(int irq, void *dev_id);
static void ft1000_enable_interrupts(struct net_device *dev);
static void ft1000_disable_interrupts(struct net_device *dev);
/* new kernel */
MODULE_AUTHOR("");
MODULE_DESCRIPTION
("Support for Flarion Flash OFDM NIC Device. Support for PCMCIA when used with ft1000_cs.");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("FT1000");
#define MAX_RCV_LOOP 100
/*---------------------------------------------------------------------------
Function: ft1000_read_fifo_len
Description: This function will read the ASIC Uplink FIFO status register
which will return the number of bytes remaining in the Uplink FIFO.
Sixteen bytes are subtracted to make sure that the ASIC does not
reach its threshold.
Input:
dev - network device structure
Output:
value - number of bytes available in the ASIC Uplink FIFO.
-------------------------------------------------------------------------*/
static inline u16 ft1000_read_fifo_len(struct net_device *dev)
{
struct ft1000_info *info = netdev_priv(dev);
if (info->AsicID == ELECTRABUZZ_ID)
return (ft1000_read_reg(dev, FT1000_REG_UFIFO_STAT) - 16);
else
return (ft1000_read_reg(dev, FT1000_REG_MAG_UFSR) - 16);
}
/*---------------------------------------------------------------------------
Function: ft1000_read_dpram
Description: This function will read the specific area of dpram
(Electrabuzz ASIC only)
Input:
dev - device structure
offset - index of dpram
Output:
value - value of dpram
-------------------------------------------------------------------------*/
u16 ft1000_read_dpram(struct net_device *dev, int offset)
{
struct ft1000_info *info = netdev_priv(dev);
unsigned long flags;
u16 data;
/* Provide mutual exclusive access while reading ASIC registers. */
spin_lock_irqsave(&info->dpram_lock, flags);
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR, offset);
data = ft1000_read_reg(dev, FT1000_REG_DPRAM_DATA);
spin_unlock_irqrestore(&info->dpram_lock, flags);
return data;
}
/*---------------------------------------------------------------------------
Function: ft1000_write_dpram
Description: This function will write to a specific area of dpram
(Electrabuzz ASIC only)
Input:
dev - device structure
offset - index of dpram
value - value to write
Output:
none.
-------------------------------------------------------------------------*/
static inline void ft1000_write_dpram(struct net_device *dev,
int offset, u16 value)
{
struct ft1000_info *info = netdev_priv(dev);
unsigned long flags;
/* Provide mutual exclusive access while reading ASIC registers. */
spin_lock_irqsave(&info->dpram_lock, flags);
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR, offset);
ft1000_write_reg(dev, FT1000_REG_DPRAM_DATA, value);
spin_unlock_irqrestore(&info->dpram_lock, flags);
}
/*---------------------------------------------------------------------------
Function: ft1000_read_dpram_mag_16
Description: This function will read the specific area of dpram
(Magnemite ASIC only)
Input:
dev - device structure
offset - index of dpram
Output:
value - value of dpram
-------------------------------------------------------------------------*/
u16 ft1000_read_dpram_mag_16(struct net_device *dev, int offset, int Index)
{
struct ft1000_info *info = netdev_priv(dev);
unsigned long flags;
u16 data;
/* Provide mutual exclusive access while reading ASIC registers. */
spin_lock_irqsave(&info->dpram_lock, flags);
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR, offset);
/* check if we want to read upper or lower 32-bit word */
if (Index) {
data = ft1000_read_reg(dev, FT1000_REG_MAG_DPDATAL);
} else {
data = ft1000_read_reg(dev, FT1000_REG_MAG_DPDATAH);
}
spin_unlock_irqrestore(&info->dpram_lock, flags);
return data;
}
/*---------------------------------------------------------------------------
Function: ft1000_write_dpram_mag_16
Description: This function will write to a specific area of dpram
(Magnemite ASIC only)
Input:
dev - device structure
offset - index of dpram
value - value to write
Output:
none.
-------------------------------------------------------------------------*/
static inline void ft1000_write_dpram_mag_16(struct net_device *dev,
int offset, u16 value, int Index)
{
struct ft1000_info *info = netdev_priv(dev);
unsigned long flags;
/* Provide mutual exclusive access while reading ASIC registers. */
spin_lock_irqsave(&info->dpram_lock, flags);
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR, offset);
if (Index) {
ft1000_write_reg(dev, FT1000_REG_MAG_DPDATAL, value);
} else {
ft1000_write_reg(dev, FT1000_REG_MAG_DPDATAH, value);
}
spin_unlock_irqrestore(&info->dpram_lock, flags);
}
/*---------------------------------------------------------------------------
Function: ft1000_read_dpram_mag_32
Description: This function will read the specific area of dpram
(Magnemite ASIC only)
Input:
dev - device structure
offset - index of dpram
Output:
value - value of dpram
-------------------------------------------------------------------------*/
u32 ft1000_read_dpram_mag_32(struct net_device *dev, int offset)
{
struct ft1000_info *info = netdev_priv(dev);
unsigned long flags;
u32 data;
/* Provide mutual exclusive access while reading ASIC registers. */
spin_lock_irqsave(&info->dpram_lock, flags);
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR, offset);
data = inl(dev->base_addr + FT1000_REG_MAG_DPDATAL);
spin_unlock_irqrestore(&info->dpram_lock, flags);
return data;
}
/*---------------------------------------------------------------------------
Function: ft1000_write_dpram_mag_32
Description: This function will write to a specific area of dpram
(Magnemite ASIC only)
Input:
dev - device structure
offset - index of dpram
value - value to write
Output:
none.
-------------------------------------------------------------------------*/
void ft1000_write_dpram_mag_32(struct net_device *dev, int offset, u32 value)
{
struct ft1000_info *info = netdev_priv(dev);
unsigned long flags;
/* Provide mutual exclusive access while reading ASIC registers. */
spin_lock_irqsave(&info->dpram_lock, flags);
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR, offset);
outl(value, dev->base_addr + FT1000_REG_MAG_DPDATAL);
spin_unlock_irqrestore(&info->dpram_lock, flags);
}
/*---------------------------------------------------------------------------
Function: ft1000_enable_interrupts
Description: This function will enable interrupts base on the current interrupt mask.
Input:
dev - device structure
Output:
None.
-------------------------------------------------------------------------*/
static void ft1000_enable_interrupts(struct net_device *dev)
{
u16 tempword;
DEBUG(1, "ft1000_hw:ft1000_enable_interrupts()\n");
ft1000_write_reg(dev, FT1000_REG_SUP_IMASK, ISR_DEFAULT_MASK);
tempword = ft1000_read_reg(dev, FT1000_REG_SUP_IMASK);
DEBUG(1,
"ft1000_hw:ft1000_enable_interrupts:current interrupt enable mask = 0x%x\n",
tempword);
}
/*---------------------------------------------------------------------------
Function: ft1000_disable_interrupts
Description: This function will disable all interrupts.
Input:
dev - device structure
Output:
None.
-------------------------------------------------------------------------*/
static void ft1000_disable_interrupts(struct net_device *dev)
{
u16 tempword;
DEBUG(1, "ft1000_hw: ft1000_disable_interrupts()\n");
ft1000_write_reg(dev, FT1000_REG_SUP_IMASK, ISR_MASK_ALL);
tempword = ft1000_read_reg(dev, FT1000_REG_SUP_IMASK);
DEBUG(1,
"ft1000_hw:ft1000_disable_interrupts:current interrupt enable mask = 0x%x\n",
tempword);
}
/*---------------------------------------------------------------------------
Function: ft1000_reset_asic
Description: This function will call the Card Service function to reset the
ASIC.
Input:
dev - device structure
Output:
none
-------------------------------------------------------------------------*/
static void ft1000_reset_asic(struct net_device *dev)
{
struct ft1000_info *info = netdev_priv(dev);
struct ft1000_pcmcia *pcmcia = info->priv;
u16 tempword;
DEBUG(1, "ft1000_hw:ft1000_reset_asic called\n");
(*info->ft1000_reset) (pcmcia->link);
/*
* Let's use the register provided by the Magnemite ASIC to reset the
* ASIC and DSP.
*/
if (info->AsicID == MAGNEMITE_ID) {
ft1000_write_reg(dev, FT1000_REG_RESET,
(DSP_RESET_BIT | ASIC_RESET_BIT));
}
mdelay(1);
if (info->AsicID == ELECTRABUZZ_ID) {
/* set watermark to -1 in order to not generate an interrupt */
ft1000_write_reg(dev, FT1000_REG_WATERMARK, 0xffff);
} else {
/* set watermark to -1 in order to not generate an interrupt */
ft1000_write_reg(dev, FT1000_REG_MAG_WATERMARK, 0xffff);
}
/* clear interrupts */
tempword = ft1000_read_reg(dev, FT1000_REG_SUP_ISR);
DEBUG(1, "ft1000_hw: interrupt status register = 0x%x\n", tempword);
ft1000_write_reg(dev, FT1000_REG_SUP_ISR, tempword);
tempword = ft1000_read_reg(dev, FT1000_REG_SUP_ISR);
DEBUG(1, "ft1000_hw: interrupt status register = 0x%x\n", tempword);
}
/*---------------------------------------------------------------------------
Function: ft1000_reset_card
Description: This function will reset the card
Input:
dev - device structure
Output:
status - false (card reset fail)
true (card reset successful)
-------------------------------------------------------------------------*/
static int ft1000_reset_card(struct net_device *dev)
{
struct ft1000_info *info = netdev_priv(dev);
u16 tempword;
int i;
unsigned long flags;
struct prov_record *ptr;
DEBUG(1, "ft1000_hw:ft1000_reset_card called.....\n");
info->CardReady = 0;
info->ProgConStat = 0;
info->squeseqnum = 0;
ft1000_disable_interrupts(dev);
/* del_timer(&poll_timer); */
/* Make sure we free any memory reserve for provisioning */
while (list_empty(&info->prov_list) == 0) {
DEBUG(0,
"ft1000_hw:ft1000_reset_card:deleting provisioning record\n");
ptr = list_entry(info->prov_list.next, struct prov_record, list);
list_del(&ptr->list);
kfree(ptr->pprov_data);
kfree(ptr);
}
if (info->AsicID == ELECTRABUZZ_ID) {
DEBUG(1, "ft1000_hw:ft1000_reset_card:resetting DSP\n");
ft1000_write_reg(dev, FT1000_REG_RESET, DSP_RESET_BIT);
} else {
DEBUG(1,
"ft1000_hw:ft1000_reset_card:resetting ASIC and DSP\n");
ft1000_write_reg(dev, FT1000_REG_RESET,
(DSP_RESET_BIT | ASIC_RESET_BIT));
}
/* Copy DSP session record into info block if this is not a coldstart */
if (ft1000_card_present == 1) {
spin_lock_irqsave(&info->dpram_lock, flags);
if (info->AsicID == ELECTRABUZZ_ID) {
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR,
FT1000_DPRAM_RX_BASE);
for (i = 0; i < MAX_DSP_SESS_REC; i++) {
info->DSPSess.Rec[i] =
ft1000_read_reg(dev,
FT1000_REG_DPRAM_DATA);
}
} else {
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR,
FT1000_DPRAM_MAG_RX_BASE);
for (i = 0; i < MAX_DSP_SESS_REC / 2; i++) {
info->DSPSess.MagRec[i] =
inl(dev->base_addr + FT1000_REG_MAG_DPDATA);
}
}
spin_unlock_irqrestore(&info->dpram_lock, flags);
}
DEBUG(1, "ft1000_hw:ft1000_reset_card:resetting ASIC\n");
mdelay(10);
/* reset ASIC */
ft1000_reset_asic(dev);
DEBUG(1, "ft1000_hw:ft1000_reset_card:downloading dsp image\n");
if (info->AsicID == MAGNEMITE_ID) {
/* Put dsp in reset and take ASIC out of reset */
DEBUG(0,
"ft1000_hw:ft1000_reset_card:Put DSP in reset and take ASIC out of reset\n");
ft1000_write_reg(dev, FT1000_REG_RESET, DSP_RESET_BIT);
/* Setting MAGNEMITE ASIC to big endian mode */
ft1000_write_reg(dev, FT1000_REG_SUP_CTRL, HOST_INTF_BE);
/* Download bootloader */
card_bootload(dev);
/* Take DSP out of reset */
ft1000_write_reg(dev, FT1000_REG_RESET, 0);
/* FLARION_DSP_ACTIVE; */
mdelay(10);
DEBUG(0, "ft1000_hw:ft1000_reset_card:Take DSP out of reset\n");
/* Wait for 0xfefe indicating dsp ready before starting download */
for (i = 0; i < 50; i++) {
tempword =
ft1000_read_dpram_mag_16(dev, FT1000_MAG_DPRAM_FEFE,
FT1000_MAG_DPRAM_FEFE_INDX);
if (tempword == 0xfefe) {
break;
}
mdelay(20);
}
if (i == 50) {
DEBUG(0,
"ft1000_hw:ft1000_reset_card:No FEFE detected from DSP\n");
return false;
}
} else {
/* Take DSP out of reset */
ft1000_write_reg(dev, FT1000_REG_RESET, ~DSP_RESET_BIT);
mdelay(10);
}
if (card_download(dev, fw_entry->data, fw_entry->size)) {
DEBUG(1, "card download unsuccessful\n");
return false;
} else {
DEBUG(1, "card download successful\n");
}
mdelay(10);
if (info->AsicID == ELECTRABUZZ_ID) {
/*
* Need to initialize the FIFO length counter to zero in order to sync up
* with the DSP
*/
info->fifo_cnt = 0;
ft1000_write_dpram(dev, FT1000_FIFO_LEN, info->fifo_cnt);
/* Initialize DSP heartbeat area to ho */
ft1000_write_dpram(dev, FT1000_HI_HO, ho);
tempword = ft1000_read_dpram(dev, FT1000_HI_HO);
DEBUG(1, "ft1000_hw:ft1000_reset_asic:hi_ho value = 0x%x\n",
tempword);
} else {
/* Initialize DSP heartbeat area to ho */
ft1000_write_dpram_mag_16(dev, FT1000_MAG_HI_HO, ho_mag,
FT1000_MAG_HI_HO_INDX);
tempword =
ft1000_read_dpram_mag_16(dev, FT1000_MAG_HI_HO,
FT1000_MAG_HI_HO_INDX);
DEBUG(1, "ft1000_hw:ft1000_reset_card:hi_ho value = 0x%x\n",
tempword);
}
info->CardReady = 1;
ft1000_enable_interrupts(dev);
/* Schedule heartbeat process to run every 2 seconds */
/* poll_timer.expires = jiffies + (2*HZ); */
/* poll_timer.data = (u_long)dev; */
/* add_timer(&poll_timer); */
return true;
}
/*---------------------------------------------------------------------------
Function: ft1000_chkcard
Description: This function will check if the device is presently available on
the system.
Input:
dev - device structure
Output:
status - false (device is not present)
true (device is present)
-------------------------------------------------------------------------*/
static int ft1000_chkcard(struct net_device *dev)
{
u16 tempword;
/*
* Mask register is used to check for device presence since it is never
* set to zero.
*/
tempword = ft1000_read_reg(dev, FT1000_REG_SUP_IMASK);
if (tempword == 0) {
DEBUG(1,
"ft1000_hw:ft1000_chkcard: IMASK = 0 Card not detected\n");
return false;
}
/*
* The system will return the value of 0xffff for the version register
* if the device is not present.
*/
tempword = ft1000_read_reg(dev, FT1000_REG_ASIC_ID);
if (tempword == 0xffff) {
DEBUG(1,
"ft1000_hw:ft1000_chkcard: Version = 0xffff Card not detected\n");
return false;
}
return true;
}
/*---------------------------------------------------------------------------
Function: ft1000_hbchk
Description: This function will perform the heart beat check of the DSP as
well as the ASIC.
Input:
dev - device structure
Output:
none
-------------------------------------------------------------------------*/
static void ft1000_hbchk(u_long data)
{
struct net_device *dev = (struct net_device *)data;
struct ft1000_info *info;
u16 tempword;
info = netdev_priv(dev);
if (info->CardReady == 1) {
/* Perform dsp heartbeat check */
if (info->AsicID == ELECTRABUZZ_ID) {
tempword = ft1000_read_dpram(dev, FT1000_HI_HO);
} else {
tempword =
ntohs(ft1000_read_dpram_mag_16
(dev, FT1000_MAG_HI_HO,
FT1000_MAG_HI_HO_INDX));
}
DEBUG(1, "ft1000_hw:ft1000_hbchk:hi_ho value = 0x%x\n",
tempword);
/* Let's perform another check if ho is not detected */
if (tempword != ho) {
if (info->AsicID == ELECTRABUZZ_ID) {
tempword = ft1000_read_dpram(dev, FT1000_HI_HO);
}
else {
tempword = ntohs(ft1000_read_dpram_mag_16(dev, FT1000_MAG_HI_HO, FT1000_MAG_HI_HO_INDX));
}
}
if (tempword != ho) {
printk(KERN_INFO
"ft1000: heartbeat failed - no ho detected\n");
if (info->AsicID == ELECTRABUZZ_ID) {
info->DSP_TIME[0] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER0);
info->DSP_TIME[1] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER1);
info->DSP_TIME[2] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER2);
info->DSP_TIME[3] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER3);
} else {
info->DSP_TIME[0] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER0,
FT1000_MAG_DSP_TIMER0_INDX);
info->DSP_TIME[1] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER1,
FT1000_MAG_DSP_TIMER1_INDX);
info->DSP_TIME[2] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER2,
FT1000_MAG_DSP_TIMER2_INDX);
info->DSP_TIME[3] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER3,
FT1000_MAG_DSP_TIMER3_INDX);
}
info->DrvErrNum = DSP_HB_INFO;
if (ft1000_reset_card(dev) == 0) {
printk(KERN_INFO
"ft1000: Hardware Failure Detected - PC Card disabled\n");
info->ProgConStat = 0xff;
return;
}
/* Schedule this module to run every 2 seconds */
poll_timer.expires = jiffies + (2*HZ);
poll_timer.data = (u_long)dev;
add_timer(&poll_timer);
return;
}
tempword = ft1000_read_reg(dev, FT1000_REG_DOORBELL);
/* Let's check doorbell again if fail */
if (tempword & FT1000_DB_HB) {
tempword = ft1000_read_reg(dev, FT1000_REG_DOORBELL);
}
if (tempword & FT1000_DB_HB) {
printk(KERN_INFO
"ft1000: heartbeat doorbell not clear by firmware\n");
if (info->AsicID == ELECTRABUZZ_ID) {
info->DSP_TIME[0] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER0);
info->DSP_TIME[1] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER1);
info->DSP_TIME[2] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER2);
info->DSP_TIME[3] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER3);
} else {
info->DSP_TIME[0] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER0,
FT1000_MAG_DSP_TIMER0_INDX);
info->DSP_TIME[1] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER1,
FT1000_MAG_DSP_TIMER1_INDX);
info->DSP_TIME[2] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER2,
FT1000_MAG_DSP_TIMER2_INDX);
info->DSP_TIME[3] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER3,
FT1000_MAG_DSP_TIMER3_INDX);
}
info->DrvErrNum = DSP_HB_INFO;
if (ft1000_reset_card(dev) == 0) {
printk(KERN_INFO
"ft1000: Hardware Failure Detected - PC Card disabled\n");
info->ProgConStat = 0xff;
return;
}
/* Schedule this module to run every 2 seconds */
poll_timer.expires = jiffies + (2*HZ);
poll_timer.data = (u_long)dev;
add_timer(&poll_timer);
return;
}
/*
* Set dedicated area to hi and ring appropriate doorbell according
* to hi/ho heartbeat protocol
*/
if (info->AsicID == ELECTRABUZZ_ID) {
ft1000_write_dpram(dev, FT1000_HI_HO, hi);
} else {
ft1000_write_dpram_mag_16(dev, FT1000_MAG_HI_HO, hi_mag,
FT1000_MAG_HI_HO_INDX);
}
if (info->AsicID == ELECTRABUZZ_ID) {
tempword = ft1000_read_dpram(dev, FT1000_HI_HO);
} else {
tempword =
ntohs(ft1000_read_dpram_mag_16
(dev, FT1000_MAG_HI_HO,
FT1000_MAG_HI_HO_INDX));
}
/* Let's write hi again if fail */
if (tempword != hi) {
if (info->AsicID == ELECTRABUZZ_ID) {
ft1000_write_dpram(dev, FT1000_HI_HO, hi);
}
else {
ft1000_write_dpram_mag_16(dev, FT1000_MAG_HI_HO, hi_mag, FT1000_MAG_HI_HO_INDX);
}
if (info->AsicID == ELECTRABUZZ_ID) {
tempword = ft1000_read_dpram(dev, FT1000_HI_HO);
}
else {
tempword = ntohs(ft1000_read_dpram_mag_16(dev, FT1000_MAG_HI_HO, FT1000_MAG_HI_HO_INDX));
}
}
if (tempword != hi) {
printk(KERN_INFO
"ft1000: heartbeat failed - cannot write hi into DPRAM\n");
if (info->AsicID == ELECTRABUZZ_ID) {
info->DSP_TIME[0] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER0);
info->DSP_TIME[1] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER1);
info->DSP_TIME[2] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER2);
info->DSP_TIME[3] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER3);
} else {
info->DSP_TIME[0] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER0,
FT1000_MAG_DSP_TIMER0_INDX);
info->DSP_TIME[1] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER1,
FT1000_MAG_DSP_TIMER1_INDX);
info->DSP_TIME[2] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER2,
FT1000_MAG_DSP_TIMER2_INDX);
info->DSP_TIME[3] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER3,
FT1000_MAG_DSP_TIMER3_INDX);
}
info->DrvErrNum = DSP_HB_INFO;
if (ft1000_reset_card(dev) == 0) {
printk(KERN_INFO
"ft1000: Hardware Failure Detected - PC Card disabled\n");
info->ProgConStat = 0xff;
return;
}
/* Schedule this module to run every 2 seconds */
poll_timer.expires = jiffies + (2*HZ);
poll_timer.data = (u_long)dev;
add_timer(&poll_timer);
return;
}
ft1000_write_reg(dev, FT1000_REG_DOORBELL, FT1000_DB_HB);
}
/* Schedule this module to run every 2 seconds */
poll_timer.expires = jiffies + (2 * HZ);
poll_timer.data = (u_long) dev;
add_timer(&poll_timer);
}
/*---------------------------------------------------------------------------
Function: ft1000_send_cmd
Description:
Input:
Output:
-------------------------------------------------------------------------*/
static void ft1000_send_cmd (struct net_device *dev, u16 *ptempbuffer, int size, u16 qtype)
{
struct ft1000_info *info = netdev_priv(dev);
int i;
u16 tempword;
unsigned long flags;
size += sizeof(struct pseudo_hdr);
/* check for odd byte and increment to 16-bit word align value */
if ((size & 0x0001)) {
size++;
}
DEBUG(1, "FT1000:ft1000_send_cmd:total length = %d\n", size);
DEBUG(1, "FT1000:ft1000_send_cmd:length = %d\n", ntohs(*ptempbuffer));
/*
* put message into slow queue area
* All messages are in the form total_len + pseudo header + message body
*/
spin_lock_irqsave(&info->dpram_lock, flags);
/* Make sure SLOWQ doorbell is clear */
tempword = ft1000_read_reg(dev, FT1000_REG_DOORBELL);
i=0;
while (tempword & FT1000_DB_DPRAM_TX) {
mdelay(10);
i++;
if (i==10) {
spin_unlock_irqrestore(&info->dpram_lock, flags);
return;
}
tempword = ft1000_read_reg(dev, FT1000_REG_DOORBELL);
}
if (info->AsicID == ELECTRABUZZ_ID) {
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR,
FT1000_DPRAM_TX_BASE);
/* Write total length to dpram */
ft1000_write_reg(dev, FT1000_REG_DPRAM_DATA, size);
/* Write pseudo header and messgae body */
for (i = 0; i < (size >> 1); i++) {
DEBUG(1, "FT1000:ft1000_send_cmd:data %d = 0x%x\n", i,
*ptempbuffer);
tempword = htons(*ptempbuffer++);
ft1000_write_reg(dev, FT1000_REG_DPRAM_DATA, tempword);
}
} else {
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR,
FT1000_DPRAM_MAG_TX_BASE);
/* Write total length to dpram */
ft1000_write_reg(dev, FT1000_REG_MAG_DPDATAH, htons(size));
/* Write pseudo header and messgae body */
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR,
FT1000_DPRAM_MAG_TX_BASE + 1);
for (i = 0; i < (size >> 2); i++) {
DEBUG(1, "FT1000:ft1000_send_cmd:data = 0x%x\n",
*ptempbuffer);
outw(*ptempbuffer++,
dev->base_addr + FT1000_REG_MAG_DPDATAL);
DEBUG(1, "FT1000:ft1000_send_cmd:data = 0x%x\n",
*ptempbuffer);
outw(*ptempbuffer++,
dev->base_addr + FT1000_REG_MAG_DPDATAH);
}
DEBUG(1, "FT1000:ft1000_send_cmd:data = 0x%x\n", *ptempbuffer);
outw(*ptempbuffer++, dev->base_addr + FT1000_REG_MAG_DPDATAL);
DEBUG(1, "FT1000:ft1000_send_cmd:data = 0x%x\n", *ptempbuffer);
outw(*ptempbuffer++, dev->base_addr + FT1000_REG_MAG_DPDATAH);
}
spin_unlock_irqrestore(&info->dpram_lock, flags);
/* ring doorbell to notify DSP that we have a message ready */
ft1000_write_reg(dev, FT1000_REG_DOORBELL, FT1000_DB_DPRAM_TX);
}
/*---------------------------------------------------------------------------
Function: ft1000_receive_cmd
Description: This function will read a message from the dpram area.
Input:
dev - network device structure
pbuffer - caller supply address to buffer
pnxtph - pointer to next pseudo header
Output:
Status = 0 (unsuccessful)
= 1 (successful)
-------------------------------------------------------------------------*/
static bool ft1000_receive_cmd(struct net_device *dev, u16 *pbuffer,
int maxsz, u16 *pnxtph)
{
struct ft1000_info *info = netdev_priv(dev);
u16 size;
u16 *ppseudohdr;
int i;
u16 tempword;
unsigned long flags;
if (info->AsicID == ELECTRABUZZ_ID) {
size = ( ft1000_read_dpram(dev, *pnxtph) ) + sizeof(struct pseudo_hdr);
} else {
size =
ntohs(ft1000_read_dpram_mag_16
(dev, FT1000_MAG_PH_LEN,
FT1000_MAG_PH_LEN_INDX)) + sizeof(struct pseudo_hdr);
}
if (size > maxsz) {
DEBUG(1,
"FT1000:ft1000_receive_cmd:Invalid command length = %d\n",
size);
return false;
} else {
ppseudohdr = (u16 *) pbuffer;
spin_lock_irqsave(&info->dpram_lock, flags);
if (info->AsicID == ELECTRABUZZ_ID) {
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR,
FT1000_DPRAM_RX_BASE + 2);
for (i = 0; i <= (size >> 1); i++) {
tempword =
ft1000_read_reg(dev, FT1000_REG_DPRAM_DATA);
*pbuffer++ = ntohs(tempword);
}
} else {
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR,
FT1000_DPRAM_MAG_RX_BASE);
*pbuffer = inw(dev->base_addr + FT1000_REG_MAG_DPDATAH);
DEBUG(1, "ft1000_hw:received data = 0x%x\n", *pbuffer);
pbuffer++;
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR,
FT1000_DPRAM_MAG_RX_BASE + 1);
for (i = 0; i <= (size >> 2); i++) {
*pbuffer =
inw(dev->base_addr +
FT1000_REG_MAG_DPDATAL);
pbuffer++;
*pbuffer =
inw(dev->base_addr +
FT1000_REG_MAG_DPDATAH);
pbuffer++;
}
/* copy odd aligned word */
*pbuffer = inw(dev->base_addr + FT1000_REG_MAG_DPDATAL);
DEBUG(1, "ft1000_hw:received data = 0x%x\n", *pbuffer);
pbuffer++;
*pbuffer = inw(dev->base_addr + FT1000_REG_MAG_DPDATAH);
DEBUG(1, "ft1000_hw:received data = 0x%x\n", *pbuffer);
pbuffer++;
}
if (size & 0x0001) {
/* copy odd byte from fifo */
tempword = ft1000_read_reg(dev, FT1000_REG_DPRAM_DATA);
*pbuffer = ntohs(tempword);
}
spin_unlock_irqrestore(&info->dpram_lock, flags);
/*
* Check if pseudo header checksum is good
* Calculate pseudo header checksum
*/
tempword = *ppseudohdr++;
for (i = 1; i < 7; i++) {
tempword ^= *ppseudohdr++;
}
if ((tempword != *ppseudohdr)) {
DEBUG(1,
"FT1000:ft1000_receive_cmd:Pseudo header checksum mismatch\n");
/* Drop this message */
return false;
}
return true;
}
}
/*---------------------------------------------------------------------------
Function: ft1000_proc_drvmsg
Description: This function will process the various driver messages.
Input:
dev - device structure
pnxtph - pointer to next pseudo header
Output:
none
-------------------------------------------------------------------------*/
static void ft1000_proc_drvmsg(struct net_device *dev)
{
struct ft1000_info *info = netdev_priv(dev);
u16 msgtype;
u16 tempword;
struct media_msg *pmediamsg;
struct dsp_init_msg *pdspinitmsg;
struct drv_msg *pdrvmsg;
u16 len;
u16 i;
struct prov_record *ptr;
struct pseudo_hdr *ppseudo_hdr;
u16 *pmsg;
struct timeval tv;
union {
u8 byte[2];
u16 wrd;
} convert;
if (info->AsicID == ELECTRABUZZ_ID) {
tempword = FT1000_DPRAM_RX_BASE+2;
}
else {
tempword = FT1000_DPRAM_MAG_RX_BASE;
}
if ( ft1000_receive_cmd(dev, &cmdbuffer[0], MAX_CMD_SQSIZE, &tempword) ) {
/* Get the message type which is total_len + PSEUDO header + msgtype + message body */
pdrvmsg = (struct drv_msg *) & cmdbuffer[0];
msgtype = ntohs(pdrvmsg->type);
DEBUG(1, "Command message type = 0x%x\n", msgtype);
switch (msgtype) {
case DSP_PROVISION:
DEBUG(0,
"Got a provisioning request message from DSP\n");
mdelay(25);
while (list_empty(&info->prov_list) == 0) {
DEBUG(0, "Sending a provisioning message\n");
/* Make sure SLOWQ doorbell is clear */
tempword =
ft1000_read_reg(dev, FT1000_REG_DOORBELL);
i = 0;
while (tempword & FT1000_DB_DPRAM_TX) {
mdelay(5);
i++;
if (i == 10) {
break;
}
}
ptr =
list_entry(info->prov_list.next,
struct prov_record, list);
len = *(u16 *) ptr->pprov_data;
len = htons(len);
pmsg = (u16 *) ptr->pprov_data;
ppseudo_hdr = (struct pseudo_hdr *) pmsg;
/* Insert slow queue sequence number */
ppseudo_hdr->seq_num = info->squeseqnum++;
ppseudo_hdr->portsrc = 0;
/* Calculate new checksum */
ppseudo_hdr->checksum = *pmsg++;
DEBUG(1, "checksum = 0x%x\n",
ppseudo_hdr->checksum);
for (i = 1; i < 7; i++) {
ppseudo_hdr->checksum ^= *pmsg++;
DEBUG(1, "checksum = 0x%x\n",
ppseudo_hdr->checksum);
}
ft1000_send_cmd (dev, (u16 *)ptr->pprov_data, len, SLOWQ_TYPE);
list_del(&ptr->list);
kfree(ptr->pprov_data);
kfree(ptr);
}
/*
* Indicate adapter is ready to take application messages after all
* provisioning messages are sent
*/
info->CardReady = 1;
break;
case MEDIA_STATE:
pmediamsg = (struct media_msg *) & cmdbuffer[0];
if (info->ProgConStat != 0xFF) {
if (pmediamsg->state) {
DEBUG(1, "Media is up\n");
if (info->mediastate == 0) {
netif_carrier_on(dev);
netif_wake_queue(dev);
info->mediastate = 1;
do_gettimeofday(&tv);
info->ConTm = tv.tv_sec;
}
} else {
DEBUG(1, "Media is down\n");
if (info->mediastate == 1) {
info->mediastate = 0;
netif_carrier_off(dev);
netif_stop_queue(dev);
info->ConTm = 0;
}
}
}
else {
DEBUG(1, "Media is down\n");
if (info->mediastate == 1) {
info->mediastate = 0;
netif_carrier_off(dev);
netif_stop_queue(dev);
info->ConTm = 0;
}
}
break;
case DSP_INIT_MSG:
pdspinitmsg = (struct dsp_init_msg *) & cmdbuffer[0];
memcpy(info->DspVer, pdspinitmsg->DspVer, DSPVERSZ);
DEBUG(1, "DSPVER = 0x%2x 0x%2x 0x%2x 0x%2x\n",
info->DspVer[0], info->DspVer[1], info->DspVer[2],
info->DspVer[3]);
memcpy(info->HwSerNum, pdspinitmsg->HwSerNum,
HWSERNUMSZ);
memcpy(info->Sku, pdspinitmsg->Sku, SKUSZ);
memcpy(info->eui64, pdspinitmsg->eui64, EUISZ);
dev->dev_addr[0] = info->eui64[0];
dev->dev_addr[1] = info->eui64[1];
dev->dev_addr[2] = info->eui64[2];
dev->dev_addr[3] = info->eui64[5];
dev->dev_addr[4] = info->eui64[6];
dev->dev_addr[5] = info->eui64[7];
if (ntohs(pdspinitmsg->length) ==
(sizeof(struct dsp_init_msg) - 20)) {
memcpy(info->ProductMode,
pdspinitmsg->ProductMode, MODESZ);
memcpy(info->RfCalVer, pdspinitmsg->RfCalVer,
CALVERSZ);
memcpy(info->RfCalDate, pdspinitmsg->RfCalDate,
CALDATESZ);
DEBUG(1, "RFCalVer = 0x%2x 0x%2x\n",
info->RfCalVer[0], info->RfCalVer[1]);
}
break ;
case DSP_STORE_INFO:
DEBUG(1, "FT1000:drivermsg:Got DSP_STORE_INFO\n");
tempword = ntohs(pdrvmsg->length);
info->DSPInfoBlklen = tempword;
if (tempword < (MAX_DSP_SESS_REC - 4)) {
pmsg = (u16 *) & pdrvmsg->data[0];
for (i = 0; i < ((tempword + 1) / 2); i++) {
DEBUG(1,
"FT1000:drivermsg:dsp info data = 0x%x\n",
*pmsg);
info->DSPInfoBlk[i + 10] = *pmsg++;
}
}
break;
case DSP_GET_INFO:
DEBUG(1, "FT1000:drivermsg:Got DSP_GET_INFO\n");
/*
* copy dsp info block to dsp
* allow any outstanding ioctl to finish
*/
mdelay(10);
tempword = ft1000_read_reg(dev, FT1000_REG_DOORBELL);
if (tempword & FT1000_DB_DPRAM_TX) {
mdelay(10);
tempword =
ft1000_read_reg(dev, FT1000_REG_DOORBELL);
if (tempword & FT1000_DB_DPRAM_TX) {
mdelay(10);
}
}
if ((tempword & FT1000_DB_DPRAM_TX) == 0) {
/*
* Put message into Slow Queue
* Form Pseudo header
*/
pmsg = (u16 *) info->DSPInfoBlk;
ppseudo_hdr = (struct pseudo_hdr *) pmsg;
ppseudo_hdr->length =
htons(info->DSPInfoBlklen + 4);
ppseudo_hdr->source = 0x10;
ppseudo_hdr->destination = 0x20;
ppseudo_hdr->portdest = 0;
ppseudo_hdr->portsrc = 0;
ppseudo_hdr->sh_str_id = 0;
ppseudo_hdr->control = 0;
ppseudo_hdr->rsvd1 = 0;
ppseudo_hdr->rsvd2 = 0;
ppseudo_hdr->qos_class = 0;
/* Insert slow queue sequence number */
ppseudo_hdr->seq_num = info->squeseqnum++;
/* Insert application id */
ppseudo_hdr->portsrc = 0;
/* Calculate new checksum */
ppseudo_hdr->checksum = *pmsg++;
for (i = 1; i < 7; i++) {
ppseudo_hdr->checksum ^= *pmsg++;
}
info->DSPInfoBlk[8] = 0x7200;
info->DSPInfoBlk[9] =
htons(info->DSPInfoBlklen);
ft1000_send_cmd (dev, (u16 *)info->DSPInfoBlk, (u16)(info->DSPInfoBlklen+4), 0);
}
break;
case GET_DRV_ERR_RPT_MSG:
DEBUG(1, "FT1000:drivermsg:Got GET_DRV_ERR_RPT_MSG\n");
/*
* copy driver error message to dsp
* allow any outstanding ioctl to finish
*/
mdelay(10);
tempword = ft1000_read_reg(dev, FT1000_REG_DOORBELL);
if (tempword & FT1000_DB_DPRAM_TX) {
mdelay(10);
tempword =
ft1000_read_reg(dev, FT1000_REG_DOORBELL);
if (tempword & FT1000_DB_DPRAM_TX) {
mdelay(10);
}
}
if ((tempword & FT1000_DB_DPRAM_TX) == 0) {
/*
* Put message into Slow Queue
* Form Pseudo header
*/
pmsg = (u16 *) & tempbuffer[0];
ppseudo_hdr = (struct pseudo_hdr *) pmsg;
ppseudo_hdr->length = htons(0x0012);
ppseudo_hdr->source = 0x10;
ppseudo_hdr->destination = 0x20;
ppseudo_hdr->portdest = 0;
ppseudo_hdr->portsrc = 0;
ppseudo_hdr->sh_str_id = 0;
ppseudo_hdr->control = 0;
ppseudo_hdr->rsvd1 = 0;
ppseudo_hdr->rsvd2 = 0;
ppseudo_hdr->qos_class = 0;
/* Insert slow queue sequence number */
ppseudo_hdr->seq_num = info->squeseqnum++;
/* Insert application id */
ppseudo_hdr->portsrc = 0;
/* Calculate new checksum */
ppseudo_hdr->checksum = *pmsg++;
for (i=1; i<7; i++) {
ppseudo_hdr->checksum ^= *pmsg++;
}
pmsg = (u16 *) & tempbuffer[16];
*pmsg++ = htons(RSP_DRV_ERR_RPT_MSG);
*pmsg++ = htons(0x000e);
*pmsg++ = htons(info->DSP_TIME[0]);
*pmsg++ = htons(info->DSP_TIME[1]);
*pmsg++ = htons(info->DSP_TIME[2]);
*pmsg++ = htons(info->DSP_TIME[3]);
convert.byte[0] = info->DspVer[0];
convert.byte[1] = info->DspVer[1];
*pmsg++ = convert.wrd;
convert.byte[0] = info->DspVer[2];
convert.byte[1] = info->DspVer[3];
*pmsg++ = convert.wrd;
*pmsg++ = htons(info->DrvErrNum);
ft1000_send_cmd (dev, (u16 *)&tempbuffer[0], (u16)(0x0012), 0);
info->DrvErrNum = 0;
}
break;
default:
break;
}
}
}
/*---------------------------------------------------------------------------
Function: ft1000_parse_dpram_msg
Description: This function will parse the message received from the DSP
via the DPRAM interface.
Input:
dev - device structure
Output:
status - FAILURE
SUCCESS
-------------------------------------------------------------------------*/
static int ft1000_parse_dpram_msg(struct net_device *dev)
{
struct ft1000_info *info = netdev_priv(dev);
u16 doorbell;
u16 portid;
u16 nxtph;
u16 total_len;
int i = 0;
int cnt;
unsigned long flags;
doorbell = ft1000_read_reg(dev, FT1000_REG_DOORBELL);
DEBUG(1, "Doorbell = 0x%x\n", doorbell);
if (doorbell & FT1000_ASIC_RESET_REQ) {
/* Copy DSP session record from info block */
spin_lock_irqsave(&info->dpram_lock, flags);
if (info->AsicID == ELECTRABUZZ_ID) {
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR,
FT1000_DPRAM_RX_BASE);
for (i = 0; i < MAX_DSP_SESS_REC; i++) {
ft1000_write_reg(dev, FT1000_REG_DPRAM_DATA,
info->DSPSess.Rec[i]);
}
} else {
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR,
FT1000_DPRAM_MAG_RX_BASE);
for (i = 0; i < MAX_DSP_SESS_REC / 2; i++) {
outl(info->DSPSess.MagRec[i],
dev->base_addr + FT1000_REG_MAG_DPDATA);
}
}
spin_unlock_irqrestore(&info->dpram_lock, flags);
/* clear ASIC RESET request */
ft1000_write_reg(dev, FT1000_REG_DOORBELL,
FT1000_ASIC_RESET_REQ);
DEBUG(1, "Got an ASIC RESET Request\n");
ft1000_write_reg(dev, FT1000_REG_DOORBELL,
FT1000_ASIC_RESET_DSP);
if (info->AsicID == MAGNEMITE_ID) {
/* Setting MAGNEMITE ASIC to big endian mode */
ft1000_write_reg(dev, FT1000_REG_SUP_CTRL,
HOST_INTF_BE);
}
}
if (doorbell & FT1000_DSP_ASIC_RESET) {
DEBUG(0,
"FT1000:ft1000_parse_dpram_msg: Got a dsp ASIC reset message\n");
ft1000_write_reg(dev, FT1000_REG_DOORBELL,
FT1000_DSP_ASIC_RESET);
udelay(200);
return SUCCESS;
}
if (doorbell & FT1000_DB_DPRAM_RX) {
DEBUG(1,
"FT1000:ft1000_parse_dpram_msg: Got a slow queue message\n");
nxtph = FT1000_DPRAM_RX_BASE + 2;
if (info->AsicID == ELECTRABUZZ_ID) {
total_len =
ft1000_read_dpram(dev, FT1000_DPRAM_RX_BASE);
} else {
total_len =
ntohs(ft1000_read_dpram_mag_16
(dev, FT1000_MAG_TOTAL_LEN,
FT1000_MAG_TOTAL_LEN_INDX));
}
DEBUG(1, "FT1000:ft1000_parse_dpram_msg:total length = %d\n",
total_len);
if ((total_len < MAX_CMD_SQSIZE) && (total_len > sizeof(struct pseudo_hdr))) {
total_len += nxtph;
cnt = 0;
/*
* ft1000_read_reg will return a value that needs to be byteswap
* in order to get DSP_QID_OFFSET.
*/
if (info->AsicID == ELECTRABUZZ_ID) {
portid =
(ft1000_read_dpram
(dev,
DSP_QID_OFFSET + FT1000_DPRAM_RX_BASE +
2) >> 8) & 0xff;
} else {
portid =
(ft1000_read_dpram_mag_16
(dev, FT1000_MAG_PORT_ID,
FT1000_MAG_PORT_ID_INDX) & 0xff);
}
DEBUG(1, "DSP_QID = 0x%x\n", portid);
if (portid == DRIVERID) {
/* We are assumming one driver message from the DSP at a time. */
ft1000_proc_drvmsg(dev);
}
}
ft1000_write_reg(dev, FT1000_REG_DOORBELL, FT1000_DB_DPRAM_RX);
}
if (doorbell & FT1000_DB_COND_RESET) {
/* Reset ASIC and DSP */
if (info->AsicID == ELECTRABUZZ_ID) {
info->DSP_TIME[0] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER0);
info->DSP_TIME[1] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER1);
info->DSP_TIME[2] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER2);
info->DSP_TIME[3] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER3);
} else {
info->DSP_TIME[0] =
ft1000_read_dpram_mag_16(dev, FT1000_MAG_DSP_TIMER0,
FT1000_MAG_DSP_TIMER0_INDX);
info->DSP_TIME[1] =
ft1000_read_dpram_mag_16(dev, FT1000_MAG_DSP_TIMER1,
FT1000_MAG_DSP_TIMER1_INDX);
info->DSP_TIME[2] =
ft1000_read_dpram_mag_16(dev, FT1000_MAG_DSP_TIMER2,
FT1000_MAG_DSP_TIMER2_INDX);
info->DSP_TIME[3] =
ft1000_read_dpram_mag_16(dev, FT1000_MAG_DSP_TIMER3,
FT1000_MAG_DSP_TIMER3_INDX);
}
info->DrvErrNum = DSP_CONDRESET_INFO;
DEBUG(1, "ft1000_hw:DSP conditional reset requested\n");
ft1000_reset_card(dev);
ft1000_write_reg(dev, FT1000_REG_DOORBELL,
FT1000_DB_COND_RESET);
}
/* let's clear any unexpected doorbells from DSP */
doorbell =
doorbell & ~(FT1000_DB_DPRAM_RX | FT1000_ASIC_RESET_REQ |
FT1000_DB_COND_RESET | 0xff00);
if (doorbell) {
DEBUG(1, "Clearing unexpected doorbell = 0x%x\n", doorbell);
ft1000_write_reg(dev, FT1000_REG_DOORBELL, doorbell);
}
return SUCCESS;
}
/*---------------------------------------------------------------------------
Function: ft1000_flush_fifo
Description: This function will flush one packet from the downlink
FIFO.
Input:
dev - device structure
drv_err - driver error causing the flush fifo
Output:
None.
-------------------------------------------------------------------------*/
static void ft1000_flush_fifo(struct net_device *dev, u16 DrvErrNum)
{
struct ft1000_info *info = netdev_priv(dev);
struct ft1000_pcmcia *pcmcia = info->priv;
u16 i;
u32 templong;
u16 tempword;
DEBUG(1, "ft1000:ft1000_hw:ft1000_flush_fifo called\n");
if (pcmcia->PktIntfErr > MAX_PH_ERR) {
if (info->AsicID == ELECTRABUZZ_ID) {
info->DSP_TIME[0] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER0);
info->DSP_TIME[1] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER1);
info->DSP_TIME[2] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER2);
info->DSP_TIME[3] =
ft1000_read_dpram(dev, FT1000_DSP_TIMER3);
} else {
info->DSP_TIME[0] =
ft1000_read_dpram_mag_16(dev, FT1000_MAG_DSP_TIMER0,
FT1000_MAG_DSP_TIMER0_INDX);
info->DSP_TIME[1] =
ft1000_read_dpram_mag_16(dev, FT1000_MAG_DSP_TIMER1,
FT1000_MAG_DSP_TIMER1_INDX);
info->DSP_TIME[2] =
ft1000_read_dpram_mag_16(dev, FT1000_MAG_DSP_TIMER2,
FT1000_MAG_DSP_TIMER2_INDX);
info->DSP_TIME[3] =
ft1000_read_dpram_mag_16(dev, FT1000_MAG_DSP_TIMER3,
FT1000_MAG_DSP_TIMER3_INDX);
}
info->DrvErrNum = DrvErrNum;
ft1000_reset_card(dev);
return;
} else {
/* Flush corrupted pkt from FIFO */
i = 0;
do {
if (info->AsicID == ELECTRABUZZ_ID) {
tempword =
ft1000_read_reg(dev, FT1000_REG_DFIFO);
tempword =
ft1000_read_reg(dev, FT1000_REG_DFIFO_STAT);
} else {
templong =
inl(dev->base_addr + FT1000_REG_MAG_DFR);
tempword =
inw(dev->base_addr + FT1000_REG_MAG_DFSR);
}
i++;
/*
* This should never happen unless the ASIC is broken.
* We must reset to recover.
*/
if ((i > 2048) || (tempword == 0)) {
if (info->AsicID == ELECTRABUZZ_ID) {
info->DSP_TIME[0] =
ft1000_read_dpram(dev,
FT1000_DSP_TIMER0);
info->DSP_TIME[1] =
ft1000_read_dpram(dev,
FT1000_DSP_TIMER1);
info->DSP_TIME[2] =
ft1000_read_dpram(dev,
FT1000_DSP_TIMER2);
info->DSP_TIME[3] =
ft1000_read_dpram(dev,
FT1000_DSP_TIMER3);
} else {
info->DSP_TIME[0] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER0,
FT1000_MAG_DSP_TIMER0_INDX);
info->DSP_TIME[1] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER1,
FT1000_MAG_DSP_TIMER1_INDX);
info->DSP_TIME[2] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER2,
FT1000_MAG_DSP_TIMER2_INDX);
info->DSP_TIME[3] =
ft1000_read_dpram_mag_16(dev,
FT1000_MAG_DSP_TIMER3,
FT1000_MAG_DSP_TIMER3_INDX);
}
if (tempword == 0) {
/*
* Let's check if ASIC reads are still ok by reading the Mask register
* which is never zero at this point of the code.
*/
tempword =
inw(dev->base_addr +
FT1000_REG_SUP_IMASK);
if (tempword == 0) {
/* This indicates that we can not communicate with the ASIC */
info->DrvErrNum =
FIFO_FLUSH_BADCNT;
} else {
/* Let's assume that we really flush the FIFO */
pcmcia->PktIntfErr++;
return;
}
} else {
info->DrvErrNum = FIFO_FLUSH_MAXLIMIT;
}
return;
}
tempword = inw(dev->base_addr + FT1000_REG_SUP_STAT);
} while ((tempword & 0x03) != 0x03);
if (info->AsicID == ELECTRABUZZ_ID) {
i++;
DEBUG(0, "Flushing FIFO complete = %x\n", tempword);
/* Flush last word in FIFO. */
tempword = ft1000_read_reg(dev, FT1000_REG_DFIFO);
/* Update FIFO counter for DSP */
i = i * 2;
DEBUG(0, "Flush Data byte count to dsp = %d\n", i);
info->fifo_cnt += i;
ft1000_write_dpram(dev, FT1000_FIFO_LEN,
info->fifo_cnt);
} else {
DEBUG(0, "Flushing FIFO complete = %x\n", tempword);
/* Flush last word in FIFO */
templong = inl(dev->base_addr + FT1000_REG_MAG_DFR);
tempword = inw(dev->base_addr + FT1000_REG_SUP_STAT);
DEBUG(0, "FT1000_REG_SUP_STAT = 0x%x\n", tempword);
tempword = inw(dev->base_addr + FT1000_REG_MAG_DFSR);
DEBUG(0, "FT1000_REG_MAG_DFSR = 0x%x\n", tempword);
}
if (DrvErrNum) {
pcmcia->PktIntfErr++;
}
}
}
/*---------------------------------------------------------------------------
Function: ft1000_copy_up_pkt
Description: This function will pull Flarion packets out of the Downlink
FIFO and convert it to an ethernet packet. The ethernet packet will
then be deliver to the TCP/IP stack.
Input:
dev - device structure
Output:
status - FAILURE
SUCCESS
-------------------------------------------------------------------------*/
static int ft1000_copy_up_pkt(struct net_device *dev)
{
u16 tempword;
struct ft1000_info *info = netdev_priv(dev);
u16 len;
struct sk_buff *skb;
u16 i;
u8 *pbuffer = NULL;
u8 *ptemp = NULL;
u16 chksum;
u32 *ptemplong;
u32 templong;
DEBUG(1, "ft1000_copy_up_pkt\n");
/* Read length */
if (info->AsicID == ELECTRABUZZ_ID) {
tempword = ft1000_read_reg(dev, FT1000_REG_DFIFO);
len = tempword;
} else {
tempword = ft1000_read_reg(dev, FT1000_REG_MAG_DFRL);
len = ntohs(tempword);
}
chksum = tempword;
DEBUG(1, "Number of Bytes in FIFO = %d\n", len);
if (len > ENET_MAX_SIZE) {
DEBUG(0, "size of ethernet packet invalid\n");
if (info->AsicID == MAGNEMITE_ID) {
/* Read High word to complete 32 bit access */
tempword = ft1000_read_reg(dev, FT1000_REG_MAG_DFRH);
}
ft1000_flush_fifo(dev, DSP_PKTLEN_INFO);
info->stats.rx_errors++;
return FAILURE;
}
skb = dev_alloc_skb(len + 12 + 2);
if (skb == NULL) {
DEBUG(0, "No Network buffers available\n");
/* Read High word to complete 32 bit access */
if (info->AsicID == MAGNEMITE_ID) {
tempword = ft1000_read_reg(dev, FT1000_REG_MAG_DFRH);
}
ft1000_flush_fifo(dev, 0);
info->stats.rx_errors++;
return FAILURE;
}
pbuffer = (u8 *) skb_put(skb, len + 12);
/* Pseudo header */
if (info->AsicID == ELECTRABUZZ_ID) {
for (i = 1; i < 7; i++) {
tempword = ft1000_read_reg(dev, FT1000_REG_DFIFO);
chksum ^= tempword;
}
/* read checksum value */
tempword = ft1000_read_reg(dev, FT1000_REG_DFIFO);
} else {
tempword = ft1000_read_reg(dev, FT1000_REG_MAG_DFRH);
DEBUG(1, "Pseudo = 0x%x\n", tempword);
chksum ^= tempword;
tempword = ft1000_read_reg(dev, FT1000_REG_MAG_DFRL);
DEBUG(1, "Pseudo = 0x%x\n", tempword);
chksum ^= tempword;
tempword = ft1000_read_reg(dev, FT1000_REG_MAG_DFRH);
DEBUG(1, "Pseudo = 0x%x\n", tempword);
chksum ^= tempword;
tempword = ft1000_read_reg(dev, FT1000_REG_MAG_DFRL);
DEBUG(1, "Pseudo = 0x%x\n", tempword);
chksum ^= tempword;
tempword = ft1000_read_reg(dev, FT1000_REG_MAG_DFRH);
DEBUG(1, "Pseudo = 0x%x\n", tempword);
chksum ^= tempword;
tempword = ft1000_read_reg(dev, FT1000_REG_MAG_DFRL);
DEBUG(1, "Pseudo = 0x%x\n", tempword);
chksum ^= tempword;
/* read checksum value */
tempword = ft1000_read_reg(dev, FT1000_REG_MAG_DFRH);
DEBUG(1, "Pseudo = 0x%x\n", tempword);
}
if (chksum != tempword) {
DEBUG(0, "Packet checksum mismatch 0x%x 0x%x\n", chksum,
tempword);
ft1000_flush_fifo(dev, DSP_PKTPHCKSUM_INFO);
info->stats.rx_errors++;
kfree_skb(skb);
return FAILURE;
}
/* subtract the number of bytes read already */
ptemp = pbuffer;
/* fake MAC address */
*pbuffer++ = dev->dev_addr[0];
*pbuffer++ = dev->dev_addr[1];
*pbuffer++ = dev->dev_addr[2];
*pbuffer++ = dev->dev_addr[3];
*pbuffer++ = dev->dev_addr[4];
*pbuffer++ = dev->dev_addr[5];
*pbuffer++ = 0x00;
*pbuffer++ = 0x07;
*pbuffer++ = 0x35;
*pbuffer++ = 0xff;
*pbuffer++ = 0xff;
*pbuffer++ = 0xfe;
if (info->AsicID == ELECTRABUZZ_ID) {
for (i = 0; i < len / 2; i++) {
tempword = ft1000_read_reg(dev, FT1000_REG_DFIFO);
*pbuffer++ = (u8) (tempword >> 8);
*pbuffer++ = (u8) tempword;
if (ft1000_chkcard(dev) == false) {
kfree_skb(skb);
return FAILURE;
}
}
/* Need to read one more word if odd byte */
if (len & 0x0001) {
tempword = ft1000_read_reg(dev, FT1000_REG_DFIFO);
*pbuffer++ = (u8) (tempword >> 8);
}
} else {
ptemplong = (u32 *) pbuffer;
for (i = 0; i < len / 4; i++) {
templong = inl(dev->base_addr + FT1000_REG_MAG_DFR);
DEBUG(1, "Data = 0x%8x\n", templong);
*ptemplong++ = templong;
}
/* Need to read one more word if odd align. */
if (len & 0x0003) {
templong = inl(dev->base_addr + FT1000_REG_MAG_DFR);
DEBUG(1, "Data = 0x%8x\n", templong);
*ptemplong++ = templong;
}
}
DEBUG(1, "Data passed to Protocol layer:\n");
for (i = 0; i < len + 12; i++) {
DEBUG(1, "Protocol Data: 0x%x\n ", *ptemp++);
}
skb->dev = dev;
skb->protocol = eth_type_trans(skb, dev);
skb->ip_summed = CHECKSUM_UNNECESSARY;
netif_rx(skb);
info->stats.rx_packets++;
/* Add on 12 bytes for MAC address which was removed */
info->stats.rx_bytes += (len + 12);
if (info->AsicID == ELECTRABUZZ_ID) {
/* track how many bytes have been read from FIFO - round up to 16 bit word */
tempword = len + 16;
if (tempword & 0x01)
tempword++;
info->fifo_cnt += tempword;
ft1000_write_reg(dev, FT1000_REG_DPRAM_ADDR, FT1000_FIFO_LEN);
ft1000_write_reg(dev, FT1000_REG_DPRAM_DATA, info->fifo_cnt);
}
return SUCCESS;
}
/*---------------------------------------------------------------------------
Function: ft1000_copy_down_pkt
Description: This function will take an ethernet packet and convert it to
a Flarion packet prior to sending it to the ASIC Downlink
FIFO.
Input:
dev - device structure
packet - address of ethernet packet
len - length of IP packet
Output:
status - FAILURE
SUCCESS
-------------------------------------------------------------------------*/
static int ft1000_copy_down_pkt(struct net_device *dev, u16 * packet, u16 len)
{
struct ft1000_info *info = netdev_priv(dev);
struct ft1000_pcmcia *pcmcia = info->priv;
union {
struct pseudo_hdr blk;
u16 buff[sizeof(struct pseudo_hdr) >> 1];
u8 buffc[sizeof(struct pseudo_hdr)];
} pseudo;
int i;
u32 *plong;
DEBUG(1, "ft1000_hw: copy_down_pkt()\n");
/* Check if there is room on the FIFO */
if (len > ft1000_read_fifo_len(dev)) {
udelay(10);
if (len > ft1000_read_fifo_len(dev)) {
udelay(20);
}
if (len > ft1000_read_fifo_len(dev)) {
udelay(20);
}
if (len > ft1000_read_fifo_len(dev)) {
udelay(20);
}
if (len > ft1000_read_fifo_len(dev)) {
udelay(20);
}
if (len > ft1000_read_fifo_len(dev)) {
udelay(20);
}
if (len > ft1000_read_fifo_len(dev)) {
DEBUG(1,
"ft1000_hw:ft1000_copy_down_pkt:Transmit FIFO is fulli - pkt drop\n");
info->stats.tx_errors++;
return SUCCESS;
}
}
/* Create pseudo header and send pseudo/ip to hardware */
if (info->AsicID == ELECTRABUZZ_ID) {
pseudo.blk.length = len;
} else {
pseudo.blk.length = ntohs(len);
}
pseudo.blk.source = DSPID; /* Need to swap to get in correct order */
pseudo.blk.destination = HOSTID;
pseudo.blk.portdest = NETWORKID; /* Need to swap to get in correct order */
pseudo.blk.portsrc = DSPAIRID;
pseudo.blk.sh_str_id = 0;
pseudo.blk.control = 0;
pseudo.blk.rsvd1 = 0;
pseudo.blk.seq_num = 0;
pseudo.blk.rsvd2 = pcmcia->packetseqnum++;
pseudo.blk.qos_class = 0;
/* Calculate pseudo header checksum */
pseudo.blk.checksum = pseudo.buff[0];
for (i = 1; i < 7; i++) {
pseudo.blk.checksum ^= pseudo.buff[i];
}
/* Production Mode */
if (info->AsicID == ELECTRABUZZ_ID) {
/* copy first word to UFIFO_BEG reg */
ft1000_write_reg(dev, FT1000_REG_UFIFO_BEG, pseudo.buff[0]);
DEBUG(1, "ft1000_hw:ft1000_copy_down_pkt:data 0 BEG = 0x%04x\n",
pseudo.buff[0]);
/* copy subsequent words to UFIFO_MID reg */
ft1000_write_reg(dev, FT1000_REG_UFIFO_MID, pseudo.buff[1]);
DEBUG(1, "ft1000_hw:ft1000_copy_down_pkt:data 1 MID = 0x%04x\n",
pseudo.buff[1]);
ft1000_write_reg(dev, FT1000_REG_UFIFO_MID, pseudo.buff[2]);
DEBUG(1, "ft1000_hw:ft1000_copy_down_pkt:data 2 MID = 0x%04x\n",
pseudo.buff[2]);
ft1000_write_reg(dev, FT1000_REG_UFIFO_MID, pseudo.buff[3]);
DEBUG(1, "ft1000_hw:ft1000_copy_down_pkt:data 3 MID = 0x%04x\n",
pseudo.buff[3]);
ft1000_write_reg(dev, FT1000_REG_UFIFO_MID, pseudo.buff[4]);
DEBUG(1, "ft1000_hw:ft1000_copy_down_pkt:data 4 MID = 0x%04x\n",
pseudo.buff[4]);
ft1000_write_reg(dev, FT1000_REG_UFIFO_MID, pseudo.buff[5]);
DEBUG(1, "ft1000_hw:ft1000_copy_down_pkt:data 5 MID = 0x%04x\n",
pseudo.buff[5]);
ft1000_write_reg(dev, FT1000_REG_UFIFO_MID, pseudo.buff[6]);
DEBUG(1, "ft1000_hw:ft1000_copy_down_pkt:data 6 MID = 0x%04x\n",
pseudo.buff[6]);
ft1000_write_reg(dev, FT1000_REG_UFIFO_MID, pseudo.buff[7]);
DEBUG(1, "ft1000_hw:ft1000_copy_down_pkt:data 7 MID = 0x%04x\n",
pseudo.buff[7]);
/* Write PPP type + IP Packet into Downlink FIFO */
for (i = 0; i < (len >> 1) - 1; i++) {
ft1000_write_reg(dev, FT1000_REG_UFIFO_MID,
htons(*packet));
DEBUG(1,
"ft1000_hw:ft1000_copy_down_pkt:data %d MID = 0x%04x\n",
i + 8, htons(*packet));
packet++;
}
/* Check for odd byte */
if (len & 0x0001) {
ft1000_write_reg(dev, FT1000_REG_UFIFO_MID,
htons(*packet));
DEBUG(1,
"ft1000_hw:ft1000_copy_down_pkt:data MID = 0x%04x\n",
htons(*packet));
packet++;
ft1000_write_reg(dev, FT1000_REG_UFIFO_END,
htons(*packet));
DEBUG(1,
"ft1000_hw:ft1000_copy_down_pkt:data %d MID = 0x%04x\n",
i + 8, htons(*packet));
} else {
ft1000_write_reg(dev, FT1000_REG_UFIFO_END,
htons(*packet));
DEBUG(1,
"ft1000_hw:ft1000_copy_down_pkt:data %d MID = 0x%04x\n",
i + 8, htons(*packet));
}
} else {
outl(*(u32 *) & pseudo.buff[0],
dev->base_addr + FT1000_REG_MAG_UFDR);
DEBUG(1, "ft1000_copy_down_pkt: Pseudo = 0x%8x\n",
*(u32 *) & pseudo.buff[0]);
outl(*(u32 *) & pseudo.buff[2],
dev->base_addr + FT1000_REG_MAG_UFDR);
DEBUG(1, "ft1000_copy_down_pkt: Pseudo = 0x%8x\n",
*(u32 *) & pseudo.buff[2]);
outl(*(u32 *) & pseudo.buff[4],
dev->base_addr + FT1000_REG_MAG_UFDR);
DEBUG(1, "ft1000_copy_down_pkt: Pseudo = 0x%8x\n",
*(u32 *) & pseudo.buff[4]);
outl(*(u32 *) & pseudo.buff[6],
dev->base_addr + FT1000_REG_MAG_UFDR);
DEBUG(1, "ft1000_copy_down_pkt: Pseudo = 0x%8x\n",
*(u32 *) & pseudo.buff[6]);
plong = (u32 *) packet;
/* Write PPP type + IP Packet into Downlink FIFO */
for (i = 0; i < (len >> 2); i++) {
outl(*plong++, dev->base_addr + FT1000_REG_MAG_UFDR);
}
/* Check for odd alignment */
if (len & 0x0003) {
DEBUG(1,
"ft1000_hw:ft1000_copy_down_pkt:data = 0x%8x\n",
*plong);
outl(*plong++, dev->base_addr + FT1000_REG_MAG_UFDR);
}
outl(1, dev->base_addr + FT1000_REG_MAG_UFER);
}
info->stats.tx_packets++;
/* Add 14 bytes for MAC address plus ethernet type */
info->stats.tx_bytes += (len + 14);
return SUCCESS;
}
static struct net_device_stats *ft1000_stats(struct net_device *dev)
{
struct ft1000_info *info = netdev_priv(dev);
return &info->stats;
}
static int ft1000_open(struct net_device *dev)
{
DEBUG(0, "ft1000_hw: ft1000_open is called\n");
ft1000_reset_card(dev);
DEBUG(0, "ft1000_hw: ft1000_open is ended\n");
/* schedule ft1000_hbchk to perform periodic heartbeat checks on DSP and ASIC */
init_timer(&poll_timer);
poll_timer.expires = jiffies + (2 * HZ);
poll_timer.data = (u_long) dev;
add_timer(&poll_timer);
DEBUG(0, "ft1000_hw: ft1000_open is ended2\n");
return 0;
}
static int ft1000_close(struct net_device *dev)
{
struct ft1000_info *info = netdev_priv(dev);
DEBUG(0, "ft1000_hw: ft1000_close()\n");
info->CardReady = 0;
del_timer(&poll_timer);
if (ft1000_card_present == 1) {
DEBUG(0, "Media is down\n");
netif_stop_queue(dev);
ft1000_disable_interrupts(dev);
ft1000_write_reg(dev, FT1000_REG_RESET, DSP_RESET_BIT);
/* reset ASIC */
ft1000_reset_asic(dev);
}
return 0;
}
static int ft1000_start_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct ft1000_info *info = netdev_priv(dev);
u8 *pdata;
DEBUG(1, "ft1000_hw: ft1000_start_xmit()\n");
if (skb == NULL) {
DEBUG(1, "ft1000_hw: ft1000_start_xmit:skb == NULL!!!\n");
return 0;
}
DEBUG(1, "ft1000_hw: ft1000_start_xmit:length of packet = %d\n",
skb->len);
pdata = (u8 *) skb->data;
if (info->mediastate == 0) {
/* Drop packet is mediastate is down */
DEBUG(1, "ft1000_hw:ft1000_copy_down_pkt:mediastate is down\n");
return SUCCESS;
}
if ((skb->len < ENET_HEADER_SIZE) || (skb->len > ENET_MAX_SIZE)) {
/* Drop packet which has invalid size */
DEBUG(1,
"ft1000_hw:ft1000_copy_down_pkt:invalid ethernet length\n");
return SUCCESS;
}
ft1000_copy_down_pkt(dev, (u16 *) (pdata + ENET_HEADER_SIZE - 2),
skb->len - ENET_HEADER_SIZE + 2);
dev_kfree_skb(skb);
return 0;
}
static irqreturn_t ft1000_interrupt(int irq, void *dev_id)
{
struct net_device *dev = (struct net_device *)dev_id;
struct ft1000_info *info = netdev_priv(dev);
u16 tempword;
u16 inttype;
int cnt;
DEBUG(1, "ft1000_hw: ft1000_interrupt()\n");
if (info->CardReady == 0) {
ft1000_disable_interrupts(dev);
return IRQ_HANDLED;
}
if (ft1000_chkcard(dev) == false) {
ft1000_disable_interrupts(dev);
return IRQ_HANDLED;
}
ft1000_disable_interrupts(dev);
/* Read interrupt type */
inttype = ft1000_read_reg(dev, FT1000_REG_SUP_ISR);
/* Make sure we process all interrupt before leaving the ISR due to the edge trigger interrupt type */
while (inttype) {
if (inttype & ISR_DOORBELL_PEND)
ft1000_parse_dpram_msg(dev);
if (inttype & ISR_RCV) {
DEBUG(1, "Data in FIFO\n");
cnt = 0;
do {
/* Check if we have packets in the Downlink FIFO */
if (info->AsicID == ELECTRABUZZ_ID) {
tempword =
ft1000_read_reg(dev,
FT1000_REG_DFIFO_STAT);
} else {
tempword =
ft1000_read_reg(dev,
FT1000_REG_MAG_DFSR);
}
if (tempword & 0x1f) {
ft1000_copy_up_pkt(dev);
} else {
break;
}
cnt++;
} while (cnt < MAX_RCV_LOOP);
}
/* clear interrupts */
tempword = ft1000_read_reg(dev, FT1000_REG_SUP_ISR);
DEBUG(1, "ft1000_hw: interrupt status register = 0x%x\n", tempword);
ft1000_write_reg(dev, FT1000_REG_SUP_ISR, tempword);
/* Read interrupt type */
inttype = ft1000_read_reg (dev, FT1000_REG_SUP_ISR);
DEBUG(1, "ft1000_hw: interrupt status register after clear = 0x%x\n", inttype);
}
ft1000_enable_interrupts(dev);
return IRQ_HANDLED;
}
void stop_ft1000_card(struct net_device *dev)
{
struct ft1000_info *info = netdev_priv(dev);
struct prov_record *ptr;
/* int cnt; */
DEBUG(0, "ft1000_hw: stop_ft1000_card()\n");
info->CardReady = 0;
ft1000_card_present = 0;
netif_stop_queue(dev);
ft1000_disable_interrupts(dev);
/* Make sure we free any memory reserve for provisioning */
while (list_empty(&info->prov_list) == 0) {
ptr = list_entry(info->prov_list.next, struct prov_record, list);
list_del(&ptr->list);
kfree(ptr->pprov_data);
kfree(ptr);
}
kfree(info->priv);
if (info->registered) {
unregister_netdev(dev);
info->registered = 0;
}
free_irq(dev->irq, dev);
release_region(dev->base_addr, 256);
release_firmware(fw_entry);
flarion_ft1000_cnt--;
}
static void ft1000_get_drvinfo(struct net_device *dev,
struct ethtool_drvinfo *info)
{
struct ft1000_info *ft_info;
ft_info = netdev_priv(dev);
strlcpy(info->driver, "ft1000", sizeof(info->driver));
snprintf(info->bus_info, sizeof(info->bus_info), "PCMCIA 0x%lx",
dev->base_addr);
snprintf(info->fw_version, sizeof(info->fw_version), "%d.%d.%d.%d",
ft_info->DspVer[0], ft_info->DspVer[1], ft_info->DspVer[2],
ft_info->DspVer[3]);
}
static u32 ft1000_get_link(struct net_device *dev)
{
struct ft1000_info *info;
info = netdev_priv(dev);
return info->mediastate;
}
static const struct ethtool_ops ops = {
.get_drvinfo = ft1000_get_drvinfo,
.get_link = ft1000_get_link
};
struct net_device *init_ft1000_card(struct pcmcia_device *link,
void *ft1000_reset)
{
struct ft1000_info *info;
struct ft1000_pcmcia *pcmcia;
struct net_device *dev;
static const struct net_device_ops ft1000ops = /* Slavius 21.10.2009 due to kernel changes */
{
.ndo_open = &ft1000_open,
.ndo_stop = &ft1000_close,
.ndo_start_xmit = &ft1000_start_xmit,
.ndo_get_stats = &ft1000_stats,
};
DEBUG(1, "ft1000_hw: init_ft1000_card()\n");
DEBUG(1, "ft1000_hw: irq = %d\n", link->irq);
DEBUG(1, "ft1000_hw: port = 0x%04x\n", link->resource[0]->start);
flarion_ft1000_cnt++;
if (flarion_ft1000_cnt > 1) {
flarion_ft1000_cnt--;
printk(KERN_INFO
"ft1000: This driver can not support more than one instance\n");
return NULL;
}
dev = alloc_etherdev(sizeof(struct ft1000_info));
if (!dev) {
printk(KERN_ERR "ft1000: failed to allocate etherdev\n");
return NULL;
}
SET_NETDEV_DEV(dev, &link->dev);
info = netdev_priv(dev);
memset(info, 0, sizeof(struct ft1000_info));
DEBUG(1, "address of dev = 0x%8x\n", (u32) dev);
DEBUG(1, "address of dev info = 0x%8x\n", (u32) info);
DEBUG(0, "device name = %s\n", dev->name);
memset(&info->stats, 0, sizeof(struct net_device_stats));
info->priv = kzalloc(sizeof(struct ft1000_pcmcia), GFP_KERNEL);
pcmcia = info->priv;
pcmcia->link = link;
spin_lock_init(&info->dpram_lock);
info->DrvErrNum = 0;
info->registered = 1;
info->ft1000_reset = ft1000_reset;
info->mediastate = 0;
info->fifo_cnt = 0;
info->CardReady = 0;
info->DSP_TIME[0] = 0;
info->DSP_TIME[1] = 0;
info->DSP_TIME[2] = 0;
info->DSP_TIME[3] = 0;
flarion_ft1000_cnt = 0;
INIT_LIST_HEAD(&info->prov_list);
info->squeseqnum = 0;
/* dev->hard_start_xmit = &ft1000_start_xmit; */
/* dev->get_stats = &ft1000_stats; */
/* dev->open = &ft1000_open; */
/* dev->stop = &ft1000_close; */
dev->netdev_ops = &ft1000ops; /* Slavius 21.10.2009 due to kernel changes */
DEBUG(0, "device name = %s\n", dev->name);
dev->irq = link->irq;
dev->base_addr = link->resource[0]->start;
if (pcmcia_get_mac_from_cis(link, dev)) {
printk(KERN_ERR "ft1000: Could not read mac address\n");
goto err_dev;
}
if (request_irq(dev->irq, ft1000_interrupt, IRQF_SHARED, dev->name, dev)) {
printk(KERN_ERR "ft1000: Could not request_irq\n");
goto err_dev;
}
if (request_region(dev->base_addr, 256, dev->name) == NULL) {
printk(KERN_ERR "ft1000: Could not request_region\n");
goto err_irq;
}
if (register_netdev(dev) != 0) {
DEBUG(0, "ft1000: Could not register netdev");
goto err_reg;
}
info->AsicID = ft1000_read_reg(dev, FT1000_REG_ASIC_ID);
if (info->AsicID == ELECTRABUZZ_ID) {
DEBUG(0, "ft1000_hw: ELECTRABUZZ ASIC\n");
if (request_firmware(&fw_entry, "ft1000.img", &link->dev) != 0)
goto err_unreg;
} else {
DEBUG(0, "ft1000_hw: MAGNEMITE ASIC\n");
if (request_firmware(&fw_entry, "ft2000.img", &link->dev) != 0)
goto err_unreg;
}
ft1000_enable_interrupts(dev);
ft1000_card_present = 1;
dev->ethtool_ops = &ops;
printk(KERN_INFO "ft1000: %s: addr 0x%04lx irq %d, MAC addr %pM\n",
dev->name, dev->base_addr, dev->irq, dev->dev_addr);
return dev;
err_unreg:
unregister_netdev(dev);
err_reg:
release_region(dev->base_addr, 256);
err_irq:
free_irq(dev->irq, dev);
err_dev:
free_netdev(dev);
return NULL;
}
|
Brainiarc7/linux-3.18-parrot
|
drivers/staging/ft1000/ft1000-pcmcia/ft1000_hw.c
|
C
|
gpl-2.0
| 66,331
|
#ifndef VM_EVENT_ITEM_H_INCLUDED
#define VM_EVENT_ITEM_H_INCLUDED
#ifdef CONFIG_ZONE_DMA
#define DMA_ZONE(xx) xx##_DMA,
#else
#define DMA_ZONE(xx)
#endif
#ifdef CONFIG_ZONE_DMA32
#define DMA32_ZONE(xx) xx##_DMA32,
#else
#define DMA32_ZONE(xx)
#endif
#ifdef CONFIG_HIGHMEM
#define HIGHMEM_ZONE(xx) , xx##_HIGH
#else
#define HIGHMEM_ZONE(xx)
#endif
#define FOR_ALL_ZONES(xx) DMA_ZONE(xx) DMA32_ZONE(xx) xx##_NORMAL HIGHMEM_ZONE(xx) , xx##_MOVABLE
enum vm_event_item { PGPGIN, PGPGOUT, PSWPIN, PSWPOUT,
FOR_ALL_ZONES(PGALLOC),
PGFREE, PGACTIVATE, PGDEACTIVATE,
PGFAULT, PGMAJFAULT,
FOR_ALL_ZONES(PGREFILL),
FOR_ALL_ZONES(PGSTEAL_KSWAPD),
FOR_ALL_ZONES(PGSTEAL_DIRECT),
FOR_ALL_ZONES(PGSCAN_KSWAPD),
FOR_ALL_ZONES(PGSCAN_DIRECT),
PGSCAN_DIRECT_THROTTLE,
#ifdef CONFIG_NUMA
PGSCAN_ZONE_RECLAIM_FAILED,
#endif
PGINODESTEAL, SLABS_SCANNED, KSWAPD_INODESTEAL,
KSWAPD_LOW_WMARK_HIT_QUICKLY, KSWAPD_HIGH_WMARK_HIT_QUICKLY,
PAGEOUTRUN, ALLOCSTALL, SLOWPATH_ENTERED, PGROTATED,
#ifdef CONFIG_NUMA_BALANCING
NUMA_PTE_UPDATES,
NUMA_HINT_FAULTS,
NUMA_HINT_FAULTS_LOCAL,
NUMA_PAGE_MIGRATE,
#endif
#ifdef CONFIG_MIGRATION
PGMIGRATE_SUCCESS, PGMIGRATE_FAIL,
#endif
#ifdef CONFIG_COMPACTION
COMPACTMIGRATE_SCANNED, COMPACTFREE_SCANNED,
COMPACTISOLATED,
COMPACTSTALL, COMPACTFAIL, COMPACTSUCCESS,
#endif
#ifdef CONFIG_HUGETLB_PAGE
HTLB_BUDDY_PGALLOC, HTLB_BUDDY_PGALLOC_FAIL,
#endif
UNEVICTABLE_PGCULLED, /* culled to noreclaim list */
UNEVICTABLE_PGSCANNED, /* scanned for reclaimability */
UNEVICTABLE_PGRESCUED, /* rescued from noreclaim list */
UNEVICTABLE_PGMLOCKED,
UNEVICTABLE_PGMUNLOCKED,
UNEVICTABLE_PGCLEARED, /* on COW, page truncate */
UNEVICTABLE_PGSTRANDED, /* unable to isolate on unlock */
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
THP_FAULT_ALLOC,
THP_FAULT_FALLBACK,
THP_COLLAPSE_ALLOC,
THP_COLLAPSE_ALLOC_FAILED,
THP_SPLIT,
THP_ZERO_PAGE_ALLOC,
THP_ZERO_PAGE_ALLOC_FAILED,
#endif
NR_VM_EVENT_ITEMS
};
#endif /* VM_EVENT_ITEM_H_INCLUDED */
|
blakha/OS_TEST
|
include/linux/vm_event_item.h
|
C
|
gpl-2.0
| 2,012
|
/*
* Copyright (c) 1998-2010 Caucho Technology -- all rights reserved
* Copyright (c) 2011-2012 Clever Cloud SAS -- all rights reserved
*
* This file is part of Bianca(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Bianca Open Source 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.
*
* Bianca Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Bianca Open Source; if not, write to the
*
* Free SoftwareFoundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.clevercloud.relaxng.program;
import com.clevercloud.relaxng.RelaxException;
import com.clevercloud.util.CharBuffer;
import com.clevercloud.util.L10N;
import com.clevercloud.xml.QName;
import java.util.HashSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.logging.Logger;
/**
* Generates programs from patterns.
*/
abstract public class Item {
protected final static L10N L = new L10N(Item.class);
protected final static Logger log
= Logger.getLogger(Item.class.getName());
private static final Iterator<Item> EMPTY_ITEM_ITERATOR;
/**
* Adds to the first set the set of element names possible.
*/
public void firstSet(HashSet<QName> set) {
}
/**
* Adds to the first set the set of element names required.
*/
public void requiredFirstSet(HashSet<QName> set) {
if (!allowEmpty())
firstSet(set);
}
/**
* Returns true if the item can match empty.
*/
public boolean allowEmpty() {
return false;
}
/**
* Return all possible child items
*/
public Iterator<Item> getItemsIterator() {
return emptyItemIterator();
}
protected Iterator<Item> emptyItemIterator() {
return EMPTY_ITEM_ITERATOR;
}
protected Iterator<Item> itemIterator(final Item item) {
if (item == null)
return emptyItemIterator();
return new Iterator<Item>() {
private boolean _done;
public boolean hasNext() {
return !_done;
}
public Item next() {
if (!hasNext())
throw new NoSuchElementException();
_done = true;
return item;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
/**
* Returns the next item when an element of the given name is returned
*
* @param name the name of the element
* @return the program for handling the element
*/
public Item startElement(QName name)
throws RelaxException {
return null;
}
/**
* Returns true if the element is allowed somewhere in the item.
* allowsElement is used for error messages to give more information
* in cases of order dependency.
*
* @param name the name of the element
* @return true if the element is allowed somewhere
*/
public boolean allowsElement(QName name) {
return false;
}
/**
* Adds to the first set, the set of attribute names possible.
*/
public void attributeSet(HashSet<QName> set) {
}
/**
* Sets an attribute.
*
* @param name the name of the attribute
* @param value the value of the attribute
* @return the program for handling the element
*/
public boolean allowAttribute(QName name, String value)
throws RelaxException {
return false;
}
/**
* Sets an attribute.
*
* @param name the name of the attribute
* @param value the value of the attribute
* @return the program for handling the element
*/
public Item setAttribute(QName name, String value)
throws RelaxException {
return this;
}
/**
* Returns true if the item can match empty.
*/
public Item attributeEnd() {
return this;
}
/**
* Adds text.
*/
public Item text(CharSequence text)
throws RelaxException {
return null;
}
/**
* Returns the next item when the element closes
*/
public Item endElement()
throws RelaxException {
if (allowEmpty())
return EmptyItem.create();
else
return null;
}
/**
* Interleaves a continuation.
*/
public Item interleaveContinuation(Item cont) {
throw new IllegalStateException(String.valueOf(getClass().getName()));
}
/**
* Interleaves a continuation.
*/
public Item inElementContinuation(Item cont) {
throw new IllegalStateException(String.valueOf(getClass().getName()));
}
/**
* Appends a group to a continuation.
*/
public Item groupContinuation(Item cont) {
throw new IllegalStateException(String.valueOf(getClass().getName()));
}
/**
* Returns the pretty printed syntax.
*/
public String toSyntaxDescription(int depth) {
return toString();
}
/**
* Returns true for an element with simple syntax.
*/
protected boolean isSimpleSyntax() {
return false;
}
/**
* Adds a syntax newline.
*/
protected void addSyntaxNewline(CharBuffer cb, int depth) {
cb.append('\n');
for (int i = 0; i < depth; i++)
cb.append(' ');
}
/**
* Throws an error.
*/
protected RelaxException error(String msg) {
return new RelaxException(msg);
}
static {
EMPTY_ITEM_ITERATOR =
new Iterator<Item>() {
public boolean hasNext() {
return false;
}
public Item next() {
throw new NoSuchElementException();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
|
CleverCloud/Bianca
|
bianca/src/main/java/com/clevercloud/relaxng/program/Item.java
|
Java
|
gpl-2.0
| 6,298
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2007 Zuza Software Foundation
#
# This file is part of translate.
#
# translate 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.
#
# translate is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
"""This module provides functionality to work with zip files."""
# Perhaps all methods should work with a wildcard to limit searches in some
# way (examples: *.po, base.xlf, pootle-terminology.tbx)
#TODO: consider also providing directories as we currently provide files
#TODO: refactor with existing zip code (xpi.py, etc.)
from os import path
from zipfile import ZipFile
from translate.storage import factory
from translate.storage import directory
from translate.misc import wStringIO
class ZIPFile(directory.Directory):
"""This class represents a ZIP file like a directory."""
def __init__(self, filename=None):
self.filename = filename
self.filedata = []
def unit_iter(self):
"""Iterator over all the units in all the files in this zip file."""
for dirname, filename in self.file_iter():
strfile = wStringIO.StringIO(self.archive.read(path.join(dirname, filename)))
strfile.filename = filename
store = factory.getobject(strfile)
#TODO: don't regenerate all the storage objects
for unit in store.unit_iter():
yield unit
def scanfiles(self):
"""Populate the internal file data."""
self.filedata = []
self.archive = ZipFile(self.filename)
for completename in self.archive.namelist():
dir, name = path.split(completename)
self.filedata.append((dir, name))
|
mozilla/verbatim
|
vendor/lib/python/translate/storage/zip.py
|
Python
|
gpl-2.0
| 2,203
|
// Copyright 2019 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.
#include "DolphinQt/Config/VerifyWidget.h"
#include <memory>
#include <tuple>
#include <vector>
#include <QByteArray>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QLabel>
#include <QProgressDialog>
#include <QVBoxLayout>
#include "Common/CommonTypes.h"
#include "DiscIO/Volume.h"
#include "DiscIO/VolumeVerifier.h"
VerifyWidget::VerifyWidget(std::shared_ptr<DiscIO::Volume> volume) : m_volume(std::move(volume))
{
QVBoxLayout* layout = new QVBoxLayout;
CreateWidgets();
ConnectWidgets();
layout->addWidget(m_problems);
layout->addWidget(m_summary_text);
layout->addLayout(m_hash_layout);
layout->addWidget(m_verify_button);
layout->setStretchFactor(m_problems, 5);
layout->setStretchFactor(m_summary_text, 2);
setLayout(layout);
}
void VerifyWidget::CreateWidgets()
{
m_problems = new QTableWidget(0, 2, this);
m_problems->setHorizontalHeaderLabels({tr("Problem"), tr("Severity")});
m_problems->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
m_problems->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
m_problems->horizontalHeader()->setHighlightSections(false);
m_problems->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
m_problems->verticalHeader()->hide();
m_summary_text = new QTextEdit(this);
m_summary_text->setReadOnly(true);
m_hash_layout = new QFormLayout;
std::tie(m_crc32_checkbox, m_crc32_line_edit) = AddHashLine(m_hash_layout, tr("CRC32:"));
std::tie(m_md5_checkbox, m_md5_line_edit) = AddHashLine(m_hash_layout, tr("MD5:"));
std::tie(m_sha1_checkbox, m_sha1_line_edit) = AddHashLine(m_hash_layout, tr("SHA-1:"));
// Extend line edits to their maximum possible widths (needed on macOS)
m_hash_layout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow);
m_verify_button = new QPushButton(tr("Verify Integrity"), this);
}
std::pair<QCheckBox*, QLineEdit*> VerifyWidget::AddHashLine(QFormLayout* layout, QString text)
{
QLineEdit* line_edit = new QLineEdit(this);
line_edit->setReadOnly(true);
QCheckBox* checkbox = new QCheckBox(tr("Calculate"), this);
checkbox->setChecked(true);
QHBoxLayout* hbox_layout = new QHBoxLayout;
hbox_layout->addWidget(line_edit);
hbox_layout->addWidget(checkbox);
layout->addRow(text, hbox_layout);
return std::pair(checkbox, line_edit);
}
void VerifyWidget::ConnectWidgets()
{
connect(m_verify_button, &QPushButton::clicked, this, &VerifyWidget::Verify);
}
static void SetHash(QLineEdit* line_edit, const std::vector<u8>& hash)
{
const QByteArray byte_array = QByteArray::fromRawData(reinterpret_cast<const char*>(hash.data()),
static_cast<int>(hash.size()));
line_edit->setText(QString::fromLatin1(byte_array.toHex()));
}
void VerifyWidget::Verify()
{
DiscIO::VolumeVerifier verifier(
*m_volume,
{m_crc32_checkbox->isChecked(), m_md5_checkbox->isChecked(), m_sha1_checkbox->isChecked()});
// We have to divide the number of processed bytes with something so it won't make ints overflow
constexpr int DIVISOR = 0x100;
QProgressDialog progress(tr("Verifying"), tr("Cancel"), 0, verifier.GetTotalBytes() / DIVISOR,
this);
progress.setWindowTitle(tr("Verifying"));
progress.setWindowFlags(progress.windowFlags() & ~Qt::WindowContextHelpButtonHint);
progress.setMinimumDuration(500);
progress.setWindowModality(Qt::WindowModal);
verifier.Start();
while (verifier.GetBytesProcessed() != verifier.GetTotalBytes())
{
progress.setValue(verifier.GetBytesProcessed() / DIVISOR);
if (progress.wasCanceled())
return;
verifier.Process();
}
verifier.Finish();
DiscIO::VolumeVerifier::Result result = verifier.GetResult();
progress.setValue(verifier.GetBytesProcessed() / DIVISOR);
m_summary_text->setText(QString::fromStdString(result.summary_text));
m_problems->setRowCount(static_cast<int>(result.problems.size()));
for (int i = 0; i < m_problems->rowCount(); ++i)
{
const DiscIO::VolumeVerifier::Problem problem = result.problems[i];
QString severity;
switch (problem.severity)
{
case DiscIO::VolumeVerifier::Severity::Low:
severity = tr("Low");
break;
case DiscIO::VolumeVerifier::Severity::Medium:
severity = tr("Medium");
break;
case DiscIO::VolumeVerifier::Severity::High:
severity = tr("High");
break;
}
SetProblemCellText(i, 0, QString::fromStdString(problem.text));
SetProblemCellText(i, 1, severity);
}
SetHash(m_crc32_line_edit, result.hashes.crc32);
SetHash(m_md5_line_edit, result.hashes.md5);
SetHash(m_sha1_line_edit, result.hashes.sha1);
}
void VerifyWidget::SetProblemCellText(int row, int column, QString text)
{
QLabel* label = new QLabel(text);
label->setTextInteractionFlags(Qt::TextSelectableByMouse);
label->setWordWrap(true);
label->setMargin(4);
m_problems->setCellWidget(row, column, label);
}
|
LAGonauta/dolphin
|
Source/Core/DolphinQt/Config/VerifyWidget.cpp
|
C++
|
gpl-2.0
| 5,103
|
## Cypher Queries
### Journal Publishing Profiles
```cypher
// show distinct publishers with number of articles published
match (w:Work)
where w.publisher <> "null"
return distinct(w.publisher) as Publishers, count(*) as Articles
order by Articles desc
```
```cypher
//show top journals in any given field (department)
match (w:Work)
where w.department = "Physics"
return distinct(w.publisher) as Publishers, count(*) as Articles
order by Articles desc
```
```cypher
// show top fields (departments) that publish in any given journal
match (w:Work {publisher:"Elsevier"}) // change journal name as necessary
where w.department <> "null"
return w.department as Department, count(*) as Articles
order by Articles desc
```
### Items with Co-Authors
```cypher
//show titles with most co-authors
match (a:Work)<-[b]-(c:Creator)
where a.title <> "null"
with a.title as Title, count(c) as Authors
return Title, Authors
order by Authors descending
```
### Recommendation Engine
The following queries are adapted from [Building a Recommendation Engine with Cypher in Two Minutes](http://neo4j.com/developer/guide-build-a-recommendation-engine/).
```cypher
match (first:Creator)-->(a:Work)<--(co:Creator),
(co)-->(b:Work)<--(other:Creator)
where (first.id ="536869656265722C20537475617274"
or first.id="536869656265722C20537475617274204D2E")
and not (other.id = "536869656265722C20537475617274204D2E" or other.id = "536869656265722C20537475617274")
and not (first)-->(:Work)<--(other)
return other.name as name, count(distinct b) as frequency
order by frequency desc
```
```cypher
match (first:Creator)-->(a:Work)<--(co:Creator),
(co)-->(b:Work)<--(other:Creator)
where (first.id ="536869656265722C20537475617274"
or first.id="536869656265722C20537475617274204D2E")
and not (other.id = "536869656265722C20537475617274204D2E" or other.id = "536869656265722C20537475617274")
and not (first)-->(:Work)<--(other)
return other,b,co,a,first
limit 30
```
### Shortest Path Analysis
```cypher
match (a:Creator {name:"Shieber, Stuart"}), (s:Subject {subject:"Public Health"})
with a,s
match p = shortestPath((a)-[*]-(s)), (s)--(w)--(c:Creator)
return p,w,s,c
```
```cypher
match (a:Creator {name:"Shieber, Stuart"}), (s:Subject {subject:"Public Health"})
with a,s
match p = allShortestPaths((a)-[*]-(s)), (s)--(w)--(c:Creator)
return p,w,s,c
```
|
HeardLibrary/graphs-without-ontologies
|
Cypher/readme.md
|
Markdown
|
gpl-2.0
| 2,384
|
/*
* (C) Copyright 2015 ILLC University of Amsterdam (http://www.illc.uva.nl)
*
* This work was supported by "STW Open Technologieprogramma" grant
* under project name "Data-Powered Domain-Specific Translation Services On Demand"
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* 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.
*
*/
package nl.uva.illc.dataselection;
import edu.berkeley.nlp.lm.ConfigOptions;
import edu.berkeley.nlp.lm.NgramLanguageModel;
import edu.berkeley.nlp.lm.StringWordIndexer;
import edu.berkeley.nlp.lm.io.ArpaLmReader;
import edu.berkeley.nlp.lm.io.LmReaders;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import net.openhft.koloboke.collect.map.hash.HashIntFloatMap;
import net.openhft.koloboke.collect.map.hash.HashIntFloatMaps;
import net.openhft.koloboke.collect.map.hash.HashIntIntMap;
import net.openhft.koloboke.collect.map.hash.HashIntIntMaps;
import net.openhft.koloboke.collect.map.hash.HashIntObjMap;
import net.openhft.koloboke.collect.map.hash.HashIntObjMaps;
import net.openhft.koloboke.collect.map.hash.HashObjIntMap;
import net.openhft.koloboke.collect.map.hash.HashObjIntMaps;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Invitation based data selection approach exploits in-domain data (both
* monolingual and bilingual) as prior to guide word alignment and phrase pair
* estimates in the large mix-domain corpus. As a by-product, accurate estimates
* for P(D|e,f) of the mixed-domain sentences are produced (with D being either
* in-domain or out-of-domain), which can be used to rank the sentences in Dmix
* according to their relevance to Din.
*
* For more information see: Hoang, Cuong and Sima'an, Khalil (2014): Latent
* Domain Translation Models in Mix-of-Domains Haystack, Proceedings of COLING
* 2014, the 25th International Conference on Computational Linguistics
* http://www.aclweb.org/anthology/C14-1182.pdf
*
* @author Amir Kamran
*/
public class InvitationModel {
private static Logger log = LogManager.getLogger(InvitationModel.class);
static String IN = null;
static String MIX = null;
static String SRC = null;
static String TRG = null;
static int iMAX = 10;
static int src_indomain[][] = null;
static int trg_indomain[][] = null;
static int src_mixdomain[][] = null;
static int trg_mixdomain[][] = null;
static int src_outdomain[][] = null;
static int trg_outdomain[][] = null;
static HashObjIntMap<String> src_codes = null;
static HashObjIntMap<String> trg_codes = null;
static float lm[][] = null;
static float LOG_0_5 = (float) Math.log(0.5);
// default confidence threshold: use to decide which sentences
// will update the translation table
static float CONF_THRESHOLD = (float) Math.log(0.5);
// default convergence threshold: How much change in PD1 is significant
// to continue to next iteration
static float CONV_THRESHOLD = 0.00001f;
static float PD1 = LOG_0_5;
static float PD0 = LOG_0_5;
static TranslationTable ttable[] = new TranslationTable[4];
public static CountDownLatch latch = null;
public static ExecutorService jobs = Executors.newCachedThreadPool();
public static HashIntIntMap ignore = HashIntIntMaps.newMutableMap();
public static float n = 0.5f;
public static float V = 500000f;
public static float nV = n * V;
public static float p = -(float) Math.log(V);
public static void main(String args[]) throws IOException,
InterruptedException {
log.info("Start ...");
processCommandLineArguments(args);
readFiles();
initialize();
burnIN();
createLM();
training();
jobs.shutdown();
jobs.awaitTermination(10, TimeUnit.MINUTES);
log.info("END");
}
public static void processCommandLineArguments(String args[]) {
Options options = new Options();
options.addOption("cmix", "mix-domain-corpus", true,
"Mix-domain corpus name");
options.addOption("cin", "in-domain-corpus", true,
"In-domain corpus name");
options.addOption("src", "src-language", true, "Source Language");
options.addOption("trg", "trg-language", true, "Target Language");
options.addOption("i", "max-iterations", true, "Maximum Iterations");
options.addOption("th", "threshold", true, "This threshold deicdes which sentences updates translation tables. Default is 0.5");
options.addOption("cf", "conv_threshold", true, "This threshold decide if the convergence is reached. Default is 0.00001");
CommandLineParser parser = new GnuParser();
try {
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("cmix") && cmd.hasOption("cin")
&& cmd.hasOption("src") && cmd.hasOption("trg")) {
MIX = cmd.getOptionValue("cmix");
IN = cmd.getOptionValue("cin");
SRC = cmd.getOptionValue("src");
TRG = cmd.getOptionValue("trg");
if (cmd.hasOption("i")) {
iMAX = Integer.parseInt(cmd.getOptionValue("i"));
}
if (cmd.hasOption("th")) {
CONF_THRESHOLD = (float) Math.log(Double.parseDouble(cmd.getOptionValue("th")));
}
if (cmd.hasOption("cf")) {
CONV_THRESHOLD = (float) Float.parseFloat(cmd.getOptionValue("cf"));
}
} else {
System.out.println("Missing required argumetns!");
printHelp(options);
}
} catch (ParseException e) {
printHelp(options);
}
}
private static void printHelp(Options options) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("java " + InvitationModel.class.getName(), options);
System.exit(1);
}
public static void initialize() throws InterruptedException {
log.info("Initializing Translaiton Tables");
for (int i = 0; i < ttable.length; i++) {
ttable[i] = new TranslationTable();
}
latch = new CountDownLatch(4);
initializeTranslationTable(src_indomain, trg_indomain, ttable[0]);
initializeTranslationTable(trg_indomain, src_indomain, ttable[1]);
initializeTranslationTable(src_mixdomain, trg_mixdomain, ttable[2]);
initializeTranslationTable(trg_mixdomain, src_mixdomain, ttable[3]);
latch.await();
log.info("DONE");
}
public static void initializeTranslationTable(final int src[][],
final int trg[][], final TranslationTable ttable) {
jobs.execute(new Runnable() {
@Override
public void run() {
HashIntFloatMap totals = HashIntFloatMaps.newMutableMap();
for (int sent = 0; sent < src.length; sent++) {
if (sent % 100000 == 0)
log.debug("Sentence " + sent);
int ssent[] = src[sent];
int tsent[] = trg[sent];
for (int t = 1; t < tsent.length; t++) {
int tw = tsent[t];
for (int s = 0; s < ssent.length; s++) {
int sw = ssent[s];
ttable.increas(tw, sw, 1f);
totals.addValue(sw, 1f, 0f);
}
}
}
// normalizing and smoothing
for (int tw : ttable.ttable.keySet()) {
HashIntFloatMap tMap = ttable.ttable.get(tw);
for (int sw : tMap.keySet()) {
float prob = (float) (Math.log(ttable.get(tw, sw) + n) - Math
.log(totals.get(sw) + nV));
ttable.put(tw, sw, prob);
}
}
log.info(".");
InvitationModel.latch.countDown();
}
});
}
public static void createLM() throws InterruptedException {
log.info("Creating Language Models ...");
lm = new float[4][];
latch = new CountDownLatch(4);
createLM(IN + "." + SRC + ".encoded", lm, 0, src_mixdomain);
createLM(IN + "." + TRG + ".encoded", lm, 1, trg_mixdomain);
createLM("outdomain." + SRC + ".encoded", lm, 2, src_mixdomain);
createLM("outdomain." + TRG + ".encoded", lm, 3, trg_mixdomain);
latch.await();
log.info("DONE");
}
public static void burnIN() throws IOException, InterruptedException {
log.info("BurnIN started ... ");
HashIntObjMap<Result> results = null;
for (int i = 1; i <= 1; i++) {
log.info("Iteration " + i);
results = HashIntObjMaps.newMutableMap();
float sPD[][] = new float[2][src_mixdomain.length];
int split = (int) Math.ceil(src_mixdomain.length / 100000d);
latch = new CountDownLatch(split);
for (int sent = 0; sent < src_mixdomain.length; sent += 100000) {
int end = sent + 100000;
if (end > src_mixdomain.length) {
end = src_mixdomain.length;
}
calcualteBurnInScore(sent, end, sPD);
}
latch.await();
float countPD[] = new float[2];
countPD[0] = Float.NEGATIVE_INFINITY;
countPD[1] = Float.NEGATIVE_INFINITY;
for (int sent = 0; sent < src_mixdomain.length; sent++) {
if (ignore.containsKey(sent))
continue;
if (Float.isNaN(sPD[0][sent]) || Float.isNaN(sPD[1][sent])) {
ignore.put(sent, sent);
log.info("Ignoring " + (sent + 1));
continue;
}
countPD[0] = logAdd(countPD[0], sPD[0][sent]);
countPD[1] = logAdd(countPD[1], sPD[1][sent]);
results.put(sent, new Result(sent, sPD[0][sent]));
}
}
log.info("BurnIN DONE");
log.info("Writing outdomain corpus ... ");
ArrayList<Result> sortedResult = new ArrayList<Result>(results.values());
Collections.sort(sortedResult);
PrintWriter src_out = new PrintWriter("outdomain." + SRC + ".encoded");
PrintWriter trg_out = new PrintWriter("outdomain." + TRG + ".encoded");
PrintWriter out_score = new PrintWriter("outdomain.scores");
src_outdomain = new int[src_indomain.length][];
trg_outdomain = new int[trg_indomain.length][];
int j = 0;
for (Result r : sortedResult) {
int sentIndex = r.sentenceNumber - 1;
int ssent[] = src_mixdomain[sentIndex];
int tsent[] = trg_mixdomain[sentIndex];
out_score.println(r.sentenceNumber + "\t" + r.score);
src_outdomain[j] = ssent;
trg_outdomain[j] = tsent;
for (int w = 1; w < ssent.length; w++) {
src_out.print(ssent[w]);
src_out.print(" ");
}
src_out.println();
for (int w = 1; w < tsent.length; w++) {
trg_out.print(tsent[w]);
trg_out.print(" ");
}
trg_out.println();
j++;
if (j == src_indomain.length) {
break;
}
}
out_score.close();
src_out.close();
trg_out.close();
log.info("DONE");
}
public static void training() throws FileNotFoundException,
InterruptedException {
log.info("Starting Invitation EM ...");
latch = new CountDownLatch(2);
ttable[2] = new TranslationTable();
ttable[3] = new TranslationTable();
initializeTranslationTable(src_outdomain, trg_outdomain, ttable[2]);
initializeTranslationTable(trg_outdomain, src_outdomain, ttable[3]);
latch.await();
for (int i = 1; i <= iMAX; i++) {
log.info("Iteration " + i);
HashIntObjMap<Result> results = HashIntObjMaps.newMutableMap();
float sPD[][] = new float[2][src_mixdomain.length];
int splits = 10;
int split_size = src_mixdomain.length / splits;
latch = new CountDownLatch(splits);
for (int s=0;s<splits;s++) {
int start = s*split_size;
int end = start + split_size;
if (s==(splits-1)) {
end = src_mixdomain.length;
}
calcualteScore(start, end, sPD);
}
latch.await();
float countPD[] = new float[2];
countPD[0] = Float.NEGATIVE_INFINITY;
countPD[1] = Float.NEGATIVE_INFINITY;
for (int sent = 0; sent < src_mixdomain.length; sent++) {
if (ignore.containsKey(sent))
continue;
if (Float.isNaN(sPD[0][sent]) || Float.isNaN(sPD[1][sent])) {
ignore.put(sent, sent);
log.info("Ignoring " + (sent + 1));
continue;
}
countPD[0] = logAdd(countPD[0], sPD[0][sent]);
countPD[1] = logAdd(countPD[1], sPD[1][sent]);
float srcP = lm[0][sent];
float trgP = lm[1][sent];
results.put(sent, new Result(sent, sPD[1][sent], srcP + trgP));
}
float newPD1 = countPD[1] - logAdd(countPD[0], countPD[1]);
float newPD0 = countPD[0] - logAdd(countPD[0], countPD[1]);
log.info("PD1 ~ PD0 " + Math.exp(newPD1) + " ~ " + Math.exp(newPD0));
writeResult(i, results);
if(i>1 && Math.abs(Math.exp(newPD1) - Math.exp(PD1)) <= CONV_THRESHOLD) {
log.info("Convergence threshold reached.");
break;
}
PD1 = newPD1;
PD0 = newPD0;
if (i < iMAX) {
latch = new CountDownLatch(4);
updateTranslationTable(src_mixdomain, trg_mixdomain, ttable[0], sPD[1]);
updateTranslationTable(trg_mixdomain, src_mixdomain, ttable[1], sPD[1]);
updateTranslationTable(src_mixdomain, trg_mixdomain, ttable[2], sPD[0]);
updateTranslationTable(trg_mixdomain, src_mixdomain, ttable[3], sPD[0]);
latch.await();
}
}
}
public static void calcualteScore(final int start, final int end,
final float sPD[][]) {
jobs.execute(new Runnable() {
@Override
public void run() {
for (int sent = start; sent < end; sent++) {
if (ignore.containsKey(sent))
continue;
int ssent[] = src_mixdomain[sent];
int tsent[] = trg_mixdomain[sent];
float sProb[] = new float[4];
sProb[0] = calculateProb(ssent, tsent, ttable[0]);
sProb[1] = calculateProb(tsent, ssent, ttable[1]);
sProb[2] = calculateProb(ssent, tsent, ttable[2]);
sProb[3] = calculateProb(tsent, ssent, ttable[3]);
float in_score = PD1 + logAdd(sProb[0] + lm[1][sent], sProb[1] + lm[0][sent]);
float mix_score = PD0 + logAdd(sProb[2] + lm[3][sent], sProb[3] + lm[2][sent]);
sPD[1][sent] = in_score - logAdd(in_score, mix_score);
sPD[0][sent] = mix_score - logAdd(in_score, mix_score);
}
InvitationModel.latch.countDown();
}
});
}
public static void calcualteBurnInScore(final int start, final int end,
final float sPD[][]) {
jobs.execute(new Runnable() {
@Override
public void run() {
for (int sent = start; sent < end; sent++) {
if (ignore.containsKey(sent))
continue;
int ssent[] = src_mixdomain[sent];
int tsent[] = trg_mixdomain[sent];
float sProb[] = new float[4];
sProb[0] = calculateProb(ssent, tsent, ttable[0]);
sProb[1] = calculateProb(tsent, ssent, ttable[1]);
sProb[2] = calculateProb(ssent, tsent, ttable[2]);
sProb[3] = calculateProb(tsent, ssent, ttable[3]);
float in_score = PD1 + logAdd(sProb[0], sProb[1]);
float mix_score = PD0 + logAdd(sProb[2], sProb[3]);
sPD[1][sent] = in_score - logAdd(in_score, mix_score);
sPD[0][sent] = mix_score - logAdd(in_score, mix_score);
}
InvitationModel.latch.countDown();
}
});
}
public static void writeResult(final int iterationNumber,
final HashIntObjMap<Result> results) {
jobs.execute(new Runnable() {
@Override
public void run() {
ArrayList<Result> sortedResult = new ArrayList<Result>(results
.values());
Collections.sort(sortedResult);
try {
PrintWriter output = new PrintWriter("output_"
+ iterationNumber + ".txt");
for (Result r : sortedResult) {
output.println(r.sentenceNumber + "\t"
+ Math.exp(r.score) + "\t"
+ Math.exp(r.lm_score));
}
output.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
});
}
public static float calculateProb(final int ssent[], final int tsent[],
final TranslationTable ttable) {
float prob = 0;
for (int t = 1; t < tsent.length; t++) {
int tw = tsent[t];
float sum = Float.NEGATIVE_INFINITY;
for (int s = 0; s < ssent.length; s++) {
int sw = ssent[s];
sum = logAdd(sum, ttable.get(tw, sw, p));
}
prob += sum;
}
return prob - (float)Math.log(Math.pow(ssent.length, tsent.length-1));
}
public static void updateTranslationTable(final int src[][],
final int trg[][], final TranslationTable ttable, final float sPD[]) {
jobs.execute(new Runnable() {
@Override
public void run() {
log.info("Updating translation table ... ");
TranslationTable counts = new TranslationTable();
HashIntFloatMap totals = HashIntFloatMaps.newMutableMap();
for (int sent = 0; sent < src.length; sent++) {
if (sent % 100000 == 0)
log.debug("Sentence " + sent);
if (ignore.containsKey(sent))
continue;
if(sPD[sent] < CONF_THRESHOLD) continue;
int ssent[] = src[sent];
int tsent[] = trg[sent];
HashIntFloatMap s_total = HashIntFloatMaps.newMutableMap();
// calculating normalization
for (int t = 1; t < tsent.length; t++) {
int tw = tsent[t];
for (int s = 0; s < ssent.length; s++) {
int sw = ssent[s];
s_total.put(
tw,
logAdd(s_total.getOrDefault(tw,
Float.NEGATIVE_INFINITY), ttable
.get(tw, sw, p)));
}
}
// collect counts
for (int t = 1; t < tsent.length; t++) {
int tw = tsent[t];
for (int s = 0; s < ssent.length; s++) {
int sw = ssent[s];
float in_count = sPD[sent]
+ (ttable.get(tw, sw, p) - s_total.get(tw));
counts.put(
tw,
sw,
logAdd(counts.get(tw, sw,
Float.NEGATIVE_INFINITY), in_count));
totals.put(
sw,
logAdd(totals.getOrDefault(sw,
Float.NEGATIVE_INFINITY), in_count));
}
}
}
// maximization
for (int tw : counts.ttable.keySet()) {
HashIntFloatMap tMap = counts.ttable.get(tw);
for (int sw : tMap.keySet()) {
float newProb = counts.get(tw, sw) - totals.get(sw);
ttable.put(tw, sw, newProb);
}
}
log.info("Updating translation table DONE");
InvitationModel.latch.countDown();
}
});
}
public static void readFiles() throws IOException, InterruptedException {
log.info("Reading files");
src_codes = HashObjIntMaps.newMutableMap();
trg_codes = HashObjIntMaps.newMutableMap();
src_codes.put(null, 0);
trg_codes.put(null, 0);
LineNumberReader lr = new LineNumberReader(new FileReader(IN + "."
+ SRC));
lr.skip(Long.MAX_VALUE);
int indomain_size = lr.getLineNumber();
lr.close();
lr = new LineNumberReader(new FileReader(MIX + "." + SRC));
lr.skip(Long.MAX_VALUE);
int mixdomain_size = lr.getLineNumber();
lr.close();
src_indomain = new int[indomain_size][];
trg_indomain = new int[indomain_size][];
src_mixdomain = new int[mixdomain_size][];
trg_mixdomain = new int[mixdomain_size][];
latch = new CountDownLatch(2);
readFile(IN + "." + SRC, src_codes, src_indomain);
readFile(IN + "." + TRG, trg_codes, trg_indomain);
latch.await();
latch = new CountDownLatch(2);
readFile(MIX + "." + SRC, src_codes, src_mixdomain);
readFile(MIX + "." + TRG, trg_codes, trg_mixdomain);
latch.await();
}
public static void readFile(final String fileName,
final HashObjIntMap<String> codes, final int lines[][])
throws IOException {
jobs.execute(new Runnable() {
@Override
public void run() {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream(fileName), Charset
.forName("UTF8")));
String line = null;
int i = 0;
while ((line = reader.readLine()) != null) {
String words[] = line.split("\\s+");
lines[i] = new int[words.length + 1];
lines[i][0] = 0;
int j = 1;
for (String word : words) {
int code = 0;
if (!codes.containsKey(word)) {
code = codes.size() + 1;
codes.put(word, code);
} else {
code = codes.getInt(word);
}
lines[i][j++] = code;
}
i++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
writeEncodedFile(fileName + ".encoded", lines);
log.info(fileName + " ... DONE");
InvitationModel.latch.countDown();
}
});
}
public static void writeEncodedFile(final String fileName,
final int lines[][]) {
jobs.execute(new Runnable() {
@Override
public void run() {
try {
BufferedWriter encodedWriter = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(
fileName), Charset.forName("UTF8")));
for (int i = 0; i < lines.length; i++) {
for (int j = 1; j < lines[i].length; j++) {
int word = lines[i][j];
encodedWriter.write("" + word);
encodedWriter.write(" ");
}
encodedWriter.write("\n");
}
encodedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public static float getLMProb(NgramLanguageModel<String> lm, int sent[]) {
List<String> words = new ArrayList<String>();
for (int i = 1; i < sent.length; i++) {
words.add("" + sent[i]);
}
return lm.getLogProb(words);
}
public static void createLM(final String fileName, final float lm[][],
final int index, final int corpus[][]) {
jobs.execute(new Runnable() {
@Override
public void run() {
log.info("Creating language model");
NgramLanguageModel<String> createdLM = null;
final int lmOrder = 4;
final List<String> inputFiles = new ArrayList<String>();
inputFiles.add(fileName);
final StringWordIndexer wordIndexer = new StringWordIndexer();
wordIndexer.setStartSymbol(ArpaLmReader.START_SYMBOL);
wordIndexer.setEndSymbol(ArpaLmReader.END_SYMBOL);
wordIndexer.setUnkSymbol(ArpaLmReader.UNK_SYMBOL);
createdLM = LmReaders
.readContextEncodedKneserNeyLmFromTextFile(inputFiles,
wordIndexer, lmOrder, new ConfigOptions(),
new File(fileName + ".lm"));
lm[index] = new float[corpus.length];
for (int i = 0; i < corpus.length; i++) {
int sent[] = corpus[i];
lm[index][i] = getLMProb(createdLM, sent);
}
log.info(".");
InvitationModel.latch.countDown();
}
});
}
public static float logAdd(float a, float b) {
float max, negDiff;
if (a > b) {
max = a;
negDiff = b - a;
} else {
max = b;
negDiff = a - b;
}
if (max == Float.NEGATIVE_INFINITY) {
return max;
} else if (negDiff < -20.0f) {
return max;
} else {
return max + (float) Math.log(1.0 + Math.exp(negDiff));
}
}
}
class Result implements Comparable<Result> {
int sentenceNumber;
float score = 1;
float lm_score = 1;
public Result(int sentenceNumber, float score) {
this.sentenceNumber = sentenceNumber + 1;
this.score = score;
}
public Result(int sentenceNumber, float score, float lm_score) {
this.sentenceNumber = sentenceNumber + 1;
this.score = score;
this.lm_score = lm_score;
}
@Override
public int compareTo(Result result) {
int cmp = Float.compare(result.score, this.score);
if (cmp == 0) {
cmp = Float.compare(result.lm_score, this.lm_score);
}
return cmp;
}
}
|
amirkamran/InvitationModel
|
src/main/java/nl/uva/illc/dataselection/InvitationModel.java
|
Java
|
gpl-2.0
| 23,668
|
/*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2012 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Christian Stocker <chregu@php.net> |
| Rob Richards <rrichards@php.net> |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#if HAVE_LIBXML && HAVE_DOM
#include "php_dom.h"
/* {{{ arginfo */
ZEND_BEGIN_ARG_INFO_EX(arginfo_dom_implementationlist_item, 0, 0, 1)
ZEND_ARG_INFO(0, index)
ZEND_END_ARG_INFO();
/* }}} */
/*
* class domimplementationlist
*
* URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#DOMImplementationList
* Since: DOM Level 3
*/
const zend_function_entry php_dom_domimplementationlist_class_functions[] = {
PHP_FALIAS(item, dom_domimplementationlist_item, arginfo_dom_implementationlist_item)
{NULL, NULL, NULL}
};
/* {{{ attribute protos, not implemented yet */
/* {{{ length unsigned long
readonly=yes
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#DOMImplementationList-length
Since:
*/
int dom_domimplementationlist_length_read(dom_object *obj, zval **retval TSRMLS_DC)
{
ALLOC_ZVAL(*retval);
ZVAL_STRING(*retval, "TEST", 1);
return SUCCESS;
}
/* }}} */
/* {{{ proto domdomimplementation dom_domimplementationlist_item(int index);
URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#DOMImplementationList-item
Since:
*/
PHP_FUNCTION(dom_domimplementationlist_item)
{
DOM_NOT_IMPLEMENTED();
}
/* }}} end dom_domimplementationlist_item */
/* }}} */
#endif
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
|
ssanglee/capstone
|
php-5.4.6/ext/dom/domimplementationlist.c
|
C
|
gpl-2.0
| 2,688
|
/*
* smixlate.c --
*
* Translate OIDs located in the input stream.
*
* Copyright (c) 2006 Juergen Schoenwaelder, International University Bremen.
*
* See the file "COPYING" for information on usage and redistribution
* of this file, and for a DISCLAIMER OF ALL WARRANTIES.
*
* @(#) $Id: smilint.c 1867 2004-10-06 13:45:31Z strauss $
*/
#include <config.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_WIN_H
#include "win.h"
#endif
#include "smi.h"
#include "shhopt.h"
#include "dstring.h"
static int flags;
static int aFlag = 0; /* translate all OIDs */
static int fFlag = 0; /* preserve formatting */
static void translate(dstring_t *token, dstring_t *subst)
{
SmiNode *smiNode;
SmiSubid oid[256];
unsigned int oidlen = 0;
unsigned int i;
char *p;
assert(token && subst);
dstring_truncate(subst, 0);
dstring_assign(subst, dstring_str(token));
for (oidlen = 0, p = strtok(dstring_str(token), ". "); p;
oidlen++, p = strtok(NULL, ". ")) {
oid[oidlen] = strtoul(p, NULL, 0);
}
smiNode = smiGetNodeByOID(oidlen, oid);
if (smiNode &&
(aFlag
|| smiNode->nodekind == SMI_NODEKIND_SCALAR
|| smiNode->nodekind == SMI_NODEKIND_COLUMN
|| smiNode->nodekind == SMI_NODEKIND_NOTIFICATION
|| smiNode->nodekind == SMI_NODEKIND_TABLE
|| smiNode->nodekind == SMI_NODEKIND_ROW)) {
dstring_assign(subst, smiNode->name);
for (i = smiNode->oidlen; i < oidlen; i++) {
dstring_append_printf(subst, ".%d", oid[i]);
}
}
}
static void process(FILE *stream)
{
int c, space = 0;
enum { TXT, NUM, NUMDOT, NUMDOTNUM, OID, OIDDOT, EATSPACE } state = TXT;
dstring_t *token, *subst;
token = dstring_new();
subst = dstring_new();
if (! token || ! subst) {
return;
}
/*
* Shall we require iswhite() or ispunct() before and after the
* OID?
*
* TODO: - translate instance identifier to something meaningful
* (e.g. foobar["name",32]) where possible
* - generate warnings if instance identifier are incomplete
* - provide a reverse translation service (-x) (but this is
* more complex since it is unclear how to identify names
* - make the white space magic optional
*/
while ((c = fgetc(stream)) != EOF) {
switch (state) {
case TXT:
fputs(dstring_str(token), stdout);
dstring_truncate(token, 0);
if (isdigit(c) && c >= '0' && c <= '2') {
dstring_append_char(token, (char) c);
state = NUM;
} else {
fputc(c, stdout);
fflush(stdout);
}
break;
case NUM:
if (isdigit(c)) {
dstring_append_char(token, (char) c);
} else if (c == '.') {
dstring_append_char(token, (char) c);
state = NUMDOT;
} else {
dstring_append_char(token, (char) c);
state = TXT;
}
break;
case NUMDOT:
if (isdigit(c)) {
dstring_append_char(token, (char) c);
state = NUMDOTNUM;
} else {
dstring_append_char(token, (char) c);
state = TXT;
}
break;
case NUMDOTNUM:
if (isdigit(c)) {
dstring_append_char(token, (char) c);
} if (c == '.') {
dstring_append_char(token, (char) c);
state = OID;
} else {
dstring_append_char(token, (char) c);
state = TXT;
}
break;
case OID:
if (isdigit(c)) {
dstring_append_char(token, (char) c);
} else if (c == '.') {
dstring_append_char(token, (char) c);
state = OIDDOT;
} else {
translate(token, subst);
if (fFlag) {
if (dstring_len(subst) < dstring_len(token)) {
dstring_expand(subst, dstring_len(token), ' ');
}
}
fputs(dstring_str(subst), stdout);
if (dstring_len(subst) > dstring_len(token)) {
space = dstring_len(subst) - dstring_len(token) - 1;
} else {
space = 0;
}
if (fFlag && space > 0 && c == ' ') {
state = EATSPACE;
space--;
} else {
state = TXT;
space = 0;
fputc(c, stdout);
}
dstring_truncate(token, 0);
}
break;
case OIDDOT:
if (isdigit(c)) {
dstring_append_char(token, (char) c);
state = OID;
} else {
translate(token, subst);
fputs(dstring_str(subst), stdout);
fputc(c, stdout);
dstring_truncate(token, 0);
state = TXT;
}
break;
case EATSPACE:
if (c == ' ' && space > 0) {
space--;
} else {
state = TXT;
}
break;
}
}
if (dstring_len(token)) {
switch (state) {
case TXT:
case NUM:
case NUMDOT:
case NUMDOTNUM:
fputs(dstring_str(token), stdout);
dstring_truncate(token, 0);
fputc(c, stdout);
fflush(stdout);
break;
case OID:
if (isdigit(c)) {
dstring_append_char(token, (char) c);
} else {
translate(token, subst);
if (fFlag) {
if (dstring_len(subst) < dstring_len(token)) {
dstring_expand(subst, dstring_len(token), ' ');
}
}
fputs(dstring_str(subst), stdout);
if (dstring_len(subst) > dstring_len(token)) {
space = dstring_len(subst) - dstring_len(token) - 1;
} else {
space = 0;
}
if (fFlag && space > 0 && c == ' ') {
space--;
} else {
space = 0;
fputc(c, stdout);
}
dstring_truncate(token, 0);
}
break;
case OIDDOT:
if (isdigit(c)) {
dstring_append_char(token, (char) c);
} else {
translate(token, subst);
fputs(dstring_str(subst), stdout);
fputc(c, stdout);
dstring_truncate(token, 0);
}
break;
case EATSPACE:
if (c == ' ' && space > 0) {
space--;
} else {
fputc(c, stdout);
}
break;
}
}
}
static void usage()
{
fprintf(stderr,
"Usage: smixlate [options] [module or path ...]\n"
" -V, --version show version and license information\n"
" -h, --help show usage information\n"
" -c, --config=file load a specific configuration file\n"
" -p, --preload=module preload <module>\n"
" -r, --recursive print errors also for imported modules\n"
" -l, --level=level set maximum level of errors and warnings\n"
" -i, --ignore=prefix ignore errors matching prefix pattern\n"
" -I, --noignore=prefix do not ignore errors matching prefix pattern\n"
" -a, --all replace all OIDs (including OID prefixes)\n"
" -f, --format preserve formatting as much as possible\n");
}
static void help() { usage(); exit(0); }
static void version() { printf("smixlate " SMI_VERSION_STRING "\n"); exit(0); }
static void config(char *filename) { smiReadConfig(filename, "smixlate"); }
static void preload(char *module) { smiLoadModule(module); }
static void recursive() { flags |= SMI_FLAG_RECURSIVE; smiSetFlags(flags); }
static void level(int lev) { smiSetErrorLevel(lev); }
static void ignore(char *ign) { smiSetSeverity(ign, 128); }
static void noignore(char *ign) { smiSetSeverity(ign, -1); }
int main(int argc, char *argv[])
{
int i;
static optStruct opt[] = {
/* short long type var/func special */
{ 'a', "all", OPT_FLAG, &aFlag, 0 },
{ 'f', "format", OPT_FLAG, &fFlag, 0 },
{ 'h', "help", OPT_FLAG, help, OPT_CALLFUNC },
{ 'V', "version", OPT_FLAG, version, OPT_CALLFUNC },
{ 'c', "config", OPT_STRING, config, OPT_CALLFUNC },
{ 'p', "preload", OPT_STRING, preload, OPT_CALLFUNC },
{ 'r', "recursive", OPT_FLAG, recursive, OPT_CALLFUNC },
{ 'l', "level", OPT_INT, level, OPT_CALLFUNC },
{ 'i', "ignore", OPT_STRING, ignore, OPT_CALLFUNC },
{ 'I', "noignore", OPT_STRING, noignore, OPT_CALLFUNC },
{ 0, 0, OPT_END, 0, 0 } /* no more options */
};
for (i = 1; i < argc; i++)
if ((strstr(argv[i], "-c") == argv[i]) ||
(strstr(argv[i], "--config") == argv[i])) break;
if (i == argc)
smiInit("smixlate");
else
smiInit(NULL);
flags = smiGetFlags();
flags |= SMI_FLAG_ERRORS;
flags |= SMI_FLAG_NODESCR;
smiSetFlags(flags);
optParseOptions(&argc, argv, opt, 0);
for (i = 1; i < argc; i++) {
if (smiLoadModule(argv[i]) == NULL) {
fprintf(stderr, "smixlate: cannot locate module `%s'\n",
argv[i]);
smiExit();
exit(1);
}
}
process(stdin);
smiExit();
return 0;
}
|
vertexclique/travertine
|
libsmi/tools/smixlate.c
|
C
|
gpl-2.0
| 8,384
|
/*
Siesta 2.0.5
Copyright(c) 2009-2013 Bryntum AB
http://bryntum.com/contact
http://bryntum.com/products/siesta/license
*/
.icon-delete {
background : transparent url(../images/cross.png) no-repeat left center !important;
cursor : pointer;
height : 10px;
width : 10px;
background-size : 8px 8px !important;
margin : 4px 2px;
}
.recorder-tool {
background : none !important;
border : none !important;
}
.recorder-tool-icon {
font-size : 1.1em;
color : rgb(7, 89, 133);
padding-top : 0.1em;
}
.recorder-tool-icon:hover {
color : #222;
}
.icon-record {
border-radius : 10px;
width : 10px !important;
height : 10px !important;
margin-top : 3px;
background : #ff1111;
margin-left : 2px;
}
.icon-record:hover {
background : darkred;
}
.recorder-tool-icon.icon-close {
font-size : 0.9em;
padding-top : 0.2em;
}
.cheatsheet {
background : #eee;
padding : 5px;
}
.cheatsheet-type {
width : 135px;
font-weight : bold;
margin-top : 5px;
}
.cheatsheet td {
white-space : nowrap;
color : #555;
}
.eventview-offsetcolumn > .x-grid-cell-inner {
position : relative;
color : #777;
}
.eventview-clearoffset {
position : absolute;
width : 11px;
height : 11px;
right : 4px;
top : 0px;
cursor : pointer;
}
.x-grid-row-over .eventview-clearoffset {
background : transparent url(../images/bullet_delete.png) no-repeat left center !important;
}
@keyframes blink {
0% { opacity : 0; }
100% { opacity : 1; }
}
@-webkit-keyframes blink {
0% { opacity : 0; }
100% { opacity : 1; }
}
.recorder-recording .icon-record {
-webkit-animation : blink 0.5s linear infinite;
-moz-animation : blink 0.5s linear infinite;
animation : blink 0.5s linear infinite;
-webkit-animation-timing-function : cubic-bezier(1.0, 0, 0, 1.0);
-webkit-animation-direction : alternate;
animation-direction : alternate;
}
.siesta-recorder-codeeditor .CodeMirror {
background-image : url(../images/ok.png);
background-repeat : no-repeat;
background-position : right top;
background-size : 10px 10px;
}
.siesta-recorder-codeeditor.x-form-invalid .CodeMirror {
background-image : url(../images/cross.png);
}
|
m-revetria/sencha-touch-bdd-example
|
resources/siesta-2.0.5-lite/lib/Siesta/Recorder/Recorder.css
|
CSS
|
gpl-2.0
| 2,477
|
--
-- $Id$
--
-- This file is part of the OpenLink Software Virtuoso Open-Source (VOS)
-- project.
--
-- Copyright (C) 1998-2012 OpenLink Software
--
-- This project 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; only version 2 of the License, dated June 1991.
--
-- 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
--
--
DB.DBA.USER_CREATE ('interop4', uuid(), vector ('DISABLED', 1))
;
DB.DBA.user_set_qualifier ('interop4', 'interop4');
DB.DBA.VHOST_REMOVE (lpath=>'/r4/groupG/dime/rpc')
;
DB.DBA.VHOST_DEFINE (lpath=>'/r4/groupG/dime/rpc', ppath=>'/SOAP/', soap_user=>'interop4',
soap_opts => vector (
'Namespace','http://soapinterop.org/attachments/','MethodInSoapAction','no', 'ServiceName', 'GroupGService'
)
)
;
-- methods
use interop4;
create procedure
"EchoBase64AsAttachment" (in "In" nvarchar __soap_type 'http://www.w3.org/2001/XMLSchema:base64Binary')
returns nvarchar __soap_type 'http://soapinterop.org/attachments/xsd:ReferencedBinary'
__soap_dime_enc out
{
declare _Out any;
_Out := decode_base64 (cast ("In" as varchar));
--dbg_obj_print ('echoBase64AsAttachment :', _Out);
return vector (uuid(), 'application/octetstream', _Out);
}
;
create procedure
"EchoAttachmentAsBase64" (in "In" nvarchar __soap_type 'http://soapinterop.org/attachments/xsd:ReferencedBinary')
returns nvarchar __soap_type 'http://www.w3.org/2001/XMLSchema:base64Binary'
__soap_dime_enc in
{
--dbg_obj_print ('EchoAttachmentAsBase64 :', "In");
if (not isarray ("In"))
signal ('TEST1' ,'The attachment is missing or not DIME encoded.');
return encode_base64 (cast ("In"[2] as varchar));
}
;
create procedure
"EchoAttachment" (in "In" nvarchar __soap_type 'http://soapinterop.org/attachments/xsd:ReferencedBinary')
returns nvarchar __soap_type 'http://soapinterop.org/attachments/xsd:ReferencedBinary'
__soap_dime_enc inout
{
--dbg_obj_print ('EchoAttachment :', "In");
if (not isarray ("In"))
signal ('TEST2' ,'The attachment is missing or not DIME encoded.');
return vector (uuid(), "In"[1], "In"[2]);
}
;
create procedure
"EchoAttachments" (in "In" any __soap_type 'http://soapinterop.org/attachments/xsd:ArrayOfBinary')
returns nvarchar __soap_type 'http://soapinterop.org/attachments/xsd:ArrayOfBinary'
__soap_dime_enc inout
{
declare i, l int;
declare arr any;
--dbg_obj_print ('EchoAttachments :', "In");
l := length ("In");
arr := make_array (l, 'any');
while (i < l)
{
if (not isarray ("In"[i]))
signal ('TEST3' ,'The attachment is missing or not DIME encoded.');
aset (arr, i, vector (uuid(), "In"[i][1], "In"[i][2]));
i := i + 1;
}
return arr;
}
;
create procedure
"EchoAttachmentAsString" (in "In" nvarchar __soap_type 'http://soapinterop.org/attachments/xsd:ReferencedText')
returns nvarchar __soap_type 'http://www.w3.org/2001/XMLSchema:string'
__soap_dime_enc in
{
declare enc, typ, src varchar;
declare decoded nvarchar;
if (not isarray ("In"))
signal ('TEST4' ,'The attachment is missing or not DIME encoded.');
src := "In"[2];
enc := "In"[1];
typ := http_request_header (vector('Content-Type:' || enc), 'Content-Type');
enc := http_request_header (vector('Content-Type:' || enc), 'Content-Type', 'charset', current_charset ());
if (typ like 'text/%')
{
declare exit handler for sqlstate '*'
{
if (lower(enc) = 'utf-16')
{
decoded := charset_recode (src, 'UTF-16LE', '_WIDE_');
goto next;
}
else
resignal;
};
decoded := charset_recode (src, enc, '_WIDE_');
}
else
decoded := src;
next:
--dbg_obj_print ('EchoAttachmentAsString: ', decoded);
return decoded;
}
;
create procedure
"EchoUnrefAttachments" (inout ws_soap_attachments any)
__soap_type '__VOID__'
__soap_dime_enc inout
{
declare arr any;
declare i, l int;
l := length (ws_soap_attachments);
if (l > 1)
{
arr := make_array (l-1, 'any'); i := 1;
while (i < l)
{
if (not isarray (ws_soap_attachments[i]))
signal ('TEST5' ,'The attachment is missing or not DIME encoded.');
aset (arr, i-1, vector (uuid(), ws_soap_attachments[i][1], ws_soap_attachments[i][2]));
i := i + 1;
}
ws_soap_attachments := arr;
}
else
ws_soap_attachments := NULL;
--dbg_obj_print ('EchoUnrefAttachments', ws_soap_attachments);
return;
}
;
-- grants
grant execute on "EchoBase64AsAttachment" to "interop4"
;
grant execute on "EchoAttachmentAsBase64" to "interop4"
;
grant execute on "EchoAttachment" to "interop4"
;
grant execute on "EchoAttachments" to "interop4"
;
grant execute on "EchoAttachmentAsString" to "interop4"
;
grant execute on "EchoUnrefAttachments" to "interop4"
;
use DB;
|
trueg/virtuoso-opensource
|
binsrc/vsp/soapdemo/r4/dime-rpc.sql
|
SQL
|
gpl-2.0
| 5,242
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using Roadkill.Core.Converters;
using System.Web;
using System.Text.RegularExpressions;
using Recaptcha;
using System.Web.UI;
using System.IO;
using Roadkill.Core.Configuration;
using Roadkill.Core.Services;
using StructureMap;
using ControllerBase = Roadkill.Core.Mvc.Controllers.ControllerBase;
using Roadkill.Core.Attachments;
using Roadkill.Core.Mvc.ViewModels;
using Roadkill.Core.Localization;
using Roadkill.Core.DI;
using System.Linq.Expressions;
using Roadkill.Core.Mvc.Controllers;
using System.Web.Optimization;
using Roadkill.Core.Mvc;
namespace Roadkill.Core.Extensions
{
/// <summary>
/// Roadkill specific extensions methods for the <see cref="UrlHelper"/> class.
/// </summary>
public static class UrlHelperExtensions
{
/// <summary>
/// Gets a complete URL path to an item in the current theme directory.
/// </summary>
/// <param name="helper">The helper.</param>
/// <param name="relativePath">The filename or path inside the current theme directory.</param>
/// <returns>A url path to the item, e.g. '/MySite/Themes/Mediawiki/logo.png'</returns>
public static string ThemeContent(this UrlHelper helper, string relativePath, SiteSettings settings)
{
return helper.Content(settings.ThemePath + "/" + relativePath);
}
/// <summary>
/// Provides a CSS link tag for the CSS file provided. If the relative path does not begin with ~ then
/// the Assets/Css folder is assumed.
/// </summary>
public static MvcHtmlString CssLink(this UrlHelper helper, string relativePath)
{
string path = relativePath;
if (!path.StartsWith("~"))
path = "~/Assets/CSS/" + relativePath;
path = helper.Content(path);
string html = string.Format("<link href=\"{0}?version={1}\" rel=\"stylesheet\" type=\"text/css\" />", path, ApplicationSettings.ProductVersion);
return MvcHtmlString.Create(html);
}
/// <summary>
/// Provides a Javascript script tag for the Javascript file provided. If the relative path does not begin with ~ then
/// the Assets/Scripts folder is assumed.
/// </summary>
public static MvcHtmlString ScriptLink(this UrlHelper helper, string relativePath)
{
string path = relativePath;
if (!path.StartsWith("~"))
path = "~/Assets/Scripts/" + relativePath;
path = helper.Content(path);
string html = string.Format("<script type=\"text/javascript\" language=\"javascript\" src=\"{0}?version={1}\"></script>", path, ApplicationSettings.ProductVersion);
return MvcHtmlString.Create(html);
}
/// <summary>
/// Provides a Javascript script tag for the installer Javascript file provided, using ~/Assets/Scripts/roadkill/installer as the base path.
/// </summary>
public static MvcHtmlString InstallerScriptLink(this UrlHelper helper, string filename)
{
string path = helper.Content("~/Assets/Scripts/roadkill/installer/" + filename);
string html = string.Format("<script type=\"text/javascript\" language=\"javascript\" src=\"{0}?version={1}\"></script>", path, ApplicationSettings.ProductVersion);
return MvcHtmlString.Create(html);
}
/// <summary>
/// Provides a CSS tag for the Bootstrap framework.
/// </summary>
public static MvcHtmlString BootstrapCSS(this UrlHelper helper)
{
string path = helper.Content("~/Assets/bootstrap/css/bootstrap.min.css");
string html = string.Format("<link href=\"{0}?version={1}\" rel=\"stylesheet\" type=\"text/css\" />", path, ApplicationSettings.ProductVersion);
return MvcHtmlString.Create(html);
}
/// <summary>
/// Provides a Javascript script tag for the Bootstrap framework.
/// </summary>
public static MvcHtmlString BootstrapJS(this UrlHelper helper)
{
string path = helper.Content("~/Assets/bootstrap/js/bootstrap.min.js");
string html = string.Format("<script type=\"text/javascript\" language=\"javascript\" src=\"{0}?version={1}\"></script>", path, ApplicationSettings.ProductVersion);
return MvcHtmlString.Create(html);
}
/// <summary>
/// Returns the script link for the JS bundle
/// </summary>
public static MvcHtmlString JsBundle(this UrlHelper helper)
{
StringBuilder builder = new StringBuilder();
string mainJs = Scripts.Render("~/Assets/Scripts/" + Bundles.JsFilename).ToHtmlString();
mainJs = mainJs.Replace("\r\n", ""); // remove these newlines, the newlines are done in the view
builder.AppendLine(mainJs);
string jsVars = "";
jsVars = ScriptLink(helper, "~/home/globaljsvars").ToHtmlString();
jsVars = jsVars.Replace("\r\n", ""); // more cleanup to tidy the HTML up
builder.Append(jsVars, 2);
return MvcHtmlString.Create(builder.ToString());
}
/// <summary>
/// Returns the script link for the CSS bundle.
/// </summary>
public static MvcHtmlString CssBundle(this UrlHelper helper)
{
string html = Styles.Render("~/Assets/CSS/" + Bundles.CssFilename).ToHtmlString();
html = html.Replace("\r\n", ""); // done in the view
return MvcHtmlString.Create(html);
}
}
}
|
anubees/allscripts-sunrise-wiki
|
src/Roadkill.Core/Extensions/UrlHelperExtensions.cs
|
C#
|
gpl-2.0
| 5,106
|
#ifndef PERSON_H
#define PERSON_H
#include <QString>
#include <QDate>
#include <iostream>
/**
* @brief The Person class
*
* This class is abstract (you can't make objects of this type), and is used to represent general Person characteristics.
*
* Public methods:
* QString getName() const;
* bool getGender() const;
* QString getGenderAsString() const;
* unsigned int getAge() const;
*/
class Person {
public:
Person(): firstName(QString()), lastName(QString()), gender(false), born_date(QDate::currentDate()) {}
Person(const QString& firstName, const QString& lastName): firstName(firstName), lastName(lastName), gender(false), born_date(QDate::currentDate()) {}
Person(const QString& firstName, const QString& lastName, bool gender, const QDate& born_date):
firstName(firstName), lastName(lastName), gender(gender), born_date(born_date) {}
virtual ~Person() {}
virtual void setFirstName(const QString&);
virtual void setLastName(const QString&);
virtual void setGender(bool);
virtual QString getFullName() const;
virtual QString getFirstName() const;
virtual QString getLastName() const;
virtual bool getGender() const;
virtual QString getGenderAsString() const;
virtual unsigned int getAge() const;
virtual QString getContact() const = 0;
private:
QString firstName;
QString lastName;
bool gender;
QDate born_date;
};
#endif // PERSON_H
|
mariusmg2/X-Courier
|
person.h
|
C
|
gpl-2.0
| 1,438
|
#include "SeqLib/FermiAssembler.h"
#define MAG_MIN_NSR_COEF .1
namespace SeqLib {
FermiAssembler::FermiAssembler() : m_seqs(0), m(0), size(0), n_seqs(0), n_utg(0), m_utgs(0) {
fml_opt_init(&opt);
}
FermiAssembler::~FermiAssembler() {
ClearReads();
ClearContigs();
}
// code copied and slightly modified from
// fermi-lite/misc.c by Heng Li
void FermiAssembler::DirectAssemble(float kcov) {
rld_t *e = fml_seq2fmi(&opt, n_seqs, m_seqs);
mag_t *g = fml_fmi2mag(&opt, e);
opt.mag_opt.min_ensr = opt.mag_opt.min_ensr > kcov * MAG_MIN_NSR_COEF? opt.mag_opt.min_ensr : (int)(kcov * MAG_MIN_NSR_COEF + .499);
//opt.mag_opt.min_ensr = opt.mag_opt.min_ensr < opt0->max_cnt? opt.mag_opt.min_ensr : opt0->max_cnt;
//opt.mag_opt.min_ensr = opt.mag_opt.min_ensr > opt0->min_cnt? opt.mag_opt.min_ensr : opt0->min_cnt;
opt.mag_opt.min_insr = opt.mag_opt.min_ensr - 1;
fml_mag_clean(&opt, g);
m_utgs = fml_mag2utg(g, &n_utg);
}
void FermiAssembler::AddRead(const BamRecord& r) {
AddRead(UnalignedSequence(r.Qname(), r.Sequence(), r.Qualities())); // probably faster way
}
void FermiAssembler::AddRead(const UnalignedSequence& r) {
if (r.Seq.empty())
return;
if (r.Name.empty())
return;
// dynamically alloc the memory
if (m <= n_seqs)
m = m <= 0 ? 32 : (m*2); // if out of mem, double it
m_seqs = (fseq1_t*)realloc(m_seqs, m * sizeof(fseq1_t));
// add the name
m_names.push_back(r.Name);
// construct the seq
fseq1_t *s;
s = &m_seqs[n_seqs];
s->seq = strdup(r.Seq.c_str());
s->qual = r.Qual.empty() ? NULL : strdup(r.Qual.c_str());
s->l_seq = r.Seq.length();
size += m_seqs[n_seqs++].l_seq;
}
void FermiAssembler::AddReads(const UnalignedSequenceVector& v) {
// alloc the memory
m = n_seqs + v.size();
m_seqs = (fseq1_t*)realloc(m_seqs, m * sizeof(fseq1_t));
for (UnalignedSequenceVector::const_iterator r = v.begin(); r != v.end(); ++r) {
m_names.push_back(r->Name);
fseq1_t *s;
s = &m_seqs[n_seqs];
s->seq = strdup(r->Seq.c_str());
s->qual = strdup(r->Qual.c_str());
s->l_seq = r->Seq.length();
size += m_seqs[n_seqs++].l_seq;
}
}
void FermiAssembler::AddReads(const BamRecordVector& brv) {
// alloc the memory
m_seqs = (fseq1_t*)realloc(m_seqs, (n_seqs + brv.size()) * sizeof(fseq1_t));
uint64_t size = 0;
for (BamRecordVector::const_iterator r = brv.begin(); r != brv.end(); ++r) {
m_names.push_back(r->Qname());
fseq1_t *s;
s = &m_seqs[n_seqs];
s->seq = strdup(r->Sequence().c_str());
s->qual = strdup(r->Qualities().c_str());
s->l_seq = r->Sequence().length();
size += m_seqs[n_seqs++].l_seq;
}
}
void FermiAssembler::ClearContigs() {
fml_utg_destroy(n_utg, m_utgs);
m_utgs = 0;
n_utg = 0;
}
void FermiAssembler::ClearReads() {
if (!m_seqs)
return; //already cleared
for (size_t i = 0; i < n_seqs; ++i) {
fseq1_t * s = &m_seqs[i];
if (s->qual)
free(s->qual);
s->qual = NULL;
if (s->seq)
free(s->seq);
s->seq = NULL;
}
free(m_seqs);
m_seqs = NULL;
}
void FermiAssembler::CorrectReads() {
fml_correct(&opt, n_seqs, m_seqs);
}
void FermiAssembler::CorrectAndFilterReads() {
fml_fltuniq(&opt, n_seqs, m_seqs);
}
void FermiAssembler::PerformAssembly() {
m_utgs = fml_assemble(&opt, n_seqs, m_seqs, &n_utg); // assemble!
}
std::vector<std::string> FermiAssembler::GetContigs() const {
std::vector<std::string> c;
for (size_t i = 0; i < n_utg; ++i)
c.push_back(std::string(m_utgs[i].seq));
return c;
}
/*void FermiAssembler::count() {
// initialize BFC options
uint64_t tot_len = 0;
for (int i = 0; i < n_seqs; ++i)
tot_len += m_seqs[i].l_seq; // compute total length
int l_pre = tot_len - 8 < 20? tot_len - 8 : 20;
//bfc_ch_t *ch = fml_count(n_seqs, m_seqs, opt.ec_k, 20, l_pre, opt.n_threads);
//std::cerr << " ch->k " << ch->k << " ch->l_pre " << ch->l_pre << std::endl;
// directly from fml count
cnt_step_t cs;
cs.n_seqs = n_seqs, cs.seqs = m_seqs, cs.k = opt.ec_k, cs.q = 20;
cs.ch = bfc_ch_init(cs.k, l_pre);
}*/
UnalignedSequenceVector FermiAssembler::GetSequences() const {
UnalignedSequenceVector r;
for (size_t i = 0; i < n_seqs; ++i) {
fseq1_t * s = &m_seqs[i];
UnalignedSequence read;
if (s->seq)
read.Seq = (std::string(s->seq));
read.Name = m_names[i];
r.push_back(read);
}
return r;
}
}
void
SeqLib::FermiAssembler::WriteGFA(std::ostream &out)
{
int i, j;
out << "H\tVN:Z:1.0" << std::endl;
for (i = 0; i < n_utg; ++i) {
const fml_utg_t *u = m_utgs + i;
out << "S\t" << i << "\t";
out << u->seq << "\tLN:i:" << u->len << "\tRC:i:" << u->nsr << "\tPD:Z:";
out << u->cov << std::endl;
for (j = 0; j < u->n_ovlp[0] + u->n_ovlp[1]; ++j) {
fml_ovlp_t *o = &u->ovlp[j];
if (i < o->id) {
out << "L\t" << i << "\t"
<< "+-"[!o->from] << "\t" << o->id << "\t"
<< "+-"[o->to] << "\t" << o->len << "M" << std::endl;
}
}
}
}
|
jwalabroad/SnowTools
|
src/FermiAssembler.cpp
|
C++
|
gpl-2.0
| 5,311
|
# iRailTelegram
Telegram bot for iRail
|
MCautreels/iRailTelegram
|
README.md
|
Markdown
|
gpl-2.0
| 39
|
/*************************************************************************
bq Cervantes e-book reader application
Copyright (C) 2011-2013 Mundoreader, S.L
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.
You should have received a copy of the GNU General Public License
along with the source code. If not, see <http://www.gnu.org/licenses/>.
*************************************************************************/
#ifndef VIEWERSEARCHCONTEXTMENU_H
#define VIEWERSEARCHCONTEXTMENU_H
#include "ui_ViewerSearchContextMenu.h"
#include "PopUp.h"
class ViewerSearchContextMenu : public PopUp
,protected Ui::ViewerSearchContextMenu
{
Q_OBJECT
public:
ViewerSearchContextMenu(QWidget*);
virtual ~ViewerSearchContextMenu();
public slots:
void setCurrentResultIndex(int);
void setTotalResults(int);
signals:
void close();
void previousResult();
void nextResult();
void backToList();
protected:
void mousePressEvent(QMouseEvent *);
};
#endif // VIEWERSEARCHCONTEXTMENU_H
|
bq/cervantes
|
bqViewer/inc/ViewerSearchContextMenu.h
|
C
|
gpl-2.0
| 1,461
|
/* 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/kernel.h>
#include <linux/list.h>
#include <linux/platform_device.h>
#include <linux/msm_rotator.h>
#include <linux/ion.h>
#include <linux/gpio.h>
#include <linux/coresight.h>
#include <asm/clkdev.h>
#include <linux/msm_kgsl.h>
#include <linux/android_pmem.h>
#include <mach/irqs-8960.h>
#include <mach/dma.h>
#include <linux/dma-mapping.h>
#include <mach/board.h>
#include <mach/msm_iomap.h>
#include <mach/msm_hsusb.h>
#include <mach/msm_sps.h>
#include <mach/rpm.h>
#include <mach/msm_bus_board.h>
#include <mach/msm_memtypes.h>
#include <mach/msm_smd.h>
#include <mach/msm_dcvs.h>
#include <mach/msm_rtb.h>
#include <mach/msm_cache_dump.h>
#include <sound/msm-dai-q6.h>
#include <sound/apr_audio.h>
#include <mach/msm_tsif.h>
#include <mach/msm_serial_hs_lite.h>
#include "clock.h"
#include "devices.h"
#include "devices-msm8x60.h"
#include "footswitch.h"
#include "msm_watchdog.h"
#include "rpm_log.h"
#include "rpm_stats.h"
#include "pil-q6v4.h"
#include "scm-pas.h"
#include <mach/msm_dcvs.h>
#include <mach/iommu_domains.h>
#include <mach/msm_xo.h>
#ifdef CONFIG_MSM_MPM
#include <mach/mpm.h>
#endif
#ifdef CONFIG_MSM_DSPS
#include <mach/msm_dsps.h>
#endif
/* Address of GSBI blocks */
#define MSM_GSBI1_PHYS 0x16000000
#define MSM_GSBI2_PHYS 0x16100000
#define MSM_GSBI3_PHYS 0x16200000
#define MSM_GSBI4_PHYS 0x16300000
#define MSM_GSBI5_PHYS 0x16400000
#define MSM_GSBI6_PHYS 0x16500000
#define MSM_GSBI7_PHYS 0x16600000
#define MSM_GSBI8_PHYS 0x1A000000
#define MSM_GSBI9_PHYS 0x1A100000
#define MSM_GSBI10_PHYS 0x1A200000
#define MSM_GSBI11_PHYS 0x12440000
#define MSM_GSBI12_PHYS 0x12480000
#define MSM_UART2DM_PHYS (MSM_GSBI2_PHYS + 0x40000)
#define MSM_UART5DM_PHYS (MSM_GSBI5_PHYS + 0x40000)
#define MSM_UART6DM_PHYS (MSM_GSBI6_PHYS + 0x40000)
#define MSM_UART8DM_PHYS (MSM_GSBI8_PHYS + 0x40000)
#define MSM_UART9DM_PHYS (MSM_GSBI9_PHYS + 0x40000)
/* 20120704, sukkkong.kim@lge.com, Add IRRC UART [START] */
#ifdef CONFIG_LGE_IRRC
#define MSM_UART4DM_PHYS (MSM_GSBI4_PHYS + 0x40000)
#endif
/* 20120704, sukkkong.kim@lge.com, Add IRRC UART [END] */
/* GSBI QUP devices */
#define MSM_GSBI1_QUP_PHYS (MSM_GSBI1_PHYS + 0x80000)
#define MSM_GSBI2_QUP_PHYS (MSM_GSBI2_PHYS + 0x80000)
#define MSM_GSBI3_QUP_PHYS (MSM_GSBI3_PHYS + 0x80000)
#define MSM_GSBI4_QUP_PHYS (MSM_GSBI4_PHYS + 0x80000)
#define MSM_GSBI5_QUP_PHYS (MSM_GSBI5_PHYS + 0x80000)
#define MSM_GSBI6_QUP_PHYS (MSM_GSBI6_PHYS + 0x80000)
#define MSM_GSBI7_QUP_PHYS (MSM_GSBI7_PHYS + 0x80000)
#define MSM_GSBI8_QUP_PHYS (MSM_GSBI8_PHYS + 0x80000)
#define MSM_GSBI9_QUP_PHYS (MSM_GSBI9_PHYS + 0x80000)
#define MSM_GSBI10_QUP_PHYS (MSM_GSBI10_PHYS + 0x80000)
#define MSM_GSBI11_QUP_PHYS (MSM_GSBI11_PHYS + 0x20000)
#define MSM_GSBI12_QUP_PHYS (MSM_GSBI12_PHYS + 0x20000)
#define MSM_QUP_SIZE SZ_4K
#define MSM_PMIC1_SSBI_CMD_PHYS 0x00500000
#define MSM_PMIC2_SSBI_CMD_PHYS 0x00C00000
#define MSM_PMIC_SSBI_SIZE SZ_4K
#define MSM8960_HSUSB_PHYS 0x12500000
#define MSM8960_HSUSB_SIZE SZ_4K
static struct resource resources_otg[] = {
{
.start = MSM8960_HSUSB_PHYS,
.end = MSM8960_HSUSB_PHYS + MSM8960_HSUSB_SIZE,
.flags = IORESOURCE_MEM,
},
{
.start = USB1_HS_IRQ,
.end = USB1_HS_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm8960_device_otg = {
.name = "msm_otg",
.id = -1,
.num_resources = ARRAY_SIZE(resources_otg),
.resource = resources_otg,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
static struct resource resources_hsusb[] = {
{
.start = MSM8960_HSUSB_PHYS,
.end = MSM8960_HSUSB_PHYS + MSM8960_HSUSB_SIZE,
.flags = IORESOURCE_MEM,
},
{
.start = USB1_HS_IRQ,
.end = USB1_HS_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm8960_device_gadget_peripheral = {
.name = "msm_hsusb",
.id = -1,
.num_resources = ARRAY_SIZE(resources_hsusb),
.resource = resources_hsusb,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
static struct resource resources_hsusb_host[] = {
{
.start = MSM8960_HSUSB_PHYS,
.end = MSM8960_HSUSB_PHYS + MSM8960_HSUSB_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.start = USB1_HS_IRQ,
.end = USB1_HS_IRQ,
.flags = IORESOURCE_IRQ,
},
};
static u64 dma_mask = DMA_BIT_MASK(32);
struct platform_device msm_device_hsusb_host = {
.name = "msm_hsusb_host",
.id = -1,
.num_resources = ARRAY_SIZE(resources_hsusb_host),
.resource = resources_hsusb_host,
.dev = {
.dma_mask = &dma_mask,
.coherent_dma_mask = 0xffffffff,
},
};
static struct resource resources_hsic_host[] = {
{
.start = 0x12520000,
.end = 0x12520000 + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
{
.start = USB_HSIC_IRQ,
.end = USB_HSIC_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.start = MSM_GPIO_TO_INT(69),
.end = MSM_GPIO_TO_INT(69),
.name = "peripheral_status_irq",
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm_device_hsic_host = {
.name = "msm_hsic_host",
.id = -1,
.num_resources = ARRAY_SIZE(resources_hsic_host),
.resource = resources_hsic_host,
.dev = {
.dma_mask = &dma_mask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
};
struct platform_device msm8960_device_acpuclk = {
.name = "acpuclk-8960",
.id = -1,
};
#define SHARED_IMEM_TZ_BASE 0x2a03f720
static struct resource tzlog_resources[] = {
{
.start = SHARED_IMEM_TZ_BASE,
.end = SHARED_IMEM_TZ_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
};
struct platform_device msm_device_tz_log = {
.name = "tz_log",
.id = 0,
.num_resources = ARRAY_SIZE(tzlog_resources),
.resource = tzlog_resources,
};
static struct resource resources_uart_gsbi2[] = {
{
.start = MSM8960_GSBI2_UARTDM_IRQ,
.end = MSM8960_GSBI2_UARTDM_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.start = MSM_UART2DM_PHYS,
.end = MSM_UART2DM_PHYS + PAGE_SIZE - 1,
.name = "uartdm_resource",
.flags = IORESOURCE_MEM,
},
{
.start = MSM_GSBI2_PHYS,
.end = MSM_GSBI2_PHYS + PAGE_SIZE - 1,
.name = "gsbi_resource",
.flags = IORESOURCE_MEM,
},
};
struct platform_device msm8960_device_uart_gsbi2 = {
.name = "msm_serial_hsl",
.id = 0,
.num_resources = ARRAY_SIZE(resources_uart_gsbi2),
.resource = resources_uart_gsbi2,
};
/* GSBI 6 used into UARTDM Mode */
static struct resource msm_uart_dm6_resources[] = {
{
.start = MSM_UART6DM_PHYS,
.end = MSM_UART6DM_PHYS + PAGE_SIZE - 1,
.name = "uartdm_resource",
.flags = IORESOURCE_MEM,
},
{
.start = GSBI6_UARTDM_IRQ,
.end = GSBI6_UARTDM_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.start = MSM_GSBI6_PHYS,
.end = MSM_GSBI6_PHYS + 4 - 1,
.name = "gsbi_resource",
.flags = IORESOURCE_MEM,
},
{
.start = DMOV_HSUART_GSBI6_TX_CHAN,
.end = DMOV_HSUART_GSBI6_RX_CHAN,
.name = "uartdm_channels",
.flags = IORESOURCE_DMA,
},
{
.start = DMOV_HSUART_GSBI6_TX_CRCI,
.end = DMOV_HSUART_GSBI6_RX_CRCI,
.name = "uartdm_crci",
.flags = IORESOURCE_DMA,
},
};
static u64 msm_uart_dm6_dma_mask = DMA_BIT_MASK(32);
struct platform_device msm_device_uart_dm6 = {
.name = "msm_serial_hs",
.id = 0,
.num_resources = ARRAY_SIZE(msm_uart_dm6_resources),
.resource = msm_uart_dm6_resources,
.dev = {
.dma_mask = &msm_uart_dm6_dma_mask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
};
/*
* GSBI 9 used into UARTDM Mode
* For 8960 Fusion 2.2 Primary IPC
*/
static struct resource msm_uart_dm9_resources[] = {
{
.start = MSM_UART9DM_PHYS,
.end = MSM_UART9DM_PHYS + PAGE_SIZE - 1,
.name = "uartdm_resource",
.flags = IORESOURCE_MEM,
},
{
.start = GSBI9_UARTDM_IRQ,
.end = GSBI9_UARTDM_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.start = MSM_GSBI9_PHYS,
.end = MSM_GSBI9_PHYS + 4 - 1,
.name = "gsbi_resource",
.flags = IORESOURCE_MEM,
},
{
.start = DMOV_HSUART_GSBI9_TX_CHAN,
.end = DMOV_HSUART_GSBI9_RX_CHAN,
.name = "uartdm_channels",
.flags = IORESOURCE_DMA,
},
{
.start = DMOV_HSUART_GSBI9_TX_CRCI,
.end = DMOV_HSUART_GSBI9_RX_CRCI,
.name = "uartdm_crci",
.flags = IORESOURCE_DMA,
},
};
static u64 msm_uart_dm9_dma_mask = DMA_BIT_MASK(32);
struct platform_device msm_device_uart_dm9 = {
.name = "msm_serial_hs",
.id = 1,
.num_resources = ARRAY_SIZE(msm_uart_dm9_resources),
.resource = msm_uart_dm9_resources,
.dev = {
.dma_mask = &msm_uart_dm9_dma_mask,
.coherent_dma_mask = DMA_BIT_MASK(32),
},
};
static struct resource resources_uart_gsbi5[] = {
{
.start = GSBI5_UARTDM_IRQ,
.end = GSBI5_UARTDM_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.start = MSM_UART5DM_PHYS,
.end = MSM_UART5DM_PHYS + PAGE_SIZE - 1,
.name = "uartdm_resource",
.flags = IORESOURCE_MEM,
},
{
.start = MSM_GSBI5_PHYS,
.end = MSM_GSBI5_PHYS + PAGE_SIZE - 1,
.name = "gsbi_resource",
.flags = IORESOURCE_MEM,
},
};
struct platform_device msm8960_device_uart_gsbi5 = {
.name = "msm_serial_hsl",
.id = 0,
.num_resources = ARRAY_SIZE(resources_uart_gsbi5),
.resource = resources_uart_gsbi5,
};
static struct msm_serial_hslite_platform_data uart_gsbi8_pdata = {
.line = 0,
};
static struct resource resources_uart_gsbi8[] = {
{
.start = GSBI8_UARTDM_IRQ,
.end = GSBI8_UARTDM_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.start = MSM_UART8DM_PHYS,
.end = MSM_UART8DM_PHYS + PAGE_SIZE - 1,
.name = "uartdm_resource",
.flags = IORESOURCE_MEM,
},
{
.start = MSM_GSBI8_PHYS,
.end = MSM_GSBI8_PHYS + PAGE_SIZE - 1,
.name = "gsbi_resource",
.flags = IORESOURCE_MEM,
},
};
struct platform_device msm8960_device_uart_gsbi8 = {
.name = "msm_serial_hsl",
.id = 1,
.num_resources = ARRAY_SIZE(resources_uart_gsbi8),
.resource = resources_uart_gsbi8,
.dev.platform_data = &uart_gsbi8_pdata,
};
/* 20111205, chaeuk.lee@lge.com, Add IrDA UART [START] */
#ifdef CONFIG_LGE_IRDA
static struct resource resources_irda_gsbi9[] = {
{
.start = GSBI9_UARTDM_IRQ,
.end = GSBI9_UARTDM_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.start = MSM_UART9DM_PHYS,
.end = MSM_UART9DM_PHYS + PAGE_SIZE - 1,
.name = "uartdm_resource",
.flags = IORESOURCE_MEM,
},
{
.start = MSM_GSBI9_PHYS,
.end = MSM_GSBI9_PHYS + PAGE_SIZE - 1,
.name = "gsbi_resource",
.flags = IORESOURCE_MEM,
},
};
struct platform_device msm8960_device_irda_gsbi9 = {
.name = "msm_serial_hsl",
.id = 2,
.num_resources = ARRAY_SIZE(resources_irda_gsbi9),
.resource = resources_irda_gsbi9,
};
#endif
/* 20111205, chaeuk.lee@lge.com, Add IrDA UART [END] */
/* 20120704, sukkkong.kim@lge.com, Add IRRC UART [START] */
#ifdef CONFIG_LGE_IRRC
static struct resource resources_uart_gsbi4[] = {
{
.start = GSBI4_UARTDM_IRQ,
.end = GSBI4_UARTDM_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.start = MSM_UART4DM_PHYS,
.end = MSM_UART4DM_PHYS + PAGE_SIZE - 1,
.name = "uartdm_resource",
.flags = IORESOURCE_MEM,
},
{
.start = MSM_GSBI4_PHYS,
.end = MSM_GSBI4_PHYS + PAGE_SIZE - 1,
.name = "gsbi_resource",
.flags = IORESOURCE_MEM,
},
};
struct platform_device msm8960_device_uart_gsbi4= {
.name = "msm_serial_hsl",
.id = 1,
.num_resources = ARRAY_SIZE(resources_uart_gsbi4),
.resource = resources_uart_gsbi4,
};
#endif
/* 20120704, sukkkong.kim@lge.com, Add IRRC UART [END] */
/* MSM Video core device */
#ifdef CONFIG_MSM_BUS_SCALING
static struct msm_bus_vectors vidc_init_vectors[] = {
{
.src = MSM_BUS_MASTER_HD_CODEC_PORT0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = 0,
},
{
.src = MSM_BUS_MASTER_HD_CODEC_PORT1,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = 0,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = 0,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = 0,
},
};
static struct msm_bus_vectors vidc_venc_vga_vectors[] = {
{
.src = MSM_BUS_MASTER_HD_CODEC_PORT0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 54525952,
.ib = 436207616,
},
{
.src = MSM_BUS_MASTER_HD_CODEC_PORT1,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 72351744,
.ib = 289406976,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 500000,
.ib = 1000000,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 500000,
.ib = 1000000,
},
};
static struct msm_bus_vectors vidc_vdec_vga_vectors[] = {
{
.src = MSM_BUS_MASTER_HD_CODEC_PORT0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 40894464,
.ib = 327155712,
},
{
.src = MSM_BUS_MASTER_HD_CODEC_PORT1,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 48234496,
.ib = 192937984,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 500000,
.ib = 2000000,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 500000,
.ib = 2000000,
},
};
static struct msm_bus_vectors vidc_venc_720p_vectors[] = {
{
.src = MSM_BUS_MASTER_HD_CODEC_PORT0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 163577856,
.ib = 1308622848,
},
{
.src = MSM_BUS_MASTER_HD_CODEC_PORT1,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 219152384,
.ib = 876609536,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 1750000,
.ib = 3500000,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 1750000,
.ib = 3500000,
},
};
static struct msm_bus_vectors vidc_vdec_720p_vectors[] = {
{
.src = MSM_BUS_MASTER_HD_CODEC_PORT0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 121634816,
.ib = 973078528,
},
{
.src = MSM_BUS_MASTER_HD_CODEC_PORT1,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 155189248,
.ib = 620756992,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 1750000,
.ib = 7000000,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 1750000,
.ib = 7000000,
},
};
static struct msm_bus_vectors vidc_venc_1080p_vectors[] = {
{
.src = MSM_BUS_MASTER_HD_CODEC_PORT0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 372244480,
.ib = 2560000000U,
},
{
.src = MSM_BUS_MASTER_HD_CODEC_PORT1,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 501219328,
.ib = 2560000000U,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 2500000,
.ib = 5000000,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 2500000,
.ib = 5000000,
},
};
static struct msm_bus_vectors vidc_vdec_1080p_vectors[] = {
{
.src = MSM_BUS_MASTER_HD_CODEC_PORT0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 222298112,
.ib = 2560000000U,
},
{
.src = MSM_BUS_MASTER_HD_CODEC_PORT1,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 330301440,
.ib = 2560000000U,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 2500000,
.ib = 700000000,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 2500000,
.ib = 10000000,
},
};
static struct msm_bus_vectors vidc_venc_1080p_turbo_vectors[] = {
{
.src = MSM_BUS_MASTER_HD_CODEC_PORT0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 222298112,
.ib = 3522000000U,
},
{
.src = MSM_BUS_MASTER_HD_CODEC_PORT1,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 330301440,
.ib = 3522000000U,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 2500000,
.ib = 700000000,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 2500000,
.ib = 10000000,
},
};
static struct msm_bus_vectors vidc_vdec_1080p_turbo_vectors[] = {
{
.src = MSM_BUS_MASTER_HD_CODEC_PORT0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 222298112,
.ib = 3522000000U,
},
{
.src = MSM_BUS_MASTER_HD_CODEC_PORT1,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 330301440,
.ib = 3522000000U,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 2500000,
.ib = 700000000,
},
{
.src = MSM_BUS_MASTER_AMPSS_M0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 2500000,
.ib = 10000000,
},
};
static struct msm_bus_paths vidc_bus_client_config[] = {
{
ARRAY_SIZE(vidc_init_vectors),
vidc_init_vectors,
},
{
ARRAY_SIZE(vidc_venc_vga_vectors),
vidc_venc_vga_vectors,
},
{
ARRAY_SIZE(vidc_vdec_vga_vectors),
vidc_vdec_vga_vectors,
},
{
ARRAY_SIZE(vidc_venc_720p_vectors),
vidc_venc_720p_vectors,
},
{
ARRAY_SIZE(vidc_vdec_720p_vectors),
vidc_vdec_720p_vectors,
},
{
ARRAY_SIZE(vidc_venc_1080p_vectors),
vidc_venc_1080p_vectors,
},
{
ARRAY_SIZE(vidc_vdec_1080p_vectors),
vidc_vdec_1080p_vectors,
},
{
ARRAY_SIZE(vidc_venc_1080p_turbo_vectors),
vidc_vdec_1080p_turbo_vectors,
},
{
ARRAY_SIZE(vidc_vdec_1080p_turbo_vectors),
vidc_vdec_1080p_turbo_vectors,
},
};
static struct msm_bus_scale_pdata vidc_bus_client_data = {
vidc_bus_client_config,
ARRAY_SIZE(vidc_bus_client_config),
.name = "vidc",
};
#endif
#ifdef CONFIG_HW_RANDOM_MSM
/* PRNG device */
#define MSM_PRNG_PHYS 0x1A500000
static struct resource rng_resources = {
.flags = IORESOURCE_MEM,
.start = MSM_PRNG_PHYS,
.end = MSM_PRNG_PHYS + SZ_512 - 1,
};
struct platform_device msm_device_rng = {
.name = "msm_rng",
.id = 0,
.num_resources = 1,
.resource = &rng_resources,
};
#endif
#define MSM_VIDC_BASE_PHYS 0x04400000
#define MSM_VIDC_BASE_SIZE 0x00100000
static struct resource msm_device_vidc_resources[] = {
{
.start = MSM_VIDC_BASE_PHYS,
.end = MSM_VIDC_BASE_PHYS + MSM_VIDC_BASE_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.start = VCODEC_IRQ,
.end = VCODEC_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct msm_vidc_platform_data vidc_platform_data = {
#ifdef CONFIG_MSM_BUS_SCALING
.vidc_bus_client_pdata = &vidc_bus_client_data,
#endif
#ifdef CONFIG_MSM_MULTIMEDIA_USE_ION
.memtype = ION_CP_MM_HEAP_ID,
.enable_ion = 1,
.cp_enabled = 1,
#else
.memtype = MEMTYPE_EBI1,
.enable_ion = 0,
#endif
.disable_dmx = 0,
.disable_fullhd = 0,
.cont_mode_dpb_count = 18,
.fw_addr = 0x9fe00000,
};
struct platform_device msm_device_vidc = {
.name = "msm_vidc",
.id = 0,
.num_resources = ARRAY_SIZE(msm_device_vidc_resources),
.resource = msm_device_vidc_resources,
.dev = {
.platform_data = &vidc_platform_data,
},
};
#define MSM_SDC1_BASE 0x12400000
#define MSM_SDC1_DML_BASE (MSM_SDC1_BASE + 0x800)
#define MSM_SDC1_BAM_BASE (MSM_SDC1_BASE + 0x2000)
#define MSM_SDC2_BASE 0x12140000
#define MSM_SDC2_DML_BASE (MSM_SDC2_BASE + 0x800)
#define MSM_SDC2_BAM_BASE (MSM_SDC2_BASE + 0x2000)
#define MSM_SDC3_BASE 0x12180000
#define MSM_SDC3_DML_BASE (MSM_SDC3_BASE + 0x800)
#define MSM_SDC3_BAM_BASE (MSM_SDC3_BASE + 0x2000)
#define MSM_SDC4_BASE 0x121C0000
#define MSM_SDC4_DML_BASE (MSM_SDC4_BASE + 0x800)
#define MSM_SDC4_BAM_BASE (MSM_SDC4_BASE + 0x2000)
#define MSM_SDC5_BASE 0x12200000
#define MSM_SDC5_DML_BASE (MSM_SDC5_BASE + 0x800)
#define MSM_SDC5_BAM_BASE (MSM_SDC5_BASE + 0x2000)
static struct resource resources_sdc1[] = {
{
.name = "core_mem",
.flags = IORESOURCE_MEM,
.start = MSM_SDC1_BASE,
.end = MSM_SDC1_DML_BASE - 1,
},
{
.name = "core_irq",
.flags = IORESOURCE_IRQ,
.start = SDC1_IRQ_0,
.end = SDC1_IRQ_0
},
#ifdef CONFIG_MMC_MSM_SPS_SUPPORT
{
.name = "sdcc_dml_addr",
.start = MSM_SDC1_DML_BASE,
.end = MSM_SDC1_BAM_BASE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "sdcc_bam_addr",
.start = MSM_SDC1_BAM_BASE,
.end = MSM_SDC1_BAM_BASE + (2 * SZ_4K) - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "sdcc_bam_irq",
.start = SDC1_BAM_IRQ,
.end = SDC1_BAM_IRQ,
.flags = IORESOURCE_IRQ,
},
#endif
};
static struct resource resources_sdc2[] = {
{
.name = "core_mem",
.flags = IORESOURCE_MEM,
.start = MSM_SDC2_BASE,
.end = MSM_SDC2_DML_BASE - 1,
},
{
.name = "core_irq",
.flags = IORESOURCE_IRQ,
.start = SDC2_IRQ_0,
.end = SDC2_IRQ_0
},
#ifdef CONFIG_MMC_MSM_SPS_SUPPORT
{
.name = "sdcc_dml_addr",
.start = MSM_SDC2_DML_BASE,
.end = MSM_SDC2_BAM_BASE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "sdcc_bam_addr",
.start = MSM_SDC2_BAM_BASE,
.end = MSM_SDC2_BAM_BASE + (2 * SZ_4K) - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "sdcc_bam_irq",
.start = SDC2_BAM_IRQ,
.end = SDC2_BAM_IRQ,
.flags = IORESOURCE_IRQ,
},
#endif
};
static struct resource resources_sdc3[] = {
{
.name = "core_mem",
.flags = IORESOURCE_MEM,
.start = MSM_SDC3_BASE,
.end = MSM_SDC3_DML_BASE - 1,
},
{
.name = "core_irq",
.flags = IORESOURCE_IRQ,
.start = SDC3_IRQ_0,
.end = SDC3_IRQ_0
},
#ifdef CONFIG_MMC_MSM_SPS_SUPPORT
{
.name = "sdcc_dml_addr",
.start = MSM_SDC3_DML_BASE,
.end = MSM_SDC3_BAM_BASE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "sdcc_bam_addr",
.start = MSM_SDC3_BAM_BASE,
.end = MSM_SDC3_BAM_BASE + (2 * SZ_4K) - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "sdcc_bam_irq",
.start = SDC3_BAM_IRQ,
.end = SDC3_BAM_IRQ,
.flags = IORESOURCE_IRQ,
},
#endif
};
static struct resource resources_sdc4[] = {
{
.name = "core_mem",
.flags = IORESOURCE_MEM,
.start = MSM_SDC4_BASE,
.end = MSM_SDC4_DML_BASE - 1,
},
{
.name = "core_irq",
.flags = IORESOURCE_IRQ,
.start = SDC4_IRQ_0,
.end = SDC4_IRQ_0
},
#ifdef CONFIG_MMC_MSM_SPS_SUPPORT
{
.name = "sdcc_dml_addr",
.start = MSM_SDC4_DML_BASE,
.end = MSM_SDC4_BAM_BASE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "sdcc_bam_addr",
.start = MSM_SDC4_BAM_BASE,
.end = MSM_SDC4_BAM_BASE + (2 * SZ_4K) - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "sdcc_bam_irq",
.start = SDC4_BAM_IRQ,
.end = SDC4_BAM_IRQ,
.flags = IORESOURCE_IRQ,
},
#endif
};
static struct resource resources_sdc5[] = {
{
.name = "core_mem",
.flags = IORESOURCE_MEM,
.start = MSM_SDC5_BASE,
.end = MSM_SDC5_DML_BASE - 1,
},
{
.name = "core_irq",
.flags = IORESOURCE_IRQ,
.start = SDC5_IRQ_0,
.end = SDC5_IRQ_0
},
#ifdef CONFIG_MMC_MSM_SPS_SUPPORT
{
.name = "sdcc_dml_addr",
.start = MSM_SDC5_DML_BASE,
.end = MSM_SDC5_BAM_BASE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "sdcc_bam_addr",
.start = MSM_SDC5_BAM_BASE,
.end = MSM_SDC5_BAM_BASE + (2 * SZ_4K) - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "sdcc_bam_irq",
.start = SDC5_BAM_IRQ,
.end = SDC5_BAM_IRQ,
.flags = IORESOURCE_IRQ,
},
#endif
};
struct platform_device msm_device_sdc1 = {
.name = "msm_sdcc",
.id = 1,
.num_resources = ARRAY_SIZE(resources_sdc1),
.resource = resources_sdc1,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
struct platform_device msm_device_sdc2 = {
.name = "msm_sdcc",
.id = 2,
.num_resources = ARRAY_SIZE(resources_sdc2),
.resource = resources_sdc2,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
struct platform_device msm_device_sdc3 = {
.name = "msm_sdcc",
.id = 3,
.num_resources = ARRAY_SIZE(resources_sdc3),
.resource = resources_sdc3,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
struct platform_device msm_device_sdc4 = {
.name = "msm_sdcc",
.id = 4,
.num_resources = ARRAY_SIZE(resources_sdc4),
.resource = resources_sdc4,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
struct platform_device msm_device_sdc5 = {
.name = "msm_sdcc",
.id = 5,
.num_resources = ARRAY_SIZE(resources_sdc5),
.resource = resources_sdc5,
.dev = {
.coherent_dma_mask = 0xffffffff,
},
};
#define MSM_LPASS_QDSP6SS_PHYS 0x28800000
#define SFAB_LPASS_Q6_ACLK_CTL (MSM_CLK_CTL_BASE + 0x23A0)
static struct resource msm_8960_q6_lpass_resources[] = {
{
.start = MSM_LPASS_QDSP6SS_PHYS,
.end = MSM_LPASS_QDSP6SS_PHYS + SZ_256 - 1,
.flags = IORESOURCE_MEM,
},
};
static struct pil_q6v4_pdata msm_8960_q6_lpass_data = {
.strap_tcm_base = 0x01460000,
.strap_ahb_upper = 0x00290000,
.strap_ahb_lower = 0x00000280,
.aclk_reg = SFAB_LPASS_Q6_ACLK_CTL,
.name = "q6",
.pas_id = PAS_Q6,
.bus_port = MSM_BUS_MASTER_LPASS_PROC,
};
struct platform_device msm_8960_q6_lpass = {
.name = "pil_qdsp6v4",
.id = 0,
.num_resources = ARRAY_SIZE(msm_8960_q6_lpass_resources),
.resource = msm_8960_q6_lpass_resources,
.dev.platform_data = &msm_8960_q6_lpass_data,
};
#define MSM_MSS_ENABLE_PHYS 0x08B00000
#define MSM_FW_QDSP6SS_PHYS 0x08800000
#define MSS_Q6FW_JTAG_CLK_CTL (MSM_CLK_CTL_BASE + 0x2C6C)
#define SFAB_MSS_Q6_FW_ACLK_CTL (MSM_CLK_CTL_BASE + 0x2044)
static struct resource msm_8960_q6_mss_fw_resources[] = {
{
.start = MSM_FW_QDSP6SS_PHYS,
.end = MSM_FW_QDSP6SS_PHYS + SZ_256 - 1,
.flags = IORESOURCE_MEM,
},
{
.start = MSM_MSS_ENABLE_PHYS,
.end = MSM_MSS_ENABLE_PHYS + 4 - 1,
.flags = IORESOURCE_MEM,
},
};
static struct pil_q6v4_pdata msm_8960_q6_mss_fw_data = {
.strap_tcm_base = 0x00400000,
.strap_ahb_upper = 0x00090000,
.strap_ahb_lower = 0x00000080,
.aclk_reg = SFAB_MSS_Q6_FW_ACLK_CTL,
.jtag_clk_reg = MSS_Q6FW_JTAG_CLK_CTL,
.xo1_id = MSM_XO_TCXO_A0,
.xo2_id = MSM_XO_TCXO_A1,
.name = "modem_fw",
.depends = "q6",
.pas_id = PAS_MODEM_FW,
.bus_port = MSM_BUS_MASTER_MSS_FW_PROC,
};
struct platform_device msm_8960_q6_mss_fw = {
.name = "pil_qdsp6v4",
.id = 1,
.num_resources = ARRAY_SIZE(msm_8960_q6_mss_fw_resources),
.resource = msm_8960_q6_mss_fw_resources,
.dev.platform_data = &msm_8960_q6_mss_fw_data,
};
#define MSM_SW_QDSP6SS_PHYS 0x08900000
#define SFAB_MSS_Q6_SW_ACLK_CTL (MSM_CLK_CTL_BASE + 0x2040)
#define MSS_Q6SW_JTAG_CLK_CTL (MSM_CLK_CTL_BASE + 0x2C68)
static struct resource msm_8960_q6_mss_sw_resources[] = {
{
.start = MSM_SW_QDSP6SS_PHYS,
.end = MSM_SW_QDSP6SS_PHYS + SZ_256 - 1,
.flags = IORESOURCE_MEM,
},
{
.start = MSM_MSS_ENABLE_PHYS,
.end = MSM_MSS_ENABLE_PHYS + 4 - 1,
.flags = IORESOURCE_MEM,
},
};
static struct pil_q6v4_pdata msm_8960_q6_mss_sw_data = {
.strap_tcm_base = 0x00420000,
.strap_ahb_upper = 0x00090000,
.strap_ahb_lower = 0x00000080,
.aclk_reg = SFAB_MSS_Q6_SW_ACLK_CTL,
.jtag_clk_reg = MSS_Q6SW_JTAG_CLK_CTL,
.name = "modem",
.depends = "modem_fw",
.pas_id = PAS_MODEM_SW,
.bus_port = MSM_BUS_MASTER_MSS_SW_PROC,
};
struct platform_device msm_8960_q6_mss_sw = {
.name = "pil_qdsp6v4",
.id = 2,
.num_resources = ARRAY_SIZE(msm_8960_q6_mss_sw_resources),
.resource = msm_8960_q6_mss_sw_resources,
.dev.platform_data = &msm_8960_q6_mss_sw_data,
};
static struct resource msm_8960_riva_resources[] = {
{
.start = 0x03204000,
.end = 0x03204000 + SZ_256 - 1,
.flags = IORESOURCE_MEM,
},
};
struct platform_device msm_8960_riva = {
.name = "pil_riva",
.id = -1,
.num_resources = ARRAY_SIZE(msm_8960_riva_resources),
.resource = msm_8960_riva_resources,
};
struct platform_device msm_pil_tzapps = {
.name = "pil_tzapps",
.id = -1,
};
struct platform_device msm_pil_dsps = {
.name = "pil_dsps",
.id = -1,
.dev.platform_data = "dsps",
};
struct platform_device msm_pil_vidc = {
.name = "pil_vidc",
.id = -1,
};
static struct resource smd_resource[] = {
{
.name = "a9_m2a_0",
.start = INT_A9_M2A_0,
.flags = IORESOURCE_IRQ,
},
{
.name = "a9_m2a_5",
.start = INT_A9_M2A_5,
.flags = IORESOURCE_IRQ,
},
{
.name = "adsp_a11",
.start = INT_ADSP_A11,
.flags = IORESOURCE_IRQ,
},
{
.name = "adsp_a11_smsm",
.start = INT_ADSP_A11_SMSM,
.flags = IORESOURCE_IRQ,
},
{
.name = "dsps_a11",
.start = INT_DSPS_A11,
.flags = IORESOURCE_IRQ,
},
{
.name = "dsps_a11_smsm",
.start = INT_DSPS_A11_SMSM,
.flags = IORESOURCE_IRQ,
},
{
.name = "wcnss_a11",
.start = INT_WCNSS_A11,
.flags = IORESOURCE_IRQ,
},
{
.name = "wcnss_a11_smsm",
.start = INT_WCNSS_A11_SMSM,
.flags = IORESOURCE_IRQ,
},
};
static struct smd_subsystem_config smd_config_list[] = {
{
.irq_config_id = SMD_MODEM,
.subsys_name = "modem",
.edge = SMD_APPS_MODEM,
.smd_int.irq_name = "a9_m2a_0",
.smd_int.flags = IRQF_TRIGGER_RISING,
.smd_int.irq_id = -1,
.smd_int.device_name = "smd_dev",
.smd_int.dev_id = 0,
.smd_int.out_bit_pos = 1 << 3,
.smd_int.out_base = (void __iomem *)MSM_APCS_GCC_BASE,
.smd_int.out_offset = 0x8,
.smsm_int.irq_name = "a9_m2a_5",
.smsm_int.flags = IRQF_TRIGGER_RISING,
.smsm_int.irq_id = -1,
.smsm_int.device_name = "smd_smsm",
.smsm_int.dev_id = 0,
.smsm_int.out_bit_pos = 1 << 4,
.smsm_int.out_base = (void __iomem *)MSM_APCS_GCC_BASE,
.smsm_int.out_offset = 0x8,
},
{
.irq_config_id = SMD_Q6,
.subsys_name = "q6",
.edge = SMD_APPS_QDSP,
.smd_int.irq_name = "adsp_a11",
.smd_int.flags = IRQF_TRIGGER_RISING,
.smd_int.irq_id = -1,
.smd_int.device_name = "smd_dev",
.smd_int.dev_id = 0,
.smd_int.out_bit_pos = 1 << 15,
.smd_int.out_base = (void __iomem *)MSM_APCS_GCC_BASE,
.smd_int.out_offset = 0x8,
.smsm_int.irq_name = "adsp_a11_smsm",
.smsm_int.flags = IRQF_TRIGGER_RISING,
.smsm_int.irq_id = -1,
.smsm_int.device_name = "smd_smsm",
.smsm_int.dev_id = 0,
.smsm_int.out_bit_pos = 1 << 14,
.smsm_int.out_base = (void __iomem *)MSM_APCS_GCC_BASE,
.smsm_int.out_offset = 0x8,
},
{
.irq_config_id = SMD_DSPS,
.subsys_name = "dsps",
.edge = SMD_APPS_DSPS,
.smd_int.irq_name = "dsps_a11",
.smd_int.flags = IRQF_TRIGGER_RISING,
.smd_int.irq_id = -1,
.smd_int.device_name = "smd_dev",
.smd_int.dev_id = 0,
.smd_int.out_bit_pos = 1,
.smd_int.out_base = (void __iomem *)MSM_SIC_NON_SECURE_BASE,
.smd_int.out_offset = 0x4080,
.smsm_int.irq_name = "dsps_a11_smsm",
.smsm_int.flags = IRQF_TRIGGER_RISING,
.smsm_int.irq_id = -1,
.smsm_int.device_name = "smd_smsm",
.smsm_int.dev_id = 0,
.smsm_int.out_bit_pos = 1,
.smsm_int.out_base = (void __iomem *)MSM_SIC_NON_SECURE_BASE,
.smsm_int.out_offset = 0x4094,
},
{
.irq_config_id = SMD_WCNSS,
.subsys_name = "wcnss",
.edge = SMD_APPS_WCNSS,
.smd_int.irq_name = "wcnss_a11",
.smd_int.flags = IRQF_TRIGGER_RISING,
.smd_int.irq_id = -1,
.smd_int.device_name = "smd_dev",
.smd_int.dev_id = 0,
.smd_int.out_bit_pos = 1 << 25,
.smd_int.out_base = (void __iomem *)MSM_APCS_GCC_BASE,
.smd_int.out_offset = 0x8,
.smsm_int.irq_name = "wcnss_a11_smsm",
.smsm_int.flags = IRQF_TRIGGER_RISING,
.smsm_int.irq_id = -1,
.smsm_int.device_name = "smd_smsm",
.smsm_int.dev_id = 0,
.smsm_int.out_bit_pos = 1 << 23,
.smsm_int.out_base = (void __iomem *)MSM_APCS_GCC_BASE,
.smsm_int.out_offset = 0x8,
},
};
static struct smd_subsystem_restart_config smd_ssr_config = {
.disable_smsm_reset_handshake = 1,
};
static struct smd_platform smd_platform_data = {
.num_ss_configs = ARRAY_SIZE(smd_config_list),
.smd_ss_configs = smd_config_list,
.smd_ssr_config = &smd_ssr_config,
};
struct platform_device msm_device_smd = {
.name = "msm_smd",
.id = -1,
.resource = smd_resource,
.num_resources = ARRAY_SIZE(smd_resource),
.dev = {
.platform_data = &smd_platform_data,
},
};
struct platform_device msm_device_bam_dmux = {
.name = "BAM_RMNT",
.id = -1,
};
static struct msm_watchdog_pdata msm_watchdog_pdata = {
.pet_time = 10000,
.bark_time = 16000, // set 11s to 16s
.has_secure = true,
};
struct platform_device msm8960_device_watchdog = {
.name = "msm_watchdog",
.id = -1,
.dev = {
.platform_data = &msm_watchdog_pdata,
},
};
static struct resource msm_dmov_resource[] = {
{
.start = ADM_0_SCSS_1_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.start = 0x18320000,
.end = 0x18320000 + SZ_1M - 1,
.flags = IORESOURCE_MEM,
},
};
static struct msm_dmov_pdata msm_dmov_pdata = {
.sd = 1,
.sd_size = 0x800,
};
struct platform_device msm8960_device_dmov = {
.name = "msm_dmov",
.id = -1,
.resource = msm_dmov_resource,
.num_resources = ARRAY_SIZE(msm_dmov_resource),
.dev = {
.platform_data = &msm_dmov_pdata,
},
};
static struct platform_device *msm_sdcc_devices[] __initdata = {
&msm_device_sdc1,
&msm_device_sdc2,
&msm_device_sdc3,
&msm_device_sdc4,
&msm_device_sdc5,
};
int __init msm_add_sdcc(unsigned int controller, struct mmc_platform_data *plat)
{
struct platform_device *pdev;
if (controller < 1 || controller > 5)
return -EINVAL;
pdev = msm_sdcc_devices[controller-1];
pdev->dev.platform_data = plat;
return platform_device_register(pdev);
}
static struct resource resources_qup_i2c_gsbi4[] = {
{
.name = "gsbi_qup_i2c_addr",
.start = MSM_GSBI4_PHYS,
.end = MSM_GSBI4_PHYS + 4 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_phys_addr",
.start = MSM_GSBI4_QUP_PHYS,
.end = MSM_GSBI4_QUP_PHYS + MSM_QUP_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_err_intr",
.start = GSBI4_QUP_IRQ,
.end = GSBI4_QUP_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm8960_device_qup_i2c_gsbi4 = {
.name = "qup_i2c",
.id = 4,
.num_resources = ARRAY_SIZE(resources_qup_i2c_gsbi4),
.resource = resources_qup_i2c_gsbi4,
};
static struct resource resources_qup_i2c_gsbi3[] = {
{
.name = "gsbi_qup_i2c_addr",
.start = MSM_GSBI3_PHYS,
.end = MSM_GSBI3_PHYS + 4 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_phys_addr",
.start = MSM_GSBI3_QUP_PHYS,
.end = MSM_GSBI3_QUP_PHYS + MSM_QUP_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_err_intr",
.start = GSBI3_QUP_IRQ,
.end = GSBI3_QUP_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm8960_device_qup_i2c_gsbi3 = {
.name = "qup_i2c",
.id = 3,
.num_resources = ARRAY_SIZE(resources_qup_i2c_gsbi3),
.resource = resources_qup_i2c_gsbi3,
};
#ifdef CONFIG_LGE_AUDIO_TPA2028D
static struct resource resources_qup_i2c_gsbi9[] = {
{
.name = "gsbi_qup_i2c_addr",
.start = MSM_GSBI9_PHYS,
.end = MSM_GSBI9_PHYS + 4 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_phys_addr",
.start = MSM_GSBI9_QUP_PHYS,
.end = MSM_GSBI9_QUP_PHYS + MSM_QUP_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_err_intr",
.start = GSBI9_QUP_IRQ,
.end = GSBI9_QUP_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm8960_device_qup_i2c_gsbi9 = {
.name = "qup_i2c",
.id = 9,
.num_resources = ARRAY_SIZE(resources_qup_i2c_gsbi9),
.resource = resources_qup_i2c_gsbi9,
};
#endif
static struct resource resources_qup_i2c_gsbi10[] = {
{
.name = "gsbi_qup_i2c_addr",
.start = MSM_GSBI10_PHYS,
.end = MSM_GSBI10_PHYS + 4 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_phys_addr",
.start = MSM_GSBI10_QUP_PHYS,
.end = MSM_GSBI10_QUP_PHYS + MSM_QUP_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_err_intr",
.start = GSBI10_QUP_IRQ,
.end = GSBI10_QUP_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm8960_device_qup_i2c_gsbi10 = {
.name = "qup_i2c",
.id = 10,
.num_resources = ARRAY_SIZE(resources_qup_i2c_gsbi10),
.resource = resources_qup_i2c_gsbi10,
};
static struct resource resources_qup_i2c_gsbi12[] = {
{
.name = "gsbi_qup_i2c_addr",
.start = MSM_GSBI12_PHYS,
.end = MSM_GSBI12_PHYS + 4 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_phys_addr",
.start = MSM_GSBI12_QUP_PHYS,
.end = MSM_GSBI12_QUP_PHYS + MSM_QUP_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_err_intr",
.start = GSBI12_QUP_IRQ,
.end = GSBI12_QUP_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm8960_device_qup_i2c_gsbi12 = {
.name = "qup_i2c",
.id = 12,
.num_resources = ARRAY_SIZE(resources_qup_i2c_gsbi12),
.resource = resources_qup_i2c_gsbi12,
};
#ifdef CONFIG_MACH_LGE
static struct resource resources_qup_i2c_gsbi1[] = {
{
.name = "gsbi_qup_i2c_addr",
.start = MSM_GSBI1_PHYS,
.end = MSM_GSBI1_PHYS + MSM_QUP_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_phys_addr",
.start = MSM_GSBI1_QUP_PHYS,
.end = MSM_GSBI1_QUP_PHYS + 4 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_err_intr",
.start = MSM8960_GSBI1_QUP_IRQ,
.end = MSM8960_GSBI1_QUP_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm8960_device_qup_i2c_gsbi1 = {
.name = "qup_i2c",
.id = 1,
.num_resources = ARRAY_SIZE(resources_qup_i2c_gsbi1),
.resource = resources_qup_i2c_gsbi1,
};
static struct resource resources_qup_i2c_gsbi2[] = {
{
.name = "gsbi_qup_i2c_addr",
.start = MSM_GSBI2_PHYS,
.end = MSM_GSBI2_PHYS + MSM_QUP_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_phys_addr",
.start = MSM_GSBI2_QUP_PHYS,
.end = MSM_GSBI2_QUP_PHYS + 4 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_err_intr",
.start = MSM8960_GSBI2_QUP_IRQ,
.end = MSM8960_GSBI2_QUP_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm8960_device_qup_i2c_gsbi2 = {
.name = "qup_i2c",
.id = 2,
.num_resources = ARRAY_SIZE(resources_qup_i2c_gsbi2),
.resource = resources_qup_i2c_gsbi2,
};
static struct resource resources_qup_i2c_gsbi5[] = {
{
.name = "gsbi_qup_i2c_addr",
.start = MSM_GSBI5_PHYS,
.end = MSM_GSBI5_PHYS + MSM_QUP_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_phys_addr",
.start = MSM_GSBI5_QUP_PHYS,
.end = MSM_GSBI5_QUP_PHYS + 4 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_err_intr",
.start = GSBI5_QUP_IRQ,
.end = GSBI5_QUP_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm8960_device_qup_i2c_gsbi5 = {
.name = "qup_i2c",
.id = 5,
.num_resources = ARRAY_SIZE(resources_qup_i2c_gsbi5),
.resource = resources_qup_i2c_gsbi5,
};
static struct resource resources_qup_i2c_gsbi7[] = {
{
.name = "gsbi_qup_i2c_addr",
.start = MSM_GSBI7_PHYS,
.end = MSM_GSBI7_PHYS + MSM_QUP_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_phys_addr",
.start = MSM_GSBI7_QUP_PHYS,
.end = MSM_GSBI7_QUP_PHYS + 4 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_err_intr",
.start = GSBI7_QUP_IRQ,
.end = GSBI7_QUP_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm8960_device_qup_i2c_gsbi7 = {
.name = "qup_i2c",
.id = 7,
.num_resources = ARRAY_SIZE(resources_qup_i2c_gsbi7),
.resource = resources_qup_i2c_gsbi7,
};
static struct resource resources_qup_i2c_gsbi8[] = {
{
.name = "gsbi_qup_i2c_addr",
.start = MSM_GSBI8_PHYS,
.end = MSM_GSBI8_PHYS + MSM_QUP_SIZE - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_phys_addr",
.start = MSM_GSBI8_QUP_PHYS,
.end = MSM_GSBI8_QUP_PHYS + 4 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "qup_err_intr",
.start = GSBI8_QUP_IRQ,
.end = GSBI8_QUP_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm8960_device_qup_i2c_gsbi8 = {
.name = "qup_i2c",
.id = 8,
.num_resources = ARRAY_SIZE(resources_qup_i2c_gsbi8),
.resource = resources_qup_i2c_gsbi8,
};
#endif /* CONFIG_MACH_LGE */
#ifdef CONFIG_MSM_CAMERA
static struct resource msm_cam_gsbi4_i2c_mux_resources[] = {
{
.name = "i2c_mux_rw",
.start = 0x008003E0,
.end = 0x008003E0 + SZ_8 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "i2c_mux_ctl",
.start = 0x008020B8,
.end = 0x008020B8 + SZ_4 - 1,
.flags = IORESOURCE_MEM,
},
};
struct platform_device msm8960_device_i2c_mux_gsbi4 = {
.name = "msm_cam_i2c_mux",
.id = 0,
.resource = msm_cam_gsbi4_i2c_mux_resources,
.num_resources = ARRAY_SIZE(msm_cam_gsbi4_i2c_mux_resources),
};
static struct resource msm_csiphy0_resources[] = {
{
.name = "csiphy",
.start = 0x04800C00,
.end = 0x04800C00 + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "csiphy",
.start = CSIPHY_4LN_IRQ,
.end = CSIPHY_4LN_IRQ,
.flags = IORESOURCE_IRQ,
},
};
static struct resource msm_csiphy1_resources[] = {
{
.name = "csiphy",
.start = 0x04801000,
.end = 0x04801000 + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "csiphy",
.start = MSM8960_CSIPHY_2LN_IRQ,
.end = MSM8960_CSIPHY_2LN_IRQ,
.flags = IORESOURCE_IRQ,
},
};
static struct resource msm_csiphy2_resources[] = {
{
.name = "csiphy",
.start = 0x04801400,
.end = 0x04801400 + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "csiphy",
.start = MSM8960_CSIPHY_2_2LN_IRQ,
.end = MSM8960_CSIPHY_2_2LN_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm8960_device_csiphy0 = {
.name = "msm_csiphy",
.id = 0,
.resource = msm_csiphy0_resources,
.num_resources = ARRAY_SIZE(msm_csiphy0_resources),
};
struct platform_device msm8960_device_csiphy1 = {
.name = "msm_csiphy",
.id = 1,
.resource = msm_csiphy1_resources,
.num_resources = ARRAY_SIZE(msm_csiphy1_resources),
};
struct platform_device msm8960_device_csiphy2 = {
.name = "msm_csiphy",
.id = 2,
.resource = msm_csiphy2_resources,
.num_resources = ARRAY_SIZE(msm_csiphy2_resources),
};
static struct resource msm_csid0_resources[] = {
{
.name = "csid",
.start = 0x04800000,
.end = 0x04800000 + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "csid",
.start = CSI_0_IRQ,
.end = CSI_0_IRQ,
.flags = IORESOURCE_IRQ,
},
};
static struct resource msm_csid1_resources[] = {
{
.name = "csid",
.start = 0x04800400,
.end = 0x04800400 + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "csid",
.start = CSI_1_IRQ,
.end = CSI_1_IRQ,
.flags = IORESOURCE_IRQ,
},
};
static struct resource msm_csid2_resources[] = {
{
.name = "csid",
.start = 0x04801800,
.end = 0x04801800 + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "csid",
.start = CSI_2_IRQ,
.end = CSI_2_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm8960_device_csid0 = {
.name = "msm_csid",
.id = 0,
.resource = msm_csid0_resources,
.num_resources = ARRAY_SIZE(msm_csid0_resources),
};
struct platform_device msm8960_device_csid1 = {
.name = "msm_csid",
.id = 1,
.resource = msm_csid1_resources,
.num_resources = ARRAY_SIZE(msm_csid1_resources),
};
struct platform_device msm8960_device_csid2 = {
.name = "msm_csid",
.id = 2,
.resource = msm_csid2_resources,
.num_resources = ARRAY_SIZE(msm_csid2_resources),
};
struct resource msm_ispif_resources[] = {
{
.name = "ispif",
.start = 0x04800800,
.end = 0x04800800 + SZ_1K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "ispif",
.start = ISPIF_IRQ,
.end = ISPIF_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm8960_device_ispif = {
.name = "msm_ispif",
.id = 0,
.resource = msm_ispif_resources,
.num_resources = ARRAY_SIZE(msm_ispif_resources),
};
static struct resource msm_vfe_resources[] = {
{
.name = "vfe32",
.start = 0x04500000,
.end = 0x04500000 + SZ_1M - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "vfe32",
.start = VFE_IRQ,
.end = VFE_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm8960_device_vfe = {
.name = "msm_vfe",
.id = 0,
.resource = msm_vfe_resources,
.num_resources = ARRAY_SIZE(msm_vfe_resources),
};
static struct resource msm_vpe_resources[] = {
{
.name = "vpe",
.start = 0x05300000,
.end = 0x05300000 + SZ_1M - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "vpe",
.start = VPE_IRQ,
.end = VPE_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm8960_device_vpe = {
.name = "msm_vpe",
.id = 0,
.resource = msm_vpe_resources,
.num_resources = ARRAY_SIZE(msm_vpe_resources),
};
#endif
#define MSM_TSIF0_PHYS (0x18200000)
#define MSM_TSIF1_PHYS (0x18201000)
#define MSM_TSIF_SIZE (0x200)
#define TSIF_0_CLK GPIO_CFG(75, 1, GPIO_CFG_INPUT, \
GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA)
#define TSIF_0_EN GPIO_CFG(76, 1, GPIO_CFG_INPUT, \
GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA)
#define TSIF_0_DATA GPIO_CFG(77, 1, GPIO_CFG_INPUT, \
GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA)
#define TSIF_0_SYNC GPIO_CFG(82, 1, GPIO_CFG_INPUT, \
GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA)
#define TSIF_1_CLK GPIO_CFG(79, 1, GPIO_CFG_INPUT, \
GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA)
#define TSIF_1_EN GPIO_CFG(80, 1, GPIO_CFG_INPUT, \
GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA)
#define TSIF_1_DATA GPIO_CFG(81, 1, GPIO_CFG_INPUT, \
GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA)
#define TSIF_1_SYNC GPIO_CFG(78, 1, GPIO_CFG_INPUT, \
GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA)
static const struct msm_gpio tsif0_gpios[] = {
{ .gpio_cfg = TSIF_0_CLK, .label = "tsif_clk", },
{ .gpio_cfg = TSIF_0_EN, .label = "tsif_en", },
{ .gpio_cfg = TSIF_0_DATA, .label = "tsif_data", },
{ .gpio_cfg = TSIF_0_SYNC, .label = "tsif_sync", },
};
static const struct msm_gpio tsif1_gpios[] = {
{ .gpio_cfg = TSIF_1_CLK, .label = "tsif_clk", },
{ .gpio_cfg = TSIF_1_EN, .label = "tsif_en", },
{ .gpio_cfg = TSIF_1_DATA, .label = "tsif_data", },
{ .gpio_cfg = TSIF_1_SYNC, .label = "tsif_sync", },
};
struct msm_tsif_platform_data tsif1_platform_data = {
.num_gpios = ARRAY_SIZE(tsif1_gpios),
.gpios = tsif1_gpios,
.tsif_pclk = "tsif_pclk",
.tsif_ref_clk = "tsif_ref_clk",
};
struct resource tsif1_resources[] = {
[0] = {
.flags = IORESOURCE_IRQ,
.start = TSIF2_IRQ,
.end = TSIF2_IRQ,
},
[1] = {
.flags = IORESOURCE_MEM,
.start = MSM_TSIF1_PHYS,
.end = MSM_TSIF1_PHYS + MSM_TSIF_SIZE - 1,
},
[2] = {
.flags = IORESOURCE_DMA,
.start = DMOV_TSIF_CHAN,
.end = DMOV_TSIF_CRCI,
},
};
struct msm_tsif_platform_data tsif0_platform_data = {
.num_gpios = ARRAY_SIZE(tsif0_gpios),
.gpios = tsif0_gpios,
.tsif_pclk = "tsif_pclk",
.tsif_ref_clk = "tsif_ref_clk",
};
struct resource tsif0_resources[] = {
[0] = {
.flags = IORESOURCE_IRQ,
.start = TSIF1_IRQ,
.end = TSIF1_IRQ,
},
[1] = {
.flags = IORESOURCE_MEM,
.start = MSM_TSIF0_PHYS,
.end = MSM_TSIF0_PHYS + MSM_TSIF_SIZE - 1,
},
[2] = {
.flags = IORESOURCE_DMA,
.start = DMOV_TSIF_CHAN,
.end = DMOV_TSIF_CRCI,
},
};
struct platform_device msm_device_tsif[2] = {
{
.name = "msm_tsif",
.id = 0,
.num_resources = ARRAY_SIZE(tsif0_resources),
.resource = tsif0_resources,
.dev = {
.platform_data = &tsif0_platform_data
},
},
{
.name = "msm_tsif",
.id = 1,
.num_resources = ARRAY_SIZE(tsif1_resources),
.resource = tsif1_resources,
.dev = {
.platform_data = &tsif1_platform_data
},
}
};
static struct resource resources_ssbi_pmic[] = {
{
.start = MSM_PMIC1_SSBI_CMD_PHYS,
.end = MSM_PMIC1_SSBI_CMD_PHYS + MSM_PMIC_SSBI_SIZE - 1,
.flags = IORESOURCE_MEM,
},
};
struct platform_device msm8960_device_ssbi_pmic = {
.name = "msm_ssbi",
.id = 0,
.resource = resources_ssbi_pmic,
.num_resources = ARRAY_SIZE(resources_ssbi_pmic),
};
static struct resource resources_qup_spi_gsbi1[] = {
{
.name = "spi_base",
.start = MSM_GSBI1_QUP_PHYS,
.end = MSM_GSBI1_QUP_PHYS + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "gsbi_base",
.start = MSM_GSBI1_PHYS,
.end = MSM_GSBI1_PHYS + 4 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "spi_irq_in",
.start = MSM8960_GSBI1_QUP_IRQ,
.end = MSM8960_GSBI1_QUP_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.name = "spi_clk",
.start = 9,
.end = 9,
.flags = IORESOURCE_IO,
},
{
.name = "spi_miso",
.start = 7,
.end = 7,
.flags = IORESOURCE_IO,
},
{
.name = "spi_mosi",
.start = 6,
.end = 6,
.flags = IORESOURCE_IO,
},
{
.name = "spi_cs",
.start = 8,
.end = 8,
.flags = IORESOURCE_IO,
},
{
.name = "spi_cs1",
.start = 14,
.end = 14,
.flags = IORESOURCE_IO,
},
};
struct platform_device msm8960_device_qup_spi_gsbi1 = {
.name = "spi_qsd",
.id = 0,
.num_resources = ARRAY_SIZE(resources_qup_spi_gsbi1),
.resource = resources_qup_spi_gsbi1,
};
struct platform_device msm_pcm = {
.name = "msm-pcm-dsp",
.id = -1,
};
struct platform_device msm_multi_ch_pcm = {
.name = "msm-multi-ch-pcm-dsp",
.id = -1,
};
struct platform_device msm_lowlatency_pcm = {
.name = "msm-lowlatency-pcm-dsp",
.id = -1,
};
struct platform_device msm_pcm_routing = {
.name = "msm-pcm-routing",
.id = -1,
};
struct platform_device msm_cpudai0 = {
.name = "msm-dai-q6",
.id = 0x4000,
};
struct platform_device msm_cpudai1 = {
.name = "msm-dai-q6",
.id = 0x4001,
};
struct platform_device msm8960_cpudai_slimbus_2_rx = {
.name = "msm-dai-q6",
.id = 0x4004,
};
struct platform_device msm8960_cpudai_slimbus_2_tx = {
.name = "msm-dai-q6",
.id = 0x4005,
};
struct platform_device msm_cpudai_hdmi_rx = {
.name = "msm-dai-q6-hdmi",
.id = 8,
};
struct platform_device msm_cpudai_bt_rx = {
.name = "msm-dai-q6",
.id = 0x3000,
};
struct platform_device msm_cpudai_bt_tx = {
.name = "msm-dai-q6",
.id = 0x3001,
};
struct platform_device msm_cpudai_fm_rx = {
.name = "msm-dai-q6",
.id = 0x3004,
};
struct platform_device msm_cpudai_fm_tx = {
.name = "msm-dai-q6",
.id = 0x3005,
};
struct platform_device msm_cpudai_incall_music_rx = {
.name = "msm-dai-q6",
.id = 0x8005,
};
struct platform_device msm_cpudai_incall_record_rx = {
.name = "msm-dai-q6",
.id = 0x8004,
};
struct platform_device msm_cpudai_incall_record_tx = {
.name = "msm-dai-q6",
.id = 0x8003,
};
/*
* Machine specific data for AUX PCM Interface
* which the driver will be unware of.
*/
struct msm_dai_auxpcm_pdata auxpcm_pdata = {
.clk = "pcm_clk",
.mode_8k = {
.mode = AFE_PCM_CFG_MODE_PCM,
.sync = AFE_PCM_CFG_SYNC_INT,
.frame = AFE_PCM_CFG_FRM_256BPF,
.quant = AFE_PCM_CFG_QUANT_LINEAR_NOPAD,
.slot = 0,
.data = AFE_PCM_CFG_CDATAOE_MASTER,
.pcm_clk_rate = 2048000,
},
.mode_16k = {
.mode = AFE_PCM_CFG_MODE_PCM,
.sync = AFE_PCM_CFG_SYNC_INT,
.frame = AFE_PCM_CFG_FRM_256BPF,
.quant = AFE_PCM_CFG_QUANT_LINEAR_NOPAD,
.slot = 0,
.data = AFE_PCM_CFG_CDATAOE_MASTER,
.pcm_clk_rate = 4096000,
}
};
struct platform_device msm_cpudai_auxpcm_rx = {
.name = "msm-dai-q6",
.id = 2,
.dev = {
.platform_data = &auxpcm_pdata,
},
};
struct platform_device msm_cpudai_auxpcm_tx = {
.name = "msm-dai-q6",
.id = 3,
.dev = {
.platform_data = &auxpcm_pdata,
},
};
struct platform_device msm_cpu_fe = {
.name = "msm-dai-fe",
.id = -1,
};
struct platform_device msm_stub_codec = {
.name = "msm-stub-codec",
.id = 1,
};
struct platform_device msm_voice = {
.name = "msm-pcm-voice",
.id = -1,
};
struct platform_device msm_voip = {
.name = "msm-voip-dsp",
.id = -1,
};
struct platform_device msm_lpa_pcm = {
.name = "msm-pcm-lpa",
.id = -1,
};
struct platform_device msm_compr_dsp = {
.name = "msm-compr-dsp",
.id = -1,
};
struct platform_device msm_pcm_hostless = {
.name = "msm-pcm-hostless",
.id = -1,
};
struct platform_device msm_cpudai_afe_01_rx = {
.name = "msm-dai-q6",
.id = 0xE0,
};
struct platform_device msm_cpudai_afe_01_tx = {
.name = "msm-dai-q6",
.id = 0xF0,
};
struct platform_device msm_cpudai_afe_02_rx = {
.name = "msm-dai-q6",
.id = 0xF1,
};
struct platform_device msm_cpudai_afe_02_tx = {
.name = "msm-dai-q6",
.id = 0xE1,
};
struct platform_device msm_pcm_afe = {
.name = "msm-pcm-afe",
.id = -1,
};
static struct fs_driver_data gfx2d0_fs_data = {
.clks = (struct fs_clk_data[]){
{ .name = "core_clk" },
{ .name = "iface_clk" },
{ 0 }
},
.bus_port0 = MSM_BUS_MASTER_GRAPHICS_2D_CORE0,
};
static struct fs_driver_data gfx2d1_fs_data = {
.clks = (struct fs_clk_data[]){
{ .name = "core_clk" },
{ .name = "iface_clk" },
{ 0 }
},
.bus_port0 = MSM_BUS_MASTER_GRAPHICS_2D_CORE1,
};
static struct fs_driver_data gfx3d_fs_data = {
.clks = (struct fs_clk_data[]){
{ .name = "core_clk", .reset_rate = 27000000 },
{ .name = "iface_clk" },
{ 0 }
},
.bus_port0 = MSM_BUS_MASTER_GRAPHICS_3D,
};
static struct fs_driver_data ijpeg_fs_data = {
.clks = (struct fs_clk_data[]){
{ .name = "core_clk" },
{ .name = "iface_clk" },
{ .name = "bus_clk" },
{ 0 }
},
.bus_port0 = MSM_BUS_MASTER_JPEG_ENC,
};
static struct fs_driver_data mdp_fs_data = {
.clks = (struct fs_clk_data[]){
{ .name = "core_clk" },
{ .name = "iface_clk" },
{ .name = "bus_clk" },
{ .name = "vsync_clk" },
{ .name = "lut_clk" },
#ifdef CONFIG_FB_MSM_HDMI_MSM_PANEL
{ .name = "tv_src_clk" },
{ .name = "tv_clk" },
#endif
{ .name = "reset1_clk" },
{ .name = "reset2_clk" },
{ 0 }
},
.bus_port0 = MSM_BUS_MASTER_MDP_PORT0,
.bus_port1 = MSM_BUS_MASTER_MDP_PORT1,
};
static struct fs_driver_data rot_fs_data = {
.clks = (struct fs_clk_data[]){
{ .name = "core_clk" },
{ .name = "iface_clk" },
{ .name = "bus_clk" },
{ 0 }
},
.bus_port0 = MSM_BUS_MASTER_ROTATOR,
};
static struct fs_driver_data ved_fs_data = {
.clks = (struct fs_clk_data[]){
{ .name = "core_clk" },
{ .name = "iface_clk" },
{ .name = "bus_clk" },
{ 0 }
},
.bus_port0 = MSM_BUS_MASTER_HD_CODEC_PORT0,
.bus_port1 = MSM_BUS_MASTER_HD_CODEC_PORT1,
};
static struct fs_driver_data vfe_fs_data = {
.clks = (struct fs_clk_data[]){
{ .name = "core_clk" },
{ .name = "iface_clk" },
{ .name = "bus_clk" },
{ 0 }
},
.bus_port0 = MSM_BUS_MASTER_VFE,
};
static struct fs_driver_data vpe_fs_data = {
.clks = (struct fs_clk_data[]){
{ .name = "core_clk" },
{ .name = "iface_clk" },
{ .name = "bus_clk" },
{ 0 }
},
.bus_port0 = MSM_BUS_MASTER_VPE,
};
struct platform_device *msm8960_footswitch[] __initdata = {
FS_8X60(FS_MDP, "vdd", "mdp.0", &mdp_fs_data),
FS_8X60(FS_ROT, "vdd", "msm_rotator.0", &rot_fs_data),
FS_8X60(FS_IJPEG, "vdd", "msm_gemini.0", &ijpeg_fs_data),
FS_8X60(FS_VFE, "vdd", "msm_vfe.0", &vfe_fs_data),
FS_8X60(FS_VPE, "vdd", "msm_vpe.0", &vpe_fs_data),
FS_8X60(FS_GFX3D, "vdd", "kgsl-3d0.0", &gfx3d_fs_data),
FS_8X60(FS_GFX2D0, "vdd", "kgsl-2d0.0", &gfx2d0_fs_data),
FS_8X60(FS_GFX2D1, "vdd", "kgsl-2d1.1", &gfx2d1_fs_data),
FS_8X60(FS_VED, "vdd", "msm_vidc.0", &ved_fs_data),
};
unsigned msm8960_num_footswitch __initdata = ARRAY_SIZE(msm8960_footswitch);
#ifdef CONFIG_MSM_ROTATOR
static struct msm_bus_vectors rotator_init_vectors[] = {
{
.src = MSM_BUS_MASTER_ROTATOR,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = 0,
},
};
static struct msm_bus_vectors rotator_ui_vectors[] = {
{
.src = MSM_BUS_MASTER_ROTATOR,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = (1024 * 600 * 4 * 2 * 60),
.ib = (1024 * 600 * 4 * 2 * 60 * 1.5),
},
};
static struct msm_bus_vectors rotator_vga_vectors[] = {
{
.src = MSM_BUS_MASTER_ROTATOR,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = (640 * 480 * 2 * 2 * 30),
.ib = (640 * 480 * 2 * 2 * 30 * 1.5),
},
};
static struct msm_bus_vectors rotator_720p_vectors[] = {
{
.src = MSM_BUS_MASTER_ROTATOR,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = (1280 * 736 * 2 * 2 * 30),
.ib = (1280 * 736 * 2 * 2 * 30 * 1.5),
},
};
static struct msm_bus_vectors rotator_1080p_vectors[] = {
{
.src = MSM_BUS_MASTER_ROTATOR,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = (1920 * 1088 * 2 * 2 * 30),
.ib = (1920 * 1088 * 2 * 2 * 30 * 1.5),
},
};
static struct msm_bus_paths rotator_bus_scale_usecases[] = {
{
ARRAY_SIZE(rotator_init_vectors),
rotator_init_vectors,
},
{
ARRAY_SIZE(rotator_ui_vectors),
rotator_ui_vectors,
},
{
ARRAY_SIZE(rotator_vga_vectors),
rotator_vga_vectors,
},
{
ARRAY_SIZE(rotator_720p_vectors),
rotator_720p_vectors,
},
{
ARRAY_SIZE(rotator_1080p_vectors),
rotator_1080p_vectors,
},
};
struct msm_bus_scale_pdata rotator_bus_scale_pdata = {
rotator_bus_scale_usecases,
ARRAY_SIZE(rotator_bus_scale_usecases),
.name = "rotator",
};
void __init msm_rotator_update_bus_vectors(unsigned int xres,
unsigned int yres)
{
rotator_ui_vectors[0].ab = xres * yres * 4 * 2 * 60;
rotator_ui_vectors[0].ib = xres * yres * 4 * 2 * 60 * 3 / 2;
}
#define ROTATOR_HW_BASE 0x04E00000
static struct resource resources_msm_rotator[] = {
{
.start = ROTATOR_HW_BASE,
.end = ROTATOR_HW_BASE + 0x100000 - 1,
.flags = IORESOURCE_MEM,
},
{
.start = ROT_IRQ,
.end = ROT_IRQ,
.flags = IORESOURCE_IRQ,
},
};
static struct msm_rot_clocks rotator_clocks[] = {
{
.clk_name = "core_clk",
.clk_type = ROTATOR_CORE_CLK,
.clk_rate = 200 * 1000 * 1000,
},
{
.clk_name = "iface_clk",
.clk_type = ROTATOR_PCLK,
.clk_rate = 0,
},
};
static struct msm_rotator_platform_data rotator_pdata = {
.number_of_clocks = ARRAY_SIZE(rotator_clocks),
.hardware_version_number = 0x01020309,
.rotator_clks = rotator_clocks,
#ifdef CONFIG_MSM_BUS_SCALING
.bus_scale_table = &rotator_bus_scale_pdata,
#endif
};
struct platform_device msm_rotator_device = {
.name = "msm_rotator",
.id = 0,
.num_resources = ARRAY_SIZE(resources_msm_rotator),
.resource = resources_msm_rotator,
.dev = {
.platform_data = &rotator_pdata,
},
};
void __init msm_rotator_set_split_iommu_domain(void)
{
rotator_pdata.rot_iommu_split_domain = 1;
}
#endif
#define MIPI_DSI_HW_BASE 0x04700000
#define MDP_HW_BASE 0x05100000
static struct resource msm_mipi_dsi1_resources[] = {
{
.name = "mipi_dsi",
.start = MIPI_DSI_HW_BASE,
.end = MIPI_DSI_HW_BASE + 0x000F0000 - 1,
.flags = IORESOURCE_MEM,
},
{
.start = DSI1_IRQ,
.end = DSI1_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm_mipi_dsi1_device = {
.name = "mipi_dsi",
.id = 1,
.num_resources = ARRAY_SIZE(msm_mipi_dsi1_resources),
.resource = msm_mipi_dsi1_resources,
};
static struct resource msm_mdp_resources[] = {
{
.name = "mdp",
.start = MDP_HW_BASE,
.end = MDP_HW_BASE + 0x000F0000 - 1,
.flags = IORESOURCE_MEM,
},
{
.start = MDP_IRQ,
.end = MDP_IRQ,
.flags = IORESOURCE_IRQ,
},
};
static struct platform_device msm_mdp_device = {
.name = "mdp",
.id = 0,
.num_resources = ARRAY_SIZE(msm_mdp_resources),
.resource = msm_mdp_resources,
};
static void __init msm_register_device(struct platform_device *pdev, void *data)
{
int ret;
pdev->dev.platform_data = data;
ret = platform_device_register(pdev);
if (ret)
dev_err(&pdev->dev,
"%s: platform_device_register() failed = %d\n",
__func__, ret);
}
#ifdef CONFIG_MSM_BUS_SCALING
static struct platform_device msm_dtv_device = {
.name = "dtv",
.id = 0,
};
#endif
struct platform_device msm_lvds_device = {
.name = "lvds",
.id = 0,
};
void __init msm_fb_register_device(char *name, void *data)
{
if (!strncmp(name, "mdp", 3))
msm_register_device(&msm_mdp_device, data);
else if (!strncmp(name, "mipi_dsi", 8))
msm_register_device(&msm_mipi_dsi1_device, data);
else if (!strncmp(name, "lvds", 4))
msm_register_device(&msm_lvds_device, data);
#ifdef CONFIG_MSM_BUS_SCALING
else if (!strncmp(name, "dtv", 3))
msm_register_device(&msm_dtv_device, data);
#endif
else
printk(KERN_ERR "%s: unknown device! %s\n", __func__, name);
}
static struct resource resources_sps[] = {
{
.name = "pipe_mem",
.start = 0x12800000,
.end = 0x12800000 + 0x4000 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "bamdma_dma",
.start = 0x12240000,
.end = 0x12240000 + 0x1000 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "bamdma_bam",
.start = 0x12244000,
.end = 0x12244000 + 0x4000 - 1,
.flags = IORESOURCE_MEM,
},
{
.name = "bamdma_irq",
.start = SPS_BAM_DMA_IRQ,
.end = SPS_BAM_DMA_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct msm_sps_platform_data msm_sps_pdata = {
.bamdma_restricted_pipes = 0x06,
};
struct platform_device msm_device_sps = {
.name = "msm_sps",
.id = -1,
.num_resources = ARRAY_SIZE(resources_sps),
.resource = resources_sps,
.dev.platform_data = &msm_sps_pdata,
};
#ifdef CONFIG_MSM_MPM
static uint16_t msm_mpm_irqs_m2a[MSM_MPM_NR_MPM_IRQS] __initdata = {
[1] = MSM_GPIO_TO_INT(46),
[2] = MSM_GPIO_TO_INT(150),
[4] = MSM_GPIO_TO_INT(103),
[5] = MSM_GPIO_TO_INT(104),
[6] = MSM_GPIO_TO_INT(105),
[7] = MSM_GPIO_TO_INT(106),
[8] = MSM_GPIO_TO_INT(107),
[9] = MSM_GPIO_TO_INT(7),
[10] = MSM_GPIO_TO_INT(11),
[11] = MSM_GPIO_TO_INT(15),
[12] = MSM_GPIO_TO_INT(19),
[13] = MSM_GPIO_TO_INT(23),
[14] = MSM_GPIO_TO_INT(27),
[15] = MSM_GPIO_TO_INT(31),
[16] = MSM_GPIO_TO_INT(35),
[19] = MSM_GPIO_TO_INT(90),
[20] = MSM_GPIO_TO_INT(92),
[23] = MSM_GPIO_TO_INT(85),
[24] = MSM_GPIO_TO_INT(83),
[25] = USB1_HS_IRQ,
[27] = HDMI_IRQ,
[29] = MSM_GPIO_TO_INT(10),
[30] = MSM_GPIO_TO_INT(102),
[31] = MSM_GPIO_TO_INT(81),
[32] = MSM_GPIO_TO_INT(78),
[33] = MSM_GPIO_TO_INT(94),
[34] = MSM_GPIO_TO_INT(72),
[35] = MSM_GPIO_TO_INT(39),
[36] = MSM_GPIO_TO_INT(43),
[37] = MSM_GPIO_TO_INT(61),
[38] = MSM_GPIO_TO_INT(50),
[39] = MSM_GPIO_TO_INT(42),
[41] = MSM_GPIO_TO_INT(62),
[42] = MSM_GPIO_TO_INT(76),
[43] = MSM_GPIO_TO_INT(75),
[44] = MSM_GPIO_TO_INT(70),
[45] = MSM_GPIO_TO_INT(69),
[46] = MSM_GPIO_TO_INT(67),
[47] = MSM_GPIO_TO_INT(65),
[48] = MSM_GPIO_TO_INT(58),
[49] = MSM_GPIO_TO_INT(54),
[50] = MSM_GPIO_TO_INT(52),
[51] = MSM_GPIO_TO_INT(49),
[52] = MSM_GPIO_TO_INT(40),
[53] = MSM_GPIO_TO_INT(37),
[54] = MSM_GPIO_TO_INT(24),
[55] = MSM_GPIO_TO_INT(14),
};
static uint16_t msm_mpm_bypassed_apps_irqs[] __initdata = {
TLMM_MSM_SUMMARY_IRQ,
RPM_APCC_CPU0_GP_HIGH_IRQ,
RPM_APCC_CPU0_GP_MEDIUM_IRQ,
RPM_APCC_CPU0_GP_LOW_IRQ,
RPM_APCC_CPU0_WAKE_UP_IRQ,
RPM_APCC_CPU1_GP_HIGH_IRQ,
RPM_APCC_CPU1_GP_MEDIUM_IRQ,
RPM_APCC_CPU1_GP_LOW_IRQ,
RPM_APCC_CPU1_WAKE_UP_IRQ,
MSS_TO_APPS_IRQ_0,
MSS_TO_APPS_IRQ_1,
MSS_TO_APPS_IRQ_2,
MSS_TO_APPS_IRQ_3,
MSS_TO_APPS_IRQ_4,
MSS_TO_APPS_IRQ_5,
MSS_TO_APPS_IRQ_6,
MSS_TO_APPS_IRQ_7,
MSS_TO_APPS_IRQ_8,
MSS_TO_APPS_IRQ_9,
LPASS_SCSS_GP_LOW_IRQ,
LPASS_SCSS_GP_MEDIUM_IRQ,
LPASS_SCSS_GP_HIGH_IRQ,
SPS_MTI_30,
SPS_MTI_31,
RIVA_APSS_SPARE_IRQ,
RIVA_APPS_WLAN_SMSM_IRQ,
RIVA_APPS_WLAN_RX_DATA_AVAIL_IRQ,
RIVA_APPS_WLAN_DATA_XFER_DONE_IRQ,
};
struct msm_mpm_device_data msm8960_mpm_dev_data __initdata = {
.irqs_m2a = msm_mpm_irqs_m2a,
.irqs_m2a_size = ARRAY_SIZE(msm_mpm_irqs_m2a),
.bypassed_apps_irqs = msm_mpm_bypassed_apps_irqs,
.bypassed_apps_irqs_size = ARRAY_SIZE(msm_mpm_bypassed_apps_irqs),
.mpm_request_reg_base = MSM_RPM_BASE + 0x9d8,
.mpm_status_reg_base = MSM_RPM_BASE + 0xdf8,
.mpm_apps_ipc_reg = MSM_APCS_GCC_BASE + 0x008,
.mpm_apps_ipc_val = BIT(1),
.mpm_ipc_irq = RPM_APCC_CPU0_GP_MEDIUM_IRQ,
};
#endif
#define LPASS_SLIMBUS_PHYS 0x28080000
#define LPASS_SLIMBUS_BAM_PHYS 0x28084000
#define LPASS_SLIMBUS_SLEW (MSM8960_TLMM_PHYS + 0x207C)
/* Board info for the slimbus slave device */
static struct resource slimbus_res[] = {
{
.start = LPASS_SLIMBUS_PHYS,
.end = LPASS_SLIMBUS_PHYS + 8191,
.flags = IORESOURCE_MEM,
.name = "slimbus_physical",
},
{
.start = LPASS_SLIMBUS_BAM_PHYS,
.end = LPASS_SLIMBUS_BAM_PHYS + 8191,
.flags = IORESOURCE_MEM,
.name = "slimbus_bam_physical",
},
{
.start = LPASS_SLIMBUS_SLEW,
.end = LPASS_SLIMBUS_SLEW + 4 - 1,
.flags = IORESOURCE_MEM,
.name = "slimbus_slew_reg",
},
{
.start = SLIMBUS0_CORE_EE1_IRQ,
.end = SLIMBUS0_CORE_EE1_IRQ,
.flags = IORESOURCE_IRQ,
.name = "slimbus_irq",
},
{
.start = SLIMBUS0_BAM_EE1_IRQ,
.end = SLIMBUS0_BAM_EE1_IRQ,
.flags = IORESOURCE_IRQ,
.name = "slimbus_bam_irq",
},
};
struct platform_device msm_slim_ctrl = {
.name = "msm_slim_ctrl",
.id = 1,
.num_resources = ARRAY_SIZE(slimbus_res),
.resource = slimbus_res,
.dev = {
.coherent_dma_mask = 0xffffffffULL,
},
};
static struct msm_dcvs_freq_entry grp3d_freq[] = {
{0, 0, 333932},
{0, 0, 497532},
{0, 0, 707610},
{0, 0, 844545},
};
static struct msm_dcvs_freq_entry grp2d_freq[] = {
{0, 0, 86000},
{0, 0, 200000},
};
static struct msm_dcvs_core_info grp3d_core_info = {
.freq_tbl = &grp3d_freq[0],
.core_param = {
.max_time_us = 100000,
.num_freq = ARRAY_SIZE(grp3d_freq),
},
.algo_param = {
.slack_time_us = 39000,
.disable_pc_threshold = 86000,
.ss_window_size = 1000000,
.ss_util_pct = 95,
.em_max_util_pct = 97,
.ss_iobusy_conv = 100,
},
};
static struct msm_dcvs_core_info grp2d_core_info = {
.freq_tbl = &grp2d_freq[0],
.core_param = {
.max_time_us = 100000,
.num_freq = ARRAY_SIZE(grp2d_freq),
},
.algo_param = {
.slack_time_us = 39000,
.disable_pc_threshold = 90000,
.ss_window_size = 1000000,
.ss_util_pct = 90,
.em_max_util_pct = 95,
},
};
#ifdef CONFIG_MSM_BUS_SCALING
static struct msm_bus_vectors grp3d_init_vectors[] = {
{
.src = MSM_BUS_MASTER_GRAPHICS_3D,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = 0,
},
};
static struct msm_bus_vectors grp3d_low_vectors[] = {
{
.src = MSM_BUS_MASTER_GRAPHICS_3D,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = KGSL_CONVERT_TO_MBPS(1000),
},
};
static struct msm_bus_vectors grp3d_nominal_low_vectors[] = {
{
.src = MSM_BUS_MASTER_GRAPHICS_3D,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = KGSL_CONVERT_TO_MBPS(2048),
},
};
#ifdef CONFIG_GPU_OVERCLOCK
static struct msm_bus_vectors grp3d_nominal_high_vectors[] = {
{
.src = MSM_BUS_MASTER_GRAPHICS_3D,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = KGSL_CONVERT_TO_MBPS(3968),
},
};
static struct msm_bus_vectors grp3d_max_vectors[] = {
{
.src = MSM_BUS_MASTER_GRAPHICS_3D,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = KGSL_CONVERT_TO_MBPS(5290),
},
};
#else
static struct msm_bus_vectors grp3d_nominal_high_vectors[] = {
{
.src = MSM_BUS_MASTER_GRAPHICS_3D,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = KGSL_CONVERT_TO_MBPS(2656),
},
};
static struct msm_bus_vectors grp3d_max_vectors[] = {
{
.src = MSM_BUS_MASTER_GRAPHICS_3D,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = KGSL_CONVERT_TO_MBPS(3968),
},
};
#endif
static struct msm_bus_paths grp3d_bus_scale_usecases[] = {
{
ARRAY_SIZE(grp3d_init_vectors),
grp3d_init_vectors,
},
{
ARRAY_SIZE(grp3d_low_vectors),
grp3d_low_vectors,
},
{
ARRAY_SIZE(grp3d_nominal_low_vectors),
grp3d_nominal_low_vectors,
},
{
ARRAY_SIZE(grp3d_nominal_high_vectors),
grp3d_nominal_high_vectors,
},
{
ARRAY_SIZE(grp3d_max_vectors),
grp3d_max_vectors,
},
};
static struct msm_bus_scale_pdata grp3d_bus_scale_pdata = {
grp3d_bus_scale_usecases,
ARRAY_SIZE(grp3d_bus_scale_usecases),
.name = "grp3d",
};
static struct msm_bus_vectors grp2d0_init_vectors[] = {
{
.src = MSM_BUS_MASTER_GRAPHICS_2D_CORE0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = 0,
},
};
static struct msm_bus_vectors grp2d0_nominal_vectors[] = {
{
.src = MSM_BUS_MASTER_GRAPHICS_2D_CORE0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = KGSL_CONVERT_TO_MBPS(1000),
},
};
static struct msm_bus_vectors grp2d0_max_vectors[] = {
{
.src = MSM_BUS_MASTER_GRAPHICS_2D_CORE0,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = KGSL_CONVERT_TO_MBPS(2048),
},
};
static struct msm_bus_paths grp2d0_bus_scale_usecases[] = {
{
ARRAY_SIZE(grp2d0_init_vectors),
grp2d0_init_vectors,
},
{
ARRAY_SIZE(grp2d0_nominal_vectors),
grp2d0_nominal_vectors,
},
{
ARRAY_SIZE(grp2d0_max_vectors),
grp2d0_max_vectors,
},
};
struct msm_bus_scale_pdata grp2d0_bus_scale_pdata = {
grp2d0_bus_scale_usecases,
ARRAY_SIZE(grp2d0_bus_scale_usecases),
.name = "grp2d0",
};
static struct msm_bus_vectors grp2d1_init_vectors[] = {
{
.src = MSM_BUS_MASTER_GRAPHICS_2D_CORE1,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = 0,
},
};
static struct msm_bus_vectors grp2d1_nominal_vectors[] = {
{
.src = MSM_BUS_MASTER_GRAPHICS_2D_CORE1,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = KGSL_CONVERT_TO_MBPS(1000),
},
};
static struct msm_bus_vectors grp2d1_max_vectors[] = {
{
.src = MSM_BUS_MASTER_GRAPHICS_2D_CORE1,
.dst = MSM_BUS_SLAVE_EBI_CH0,
.ab = 0,
.ib = KGSL_CONVERT_TO_MBPS(2048),
},
};
static struct msm_bus_paths grp2d1_bus_scale_usecases[] = {
{
ARRAY_SIZE(grp2d1_init_vectors),
grp2d1_init_vectors,
},
{
ARRAY_SIZE(grp2d1_nominal_vectors),
grp2d1_nominal_vectors,
},
{
ARRAY_SIZE(grp2d1_max_vectors),
grp2d1_max_vectors,
},
};
struct msm_bus_scale_pdata grp2d1_bus_scale_pdata = {
grp2d1_bus_scale_usecases,
ARRAY_SIZE(grp2d1_bus_scale_usecases),
.name = "grp2d1",
};
#endif
static struct resource kgsl_3d0_resources[] = {
{
.name = KGSL_3D0_REG_MEMORY,
.start = 0x04300000, /* GFX3D address */
.end = 0x0431ffff,
.flags = IORESOURCE_MEM,
},
{
.name = KGSL_3D0_IRQ,
.start = GFX3D_IRQ,
.end = GFX3D_IRQ,
.flags = IORESOURCE_IRQ,
},
};
static const struct kgsl_iommu_ctx kgsl_3d0_iommu_ctxs[] = {
{ "gfx3d_user", 0 },
{ "gfx3d_priv", 1 },
};
static struct kgsl_device_iommu_data kgsl_3d0_iommu_data[] = {
{
.iommu_ctxs = kgsl_3d0_iommu_ctxs,
.iommu_ctx_count = ARRAY_SIZE(kgsl_3d0_iommu_ctxs),
.physstart = 0x07C00000,
.physend = 0x07C00000 + SZ_1M - 1,
},
};
static struct kgsl_device_platform_data kgsl_3d0_pdata = {
.pwrlevel = {
#ifdef CONFIG_GPU_OVERCLOCK
{
.gpu_freq = 480000000,
.bus_freq = 4,
.io_fraction = 0,
},
{
.gpu_freq = 400000000,
.bus_freq = 3,
.io_fraction = 0,
},
#else
{
.gpu_freq = 400000000,
.bus_freq = 4,
.io_fraction = 0,
},
{
.gpu_freq = 300000000,
.bus_freq = 3,
.io_fraction = 33,
},
#endif
{
.gpu_freq = 200000000,
.bus_freq = 2,
.io_fraction = 100,
},
{
.gpu_freq = 128000000,
.bus_freq = 1,
.io_fraction = 100,
},
{
.gpu_freq = 27000000,
.bus_freq = 0,
},
},
.init_level = 1,
.num_levels = ARRAY_SIZE(grp3d_freq) + 1,
.set_grp_async = NULL,
.idle_timeout = HZ/12,
.nap_allowed = true,
.clk_map = KGSL_CLK_CORE | KGSL_CLK_IFACE | KGSL_CLK_MEM_IFACE,
#ifdef CONFIG_MSM_BUS_SCALING
.bus_scale_table = &grp3d_bus_scale_pdata,
#endif
.iommu_data = kgsl_3d0_iommu_data,
.iommu_count = ARRAY_SIZE(kgsl_3d0_iommu_data),
.core_info = &grp3d_core_info,
};
struct platform_device msm_kgsl_3d0 = {
.name = "kgsl-3d0",
.id = 0,
.num_resources = ARRAY_SIZE(kgsl_3d0_resources),
.resource = kgsl_3d0_resources,
.dev = {
.platform_data = &kgsl_3d0_pdata,
},
};
static struct resource kgsl_2d0_resources[] = {
{
.name = KGSL_2D0_REG_MEMORY,
.start = 0x04100000, /* Z180 base address */
.end = 0x04100FFF,
.flags = IORESOURCE_MEM,
},
{
.name = KGSL_2D0_IRQ,
.start = GFX2D0_IRQ,
.end = GFX2D0_IRQ,
.flags = IORESOURCE_IRQ,
},
};
static const struct kgsl_iommu_ctx kgsl_2d0_iommu_ctxs[] = {
{ "gfx2d0_2d0", 0 },
};
static struct kgsl_device_iommu_data kgsl_2d0_iommu_data[] = {
{
.iommu_ctxs = kgsl_2d0_iommu_ctxs,
.iommu_ctx_count = ARRAY_SIZE(kgsl_2d0_iommu_ctxs),
.physstart = 0x07D00000,
.physend = 0x07D00000 + SZ_1M - 1,
},
};
static struct kgsl_device_platform_data kgsl_2d0_pdata = {
.pwrlevel = {
{
.gpu_freq = 200000000,
.bus_freq = 2,
},
{
.gpu_freq = 96000000,
.bus_freq = 1,
},
{
.gpu_freq = 27000000,
.bus_freq = 0,
},
},
.init_level = 0,
.num_levels = ARRAY_SIZE(grp2d_freq) + 1,
.set_grp_async = NULL,
.idle_timeout = HZ/5,
.nap_allowed = true,
.clk_map = KGSL_CLK_CORE | KGSL_CLK_IFACE,
#ifdef CONFIG_MSM_BUS_SCALING
.bus_scale_table = &grp2d0_bus_scale_pdata,
#endif
.iommu_data = kgsl_2d0_iommu_data,
.iommu_count = ARRAY_SIZE(kgsl_2d0_iommu_data),
.core_info = &grp2d_core_info,
};
struct platform_device msm_kgsl_2d0 = {
.name = "kgsl-2d0",
.id = 0,
.num_resources = ARRAY_SIZE(kgsl_2d0_resources),
.resource = kgsl_2d0_resources,
.dev = {
.platform_data = &kgsl_2d0_pdata,
},
};
static const struct kgsl_iommu_ctx kgsl_2d1_iommu_ctxs[] = {
{ "gfx2d1_2d1", 0 },
};
static struct kgsl_device_iommu_data kgsl_2d1_iommu_data[] = {
{
.iommu_ctxs = kgsl_2d1_iommu_ctxs,
.iommu_ctx_count = ARRAY_SIZE(kgsl_2d1_iommu_ctxs),
.physstart = 0x07E00000,
.physend = 0x07E00000 + SZ_1M - 1,
},
};
static struct resource kgsl_2d1_resources[] = {
{
.name = KGSL_2D1_REG_MEMORY,
.start = 0x04200000, /* Z180 device 1 base address */
.end = 0x04200FFF,
.flags = IORESOURCE_MEM,
},
{
.name = KGSL_2D1_IRQ,
.start = GFX2D1_IRQ,
.end = GFX2D1_IRQ,
.flags = IORESOURCE_IRQ,
},
};
static struct kgsl_device_platform_data kgsl_2d1_pdata = {
.pwrlevel = {
{
.gpu_freq = 200000000,
.bus_freq = 2,
},
{
.gpu_freq = 96000000,
.bus_freq = 1,
},
{
.gpu_freq = 27000000,
.bus_freq = 0,
},
},
.init_level = 0,
.num_levels = ARRAY_SIZE(grp2d_freq) + 1,
.set_grp_async = NULL,
.idle_timeout = HZ/5,
.nap_allowed = true,
.clk_map = KGSL_CLK_CORE | KGSL_CLK_IFACE,
#ifdef CONFIG_MSM_BUS_SCALING
.bus_scale_table = &grp2d1_bus_scale_pdata,
#endif
.iommu_data = kgsl_2d1_iommu_data,
.iommu_count = ARRAY_SIZE(kgsl_2d1_iommu_data),
.core_info = &grp2d_core_info,
};
struct platform_device msm_kgsl_2d1 = {
.name = "kgsl-2d1",
.id = 1,
.num_resources = ARRAY_SIZE(kgsl_2d1_resources),
.resource = kgsl_2d1_resources,
.dev = {
.platform_data = &kgsl_2d1_pdata,
},
};
#ifdef CONFIG_MSM_GEMINI
static struct resource msm_gemini_resources[] = {
{
.start = 0x04600000,
.end = 0x04600000 + SZ_1M - 1,
.flags = IORESOURCE_MEM,
},
{
.start = JPEG_IRQ,
.end = JPEG_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm8960_gemini_device = {
.name = "msm_gemini",
.resource = msm_gemini_resources,
.num_resources = ARRAY_SIZE(msm_gemini_resources),
};
#endif
#ifdef CONFIG_MSM_MERCURY
static struct resource msm_mercury_resources[] = {
{
.start = 0x05000000,
.end = 0x05000000 + SZ_1M - 1,
.name = "mercury_resource_base",
.flags = IORESOURCE_MEM,
},
{
.start = JPEGD_IRQ,
.end = JPEGD_IRQ,
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm8960_mercury_device = {
.name = "msm_mercury",
.resource = msm_mercury_resources,
.num_resources = ARRAY_SIZE(msm_mercury_resources),
};
#endif
struct msm_rpm_platform_data msm8960_rpm_data __initdata = {
.reg_base_addrs = {
[MSM_RPM_PAGE_STATUS] = MSM_RPM_BASE,
[MSM_RPM_PAGE_CTRL] = MSM_RPM_BASE + 0x400,
[MSM_RPM_PAGE_REQ] = MSM_RPM_BASE + 0x600,
[MSM_RPM_PAGE_ACK] = MSM_RPM_BASE + 0xa00,
},
.irq_ack = RPM_APCC_CPU0_GP_HIGH_IRQ,
.irq_err = RPM_APCC_CPU0_GP_LOW_IRQ,
.irq_wakeup = RPM_APCC_CPU0_WAKE_UP_IRQ,
.ipc_rpm_reg = MSM_APCS_GCC_BASE + 0x008,
.ipc_rpm_val = 4,
.target_id = {
MSM_RPM_MAP(8960, NOTIFICATION_CONFIGURED_0, NOTIFICATION, 4),
MSM_RPM_MAP(8960, NOTIFICATION_REGISTERED_0, NOTIFICATION, 4),
MSM_RPM_MAP(8960, INVALIDATE_0, INVALIDATE, 8),
MSM_RPM_MAP(8960, TRIGGER_TIMED_TO, TRIGGER_TIMED, 1),
MSM_RPM_MAP(8960, TRIGGER_TIMED_SCLK_COUNT, TRIGGER_TIMED, 1),
MSM_RPM_MAP(8960, RPM_CTL, RPM_CTL, 1),
MSM_RPM_MAP(8960, CXO_CLK, CXO_CLK, 1),
MSM_RPM_MAP(8960, PXO_CLK, PXO_CLK, 1),
MSM_RPM_MAP(8960, APPS_FABRIC_CLK, APPS_FABRIC_CLK, 1),
MSM_RPM_MAP(8960, SYSTEM_FABRIC_CLK, SYSTEM_FABRIC_CLK, 1),
MSM_RPM_MAP(8960, MM_FABRIC_CLK, MM_FABRIC_CLK, 1),
MSM_RPM_MAP(8960, DAYTONA_FABRIC_CLK, DAYTONA_FABRIC_CLK, 1),
MSM_RPM_MAP(8960, SFPB_CLK, SFPB_CLK, 1),
MSM_RPM_MAP(8960, CFPB_CLK, CFPB_CLK, 1),
MSM_RPM_MAP(8960, MMFPB_CLK, MMFPB_CLK, 1),
MSM_RPM_MAP(8960, EBI1_CLK, EBI1_CLK, 1),
MSM_RPM_MAP(8960, APPS_FABRIC_CFG_HALT_0,
APPS_FABRIC_CFG_HALT, 2),
MSM_RPM_MAP(8960, APPS_FABRIC_CFG_CLKMOD_0,
APPS_FABRIC_CFG_CLKMOD, 3),
MSM_RPM_MAP(8960, APPS_FABRIC_CFG_IOCTL,
APPS_FABRIC_CFG_IOCTL, 1),
MSM_RPM_MAP(8960, APPS_FABRIC_ARB_0, APPS_FABRIC_ARB, 12),
MSM_RPM_MAP(8960, SYS_FABRIC_CFG_HALT_0,
SYS_FABRIC_CFG_HALT, 2),
MSM_RPM_MAP(8960, SYS_FABRIC_CFG_CLKMOD_0,
SYS_FABRIC_CFG_CLKMOD, 3),
MSM_RPM_MAP(8960, SYS_FABRIC_CFG_IOCTL,
SYS_FABRIC_CFG_IOCTL, 1),
MSM_RPM_MAP(8960, SYSTEM_FABRIC_ARB_0,
SYSTEM_FABRIC_ARB, 29),
MSM_RPM_MAP(8960, MMSS_FABRIC_CFG_HALT_0,
MMSS_FABRIC_CFG_HALT, 2),
MSM_RPM_MAP(8960, MMSS_FABRIC_CFG_CLKMOD_0,
MMSS_FABRIC_CFG_CLKMOD, 3),
MSM_RPM_MAP(8960, MMSS_FABRIC_CFG_IOCTL,
MMSS_FABRIC_CFG_IOCTL, 1),
MSM_RPM_MAP(8960, MM_FABRIC_ARB_0, MM_FABRIC_ARB, 23),
MSM_RPM_MAP(8960, PM8921_S1_0, PM8921_S1, 2),
MSM_RPM_MAP(8960, PM8921_S2_0, PM8921_S2, 2),
MSM_RPM_MAP(8960, PM8921_S3_0, PM8921_S3, 2),
MSM_RPM_MAP(8960, PM8921_S4_0, PM8921_S4, 2),
MSM_RPM_MAP(8960, PM8921_S5_0, PM8921_S5, 2),
MSM_RPM_MAP(8960, PM8921_S6_0, PM8921_S6, 2),
MSM_RPM_MAP(8960, PM8921_S7_0, PM8921_S7, 2),
MSM_RPM_MAP(8960, PM8921_S8_0, PM8921_S8, 2),
MSM_RPM_MAP(8960, PM8921_L1_0, PM8921_L1, 2),
MSM_RPM_MAP(8960, PM8921_L2_0, PM8921_L2, 2),
MSM_RPM_MAP(8960, PM8921_L3_0, PM8921_L3, 2),
MSM_RPM_MAP(8960, PM8921_L4_0, PM8921_L4, 2),
MSM_RPM_MAP(8960, PM8921_L5_0, PM8921_L5, 2),
MSM_RPM_MAP(8960, PM8921_L6_0, PM8921_L6, 2),
MSM_RPM_MAP(8960, PM8921_L7_0, PM8921_L7, 2),
MSM_RPM_MAP(8960, PM8921_L8_0, PM8921_L8, 2),
MSM_RPM_MAP(8960, PM8921_L9_0, PM8921_L9, 2),
MSM_RPM_MAP(8960, PM8921_L10_0, PM8921_L10, 2),
MSM_RPM_MAP(8960, PM8921_L11_0, PM8921_L11, 2),
MSM_RPM_MAP(8960, PM8921_L12_0, PM8921_L12, 2),
MSM_RPM_MAP(8960, PM8921_L13_0, PM8921_L13, 2),
MSM_RPM_MAP(8960, PM8921_L14_0, PM8921_L14, 2),
MSM_RPM_MAP(8960, PM8921_L15_0, PM8921_L15, 2),
MSM_RPM_MAP(8960, PM8921_L16_0, PM8921_L16, 2),
MSM_RPM_MAP(8960, PM8921_L17_0, PM8921_L17, 2),
MSM_RPM_MAP(8960, PM8921_L18_0, PM8921_L18, 2),
MSM_RPM_MAP(8960, PM8921_L19_0, PM8921_L19, 2),
MSM_RPM_MAP(8960, PM8921_L20_0, PM8921_L20, 2),
MSM_RPM_MAP(8960, PM8921_L21_0, PM8921_L21, 2),
MSM_RPM_MAP(8960, PM8921_L22_0, PM8921_L22, 2),
MSM_RPM_MAP(8960, PM8921_L23_0, PM8921_L23, 2),
MSM_RPM_MAP(8960, PM8921_L24_0, PM8921_L24, 2),
MSM_RPM_MAP(8960, PM8921_L25_0, PM8921_L25, 2),
MSM_RPM_MAP(8960, PM8921_L26_0, PM8921_L26, 2),
MSM_RPM_MAP(8960, PM8921_L27_0, PM8921_L27, 2),
MSM_RPM_MAP(8960, PM8921_L28_0, PM8921_L28, 2),
MSM_RPM_MAP(8960, PM8921_L29_0, PM8921_L29, 2),
MSM_RPM_MAP(8960, PM8921_CLK1_0, PM8921_CLK1, 2),
MSM_RPM_MAP(8960, PM8921_CLK2_0, PM8921_CLK2, 2),
MSM_RPM_MAP(8960, PM8921_LVS1, PM8921_LVS1, 1),
MSM_RPM_MAP(8960, PM8921_LVS2, PM8921_LVS2, 1),
MSM_RPM_MAP(8960, PM8921_LVS3, PM8921_LVS3, 1),
MSM_RPM_MAP(8960, PM8921_LVS4, PM8921_LVS4, 1),
MSM_RPM_MAP(8960, PM8921_LVS5, PM8921_LVS5, 1),
MSM_RPM_MAP(8960, PM8921_LVS6, PM8921_LVS6, 1),
MSM_RPM_MAP(8960, PM8921_LVS7, PM8921_LVS7, 1),
MSM_RPM_MAP(8960, NCP_0, NCP, 2),
MSM_RPM_MAP(8960, CXO_BUFFERS, CXO_BUFFERS, 1),
MSM_RPM_MAP(8960, USB_OTG_SWITCH, USB_OTG_SWITCH, 1),
MSM_RPM_MAP(8960, HDMI_SWITCH, HDMI_SWITCH, 1),
MSM_RPM_MAP(8960, DDR_DMM_0, DDR_DMM, 2),
MSM_RPM_MAP(8960, QDSS_CLK, QDSS_CLK, 1),
},
.target_status = {
MSM_RPM_STATUS_ID_MAP(8960, VERSION_MAJOR),
MSM_RPM_STATUS_ID_MAP(8960, VERSION_MINOR),
MSM_RPM_STATUS_ID_MAP(8960, VERSION_BUILD),
MSM_RPM_STATUS_ID_MAP(8960, SUPPORTED_RESOURCES_0),
MSM_RPM_STATUS_ID_MAP(8960, SUPPORTED_RESOURCES_1),
MSM_RPM_STATUS_ID_MAP(8960, SUPPORTED_RESOURCES_2),
MSM_RPM_STATUS_ID_MAP(8960, RESERVED_SUPPORTED_RESOURCES_0),
MSM_RPM_STATUS_ID_MAP(8960, SEQUENCE),
MSM_RPM_STATUS_ID_MAP(8960, RPM_CTL),
MSM_RPM_STATUS_ID_MAP(8960, CXO_CLK),
MSM_RPM_STATUS_ID_MAP(8960, PXO_CLK),
MSM_RPM_STATUS_ID_MAP(8960, APPS_FABRIC_CLK),
MSM_RPM_STATUS_ID_MAP(8960, SYSTEM_FABRIC_CLK),
MSM_RPM_STATUS_ID_MAP(8960, MM_FABRIC_CLK),
MSM_RPM_STATUS_ID_MAP(8960, DAYTONA_FABRIC_CLK),
MSM_RPM_STATUS_ID_MAP(8960, SFPB_CLK),
MSM_RPM_STATUS_ID_MAP(8960, CFPB_CLK),
MSM_RPM_STATUS_ID_MAP(8960, MMFPB_CLK),
MSM_RPM_STATUS_ID_MAP(8960, EBI1_CLK),
MSM_RPM_STATUS_ID_MAP(8960, APPS_FABRIC_CFG_HALT),
MSM_RPM_STATUS_ID_MAP(8960, APPS_FABRIC_CFG_CLKMOD),
MSM_RPM_STATUS_ID_MAP(8960, APPS_FABRIC_CFG_IOCTL),
MSM_RPM_STATUS_ID_MAP(8960, APPS_FABRIC_ARB),
MSM_RPM_STATUS_ID_MAP(8960, SYS_FABRIC_CFG_HALT),
MSM_RPM_STATUS_ID_MAP(8960, SYS_FABRIC_CFG_CLKMOD),
MSM_RPM_STATUS_ID_MAP(8960, SYS_FABRIC_CFG_IOCTL),
MSM_RPM_STATUS_ID_MAP(8960, SYSTEM_FABRIC_ARB),
MSM_RPM_STATUS_ID_MAP(8960, MMSS_FABRIC_CFG_HALT),
MSM_RPM_STATUS_ID_MAP(8960, MMSS_FABRIC_CFG_CLKMOD),
MSM_RPM_STATUS_ID_MAP(8960, MMSS_FABRIC_CFG_IOCTL),
MSM_RPM_STATUS_ID_MAP(8960, MM_FABRIC_ARB),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_S1_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_S1_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_S2_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_S2_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_S3_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_S3_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_S4_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_S4_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_S5_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_S5_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_S6_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_S6_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_S7_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_S7_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_S8_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_S8_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L1_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L1_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L2_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L2_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L3_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L3_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L4_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L4_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L5_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L5_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L6_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L6_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L7_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L7_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L8_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L8_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L9_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L9_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L10_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L10_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L11_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L11_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L12_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L12_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L13_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L13_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L14_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L14_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L15_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L15_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L16_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L16_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L17_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L17_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L18_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L18_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L19_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L19_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L20_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L20_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L21_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L21_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L22_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L22_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L23_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L23_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L24_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L24_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L25_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L25_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L26_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L26_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L27_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L27_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L28_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L28_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L29_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_L29_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_CLK1_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_CLK1_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_CLK2_0),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_CLK2_1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_LVS1),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_LVS2),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_LVS3),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_LVS4),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_LVS5),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_LVS6),
MSM_RPM_STATUS_ID_MAP(8960, PM8921_LVS7),
MSM_RPM_STATUS_ID_MAP(8960, NCP_0),
MSM_RPM_STATUS_ID_MAP(8960, NCP_1),
MSM_RPM_STATUS_ID_MAP(8960, CXO_BUFFERS),
MSM_RPM_STATUS_ID_MAP(8960, USB_OTG_SWITCH),
MSM_RPM_STATUS_ID_MAP(8960, HDMI_SWITCH),
MSM_RPM_STATUS_ID_MAP(8960, DDR_DMM_0),
MSM_RPM_STATUS_ID_MAP(8960, DDR_DMM_1),
MSM_RPM_STATUS_ID_MAP(8960, EBI1_CH0_RANGE),
MSM_RPM_STATUS_ID_MAP(8960, EBI1_CH1_RANGE),
},
.target_ctrl_id = {
MSM_RPM_CTRL_MAP(8960, VERSION_MAJOR),
MSM_RPM_CTRL_MAP(8960, VERSION_MINOR),
MSM_RPM_CTRL_MAP(8960, VERSION_BUILD),
MSM_RPM_CTRL_MAP(8960, REQ_CTX_0),
MSM_RPM_CTRL_MAP(8960, REQ_SEL_0),
MSM_RPM_CTRL_MAP(8960, ACK_CTX_0),
MSM_RPM_CTRL_MAP(8960, ACK_SEL_0),
},
.sel_invalidate = MSM_RPM_8960_SEL_INVALIDATE,
.sel_notification = MSM_RPM_8960_SEL_NOTIFICATION,
.sel_last = MSM_RPM_8960_SEL_LAST,
.ver = {3, 0, 0},
};
struct platform_device msm8960_rpm_device = {
.name = "msm_rpm",
.id = -1,
};
static struct msm_rpm_log_platform_data msm_rpm_log_pdata = {
.phys_addr_base = 0x0010C000,
.reg_offsets = {
[MSM_RPM_LOG_PAGE_INDICES] = 0x00000080,
[MSM_RPM_LOG_PAGE_BUFFER] = 0x000000A0,
},
.phys_size = SZ_8K,
.log_len = 4096, /* log's buffer length in bytes */
.log_len_mask = (4096 >> 2) - 1, /* length mask in units of u32 */
};
struct platform_device msm8960_rpm_log_device = {
.name = "msm_rpm_log",
.id = -1,
.dev = {
.platform_data = &msm_rpm_log_pdata,
},
};
static struct msm_rpmstats_platform_data msm_rpm_stat_pdata = {
.phys_addr_base = 0x0010DD04,
.phys_size = SZ_256,
};
struct platform_device msm8960_rpm_stat_device = {
.name = "msm_rpm_stat",
.id = -1,
.dev = {
.platform_data = &msm_rpm_stat_pdata,
},
};
struct platform_device msm_bus_sys_fabric = {
.name = "msm_bus_fabric",
.id = MSM_BUS_FAB_SYSTEM,
};
struct platform_device msm_bus_apps_fabric = {
.name = "msm_bus_fabric",
.id = MSM_BUS_FAB_APPSS,
};
struct platform_device msm_bus_mm_fabric = {
.name = "msm_bus_fabric",
.id = MSM_BUS_FAB_MMSS,
};
struct platform_device msm_bus_sys_fpb = {
.name = "msm_bus_fabric",
.id = MSM_BUS_FAB_SYSTEM_FPB,
};
struct platform_device msm_bus_cpss_fpb = {
.name = "msm_bus_fabric",
.id = MSM_BUS_FAB_CPSS_FPB,
};
/* Sensors DSPS platform data */
#ifdef CONFIG_MSM_DSPS
#define PPSS_DSPS_TCM_CODE_BASE 0x12000000
#define PPSS_DSPS_TCM_CODE_SIZE 0x28000
#define PPSS_DSPS_TCM_BUF_BASE 0x12040000
#define PPSS_DSPS_TCM_BUF_SIZE 0x4000
#define PPSS_DSPS_PIPE_BASE 0x12800000
#define PPSS_DSPS_PIPE_SIZE 0x4000
#define PPSS_DSPS_DDR_BASE 0x8fe00000
#define PPSS_DSPS_DDR_SIZE 0x100000
#define PPSS_SMEM_BASE 0x80000000
#define PPSS_SMEM_SIZE 0x200000
#define PPSS_REG_PHYS_BASE 0x12080000
static struct dsps_clk_info dsps_clks[] = {};
static struct dsps_regulator_info dsps_regs[] = {};
/*
* Note: GPIOs field is intialized in run-time at the function
* msm8960_init_dsps().
*/
struct msm_dsps_platform_data msm_dsps_pdata = {
.clks = dsps_clks,
.clks_num = ARRAY_SIZE(dsps_clks),
.gpios = NULL,
.gpios_num = 0,
.regs = dsps_regs,
.regs_num = ARRAY_SIZE(dsps_regs),
.dsps_pwr_ctl_en = 1,
.tcm_code_start = PPSS_DSPS_TCM_CODE_BASE,
.tcm_code_size = PPSS_DSPS_TCM_CODE_SIZE,
.tcm_buf_start = PPSS_DSPS_TCM_BUF_BASE,
.tcm_buf_size = PPSS_DSPS_TCM_BUF_SIZE,
.pipe_start = PPSS_DSPS_PIPE_BASE,
.pipe_size = PPSS_DSPS_PIPE_SIZE,
.ddr_start = PPSS_DSPS_DDR_BASE,
.ddr_size = PPSS_DSPS_DDR_SIZE,
.smem_start = PPSS_SMEM_BASE,
.smem_size = PPSS_SMEM_SIZE,
.signature = DSPS_SIGNATURE,
};
static struct resource msm_dsps_resources[] = {
{
.start = PPSS_REG_PHYS_BASE,
.end = PPSS_REG_PHYS_BASE + SZ_8K - 1,
.name = "ppss_reg",
.flags = IORESOURCE_MEM,
},
{
.start = PPSS_WDOG_TIMER_IRQ,
.end = PPSS_WDOG_TIMER_IRQ,
.name = "ppss_wdog",
.flags = IORESOURCE_IRQ,
},
};
struct platform_device msm_dsps_device = {
.name = "msm_dsps",
.id = 0,
.num_resources = ARRAY_SIZE(msm_dsps_resources),
.resource = msm_dsps_resources,
.dev.platform_data = &msm_dsps_pdata,
};
#endif /* CONFIG_MSM_DSPS */
#ifdef CONFIG_MSM_QDSS
#define MSM_QDSS_PHYS_BASE 0x01A00000
#define MSM_ETB_PHYS_BASE (MSM_QDSS_PHYS_BASE + 0x1000)
#define MSM_TPIU_PHYS_BASE (MSM_QDSS_PHYS_BASE + 0x3000)
#define MSM_FUNNEL_PHYS_BASE (MSM_QDSS_PHYS_BASE + 0x4000)
#define MSM_ETM_PHYS_BASE (MSM_QDSS_PHYS_BASE + 0x1C000)
#define QDSS_SOURCE(src_name, fpm) { .name = src_name, .fport_mask = fpm, }
static struct qdss_source msm_qdss_sources[] = {
QDSS_SOURCE("msm_etm", 0x3),
};
static struct msm_qdss_platform_data qdss_pdata = {
.src_table = msm_qdss_sources,
.size = ARRAY_SIZE(msm_qdss_sources),
.afamily = 1,
};
struct platform_device msm_qdss_device = {
.name = "msm_qdss",
.id = -1,
.dev = {
.platform_data = &qdss_pdata,
},
};
static struct resource msm_etb_resources[] = {
{
.start = MSM_ETB_PHYS_BASE,
.end = MSM_ETB_PHYS_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
};
struct platform_device msm_etb_device = {
.name = "msm_etb",
.id = 0,
.num_resources = ARRAY_SIZE(msm_etb_resources),
.resource = msm_etb_resources,
};
static struct resource msm_tpiu_resources[] = {
{
.start = MSM_TPIU_PHYS_BASE,
.end = MSM_TPIU_PHYS_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
};
struct platform_device msm_tpiu_device = {
.name = "msm_tpiu",
.id = 0,
.num_resources = ARRAY_SIZE(msm_tpiu_resources),
.resource = msm_tpiu_resources,
};
static struct resource msm_funnel_resources[] = {
{
.start = MSM_FUNNEL_PHYS_BASE,
.end = MSM_FUNNEL_PHYS_BASE + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
};
struct platform_device msm_funnel_device = {
.name = "msm_funnel",
.id = 0,
.num_resources = ARRAY_SIZE(msm_funnel_resources),
.resource = msm_funnel_resources,
};
static struct resource msm_etm_resources[] = {
{
.start = MSM_ETM_PHYS_BASE,
.end = MSM_ETM_PHYS_BASE + (SZ_4K * 2) - 1,
.flags = IORESOURCE_MEM,
},
};
struct platform_device msm_etm_device = {
.name = "msm_etm",
.id = 0,
.num_resources = ARRAY_SIZE(msm_etm_resources),
.resource = msm_etm_resources,
};
#endif
static struct resource msm_ebi1_ch0_erp_resources[] = {
{
.start = HSDDRX_EBI1CH0_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.start = 0x00A40000,
.end = 0x00A40000 + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
};
struct platform_device msm8960_device_ebi1_ch0_erp = {
.name = "msm_ebi_erp",
.id = 0,
.num_resources = ARRAY_SIZE(msm_ebi1_ch0_erp_resources),
.resource = msm_ebi1_ch0_erp_resources,
};
static struct resource msm_ebi1_ch1_erp_resources[] = {
{
.start = HSDDRX_EBI1CH1_IRQ,
.flags = IORESOURCE_IRQ,
},
{
.start = 0x00D40000,
.end = 0x00D40000 + SZ_4K - 1,
.flags = IORESOURCE_MEM,
},
};
struct platform_device msm8960_device_ebi1_ch1_erp = {
.name = "msm_ebi_erp",
.id = 1,
.num_resources = ARRAY_SIZE(msm_ebi1_ch1_erp_resources),
.resource = msm_ebi1_ch1_erp_resources,
};
static int msm8960_LPM_latency = 1000; /* >100 usec for WFI */
struct platform_device msm8960_cpu_idle_device = {
.name = "msm_cpu_idle",
.id = -1,
.dev = {
.platform_data = &msm8960_LPM_latency,
},
};
static struct msm_dcvs_freq_entry msm8960_freq[] = {
{ 384000, 166981, 345600},
{ 702000, 213049, 632502},
{1026000, 285712, 925613},
{1242000, 383945, 1176550},
{1458000, 419729, 1465478},
{1512000, 434116, 1546674},
};
static struct msm_dcvs_core_info msm8960_core_info = {
.freq_tbl = &msm8960_freq[0],
.core_param = {
.max_time_us = 100000,
.num_freq = ARRAY_SIZE(msm8960_freq),
},
.algo_param = {
.slack_time_us = 58000,
.scale_slack_time = 0,
.scale_slack_time_pct = 0,
.disable_pc_threshold = 1458000,
.em_window_size = 100000,
.em_max_util_pct = 97,
.ss_window_size = 1000000,
.ss_util_pct = 95,
.ss_iobusy_conv = 100,
},
};
struct platform_device msm8960_msm_gov_device = {
.name = "msm_dcvs_gov",
.id = -1,
.dev = {
.platform_data = &msm8960_core_info,
},
};
static struct resource msm_cache_erp_resources[] = {
{
.name = "l1_irq",
.start = SC_SICCPUXEXTFAULTIRPTREQ,
.flags = IORESOURCE_IRQ,
},
{
.name = "l2_irq",
.start = APCC_QGICL2IRPTREQ,
.flags = IORESOURCE_IRQ,
}
};
struct platform_device msm8960_device_cache_erp = {
.name = "msm_cache_erp",
.id = -1,
.num_resources = ARRAY_SIZE(msm_cache_erp_resources),
.resource = msm_cache_erp_resources,
};
struct msm_iommu_domain_name msm8960_iommu_ctx_names[] = {
/* Camera */
{
.name = "vpe_src",
.domain = CAMERA_DOMAIN,
},
/* Camera */
{
.name = "vpe_dst",
.domain = CAMERA_DOMAIN,
},
/* Camera */
{
.name = "vfe_imgwr",
.domain = CAMERA_DOMAIN,
},
/* Camera */
{
.name = "vfe_misc",
.domain = CAMERA_DOMAIN,
},
/* Camera */
{
.name = "ijpeg_src",
.domain = CAMERA_DOMAIN,
},
/* Camera */
{
.name = "ijpeg_dst",
.domain = CAMERA_DOMAIN,
},
/* Camera */
{
.name = "jpegd_src",
.domain = CAMERA_DOMAIN,
},
/* Camera */
{
.name = "jpegd_dst",
.domain = CAMERA_DOMAIN,
},
/* Rotator */
{
.name = "rot_src",
.domain = ROTATOR_SRC_DOMAIN,
},
/* Rotator */
{
.name = "rot_dst",
.domain = ROTATOR_SRC_DOMAIN,
},
/* Video */
{
.name = "vcodec_a_mm1",
.domain = VIDEO_DOMAIN,
},
/* Video */
{
.name = "vcodec_b_mm2",
.domain = VIDEO_DOMAIN,
},
/* Video */
{
.name = "vcodec_a_stream",
.domain = VIDEO_DOMAIN,
},
};
static struct mem_pool msm8960_video_pools[] = {
/*
* Video hardware has the following requirements:
* 1. All video addresses used by the video hardware must be at a higher
* address than video firmware address.
* 2. Video hardware can only access a range of 256MB from the base of
* the video firmware.
*/
[VIDEO_FIRMWARE_POOL] =
/* Low addresses, intended for video firmware */
{
.paddr = SZ_128K,
.size = SZ_16M - SZ_128K,
},
[VIDEO_MAIN_POOL] =
/* Main video pool */
{
.paddr = SZ_16M,
.size = SZ_256M - SZ_16M,
},
[GEN_POOL] =
/* Remaining address space up to 2G */
{
.paddr = SZ_256M,
.size = SZ_2G - SZ_256M,
},
};
static struct mem_pool msm8960_camera_pools[] = {
[GEN_POOL] =
/* One address space for camera */
{
.paddr = SZ_128K,
.size = SZ_2G - SZ_128K,
},
};
static struct mem_pool msm8960_display_read_pools[] = {
[GEN_POOL] =
/* One address space for display reads */
{
.paddr = SZ_128K,
.size = SZ_2G - SZ_128K,
},
};
static struct mem_pool msm8960_rotator_src_pools[] = {
[GEN_POOL] =
/* One address space for rotator src */
{
.paddr = SZ_128K,
.size = SZ_2G - SZ_128K,
},
};
static struct msm_iommu_domain msm8960_iommu_domains[] = {
[VIDEO_DOMAIN] = {
.iova_pools = msm8960_video_pools,
.npools = ARRAY_SIZE(msm8960_video_pools),
},
[CAMERA_DOMAIN] = {
.iova_pools = msm8960_camera_pools,
.npools = ARRAY_SIZE(msm8960_camera_pools),
},
[DISPLAY_READ_DOMAIN] = {
.iova_pools = msm8960_display_read_pools,
.npools = ARRAY_SIZE(msm8960_display_read_pools),
},
[ROTATOR_SRC_DOMAIN] = {
.iova_pools = msm8960_rotator_src_pools,
.npools = ARRAY_SIZE(msm8960_rotator_src_pools),
},
};
struct iommu_domains_pdata msm8960_iommu_domain_pdata = {
.domains = msm8960_iommu_domains,
.ndomains = ARRAY_SIZE(msm8960_iommu_domains),
.domain_names = msm8960_iommu_ctx_names,
.nnames = ARRAY_SIZE(msm8960_iommu_ctx_names),
.domain_alloc_flags = 0,
};
struct platform_device msm8960_iommu_domain_device = {
.name = "iommu_domains",
.id = -1,
.dev = {
.platform_data = &msm8960_iommu_domain_pdata,
}
};
struct msm_rtb_platform_data msm8960_rtb_pdata = {
.size = SZ_1M,
};
static int __init msm_rtb_set_buffer_size(char *p)
{
int s;
s = memparse(p, NULL);
msm8960_rtb_pdata.size = ALIGN(s, SZ_4K);
return 0;
}
early_param("msm_rtb_size", msm_rtb_set_buffer_size);
struct platform_device msm8960_rtb_device = {
.name = "msm_rtb",
.id = -1,
.dev = {
.platform_data = &msm8960_rtb_pdata,
},
};
#define MSM_8960_L1_SIZE SZ_1M
/*
* The actual L2 size is smaller but we need a larger buffer
* size to store other dump information
*/
#define MSM_8960_L2_SIZE SZ_4M
struct msm_cache_dump_platform_data msm8960_cache_dump_pdata = {
.l2_size = MSM_8960_L2_SIZE,
.l1_size = MSM_8960_L1_SIZE,
};
struct platform_device msm8960_cache_dump_device = {
.name = "msm_cache_dump",
.id = -1,
.dev = {
.platform_data = &msm8960_cache_dump_pdata,
},
};
#define MDM2AP_ERRFATAL 40
#define AP2MDM_ERRFATAL 80
#define MDM2AP_STATUS 24
#define AP2MDM_STATUS 77
#define AP2MDM_PMIC_PWR_EN 22
#define AP2MDM_KPDPWR_N 79
#define AP2MDM_SOFT_RESET 78
static struct resource sglte_resources[] = {
{
.start = MDM2AP_ERRFATAL,
.end = MDM2AP_ERRFATAL,
.name = "MDM2AP_ERRFATAL",
.flags = IORESOURCE_IO,
},
{
.start = AP2MDM_ERRFATAL,
.end = AP2MDM_ERRFATAL,
.name = "AP2MDM_ERRFATAL",
.flags = IORESOURCE_IO,
},
{
.start = MDM2AP_STATUS,
.end = MDM2AP_STATUS,
.name = "MDM2AP_STATUS",
.flags = IORESOURCE_IO,
},
{
.start = AP2MDM_STATUS,
.end = AP2MDM_STATUS,
.name = "AP2MDM_STATUS",
.flags = IORESOURCE_IO,
},
{
.start = AP2MDM_PMIC_PWR_EN,
.end = AP2MDM_PMIC_PWR_EN,
.name = "AP2MDM_PMIC_PWR_EN",
.flags = IORESOURCE_IO,
},
{
.start = AP2MDM_KPDPWR_N,
.end = AP2MDM_KPDPWR_N,
.name = "AP2MDM_KPDPWR_N",
.flags = IORESOURCE_IO,
},
{
.start = AP2MDM_SOFT_RESET,
.end = AP2MDM_SOFT_RESET,
.name = "AP2MDM_SOFT_RESET",
.flags = IORESOURCE_IO,
},
};
struct platform_device mdm_sglte_device = {
.name = "mdm2_modem",
.id = -1,
.num_resources = ARRAY_SIZE(sglte_resources),
.resource = sglte_resources,
};
|
chevanlol360/Kernel_LGE_Fx1
|
arch/arm/mach-msm/devices-8960.c
|
C
|
gpl-2.0
| 97,625
|
--:SETVAR currentendyear 2016
Set nocount on
Select quotename(rp.relatedpairguid, '"') AS '"ID"', quotename(rp.personid1, '"')AS '"StudentID"', quotename(rp.personid2, '"')AS '"GuardianID"',
quotename(rt.typeid, '"') AS '"RelationshipID"'
FROM Student as s
INNER JOIN RelatedPair as rp ON s.personid = rp.personid1
INNER JOIN RelationshipType AS rt on rp.name = rt.name
INNER JOIN Person as P ON rp.personid2 = p.personid
--INNER JOIN [identity] as i ON p.personid = i.personid
WHERE s. servicetype = 'P' AND s.endYear = $(currentendyear) AND (s.endDate IS NULL OR NOT EXISTS (SELECT * from student WHERE endDate IS NULL AND endYear = $(currentendyear)))
AND rp.guardian = '1' AND rp.guardian = '1' AND (s.schoolid >= '2' AND s.schoolid <= '4')
ORDER BY rp.personid1
|
Per-Forma/IC-Enrich-CO
|
StudentGuardians.sql
|
SQL
|
gpl-2.0
| 802
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>SmartSorter: Base/code/basic_classif.cpp Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
</head>
<body>
<div id="top"><!-- do not remove this div! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">SmartSorter
 <span id="projectnumber">1</span>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- Generated by Doxygen 1.7.6.1 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
</ul>
</div>
</div>
<div class="header">
<div class="headertitle">
<div class="title">Base/code/basic_classif.cpp</div> </div>
</div><!--header-->
<div class="contents">
<div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 <span class="comment">/**********************************/</span>
<a name="l00002"></a>00002 <span class="comment">// This file is part of SmartSorter</span>
<a name="l00003"></a>00003 <span class="comment">// Author: Radim Svacek</span>
<a name="l00004"></a>00004 <span class="comment">// Created: 2015</span>
<a name="l00005"></a>00005 <span class="comment">/**********************************/</span>
<a name="l00006"></a>00006
<a name="l00007"></a>00007 <span class="preprocessor">#include "basic_classif.h"</span>
<a name="l00008"></a>00008
<a name="l00010"></a><a class="code" href="classBasicClassification.html#a2eb4b6500f89def59797c33acd912e2f">00010</a> <a class="code" href="classBasicClassification.html#a2eb4b6500f89def59797c33acd912e2f" title="Create some basic attributes with can be used for every file format.">BasicClassification::BasicClassification</a>(){
<a name="l00011"></a>00011 <a class="code" href="classAttribute.html" title="Stands for one file property.">Attribute</a> *newAttribute;
<a name="l00012"></a>00012 std::vector<int> attributeOperations;
<a name="l00013"></a>00013
<a name="l00014"></a>00014 attributeOperations = {LESS,LESS_EQUAL,MORE,MORE_EQUAL,EQUAL};
<a name="l00015"></a>00015 newAttribute = <span class="keyword">new</span> <a class="code" href="classAttribute.html" title="Stands for one file property.">Attribute</a>(PROPERTY_SIZE,attributeOperations,NUM_TYPE);
<a name="l00016"></a>00016 properties.push_back(newAttribute);
<a name="l00017"></a>00017
<a name="l00018"></a>00018 <span class="comment">//a = new Attribute(PropertyCreationDate,ops,Date_type);</span>
<a name="l00019"></a>00019 <span class="comment">//Properties.push_back(a);</span>
<a name="l00020"></a>00020
<a name="l00021"></a>00021 newAttribute = <span class="keyword">new</span> <a class="code" href="classAttribute.html" title="Stands for one file property.">Attribute</a>(PROPERTY_LAST_MODIFICATION_DATE,attributeOperations,DATE_TYPE);
<a name="l00022"></a>00022 properties.push_back(newAttribute);
<a name="l00023"></a>00023
<a name="l00024"></a>00024 attributeOperations = {EQUAL,CONTAINS,NOT_CONTAINS};
<a name="l00025"></a>00025 newAttribute = <span class="keyword">new</span> <a class="code" href="classAttribute.html" title="Stands for one file property.">Attribute</a>(PROPERTY_NAME,attributeOperations,TEXT_TYPE);
<a name="l00026"></a>00026 properties.push_back(newAttribute);
<a name="l00027"></a>00027
<a name="l00028"></a>00028 newAttribute = <span class="keyword">new</span> <a class="code" href="classAttribute.html" title="Stands for one file property.">Attribute</a>(PROPERTY_EXTENSION,attributeOperations,TEXT_TYPE);
<a name="l00029"></a>00029 properties.push_back(newAttribute);
<a name="l00030"></a>00030
<a name="l00031"></a>00031 attributeOperations.clear();
<a name="l00032"></a>00032
<a name="l00033"></a>00033 <a class="code" href="classBasicClassification.html#ada8cd48fda69f1e76a9ffa278a81d24d" title="Find and load plugins in folder "plugins".">LoadPlugins</a>();
<a name="l00034"></a>00034
<a name="l00035"></a>00035
<a name="l00036"></a>00036 }
<a name="l00037"></a>00037
<a name="l00039"></a><a class="code" href="classBasicClassification.html#a99fe4d3b5de48e5218a1b3c5485a15d2">00039</a> <a class="code" href="classBasicClassification.html#a99fe4d3b5de48e5218a1b3c5485a15d2" title="Clean memory.">BasicClassification::~BasicClassification</a>(){
<a name="l00040"></a>00040 <span class="keywordflow">for</span>(<span class="keyword">auto</span> pluginsIterator = PluginsFormats.begin(); pluginsIterator != PluginsFormats.end(); ++pluginsIterator) {
<a name="l00041"></a>00041 <span class="keyword">delete</span> (*pluginsIterator);
<a name="l00042"></a>00042 }
<a name="l00043"></a>00043 PluginsFormats.clear();
<a name="l00044"></a>00044
<a name="l00045"></a>00045 <span class="keywordflow">for</span>(<span class="keyword">auto</span> pluginsIterator = properties.begin(); pluginsIterator != properties.end(); ++pluginsIterator) {
<a name="l00046"></a>00046 <span class="keyword">delete</span> (*pluginsIterator);
<a name="l00047"></a>00047 }
<a name="l00048"></a>00048 properties.clear();
<a name="l00049"></a>00049 }
<a name="l00050"></a>00050
<a name="l00052"></a><a class="code" href="classBasicClassification.html#a6a521e25c72286d8f3e31ccad56a3de8">00052</a> QStringList <a class="code" href="classBasicClassification.html#a6a521e25c72286d8f3e31ccad56a3de8" title="Returns names of loaded plugins .. just for info.">BasicClassification::GetLoadedPlugins</a>(){
<a name="l00053"></a>00053 QStringList namesList;
<a name="l00054"></a>00054 <span class="keywordflow">for</span>(<span class="keyword">auto</span> pluginsIterator = PluginsFormats.begin(); pluginsIterator != PluginsFormats.end(); ++pluginsIterator) {
<a name="l00055"></a>00055 namesList << (*pluginsIterator)->GetName();
<a name="l00056"></a>00056 }
<a name="l00057"></a>00057 <span class="keywordflow">return</span> namesList;
<a name="l00058"></a>00058 }
<a name="l00059"></a>00059
<a name="l00061"></a><a class="code" href="classBasicClassification.html#ada8cd48fda69f1e76a9ffa278a81d24d">00061</a> <span class="keywordtype">void</span> <a class="code" href="classBasicClassification.html#ada8cd48fda69f1e76a9ffa278a81d24d" title="Find and load plugins in folder "plugins".">BasicClassification::LoadPlugins</a>(){
<a name="l00062"></a>00062 QDir pluginsDir = QDir(qApp->applicationDirPath());
<a name="l00063"></a>00063 pluginsDir.cd(<span class="stringliteral">"plugins"</span>);
<a name="l00064"></a>00064
<a name="l00065"></a>00065 <span class="keywordflow">foreach</span> (QString fileName, pluginsDir.entryList(QDir::Files)){
<a name="l00066"></a>00066 QPluginLoader loader(pluginsDir.absoluteFilePath(fileName));
<a name="l00067"></a>00067 QObject *plugin = loader.instance();
<a name="l00068"></a>00068 <span class="keywordflow">if</span>(plugin){
<a name="l00069"></a>00069 InitializePlugin(plugin);
<a name="l00070"></a>00070 }
<a name="l00071"></a>00071
<a name="l00072"></a>00072 }
<a name="l00073"></a>00073 }
<a name="l00074"></a>00074
<a name="l00076"></a>00076 <span class="keywordtype">void</span> BasicClassification::InitializePlugin(QObject *plugin){
<a name="l00077"></a>00077 <a class="code" href="classPluginInterface.html" title="Interface for plugins.">PluginInterface</a> *importedPlugin = qobject_cast<<a class="code" href="classPluginInterface.html" title="Interface for plugins.">PluginInterface</a> *>(plugin);
<a name="l00078"></a>00078 <span class="keywordflow">if</span>(importedPlugin){
<a name="l00079"></a>00079 <span class="comment">// Plugin was sucessfully loaded !</span>
<a name="l00080"></a>00080 importedPlugin->Initialize();
<a name="l00081"></a>00081 PluginsFormats.push_back(importedPlugin);
<a name="l00082"></a>00082 }
<a name="l00083"></a>00083 }
<a name="l00084"></a>00084
<a name="l00086"></a><a class="code" href="classBasicClassification.html#acae5812c2113a657902a1429478bb23c">00086</a> QStringList <a class="code" href="classBasicClassification.html#acae5812c2113a657902a1429478bb23c" title="Load properties for GUI dialog.">BasicClassification::GetProperties</a>(QString format){
<a name="l00087"></a>00087 QStringList listToReturn;
<a name="l00088"></a>00088 <span class="comment">// Format was not selected -> no properties to choose</span>
<a name="l00089"></a>00089 <span class="keywordflow">if</span>(format==<span class="stringliteral">""</span>)
<a name="l00090"></a>00090 <span class="keywordflow">return</span> listToReturn;
<a name="l00091"></a>00091 <span class="comment">// Add first row for select box</span>
<a name="l00092"></a>00092 listToReturn << <span class="stringliteral">""</span>;
<a name="l00093"></a>00093
<a name="l00094"></a>00094 <span class="comment">// Choose basic properties</span>
<a name="l00095"></a>00095 <span class="keywordflow">for</span>(<span class="keyword">auto</span> propertiesIterator = properties.begin(); propertiesIterator != properties.end(); ++propertiesIterator) {
<a name="l00096"></a>00096 <span class="comment">// If is specific format, extension property will not be shown</span>
<a name="l00097"></a>00097 <span class="keywordflow">if</span>((*propertiesIterator)->GetName() == PROPERTY_EXTENSION){
<a name="l00098"></a>00098 <span class="keywordflow">if</span>(IsGeneralFormat(format)){
<a name="l00099"></a>00099 listToReturn << (*propertiesIterator)->GetName();
<a name="l00100"></a>00100 }
<a name="l00101"></a>00101 }
<a name="l00102"></a>00102 <span class="keywordflow">else</span>{
<a name="l00103"></a>00103 listToReturn << (*propertiesIterator)->GetName();
<a name="l00104"></a>00104 }
<a name="l00105"></a>00105 }
<a name="l00106"></a>00106
<a name="l00107"></a>00107 <span class="comment">// If exists plugin for that format add some properties</span>
<a name="l00108"></a>00108 <span class="keywordflow">for</span>(<span class="keyword">auto</span> pluginsIterator = PluginsFormats.begin(); pluginsIterator != PluginsFormats.end(); ++pluginsIterator) {
<a name="l00109"></a>00109 <span class="keywordflow">if</span>(format == (*pluginsIterator)->GetName()){
<a name="l00110"></a>00110 listToReturn << (*pluginsIterator)->GetProperties();
<a name="l00111"></a>00111 }
<a name="l00112"></a>00112 }
<a name="l00113"></a>00113 <span class="keywordflow">return</span> listToReturn;
<a name="l00114"></a>00114 }
<a name="l00115"></a>00115
<a name="l00116"></a>00116
<a name="l00118"></a><a class="code" href="classBasicClassification.html#ab78acda1bf8e6b718daf17747b7cb479">00118</a> QStringList <a class="code" href="classBasicClassification.html#ab78acda1bf8e6b718daf17747b7cb479" title="Load properties for distribution to DIALOG.">BasicClassification::GetPropertiesForDistribution</a>(QString format){
<a name="l00119"></a>00119 QStringList listToReturn;
<a name="l00120"></a>00120 listToReturn = BASIC_DISTRIBUTION_PROPERTIES;
<a name="l00121"></a>00121 listToReturn << PROPERTY_EXTENSION;
<a name="l00122"></a>00122
<a name="l00123"></a>00123 <span class="comment">// If exists plugin for that format add some properties</span>
<a name="l00124"></a>00124 <span class="keywordflow">for</span>(<span class="keyword">auto</span> pluginsIterator = PluginsFormats.begin(); pluginsIterator != PluginsFormats.end(); ++pluginsIterator) {
<a name="l00125"></a>00125 <span class="keywordflow">if</span>(format == (*pluginsIterator)->GetName()){
<a name="l00126"></a>00126 listToReturn << (*pluginsIterator)->GetPropertiesForDistribution();
<a name="l00127"></a>00127 }
<a name="l00128"></a>00128 }
<a name="l00129"></a>00129
<a name="l00130"></a>00130 <span class="keywordflow">return</span> listToReturn;
<a name="l00131"></a>00131 }
<a name="l00132"></a>00132
<a name="l00133"></a>00133
<a name="l00135"></a><a class="code" href="classBasicClassification.html#ad1bade2cad8b2cea5c89c12466c1f921">00135</a> QStringList <a class="code" href="classBasicClassification.html#ad1bade2cad8b2cea5c89c12466c1f921" title="Load file formats for GUI dialog.">BasicClassification::GetFileFormats</a>(){
<a name="l00136"></a>00136 <span class="keywordflow">return</span> QStringList() << GENERAL_FORMATS << SPECIFIC_FORMATS;
<a name="l00137"></a>00137 }
<a name="l00138"></a>00138
<a name="l00140"></a><a class="code" href="classBasicClassification.html#a81294121362d1c6aa228938057bf88df">00140</a> QString <a class="code" href="classBasicClassification.html#a81294121362d1c6aa228938057bf88df" title="Load file formats for GUI dialog.">BasicClassification::GetGeneralFileFormat</a>(QString format){
<a name="l00141"></a>00141
<a name="l00142"></a>00142 <span class="keywordflow">foreach</span>(QString str,PICTURE_FORMATS){
<a name="l00143"></a>00143 <span class="keywordflow">if</span>(QString::compare(format,str,Qt::CaseInsensitive) == 0){
<a name="l00144"></a>00144 <span class="keywordflow">return</span> PICTURES;
<a name="l00145"></a>00145 }
<a name="l00146"></a>00146 }
<a name="l00147"></a>00147
<a name="l00148"></a>00148 <span class="keywordflow">foreach</span>(QString str,ARCHIVE_FORMATS){
<a name="l00149"></a>00149 <span class="keywordflow">if</span>(QString::compare(format,str,Qt::CaseInsensitive) == 0){
<a name="l00150"></a>00150 <span class="keywordflow">return</span> ARCHIVES;
<a name="l00151"></a>00151 }
<a name="l00152"></a>00152 }
<a name="l00153"></a>00153
<a name="l00154"></a>00154 <span class="keywordflow">foreach</span>(QString str,DOCUMENT_FORMATS){
<a name="l00155"></a>00155 <span class="keywordflow">if</span>(QString::compare(format,str,Qt::CaseInsensitive) == 0){
<a name="l00156"></a>00156 <span class="keywordflow">return</span> DOCUMENTS;
<a name="l00157"></a>00157 }
<a name="l00158"></a>00158 }
<a name="l00159"></a>00159
<a name="l00160"></a>00160 <span class="keywordflow">foreach</span>(QString str,VIDEO_FORMATS){
<a name="l00161"></a>00161 <span class="keywordflow">if</span>(QString::compare(format,str,Qt::CaseInsensitive) == 0){
<a name="l00162"></a>00162 <span class="keywordflow">return</span> VIDEOS;
<a name="l00163"></a>00163 }
<a name="l00164"></a>00164 }
<a name="l00165"></a>00165
<a name="l00166"></a>00166 <span class="keywordflow">foreach</span>(QString str,AUDIO_FORMATS){
<a name="l00167"></a>00167 <span class="keywordflow">if</span>(QString::compare(format,str,Qt::CaseInsensitive) == 0){
<a name="l00168"></a>00168 <span class="keywordflow">return</span> AUDIOS;
<a name="l00169"></a>00169 }
<a name="l00170"></a>00170 }
<a name="l00171"></a>00171
<a name="l00172"></a>00172 <span class="keywordflow">return</span> QString();
<a name="l00173"></a>00173 }
<a name="l00174"></a>00174
<a name="l00176"></a><a class="code" href="classBasicClassification.html#a4221d7393b8f5e63c1f1b28f6d4557f9">00176</a> std::vector<int> <a class="code" href="classBasicClassification.html#a4221d7393b8f5e63c1f1b28f6d4557f9" title="Load each property's possible operations for GUI dialog.">BasicClassification::GetPropertyOperations</a>(QString property,QString fileFormat){
<a name="l00177"></a>00177 <span class="keywordflow">for</span>(<span class="keyword">auto</span> propertiesIterator = properties.begin(); propertiesIterator != properties.end(); ++propertiesIterator){
<a name="l00178"></a>00178 <span class="keywordflow">if</span>(((*propertiesIterator)->GetName())==property)
<a name="l00179"></a>00179 <span class="keywordflow">return</span> (*propertiesIterator)->GetPropertyOperations();
<a name="l00180"></a>00180 }
<a name="l00181"></a>00181
<a name="l00182"></a>00182 <span class="comment">// If exists plugin for that format try to find operations there</span>
<a name="l00183"></a>00183 <span class="keywordflow">for</span>(<span class="keyword">auto</span> pluginsIterator = PluginsFormats.begin(); pluginsIterator != PluginsFormats.end(); ++pluginsIterator) {
<a name="l00184"></a>00184 <span class="keywordflow">if</span>(fileFormat == (*pluginsIterator)->GetName()){
<a name="l00185"></a>00185 <span class="keywordflow">return</span> (*pluginsIterator)->GetPropertyOperations(property);
<a name="l00186"></a>00186 }
<a name="l00187"></a>00187 }
<a name="l00188"></a>00188
<a name="l00189"></a>00189 <span class="keywordflow">return</span> std::vector<int>();
<a name="l00190"></a>00190 }
<a name="l00191"></a>00191
<a name="l00193"></a><a class="code" href="classBasicClassification.html#a09e1ef66bf5b09d23cd83480f26554b8">00193</a> <span class="keywordtype">int</span> <a class="code" href="classBasicClassification.html#a09e1ef66bf5b09d23cd83480f26554b8" title="Load type of property for GUI dialog.">BasicClassification::GetPropertyType</a>(QString arg,QString fileFormat){
<a name="l00194"></a>00194 <span class="keywordflow">for</span>(<span class="keyword">auto</span> propertiesIterator = properties.begin(); propertiesIterator != properties.end(); ++propertiesIterator){
<a name="l00195"></a>00195 <span class="keywordflow">if</span>(((*propertiesIterator)->GetName())==arg)
<a name="l00196"></a>00196 <span class="keywordflow">return</span> (*propertiesIterator)->GetPropertyType();
<a name="l00197"></a>00197 }
<a name="l00198"></a>00198
<a name="l00199"></a>00199 <span class="comment">// If exists plugin for that format try to find operations there</span>
<a name="l00200"></a>00200 <span class="keywordflow">for</span>(<span class="keyword">auto</span> pluginsIterator = PluginsFormats.begin(); pluginsIterator != PluginsFormats.end(); ++pluginsIterator) {
<a name="l00201"></a>00201 <span class="keywordflow">if</span>(fileFormat == (*pluginsIterator)->GetName()){
<a name="l00202"></a>00202 <span class="keywordflow">return</span> (*pluginsIterator)->GetPropertyType(arg);
<a name="l00203"></a>00203 }
<a name="l00204"></a>00204 }
<a name="l00205"></a>00205 <span class="keywordflow">return</span> 0;
<a name="l00206"></a>00206 }
<a name="l00207"></a>00207
<a name="l00209"></a>00209 <span class="keywordtype">bool</span> BasicClassification::IsGeneralFormat(QString attribute){
<a name="l00210"></a>00210
<a name="l00211"></a>00211 <span class="keywordflow">foreach</span>(QString str,GENERAL_FORMATS){
<a name="l00212"></a>00212 <span class="keywordflow">if</span>(str==attribute)
<a name="l00213"></a>00213 <span class="keywordflow">return</span> <span class="keyword">true</span>;
<a name="l00214"></a>00214 }
<a name="l00215"></a>00215 <span class="keywordflow">return</span> <span class="keyword">false</span>;
<a name="l00216"></a>00216 }
<a name="l00217"></a>00217
<a name="l00219"></a>00219 <span class="keywordtype">bool</span> BasicClassification::IsBasicProperty(QString property){
<a name="l00220"></a>00220 <span class="keywordflow">for</span>(<span class="keyword">auto</span> propertiesIterator = properties.begin(); propertiesIterator != properties.end(); ++propertiesIterator){
<a name="l00221"></a>00221 <span class="keywordflow">if</span>(((*propertiesIterator)->GetName())==property)
<a name="l00222"></a>00222 <span class="keywordflow">return</span> <span class="keyword">true</span>;
<a name="l00223"></a>00223 }
<a name="l00224"></a>00224 <span class="keywordflow">return</span> <span class="keyword">false</span>;
<a name="l00225"></a>00225 }
<a name="l00226"></a>00226
<a name="l00228"></a><a class="code" href="classBasicClassification.html#affca8925f1731505a8034c89655ed940">00228</a> <span class="keywordtype">bool</span> <a class="code" href="classBasicClassification.html#affca8925f1731505a8034c89655ed940" title="Check if file fullfilled condition in specicif branch of node.">BasicClassification::IsFileFullfilCondition</a>(<a class="code" href="classTreeBranch.html" title="Branch of node.">TreeBranch</a> * branch, <a class="code" href="classFile.html" title="Represents file.">File</a> * file, QString property){
<a name="l00229"></a>00229
<a name="l00230"></a>00230 <span class="comment">// If is it only walkthrough branch, immediately return true</span>
<a name="l00231"></a>00231 <span class="keywordflow">if</span>(branch->IsWalkThrough())
<a name="l00232"></a>00232 <span class="keywordflow">return</span> <span class="keyword">true</span>;
<a name="l00233"></a>00233
<a name="l00234"></a>00234 <span class="comment">// If property to compare is one of basic properties, find proper method to compare</span>
<a name="l00235"></a>00235 <span class="comment">// and there check if condition is fullfilled</span>
<a name="l00236"></a>00236 <span class="keywordflow">if</span>(IsBasicProperty(property)){
<a name="l00237"></a>00237 <span class="keywordflow">if</span>(property == PROPERTY_SIZE){
<a name="l00238"></a>00238 <span class="keywordflow">return</span> IsSizeConditionTrue(branch,file);
<a name="l00239"></a>00239 }
<a name="l00240"></a>00240 <span class="keywordflow">else</span> <span class="keywordflow">if</span>(property == PROPERTY_CREATION_DATE){
<a name="l00241"></a>00241 <span class="keywordflow">return</span> IsCreationDateConditionTrue(branch,file);
<a name="l00242"></a>00242 }
<a name="l00243"></a>00243 <span class="keywordflow">else</span> <span class="keywordflow">if</span>(property == PROPERTY_LAST_MODIFICATION_DATE){
<a name="l00244"></a>00244 <span class="keywordflow">return</span> IsLastModificationDateConditionTrue(branch,file);
<a name="l00245"></a>00245 }
<a name="l00246"></a>00246 <span class="keywordflow">else</span> <span class="keywordflow">if</span>(property == PROPERTY_NAME){
<a name="l00247"></a>00247 <span class="keywordflow">return</span> IsNameConditionTrue(branch,file);
<a name="l00248"></a>00248 }
<a name="l00249"></a>00249 <span class="keywordflow">else</span> <span class="keywordflow">if</span>(property == PROPERTY_EXTENSION){
<a name="l00250"></a>00250 <span class="keywordflow">return</span> IsExtensionConditionTrue(branch,file);
<a name="l00251"></a>00251 }
<a name="l00252"></a>00252 <span class="keywordflow">else</span>
<a name="l00253"></a>00253 <span class="keywordflow">return</span> <span class="keyword">false</span>;
<a name="l00254"></a>00254 }
<a name="l00255"></a>00255
<a name="l00256"></a>00256 <span class="comment">// In case of property from plugin it is necessary to find specific</span>
<a name="l00257"></a>00257 <span class="comment">// method to compare this property in plugin which is destined for that</span>
<a name="l00258"></a>00258 <span class="comment">// file format</span>
<a name="l00259"></a>00259 <span class="keywordflow">else</span>{
<a name="l00260"></a>00260 <span class="comment">// If exists plugin for that format try to find truth there</span>
<a name="l00261"></a>00261 <span class="keywordflow">for</span>(<span class="keyword">auto</span> pluginsIterator = PluginsFormats.begin(); pluginsIterator != PluginsFormats.end(); ++pluginsIterator) {
<a name="l00262"></a>00262 <span class="keywordflow">if</span>((*pluginsIterator)->IsSupportedFormat(file->GetExtension())){
<a name="l00263"></a>00263 <span class="keywordflow">return</span> (*pluginsIterator)->IsFileFullfillCondition(branch,file,property);
<a name="l00264"></a>00264 }
<a name="l00265"></a>00265 }
<a name="l00266"></a>00266 <span class="keywordflow">return</span> <span class="keyword">false</span>;
<a name="l00267"></a>00267 }
<a name="l00268"></a>00268 }
<a name="l00269"></a>00269
<a name="l00270"></a>00270
<a name="l00271"></a>00271
<a name="l00273"></a>00273 <span class="keywordtype">bool</span> BasicClassification::IsSizeConditionTrue(<a class="code" href="classTreeBranch.html" title="Branch of node.">TreeBranch</a> * branch, <a class="code" href="classFile.html" title="Represents file.">File</a> * file){
<a name="l00274"></a>00274 <span class="keywordflow">switch</span>(branch->GetOperand()){
<a name="l00275"></a>00275 <span class="keywordflow">case</span> LESS:
<a name="l00276"></a>00276 <span class="keywordflow">return</span> (file->GetSize() < branch->GetNumericValue()*MEGA);
<a name="l00277"></a>00277 <span class="keywordflow">case</span> LESS_EQUAL:
<a name="l00278"></a>00278 <span class="keywordflow">return</span> (file->GetSize() <= branch->GetNumericValue()*MEGA);
<a name="l00279"></a>00279 <span class="keywordflow">case</span> EQUAL:
<a name="l00280"></a>00280 <span class="keywordflow">return</span> (file->GetSize() == branch->GetNumericValue()*MEGA);
<a name="l00281"></a>00281 <span class="keywordflow">case</span> MORE:
<a name="l00282"></a>00282 <span class="keywordflow">return</span> (file->GetSize() > branch->GetNumericValue()*MEGA);
<a name="l00283"></a>00283 <span class="keywordflow">case</span> MORE_EQUAL:
<a name="l00284"></a>00284 <span class="keywordflow">return</span> (file->GetSize() >= branch->GetNumericValue()*MEGA);
<a name="l00285"></a>00285 }
<a name="l00286"></a>00286 <span class="keywordflow">return</span> <span class="keyword">false</span>;
<a name="l00287"></a>00287 }
<a name="l00288"></a>00288
<a name="l00290"></a>00290 <span class="keywordtype">bool</span> BasicClassification::IsCreationDateConditionTrue(<a class="code" href="classTreeBranch.html" title="Branch of node.">TreeBranch</a> * branch, <a class="code" href="classFile.html" title="Represents file.">File</a> * file){
<a name="l00291"></a>00291 <span class="keywordflow">switch</span>(branch->GetOperand()){
<a name="l00292"></a>00292 <span class="keywordflow">case</span> LESS:
<a name="l00293"></a>00293 <span class="keywordflow">return</span> (file->GetCreationDate() < branch->GetDateValue());
<a name="l00294"></a>00294 <span class="keywordflow">case</span> LESS_EQUAL:
<a name="l00295"></a>00295 <span class="keywordflow">return</span> (file->GetCreationDate() <= branch->GetDateValue());
<a name="l00296"></a>00296 <span class="keywordflow">case</span> EQUAL:
<a name="l00297"></a>00297 <span class="keywordflow">return</span> (file->GetCreationDate() == branch->GetDateValue());
<a name="l00298"></a>00298 <span class="keywordflow">case</span> MORE:
<a name="l00299"></a>00299 <span class="keywordflow">return</span> (file->GetCreationDate() > branch->GetDateValue());
<a name="l00300"></a>00300 <span class="keywordflow">case</span> MORE_EQUAL:
<a name="l00301"></a>00301 <span class="keywordflow">return</span> (file->GetCreationDate() >= branch->GetDateValue());
<a name="l00302"></a>00302 }
<a name="l00303"></a>00303 <span class="keywordflow">return</span> <span class="keyword">false</span>;
<a name="l00304"></a>00304 }
<a name="l00305"></a>00305
<a name="l00307"></a>00307 <span class="keywordtype">bool</span> BasicClassification::IsLastModificationDateConditionTrue(<a class="code" href="classTreeBranch.html" title="Branch of node.">TreeBranch</a> * branch, <a class="code" href="classFile.html" title="Represents file.">File</a> * file){
<a name="l00308"></a>00308 <span class="keywordflow">switch</span>(branch->GetOperand()){
<a name="l00309"></a>00309 <span class="keywordflow">case</span> LESS:
<a name="l00310"></a>00310 <span class="keywordflow">return</span> (file->GetLastModificationDateDate() < branch->GetDateValue());
<a name="l00311"></a>00311 <span class="keywordflow">case</span> LESS_EQUAL:
<a name="l00312"></a>00312 <span class="keywordflow">return</span> (file->GetLastModificationDateDate() <= branch->GetDateValue());
<a name="l00313"></a>00313 <span class="keywordflow">case</span> EQUAL:
<a name="l00314"></a>00314 <span class="keywordflow">return</span> (file->GetLastModificationDateDate() == branch->GetDateValue());
<a name="l00315"></a>00315 <span class="keywordflow">case</span> MORE:
<a name="l00316"></a>00316 <span class="keywordflow">return</span> (file->GetLastModificationDateDate() > branch->GetDateValue());
<a name="l00317"></a>00317 <span class="keywordflow">case</span> MORE_EQUAL:
<a name="l00318"></a>00318 <span class="keywordflow">return</span> (file->GetLastModificationDateDate() >= branch->GetDateValue());
<a name="l00319"></a>00319 }
<a name="l00320"></a>00320 <span class="keywordflow">return</span> <span class="keyword">false</span>;
<a name="l00321"></a>00321 }
<a name="l00322"></a>00322
<a name="l00324"></a>00324 <span class="keywordtype">bool</span> BasicClassification::IsNameConditionTrue(<a class="code" href="classTreeBranch.html" title="Branch of node.">TreeBranch</a> * branch, <a class="code" href="classFile.html" title="Represents file.">File</a> * file){
<a name="l00325"></a>00325 <span class="keywordflow">switch</span>(branch->GetOperand()){
<a name="l00326"></a>00326 <span class="keywordflow">case</span> EQUAL:
<a name="l00327"></a>00327 <span class="keywordflow">return</span> (file->GetBaseName() == branch->GetStringValue());
<a name="l00328"></a>00328 <span class="keywordflow">case</span> CONTAINS:
<a name="l00329"></a>00329 <span class="keywordflow">return</span> file->GetBaseName().contains(branch->GetStringValue(),Qt::CaseInsensitive);
<a name="l00330"></a>00330 <span class="keywordflow">case</span> NOT_CONTAINS:
<a name="l00331"></a>00331 <span class="keywordflow">return</span> !file->GetBaseName().contains(branch->GetStringValue(),Qt::CaseInsensitive);
<a name="l00332"></a>00332 }
<a name="l00333"></a>00333 <span class="keywordflow">return</span> <span class="keyword">false</span>;
<a name="l00334"></a>00334 }
<a name="l00335"></a>00335
<a name="l00337"></a>00337 <span class="keywordtype">bool</span> BasicClassification::IsExtensionConditionTrue(<a class="code" href="classTreeBranch.html" title="Branch of node.">TreeBranch</a> * branch, <a class="code" href="classFile.html" title="Represents file.">File</a> * file){
<a name="l00338"></a>00338 <span class="keywordflow">switch</span>(branch->GetOperand()){
<a name="l00339"></a>00339 <span class="keywordflow">case</span> EQUAL:
<a name="l00340"></a>00340 <span class="keywordflow">return</span> (file->GetExtension() == branch->GetStringValue());
<a name="l00341"></a>00341 <span class="keywordflow">case</span> CONTAINS:
<a name="l00342"></a>00342 <span class="keywordflow">return</span> file->GetExtension().contains(branch->GetStringValue(),Qt::CaseInsensitive);
<a name="l00343"></a>00343 <span class="keywordflow">case</span> NOT_CONTAINS:
<a name="l00344"></a>00344 <span class="keywordflow">return</span> !file->GetExtension().contains(branch->GetStringValue(),Qt::CaseInsensitive);
<a name="l00345"></a>00345 }
<a name="l00346"></a>00346 <span class="keywordflow">return</span> <span class="keyword">false</span>;
<a name="l00347"></a>00347 }
<a name="l00348"></a>00348
<a name="l00350"></a><a class="code" href="classBasicClassification.html#ad596956301c8a3821ad0a23a87c266cd">00350</a> QString <a class="code" href="classBasicClassification.html#ad596956301c8a3821ad0a23a87c266cd" title="Returning exact path for specific file based on file's properties.">BasicClassification::GetDistributionPath</a>(QString distribution,<a class="code" href="classFile.html" title="Represents file.">File</a> *file){
<a name="l00351"></a>00351 <span class="keywordflow">if</span>(distribution.isEmpty())
<a name="l00352"></a>00352 <span class="keywordflow">return</span> <span class="stringliteral">""</span>;
<a name="l00353"></a>00353
<a name="l00354"></a>00354 QString result = <span class="stringliteral">""</span>;
<a name="l00355"></a>00355 QStringList properties = distribution.split(<span class="stringliteral">"/"</span>);
<a name="l00356"></a>00356 QString midResult;
<a name="l00357"></a>00357 <span class="keywordflow">foreach</span>(QString str,properties){
<a name="l00358"></a>00358 midResult = <a class="code" href="classBasicClassification.html#a6e24dc1fa4f06b4dabdbd49357a22312" title="Returning property of specific file.">GetNextFolderForDistribution</a>(str,file);
<a name="l00359"></a>00359 <span class="keywordflow">if</span>(!midResult.isEmpty())
<a name="l00360"></a>00360 result += midResult+<span class="stringliteral">"/"</span>;
<a name="l00361"></a>00361 }
<a name="l00362"></a>00362 <span class="keywordflow">return</span> result;
<a name="l00363"></a>00363 }
<a name="l00364"></a>00364
<a name="l00366"></a><a class="code" href="classBasicClassification.html#a6e24dc1fa4f06b4dabdbd49357a22312">00366</a> QString <a class="code" href="classBasicClassification.html#a6e24dc1fa4f06b4dabdbd49357a22312" title="Returning property of specific file.">BasicClassification::GetNextFolderForDistribution</a>(QString property, <a class="code" href="classFile.html" title="Represents file.">File</a> *file){
<a name="l00367"></a>00367 <span class="keywordflow">if</span>(property == <span class="stringliteral">"Year"</span>)
<a name="l00368"></a>00368 <span class="keywordflow">return</span> QString::number(file->GetCreationYear());
<a name="l00369"></a>00369 <span class="keywordflow">else</span> <span class="keywordflow">if</span>(property == <span class="stringliteral">"Month"</span>)
<a name="l00370"></a>00370 <span class="keywordflow">return</span> QString::number(file->GetCreationMonth());
<a name="l00371"></a>00371 <span class="keywordflow">else</span> <span class="keywordflow">if</span>(property == <span class="stringliteral">"Day"</span>)
<a name="l00372"></a>00372 <span class="keywordflow">return</span> QString::number(file->GetCreationDay());
<a name="l00373"></a>00373 <span class="keywordflow">else</span> <span class="keywordflow">if</span>(property == <span class="stringliteral">"Extension"</span>)
<a name="l00374"></a>00374 <span class="keywordflow">return</span> file->GetExtension();
<a name="l00375"></a>00375 <span class="keywordflow">else</span>{
<a name="l00376"></a>00376 <span class="comment">// If exists plugin for that format try to find distribution path there</span>
<a name="l00377"></a>00377 <span class="keywordflow">for</span>(<span class="keyword">auto</span> pluginsIterator = PluginsFormats.begin(); pluginsIterator != PluginsFormats.end(); ++pluginsIterator) {
<a name="l00378"></a>00378 <span class="keywordflow">if</span>((*pluginsIterator)->IsSupportedFormat(file->GetExtension())){
<a name="l00379"></a>00379 <span class="keywordflow">return</span> (*pluginsIterator)->GetPropertyValueForDistribution(file,property);
<a name="l00380"></a>00380 }
<a name="l00381"></a>00381 }
<a name="l00382"></a>00382 }
<a name="l00383"></a>00383 <span class="keywordflow">return</span> <span class="stringliteral">"Default"</span>;
<a name="l00384"></a>00384 }
<a name="l00385"></a>00385
</pre></div></div><!-- contents -->
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Functions</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<hr class="footer"/><address class="footer"><small>
Generated on Fri May 15 2015 23:34:50 for SmartSorter by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.7.6.1
</small></address>
</body>
</html>
|
radimsvacek/SmartSorter
|
doc/basic__classif_8cpp_source.html
|
HTML
|
gpl-2.0
| 39,362
|
<?php
/**
* Plugin Name.
*
* @package Excel_Import
* @author Vincent Schroeder
* @license GPL-2.0+
* @link http://webteilchen.de
* @copyright 2013 Webteilchen
*/
function wp_excel_cms_get($name){
$excel_data = new WP_Excel_Cms();
return $excel_data->get_excel_data($name);
}
// [bartag foo="foo-value"]
function wp_excel_cms_shortcode( $atts ) {
extract( shortcode_atts( array(
'name' => '',
'template' => 'default',
), $atts ) );
$excel_data = new WP_Excel_Cms();
$data = $excel_data->get_excel_data($name);
$template = $excel_data->getTemplate($template, $data, $name);
return $template;
}
add_shortcode( 'wp_excel_cms', 'wp_excel_cms_shortcode' );
/**
* Plugin class. This class should ideally be used to work with the
* public-facing side of the WordPress site.
*
* If you're interested in introducing administrative or dashboard
* functionality, then refer to `class-plugin-name-admin.php`
*
* @TODO: Rename this class to a proper name for your plugin.
*
* @package Plugin_Name
* @author Vincent Schroeder
*/
class WP_Excel_Cms {
/**
* Plugin version, used for cache-busting of style and script file references.
*
* @since 1.0.0
*
* @var string
*/
const VERSION = '1.0.1';
/**
* @TODO - Rename "plugin-name" to the name your your plugin
*
* Unique identifier for your plugin.
*
*
* The variable name is used as the text domain when internationalizing strings
* of text. Its value should match the Text Domain file header in the main
* plugin file.
*
* @since 1.0.0
*
* @var string
*/
protected $plugin_slug = 'wp-excel-cms';
/**
* Instance of this class.
*
* @since 1.0.0
*
* @var object
*/
protected static $instance = null;
/**
* Initialize the plugin by setting localization and loading public scripts
* and styles.
*
* @since 1.0.0
*/
public function __construct() {
// Load plugin text domain
add_action( 'init', array( $this, 'load_plugin_textdomain' ) );
// Activate plugin when new blog is added
add_action( 'wpmu_new_blog', array( $this, 'activate_new_site' ) );
// Load public-facing style sheet and JavaScript.
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_styles' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
/* Define custom functionality.
* Refer To http://codex.wordpress.org/Plugin_API#Hooks.2C_Actions_and_Filters
*/
add_action( '@TODO', array( $this, 'action_method_name' ) );
add_filter( '@TODO', array( $this, 'filter_method_name' ) );
$upload_dir = wp_upload_dir();
$this->upload_base_url = $upload_dir['baseurl'].'/wp-excel-cms';
$this->upload_dir = $upload_dir['basedir'].'/wp-excel-cms';
$this->admin_plugin_url = admin_url( "options-general.php?page=".$_GET["page"] );
$this->plugin_dir = plugin_dir_path( __FILE__ );
$this->template_dir = $this->plugin_dir.'/templates';
}
public function getTemplate($template = 'default',$data = array(), $name = ''){
$template_path = $this->template_dir.'/'.$template .'.php';
ob_start();
include($template_path); //file_get_contents();
$out = ob_get_contents();
ob_end_clean();
return $out;
}
public function get_excel_data($name){
$file_name = $name.'.json';
$file_path_name = $this->upload_dir.'/'.$file_name;
return json_decode(file_get_contents($file_path_name));
$count = count($data);
# $data[0] => Kategorie
# $data[1] => Unterkategorie
# $data[2] => Name
# $data[3] => Preis
# $data[4] => Beschreibung
for($i=1;$i<$count;$i++){
$catIndex = strtolower($this->clean_str($data[$i][0]));
$subCatIndex = strtolower($this->clean_str($data[$i][1]));
if(!empty($catIndex)){
$categories[$catIndex] = $data[$i][0];
$subCategories[$subCatIndex] = $data[$i][1];
$preparedData[$catIndex][$subCatIndex][] = array(
'name' => $data[$i][2],
'price' => $data[$i][3],
'description' => $data[$i][4],
);
}
}
echo '<pre>';
print_r($preparedData);
echo '</pre>';
}
/**
* Return the plugin slug.
*
* @since 1.0.0
*
*@return Plugin slug variable.
*/
public function get_plugin_slug() {
return $this->plugin_slug;
}
/**
* Return an instance of this class.
*
* @since 1.0.0
*
* @return object A single instance of this class.
*/
public static function get_instance() {
// If the single instance hasn't been set, set it now.
if ( null == self::$instance ) {
self::$instance = new self;
}
return self::$instance;
}
/**
* Fired when the plugin is activated.
*
* @since 1.0.0
*
* @param boolean $network_wide True if WPMU superadmin uses
* "Network Activate" action, false if
* WPMU is disabled or plugin is
* activated on an individual blog.
*/
public static function activate( $network_wide ) {
if ( function_exists( 'is_multisite' ) && is_multisite() ) {
if ( $network_wide ) {
// Get all blog ids
$blog_ids = self::get_blog_ids();
foreach ( $blog_ids as $blog_id ) {
switch_to_blog( $blog_id );
self::single_activate();
}
restore_current_blog();
} else {
self::single_activate();
}
} else {
self::single_activate();
}
}
/**
* Fired when the plugin is deactivated.
*
* @since 1.0.0
*
* @param boolean $network_wide True if WPMU superadmin uses
* "Network Deactivate" action, false if
* WPMU is disabled or plugin is
* deactivated on an individual blog.
*/
public static function deactivate( $network_wide ) {
if ( function_exists( 'is_multisite' ) && is_multisite() ) {
if ( $network_wide ) {
// Get all blog ids
$blog_ids = self::get_blog_ids();
foreach ( $blog_ids as $blog_id ) {
switch_to_blog( $blog_id );
self::single_deactivate();
}
restore_current_blog();
} else {
self::single_deactivate();
}
} else {
self::single_deactivate();
}
}
/**
* Fired when a new site is activated with a WPMU environment.
*
* @since 1.0.0
*
* @param int $blog_id ID of the new blog.
*/
public function activate_new_site( $blog_id ) {
if ( 1 !== did_action( 'wpmu_new_blog' ) ) {
return;
}
switch_to_blog( $blog_id );
self::single_activate();
restore_current_blog();
}
/**
* Get all blog ids of blogs in the current network that are:
* - not archived
* - not spam
* - not deleted
*
* @since 1.0.0
*
* @return array|false The blog ids, false if no matches.
*/
private static function get_blog_ids() {
global $wpdb;
// get an array of blog ids
$sql = "SELECT blog_id FROM $wpdb->blogs
WHERE archived = '0' AND spam = '0'
AND deleted = '0'";
return $wpdb->get_col( $sql );
}
/**
* Fired for each blog when the plugin is activated.
*
* @since 1.0.0
*/
private static function single_activate() {
// @TODO: Define activation functionality here
}
/**
* Fired for each blog when the plugin is deactivated.
*
* @since 1.0.0
*/
private static function single_deactivate() {
// @TODO: Define deactivation functionality here
}
/**
* Load the plugin text domain for translation.
*
* @since 1.0.0
*/
public function load_plugin_textdomain() {
$domain = $this->plugin_slug;
$locale = apply_filters( 'plugin_locale', get_locale(), $domain );
load_textdomain( $domain, trailingslashit( WP_LANG_DIR ) . $domain . '/' . $domain . '-' . $locale . '.mo' );
}
/**
* Register and enqueue public-facing style sheet.
*
* @since 1.0.0
*/
public function enqueue_styles() {
wp_enqueue_style( $this->plugin_slug . '-plugin-styles', plugins_url( 'assets/css/public.css', __FILE__ ), array(), self::VERSION );
}
/**
* Register and enqueues public-facing JavaScript files.
*
* @since 1.0.0
*/
public function enqueue_scripts() {
wp_enqueue_script( $this->plugin_slug . '-plugin-script', plugins_url( 'assets/js/public.js', __FILE__ ), array( 'jquery' ), self::VERSION );
}
/**
* NOTE: Actions are points in the execution of a page or process
* lifecycle that WordPress fires.
*
* Actions: http://codex.wordpress.org/Plugin_API#Actions
* Reference: http://codex.wordpress.org/Plugin_API/Action_Reference
*
* @since 1.0.0
*/
public function action_method_name() {
// @TODO: Define your action hook callback here
}
/**
* NOTE: Filters are points of execution in which WordPress modifies data
* before saving it or sending it to the browser.
*
* Filters: http://codex.wordpress.org/Plugin_API#Filters
* Reference: http://codex.wordpress.org/Plugin_API/Filter_Reference
*
* @since 1.0.0
*/
public function filter_method_name() {
// @TODO: Define your filter hook callback here
}
}
|
clicker360/interlingua
|
wp-content/plugins/wp-excel-cms/public/wp-excel-cms.php
|
PHP
|
gpl-2.0
| 10,089
|
<?php
/**
* Cookie.class.php
*
* Copyright 2014- Samuli Järvelä
* Released under GPL License.
*
* License: http://www.cloudberryapp.com/license.php
*/
class Cookie {
private $settings = NULL;
function __construct($settings) {
$this->settings = $settings;
}
function add($name, $val, $expire = NULL) {
setcookie($this->getName($name), $val, $expire, "/");
}
function get($name) {
return $_COOKIE[$this->getName($name)];
}
function remove($name) {
$this->add($name, "", time()-42000);
}
function exists($name) {
return isset($_COOKIE[$this->getName($name)]);
}
private function getName($n) {
$id = $this->settings ? $this->settings->setting("session_name") : FALSE;
if (!$id) $id = "app";
return "cloudberry_".$id."_".$n;
}
}
?>
|
sjarvela/cloudberry
|
backend/_old/include/Cookie.class.php
|
PHP
|
gpl-2.0
| 815
|
/************************************************************************
$Id: gamecontroller.h,v 1.2 2005/02/24 10:27:53 jonico Exp $
RTB - Team Framework: Framework for RealTime Battle robots to communicate efficiently in a team
Copyright (C) 2004 The RTB- Team Framework Group: http://rtb-team.sourceforge.net
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
$Log: gamecontroller.h,v $
Revision 1.2 2005/02/24 10:27:53 jonico
Updated newest version of the framework
Revision 1.2 2005/01/06 17:59:32 jonico
Now all files in the repository have their new header format.
**************************************************************************/
#ifndef GAMECONTROLLER_H
#define GAMECONTROLLER_H
#include <exception>
/**
* Namespace GameControl
*/
namespace GameControl {
using std::bad_exception;
/**
* Class GameController
*/
class GameController {
/*
* Public stuff
*/
public:
/*
* Operations
*/
/**
* When this method will return, the whole sequence is over or an unrevoverable error has occured
* @return true for success, false for error
*/
virtual bool start () throw (bad_exception) =0; // I think, the GameContollers should handle all occuring exceptions by itself
/**
* destructor (does nothing)
*/
virtual ~GameController () throw () {};
};
}
#endif //GAMECONTROLLER_H
|
ezag/realtimebattle
|
rtb-team-framework/gamecontrol/gamecontroller.h
|
C
|
gpl-2.0
| 2,051
|
package it.unibas.freesbee.websla.ws.web.stub;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Classe Java per getServiziInf2ErogatiResponse complex type.
*
* <p>Il seguente frammento di schema specifica il contenuto previsto contenuto in questa classe.
*
* <pre>
* <complexType name="getServiziInf2ErogatiResponse">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="servizio" type="{http://web.ws.freesbeesla.unibas.it/}servizio" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "getServiziInf2ErogatiResponse", propOrder = {
"servizio"
})
public class GetServiziInf2ErogatiResponse {
protected List<Servizio> servizio;
/**
* Gets the value of the servizio property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the servizio property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getServizio().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Servizio }
*
*
*/
public List<Servizio> getServizio() {
if (servizio == null) {
servizio = new ArrayList<Servizio>();
}
return this.servizio;
}
}
|
donatellosantoro/freESBee
|
freesbeeWebSla/src/it/unibas/freesbee/websla/ws/web/stub/GetServiziInf2ErogatiResponse.java
|
Java
|
gpl-2.0
| 1,863
|
/*
* Copyright (c) 1998-2011 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package javax.inject;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.*;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* The @ApplicationScoped represents the servlet application scope
*/
@Scope
@Documented
@Retention(RUNTIME)
public @interface Singleton {
}
|
dlitz/resin
|
modules/webbeans/src/javax/inject/Singleton.java
|
Java
|
gpl-2.0
| 1,425
|
/* Instruction building/extraction support for fr30. -*- C -*-
THIS FILE IS MACHINE GENERATED WITH CGEN: Cpu tools GENerator.
- the resultant file is machine generated, cgen-ibld.in isn't
Copyright 1996, 1997, 1998, 1999, 2000, 2001, 2005
Free Software Foundation, Inc.
This file is part of the GNU Binutils and GDB, the GNU debugger.
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.,
51 Franklin Street - Fifth Floor, Boston, MA 02110-1301, USA. */
/* ??? Eventually more and more of this stuff can go to cpu-independent files.
Keep that in mind. */
#include "sysdep.h"
#include <stdio.h>
#include "ansidecl.h"
#include "dis-asm.h"
#include "bfd.h"
#include "symcat.h"
#include "fr30-desc.h"
#include "fr30-opc.h"
#include "opintl.h"
#include "safe-ctype.h"
#undef min
#define min(a,b) ((a) < (b) ? (a) : (b))
#undef max
#define max(a,b) ((a) > (b) ? (a) : (b))
/* Used by the ifield rtx function. */
#define FLD(f) (fields->f)
static const char * insert_normal
(CGEN_CPU_DESC, long, unsigned int, unsigned int, unsigned int,
unsigned int, unsigned int, unsigned int, CGEN_INSN_BYTES_PTR);
static const char * insert_insn_normal
(CGEN_CPU_DESC, const CGEN_INSN *,
CGEN_FIELDS *, CGEN_INSN_BYTES_PTR, bfd_vma);
static int extract_normal
(CGEN_CPU_DESC, CGEN_EXTRACT_INFO *, CGEN_INSN_INT,
unsigned int, unsigned int, unsigned int, unsigned int,
unsigned int, unsigned int, bfd_vma, long *);
static int extract_insn_normal
(CGEN_CPU_DESC, const CGEN_INSN *, CGEN_EXTRACT_INFO *,
CGEN_INSN_INT, CGEN_FIELDS *, bfd_vma);
#if CGEN_INT_INSN_P
static void put_insn_int_value
(CGEN_CPU_DESC, CGEN_INSN_BYTES_PTR, int, int, CGEN_INSN_INT);
#endif
#if ! CGEN_INT_INSN_P
static CGEN_INLINE void insert_1
(CGEN_CPU_DESC, unsigned long, int, int, int, unsigned char *);
static CGEN_INLINE int fill_cache
(CGEN_CPU_DESC, CGEN_EXTRACT_INFO *, int, int, bfd_vma);
static CGEN_INLINE long extract_1
(CGEN_CPU_DESC, CGEN_EXTRACT_INFO *, int, int, int, unsigned char *, bfd_vma);
#endif
/* Operand insertion. */
#if ! CGEN_INT_INSN_P
/* Subroutine of insert_normal. */
static CGEN_INLINE void
insert_1 (CGEN_CPU_DESC cd,
unsigned long value,
int start,
int length,
int word_length,
unsigned char *bufp)
{
unsigned long x,mask;
int shift;
x = cgen_get_insn_value (cd, bufp, word_length);
/* Written this way to avoid undefined behaviour. */
mask = (((1L << (length - 1)) - 1) << 1) | 1;
if (CGEN_INSN_LSB0_P)
shift = (start + 1) - length;
else
shift = (word_length - (start + length));
x = (x & ~(mask << shift)) | ((value & mask) << shift);
cgen_put_insn_value (cd, bufp, word_length, (bfd_vma) x);
}
#endif /* ! CGEN_INT_INSN_P */
/* Default insertion routine.
ATTRS is a mask of the boolean attributes.
WORD_OFFSET is the offset in bits from the start of the insn of the value.
WORD_LENGTH is the length of the word in bits in which the value resides.
START is the starting bit number in the word, architecture origin.
LENGTH is the length of VALUE in bits.
TOTAL_LENGTH is the total length of the insn in bits.
The result is an error message or NULL if success. */
/* ??? This duplicates functionality with bfd's howto table and
bfd_install_relocation. */
/* ??? This doesn't handle bfd_vma's. Create another function when
necessary. */
static const char *
insert_normal (CGEN_CPU_DESC cd,
long value,
unsigned int attrs,
unsigned int word_offset,
unsigned int start,
unsigned int length,
unsigned int word_length,
unsigned int total_length,
CGEN_INSN_BYTES_PTR buffer)
{
static char errbuf[100];
/* Written this way to avoid undefined behaviour. */
unsigned long mask = (((1L << (length - 1)) - 1) << 1) | 1;
/* If LENGTH is zero, this operand doesn't contribute to the value. */
if (length == 0)
return NULL;
if (word_length > 32)
abort ();
/* For architectures with insns smaller than the base-insn-bitsize,
word_length may be too big. */
if (cd->min_insn_bitsize < cd->base_insn_bitsize)
{
if (word_offset == 0
&& word_length > total_length)
word_length = total_length;
}
/* Ensure VALUE will fit. */
if (CGEN_BOOL_ATTR (attrs, CGEN_IFLD_SIGN_OPT))
{
long minval = - (1L << (length - 1));
unsigned long maxval = mask;
if ((value > 0 && (unsigned long) value > maxval)
|| value < minval)
{
/* xgettext:c-format */
sprintf (errbuf,
_("operand out of range (%ld not between %ld and %lu)"),
value, minval, maxval);
return errbuf;
}
}
else if (! CGEN_BOOL_ATTR (attrs, CGEN_IFLD_SIGNED))
{
unsigned long maxval = mask;
if ((unsigned long) value > maxval)
{
/* xgettext:c-format */
sprintf (errbuf,
_("operand out of range (%lu not between 0 and %lu)"),
value, maxval);
return errbuf;
}
}
else
{
if (! cgen_signed_overflow_ok_p (cd))
{
long minval = - (1L << (length - 1));
long maxval = (1L << (length - 1)) - 1;
if (value < minval || value > maxval)
{
sprintf
/* xgettext:c-format */
(errbuf, _("operand out of range (%ld not between %ld and %ld)"),
value, minval, maxval);
return errbuf;
}
}
}
#if CGEN_INT_INSN_P
{
int shift;
if (CGEN_INSN_LSB0_P)
shift = (word_offset + start + 1) - length;
else
shift = total_length - (word_offset + start + length);
*buffer = (*buffer & ~(mask << shift)) | ((value & mask) << shift);
}
#else /* ! CGEN_INT_INSN_P */
{
unsigned char *bufp = (unsigned char *) buffer + word_offset / 8;
insert_1 (cd, value, start, length, word_length, bufp);
}
#endif /* ! CGEN_INT_INSN_P */
return NULL;
}
/* Default insn builder (insert handler).
The instruction is recorded in CGEN_INT_INSN_P byte order (meaning
that if CGEN_INSN_BYTES_PTR is an int * and thus, the value is
recorded in host byte order, otherwise BUFFER is an array of bytes
and the value is recorded in target byte order).
The result is an error message or NULL if success. */
static const char *
insert_insn_normal (CGEN_CPU_DESC cd,
const CGEN_INSN * insn,
CGEN_FIELDS * fields,
CGEN_INSN_BYTES_PTR buffer,
bfd_vma pc)
{
const CGEN_SYNTAX *syntax = CGEN_INSN_SYNTAX (insn);
unsigned long value;
const CGEN_SYNTAX_CHAR_TYPE * syn;
CGEN_INIT_INSERT (cd);
value = CGEN_INSN_BASE_VALUE (insn);
/* If we're recording insns as numbers (rather than a string of bytes),
target byte order handling is deferred until later. */
#if CGEN_INT_INSN_P
put_insn_int_value (cd, buffer, cd->base_insn_bitsize,
CGEN_FIELDS_BITSIZE (fields), value);
#else
cgen_put_insn_value (cd, buffer, min ((unsigned) cd->base_insn_bitsize,
(unsigned) CGEN_FIELDS_BITSIZE (fields)),
value);
#endif /* ! CGEN_INT_INSN_P */
/* ??? It would be better to scan the format's fields.
Still need to be able to insert a value based on the operand though;
e.g. storing a branch displacement that got resolved later.
Needs more thought first. */
for (syn = CGEN_SYNTAX_STRING (syntax); * syn; ++ syn)
{
const char *errmsg;
if (CGEN_SYNTAX_CHAR_P (* syn))
continue;
errmsg = (* cd->insert_operand) (cd, CGEN_SYNTAX_FIELD (*syn),
fields, buffer, pc);
if (errmsg)
return errmsg;
}
return NULL;
}
#if CGEN_INT_INSN_P
/* Cover function to store an insn value into an integral insn. Must go here
because it needs <prefix>-desc.h for CGEN_INT_INSN_P. */
static void
put_insn_int_value (CGEN_CPU_DESC cd ATTRIBUTE_UNUSED,
CGEN_INSN_BYTES_PTR buf,
int length,
int insn_length,
CGEN_INSN_INT value)
{
/* For architectures with insns smaller than the base-insn-bitsize,
length may be too big. */
if (length > insn_length)
*buf = value;
else
{
int shift = insn_length - length;
/* Written this way to avoid undefined behaviour. */
CGEN_INSN_INT mask = (((1L << (length - 1)) - 1) << 1) | 1;
*buf = (*buf & ~(mask << shift)) | ((value & mask) << shift);
}
}
#endif
/* Operand extraction. */
#if ! CGEN_INT_INSN_P
/* Subroutine of extract_normal.
Ensure sufficient bytes are cached in EX_INFO.
OFFSET is the offset in bytes from the start of the insn of the value.
BYTES is the length of the needed value.
Returns 1 for success, 0 for failure. */
static CGEN_INLINE int
fill_cache (CGEN_CPU_DESC cd ATTRIBUTE_UNUSED,
CGEN_EXTRACT_INFO *ex_info,
int offset,
int bytes,
bfd_vma pc)
{
/* It's doubtful that the middle part has already been fetched so
we don't optimize that case. kiss. */
unsigned int mask;
disassemble_info *info = (disassemble_info *) ex_info->dis_info;
/* First do a quick check. */
mask = (1 << bytes) - 1;
if (((ex_info->valid >> offset) & mask) == mask)
return 1;
/* Search for the first byte we need to read. */
for (mask = 1 << offset; bytes > 0; --bytes, ++offset, mask <<= 1)
if (! (mask & ex_info->valid))
break;
if (bytes)
{
int status;
pc += offset;
status = (*info->read_memory_func)
(pc, ex_info->insn_bytes + offset, bytes, info);
if (status != 0)
{
(*info->memory_error_func) (status, pc, info);
return 0;
}
ex_info->valid |= ((1 << bytes) - 1) << offset;
}
return 1;
}
/* Subroutine of extract_normal. */
static CGEN_INLINE long
extract_1 (CGEN_CPU_DESC cd,
CGEN_EXTRACT_INFO *ex_info ATTRIBUTE_UNUSED,
int start,
int length,
int word_length,
unsigned char *bufp,
bfd_vma pc ATTRIBUTE_UNUSED)
{
unsigned long x;
int shift;
x = cgen_get_insn_value (cd, bufp, word_length);
if (CGEN_INSN_LSB0_P)
shift = (start + 1) - length;
else
shift = (word_length - (start + length));
return x >> shift;
}
#endif /* ! CGEN_INT_INSN_P */
/* Default extraction routine.
INSN_VALUE is the first base_insn_bitsize bits of the insn in host order,
or sometimes less for cases like the m32r where the base insn size is 32
but some insns are 16 bits.
ATTRS is a mask of the boolean attributes. We only need `SIGNED',
but for generality we take a bitmask of all of them.
WORD_OFFSET is the offset in bits from the start of the insn of the value.
WORD_LENGTH is the length of the word in bits in which the value resides.
START is the starting bit number in the word, architecture origin.
LENGTH is the length of VALUE in bits.
TOTAL_LENGTH is the total length of the insn in bits.
Returns 1 for success, 0 for failure. */
/* ??? The return code isn't properly used. wip. */
/* ??? This doesn't handle bfd_vma's. Create another function when
necessary. */
static int
extract_normal (CGEN_CPU_DESC cd,
#if ! CGEN_INT_INSN_P
CGEN_EXTRACT_INFO *ex_info,
#else
CGEN_EXTRACT_INFO *ex_info ATTRIBUTE_UNUSED,
#endif
CGEN_INSN_INT insn_value,
unsigned int attrs,
unsigned int word_offset,
unsigned int start,
unsigned int length,
unsigned int word_length,
unsigned int total_length,
#if ! CGEN_INT_INSN_P
bfd_vma pc,
#else
bfd_vma pc ATTRIBUTE_UNUSED,
#endif
long *valuep)
{
long value, mask;
/* If LENGTH is zero, this operand doesn't contribute to the value
so give it a standard value of zero. */
if (length == 0)
{
*valuep = 0;
return 1;
}
if (word_length > 32)
abort ();
/* For architectures with insns smaller than the insn-base-bitsize,
word_length may be too big. */
if (cd->min_insn_bitsize < cd->base_insn_bitsize)
{
if (word_offset == 0
&& word_length > total_length)
word_length = total_length;
}
/* Does the value reside in INSN_VALUE, and at the right alignment? */
if (CGEN_INT_INSN_P || (word_offset == 0 && word_length == total_length))
{
if (CGEN_INSN_LSB0_P)
value = insn_value >> ((word_offset + start + 1) - length);
else
value = insn_value >> (total_length - ( word_offset + start + length));
}
#if ! CGEN_INT_INSN_P
else
{
unsigned char *bufp = ex_info->insn_bytes + word_offset / 8;
if (word_length > 32)
abort ();
if (fill_cache (cd, ex_info, word_offset / 8, word_length / 8, pc) == 0)
return 0;
value = extract_1 (cd, ex_info, start, length, word_length, bufp, pc);
}
#endif /* ! CGEN_INT_INSN_P */
/* Written this way to avoid undefined behaviour. */
mask = (((1L << (length - 1)) - 1) << 1) | 1;
value &= mask;
/* sign extend? */
if (CGEN_BOOL_ATTR (attrs, CGEN_IFLD_SIGNED)
&& (value & (1L << (length - 1))))
value |= ~mask;
*valuep = value;
return 1;
}
/* Default insn extractor.
INSN_VALUE is the first base_insn_bitsize bits, translated to host order.
The extracted fields are stored in FIELDS.
EX_INFO is used to handle reading variable length insns.
Return the length of the insn in bits, or 0 if no match,
or -1 if an error occurs fetching data (memory_error_func will have
been called). */
static int
extract_insn_normal (CGEN_CPU_DESC cd,
const CGEN_INSN *insn,
CGEN_EXTRACT_INFO *ex_info,
CGEN_INSN_INT insn_value,
CGEN_FIELDS *fields,
bfd_vma pc)
{
const CGEN_SYNTAX *syntax = CGEN_INSN_SYNTAX (insn);
const CGEN_SYNTAX_CHAR_TYPE *syn;
CGEN_FIELDS_BITSIZE (fields) = CGEN_INSN_BITSIZE (insn);
CGEN_INIT_EXTRACT (cd);
for (syn = CGEN_SYNTAX_STRING (syntax); *syn; ++syn)
{
int length;
if (CGEN_SYNTAX_CHAR_P (*syn))
continue;
length = (* cd->extract_operand) (cd, CGEN_SYNTAX_FIELD (*syn),
ex_info, insn_value, fields, pc);
if (length <= 0)
return length;
}
/* We recognized and successfully extracted this insn. */
return CGEN_INSN_BITSIZE (insn);
}
/* Machine generated code added here. */
const char * fr30_cgen_insert_operand
(CGEN_CPU_DESC, int, CGEN_FIELDS *, CGEN_INSN_BYTES_PTR, bfd_vma);
/* Main entry point for operand insertion.
This function is basically just a big switch statement. Earlier versions
used tables to look up the function to use, but
- if the table contains both assembler and disassembler functions then
the disassembler contains much of the assembler and vice-versa,
- there's a lot of inlining possibilities as things grow,
- using a switch statement avoids the function call overhead.
This function could be moved into `parse_insn_normal', but keeping it
separate makes clear the interface between `parse_insn_normal' and each of
the handlers. It's also needed by GAS to insert operands that couldn't be
resolved during parsing. */
const char *
fr30_cgen_insert_operand (CGEN_CPU_DESC cd,
int opindex,
CGEN_FIELDS * fields,
CGEN_INSN_BYTES_PTR buffer,
bfd_vma pc ATTRIBUTE_UNUSED)
{
const char * errmsg = NULL;
unsigned int total_length = CGEN_FIELDS_BITSIZE (fields);
switch (opindex)
{
case FR30_OPERAND_CRI :
errmsg = insert_normal (cd, fields->f_CRi, 0, 16, 12, 4, 16, total_length, buffer);
break;
case FR30_OPERAND_CRJ :
errmsg = insert_normal (cd, fields->f_CRj, 0, 16, 8, 4, 16, total_length, buffer);
break;
case FR30_OPERAND_R13 :
break;
case FR30_OPERAND_R14 :
break;
case FR30_OPERAND_R15 :
break;
case FR30_OPERAND_RI :
errmsg = insert_normal (cd, fields->f_Ri, 0, 0, 12, 4, 16, total_length, buffer);
break;
case FR30_OPERAND_RIC :
errmsg = insert_normal (cd, fields->f_Ric, 0, 16, 12, 4, 16, total_length, buffer);
break;
case FR30_OPERAND_RJ :
errmsg = insert_normal (cd, fields->f_Rj, 0, 0, 8, 4, 16, total_length, buffer);
break;
case FR30_OPERAND_RJC :
errmsg = insert_normal (cd, fields->f_Rjc, 0, 16, 8, 4, 16, total_length, buffer);
break;
case FR30_OPERAND_RS1 :
errmsg = insert_normal (cd, fields->f_Rs1, 0, 0, 8, 4, 16, total_length, buffer);
break;
case FR30_OPERAND_RS2 :
errmsg = insert_normal (cd, fields->f_Rs2, 0, 0, 12, 4, 16, total_length, buffer);
break;
case FR30_OPERAND_CC :
errmsg = insert_normal (cd, fields->f_cc, 0, 0, 4, 4, 16, total_length, buffer);
break;
case FR30_OPERAND_CCC :
errmsg = insert_normal (cd, fields->f_ccc, 0, 16, 0, 8, 16, total_length, buffer);
break;
case FR30_OPERAND_DIR10 :
{
long value = fields->f_dir10;
value = ((unsigned int) (value) >> (2));
errmsg = insert_normal (cd, value, 0, 0, 8, 8, 16, total_length, buffer);
}
break;
case FR30_OPERAND_DIR8 :
errmsg = insert_normal (cd, fields->f_dir8, 0, 0, 8, 8, 16, total_length, buffer);
break;
case FR30_OPERAND_DIR9 :
{
long value = fields->f_dir9;
value = ((unsigned int) (value) >> (1));
errmsg = insert_normal (cd, value, 0, 0, 8, 8, 16, total_length, buffer);
}
break;
case FR30_OPERAND_DISP10 :
{
long value = fields->f_disp10;
value = ((int) (value) >> (2));
errmsg = insert_normal (cd, value, 0|(1<<CGEN_IFLD_SIGNED), 0, 4, 8, 16, total_length, buffer);
}
break;
case FR30_OPERAND_DISP8 :
errmsg = insert_normal (cd, fields->f_disp8, 0|(1<<CGEN_IFLD_SIGNED), 0, 4, 8, 16, total_length, buffer);
break;
case FR30_OPERAND_DISP9 :
{
long value = fields->f_disp9;
value = ((int) (value) >> (1));
errmsg = insert_normal (cd, value, 0|(1<<CGEN_IFLD_SIGNED), 0, 4, 8, 16, total_length, buffer);
}
break;
case FR30_OPERAND_I20 :
{
{
FLD (f_i20_4) = ((unsigned int) (FLD (f_i20)) >> (16));
FLD (f_i20_16) = ((FLD (f_i20)) & (65535));
}
errmsg = insert_normal (cd, fields->f_i20_4, 0, 0, 8, 4, 16, total_length, buffer);
if (errmsg)
break;
errmsg = insert_normal (cd, fields->f_i20_16, 0, 16, 0, 16, 16, total_length, buffer);
if (errmsg)
break;
}
break;
case FR30_OPERAND_I32 :
errmsg = insert_normal (cd, fields->f_i32, 0|(1<<CGEN_IFLD_SIGN_OPT), 16, 0, 32, 32, total_length, buffer);
break;
case FR30_OPERAND_I8 :
errmsg = insert_normal (cd, fields->f_i8, 0, 0, 4, 8, 16, total_length, buffer);
break;
case FR30_OPERAND_LABEL12 :
{
long value = fields->f_rel12;
value = ((int) (((value) - (((pc) + (2))))) >> (1));
errmsg = insert_normal (cd, value, 0|(1<<CGEN_IFLD_SIGNED)|(1<<CGEN_IFLD_PCREL_ADDR), 0, 5, 11, 16, total_length, buffer);
}
break;
case FR30_OPERAND_LABEL9 :
{
long value = fields->f_rel9;
value = ((int) (((value) - (((pc) + (2))))) >> (1));
errmsg = insert_normal (cd, value, 0|(1<<CGEN_IFLD_SIGNED)|(1<<CGEN_IFLD_PCREL_ADDR), 0, 8, 8, 16, total_length, buffer);
}
break;
case FR30_OPERAND_M4 :
{
long value = fields->f_m4;
value = ((value) & (15));
errmsg = insert_normal (cd, value, 0, 0, 8, 4, 16, total_length, buffer);
}
break;
case FR30_OPERAND_PS :
break;
case FR30_OPERAND_REGLIST_HI_LD :
errmsg = insert_normal (cd, fields->f_reglist_hi_ld, 0, 0, 8, 8, 16, total_length, buffer);
break;
case FR30_OPERAND_REGLIST_HI_ST :
errmsg = insert_normal (cd, fields->f_reglist_hi_st, 0, 0, 8, 8, 16, total_length, buffer);
break;
case FR30_OPERAND_REGLIST_LOW_LD :
errmsg = insert_normal (cd, fields->f_reglist_low_ld, 0, 0, 8, 8, 16, total_length, buffer);
break;
case FR30_OPERAND_REGLIST_LOW_ST :
errmsg = insert_normal (cd, fields->f_reglist_low_st, 0, 0, 8, 8, 16, total_length, buffer);
break;
case FR30_OPERAND_S10 :
{
long value = fields->f_s10;
value = ((int) (value) >> (2));
errmsg = insert_normal (cd, value, 0|(1<<CGEN_IFLD_SIGNED), 0, 8, 8, 16, total_length, buffer);
}
break;
case FR30_OPERAND_U10 :
{
long value = fields->f_u10;
value = ((unsigned int) (value) >> (2));
errmsg = insert_normal (cd, value, 0, 0, 8, 8, 16, total_length, buffer);
}
break;
case FR30_OPERAND_U4 :
errmsg = insert_normal (cd, fields->f_u4, 0, 0, 8, 4, 16, total_length, buffer);
break;
case FR30_OPERAND_U4C :
errmsg = insert_normal (cd, fields->f_u4c, 0, 0, 12, 4, 16, total_length, buffer);
break;
case FR30_OPERAND_U8 :
errmsg = insert_normal (cd, fields->f_u8, 0, 0, 8, 8, 16, total_length, buffer);
break;
case FR30_OPERAND_UDISP6 :
{
long value = fields->f_udisp6;
value = ((unsigned int) (value) >> (2));
errmsg = insert_normal (cd, value, 0, 0, 8, 4, 16, total_length, buffer);
}
break;
default :
/* xgettext:c-format */
fprintf (stderr, _("Unrecognized field %d while building insn.\n"),
opindex);
abort ();
}
return errmsg;
}
int fr30_cgen_extract_operand
(CGEN_CPU_DESC, int, CGEN_EXTRACT_INFO *, CGEN_INSN_INT, CGEN_FIELDS *, bfd_vma);
/* Main entry point for operand extraction.
The result is <= 0 for error, >0 for success.
??? Actual values aren't well defined right now.
This function is basically just a big switch statement. Earlier versions
used tables to look up the function to use, but
- if the table contains both assembler and disassembler functions then
the disassembler contains much of the assembler and vice-versa,
- there's a lot of inlining possibilities as things grow,
- using a switch statement avoids the function call overhead.
This function could be moved into `print_insn_normal', but keeping it
separate makes clear the interface between `print_insn_normal' and each of
the handlers. */
int
fr30_cgen_extract_operand (CGEN_CPU_DESC cd,
int opindex,
CGEN_EXTRACT_INFO *ex_info,
CGEN_INSN_INT insn_value,
CGEN_FIELDS * fields,
bfd_vma pc)
{
/* Assume success (for those operands that are nops). */
int length = 1;
unsigned int total_length = CGEN_FIELDS_BITSIZE (fields);
switch (opindex)
{
case FR30_OPERAND_CRI :
length = extract_normal (cd, ex_info, insn_value, 0, 16, 12, 4, 16, total_length, pc, & fields->f_CRi);
break;
case FR30_OPERAND_CRJ :
length = extract_normal (cd, ex_info, insn_value, 0, 16, 8, 4, 16, total_length, pc, & fields->f_CRj);
break;
case FR30_OPERAND_R13 :
break;
case FR30_OPERAND_R14 :
break;
case FR30_OPERAND_R15 :
break;
case FR30_OPERAND_RI :
length = extract_normal (cd, ex_info, insn_value, 0, 0, 12, 4, 16, total_length, pc, & fields->f_Ri);
break;
case FR30_OPERAND_RIC :
length = extract_normal (cd, ex_info, insn_value, 0, 16, 12, 4, 16, total_length, pc, & fields->f_Ric);
break;
case FR30_OPERAND_RJ :
length = extract_normal (cd, ex_info, insn_value, 0, 0, 8, 4, 16, total_length, pc, & fields->f_Rj);
break;
case FR30_OPERAND_RJC :
length = extract_normal (cd, ex_info, insn_value, 0, 16, 8, 4, 16, total_length, pc, & fields->f_Rjc);
break;
case FR30_OPERAND_RS1 :
length = extract_normal (cd, ex_info, insn_value, 0, 0, 8, 4, 16, total_length, pc, & fields->f_Rs1);
break;
case FR30_OPERAND_RS2 :
length = extract_normal (cd, ex_info, insn_value, 0, 0, 12, 4, 16, total_length, pc, & fields->f_Rs2);
break;
case FR30_OPERAND_CC :
length = extract_normal (cd, ex_info, insn_value, 0, 0, 4, 4, 16, total_length, pc, & fields->f_cc);
break;
case FR30_OPERAND_CCC :
length = extract_normal (cd, ex_info, insn_value, 0, 16, 0, 8, 16, total_length, pc, & fields->f_ccc);
break;
case FR30_OPERAND_DIR10 :
{
long value;
length = extract_normal (cd, ex_info, insn_value, 0, 0, 8, 8, 16, total_length, pc, & value);
value = ((value) << (2));
fields->f_dir10 = value;
}
break;
case FR30_OPERAND_DIR8 :
length = extract_normal (cd, ex_info, insn_value, 0, 0, 8, 8, 16, total_length, pc, & fields->f_dir8);
break;
case FR30_OPERAND_DIR9 :
{
long value;
length = extract_normal (cd, ex_info, insn_value, 0, 0, 8, 8, 16, total_length, pc, & value);
value = ((value) << (1));
fields->f_dir9 = value;
}
break;
case FR30_OPERAND_DISP10 :
{
long value;
length = extract_normal (cd, ex_info, insn_value, 0|(1<<CGEN_IFLD_SIGNED), 0, 4, 8, 16, total_length, pc, & value);
value = ((value) << (2));
fields->f_disp10 = value;
}
break;
case FR30_OPERAND_DISP8 :
length = extract_normal (cd, ex_info, insn_value, 0|(1<<CGEN_IFLD_SIGNED), 0, 4, 8, 16, total_length, pc, & fields->f_disp8);
break;
case FR30_OPERAND_DISP9 :
{
long value;
length = extract_normal (cd, ex_info, insn_value, 0|(1<<CGEN_IFLD_SIGNED), 0, 4, 8, 16, total_length, pc, & value);
value = ((value) << (1));
fields->f_disp9 = value;
}
break;
case FR30_OPERAND_I20 :
{
length = extract_normal (cd, ex_info, insn_value, 0, 0, 8, 4, 16, total_length, pc, & fields->f_i20_4);
if (length <= 0) break;
length = extract_normal (cd, ex_info, insn_value, 0, 16, 0, 16, 16, total_length, pc, & fields->f_i20_16);
if (length <= 0) break;
{
FLD (f_i20) = ((((FLD (f_i20_4)) << (16))) | (FLD (f_i20_16)));
}
}
break;
case FR30_OPERAND_I32 :
length = extract_normal (cd, ex_info, insn_value, 0|(1<<CGEN_IFLD_SIGN_OPT), 16, 0, 32, 32, total_length, pc, & fields->f_i32);
break;
case FR30_OPERAND_I8 :
length = extract_normal (cd, ex_info, insn_value, 0, 0, 4, 8, 16, total_length, pc, & fields->f_i8);
break;
case FR30_OPERAND_LABEL12 :
{
long value;
length = extract_normal (cd, ex_info, insn_value, 0|(1<<CGEN_IFLD_SIGNED)|(1<<CGEN_IFLD_PCREL_ADDR), 0, 5, 11, 16, total_length, pc, & value);
value = ((((value) << (1))) + (((pc) + (2))));
fields->f_rel12 = value;
}
break;
case FR30_OPERAND_LABEL9 :
{
long value;
length = extract_normal (cd, ex_info, insn_value, 0|(1<<CGEN_IFLD_SIGNED)|(1<<CGEN_IFLD_PCREL_ADDR), 0, 8, 8, 16, total_length, pc, & value);
value = ((((value) << (1))) + (((pc) + (2))));
fields->f_rel9 = value;
}
break;
case FR30_OPERAND_M4 :
{
long value;
length = extract_normal (cd, ex_info, insn_value, 0, 0, 8, 4, 16, total_length, pc, & value);
value = ((value) | (((-1) << (4))));
fields->f_m4 = value;
}
break;
case FR30_OPERAND_PS :
break;
case FR30_OPERAND_REGLIST_HI_LD :
length = extract_normal (cd, ex_info, insn_value, 0, 0, 8, 8, 16, total_length, pc, & fields->f_reglist_hi_ld);
break;
case FR30_OPERAND_REGLIST_HI_ST :
length = extract_normal (cd, ex_info, insn_value, 0, 0, 8, 8, 16, total_length, pc, & fields->f_reglist_hi_st);
break;
case FR30_OPERAND_REGLIST_LOW_LD :
length = extract_normal (cd, ex_info, insn_value, 0, 0, 8, 8, 16, total_length, pc, & fields->f_reglist_low_ld);
break;
case FR30_OPERAND_REGLIST_LOW_ST :
length = extract_normal (cd, ex_info, insn_value, 0, 0, 8, 8, 16, total_length, pc, & fields->f_reglist_low_st);
break;
case FR30_OPERAND_S10 :
{
long value;
length = extract_normal (cd, ex_info, insn_value, 0|(1<<CGEN_IFLD_SIGNED), 0, 8, 8, 16, total_length, pc, & value);
value = ((value) << (2));
fields->f_s10 = value;
}
break;
case FR30_OPERAND_U10 :
{
long value;
length = extract_normal (cd, ex_info, insn_value, 0, 0, 8, 8, 16, total_length, pc, & value);
value = ((value) << (2));
fields->f_u10 = value;
}
break;
case FR30_OPERAND_U4 :
length = extract_normal (cd, ex_info, insn_value, 0, 0, 8, 4, 16, total_length, pc, & fields->f_u4);
break;
case FR30_OPERAND_U4C :
length = extract_normal (cd, ex_info, insn_value, 0, 0, 12, 4, 16, total_length, pc, & fields->f_u4c);
break;
case FR30_OPERAND_U8 :
length = extract_normal (cd, ex_info, insn_value, 0, 0, 8, 8, 16, total_length, pc, & fields->f_u8);
break;
case FR30_OPERAND_UDISP6 :
{
long value;
length = extract_normal (cd, ex_info, insn_value, 0, 0, 8, 4, 16, total_length, pc, & value);
value = ((value) << (2));
fields->f_udisp6 = value;
}
break;
default :
/* xgettext:c-format */
fprintf (stderr, _("Unrecognized field %d while decoding insn.\n"),
opindex);
abort ();
}
return length;
}
cgen_insert_fn * const fr30_cgen_insert_handlers[] =
{
insert_insn_normal,
};
cgen_extract_fn * const fr30_cgen_extract_handlers[] =
{
extract_insn_normal,
};
int fr30_cgen_get_int_operand (CGEN_CPU_DESC, int, const CGEN_FIELDS *);
bfd_vma fr30_cgen_get_vma_operand (CGEN_CPU_DESC, int, const CGEN_FIELDS *);
/* Getting values from cgen_fields is handled by a collection of functions.
They are distinguished by the type of the VALUE argument they return.
TODO: floating point, inlining support, remove cases where result type
not appropriate. */
int
fr30_cgen_get_int_operand (CGEN_CPU_DESC cd ATTRIBUTE_UNUSED,
int opindex,
const CGEN_FIELDS * fields)
{
int value;
switch (opindex)
{
case FR30_OPERAND_CRI :
value = fields->f_CRi;
break;
case FR30_OPERAND_CRJ :
value = fields->f_CRj;
break;
case FR30_OPERAND_R13 :
value = 0;
break;
case FR30_OPERAND_R14 :
value = 0;
break;
case FR30_OPERAND_R15 :
value = 0;
break;
case FR30_OPERAND_RI :
value = fields->f_Ri;
break;
case FR30_OPERAND_RIC :
value = fields->f_Ric;
break;
case FR30_OPERAND_RJ :
value = fields->f_Rj;
break;
case FR30_OPERAND_RJC :
value = fields->f_Rjc;
break;
case FR30_OPERAND_RS1 :
value = fields->f_Rs1;
break;
case FR30_OPERAND_RS2 :
value = fields->f_Rs2;
break;
case FR30_OPERAND_CC :
value = fields->f_cc;
break;
case FR30_OPERAND_CCC :
value = fields->f_ccc;
break;
case FR30_OPERAND_DIR10 :
value = fields->f_dir10;
break;
case FR30_OPERAND_DIR8 :
value = fields->f_dir8;
break;
case FR30_OPERAND_DIR9 :
value = fields->f_dir9;
break;
case FR30_OPERAND_DISP10 :
value = fields->f_disp10;
break;
case FR30_OPERAND_DISP8 :
value = fields->f_disp8;
break;
case FR30_OPERAND_DISP9 :
value = fields->f_disp9;
break;
case FR30_OPERAND_I20 :
value = fields->f_i20;
break;
case FR30_OPERAND_I32 :
value = fields->f_i32;
break;
case FR30_OPERAND_I8 :
value = fields->f_i8;
break;
case FR30_OPERAND_LABEL12 :
value = fields->f_rel12;
break;
case FR30_OPERAND_LABEL9 :
value = fields->f_rel9;
break;
case FR30_OPERAND_M4 :
value = fields->f_m4;
break;
case FR30_OPERAND_PS :
value = 0;
break;
case FR30_OPERAND_REGLIST_HI_LD :
value = fields->f_reglist_hi_ld;
break;
case FR30_OPERAND_REGLIST_HI_ST :
value = fields->f_reglist_hi_st;
break;
case FR30_OPERAND_REGLIST_LOW_LD :
value = fields->f_reglist_low_ld;
break;
case FR30_OPERAND_REGLIST_LOW_ST :
value = fields->f_reglist_low_st;
break;
case FR30_OPERAND_S10 :
value = fields->f_s10;
break;
case FR30_OPERAND_U10 :
value = fields->f_u10;
break;
case FR30_OPERAND_U4 :
value = fields->f_u4;
break;
case FR30_OPERAND_U4C :
value = fields->f_u4c;
break;
case FR30_OPERAND_U8 :
value = fields->f_u8;
break;
case FR30_OPERAND_UDISP6 :
value = fields->f_udisp6;
break;
default :
/* xgettext:c-format */
fprintf (stderr, _("Unrecognized field %d while getting int operand.\n"),
opindex);
abort ();
}
return value;
}
bfd_vma
fr30_cgen_get_vma_operand (CGEN_CPU_DESC cd ATTRIBUTE_UNUSED,
int opindex,
const CGEN_FIELDS * fields)
{
bfd_vma value;
switch (opindex)
{
case FR30_OPERAND_CRI :
value = fields->f_CRi;
break;
case FR30_OPERAND_CRJ :
value = fields->f_CRj;
break;
case FR30_OPERAND_R13 :
value = 0;
break;
case FR30_OPERAND_R14 :
value = 0;
break;
case FR30_OPERAND_R15 :
value = 0;
break;
case FR30_OPERAND_RI :
value = fields->f_Ri;
break;
case FR30_OPERAND_RIC :
value = fields->f_Ric;
break;
case FR30_OPERAND_RJ :
value = fields->f_Rj;
break;
case FR30_OPERAND_RJC :
value = fields->f_Rjc;
break;
case FR30_OPERAND_RS1 :
value = fields->f_Rs1;
break;
case FR30_OPERAND_RS2 :
value = fields->f_Rs2;
break;
case FR30_OPERAND_CC :
value = fields->f_cc;
break;
case FR30_OPERAND_CCC :
value = fields->f_ccc;
break;
case FR30_OPERAND_DIR10 :
value = fields->f_dir10;
break;
case FR30_OPERAND_DIR8 :
value = fields->f_dir8;
break;
case FR30_OPERAND_DIR9 :
value = fields->f_dir9;
break;
case FR30_OPERAND_DISP10 :
value = fields->f_disp10;
break;
case FR30_OPERAND_DISP8 :
value = fields->f_disp8;
break;
case FR30_OPERAND_DISP9 :
value = fields->f_disp9;
break;
case FR30_OPERAND_I20 :
value = fields->f_i20;
break;
case FR30_OPERAND_I32 :
value = fields->f_i32;
break;
case FR30_OPERAND_I8 :
value = fields->f_i8;
break;
case FR30_OPERAND_LABEL12 :
value = fields->f_rel12;
break;
case FR30_OPERAND_LABEL9 :
value = fields->f_rel9;
break;
case FR30_OPERAND_M4 :
value = fields->f_m4;
break;
case FR30_OPERAND_PS :
value = 0;
break;
case FR30_OPERAND_REGLIST_HI_LD :
value = fields->f_reglist_hi_ld;
break;
case FR30_OPERAND_REGLIST_HI_ST :
value = fields->f_reglist_hi_st;
break;
case FR30_OPERAND_REGLIST_LOW_LD :
value = fields->f_reglist_low_ld;
break;
case FR30_OPERAND_REGLIST_LOW_ST :
value = fields->f_reglist_low_st;
break;
case FR30_OPERAND_S10 :
value = fields->f_s10;
break;
case FR30_OPERAND_U10 :
value = fields->f_u10;
break;
case FR30_OPERAND_U4 :
value = fields->f_u4;
break;
case FR30_OPERAND_U4C :
value = fields->f_u4c;
break;
case FR30_OPERAND_U8 :
value = fields->f_u8;
break;
case FR30_OPERAND_UDISP6 :
value = fields->f_udisp6;
break;
default :
/* xgettext:c-format */
fprintf (stderr, _("Unrecognized field %d while getting vma operand.\n"),
opindex);
abort ();
}
return value;
}
void fr30_cgen_set_int_operand (CGEN_CPU_DESC, int, CGEN_FIELDS *, int);
void fr30_cgen_set_vma_operand (CGEN_CPU_DESC, int, CGEN_FIELDS *, bfd_vma);
/* Stuffing values in cgen_fields is handled by a collection of functions.
They are distinguished by the type of the VALUE argument they accept.
TODO: floating point, inlining support, remove cases where argument type
not appropriate. */
void
fr30_cgen_set_int_operand (CGEN_CPU_DESC cd ATTRIBUTE_UNUSED,
int opindex,
CGEN_FIELDS * fields,
int value)
{
switch (opindex)
{
case FR30_OPERAND_CRI :
fields->f_CRi = value;
break;
case FR30_OPERAND_CRJ :
fields->f_CRj = value;
break;
case FR30_OPERAND_R13 :
break;
case FR30_OPERAND_R14 :
break;
case FR30_OPERAND_R15 :
break;
case FR30_OPERAND_RI :
fields->f_Ri = value;
break;
case FR30_OPERAND_RIC :
fields->f_Ric = value;
break;
case FR30_OPERAND_RJ :
fields->f_Rj = value;
break;
case FR30_OPERAND_RJC :
fields->f_Rjc = value;
break;
case FR30_OPERAND_RS1 :
fields->f_Rs1 = value;
break;
case FR30_OPERAND_RS2 :
fields->f_Rs2 = value;
break;
case FR30_OPERAND_CC :
fields->f_cc = value;
break;
case FR30_OPERAND_CCC :
fields->f_ccc = value;
break;
case FR30_OPERAND_DIR10 :
fields->f_dir10 = value;
break;
case FR30_OPERAND_DIR8 :
fields->f_dir8 = value;
break;
case FR30_OPERAND_DIR9 :
fields->f_dir9 = value;
break;
case FR30_OPERAND_DISP10 :
fields->f_disp10 = value;
break;
case FR30_OPERAND_DISP8 :
fields->f_disp8 = value;
break;
case FR30_OPERAND_DISP9 :
fields->f_disp9 = value;
break;
case FR30_OPERAND_I20 :
fields->f_i20 = value;
break;
case FR30_OPERAND_I32 :
fields->f_i32 = value;
break;
case FR30_OPERAND_I8 :
fields->f_i8 = value;
break;
case FR30_OPERAND_LABEL12 :
fields->f_rel12 = value;
break;
case FR30_OPERAND_LABEL9 :
fields->f_rel9 = value;
break;
case FR30_OPERAND_M4 :
fields->f_m4 = value;
break;
case FR30_OPERAND_PS :
break;
case FR30_OPERAND_REGLIST_HI_LD :
fields->f_reglist_hi_ld = value;
break;
case FR30_OPERAND_REGLIST_HI_ST :
fields->f_reglist_hi_st = value;
break;
case FR30_OPERAND_REGLIST_LOW_LD :
fields->f_reglist_low_ld = value;
break;
case FR30_OPERAND_REGLIST_LOW_ST :
fields->f_reglist_low_st = value;
break;
case FR30_OPERAND_S10 :
fields->f_s10 = value;
break;
case FR30_OPERAND_U10 :
fields->f_u10 = value;
break;
case FR30_OPERAND_U4 :
fields->f_u4 = value;
break;
case FR30_OPERAND_U4C :
fields->f_u4c = value;
break;
case FR30_OPERAND_U8 :
fields->f_u8 = value;
break;
case FR30_OPERAND_UDISP6 :
fields->f_udisp6 = value;
break;
default :
/* xgettext:c-format */
fprintf (stderr, _("Unrecognized field %d while setting int operand.\n"),
opindex);
abort ();
}
}
void
fr30_cgen_set_vma_operand (CGEN_CPU_DESC cd ATTRIBUTE_UNUSED,
int opindex,
CGEN_FIELDS * fields,
bfd_vma value)
{
switch (opindex)
{
case FR30_OPERAND_CRI :
fields->f_CRi = value;
break;
case FR30_OPERAND_CRJ :
fields->f_CRj = value;
break;
case FR30_OPERAND_R13 :
break;
case FR30_OPERAND_R14 :
break;
case FR30_OPERAND_R15 :
break;
case FR30_OPERAND_RI :
fields->f_Ri = value;
break;
case FR30_OPERAND_RIC :
fields->f_Ric = value;
break;
case FR30_OPERAND_RJ :
fields->f_Rj = value;
break;
case FR30_OPERAND_RJC :
fields->f_Rjc = value;
break;
case FR30_OPERAND_RS1 :
fields->f_Rs1 = value;
break;
case FR30_OPERAND_RS2 :
fields->f_Rs2 = value;
break;
case FR30_OPERAND_CC :
fields->f_cc = value;
break;
case FR30_OPERAND_CCC :
fields->f_ccc = value;
break;
case FR30_OPERAND_DIR10 :
fields->f_dir10 = value;
break;
case FR30_OPERAND_DIR8 :
fields->f_dir8 = value;
break;
case FR30_OPERAND_DIR9 :
fields->f_dir9 = value;
break;
case FR30_OPERAND_DISP10 :
fields->f_disp10 = value;
break;
case FR30_OPERAND_DISP8 :
fields->f_disp8 = value;
break;
case FR30_OPERAND_DISP9 :
fields->f_disp9 = value;
break;
case FR30_OPERAND_I20 :
fields->f_i20 = value;
break;
case FR30_OPERAND_I32 :
fields->f_i32 = value;
break;
case FR30_OPERAND_I8 :
fields->f_i8 = value;
break;
case FR30_OPERAND_LABEL12 :
fields->f_rel12 = value;
break;
case FR30_OPERAND_LABEL9 :
fields->f_rel9 = value;
break;
case FR30_OPERAND_M4 :
fields->f_m4 = value;
break;
case FR30_OPERAND_PS :
break;
case FR30_OPERAND_REGLIST_HI_LD :
fields->f_reglist_hi_ld = value;
break;
case FR30_OPERAND_REGLIST_HI_ST :
fields->f_reglist_hi_st = value;
break;
case FR30_OPERAND_REGLIST_LOW_LD :
fields->f_reglist_low_ld = value;
break;
case FR30_OPERAND_REGLIST_LOW_ST :
fields->f_reglist_low_st = value;
break;
case FR30_OPERAND_S10 :
fields->f_s10 = value;
break;
case FR30_OPERAND_U10 :
fields->f_u10 = value;
break;
case FR30_OPERAND_U4 :
fields->f_u4 = value;
break;
case FR30_OPERAND_U4C :
fields->f_u4c = value;
break;
case FR30_OPERAND_U8 :
fields->f_u8 = value;
break;
case FR30_OPERAND_UDISP6 :
fields->f_udisp6 = value;
break;
default :
/* xgettext:c-format */
fprintf (stderr, _("Unrecognized field %d while setting vma operand.\n"),
opindex);
abort ();
}
}
/* Function to call before using the instruction builder tables. */
void
fr30_cgen_init_ibld_table (CGEN_CPU_DESC cd)
{
cd->insert_handlers = & fr30_cgen_insert_handlers[0];
cd->extract_handlers = & fr30_cgen_extract_handlers[0];
cd->insert_operand = fr30_cgen_insert_operand;
cd->extract_operand = fr30_cgen_extract_operand;
cd->get_int_operand = fr30_cgen_get_int_operand;
cd->set_int_operand = fr30_cgen_set_int_operand;
cd->get_vma_operand = fr30_cgen_get_vma_operand;
cd->set_vma_operand = fr30_cgen_set_vma_operand;
}
|
sribits/gdb
|
opcodes/fr30-ibld.c
|
C
|
gpl-2.0
| 42,637
|
package com.ihaoxue.memory.cache;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
/**
* @title 缓存管理器
* @author 杨福海(michael) www.yangfuhai.com
* @version 1.0
*/
public class ACacheManager {
private final AtomicLong cacheSize;
private final AtomicInteger cacheCount;
private final long sizeLimit;
private final int countLimit;
private final Map<File, Long> lastUsageDates = Collections.synchronizedMap(new HashMap<File, Long>());
protected File cacheDir;
public ACacheManager(File cacheDir, long sizeLimit, int countLimit) {
this.cacheDir = cacheDir;
this.sizeLimit = sizeLimit;
this.countLimit = countLimit;
cacheSize = new AtomicLong();
cacheCount = new AtomicInteger();
calculateCacheSizeAndCacheCount();
}
/**
* 计算 cacheSize和cacheCount
*/
private void calculateCacheSizeAndCacheCount() {
new Thread(new Runnable() {
@Override
public void run() {
int size = 0;
int count = 0;
File[] cachedFiles = cacheDir.listFiles();
if (cachedFiles != null) {
for (File cachedFile : cachedFiles) {
size += calculateSize(cachedFile);
count += 1;
lastUsageDates.put(cachedFile, cachedFile.lastModified());
}
cacheSize.set(size);
cacheCount.set(count);
}
}
}).start();
}
public void put(File file) {
int curCacheCount = cacheCount.get();
while (curCacheCount + 1 > countLimit) {
long freedSize = removeNext();
cacheSize.addAndGet(-freedSize);
curCacheCount = cacheCount.addAndGet(-1);
}
cacheCount.addAndGet(1);
long valueSize = calculateSize(file);
long curCacheSize = cacheSize.get();
while (curCacheSize + valueSize > sizeLimit) {
long freedSize = removeNext();
curCacheSize = cacheSize.addAndGet(-freedSize);
}
cacheSize.addAndGet(valueSize);
Long currentTime = System.currentTimeMillis();
file.setLastModified(currentTime);
lastUsageDates.put(file, currentTime);
}
public File get(String key) {
File file = newFile(key);
Long currentTime = System.currentTimeMillis();
file.setLastModified(currentTime);
lastUsageDates.put(file, currentTime);
return file;
}
public File newFile(String key) {
return new File(cacheDir, key.hashCode() + "");
}
public boolean remove(String key) {
File image = get(key);
return image.delete();
}
public void clear() {
lastUsageDates.clear();
cacheSize.set(0);
File[] files = cacheDir.listFiles();
if (files != null) {
for (File f : files) {
f.delete();
}
}
}
/**
* 移除旧的文件
*
* @return
*/
public long removeNext() {
if (lastUsageDates.isEmpty()) {
return 0;
}
Long oldestUsage = null;
File mostLongUsedFile = null;
Set<Entry<File, Long>> entries = lastUsageDates.entrySet();
synchronized (lastUsageDates) {
for (Entry<File, Long> entry : entries) {
if (mostLongUsedFile == null) {
mostLongUsedFile = entry.getKey();
oldestUsage = entry.getValue();
} else {
Long lastValueUsage = entry.getValue();
if (lastValueUsage < oldestUsage) {
oldestUsage = lastValueUsage;
mostLongUsedFile = entry.getKey();
}
}
}
}
long fileSize = calculateSize(mostLongUsedFile);
if (mostLongUsedFile.delete()) {
lastUsageDates.remove(mostLongUsedFile);
}
return fileSize;
}
public long calculateSize(File file) {
return file.length();
}
}
|
weibingithub/Memory
|
src/com/ihaoxue/memory/cache/ACacheManager.java
|
Java
|
gpl-2.0
| 3,566
|
<?php
/* Welcome to Bones :)
This is the core Bones file where most of the
main functions & features reside. If you have
any custom functions, it's best to put them
in the functions.php file.
Developed by: Eddie Machado
URL: http://themble.com/bones/
*/
/*********************
LAUNCH BONES
Let's fire off all the functions
and tools. I put it up here so it's
right up top and clean.
*********************/
// we're firing all out initial functions at the start
add_action( 'after_setup_theme', 'bones_ahoy', 16 );
function bones_ahoy() {
// launching operation cleanup
add_action( 'init', 'bones_head_cleanup' );
// remove WP version from RSS
add_filter( 'the_generator', 'bones_rss_version' );
// remove pesky injected css for recent comments widget
add_filter( 'wp_head', 'bones_remove_wp_widget_recent_comments_style', 1 );
// clean up comment styles in the head
add_action( 'wp_head', 'bones_remove_recent_comments_style', 1 );
// clean up gallery output in wp
add_filter( 'gallery_style', 'bones_gallery_style' );
// enqueue base scripts and styles
add_action( 'wp_enqueue_scripts', 'bones_scripts_and_styles', 999 );
// ie conditional wrapper
// launching this stuff after theme setup
bones_theme_support();
// adding sidebars to Wordpress (these are created in functions.php)
add_action( 'widgets_init', 'bones_register_sidebars' );
// adding the bones search form (created in functions.php)
add_filter( 'get_search_form', 'bones_wpsearch' );
// cleaning up random code around images
add_filter( 'the_content', 'bones_filter_ptags_on_images' );
// cleaning up excerpt
add_filter( 'excerpt_more', 'bones_excerpt_more' );
} /* end bones ahoy */
/*********************
WP_HEAD GOODNESS
The default wordpress head is
a mess. Let's clean it up by
removing all the junk we don't
need.
*********************/
function bones_head_cleanup() {
// category feeds
// remove_action( 'wp_head', 'feed_links_extra', 3 );
// post and comment feeds
// remove_action( 'wp_head', 'feed_links', 2 );
// EditURI link
remove_action( 'wp_head', 'rsd_link' );
// windows live writer
remove_action( 'wp_head', 'wlwmanifest_link' );
// index link
remove_action( 'wp_head', 'index_rel_link' );
// previous link
remove_action( 'wp_head', 'parent_post_rel_link', 10, 0 );
// start link
remove_action( 'wp_head', 'start_post_rel_link', 10, 0 );
// links for adjacent posts
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 );
// WP version
remove_action( 'wp_head', 'wp_generator' );
// remove WP version from css
add_filter( 'style_loader_src', 'bones_remove_wp_ver_css_js', 9999 );
// remove Wp version from scripts
add_filter( 'script_loader_src', 'bones_remove_wp_ver_css_js', 9999 );
} /* end bones head cleanup */
// remove WP version from RSS
function bones_rss_version() { return ''; }
// remove WP version from scripts
function bones_remove_wp_ver_css_js( $src ) {
if ( strpos( $src, 'ver=' ) )
$src = remove_query_arg( 'ver', $src );
return $src;
}
function custom_excerpt_length( $length ) {
return 15;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );
// remove injected CSS for recent comments widget
function bones_remove_wp_widget_recent_comments_style() {
if ( has_filter( 'wp_head', 'wp_widget_recent_comments_style' ) ) {
remove_filter( 'wp_head', 'wp_widget_recent_comments_style' );
}
}
function external_get_the_excerpt($post_id) {
global $post;
$save_post = $post;
$post = get_post($post_id);
$output = get_the_excerpt();
$post = $save_post;
echo($output);
}
if( function_exists('acf_add_options_page') ) {
acf_add_options_page(array(
'page_title' => 'ArchAgent General Settings',
'menu_title' => 'Site Settings',
'menu_slug' => 'archagent-general-settings',
'capability' => 'edit_posts',
'icon_url' => 'dashicons-desktop',
'redirect' => false
));
acf_add_options_sub_page(array(
'page_title' => 'ArchAgent Header Settings',
'menu_title' => 'Header',
'parent_slug' => 'archagent-general-settings',
));
acf_add_options_sub_page(array(
'page_title' => 'ArchAgent Footer Settings',
'menu_title' => 'Footer',
'parent_slug' => 'archagent-general-settings',
));
}
// remove injected CSS from recent comments widget
function bones_remove_recent_comments_style() {
global $wp_widget_factory;
if (isset($wp_widget_factory->widgets['WP_Widget_Recent_Comments'])) {
remove_action( 'wp_head', array($wp_widget_factory->widgets['WP_Widget_Recent_Comments'], 'recent_comments_style') );
}
}
// remove injected CSS from gallery
function bones_gallery_style($css) {
return preg_replace( "!<style type='text/css'>(.*?)</style>!s", '', $css );
}
/*********************
SCRIPTS & ENQUEUEING
*********************/
// loading modernizr and jquery, and reply script
function bones_scripts_and_styles() {
global $wp_styles; // call global $wp_styles variable to add conditional wrapper around ie stylesheet the WordPress way
if (!is_admin()) {
// modernizr (without media query polyfill)
wp_register_script( 'bones-modernizr', get_stylesheet_directory_uri() . '/library/js/libs/modernizr.custom.min.js', array(), '2.5.3', false );
// register main stylesheet
wp_register_style( 'bones-stylesheet', get_stylesheet_directory_uri() . '/library/css/style.css', array(), '', 'all' );
// ie-only style sheet
wp_register_style( 'bones-ie-only', get_stylesheet_directory_uri() . '/library/css/ie.css', array(), '' );
// comment reply script for threaded comments
if ( is_singular() AND comments_open() AND (get_option('thread_comments') == 1)) {
wp_enqueue_script( 'comment-reply' );
}
//adding scripts file in the footer
wp_register_script( 'bones-js', get_stylesheet_directory_uri() . '/library/js/scripts.js', array( 'jquery' ), '', true );
//adding scripts file in the footer
wp_register_script( 'fitvids-js', get_stylesheet_directory_uri() . '/library/js/libs/jquery.fitvids.js', array( 'jquery' ), '', true );
// enqueue styles and scripts
wp_enqueue_script( 'bones-modernizr' );
wp_enqueue_style( 'bones-stylesheet' );
wp_enqueue_style( 'bones-ie-only' );
$wp_styles->add_data( 'bones-ie-only', 'conditional', 'lt IE 9' ); // add conditional wrapper around ie stylesheet
/*
I recommend using a plugin to call jQuery
using the google cdn. That way it stays cached
and your site will load faster.
*/
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'bones-js' );
wp_enqueue_script( 'fitvids-js' );
wp_enqueue_script( 'swipe' );
}
}
/*********************
THEME SUPPORT
*********************/
// Adding WP 3+ Functions & Theme Support
function bones_theme_support() {
// wp thumbnails (sizes handled in functions.php)
add_theme_support( 'post-thumbnails' );
// default thumb size
set_post_thumbnail_size(125, 125, true);
// wp custom background (thx to @bransonwerner for update)
add_theme_support( 'custom-background',
array(
'default-image' => '', // background image default
'default-color' => '', // background color default (dont add the #)
'wp-head-callback' => '_custom_background_cb',
'admin-head-callback' => '',
'admin-preview-callback' => ''
)
);
// rss thingy
add_theme_support('automatic-feed-links');
// to add header image support go here: http://themble.com/support/adding-header-background-image-support/
// adding post format support
add_theme_support( 'post-formats',
array(
'aside', // title less blurb
'gallery', // gallery of images
'link', // quick link to other site
'image', // an image
'quote', // a quick quote
'status', // a Facebook like status update
'video', // video
'audio', // audio
'chat' // chat transcript
)
);
// wp menus
add_theme_support( 'menus' );
// registering wp3+ menus
register_nav_menus(
array(
'main-nav' => __( 'The Main Menu', 'bonestheme' ), // main nav in header
'footer-toolbar-links' => __( 'Footer Toolbar Links', 'bonestheme' ), // footer toolbar links
'footer-links' => __( 'Footer Links', 'bonestheme' ) // secondary nav in footer
)
);
} /* end bones theme support */
/*********************
WOOCOMMERCE SUPPORT
*********************/
// unhooking the default wrappers
remove_action( 'woocommerce_before_main_content', 'woocommerce_output_content_wrapper', 10);
remove_action( 'woocommerce_after_main_content', 'woocommerce_output_content_wrapper_end', 10);
// adding hook for custom wrappers
add_action('woocommerce_before_main_content', 'archagent_wrapper_start', 10);
add_action('woocommerce_after_main_content', 'archagent_wrapper_end', 10);
function archagent_wrapper_start() {
echo '<section id="wc-container" class="semi">';
}
function archagent_wrapper_end() {
echo '</section>';
}
add_action( 'after_setup_theme', 'woocommerce_support' );
function woocommerce_support() {
add_theme_support( 'woocommerce' );
}
/*******************************
WOOCOMMERCE SINGLE PRODUCT
*******************************/
// removing default tabbed content layout
add_filter( 'woocommerce_product_tabs', 'woo_remove_product_tabs', 98 );
function woo_remove_product_tabs( $tabs ) {
unset( $tabs['description'] ); // Remove the description tab
unset( $tabs['reviews'] ); // Remove the reviews tab
unset( $tabs['additional_information'] ); // Remove the additional information tab
return $tabs;
}
// reassigning the product images from before_single_product_summary to woocommerce_after_single_product_summary
remove_action( 'woocommerce_before_single_product_summary', 'woocommerce_show_product_images', 20 );
add_action( 'woocommerce_after_single_product_summary', 'woocommerce_show_product_images', 20 );
// removing rating and price from single_product_summary
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_rating', 10 );
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );
/*********************
MENUS & NAVIGATION
*********************/
// the main menu
function bones_main_nav() {
// display the wp3 menu if available
wp_nav_menu(array(
'container' => false, // remove nav container
'container_class' => '', // class of container (should you choose to use it)
'menu' => __( 'The Main Menu', 'bonestheme' ), // nav name
'menu_class' => '', // adding custom nav class
'theme_location' => 'main-nav', // where it's located in the theme
'before' => '', // before the menu
'after' => '', // after the menu
'link_before' => '', // before each link
'link_after' => '', // after each link
'depth' => 0, // limit the depth of the nav
'fallback_cb' => 'bones_main_nav_fallback' // fallback function
));
} /* end bones main nav */
// the footer menu (should you choose to use one)
function bones_footer_links() {
// display the wp3 menu if available
wp_nav_menu(array(
'container' => '', // remove nav container
'container_class' => 'footer-links clearfix', // class of container (should you choose to use it)
'menu' => __( 'Footer Links', 'bonestheme' ), // nav name
'menu_class' => 'nav footer-nav clearfix', // adding custom nav class
'theme_location' => 'footer-links', // where it's located in the theme
'before' => '', // before the menu
'after' => '', // after the menu
'link_before' => '', // before each link
'link_after' => '', // after each link
'depth' => 0, // limit the depth of the nav
'fallback_cb' => 'bones_footer_links_fallback' // fallback function
));
} /* end bones footer link */
// the footer menu (should you choose to use one)
function bones_footer_toolbar_links() {
// display the wp3 menu if available
wp_nav_menu(array(
'container' => '', // remove nav container
'container_class' => 'footer-links clearfix', // class of container (should you choose to use it)
'menu' => __( 'Footer Toolbar Links', 'bonestheme' ), // nav name
'menu_class' => 'nav', // adding custom nav class
'theme_location' => 'footer-toolbar-links', // where it's located in the theme
'before' => '', // before the menu
'after' => '', // after the menu
'link_before' => '', // before each link
'link_after' => '', // after each link
'depth' => 0, // limit the depth of the nav
'fallback_cb' => 'bones_footer_links_fallback' // fallback function
));
} /* end bones footer link */
// this is the fallback for header menu
function bones_main_nav_fallback() {
wp_page_menu( array(
'show_home' => true,
'menu_class' => 'nav top-nav clearfix', // adding custom nav class
'include' => '',
'exclude' => '',
'echo' => true,
'link_before' => '', // before each link
'link_after' => '' // after each link
) );
}
// this is the fallback for footer menu
function bones_footer_links_fallback() {
/* you can put a default here if you like */
}
/*********************
RELATED POSTS FUNCTION
*********************/
// Related Posts Function (call using bones_related_posts(); )
function bones_related_posts() {
echo '<ul id="bones-related-posts">';
global $post;
$tags = wp_get_post_tags( $post->ID );
if($tags) {
foreach( $tags as $tag ) {
$tag_arr .= $tag->slug . ',';
}
$args = array(
'tag' => $tag_arr,
'numberposts' => 5, /* you can change this to show more */
'post__not_in' => array($post->ID)
);
$related_posts = get_posts( $args );
if($related_posts) {
foreach ( $related_posts as $post ) : setup_postdata( $post ); ?>
<li class="related_post"><a class="entry-unrelated" href="<?php the_permalink() ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; }
else { ?>
<?php echo '<li class="no_related_post">' . __( 'No Related Posts Yet!', 'bonestheme' ) . '</li>'; ?>
<?php }
}
wp_reset_query();
echo '</ul>';
} /* end bones related posts function */
/*********************
PAGE NAVI
*********************/
// Numeric Page Navi (built into the theme by default)
function bones_page_navi() {
global $wp_query;
$bignum = 999999999;
if ( $wp_query->max_num_pages <= 1 )
return;
echo '<nav class="pagination">';
echo paginate_links( array(
'base' => str_replace( $bignum, '%#%', esc_url( get_pagenum_link($bignum) ) ),
'format' => '',
'current' => max( 1, get_query_var('paged') ),
'total' => $wp_query->max_num_pages,
'prev_text' => '←',
'next_text' => '→',
'type' => 'list',
'end_size' => 3,
'mid_size' => 3
) );
echo '</nav>';
} /* end page navi */
/*********************
RANDOM CLEANUP ITEMS
*********************/
add_filter('pre_get_posts', 'query_post_type');
function query_post_type($query) {
if(is_category() || is_tag()) {
$post_type = get_query_var('post_type');
if($post_type)
$post_type = $post_type;
else
$post_type = array('post','faq');
$query->set('post_type',$post_type);
return $query;
}
}
// Remove Custom Fields dashboard tab for users that are not admins
add_filter('acf/settings/show_admin', 'my_acf_show_admin');
function my_acf_show_admin( $show ) {
return current_user_can('manage_options');
}
// Add our function to the admin_menu action
add_action('admin_menu', 'sb_remove_admin_menus');
// remove the p from around imgs (http://css-tricks.com/snippets/wordpress/remove-paragraph-tags-from-around-images/)
function bones_filter_ptags_on_images($content){
return preg_replace('/<p>\s*(<a .*>)?\s*(<img .* \/>)\s*(<\/a>)?\s*<\/p>/iU', '\1\2\3', $content);
}
// This removes the annoying […] to a Read More link
function bones_excerpt_more($more) {
global $post;
// edit here if you like
return '... <a class="excerpt-read-more" href="'. get_permalink($post->ID) . '" title="'. __( 'Read', 'bonestheme' ) . get_the_title($post->ID).'">'. __( 'Read more »', 'bonestheme' ) .'</a>';
}
/*
* This is a modified the_author_posts_link() which just returns the link.
*
* This is necessary to allow usage of the usual l10n process with printf().
*/
function bones_get_the_author_posts_link() {
global $authordata;
if ( !is_object( $authordata ) )
return false;
$link = sprintf(
'<a href="%1$s" title="%2$s" rel="author">%3$s</a>',
get_author_posts_url( $authordata->ID, $authordata->user_nicename ),
esc_attr( sprintf( __( 'Posts by %s' ), get_the_author() ) ), // No further l10n needed, core will take care of this one
get_the_author()
);
return $link;
}
?>
|
devaha/archagent
|
wp-content/themes/ArchAgent/library/bones.php
|
PHP
|
gpl-2.0
| 17,209
|
/*
FUNCTION
<<vscanf>>, <<vfscanf>>, <<vsscanf>>---format argument list
INDEX
vscanf
INDEX
vfscanf
INDEX
vsscanf
ANSI_SYNOPSIS
#include <stdio.h>
#include <stdarg.h>
int vscanf(const char *<[fmt]>, va_list <[list]>);
int vfscanf(FILE *<[fp]>, const char *<[fmt]>, va_list <[list]>);
int vsscanf(const char *<[str]>, const char *<[fmt]>, va_list <[list]>);
int _vscanf_r(void *<[reent]>, const char *<[fmt]>,
va_list <[list]>);
int _vfscanf_r(void *<[reent]>, FILE *<[fp]>, const char *<[fmt]>,
va_list <[list]>);
int _vsscanf_r(void *<[reent]>, const char *<[str]>, const char *<[fmt]>,
va_list <[list]>);
TRAD_SYNOPSIS
#include <stdio.h>
#include <varargs.h>
int vscanf( <[fmt]>, <[ist]>)
char *<[fmt]>;
va_list <[list]>;
int vfscanf( <[fp]>, <[fmt]>, <[list]>)
FILE *<[fp]>;
char *<[fmt]>;
va_list <[list]>;
int vsscanf( <[str]>, <[fmt]>, <[list]>)
char *<[str]>;
char *<[fmt]>;
va_list <[list]>;
int _vscanf_r( <[reent]>, <[fmt]>, <[ist]>)
char *<[reent]>;
char *<[fmt]>;
va_list <[list]>;
int _vfscanf_r( <[reent]>, <[fp]>, <[fmt]>, <[list]>)
char *<[reent]>;
FILE *<[fp]>;
char *<[fmt]>;
va_list <[list]>;
int _vsscanf_r( <[reent]>, <[str]>, <[fmt]>, <[list]>)
char *<[reent]>;
char *<[str]>;
char *<[fmt]>;
va_list <[list]>;
DESCRIPTION
<<vscanf>>, <<vfscanf>>, and <<vsscanf>> are (respectively) variants
of <<scanf>>, <<fscanf>>, and <<sscanf>>. They differ only in
allowing their caller to pass the variable argument list as a
<<va_list>> object (initialized by <<va_start>>) rather than
directly accepting a variable number of arguments.
RETURNS
The return values are consistent with the corresponding functions:
<<vscanf>> returns the number of input fields successfully scanned,
converted, and stored; the return value does not include scanned
fields which were not stored.
If <<vscanf>> attempts to read at end-of-file, the return value
is <<EOF>>.
If no fields were stored, the return value is <<0>>.
The routines <<_vscanf_r>>, <<_vfscanf_f>>, and <<_vsscanf_r>> are
reentrant versions which take an additional first parameter which points to the
reentrancy structure.
PORTABILITY
These are GNU extensions.
Supporting OS subroutines required:
*/
/*-
* Copyright (c) 1990 The Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the University of California, Berkeley. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include <_ansi.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <wchar.h>
#include <string.h>
#ifdef _HAVE_STDC
#include <stdarg.h>
#else
#include <varargs.h>
#endif
#include "local.h"
#ifndef NO_FLOATING_POINT
#define FLOATING_POINT
#endif
#ifdef FLOATING_POINT
#include <float.h>
/* Currently a test is made to see if long double processing is warranted.
This could be changed in the future should the _ldtoa_r code be
preferred over _dtoa_r. */
#define _NO_LONGDBL
#if defined WANT_IO_LONG_DBL && (LDBL_MANT_DIG > DBL_MANT_DIG)
#undef _NO_LONGDBL
extern _LONG_DOUBLE _strtold _PARAMS((char *s, char **sptr));
#endif
#define _NO_LONGLONG
#if defined WANT_PRINTF_LONG_LONG && defined __GNUC__
# undef _NO_LONGLONG
#endif
#include "floatio.h"
#define BUF (MAXEXP+MAXFRACT+3) /* 3 = sign + decimal point + NUL */
/* An upper bound for how long a long prints in decimal. 4 / 13 approximates
log (2). Add one char for roundoff compensation and one for the sign. */
#define MAX_LONG_LEN ((CHAR_BIT * sizeof (long) - 1) * 4 / 13 + 2)
#else
#define BUF 40
#endif
/*
* Flags used during conversion.
*/
#define LONG 0x01 /* l: long or double */
#define LONGDBL 0x02 /* L: long double or long long */
#define SHORT 0x04 /* h: short */
#define SUPPRESS 0x08 /* suppress assignment */
#define POINTER 0x10 /* weird %p pointer (`fake hex') */
#define NOSKIP 0x20 /* do not skip blanks */
/*
* The following are used in numeric conversions only:
* SIGNOK, NDIGITS, DPTOK, and EXPOK are for floating point;
* SIGNOK, NDIGITS, PFXOK, and NZDIGITS are for integral.
*/
#define SIGNOK 0x40 /* +/- is (still) legal */
#define NDIGITS 0x80 /* no digits detected */
#define DPTOK 0x100 /* (float) decimal point is still legal */
#define EXPOK 0x200 /* (float) exponent (e+3, etc) still legal */
#define PFXOK 0x100 /* 0x prefix is (still) legal */
#define NZDIGITS 0x200 /* no zero digits detected */
#define VECTOR 0x400 /* v: vector */
#define FIXEDPOINT 0x800 /* r/R: fixed-point */
#define SIGNED 0x1000 /* r: signed fixed-point */
/*
* Conversion types.
*/
#define CT_CHAR 0 /* %c conversion */
#define CT_CCL 1 /* %[...] conversion */
#define CT_STRING 2 /* %s conversion */
#define CT_INT 3 /* integer, i.e., strtol or strtoul */
#define CT_FLOAT 4 /* floating, i.e., strtod */
#if 0
#define u_char unsigned char
#endif
#define u_char char
#define u_long unsigned long
#ifndef _NO_LONGLONG
typedef unsigned long long u_long_long;
#endif
typedef union
{
char c[16] __attribute__ ((__aligned__ (16)));
short h[8];
long l[4];
int i[4];
float f[4];
} vec_union;
/*static*/ u_char *__sccl ();
/*
* vfscanf
*/
#define BufferEmpty (fp->_r <= 0 && __srefill(fp))
#ifndef _REENT_ONLY
int
_DEFUN (vfscanf, (fp, fmt, ap),
register FILE *fp _AND
_CONST char *fmt _AND
va_list ap)
{
CHECK_INIT(fp);
return __svfscanf_r (fp->_data, fp, fmt, ap);
}
int
__svfscanf (fp, fmt0, ap)
register FILE *fp;
char _CONST *fmt0;
va_list ap;
{
return __svfscanf_r (_REENT, fp, fmt0, ap);
}
#endif /* !_REENT_ONLY */
int
_DEFUN (_vfscanf_r, (data, fp, fmt, ap),
struct _reent *data _AND
register FILE *fp _AND
_CONST char *fmt _AND
va_list ap)
{
return __svfscanf_r (data, fp, fmt, ap);
}
int
__svfscanf_r (rptr, fp, fmt0, ap)
struct _reent *rptr;
register FILE *fp;
char _CONST *fmt0;
va_list ap;
{
register u_char *fmt = (u_char *) fmt0;
register int c; /* character from format, or conversion */
register int type; /* conversion type */
register size_t width; /* field width, or 0 */
register char *p; /* points into all kinds of strings */
register int n; /* handy integer */
register int flags; /* flags as defined above */
register char *p0; /* saves original value of p when necessary */
int orig_flags; /* saved flags used when processing vector */
int int_width; /* tmp area to store width when processing int */
int nassigned; /* number of fields assigned */
int nread; /* number of characters consumed from fp */
int base = 0; /* base argument to strtol/strtoul */
int nbytes = 1; /* number of bytes read from fmt string */
wchar_t wc; /* wchar to use to read format string */
char vec_sep; /* vector separator char */
char last_space_char; /* last white-space char eaten - needed for vec support */
int vec_read_count; /* number of vector items to read separately */
int looped; /* has vector processing looped */
u_long (*ccfn) () = 0; /* conversion function (strtol/strtoul) */
char ccltab[256]; /* character class table for %[...] */
char buf[BUF]; /* buffer for numeric conversions */
vec_union vec_buf;
char *lptr; /* literal pointer */
#ifdef MB_CAPABLE
mbstate_t state; /* value to keep track of multibyte state */
#endif
char *ch_dest;
short *sp;
int *ip;
float *flp;
_LONG_DOUBLE *ldp;
double *dp;
long *lp;
#ifndef _NO_LONGLONG
long long *llp;
#else
u_long _uquad;
#endif
/* `basefix' is used to avoid `if' tests in the integer scanner */
static _CONST short basefix[17] =
{10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
nassigned = 0;
nread = 0;
for (;;)
{
#ifndef MB_CAPABLE
wc = *fmt;
#else
memset (&state, '\0', sizeof (state));
nbytes = _mbtowc_r (rptr, &wc, fmt, MB_CUR_MAX, &state);
#endif
fmt += nbytes;
if (wc == 0)
return nassigned;
if (nbytes == 1 && isspace (wc))
{
for (;;)
{
if (BufferEmpty)
return nassigned;
if (!isspace (*fp->_p))
break;
nread++, fp->_r--, fp->_p++;
}
continue;
}
if (wc != '%')
goto literal;
width = 0;
flags = 0;
vec_sep = ' ';
vec_read_count = 0;
looped = 0;
/*
* switch on the format. continue if done; break once format
* type is derived.
*/
again:
c = *fmt++;
switch (c)
{
case '%':
literal:
lptr = fmt - nbytes;
for (n = 0; n < nbytes; ++n)
{
if (BufferEmpty)
goto input_failure;
if (*fp->_p != *lptr)
goto match_failure;
fp->_r--, fp->_p++;
nread++;
++lptr;
}
continue;
case '*':
flags |= SUPPRESS;
goto again;
case ',':
case ';':
case ':':
case '_':
if (flags == SUPPRESS || flags == 0)
vec_sep = c;
goto again;
case 'l':
if (flags & SHORT)
continue; /* invalid format, don't process any further */
if (flags & LONG)
{
flags &= ~LONG;
flags &= ~VECTOR;
flags |= LONGDBL;
}
else
{
flags |= LONG;
if (flags & VECTOR)
vec_read_count = 4;
}
goto again;
case 'L':
flags |= LONGDBL;
flags &= ~VECTOR;
goto again;
case 'h':
flags |= SHORT;
if (flags & LONG)
continue; /* invalid format, don't process any further */
if (flags & VECTOR)
vec_read_count = 8;
goto again;
#ifdef __ALTIVEC__
case 'v':
flags |= VECTOR;
vec_read_count = (flags & SHORT) ? 8 : ((flags & LONG) ? 4 : 16);
goto again;
#endif
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
width = width * 10 + c - '0';
goto again;
/*
* Conversions. Those marked `compat' are for
* 4.[123]BSD compatibility.
*
* (According to ANSI, E and X formats are supposed to
* the same as e and x. Sorry about that.)
*/
case 'D': /* compat */
flags |= LONG;
/* FALLTHROUGH */
case 'd':
type = CT_INT;
ccfn = (u_long (*)())_strtol_r;
base = 10;
break;
case 'i':
type = CT_INT;
ccfn = (u_long (*)())_strtol_r;
base = 0;
break;
case 'O': /* compat */
flags |= LONG;
/* FALLTHROUGH */
case 'o':
type = CT_INT;
ccfn = _strtoul_r;
base = 8;
break;
case 'u':
type = CT_INT;
ccfn = _strtoul_r;
base = 10;
break;
case 'X': /* compat XXX */
case 'x':
flags |= PFXOK; /* enable 0x prefixing */
type = CT_INT;
ccfn = _strtoul_r;
base = 16;
break;
#ifdef FLOATING_POINT
case 'E': /* compat XXX */
case 'G': /* compat XXX */
/* ANSI says that E,G and X behave the same way as e,g,x */
/* FALLTHROUGH */
case 'e':
case 'f':
case 'g':
type = CT_FLOAT;
if (flags & VECTOR)
vec_read_count = 4;
break;
# ifdef __SPE__
/* treat fixed-point like %f floating point */
case 'r':
flags |= SIGNED;
/* fallthrough */
case 'R':
flags |= FIXEDPOINT;
type = CT_FLOAT;
break;
# endif
#endif
case 's':
flags &= ~VECTOR;
type = CT_STRING;
break;
case '[':
fmt = __sccl (ccltab, fmt);
flags |= NOSKIP;
flags &= ~VECTOR;
type = CT_CCL;
break;
case 'c':
flags |= NOSKIP;
type = CT_CHAR;
if (flags & VECTOR)
{
/* not allowed to have h or l with c specifier */
if (flags & (LONG | SHORT))
continue; /* invalid format don't process any further */
width = 0;
vec_read_count = 16;
}
break;
case 'p': /* pointer format is like hex */
flags |= POINTER | PFXOK;
type = CT_INT;
ccfn = _strtoul_r;
base = 16;
break;
case 'n':
if (flags & SUPPRESS) /* ??? */
continue;
flags &= ~VECTOR;
if (flags & SHORT)
{
sp = va_arg (ap, short *);
*sp = nread;
}
else if (flags & LONG)
{
lp = va_arg (ap, long *);
*lp = nread;
}
#ifndef _NO_LONGLONG
else if (flags & LONGDBL)
{
llp = va_arg (ap, long long*);
*llp = nread;
}
#endif
else
{
ip = va_arg (ap, int *);
*ip = nread;
}
continue;
/*
* Disgusting backwards compatibility hacks. XXX
*/
case '\0': /* compat */
return EOF;
default: /* compat */
if (isupper (c))
flags |= LONG;
type = CT_INT;
ccfn = (u_long (*)())_strtol_r;
base = 10;
break;
}
process:
/*
* We have a conversion that requires input.
*/
if (BufferEmpty)
goto input_failure;
/*
* Consume leading white space, except for formats that
* suppress this.
*/
last_space_char = '\0';
if ((flags & NOSKIP) == 0)
{
while (isspace (*fp->_p))
{
last_space_char = *fp->_p;
nread++;
if (--fp->_r > 0)
fp->_p++;
else
#ifndef CYGNUS_NEC
if (__srefill (fp))
#endif
goto input_failure;
}
/*
* Note that there is at least one character in the
* buffer, so conversions that do not set NOSKIP ca
* no longer result in an input failure.
*/
}
/* for vector formats process separator characters after first loop */
if (looped && (flags & VECTOR))
{
flags = orig_flags;
/* all formats other than default char have a separator char */
if (vec_sep != ' ' || type != CT_CHAR)
{
if (vec_sep == ' ' && last_space_char != ' ' ||
vec_sep != ' ' && *fp->_p != vec_sep)
goto match_failure;
if (vec_sep != ' ')
{
nread++;
if (--fp->_r > 0)
fp->_p++;
else
#ifndef CYGNUS_NEC
if (__srefill (fp))
#endif
goto input_failure;
}
}
/* after eating the separator char, we must eat any white-space
after the separator char that precedes the data to convert */
if ((flags & NOSKIP) == 0)
{
while (isspace (*fp->_p))
{
last_space_char = *fp->_p;
nread++;
if (--fp->_r > 0)
fp->_p++;
else
#ifndef CYGNUS_NEC
if (__srefill (fp))
#endif
goto input_failure;
}
}
}
else /* save to counter-act changes made to flags when processing */
orig_flags = flags;
/*
* Do the conversion.
*/
switch (type)
{
case CT_CHAR:
/* scan arbitrary characters (sets NOSKIP) */
if (width == 0)
width = 1;
if (flags & SUPPRESS)
{
size_t sum = 0;
for (;;)
{
if ((n = fp->_r) < (int)width)
{
sum += n;
width -= n;
fp->_p += n;
#ifndef CYGNUS_NEC
if (__srefill (fp))
{
#endif
if (sum == 0)
goto input_failure;
break;
#ifndef CYGNUS_NEC
}
#endif
}
else
{
sum += width;
fp->_r -= width;
fp->_p += width;
break;
}
}
nread += sum;
}
else
{
int n = width;
if (!looped)
{
if (flags & VECTOR)
ch_dest = vec_buf.c;
else
ch_dest = va_arg (ap, char *);
}
#ifdef CYGNUS_NEC
/* Kludge city for the moment */
if (fp->_r == 0)
goto input_failure;
while (n && fp->_r)
{
*ch_dest++ = *(fp->_p++);
n--;
fp->_r--;
nread++;
}
#else
size_t r = fread (ch_dest, 1, width, fp);
if (r == 0)
goto input_failure;
nread += r;
ch_dest += r;
#endif
if (!(flags & VECTOR))
nassigned++;
}
break;
case CT_CCL:
/* scan a (nonempty) character class (sets NOSKIP) */
if (width == 0)
width = ~0; /* `infinity' */
/* take only those things in the class */
if (flags & SUPPRESS)
{
n = 0;
while (ccltab[*fp->_p])
{
n++, fp->_r--, fp->_p++;
if (--width == 0)
break;
if (BufferEmpty)
{
if (n == 0)
goto input_failure;
break;
}
}
if (n == 0)
goto match_failure;
}
else
{
p0 = p = va_arg (ap, char *);
while (ccltab[*fp->_p])
{
fp->_r--;
*p++ = *fp->_p++;
if (--width == 0)
break;
if (BufferEmpty)
{
if (p == p0)
goto input_failure;
break;
}
}
n = p - p0;
if (n == 0)
goto match_failure;
*p = 0;
nassigned++;
}
nread += n;
break;
case CT_STRING:
/* like CCL, but zero-length string OK, & no NOSKIP */
if (width == 0)
width = ~0;
if (flags & SUPPRESS)
{
n = 0;
while (!isspace (*fp->_p))
{
n++, fp->_r--, fp->_p++;
if (--width == 0)
break;
if (BufferEmpty)
break;
}
nread += n;
}
else
{
p0 = p = va_arg (ap, char *);
while (!isspace (*fp->_p))
{
fp->_r--;
*p++ = *fp->_p++;
if (--width == 0)
break;
if (BufferEmpty)
break;
}
*p = 0;
nread += p - p0;
nassigned++;
}
continue;
case CT_INT:
/* scan an integer as if by strtol/strtoul */
int_width = width;
#ifdef hardway
if (int_width == 0 || int_width > sizeof (buf) - 1)
int_width = sizeof (buf) - 1;
#else
/* size_t is unsigned, hence this optimisation */
if (--int_width > sizeof (buf) - 2)
int_width = sizeof (buf) - 2;
int_width++;
#endif
flags |= SIGNOK | NDIGITS | NZDIGITS;
for (p = buf; int_width; int_width--)
{
c = *fp->_p;
/*
* Switch on the character; `goto ok' if we
* accept it as a part of number.
*/
switch (c)
{
/*
* The digit 0 is always legal, but is special.
* For %i conversions, if no digits (zero or nonzero)
* have been scanned (only signs), we will have base==0.
* In that case, we should set it to 8 and enable 0x
* prefixing. Also, if we have not scanned zero digits
* before this, do not turn off prefixing (someone else
* will turn it off if we have scanned any nonzero digits).
*/
case '0':
if (base == 0)
{
base = 8;
flags |= PFXOK;
}
if (flags & NZDIGITS)
flags &= ~(SIGNOK | NZDIGITS | NDIGITS);
else
flags &= ~(SIGNOK | PFXOK | NDIGITS);
goto ok;
/* 1 through 7 always legal */
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
base = basefix[base];
flags &= ~(SIGNOK | PFXOK | NDIGITS);
goto ok;
/* digits 8 and 9 ok iff decimal or hex */
case '8':
case '9':
base = basefix[base];
if (base <= 8)
break; /* not legal here */
flags &= ~(SIGNOK | PFXOK | NDIGITS);
goto ok;
/* letters ok iff hex */
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
/* no need to fix base here */
if (base <= 10)
break; /* not legal here */
flags &= ~(SIGNOK | PFXOK | NDIGITS);
goto ok;
/* sign ok only as first character */
case '+':
case '-':
if (flags & SIGNOK)
{
flags &= ~SIGNOK;
goto ok;
}
break;
/* x ok iff flag still set & 2nd char */
case 'x':
case 'X':
if (flags & PFXOK && p == buf + 1)
{
base = 16;/* if %i */
flags &= ~PFXOK;
goto ok;
}
break;
}
/*
* If we got here, c is not a legal character
* for a number. Stop accumulating digits.
*/
break;
ok:
/*
* c is legal: store it and look at the next.
*/
*p++ = c;
if (--fp->_r > 0)
fp->_p++;
else
#ifndef CYGNUS_NEC
if (__srefill (fp))
#endif
break; /* EOF */
}
/*
* If we had only a sign, it is no good; push back the sign.
* If the number ends in `x', it was [sign] '0' 'x', so push back
* the x and treat it as [sign] '0'.
*/
if (flags & NDIGITS)
{
if (p > buf)
_CAST_VOID ungetc (*(u_char *)-- p, fp);
goto match_failure;
}
c = ((u_char *) p)[-1];
if (c == 'x' || c == 'X')
{
--p;
/*(void)*/ ungetc (c, fp);
}
if ((flags & SUPPRESS) == 0)
{
u_long res;
*p = 0;
res = (*ccfn) (rptr, buf, (char **) NULL, base);
if ((flags & POINTER) && !(flags & VECTOR))
*(va_arg (ap, _PTR *)) = (_PTR) (unsigned _POINTER_INT) res;
else if (flags & SHORT)
{
if (!(flags & VECTOR))
sp = va_arg (ap, short *);
else if (!looped)
sp = vec_buf.h;
*sp++ = res;
}
else if (flags & LONG)
{
if (!(flags & VECTOR))
lp = va_arg (ap, long *);
else if (!looped)
lp = vec_buf.l;
*lp++ = res;
}
#ifndef _NO_LONGLONG
else if (flags & LONGDBL)
{
u_long_long resll;
if (ccfn == _strtoul_r)
resll = _strtoull_r (rptr, buf, (char **) NULL, base);
else
resll = _strtoll_r (rptr, buf, (char **) NULL, base);
llp = va_arg (ap, long long*);
*llp = resll;
}
#endif
else
{
if (!(flags & VECTOR))
{
ip = va_arg (ap, int *);
*ip++ = res;
}
else
{
if (!looped)
ch_dest = vec_buf.c;
*ch_dest++ = (char)res;
}
}
if (!(flags & VECTOR))
nassigned++;
}
nread += p - buf;
break;
#ifdef FLOATING_POINT
case CT_FLOAT:
{
/* scan a floating point number as if by strtod */
/* This code used to assume that the number of digits is reasonable.
However, ANSI / ISO C makes no such stipulation; we have to get
exact results even when there is an unreasonable amount of
leading zeroes. */
long leading_zeroes = 0;
long zeroes, exp_adjust;
char *exp_start = NULL;
int fl_width = width;
#ifdef hardway
if (fl_width == 0 || fl_width > sizeof (buf) - 1)
fl_width = sizeof (buf) - 1;
#else
/* size_t is unsigned, hence this optimisation */
if (--fl_width > sizeof (buf) - 2)
fl_width = sizeof (buf) - 2;
fl_width++;
#endif
flags |= SIGNOK | NDIGITS | DPTOK | EXPOK;
zeroes = 0;
exp_adjust = 0;
for (p = buf; fl_width; )
{
c = *fp->_p;
/*
* This code mimicks the integer conversion
* code, but is much simpler.
*/
switch (c)
{
case '0':
if (flags & NDIGITS)
{
flags &= ~SIGNOK;
zeroes++;
goto fskip;
}
/* Fall through. */
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
flags &= ~(SIGNOK | NDIGITS);
goto fok;
case '+':
case '-':
if (flags & SIGNOK)
{
flags &= ~SIGNOK;
goto fok;
}
break;
case '.':
if (flags & DPTOK)
{
flags &= ~(SIGNOK | DPTOK);
leading_zeroes = zeroes;
goto fok;
}
break;
case 'e':
case 'E':
/* no exponent without some digits */
if ((flags & (NDIGITS | EXPOK)) == EXPOK
|| ((flags & EXPOK) && zeroes))
{
if (! (flags & DPTOK))
{
exp_adjust = zeroes - leading_zeroes;
exp_start = p;
}
flags =
(flags & ~(EXPOK | DPTOK)) |
SIGNOK | NDIGITS;
zeroes = 0;
goto fok;
}
break;
}
break;
fok:
*p++ = c;
fl_width--;
fskip:
++nread;
if (--fp->_r > 0)
fp->_p++;
else
#ifndef CYGNUS_NEC
if (__srefill (fp))
#endif
break; /* EOF */
}
if (zeroes)
flags &= ~NDIGITS;
/*
* If no digits, might be missing exponent digits
* (just give back the exponent) or might be missing
* regular digits, but had sign and/or decimal point.
*/
if (flags & NDIGITS)
{
if (flags & EXPOK)
{
/* no digits at all */
while (p > buf)
{
ungetc (*(u_char *)-- p, fp);
--nread;
}
goto match_failure;
}
/* just a bad exponent (e and maybe sign) */
c = *(u_char *)-- p;
--nread;
if (c != 'e' && c != 'E')
{
_CAST_VOID ungetc (c, fp); /* sign */
c = *(u_char *)-- p;
--nread;
}
_CAST_VOID ungetc (c, fp);
}
if ((flags & SUPPRESS) == 0)
{
#ifdef _NO_LONGDBL
double res;
#else /* !_NO_LONG_DBL */
long double res;
#endif /* !_NO_LONG_DBL */
long new_exp = 0;
*p = 0;
if ((flags & (DPTOK | EXPOK)) == EXPOK)
{
exp_adjust = zeroes - leading_zeroes;
new_exp = -exp_adjust;
exp_start = p;
}
else if (exp_adjust)
new_exp = _strtol_r (rptr, (exp_start + 1), NULL, 10) - exp_adjust;
if (exp_adjust)
{
/* If there might not be enough space for the new exponent,
truncate some trailing digits to make room. */
if (exp_start >= buf + sizeof (buf) - MAX_LONG_LEN)
exp_start = buf + sizeof (buf) - MAX_LONG_LEN - 1;
sprintf (exp_start, "e%ld", new_exp);
}
#ifdef __SPE__
if (flags & FIXEDPOINT)
{
__uint64_t ufix64;
if (flags & SIGNED)
ufix64 = (__uint64_t)_strtosfix64_r (rptr, buf, NULL);
else
ufix64 = _strtoufix64_r (rptr, buf, NULL);
if (flags & SHORT)
{
__uint16_t *sp = va_arg (ap, __uint16_t *);
*sp = (__uint16_t)(ufix64 >> 48);
}
else if (flags & LONG)
{
__uint64_t *llp = va_arg (ap, __uint64_t *);
*llp = ufix64;
}
else
{
__uint32_t *lp = va_arg (ap, __uint32_t *);
*lp = (__uint32_t)(ufix64 >> 32);
}
nassigned++;
break;
}
#endif /* __SPE__ */
#ifdef _NO_LONGDBL
res = _strtod_r (rptr, buf, NULL);
#else /* !_NO_LONGDBL */
res = _strtold (buf, NULL);
#endif /* !_NO_LONGDBL */
if (flags & LONG)
{
dp = va_arg (ap, double *);
*dp = res;
}
else if (flags & LONGDBL)
{
ldp = va_arg (ap, _LONG_DOUBLE *);
*ldp = res;
}
else
{
if (!(flags & VECTOR))
flp = va_arg (ap, float *);
else if (!looped)
flp = vec_buf.f;
*flp++ = res;
}
if (!(flags & VECTOR))
nassigned++;
}
break;
}
#endif /* FLOATING_POINT */
}
if (vec_read_count-- > 1)
{
looped = 1;
goto process;
}
if (flags & VECTOR)
{
int i;
unsigned long *vp = va_arg (ap, unsigned long *);
for (i = 0; i < 4; ++i)
*vp++ = vec_buf.l[i];
nassigned++;
}
}
input_failure:
return nassigned ? nassigned : -1;
match_failure:
return nassigned;
}
/*
* Fill in the given table from the scanset at the given format
* (just after `['). Return a pointer to the character past the
* closing `]'. The table has a 1 wherever characters should be
* considered part of the scanset.
*/
/*static*/
u_char *
__sccl (tab, fmt)
register char *tab;
register u_char *fmt;
{
register int c, n, v;
/* first `clear' the whole table */
c = *fmt++; /* first char hat => negated scanset */
if (c == '^')
{
v = 1; /* default => accept */
c = *fmt++; /* get new first char */
}
else
v = 0; /* default => reject */
/* should probably use memset here */
for (n = 0; n < 256; n++)
tab[n] = v;
if (c == 0)
return fmt - 1; /* format ended before closing ] */
/*
* Now set the entries corresponding to the actual scanset to the
* opposite of the above.
*
* The first character may be ']' (or '-') without being special; the
* last character may be '-'.
*/
v = 1 - v;
for (;;)
{
tab[c] = v; /* take character c */
doswitch:
n = *fmt++; /* and examine the next */
switch (n)
{
case 0: /* format ended too soon */
return fmt - 1;
case '-':
/*
* A scanset of the form [01+-] is defined as `the digit 0, the
* digit 1, the character +, the character -', but the effect of a
* scanset such as [a-zA-Z0-9] is implementation defined. The V7
* Unix scanf treats `a-z' as `the letters a through z', but treats
* `a-a' as `the letter a, the character -, and the letter a'.
*
* For compatibility, the `-' is not considerd to define a range if
* the character following it is either a close bracket (required by
* ANSI) or is not numerically greater than the character we just
* stored in the table (c).
*/
n = *fmt;
if (n == ']' || n < c)
{
c = '-';
break; /* resume the for(;;) */
}
fmt++;
do
{ /* fill in the range */
tab[++c] = v;
}
while (c < n);
#if 1 /* XXX another disgusting compatibility hack */
/*
* Alas, the V7 Unix scanf also treats formats such
* as [a-c-e] as `the letters a through e'. This too
* is permitted by the standard....
*/
goto doswitch;
#else
c = *fmt++;
if (c == 0)
return fmt - 1;
if (c == ']')
return fmt;
#endif
break;
case ']': /* end of scanset */
return fmt;
default: /* just another character */
c = n;
break;
}
}
/* NOTREACHED */
}
|
durandj/devkitadv
|
newlib-1.11.0/newlib/libc/machine/powerpc/vfscanf.c
|
C
|
gpl-2.0
| 29,673
|
/*
* sunxi-ss-core.c - hardware cryptographic accelerator for Allwinner A20 SoC
*
* Copyright (C) 2013-2014 Corentin LABBE <clabbe.montjoie@gmail.com>
*
* Core file which registers crypto algorithms supported by the SS.
*
* You could find a link for the datasheet in Documentation/arm/sunxi/README
*
* 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/clk.h>
#include <linux/crypto.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <crypto/scatterwalk.h>
#include <linux/scatterlist.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include "sunxi-ss.h"
struct sunxi_ss_ctx *ss;
/*
* General notes for whole driver:
*
* After each request the device must be disabled with a write of 0 in SS_CTL
*
* For performance reason, we use writel_relaxed/read_relaxed for all
* operations on RX and TX FIFO and also SS_FCSR.
* Excepts for the last write on TX FIFO.
* For all other registers, we use writel/readl.
* See http://permalink.gmane.org/gmane.linux.ports.arm.kernel/117644
* and http://permalink.gmane.org/gmane.linux.ports.arm.kernel/117640
*/
static struct ahash_alg sunxi_md5_alg = {
.init = sunxi_hash_init,
.update = sunxi_hash_update,
.final = sunxi_hash_final,
.finup = sunxi_hash_finup,
.digest = sunxi_hash_digest,
.halg = {
.digestsize = MD5_DIGEST_SIZE,
.base = {
.cra_name = "md5",
.cra_driver_name = "md5-sunxi-ss",
.cra_priority = 300,
.cra_alignmask = 3,
.cra_flags = CRYPTO_ALG_TYPE_AHASH | CRYPTO_ALG_ASYNC,
.cra_blocksize = MD5_HMAC_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct sunxi_req_ctx),
.cra_module = THIS_MODULE,
.cra_type = &crypto_ahash_type,
.cra_init = sunxi_hash_crainit
}
}
};
static struct ahash_alg sunxi_sha1_alg = {
.init = sunxi_hash_init,
.update = sunxi_hash_update,
.final = sunxi_hash_final,
.finup = sunxi_hash_finup,
.digest = sunxi_hash_digest,
.halg = {
.digestsize = SHA1_DIGEST_SIZE,
.base = {
.cra_name = "sha1",
.cra_driver_name = "sha1-sunxi-ss",
.cra_priority = 300,
.cra_alignmask = 3,
.cra_flags = CRYPTO_ALG_TYPE_AHASH | CRYPTO_ALG_ASYNC,
.cra_blocksize = SHA1_BLOCK_SIZE,
.cra_ctxsize = sizeof(struct sunxi_req_ctx),
.cra_module = THIS_MODULE,
.cra_type = &crypto_ahash_type,
.cra_init = sunxi_hash_crainit
}
}
};
static struct crypto_alg sunxi_cipher_algs[] = {
{
.cra_name = "cbc(aes)",
.cra_driver_name = "cbc-aes-sunxi-ss",
.cra_priority = 300,
.cra_blocksize = AES_BLOCK_SIZE,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER,
.cra_ctxsize = sizeof(struct sunxi_tfm_ctx),
.cra_module = THIS_MODULE,
.cra_alignmask = 3,
.cra_type = &crypto_ablkcipher_type,
.cra_init = sunxi_ss_cipher_init,
.cra_u = {
.ablkcipher = {
.min_keysize = AES_MIN_KEY_SIZE,
.max_keysize = AES_MAX_KEY_SIZE,
.ivsize = AES_BLOCK_SIZE,
.setkey = sunxi_ss_aes_setkey,
.encrypt = sunxi_ss_cipher_encrypt,
.decrypt = sunxi_ss_cipher_decrypt,
}
}
}, {
.cra_name = "cbc(des)",
.cra_driver_name = "cbc-des-sunxi-ss",
.cra_priority = 300,
.cra_blocksize = DES_BLOCK_SIZE,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER,
.cra_ctxsize = sizeof(struct sunxi_req_ctx),
.cra_module = THIS_MODULE,
.cra_alignmask = 3,
.cra_type = &crypto_ablkcipher_type,
.cra_init = sunxi_ss_cipher_init,
.cra_u.ablkcipher = {
.min_keysize = DES_KEY_SIZE,
.max_keysize = DES_KEY_SIZE,
.ivsize = DES_BLOCK_SIZE,
.setkey = sunxi_ss_des_setkey,
.encrypt = sunxi_ss_cipher_encrypt,
.decrypt = sunxi_ss_cipher_decrypt,
}
}, {
.cra_name = "cbc(des3_ede)",
.cra_driver_name = "cbc-des3-sunxi-ss",
.cra_priority = 300,
.cra_blocksize = DES3_EDE_BLOCK_SIZE,
.cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER,
.cra_ctxsize = sizeof(struct sunxi_req_ctx),
.cra_module = THIS_MODULE,
.cra_alignmask = 3,
.cra_type = &crypto_ablkcipher_type,
.cra_init = sunxi_ss_cipher_init,
.cra_u.ablkcipher = {
.min_keysize = DES3_EDE_KEY_SIZE,
.max_keysize = DES3_EDE_KEY_SIZE,
.ivsize = DES3_EDE_BLOCK_SIZE,
.setkey = sunxi_ss_des3_setkey,
.encrypt = sunxi_ss_cipher_encrypt,
.decrypt = sunxi_ss_cipher_decrypt,
}
}
};
static int sunxi_ss_probe(struct platform_device *pdev)
{
struct resource *res;
u32 v;
int err;
unsigned long cr;
const unsigned long cr_ahb = 24 * 1000 * 1000;
const unsigned long cr_mod = 150 * 1000 * 1000;
if (!pdev->dev.of_node)
return -ENODEV;
ss = devm_kzalloc(&pdev->dev, sizeof(*ss), GFP_KERNEL);
if (ss == NULL)
return -ENOMEM;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
ss->base = devm_ioremap_resource(&pdev->dev, res);
if (IS_ERR(ss->base)) {
dev_err(&pdev->dev, "Cannot request MMIO\n");
return PTR_ERR(ss->base);
}
ss->ssclk = devm_clk_get(&pdev->dev, "mod");
if (IS_ERR(ss->ssclk)) {
err = PTR_ERR(ss->ssclk);
dev_err(&pdev->dev, "Cannot get SS clock err=%d\n", err);
return err;
}
dev_dbg(&pdev->dev, "clock ss acquired\n");
ss->busclk = devm_clk_get(&pdev->dev, "ahb");
if (IS_ERR(ss->busclk)) {
err = PTR_ERR(ss->busclk);
dev_err(&pdev->dev, "Cannot get AHB SS clock err=%d\n", err);
return err;
}
dev_dbg(&pdev->dev, "clock ahb_ss acquired\n");
/* Enable both clocks */
err = clk_prepare_enable(ss->busclk);
if (err != 0) {
dev_err(&pdev->dev, "Cannot prepare_enable busclk\n");
return err;
}
err = clk_prepare_enable(ss->ssclk);
if (err != 0) {
dev_err(&pdev->dev, "Cannot prepare_enable ssclk\n");
clk_disable_unprepare(ss->busclk);
return err;
}
/*
* Check that clock have the correct rates gived in the datasheet
* Try to set the clock to the maximum allowed
*/
err = clk_set_rate(ss->ssclk, cr_mod);
if (err != 0) {
dev_err(&pdev->dev, "Cannot set clock rate to ssclk\n");
clk_disable_unprepare(ss->ssclk);
clk_disable_unprepare(ss->busclk);
return err;
}
cr = clk_get_rate(ss->busclk);
if (cr >= cr_ahb)
dev_dbg(&pdev->dev, "Clock bus %lu (%lu MHz) (must be >= %lu)\n",
cr, cr / 1000000, cr_ahb);
else
dev_warn(&pdev->dev, "Clock bus %lu (%lu MHz) (must be >= %lu)\n",
cr, cr / 1000000, cr_ahb);
cr = clk_get_rate(ss->ssclk);
if (cr <= cr_mod)
if (cr < cr_mod)
dev_info(&pdev->dev, "Clock ss %lu (%lu MHz) (must be <= %lu)\n",
cr, cr / 1000000, cr_mod);
else
dev_dbg(&pdev->dev, "Clock ss %lu (%lu MHz) (must be <= %lu)\n",
cr, cr / 1000000, cr_mod);
else
dev_warn(&pdev->dev, "Clock ss is at %lu (%lu MHz) (must be <= %lu)\n",
cr, cr / 1000000, cr_mod);
/*
* Datasheet named it "Die Bonding ID"
* I expect to be a sort of Security System Revision number.
* Since the A80 seems to have an other version of SS
* this info could be useful
*/
writel(SS_ENABLED, ss->base + SS_CTL);
v = readl(ss->base + SS_CTL);
v >>= 16;
v &= 0x07;
dev_info(&pdev->dev, "Die ID %d\n", v);
writel(0, ss->base + SS_CTL);
ss->dev = &pdev->dev;
mutex_init(&ss->lock);
mutex_init(&ss->bufin_lock);
mutex_init(&ss->bufout_lock);
err = crypto_register_ahash(&sunxi_md5_alg);
if (err)
goto error_md5;
err = crypto_register_ahash(&sunxi_sha1_alg);
if (err)
goto error_sha1;
err = crypto_register_algs(sunxi_cipher_algs,
ARRAY_SIZE(sunxi_cipher_algs));
if (err)
goto error_ciphers;
return 0;
error_ciphers:
crypto_unregister_ahash(&sunxi_sha1_alg);
error_sha1:
crypto_unregister_ahash(&sunxi_md5_alg);
error_md5:
clk_disable_unprepare(ss->ssclk);
clk_disable_unprepare(ss->busclk);
return err;
}
static int __exit sunxi_ss_remove(struct platform_device *pdev)
{
if (!pdev->dev.of_node)
return 0;
crypto_unregister_ahash(&sunxi_md5_alg);
crypto_unregister_ahash(&sunxi_sha1_alg);
crypto_unregister_algs(sunxi_cipher_algs,
ARRAY_SIZE(sunxi_cipher_algs));
if (ss->buf_in != NULL)
kfree(ss->buf_in);
if (ss->buf_out != NULL)
kfree(ss->buf_out);
writel(0, ss->base + SS_CTL);
clk_disable_unprepare(ss->busclk);
clk_disable_unprepare(ss->ssclk);
return 0;
}
static const struct of_device_id a20ss_crypto_of_match_table[] = {
{ .compatible = "allwinner,sun7i-a20-crypto" },
{}
};
MODULE_DEVICE_TABLE(of, a20ss_crypto_of_match_table);
static struct platform_driver sunxi_ss_driver = {
.probe = sunxi_ss_probe,
.remove = __exit_p(sunxi_ss_remove),
.driver = {
.owner = THIS_MODULE,
.name = "sunxi-ss",
.of_match_table = a20ss_crypto_of_match_table,
},
};
module_platform_driver(sunxi_ss_driver);
MODULE_DESCRIPTION("Allwinner Security System cryptographic accelerator");
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Corentin LABBE <clabbe.montjoie@gmail.com>");
|
pokymobo/linux-yocto-lamobo-r1
|
drivers/crypto/sunxi-ss/sunxi-ss-core.c
|
C
|
gpl-2.0
| 8,878
|
div.dataTables_length label {
float: left;
text-align: left;
}
div.dataTables_length select {
width: 75px;
}
div.dataTables_filter label {
float: right;
}
div.dataTables_info {
padding-top: 8px;
}
div.dataTables_paginate {
float: right;
margin: 0;
}
table.table {
clear: both;
margin-bottom: 6px !important;
max-width: none !important;
}
table.table thead .sorting,
table.table thead .sorting_asc,
table.table thead .sorting_desc,
table.table thead .sorting_asc_disabled,
table.table thead .sorting_desc_disabled {
cursor: pointer;
*cursor: hand;
}
table.table thead .sorting { background: url('sort_both.png') no-repeat center right; }
table.table thead .sorting_asc { background: url('sort_asc.png') no-repeat center right; }
table.table thead .sorting_desc { background: url('sort_desc.png') no-repeat center right; }
table.table thead .sorting_asc_disabled { background: url('sort_asc_disabled.html') no-repeat center right; }
table.table thead .sorting_desc_disabled { background: url('sort_desc_disabled.html') no-repeat center right; }
table.dataTable th:active {
outline: none;
}
/* Scrolling */
div.dataTables_scrollHead table {
margin-bottom: 0 !important;
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
}
div.dataTables_scrollHead table thead tr:last-child th:first-child,
div.dataTables_scrollHead table thead tr:last-child td:first-child {
border-bottom-left-radius: 0 !important;
border-bottom-right-radius: 0 !important;
}
div.dataTables_scrollBody table {
border-top: none;
margin-bottom: 0 !important;
}
div.dataTables_scrollBody tbody tr:first-child th,
div.dataTables_scrollBody tbody tr:first-child td {
border-top: none;
}
div.dataTables_scrollFoot table {
border-top: none;
}
/*
* TableTools styles
*/
.table tbody tr.active td,
.table tbody tr.active th {
background-color: #08C;
color: white;
}
.table tbody tr.active:hover td,
.table tbody tr.active:hover th {
background-color: #0075b0 !important;
}
.table-striped tbody tr.active:nth-child(odd) td,
.table-striped tbody tr.active:nth-child(odd) th {
background-color: #017ebc;
}
table.DTTT_selectable tbody tr {
cursor: pointer;
*cursor: hand;
}
div.DTTT .btn {
color: #333 !important;
font-size: 12px;
}
div.DTTT .btn:hover {
text-decoration: none !important;
}
ul.DTTT_dropdown.dropdown-menu a {
color: #333 !important; /* needed only when demo_page.css is included */
}
ul.DTTT_dropdown.dropdown-menu li:hover a {
background-color: #0088cc;
color: white !important;
}
/* TableTools information display */
div.DTTT_print_info.modal {
height: 150px;
margin-top: -75px;
text-align: center;
}
div.DTTT_print_info h6 {
font-weight: normal;
font-size: 28px;
line-height: 28px;
margin: 1em;
}
div.DTTT_print_info p {
font-size: 14px;
line-height: 20px;
}
/*
* FixedColumns styles
*/
div.DTFC_LeftHeadWrapper table,
div.DTFC_LeftFootWrapper table,
table.DTFC_Cloned tr.even {
background-color: white;
}
div.DTFC_LeftHeadWrapper table {
margin-bottom: 0 !important;
border-top-right-radius: 0 !important;
border-bottom-left-radius: 0 !important;
border-bottom-right-radius: 0 !important;
}
div.DTFC_LeftHeadWrapper table thead tr:last-child th:first-child,
div.DTFC_LeftHeadWrapper table thead tr:last-child td:first-child {
border-bottom-left-radius: 0 !important;
border-bottom-right-radius: 0 !important;
}
div.DTFC_LeftBodyWrapper table {
border-top: none;
margin-bottom: 0 !important;
}
div.DTFC_LeftBodyWrapper tbody tr:first-child th,
div.DTFC_LeftBodyWrapper tbody tr:first-child td {
border-top: none;
}
div.DTFC_LeftFootWrapper table {
border-top: none;
}
|
hankqin/device-manager
|
device-zjjs/webapp/frame/css/dt_bootstrap.css
|
CSS
|
gpl-2.0
| 3,647
|
<?php
namespace Spray\Serializer\TestAssets;
use DateTime;
class Foo
{
/**
* @var BarCollection
*/
private $bars;
/**
* @var Baz
*/
private $baz;
/**
* @var DateTime
*/
private $date;
/**
* @var Ignore
*/
private $ignore;
public function __construct(
BarCollection $bars = null,
Baz $baz = null,
DateTime $date = null,
Ignore $ignore = null)
{
$this->bars = $bars;
$this->baz = $baz;
$this->date = $date;
$this->ignore = $ignore;
}
}
|
JurJean/SpraySerializer
|
test/TestAssets/Foo.php
|
PHP
|
gpl-2.0
| 597
|
<?php
/**
* @package languageDefines
* @ Maintained by Zen4All (https://zen4all.nl)
* @copyright Copyright 2003-2017 Zen Cart Development Team
* @copyright Portions Copyright 2003 osCommerce
* @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
* @version $Id: Author: DrByte Modified in v1.5.5 $
*/
define('NAVBAR_TITLE_1', 'Afrekenen - Stap 1');
define('NAVBAR_TITLE_2', 'Betaalmethode - Stap 2');
define('HEADING_TITLE', 'Stap 2 van 3 - Betaalgegevens');
define('TABLE_HEADING_BILLING_ADDRESS', 'Factuuradres');
define('TEXT_SELECTED_BILLING_DESTINATION', 'Uw factuuradres wordt aan de linkerzijde getoont. Factuuradres moet gelijk zijn aan het adres van uw creditcard! U kunt het factuuradres wijzigen door op de <em>Wijzig adres</em> knop te klikken.');
define('TITLE_BILLING_ADDRESS', 'Factuuradres:');
define('TABLE_HEADING_PAYMENT_METHOD', 'Betaalmethode');
define('TEXT_SELECT_PAYMENT_METHOD', 'Kies een betaalmethode.');
define('TITLE_PLEASE_SELECT', 'Maak keuze');
define('TEXT_ENTER_PAYMENT_INFORMATION', '');
define('TABLE_HEADING_COMMENTS', 'Speciale instructies of opmerkingen bestelling');
define('TITLE_NO_PAYMENT_OPTIONS_AVAILABLE', 'Momenteel niet beschikbaar');
define('TEXT_NO_PAYMENT_OPTIONS_AVAILABLE','<span class="alert">Sorry, wij accepteren nog geen internet betalingen uit uw regio.</span><br />Neem alstublieft even contact met ons op voor een alternatieve betaalmethode.');
define('TITLE_CONTINUE_CHECKOUT_PROCEDURE', '<strong>Doorgaan naar Stap 4</strong>');
define('TEXT_CONTINUE_CHECKOUT_PROCEDURE', '- om uw bestelling te bevestigen.');
define('TABLE_HEADING_CONDITIONS', '<span class="termsconditions">Voorwaarden en betalingscondities</span>');
define('TEXT_CONDITIONS_DESCRIPTION', '<span class="termsdescription">Lees en accepteer alstublieft de voorwaarden en betalingscondities die op de bestelling van toepassing zijn door het selectievakje aantevinken. De voorwaarden en betalingscondities kunt u <a href="' . zen_href_link(FILENAME_CONDITIONS, '', 'SSL') . '" target="_blank"><span class="pseudolink">hier [klik]</span></a>lezen.</span>');
define('TEXT_CONDITIONS_CONFIRM', '<span class="termsiagree">Ik heb de voorwaarden en betalingscondities zoals van toepassing op deze bestelling gelezen en ga hier uitdrukkelijk mee akkoord.</span>');
define('TEXT_CHECKOUT_AMOUNT_DUE', 'Totaal te voldoen: ');
define('TEXT_YOUR_TOTAL','Uw totaal');
|
Zen4All/Zen-Cart-Dutch-Language-Pack
|
1_Installation_files/includes/languages/dutch/checkout_payment.php
|
PHP
|
gpl-2.0
| 2,419
|
/*
* Copyright 2012-2014 Applifier
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import "EveryplayFaceCam.h"
#import "EveryplayCapture.h"
#import "EveryplayAccount.h"
#import "EveryplayRequest.h"
#import "EveryplaySoundEngine.h"
#pragma mark - Developer metadata
extern NSString * const kEveryplayMetadataScoreInteger; // @"score"
extern NSString * const kEveryplayMetadataLevelInteger; // @"level"
extern NSString * const kEveryplayMetadataLevelNameString; // @"level_name"
#pragma mark - View controller flow settings
typedef enum {
EveryplayFlowReturnsToGame = 1 << 0, // Default
EveryplayFlowReturnsToVideoPlayer = 1 << 1
} EveryplayFlowDefs;
#pragma mark - Error codes
extern NSString * const kEveryplayErrorDomain; // @"com.everyplay"
extern const int kEveryplayLoginCanceledError; // 100
extern const int kEveryplayMovieExportCanceledError; // 101
extern const int kEveryplayFileUploadError; // 102
#pragma mark - Notifications
extern NSString * const EveryplayAccountDidChangeNotification;
extern NSString * const EveryplayDidFailToRequestAccessNotification;
#pragma mark - Handler
typedef void(^EveryplayAccessRequestCompletionHandler)(NSError *error);
typedef void(^EveryplayPreparedAuthorizationURLHandler)(NSURL *preparedURL);
typedef void(^EveryplayDataLoadingHandler)(NSError *error, id data);
#pragma mark - Compile-time options
@interface EveryplayFeatures : NSObject
/*
* Is running on iOS 5 or later?
* Useful for disabling functionality on older devices.
*/
+ (BOOL) isSupported;
/*
* Returns the number of CPU cores on device.
* Useful for disabling functionality on older devices.
*/
+ (NSUInteger) numCores;
/*
* To disable Everyplay OpenAL implementation, override this class
* method to return NO.
*/
+ (BOOL) supportsOpenAL;
/*
* To disable Everyplay OpenAL "missing implementation" messages, override
* this class method to return YES.
*/
+ (BOOL) disableOpenALMessages;
/*
* CocosDenshion background music support currently lacks hardware
* decoder support. To disable recording support for background music,
* override this class method to return NO.
*/
+ (BOOL) supportsCocosDenshion;
/*
* AVFoundation AVAudioPlayer support currently lacks hardware
* decoder support. To disable recording support for background music,
* override this class method to return NO.
*/
+ (BOOL) supportsAVFoundation;
@end
#pragma mark -
@class EveryplayAccount;
@class EveryplayVideoPlayerViewController;
@protocol EveryplayDelegate <NSObject>
- (void)everyplayShown;
- (void)everyplayHidden;
@optional
- (void)everyplayReadyForRecording:(NSNumber *)enabled;
- (void)everyplayRecordingStarted;
- (void)everyplayRecordingStopped;
- (void)everyplayFaceCamSessionStarted;
- (void)everyplayFaceCamRecordingPermission:(NSNumber *)granted;
- (void)everyplayFaceCamSessionStopped;
- (void)everyplayUploadDidStart:(NSNumber *)videoId;
- (void)everyplayUploadDidProgress:(NSNumber *)videoId progress:(NSNumber *)progress;
- (void)everyplayUploadDidComplete:(NSNumber *)videoId;
- (void)everyplayThumbnailReadyAtFilePath:(NSString *)thumbnailFilePath;
- (void)everyplayThumbnailReadyAtURL:(NSURL *)thumbnailUrl;
- (void)everyplayThumbnailReadyAtTextureId:(NSNumber *)textureId portraitMode:(NSNumber *)portrait;
@end
@interface Everyplay : NSObject
#pragma mark - Properties
@property (nonatomic, unsafe_unretained) EveryplayCapture *capture;
@property (nonatomic, strong) EveryplayFaceCam *faceCam;
@property (nonatomic, strong) UIViewController *parentViewController;
@property (nonatomic, strong) id <EveryplayDelegate> everyplayDelegate;
@property (nonatomic, assign) EveryplayFlowDefs flowControl;
#pragma mark - Singleton
+ (Everyplay *)sharedInstance;
+ (BOOL)isSupported;
+ (Everyplay *)initWithDelegate:(id <EveryplayDelegate>)everyplayDelegate;
+ (Everyplay *)initWithDelegate:(id <EveryplayDelegate>)everyplayDelegate andParentViewController:(UIViewController *)viewController;
+ (Everyplay *)initWithDelegate:(id <EveryplayDelegate>)everyplayDelegate andAddRootViewControllerForView:(UIView *)view;
#pragma mark - Public Methods
- (void)showEveryplay;
- (void)showEveryplayWithPath:(NSString *)path;
- (void)showEveryplaySharingModal;
- (void)hideEveryplay;
- (void)playLastRecording;
- (void)mergeSessionDeveloperData:(NSDictionary *)dictionary;
#pragma mark - Video playback
- (void)playVideoWithURL:(NSURL *)videoURL;
- (void)playVideoWithDictionary:(NSDictionary *)videoDictionary;
#pragma mark - Manage Accounts
+ (EveryplayAccount *)account;
+ (void)requestAccessWithCompletionHandler:(EveryplayAccessRequestCompletionHandler)aCompletionHandler;
+ (void)requestAccessforScopes:(NSString *)scopes
withCompletionHandler:(EveryplayAccessRequestCompletionHandler)aCompletionHandler;
+ (void)removeAccess;
#pragma mark - Facebook authentication
+ (BOOL)handleOpenURL:(NSURL *)url sourceApplication:(id)sourceApplication annotation:(id)annotation;
#pragma mark - Configuration
+ (void)setClientId:(NSString *)client
clientSecret:(NSString *)secret
redirectURI:(NSString *)url;
#pragma mark - OAuth2 Flow
+ (BOOL)handleRedirectURL:(NSURL *)URL;
@end
#pragma mark - Macros
#define EVERYPLAY_CANCELED(error) ([error.domain isEqualToString:(NSString *)kEveryplayErrorDomain] && error.code == kEveryplayLoginCanceledError)
|
Reminouche/TCG
|
Assets/Plugins/Everyplay/iOS/Everyplay.framework/Headers/Everyplay.h
|
C
|
gpl-2.0
| 5,941
|
<?php
/*
Plugin Name: Statistika
*/
function statistika()
{
$count_posts = wp_count_posts();
$posts = $count_posts->publish;
$count_igre = wp_count_posts('druzabneigre');
$st_iger = $count_igre->publish;
$count_comments = get_comment_count();
$comments = $count_comments['approved'];
echo "Igre: " . $st_iger ."</br>Objav: " .$posts . "</br>Komentarjev: ".$comments." </br>Povprečje komentarjev: ".round($comments/$posts)." na objavo.";
}
function widget_statistika($args) {
extract($args);
echo $before_widget;
echo $before_title;?>Statistika<?php echo $after_title;
statistika();
echo $after_widget;
}
function statistika_init()
{
register_sidebar_widget(__('Statistika'), 'widget_statistika');
}
add_action('plugins_loaded', 'statistika_init');
?>
|
spleteh/Wordpress
|
wp-content/plugins/mu-plugins/statistika.php
|
PHP
|
gpl-2.0
| 777
|
<?php
global $wpdb;
$this->auto_clean();
$sabre_opt = $this->get_option('sabre_opt');
// Check the news
$new_spams = $this->get_new_spam();
if ($new_spams)
$new_spams = " ($new_spams)";
else
$new_spams = "";
$new_approved = $this->get_new_users();
if ($new_approved)
$new_approved = " ($new_approved)";
else
$new_approved = "";
$new_confirmed = $this->get_new_confirm();
if ($new_confirmed)
$new_confirmed = " ($new_confirmed)";
else
$new_confirmed = "";
$sabre_tabs = array ("option" => __("General Options", 'sabre'), "spam" => __("Blocked Registrations", 'sabre') . $new_spams, "approved" => __("Approved Registrations", 'sabre') . $new_approved, "confirm" => __("Registrations to confirm", 'sabre') . $new_confirmed, "about" => __("About", 'sabre'));
if (isset($_REQUEST['sabre_action']) && !empty($sabre_tabs[$_REQUEST['sabre_action']]))
$cur_tab = $_REQUEST['sabre_action'];
else
$cur_tab = "option";
echo '<ul id="sabre_menu">';
// $url = esc_url($_SERVER['PHP_SELF']) . "?page=sabre" . "&sabre_action=";
$url = "tools.php?page=sabre" . "&sabre_action=";
foreach ($sabre_tabs as $tab => $name) {
if ($cur_tab == $tab)
echo "<li class=\"current\">$name</li>";
else
echo "<li><a href=\"" . $url . $tab . "\">$name</a></li>";
}
echo '</ul>';
switch ($cur_tab)
{
case 'spam' :
case 'approved' :
case 'confirm' :
$regmsg = '';
if ($_REQUEST['add_regs'] && $_REQUEST['userid'])
$regmsg = $this->add_reg_user($_REQUEST['userid']);
if ($_REQUEST['add_regs'] && $_REQUEST['all_users'])
$regmsg = $this->add_all_users();
if ($_REQUEST['del_regs'] && $_REQUEST['list_sel'])
$regmsg = $this->del_reg_user($_REQUEST['list_sel']);
if ($_REQUEST['del_unregs']) {
$regmsg = $this->del_unreg_user($_REQUEST['del_days']);
if (isset($_REQUEST['del_auto']))
$sabre_opt['purge_days'] = (int)$_REQUEST['del_days'];
}
if ($_REQUEST['confirm_regs'] && $_REQUEST['list_sel'])
$regmsg = $this->confirm_reg_user($_REQUEST['list_sel']);
if ($_REQUEST['unconfirm_regs'] && $_REQUEST['list_sel'])
$regmsg = $this->unconfirm_reg_user($_REQUEST['list_sel']);
if ($cur_tab == 'spam') {
$where = "`status` = 'ko'";
$sabre_opt['last_spam_check'] = current_time('timestamp', 0);
$title = __("Invalid registration list", 'sabre');
}
elseif ($cur_tab == 'approved') {
$where = "`status` = 'ok'";
$sabre_opt['last_approved_check'] = current_time('timestamp', 0);
$title = __("Valid registration list", 'sabre');
}
else {
$where = "`status` = 'to confirm'";
$sabre_opt['last_confirm_check'] = current_time('timestamp', 0);
$title = __("To confirm registration list", 'sabre');
}
$query_limit_str = $query_limit = max(20, @$_REQUEST['rows_per_page']);
if (@$_REQUEST['skip_rows'])
$query_limit_str = $_REQUEST['skip_rows'] . ", " . ($_REQUEST['skip_rows'] + $query_limit);
$query = "SELECT `id`, `user`, `email`, `user_IP`, `last_mod`, `msg`, `user_id`, `invite` FROM `" . SABRE_TABLE . "` WHERE " . $where . " ORDER BY `last_mod` DESC LIMIT " . $query_limit_str;
$spam_rows = $wpdb->get_results($query);
echo '<div class="wrap sabre_notopmargin">';
if (!empty($regmsg)) {
echo '<div id="message" class="updated fade"><p>' . $regmsg . '</p></div>';
}
echo '<h2>' . $title . '</h2>';
echo '<p class="sabre_form"><form id="sabre_list_form" name="sabre_list_form" method="get" action="tools.php">';
if (function_exists('wp_nonce_field'))
wp_nonce_field('sabre-manage_registration');
if ($cur_tab == 'approved') {
echo '<h3>' . __("Manual registration", 'sabre') . '</h3>';
echo '<div class="tablenav">';
echo '<input type="submit" name="add_regs" id="add_regs" value="' . __("Add", 'sabre') . '" class="button-secondary" />';
echo '<input type="text" id="userid" name="userid" size="25"/> ' . __("Enter WordPress user name or check the box to add all existing WordPress users ", 'sabre');
echo '<input type="checkbox" name="all_users" id="all_users" value="yes" />';
echo '</div>';
echo '<h3>' . __("Manual deregistration", 'sabre') . '</h3>';
echo '<div class="tablenav">';
echo '<input type="submit" name="del_regs" id="del_regs" value="' . __("Unregister", 'sabre') . '" class="button-secondary" />' . __("Unregister selected users", 'sabre');
echo '</div>';
}
if ($cur_tab == 'spam') {
echo '<h3>' . __("Purge log", 'sabre') . '</h3>';
echo '<div class="tablenav">';
echo '<input type="submit" name="del_unregs" id="del_unregs" value="' . __("Delete", 'sabre') . '" class="button-secondary" /> ';
echo __("Log older than", 'sabre');
echo ' <input type="text" value="' . $sabre_opt['purge_days'] . '" id="del_days" name="del_days" size="3"/> ' . __("days", 'sabre');
echo ' (' . __('And do it automatically now', 'sabre') . '<input type="checkbox" name="del_auto" id="del_auto" value="yes" checked />)';
echo '</div>';
}
if ($cur_tab == 'confirm') {
echo '<h3>' . __("Warning!", 'sabre') . '</h3>';
echo '<div class="tablenav">';
if ($sabre_opt['enable_confirm'] == 'user')
_e("You set Sabre's behaviour to ask for user's confirmation of his registration. Normally, you don't have to intervene here but you can confirm or refuse it manually if needed.", 'sabre');
elseif ($sabre_opt['enable_confirm'] == 'admin')
_e("You set Sabre's behaviour to ask for your confirmation of user's registration. You have to confirm or refuse it manually to complete the process.", 'sabre');
else _e("You set Sabre's behaviour to register the user without confirmation. This screen will always be empty.", 'sabre');
echo '</div>';
if ($sabre_opt['enable_confirm'] <> 'none') {
echo '<h3>' . __("Confirm registration", 'sabre') . '</h3>';
echo '<div class="tablenav">';
echo '<input type="submit" name="confirm_regs" id="confirm_regs" value="' . __("Confirm", 'sabre') . '" class="button-secondary" />' . __("Validate selected registrations", 'sabre');
echo '</div>';
echo '<h3>' . __("Refuse registration", 'sabre') . '</h3>';
echo '<div class="tablenav">';
echo '<input type="submit" name="unconfirm_regs" id="unconfirm_regs" value="' . __("Refuse", 'sabre') . '" class="button-secondary" />' . __("Refuse selected registrations", 'sabre');
echo '</div>';
}
}
echo '<h3>' . __("Browse", 'sabre') . '</h3>';
echo '<div class="tablenav">';
echo '<input type="hidden" name="page" id="page" value="sabre" />';
echo '<input type="hidden" name="sabre_action" id="sabre_action" value="' . $cur_tab . '" />';
echo '<input type="submit" name="display_regs" id="display_regs" value="' . __("Display", 'sabre') . '" class="button-secondary" />';
echo '<input type="text" id="rows_per_page" name="rows_per_page" value="' . $query_limit . '" size="3"/> ' . __("lines per page, skipping first: ", 'sabre');
echo '<input type="text" id="skip_rows" name="skip_rows" value="' . intval(@$_REQUEST['skip_rows']) . '" size="3" />';
echo '</div>';
echo '<br class="clear" />';
echo '<table id="sabre_spam_list" class="widefat">';
echo '<thead><tr><th><strong>' . __('Id', 'sabre') . '</strong></th><th><strong>' . __('User name', 'sabre') . '</strong></th><th><strong>' . __('User E-mail', 'sabre') . '</strong></th><th><strong>' . __('User IP', 'sabre') . '</strong></th><th>' . __('When', 'sabre') . '</strong></th>' . ($cur_tab == 'spam' ? '' : '<th><strong>' . __('Invitation', 'sabre') . '</strong></th>') . '<th><strong>' . ($cur_tab == 'spam' ? __('Errors', 'sabre') : __('User ID', 'sabre')) . '</strong></th></tr></thead><tbody>';
if (is_array($spam_rows)) {
$rowid = 0;
foreach ($spam_rows as $row) {
$rowid += 1;
echo '<tr valign="middle"' . ($rowid % 2 ? '>' : ' class="alternate">');
if ($cur_tab == 'spam')
echo '<td>' . $row->id . '</td>';
else
echo '<th scope="row" class="check-column"><input type="checkbox" name="list_sel[' . $row->id . ']" id="list_sel[' . $row->id . ']" value="' . $row->id . '" />' . $row->id . '</th>';
echo '<td>';
echo $row->user;
echo '</td><td>';
echo $row->email;
echo '</td><td>';
echo $row->user_IP;
echo '</td><td>';
echo $row->last_mod;
echo '</td><td>';
if ($cur_tab == 'spam') {
$msgs= "";
if (!empty($row->msg)) {
$msgs_array = unserialize($row->msg);
if (is_array($msgs_array))
foreach ($msgs_array as $msg_type => $msg) {
$msgs .= $msg;
$msgs .= '<br />';
}
}
echo $msgs;
}
else {
echo $row->invite;
echo '</td><td>';
if ($row->user_id > 0)
echo '<a href="' . get_bloginfo('wpurl') . '/wp-admin/user-edit.php?user_id=' . $row->user_id . '" >' . $row->user_id . '</a>';
}
echo '</td></tr>';
}
}
echo '</tbody></table>';
echo '</form></p>';
echo '</div>';
$this->update_option('sabre_opt', $sabre_opt);
break;
case 'logs' :
echo '<div class="wrap sabre_notopmargin">';
echo '<h2>' . __("Events history", 'sabre') . '</h2>';
echo '</div>';
break;
case 'about' :
require_once(SABREPATH . "/classes/sabre_class_about.php");
break;
case 'option':
default:
$total_pending = $wpdb->get_var("SELECT COUNT(*) FROM `" . SABRE_TABLE . "` WHERE `status` = 'to confirm'");
echo '<div class="wrap sabre_notopmargin">';
if ($this->save_options($_POST))
echo '<div id="message" class="updated fade"><p>' . __('Options successfully saved.', 'sabre') . '</p></div>';
if (!empty($_POST['active_option']))
$active_option = sanitize_text_field($_POST['active_option']);
else
$active_option = 'captcha_table';
echo '<h2>' . __("Quick figures", 'sabre') . '</h2>';
echo '<ul>';
echo '<li>' . __('Total number of registrations stopped:', 'sabre') . ' <strong>' . (int)$sabre_opt['total_stopped'] . '</strong></li>';
echo '<li>' . __('Total number of registrations accepted:', 'sabre') . ' <strong>' . (int)$sabre_opt['total_accepted'] . '</strong></li>';
echo '<li>' . __('Number of pending confirmation:', 'sabre') . ' <strong>' . (int)$total_pending . '</strong></li>';
echo '</ul>';
echo '</div>';
$sabre_opt = $this->get_option('sabre_opt');
if (is_array($sabre_opt))
extract ($sabre_opt, EXTR_OVERWRITE) ;
echo '<div class="wrap sabre_notopmargin">';
echo '<h2>' . __("General Options", 'sabre') . '</h2>';
echo '<form id="sabre_option_form" name="sabre_option_form" method="post" action="tools.php?page=sabre&sabre_action=option">';
if (function_exists('wp_nonce_field'))
wp_nonce_field('sabre-manage_option');
echo '<input type="hidden" name="active_option" id="active_option" value="' . $active_option . '" />';
echo '<div id="sabre_opt_accordion">';
echo '<h3><a href="#">' . __("Captcha options", 'sabre') . '</a></h3>';
echo '<table id="captcha_table" class="form-table">';
echo '<tr><th><label for="sabre_enable_captcha">' . __('Enable captcha test:', 'sabre') . '</label></th><td><input type="checkbox" ' . $this->checked($enable_captcha, 'true') . ' name="sabre_enable_captcha" id="sabre_enable_captcha" value="true" /></td><td>' . __('(Turn captcha generation on/off)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_white_bg">' . __('Use white background:', 'sabre') . '</label></th><td><input type="checkbox" ' . $this->checked($white_bg, 'true') . ' name="sabre_white_bg" id="sabre_white_bg" value="true" /></td><td>' . __('(Captcha is displayed on a white background. Black background if not checked)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_acceptedChars">' . __('Accepted characters:', 'sabre') . '</label></th><td><input type="text" size="50" name="sabre_acceptedChars" id="sabre_acceptedChars" value="' . $acceptedChars . '" /></td><td>' . __('(List of valid characters for code generation)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_stringlength">' . __('String length:', 'sabre') . '</label></th><td><input type="text" size="2" name="sabre_stringlength" id="sabre_stringlength" value="' . $stringlength . '" /></td><td>' . __('(Number of characters for code)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_contrast">' . __('Contrast:', 'sabre') . '</label></th><td><input type="text" size="2" name="sabre_contrast" id="sabre_contrast" value="' . $contrast . '" /></td><td>' . __('(The higher the number, the better the contrast)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_num_polygons">' . __('Number of polygons:', 'sabre') . '</label></th><td><input type="text" size="2" name="sabre_num_polygons" id="sabre_num_polygons" value="' . $num_polygons . '" /></td><td>' . __('(Number of triangles to draw. 0 = none)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_num_ellipses">' . __('Number of ellipses:', 'sabre') . '</label></th><td><input type="text" size="2" name="sabre_num_ellipses" id="sabre_num_ellipses" value="' . $num_ellipses . '" /></td><td>' . __('(Number of ellipses to draw. 0 = none)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_num_lines">' . __('Number of lines:', 'sabre') . '</label></th><td><input type="text" size="2" name="sabre_num_lines" id="sabre_num_lines" value="' . $num_lines . '" /></td><td>' . __('(Number of lines to draw. 0 = none)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_num_dots">' . __('Number of dots:', 'sabre') . '</label></th><td><input type="text" size="2" name="sabre_num_dots" id="sabre_num_dots" value="' . $num_dots . '" /></td><td>' . __('(Number of dots to draw. 0 = none)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_min_thickness">' . __('Min. thickness:', 'sabre') . '</label></th><td><input type="text" size="2" name="sabre_min_thickness" id="sabre_min_thickness" value="' . $min_thickness . '" /></td><td>' . __('(Minimum thickness of lines in pixels)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_max_thickness">' . __('Max. thickness:', 'sabre') . '</label></th><td><input type="text" size="2" name="sabre_max_thickness" id="sabre_max_thickness" value="' . $max_thickness . '" /></td><td>' . __('(Maximum thickness of lines in pixels)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_min_radius">' . __('Min. radius:', 'sabre') . '</label></th><td><input type="text" size="2" name="sabre_min_radius" id="sabre_min_radius" value="' . $min_radius . '" /></td><td>' . __('(Minimum radius of ellipses)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_max_radius">' . __('Max. radius:', 'sabre') . '</label></th><td><input type="text" size="2" name="sabre_max_radius" id="sabre_max_radius" value="' . $max_radius . '" /></td><td>' . __('(Maximum radius of ellipses)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_object_alpha">' . __('Object alpha:', 'sabre') . '</label></th><td><input type="text" size="2" name="sabre_object_alpha" id="sabre_object_alpha" value="' . $object_alpha . '" /></td><td>' . __('(How opaque should the obscuring objects be. 0 is opaque, 127 is transparent)', 'sabre') . '</td></tr>';
echo '</table>';
echo '<h3><a href="#">' . __("Math options", 'sabre') . '</a></h3>';
echo '<table id="math_table" class="form-table">';
echo '<tr><th><label for="sabre_enable_math">' . __('Enable math test:', 'sabre') . '</label></th><td><input type="checkbox" ' . $this->checked($enable_math, 'true') . ' name="sabre_enable_math" id="sabre_enable_math" value="true" /></td><td>' . __('(Turn math control on/off)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_math_ops">' . __('Accepted operations:', 'sabre') . '</label></th><td><input type="text" size="2" name="sabre_math_ops" id="sabre_math_ops" value="' . $math_ops . '" /></td><td>' . __('(List of valid operations for math test)', 'sabre') . '</td></tr>';
echo '</table>';
echo '<h3><a href="#">' . __("Text captcha options", 'sabre') . '</a></h3>';
echo '<table id="text_table" class="form-table">';
echo '<tr><th><label for="sabre_enable_text">' . __('Enable text test:', 'sabre') . '</label></th><td><input type="checkbox" ' . $this->checked($enable_text, 'true') . ' name="sabre_enable_text" id="sabre_enable_text" value="true" /></td><td>' . __('(Turn text challenge on/off - The user will be asked to type the nth letter of a random word)', 'sabre') . '</td></tr>';
echo '</table>';
echo '<h3><a href="#">' . __("Sequence of tests", 'sabre') . '</a></h3>';
echo '<table id="seq_table" class="form-table">';
echo '<tr><th><label for="sabre_test_seq">' . __('Tests to perform:', 'sabre') . '</label></th><td><select size="1" name="sabre_test_seq" id="sabre_test_seq">';
echo '<option value="All" ' . $this->selected($sabre_seq, 'All') . ' >' . __('All', 'sabre') . '</option>';
echo '<option value="Random" ' . $this->selected($sabre_seq, 'Random') . ' >' . __('Randomly', 'sabre') . '</option>';
echo '</select></td><td>' . __('(How do we use the above tests?)', 'sabre') . '</td></tr>';
echo '</table>';
echo '<h3><a href="#">' . __("Stealth options", 'sabre') . '</a></h3>';
echo '<table id="stealth_table" class="form-table">';
echo '<tr><th><label for="sabre_enable_stealth">' . __('Enable stealth test:', 'sabre') . '</label></th><td><input type="checkbox" ' . $this->checked($enable_stealth, 'true') . ' name="sabre_enable_stealth" id="sabre_enable_stealth" value="true" /></td><td>' . __('(Turn silent control on/off)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_enable_js">' . __('Block if Javascript unsupported:', 'sabre') . '</label></th><td><input type="checkbox" ' . $this->checked($js_support, 'true') . ' name="sabre_enable_js" id="sabre_enable_js" value="true" /></td><td>' . __('(Consider that a lack of Javascript capabilities is a spambot\'s footprint)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_timeout">' . __('Session time out:', 'sabre') . '</label></th><td><input type="text" size="2" name="sabre_timeout" id="sabre_timeout" value="' . $session_timeout . '" /></td><td>' . __('(Max. time in seconds before session expires)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_speed">' . __('Speed limit:', 'sabre') . '</label></th><td><input type="text" size="2" name="sabre_speed" id="sabre_speed" value="' . $speed_limit . '" /></td><td>' . __('(Min. time in seconds to fill the registration form)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_banned_IP">' . __('Check DNS Blacklists:', 'sabre') . '</label></th><td><input type="checkbox" ' . $this->checked($check_banned_IP, 'true') . ' name="sabre_banned_IP" id="sabre_banned_IP" value="true" /></td><td>' . __('(Control if user IP address is blacklisted on DNSBL servers)', 'sabre') . '</td></tr>';
echo '</table>';
if (!is_multisite()) { // Use built-in confirmation in multisite mode
echo '<h3><a href="#">' . __("Confirmation options", 'sabre') . '</a></h3>';
echo '<table id="confirmation_table" class="form-table">';
echo '<tr><th><label for="sabre_enable_confirm">' . __('Enable confirmation:', 'sabre') . '</label></th><td><select size="1" name="sabre_enable_confirm" id="sabre_enable_confirm">';
echo '<option value="none" ' . $this->selected($enable_confirm, 'none') . ' >' . __('None', 'sabre') . '</option>';
echo '<option value="user" ' . $this->selected($enable_confirm, 'user') . ' >' . __('By user', 'sabre') . '</option>';
echo '<option value="admin" ' . $this->selected($enable_confirm, 'admin') . ' >' . __('By admin', 'sabre') . '</option>';
echo '</select></td><td>' . __('(Ask user or site\'s admin to confirm registration)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_confirm_period">' . __('Number of days:', 'sabre') . '</label></th><td><input type="text" size="2" name="sabre_confirm_period" id="sabre_confirm_period" value="' . (1 > (int)$period ? 3 : (int)$period) . '" /></td><td>' . __('(Period of time for the user to confirm his registration)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_no_entry">' . __('Deny early sign-in:', 'sabre') . '</label></th><td><input type="checkbox" ' . $this->checked($no_entry, 'true') . ' name="sabre_no_entry" id="sabre_no_entry" value="true" /></td><td>' . __("(Don't allow users to sign in before their confirmation)", 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_mail_confirm">' . __('Send mail when confirmed:', 'sabre') . '</label></th><td><input type="checkbox" ' . $this->checked($mail_confirm, 'true') . ' name="sabre_mail_confirm" id="sabre_mail_confirm" value="true" /></td><td>' . __("(Send a mail to the administrator upon user's confirmation)", 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_delete_user">' . __('Suppress unregistered users:', 'sabre') . '</label></th><td><input type="checkbox" ' . $this->checked($delete_user, 'true') . ' name="sabre_delete_user" id="sabre_delete_user" value="true" /></td><td>' . __("(Delete user account when registration is canceled)", 'sabre') . '</td></tr>';
echo '</table>';
}
echo '<h3><a href="#">' . __("Policy options", 'sabre') . '</a></h3>';
echo '<table id="policy_table" class="form-table">';
echo '<tr><th><label for="sabre_enable_policy">' . __('Enable policy agreement:', 'sabre') . '</label></th><td><input type="checkbox" ' . $this->checked($enable_policy, 'true') . ' name="sabre_enable_policy" id="sabre_enable_policy" value="true" /></td><td>' . __('(Ask for user\'s acceptance of site\'s policy)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_policy_name">' . __('Policy name:', 'sabre') . '</label></th><td><input type="text" size="20" name="sabre_policy_name" id="sabre_policy_name" value="' . stripslashes($policy_name) . '" /></td><td>' . __('(Name of agreement like Disclaimer, Licence agreement, General policy, etc...Will be shown on the registration form)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_policy_link">' . __('Policy link:', 'sabre') . '</label></th><td><input type="text" size="20" name="sabre_policy_link" id="sabre_policy_link" value="' . $policy_link . '" /></td><td>' . __('(URL of the policy text. If not blank, the name of the agreement above will turn into a link to that URL on the registration form. Can be a WordPress page or an external html file.)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_policy_text">' . __('Policy text:', 'sabre') . '</label></th><td><textarea rows="10" cols="40" name="sabre_policy_text" id="sabre_policy_text" >' . stripslashes($policy_text) . '</textarea></td><td>' . __('(Enter the text to be displayed on the registration form)', 'sabre') . '</td></tr>';
echo '</table>';
echo '<h3><a href="#">' . __("Invitation options", 'sabre') . '</a></h3>';
echo '<table id="invitation_table" class="form-table">';
echo '<tr><th><label for="sabre_enable_invite">' . __('Enable invitation:', 'sabre') . '</label></th><td><input type="checkbox" ' . $this->checked($enable_invite, 'true') . ' name="sabre_enable_invite" id="sabre_enable_invite" value="true" /></td><td>' . __('(User must provide an invitation code to register)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_invite_codes">' . __('Invitation codes:', 'sabre') . '</label></th><td><ul><li><input type="text" size="60" value="" class="unseen" disabled /></li><li><input type="text" size="15" name="text_invite_code" value="' . __('Code', 'sabre') . '" class="unseen" disabled /><input type="text" size="6" name="text_invite_number" value="' . __('Usage', 'sabre') . '" class="unseen" disabled /><input type="text" size="10" name="text_invite_date" value="' . __('Validity', 'sabre') . '" class="unseen" disabled /></li>' . $this->display_invite_codes() . '</ul></td><td>' . __('(List of valid invitation codes - Usage is the number of time the code can be used - Validity is the expiration date in YYYY-MM-DD format)', 'sabre') . '</td></tr>';
echo '</table>';
echo '<h3><a href="#">' . __("Miscellaneous options", 'sabre') . '</a></h3>';
echo '<table id="misc_table" class="form-table">';
if (!is_multisite()) { // Use built-in confirmation in multisite mode
echo '<tr><th><label for="sabre_user_pwd">' . __('User\'s password:', 'sabre') . '</label></th><td><input type="checkbox" ' . $this->checked($user_pwd, 'true') . ' name="sabre_user_pwd" id="sabre_user_pwd" value="true" /></td><td>' . __('(User can choose his own password during registration)', 'sabre') . '</td></tr>';
}
echo '<tr><th><label for="sabre_mail_from_name">' . __('Sender\'s name:', 'sabre') . '</label></th><td><input type="text" size="50" name="sabre_mail_from_name" id="sabre_mail_from_name" value="' . $mail_from_name . '" /></td><td>' . __('(Name used in mails sent by Sabre - Blog\'s name used if left blank)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_mail_from_mail">' . __('Sender\'s email:', 'sabre') . '</label></th><td><input type="text" size="50" name="sabre_mail_from_mail" id="sabre_mail_from_mail" value="' . $mail_from_mail . '" /></td><td>' . __('(Mail address in mails sent by Sabre - Administrator\'s mail used if left blank)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_show_banner">' . __('Show banner:', 'sabre') . '</label></th><td><input type="checkbox" ' . $this->checked($show_banner, 'true') . ' name="sabre_show_banner" id="sabre_show_banner" value="true" /></td><td>' . __('(Mention Sabre at the bottom of the registration form)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_show_dashboard">' . __('Show on dashboard:', 'sabre') . '</label></th><td><input type="checkbox" ' . $this->checked($show_dashboard, 'true') . ' name="sabre_show_dashboard" id="sabre_show_dashboard" value="true" /></td><td>' . __('(Include Sabre statistics on the dashboard)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_show_user">' . __('Show in profile:', 'sabre') . '</label></th><td><input type="checkbox" ' . $this->checked($show_user, 'true') . ' name="sabre_show_user" id="sabre_show_user" value="true" /></td><td>' . __('(Include Sabre informations in the user profile)', 'sabre') . '</td></tr>';
echo '<tr><th><label for="sabre_suppress_sabre">' . __('Suppress Sabre:', 'sabre') . '</label></th><td><input type="checkbox" ' . $this->checked($suppress_sabre, 'true') . ' name="sabre_suppress_sabre" id="sabre_suppress_sabre" value="true" /></td><td>' . __('(Delete all Sabre stuff when deactivating the plugin - Use with caution!)', 'sabre') . '</td></tr>';
echo '</table>';
echo '<h3><a href="#"></a></h3>';
echo '<table class="form-table">';
echo '</table>';
echo '</div>'; // End of id="sabre_opt_accordion"
echo '<p class="submit">';
echo '<input type="submit" name="sabre_option_save" value="'. __("Save options", 'sabre') . '" class="button" />';
echo '</p>';
echo '</form>';
echo '</div>';
break;
}
?>
|
cheems77/nb
|
wp-content/plugins/sabre/classes/sabre_class_admin.php
|
PHP
|
gpl-2.0
| 27,157
|
/* $Id$
*
* Lasso - A free implementation of the Liberty Alliance specifications.
*
* Copyright (C) 2004-2007 Entr'ouvert
* http://lasso.entrouvert.org
*
* Authors: See AUTHORS file in top-level directory.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#include "../private.h"
#include "samlp2_manage_name_id_response.h"
/**
* SECTION:samlp2_manage_name_id_response
* @short_description: <samlp2:ManageNameIDResponse>
*
* <figure><title>Schema fragment for samlp2:ManageNameIDResponse</title>
* <programlisting><![CDATA[
*
* <element name="ManageNameIDResponse" type="samlp:StatusResponseType"/>
* ]]></programlisting>
* </figure>
*/
/*****************************************************************************/
/* private methods */
/*****************************************************************************/
static struct XmlSnippet schema_snippets[] = {
{NULL, 0, 0, NULL, NULL, NULL}
};
/*****************************************************************************/
/* instance and class init functions */
/*****************************************************************************/
static void
class_init(LassoSamlp2ManageNameIDResponseClass *klass)
{
LassoNodeClass *nclass = LASSO_NODE_CLASS(klass);
nclass->node_data = g_new0(LassoNodeClassData, 1);
lasso_node_class_set_nodename(nclass, "ManageNameIDResponse");
lasso_node_class_set_ns(nclass, LASSO_SAML2_PROTOCOL_HREF, LASSO_SAML2_PROTOCOL_PREFIX);
lasso_node_class_add_snippets(nclass, schema_snippets);
}
GType
lasso_samlp2_manage_name_id_response_get_type()
{
static GType this_type = 0;
if (!this_type) {
static const GTypeInfo this_info = {
sizeof (LassoSamlp2ManageNameIDResponseClass),
NULL,
NULL,
(GClassInitFunc) class_init,
NULL,
NULL,
sizeof(LassoSamlp2ManageNameIDResponse),
0,
NULL,
NULL
};
this_type = g_type_register_static(LASSO_TYPE_SAMLP2_STATUS_RESPONSE,
"LassoSamlp2ManageNameIDResponse", &this_info, 0);
}
return this_type;
}
/**
* lasso_samlp2_manage_name_id_response_new:
*
* Creates a new #LassoSamlp2ManageNameIDResponse object.
*
* Return value: a newly created #LassoSamlp2ManageNameIDResponse object
**/
LassoNode*
lasso_samlp2_manage_name_id_response_new()
{
return g_object_new(LASSO_TYPE_SAMLP2_MANAGE_NAME_ID_RESPONSE, NULL);
}
|
adieu/lasso
|
lasso/xml/saml-2.0/samlp2_manage_name_id_response.c
|
C
|
gpl-2.0
| 3,026
|
/*
* linux/arch/arm/vfp/vfpmodule.c
*
* Copyright (C) 2004 ARM Limited.
* Written by Deep Blue Solutions Limited.
*
* 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/types.h>
#include <linux/cpu.h>
#include <linux/cpu_pm.h>
#include <linux/hardirq.h>
#include <linux/kernel.h>
#include <linux/notifier.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/smp.h>
#include <linux/init.h>
#include <linux/uaccess.h>
#include <linux/export.h>
#include <linux/user.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <asm/cp15.h>
#include <asm/cputype.h>
#include <asm/system_info.h>
#include <asm/thread_notify.h>
#include <asm/vfp.h>
#include "vfpinstr.h"
#include "vfp.h"
/*
* Our undef handlers (in entry.S)
*/
void vfp_testing_entry(void);
void vfp_support_entry(void);
void vfp_null_entry(void);
void (*vfp_vector)(void) = vfp_null_entry;
/*
* Dual-use variable.
* Used in startup: set to non-zero if VFP checks fail
* After startup, holds VFP architecture
*/
unsigned int VFP_arch;
/*
* The pointer to the vfpstate structure of the thread which currently
* owns the context held in the VFP hardware, or NULL if the hardware
* context is invalid.
*
* For UP, this is sufficient to tell which thread owns the VFP context.
* However, for SMP, we also need to check the CPU number stored in the
* saved state too to catch migrations.
*/
union vfp_state *vfp_current_hw_state[NR_CPUS];
/*
* Is 'thread's most up to date state stored in this CPUs hardware?
* Must be called from non-preemptible context.
*/
static bool vfp_state_in_hw(unsigned int cpu, struct thread_info *thread)
{
#ifdef CONFIG_SMP
if (thread->vfpstate.hard.cpu != cpu)
return false;
#endif
return vfp_current_hw_state[cpu] == &thread->vfpstate;
}
/*
* Force a reload of the VFP context from the thread structure. We do
* this by ensuring that access to the VFP hardware is disabled, and
* clear vfp_current_hw_state. Must be called from non-preemptible context.
*/
static void vfp_force_reload(unsigned int cpu, struct thread_info *thread)
{
if (vfp_state_in_hw(cpu, thread)) {
fmxr(FPEXC, fmrx(FPEXC) & ~FPEXC_EN);
vfp_current_hw_state[cpu] = NULL;
}
#ifdef CONFIG_SMP
thread->vfpstate.hard.cpu = NR_CPUS;
vfp_current_hw_state[cpu] = NULL;
#endif
}
/*
* Used for reporting emulation statistics via /proc
*/
static atomic64_t vfp_bounce_count = ATOMIC64_INIT(0);
/*
* Per-thread VFP initialization.
*/
static void vfp_thread_flush(struct thread_info *thread)
{
union vfp_state *vfp = &thread->vfpstate;
unsigned int cpu;
/*
* Disable VFP to ensure we initialize it first. We must ensure
* that the modification of vfp_current_hw_state[] and hardware
* disable are done for the same CPU and without preemption.
*
* Do this first to ensure that preemption won't overwrite our
* state saving should access to the VFP be enabled at this point.
*/
cpu = get_cpu();
if (vfp_current_hw_state[cpu] == vfp)
vfp_current_hw_state[cpu] = NULL;
fmxr(FPEXC, fmrx(FPEXC) & ~FPEXC_EN);
put_cpu();
memset(vfp, 0, sizeof(union vfp_state));
vfp->hard.fpexc = FPEXC_EN;
vfp->hard.fpscr = FPSCR_ROUND_NEAREST;
#ifdef CONFIG_SMP
vfp->hard.cpu = NR_CPUS;
#endif
}
static void vfp_thread_exit(struct thread_info *thread)
{
/* release case: Per-thread VFP cleanup. */
union vfp_state *vfp = &thread->vfpstate;
unsigned int cpu = get_cpu();
if (vfp_current_hw_state[cpu] == vfp)
vfp_current_hw_state[cpu] = NULL;
put_cpu();
}
static void vfp_thread_copy(struct thread_info *thread)
{
struct thread_info *parent = current_thread_info();
vfp_sync_hwstate(parent);
thread->vfpstate = parent->vfpstate;
#ifdef CONFIG_SMP
thread->vfpstate.hard.cpu = NR_CPUS;
#endif
}
/*
* When this function is called with the following 'cmd's, the following
* is true while this function is being run:
* THREAD_NOFTIFY_SWTICH:
* - the previously running thread will not be scheduled onto another CPU.
* - the next thread to be run (v) will not be running on another CPU.
* - thread->cpu is the local CPU number
* - not preemptible as we're called in the middle of a thread switch
* THREAD_NOTIFY_FLUSH:
* - the thread (v) will be running on the local CPU, so
* v === current_thread_info()
* - thread->cpu is the local CPU number at the time it is accessed,
* but may change at any time.
* - we could be preempted if tree preempt rcu is enabled, so
* it is unsafe to use thread->cpu.
* THREAD_NOTIFY_EXIT
* - the thread (v) will be running on the local CPU, so
* v === current_thread_info()
* - thread->cpu is the local CPU number at the time it is accessed,
* but may change at any time.
* - we could be preempted if tree preempt rcu is enabled, so
* it is unsafe to use thread->cpu.
*/
static int vfp_notifier(struct notifier_block *self, unsigned long cmd, void *v)
{
struct thread_info *thread = v;
u32 fpexc;
#ifdef CONFIG_SMP
unsigned int cpu;
#endif
switch (cmd) {
case THREAD_NOTIFY_SWITCH:
fpexc = fmrx(FPEXC);
#ifdef CONFIG_SMP
cpu = thread->cpu;
/*
* On SMP, if VFP is enabled, save the old state in
* case the thread migrates to a different CPU. The
* restoring is done lazily.
*/
if ((fpexc & FPEXC_EN) && vfp_current_hw_state[cpu])
vfp_save_state(vfp_current_hw_state[cpu], fpexc);
#endif
/*
* Always disable VFP so we can lazily save/restore the
* old state.
*/
fmxr(FPEXC, fpexc & ~FPEXC_EN);
break;
case THREAD_NOTIFY_FLUSH:
vfp_thread_flush(thread);
break;
case THREAD_NOTIFY_EXIT:
vfp_thread_exit(thread);
break;
case THREAD_NOTIFY_COPY:
vfp_thread_copy(thread);
break;
}
return NOTIFY_DONE;
}
static struct notifier_block vfp_notifier_block = {
.notifier_call = vfp_notifier,
};
/*
* Raise a SIGFPE for the current process.
* sicode describes the signal being raised.
*/
static void vfp_raise_sigfpe(unsigned int sicode, struct pt_regs *regs)
{
siginfo_t info;
memset(&info, 0, sizeof(info));
info.si_signo = SIGFPE;
info.si_code = sicode;
info.si_addr = (void __user *)(instruction_pointer(regs) - 4);
/*
* This is the same as NWFPE, because it's not clear what
* this is used for
*/
current->thread.error_code = 0;
current->thread.trap_no = 6;
send_sig_info(SIGFPE, &info, current);
}
static void vfp_panic(char *reason, u32 inst)
{
int i;
printk(KERN_ERR "VFP: Error: %s\n", reason);
printk(KERN_ERR "VFP: EXC 0x%08x SCR 0x%08x INST 0x%08x\n",
fmrx(FPEXC), fmrx(FPSCR), inst);
for (i = 0; i < 32; i += 2)
printk(KERN_ERR "VFP: s%2u: 0x%08x s%2u: 0x%08x\n",
i, vfp_get_float(i), i+1, vfp_get_float(i+1));
}
/*
* Process bitmask of exception conditions.
*/
static void vfp_raise_exceptions(u32 exceptions, u32 inst, u32 fpscr, struct pt_regs *regs)
{
int si_code = 0;
pr_debug("VFP: raising exceptions %08x\n", exceptions);
if (exceptions == VFP_EXCEPTION_ERROR) {
vfp_panic("unhandled bounce", inst);
vfp_raise_sigfpe(0, regs);
return;
}
/*
* If any of the status flags are set, update the FPSCR.
* Comparison instructions always return at least one of
* these flags set.
*/
if (exceptions & (FPSCR_N|FPSCR_Z|FPSCR_C|FPSCR_V))
fpscr &= ~(FPSCR_N|FPSCR_Z|FPSCR_C|FPSCR_V);
fpscr |= exceptions;
fmxr(FPSCR, fpscr);
#define RAISE(stat,en,sig) \
if (exceptions & stat && fpscr & en) \
si_code = sig;
/*
* These are arranged in priority order, least to highest.
*/
RAISE(FPSCR_DZC, FPSCR_DZE, FPE_FLTDIV);
RAISE(FPSCR_IXC, FPSCR_IXE, FPE_FLTRES);
RAISE(FPSCR_UFC, FPSCR_UFE, FPE_FLTUND);
RAISE(FPSCR_OFC, FPSCR_OFE, FPE_FLTOVF);
RAISE(FPSCR_IOC, FPSCR_IOE, FPE_FLTINV);
if (si_code)
vfp_raise_sigfpe(si_code, regs);
}
/*
* Emulate a VFP instruction.
*/
static u32 vfp_emulate_instruction(u32 inst, u32 fpscr, struct pt_regs *regs)
{
u32 exceptions = VFP_EXCEPTION_ERROR;
pr_debug("VFP: emulate: INST=0x%08x SCR=0x%08x\n", inst, fpscr);
if (INST_CPRTDO(inst)) {
if (!INST_CPRT(inst)) {
/*
* CPDO
*/
if (vfp_single(inst)) {
exceptions = vfp_single_cpdo(inst, fpscr);
} else {
exceptions = vfp_double_cpdo(inst, fpscr);
}
} else {
/*
* A CPRT instruction can not appear in FPINST2, nor
* can it cause an exception. Therefore, we do not
* have to emulate it.
*/
}
} else {
/*
* A CPDT instruction can not appear in FPINST2, nor can
* it cause an exception. Therefore, we do not have to
* emulate it.
*/
}
return exceptions & ~VFP_NAN_FLAG;
}
/*
* Package up a bounce condition.
*/
void VFP_bounce(u32 trigger, u32 fpexc, struct pt_regs *regs)
{
u32 fpscr, orig_fpscr, fpsid, exceptions;
pr_debug("VFP: bounce: trigger %08x fpexc %08x\n", trigger, fpexc);
atomic64_inc(&vfp_bounce_count);
/*
* At this point, FPEXC can have the following configuration:
*
* EX DEX IXE
* 0 1 x - synchronous exception
* 1 x 0 - asynchronous exception
* 1 x 1 - sychronous on VFP subarch 1 and asynchronous on later
* 0 0 1 - synchronous on VFP9 (non-standard subarch 1
* implementation), undefined otherwise
*
* Clear various bits and enable access to the VFP so we can
* handle the bounce.
*/
fmxr(FPEXC, fpexc & ~(FPEXC_EX|FPEXC_DEX|FPEXC_FP2V|FPEXC_VV|FPEXC_TRAP_MASK));
fpsid = fmrx(FPSID);
orig_fpscr = fpscr = fmrx(FPSCR);
/*
* Check for the special VFP subarch 1 and FPSCR.IXE bit case
*/
if ((fpsid & FPSID_ARCH_MASK) == (1 << FPSID_ARCH_BIT)
&& (fpscr & FPSCR_IXE)) {
/*
* Synchronous exception, emulate the trigger instruction
*/
goto emulate;
}
if (fpexc & FPEXC_EX) {
#ifndef CONFIG_CPU_FEROCEON
/*
* Asynchronous exception. The instruction is read from FPINST
* and the interrupted instruction has to be restarted.
*/
trigger = fmrx(FPINST);
regs->ARM_pc -= 4;
#endif
} else if (!(fpexc & FPEXC_DEX)) {
/*
* Illegal combination of bits. It can be caused by an
* unallocated VFP instruction but with FPSCR.IXE set and not
* on VFP subarch 1.
*/
vfp_raise_exceptions(VFP_EXCEPTION_ERROR, trigger, fpscr, regs);
goto exit;
}
/*
* Modify fpscr to indicate the number of iterations remaining.
* If FPEXC.EX is 0, FPEXC.DEX is 1 and the FPEXC.VV bit indicates
* whether FPEXC.VECITR or FPSCR.LEN is used.
*/
if (fpexc & (FPEXC_EX | FPEXC_VV)) {
u32 len;
len = fpexc + (1 << FPEXC_LENGTH_BIT);
fpscr &= ~FPSCR_LENGTH_MASK;
fpscr |= (len & FPEXC_LENGTH_MASK) << (FPSCR_LENGTH_BIT - FPEXC_LENGTH_BIT);
}
/*
* Handle the first FP instruction. We used to take note of the
* FPEXC bounce reason, but this appears to be unreliable.
* Emulate the bounced instruction instead.
*/
exceptions = vfp_emulate_instruction(trigger, fpscr, regs);
if (exceptions)
vfp_raise_exceptions(exceptions, trigger, orig_fpscr, regs);
/*
* If there isn't a second FP instruction, exit now. Note that
* the FPEXC.FP2V bit is valid only if FPEXC.EX is 1.
*/
if (fpexc ^ (FPEXC_EX | FPEXC_FP2V))
goto exit;
/*
* The barrier() here prevents fpinst2 being read
* before the condition above.
*/
barrier();
trigger = fmrx(FPINST2);
emulate:
exceptions = vfp_emulate_instruction(trigger, orig_fpscr, regs);
if (exceptions)
vfp_raise_exceptions(exceptions, trigger, orig_fpscr, regs);
exit:
preempt_enable();
}
static void vfp_enable(void *unused)
{
u32 access;
BUG_ON(preemptible());
access = get_copro_access();
/*
* Enable full access to VFP (cp10 and cp11)
*/
set_copro_access(access | CPACC_FULL(10) | CPACC_FULL(11));
}
#ifdef CONFIG_CPU_PM
int vfp_pm_suspend(void)
{
struct thread_info *ti = current_thread_info();
u32 fpexc = fmrx(FPEXC);
/* if vfp is on, then save state for resumption */
if (fpexc & FPEXC_EN) {
printk(KERN_DEBUG "%s: saving vfp state\n", __func__);
vfp_save_state(&ti->vfpstate, fpexc);
/* disable, just in case */
fmxr(FPEXC, fmrx(FPEXC) & ~FPEXC_EN);
} else if (vfp_current_hw_state[ti->cpu]) {
#ifndef CONFIG_SMP
fmxr(FPEXC, fpexc | FPEXC_EN);
vfp_save_state(vfp_current_hw_state[ti->cpu], fpexc);
fmxr(FPEXC, fpexc);
#endif
}
/* clear any information we had about last context state */
vfp_current_hw_state[ti->cpu] = NULL;
return 0;
}
void vfp_pm_resume(void)
{
/* ensure we have access to the vfp */
vfp_enable(NULL);
/* and disable it to ensure the next usage restores the state */
fmxr(FPEXC, fmrx(FPEXC) & ~FPEXC_EN);
}
static int vfp_cpu_pm_notifier(struct notifier_block *self, unsigned long cmd,
void *v)
{
switch (cmd) {
case CPU_PM_ENTER:
vfp_pm_suspend();
break;
case CPU_PM_ENTER_FAILED:
case CPU_PM_EXIT:
vfp_pm_resume();
break;
}
return NOTIFY_OK;
}
static struct notifier_block vfp_cpu_pm_notifier_block = {
.notifier_call = vfp_cpu_pm_notifier,
};
static void vfp_pm_init(void)
{
cpu_pm_register_notifier(&vfp_cpu_pm_notifier_block);
}
#else
static inline void vfp_pm_init(void) { }
#endif /* CONFIG_CPU_PM */
/*
* Ensure that the VFP state stored in 'thread->vfpstate' is up to date
* with the hardware state.
*/
void vfp_sync_hwstate(struct thread_info *thread)
{
unsigned int cpu = get_cpu();
if (vfp_state_in_hw(cpu, thread)) {
u32 fpexc = fmrx(FPEXC);
/*
* Save the last VFP state on this CPU.
*/
fmxr(FPEXC, fpexc | FPEXC_EN);
vfp_save_state(&thread->vfpstate, fpexc | FPEXC_EN);
fmxr(FPEXC, fpexc);
}
put_cpu();
}
/* Ensure that the thread reloads the hardware VFP state on the next use. */
void vfp_flush_hwstate(struct thread_info *thread)
{
unsigned int cpu = get_cpu();
vfp_force_reload(cpu, thread);
put_cpu();
}
/*
* Save the current VFP state into the provided structures and prepare
* for entry into a new function (signal handler).
*/
int vfp_preserve_user_clear_hwstate(struct user_vfp __user *ufp,
struct user_vfp_exc __user *ufp_exc)
{
struct thread_info *thread = current_thread_info();
struct vfp_hard_struct *hwstate = &thread->vfpstate.hard;
int err = 0;
/* Ensure that the saved hwstate is up-to-date. */
vfp_sync_hwstate(thread);
/*
* Copy the floating point registers. There can be unused
* registers see asm/hwcap.h for details.
*/
err |= __copy_to_user(&ufp->fpregs, &hwstate->fpregs,
sizeof(hwstate->fpregs));
/*
* Copy the status and control register.
*/
__put_user_error(hwstate->fpscr, &ufp->fpscr, err);
/*
* Copy the exception registers.
*/
__put_user_error(hwstate->fpexc, &ufp_exc->fpexc, err);
__put_user_error(hwstate->fpinst, &ufp_exc->fpinst, err);
__put_user_error(hwstate->fpinst2, &ufp_exc->fpinst2, err);
if (err)
return -EFAULT;
/* Ensure that VFP is disabled. */
vfp_flush_hwstate(thread);
/*
* As per the PCS, clear the length and stride bits for function
* entry.
*/
hwstate->fpscr &= ~(FPSCR_LENGTH_MASK | FPSCR_STRIDE_MASK);
return 0;
}
/* Sanitise and restore the current VFP state from the provided structures. */
int vfp_restore_user_hwstate(struct user_vfp __user *ufp,
struct user_vfp_exc __user *ufp_exc)
{
struct thread_info *thread = current_thread_info();
struct vfp_hard_struct *hwstate = &thread->vfpstate.hard;
unsigned long fpexc;
int err = 0;
/* Disable VFP to avoid corrupting the new thread state. */
vfp_flush_hwstate(thread);
/*
* Copy the floating point registers. There can be unused
* registers see asm/hwcap.h for details.
*/
err |= __copy_from_user(&hwstate->fpregs, &ufp->fpregs,
sizeof(hwstate->fpregs));
/*
* Copy the status and control register.
*/
__get_user_error(hwstate->fpscr, &ufp->fpscr, err);
/*
* Sanitise and restore the exception registers.
*/
__get_user_error(fpexc, &ufp_exc->fpexc, err);
/* Ensure the VFP is enabled. */
fpexc |= FPEXC_EN;
/* Ensure FPINST2 is invalid and the exception flag is cleared. */
fpexc &= ~(FPEXC_EX | FPEXC_FP2V);
hwstate->fpexc = fpexc;
__get_user_error(hwstate->fpinst, &ufp_exc->fpinst, err);
__get_user_error(hwstate->fpinst2, &ufp_exc->fpinst2, err);
return err ? -EFAULT : 0;
}
void vfp_kmode_exception(void)
{
/*
* If we reach this point, a floating point exception has been raised
* while running in kernel mode. If the NEON/VFP unit was enabled at the
* time, it means a VFP instruction has been issued that requires
* software assistance to complete, something which is not currently
* supported in kernel mode.
* If the NEON/VFP unit was disabled, and the location pointed to below
* is properly preceded by a call to kernel_neon_begin(), something has
* caused the task to be scheduled out and back in again. In this case,
* rebuilding and running with CONFIG_DEBUG_ATOMIC_SLEEP enabled should
* be helpful in localizing the problem.
*/
if (fmrx(FPEXC) & FPEXC_EN)
pr_crit("BUG: unsupported FP instruction in kernel mode\n");
else
pr_crit("BUG: FP instruction issued in kernel mode with FP unit disabled\n");
}
/*
* VFP hardware can lose all context when a CPU goes offline.
* As we will be running in SMP mode with CPU hotplug, we will save the
* hardware state at every thread switch. We clear our held state when
* a CPU has been killed, indicating that the VFP hardware doesn't contain
* a threads VFP state. When a CPU starts up, we re-enable access to the
* VFP hardware.
*
* Both CPU_DYING and CPU_STARTING are called on the CPU which
* is being offlined/onlined.
*/
static int vfp_hotplug(struct notifier_block *b, unsigned long action,
void *hcpu)
{
if (action == CPU_DYING || action == CPU_DYING_FROZEN) {
vfp_force_reload((long)hcpu, current_thread_info());
} else if (action == CPU_STARTING || action == CPU_STARTING_FROZEN)
vfp_enable(NULL);
return NOTIFY_OK;
}
#ifdef CONFIG_PROC_FS
static int vfp_bounce_show(struct seq_file *m, void *v)
{
seq_printf(m, "%llu\n", atomic64_read(&vfp_bounce_count));
return 0;
}
static int vfp_bounce_open(struct inode *inode, struct file *file)
{
return single_open(file, vfp_bounce_show, NULL);
}
static const struct file_operations vfp_bounce_fops = {
.open = vfp_bounce_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
#endif
#ifdef CONFIG_KERNEL_MODE_NEON
/*
* Kernel-side NEON support functions
*/
void kernel_neon_begin(void)
{
struct thread_info *thread = current_thread_info();
unsigned int cpu;
u32 fpexc;
/*
* Kernel mode NEON is only allowed outside of interrupt context
* with preemption disabled. This will make sure that the kernel
* mode NEON register contents never need to be preserved.
*/
BUG_ON(in_interrupt());
cpu = get_cpu();
fpexc = fmrx(FPEXC) | FPEXC_EN;
fmxr(FPEXC, fpexc);
/*
* Save the userland NEON/VFP state. Under UP,
* the owner could be a task other than 'current'
*/
if (vfp_state_in_hw(cpu, thread))
vfp_save_state(&thread->vfpstate, fpexc);
#ifndef CONFIG_SMP
else if (vfp_current_hw_state[cpu] != NULL)
vfp_save_state(vfp_current_hw_state[cpu], fpexc);
#endif
vfp_current_hw_state[cpu] = NULL;
}
EXPORT_SYMBOL(kernel_neon_begin);
void kernel_neon_end(void)
{
/* Disable the NEON/VFP unit. */
fmxr(FPEXC, fmrx(FPEXC) & ~FPEXC_EN);
put_cpu();
}
EXPORT_SYMBOL(kernel_neon_end);
#endif /* CONFIG_KERNEL_MODE_NEON */
/*
* VFP support code initialisation.
*/
static int __init vfp_init(void)
{
unsigned int vfpsid;
unsigned int cpu_arch = cpu_architecture();
if (cpu_arch >= CPU_ARCH_ARMv6)
on_each_cpu(vfp_enable, NULL, 1);
/*
* First check that there is a VFP that we can use.
* The handler is already setup to just log calls, so
* we just need to read the VFPSID register.
*/
vfp_vector = vfp_testing_entry;
barrier();
vfpsid = fmrx(FPSID);
barrier();
vfp_vector = vfp_null_entry;
printk(KERN_INFO "VFP support v0.3: ");
if (VFP_arch)
printk("not present\n");
else if (vfpsid & FPSID_NODOUBLE) {
printk("no double precision support\n");
} else {
hotcpu_notifier(vfp_hotplug, 0);
VFP_arch = (vfpsid & FPSID_ARCH_MASK) >> FPSID_ARCH_BIT; /* Extract the architecture version */
printk("implementor %02x architecture %d part %02x variant %x rev %x\n",
(vfpsid & FPSID_IMPLEMENTER_MASK) >> FPSID_IMPLEMENTER_BIT,
(vfpsid & FPSID_ARCH_MASK) >> FPSID_ARCH_BIT,
(vfpsid & FPSID_PART_MASK) >> FPSID_PART_BIT,
(vfpsid & FPSID_VARIANT_MASK) >> FPSID_VARIANT_BIT,
(vfpsid & FPSID_REV_MASK) >> FPSID_REV_BIT);
vfp_vector = vfp_support_entry;
thread_register_notifier(&vfp_notifier_block);
vfp_pm_init();
/*
* We detected VFP, and the support code is
* in place; report VFP support to userspace.
*/
elf_hwcap |= HWCAP_VFP;
#ifdef CONFIG_VFPv3
if (VFP_arch >= 2) {
elf_hwcap |= HWCAP_VFPv3;
/*
* Check for VFPv3 D16. CPUs in this configuration
* only have 16 x 64bit registers.
*/
if (((fmrx(MVFR0) & MVFR0_A_SIMD_MASK)) == 1)
elf_hwcap |= HWCAP_VFPv3D16;
}
#endif
/*
* Check for the presence of the Advanced SIMD
* load/store instructions, integer and single
* precision floating point operations. Only check
* for NEON if the hardware has the MVFR registers.
*/
if ((read_cpuid_id() & 0x000f0000) == 0x000f0000) {
#ifdef CONFIG_NEON
if ((fmrx(MVFR1) & 0x000fff00) == 0x00011100)
elf_hwcap |= HWCAP_NEON;
#endif
if ((fmrx(MVFR1) & 0xf0000000) == 0x10000000 ||
(read_cpuid_id() & 0xff00fc00) == 0x51000400)
elf_hwcap |= HWCAP_VFPv4;
}
}
return 0;
}
static int __init vfp_rootfs_init(void)
{
#ifdef CONFIG_PROC_FS
static struct proc_dir_entry *procfs_entry;
procfs_entry = proc_create("cpu/vfp_bounce", S_IRUGO, NULL,
&vfp_bounce_fops);
if (!procfs_entry)
pr_err("Failed to create procfs node for VFP bounce reporting\n");
#endif
return 0;
}
core_initcall(vfp_init);
rootfs_initcall(vfp_rootfs_init);
|
Dm47021/android_kernel_afyonlte
|
arch/arm/vfp/vfpmodule.c
|
C
|
gpl-2.0
| 21,884
|
<?php
//require_once(BASE_PATH . 'settings/IOnyxCreds.php');
/*
*
* DBConnect class for use with the Brafton Update API for plugins and modules
*
*/
class MySQLDBConnect implements IOnyxConnection{
//private $host;
//private $user;
//private $pass;
private $db;
protected $connection;
static $instance = null;
private $errorDisplay = true;
//constuct the db connection
public function __construct($args){
//$this->host = $args[0];
//$this->user = $args[1];
//$this->pass = $args[2];
$this->db = $args[3];
$this->connection = $this->hook($args);
}
static function GetInstance($args){
if(self::$instance == null){
self::$instance = new self($args);
}
return self::$instance;
}
//make the database connection
private function hook($args){
$host = $args[0];
$user = $args[1];
$pass = $args[2];
$db = $args[3];
$hook = mysqli_connect($host, $user, $pass, $db);
if(!$hook){
die('Error Connecting to the Database'.mysqli_connect_errno().PHP_EOL);
}
return $hook;
}
public function idle_query($sql){
$result = $this->connection->query($sql);
//echo mysqli_errno($this->connection);
return $result;
}
public function customQuery($sql){
$result = $this->connection->query($sql);
return $result;
}
//data retrieval statment $conditions must be an array of conditions.
/* $conditons format
* array("WHERE/ORDER BY ECT" => array("condtion", "condition", ect)
*
*/
public function retrieveData($table, $data, $conditions = NULL){
$table = strtolower($table);
$statement = '';
$array = array();
if($conditions){
if(!is_array($conditions)){
echo 'DBConnect Error: Your statement is malformed--> for retrieveData($table,$data,$conditions)';
exit;
}
foreach($conditions as $condition => $vals){
$statement .= $condition;
$i = 0;
foreach($vals as $key => $value){
if($i>0){ $statement .= " AND ";}
$statement .= ' '.$value;
$i++;
}
}
}
$sql = "SELECT $data FROM `$table` $statement";
//echo $sql;
$result = $this->connection->query($sql);
if(!$result){ return $result; }
while($addto = mysqli_fetch_assoc($result)){
$array[] = $addto;
}
return $array;
}
//updateData statement $conditions must be an array
public function updateData($table, $data, $conditions=NULL){
$table = strtolower($table);
if(!is_array($data)){
echo 'DBConnect Error: Your statement is malformed--> for updateData($table, $data, $conditions)';
exit;
}
if(!$conditions){
echo 'DBConnect Error: Your statement is malformed--> for updateData($table, $data, $conditions)';
exit;
}
$statement = '';
$i=0;
foreach($data as $key => $val){
$val = $this->connection->real_escape_string($val);
if($i>0){ $statement .= ','; }
$statement .= " $key = '$val'";
++$i;
}
foreach($conditions as $condition => $vals){
$statement .= ' '.$condition;
$i = 0;
foreach($vals as $key => $value){
if($i>0){ $statement .= " AND ";}
$statement .= ' '.$value;
$i++;
}
}
$sql = "UPDATE $table set $statement ";
//echo $sql;
$result = $this->connection->query($sql);
//echo mysqli_errno($this->connection);
return $result;
}
//insert statement
public function insertData($table, $data){
$table = strtolower($table);
if(!is_array($data)){
echo 'DBConnect Error: Your statement is malformed--> for insertData($table, $data)';
}
$statement = '';
$i=0;
foreach($data as $key => $val){
$val = $this->connection->real_escape_string($val);
if($i>0){ $statement .= ','; }
$statement .= " $key = '$val'";
++$i;
}
$sql = "INSERT INTO `$table` set $statement";
echo $sql;
$result = $this->connection->query($sql);
//echo mysqli_errno($this->connection);
return $result;
}
//delete data $conditions must be an array
public function deleteData($table, $data, $condition = null){
}
//create table $fields must be array
/*Standard fields are Vid, version, description, name, requires, tested, last_updated, download_link, code_name, features, {array $fields list of required fields for use with the prorietry cms update system}
public function createTable($table, $fields = NULL){
if(!is_array($fields)){
echo 'DBConnect Error: Your statement is malformed--> for createTable($table, $fields)';
return;
}
}
*/
public function schema_connection($table){
$result = $this->connection->query("SELECT * FROM $table LIMIT 0");
return $result->fetch_fields();
}
public function mysqli_error(){
return $this->connection->error;
}
public function describe($table){
return $this->connection->query("DESCRIBE `$table`");
}
public function connection_method($method){
return $this->connection->$method;
}
public function getDBName(){
return $this->db;
}
public function getDB(){
}
public function getUser(){
}
public function createTable($table, $columns, $key){
$message = '';
if(!$this->tableDetails($table)){
$query = " CREATE TABLE IF NOT EXISTS `$table` ( ";
foreach($columns as $column){
$query .= "$column->column_name $column->type $column->default , ";
}
$query .= "PRIMARY KEY ( `{$key}` ) )";
$result = $this->customQuery($query);
if($result){
$message .= '<pre class="datastructure warning">';
$message .= "DataStructure has changed: ADDED '{$table}' Table to Database<br/> ";
$message .= '</pre>';
}else if($this->errorDisplay){
$message .= '<pre class="datastructure error">';
$message .= "DataStructure has changed: There was an error applying your DataStructure change to your database<br/>". $this->connection->mysqli_error();
$message .= '</pre>';
}
return $message;
}
}
public function tableDetails($table){
return $this->connection->query("DESCRIBE `$table`");
}
public function columnInfo($table, $column_name){
$results = $this->customQuery("SELECT *
FROM information_schema.COLUMNS
WHERE
TABLE_SCHEMA = '$this->db'
AND TABLE_NAME = '$>table'
AND COLUMN_NAME = '$column_name'");
return $results;
}
public function addNewColumn($table, $columns, $column){
$pos = ($pos = OnyxUtilities::objArraySearch($columns, 'column_name', $column->column_name)) ? $pos : 0 ;
$after = $pos ? ' AFTER '.$columns[$pos -1]->column_name : ' FIRST';
$result = $this->customQuery("ALTER TABLE $table ADD $column->column_name $column->type $column->default ". $after);
return $result;
}
}
//$con = new DBConnect();
?>
|
dking3876/onyx-framework
|
onyx/setting/database/MySQLDBConnect.php
|
PHP
|
gpl-2.0
| 7,775
|
<?php
/** Esecouristes - Janvier 2013
Vanessa Kovalsky vanessa.kovalsky@free.fr
Licence GNU/GPL V3
Ajout / Modification d'une prestation
**/
include_once ("config.php");
check_all(0);
writehead();
$mysection=$_SESSION['SES_SECTION'];
get_session_parameters();
// On choisit la section concernée
if (isset ($_POST["section"])) {
$_SESSION['sectionchoice'] = intval($_POST["section"]);
$section=intval($_POST["section"]);
}
else if ( isset($_SESSION['sectionchoice']) ) {
$section=$_SESSION['sectionchoice'];
}
else {$section=$mysection;}
require 'lib/autoload.inc.php';
$db = DBFactory::getMysqlConnexionWithPDO();
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); // On émet une alerte à chaque fois qu'une requête a échoué
$manager = new PrestationManager($db);
//echo $_GET['presta_id'];
if (isset ($_GET['presta_id'])) {
$id_presta = $_GET['presta_id'];
//echo "l'id de la presta".$id_presta;
$presta = $manager->get($id_presta);
}
else // Si on a voulu enregistrer une prestation
{
$presta = new Prestation(array('libelle' => $_POST['libelle'], 'prix' => $_POST['prix'], 'section' => $section, 'id_prestation_parent' => NULL)); // On crée une nouvelle prestation
}
//print_r($presta);
// On traite le formulaire
if (isset($_POST['libelle']))
{
//echo $section;
//print_r($presta);
//echo $presta->prix();
if (isset($_POST['id_prestation'])) {
if ($section == $presta->section_id()) {
$presta_id = $_POST['id_prestation'];
$presta->setId_prestation($presta_id);
$presta->setId_prestation_parent($presta_id);
}
else {
$presta_id = $_POST['id_prestation'];
$presta->setId_prestation_parent($presta_id);
}
}
$presta->setSection_id($section);
//echo 'id ajoute';
//print_r($presta);
if (!$presta->libelleValide())
{
$message = 'Le libellé choisi est invalide.';
unset($presta);
}
else
{
$manager->savePrestation($presta);
$message = $presta->isNew() ? "La prestation a bien été ajoutée !" : "La prestation a bien été modifiée !";
}
}
?>
<!-- On affiche le formulaire -->
<h2>Ajout ou modification d'une prestation</h2>
<?php
if (isset($message)) {// On a un message à afficher ?
$message_propre = htmlentities($message);
echo '<p>', $message_propre, '</p>';// Si oui, on l'affiche
}
?>
<div id="form-prestation">
<form action="upd_prestation.php" method="post">
<fieldset class="bleu-clair">
<legend class="TabHeader">Information sur le type de prestation</legend>
<p>
<label>Libellé :</label>
<input type="text" name="libelle" maxlength="50" value="<?php if (isset($presta)) echo $presta->libelle(); ?>" />
</p>
<p>
<label>Prix :</label>
<input type="text" name="prix" maxlength="10" value="<?php if (isset($presta)) echo $presta->prix(); ?>" />
</p>
</fieldset>
<?php
if(isset($presta) && !$presta->isNew())
{
?>
<input type="hidden" name="id_prestation" value="<?php echo $presta->id_prestation(); ?>" />
<input type="submit" value="Enregistrer cette prestation" name="modifier" class="submit" />
<?php
}
else
{
?>
<input type="submit" value="Ajouter" class="submit" />
<?php
}
?>
</form>
</div>
|
vanessakovalsky/esecouristes
|
upd_prestation.php
|
PHP
|
gpl-2.0
| 3,378
|
# module includes
import elliptic
import heat
import IRT
print "Loading comatmor version 0.0.1"
|
fameyer/comatmor
|
src/comatmor/__init__.py
|
Python
|
gpl-2.0
| 96
|
// *************************************************************************
//
// Copyright 2004-2010 Bruno PAGES .
//
// This file is part of the BOUML Uml Toolkit.
//
// 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.
//
// e-mail : bouml@free.fr
// home : http://bouml.free.fr
//
// *************************************************************************
#include <qcursor.h>
#include <qgrid.h>
#include <qvbox.h>
#include <qlabel.h>
#include <qpopupmenu.h>
#include <qpushbutton.h>
#include <qfiledialog.h>
#include <qcombobox.h>
#include <qcheckbox.h>
#include <qradiobutton.h>
#include <qbuttongroup.h>
#include <qsplitter.h>
#include <qspinbox.h>
#include "GenerationSettingsDialog.h"
#include "BrowserView.h"
#include "MLinesItem.h"
#include "DialogUtil.h"
#include "UmlPixmap.h"
#include "UmlDesktop.h"
#include "strutil.h"
#include "translate.h"
QSize GenerationSettingsDialog::previous_size;
GenerationSettingsDialog::GenerationSettingsDialog()
: QTabDialog(0, "Generation Settings dialog", TRUE, 0) {
setCaption(TR("Generation settings dialog"));
setOkButton(TR("OK"));
setCancelButton(TR("Cancel"));
init_types();
init_stereotypes();
init_cpp1();
init_cpp2();
init_cpp3();
init_cpp4();
init_cpp5();
init_java1();
init_java2();
init_java3();
init_java4();
init_php1();
init_php2();
init_python1();
init_python2();
init_python3();
init_idl1();
init_idl2();
init_idl3();
init_idl4();
init_idl5();
init_descriptions();
init_dirs();
}
void GenerationSettingsDialog::polish() {
QTabDialog::polish();
UmlDesktop::setsize_center(this, previous_size, 29.0/30, 19.0/29);
}
GenerationSettingsDialog::~GenerationSettingsDialog() {
previous_size = size();
}
void GenerationSettingsDialog::init_types() {
QGrid * grid = new QGrid(1, this);
grid->setMargin(3);
grid->setSpacing(3);
new QLabel(TR("Types correspondence, and C++ operation argument default passing for them :"), grid);
types_table = new TypesTable(grid);
addTab(grid, TR("Types"));
}
void GenerationSettingsDialog::init_stereotypes() {
QGrid * grid = new QGrid(2, this);
grid->setMargin(3);
grid->setSpacing(3);
new QLabel(TR("Attributes and \nRelations\nstereotypes \ncorrespondence : "), grid);
relation_stereotypes_table =
new StereotypesTable(grid, GenerationSettings::nrelattrstereotypes,
GenerationSettings::relattr_stereotypes, FALSE);
//new QLabel(grid);
//new QLabel(grid);
new QLabel(TR("Classes's \nstereotypes \ncorrespondence : "), grid);
class_stereotypes_table =
new StereotypesTable(grid, GenerationSettings::nclassstereotypes,
GenerationSettings::class_stereotypes, TRUE);
addTab(grid, TR("Stereotypes"));
}
static void init_indent(QComboBox * cb, const char * v)
{
cb->insertItem(TR("empty"));
cb->insertItem(TR("1 space"));
QCString f = "%1 spaces";
QCString s = "2";
for (char c = '2'; c != '9'; c += 1) {
s[0] = c;
cb->insertItem(TR(f, s));
}
cb->insertItem(TR("1 tab"));
if (*v == '\t')
cb->setCurrentItem(9);
else {
int n = strlen(v);
cb->setCurrentItem((n > 8) ? 8 : n);
}
}
void GenerationSettingsDialog::init_cpp1() {
QVBox * vtab = new QVBox(this);
QGrid * grid = new QGrid(2, vtab);
grid->setMargin(3);
grid->setSpacing(3);
new QLabel(TR("Header file\ndefault content :"), grid);
edcpp_h_content = new MultiLineEdit(grid);
edcpp_h_content->setText(GenerationSettings::cpp_h_content);
QFont font = edcpp_h_content->font();
if (! hasCodec())
font.setFamily("Courier");
font.setFixedPitch(TRUE);
edcpp_h_content->setFont(font);
new QLabel(TR("Source file\ndefault content :"), grid);
edcpp_src_content = new MultiLineEdit(grid);
edcpp_src_content->setText(GenerationSettings::cpp_src_content);
edcpp_src_content->setFont(font);
new QLabel(vtab);
QHBox * htab = new QHBox(vtab);
htab->setMargin(3);
htab->setStretchFactor(new QLabel(TR("generated/reversed \nheader file extension : "), htab), 0);
edcpp_h_extension = new QComboBox(TRUE, htab);
htab->setStretchFactor(edcpp_h_extension, 100);
edcpp_h_extension->insertItem(GenerationSettings::cpp_h_extension);
edcpp_h_extension->setCurrentItem(0);
edcpp_h_extension->insertItem("h");
edcpp_h_extension->insertItem("hh");
htab->setStretchFactor(new QLabel(TR(" generated/reversed \n source file extension : "), htab), 0);
edcpp_src_extension = new QComboBox(TRUE, htab);
htab->setStretchFactor(edcpp_src_extension, 100);
edcpp_src_extension->insertItem(GenerationSettings::cpp_src_extension);
edcpp_src_extension->setCurrentItem(0);
edcpp_src_extension->insertItem("cpp");
edcpp_src_extension->insertItem("cc");
htab->setStretchFactor(new QLabel(" #include : ", htab), 0);
cpp_include_with_path_cb = new QComboBox(FALSE, htab);
cpp_include_with_path_cb->insertItem(TR("without path"));
cpp_include_with_path_cb->insertItem(TR("with absolute path"));
cpp_include_with_path_cb->insertItem(TR("with relative path"));
cpp_include_with_path_cb->insertItem(TR("with root relative path"));
if (!GenerationSettings::cpp_include_with_path)
cpp_include_with_path_cb->setCurrentItem(0);
else if (GenerationSettings::cpp_relative_path)
cpp_include_with_path_cb->setCurrentItem(2);
else if (GenerationSettings::cpp_root_relative_path)
cpp_include_with_path_cb->setCurrentItem(3);
else
cpp_include_with_path_cb->setCurrentItem(1);
htab = new QHBox(vtab);
htab->setMargin(3);
htab->setStretchFactor(new QLabel(TR("force namespace \nprefix generation : "), htab), 0);
cpp_force_namespace_gen_cb = new QCheckBox(htab);
cpp_force_namespace_gen_cb->setChecked(GenerationSettings::cpp_force_namespace_gen);
htab->setStretchFactor(new QLabel(TR(" inline operation force \n includes in header : "), htab), 0);
cpp_inline_force_incl_in_h_cb = new QCheckBox(htab);
cpp_inline_force_incl_in_h_cb->setChecked(GenerationSettings::cpp_inline_force_incl_in_h);
htab->setStretchFactor(new QLabel(TR(" generate Javadoc \n style comment : "), htab), 0);
cpp_javadoc_cb = new QCheckBox(htab);
cpp_javadoc_cb->setChecked(GenerationSettings::cpp_javadoc_comment);
htab->setStretchFactor(new QLabel(TR(" visibility indent : "), htab), 0);
indentvisi_cb = new QComboBox(FALSE, htab);
init_indent(indentvisi_cb, GenerationSettings::cpp_indent_visibility);
htab->setStretchFactor(new QLabel(htab), 1000);
addTab(vtab, "C++[1]");
if (!GenerationSettings::cpp_get_default_defs())
removePage(vtab);
}
void GenerationSettingsDialog::init_cpp2() {
QGrid * grid = new QGrid(2, this);
grid->setMargin(3);
grid->setSpacing(3);
new QLabel(TR("Class default \ndeclaration :"), grid);
edcpp_class_decl = new MultiLineEdit(grid);
edcpp_class_decl->setText(GenerationSettings::cpp_class_decl);
QFont font = edcpp_class_decl->font();
if (! hasCodec())
font.setFamily("Courier");
font.setFixedPitch(TRUE);
edcpp_class_decl->setFont(font);
new QLabel(TR("Struct default \ndeclaration :"), grid);
edcpp_struct_decl = new MultiLineEdit(grid);
edcpp_struct_decl->setText(GenerationSettings::cpp_struct_decl);
edcpp_struct_decl->setFont(font);
new QLabel(TR("Union default \ndeclaration :"), grid);
edcpp_union_decl = new MultiLineEdit(grid);
edcpp_union_decl->setText(GenerationSettings::cpp_union_decl);
edcpp_union_decl->setFont(font);
new QLabel(TR("Enum default \ndeclaration :"), grid);
edcpp_enum_decl = new MultiLineEdit(grid);
edcpp_enum_decl->setText(GenerationSettings::cpp_enum_decl);
edcpp_enum_decl->setFont(font);
new QLabel(TR("Typedef default \ndeclaration :"), grid);
edcpp_typedef_decl = new MultiLineEdit(grid);
edcpp_typedef_decl->setText(GenerationSettings::cpp_typedef_decl);
edcpp_typedef_decl->setFont(font);
addTab(grid, "C++[2]");
if (!GenerationSettings::cpp_get_default_defs())
removePage(grid);
}
void GenerationSettingsDialog::init_cpp3() {
QGrid * grid = new QGrid(2, this);
QGrid * grid2;
QHBox * htab;
grid->setMargin(3);
grid->setSpacing(3);
new QLabel(TR("Attribute \ndefault \ndeclaration :"), grid);
grid2 = new QGrid(2, grid);
(new QLabel(TR("Multiplicity"), grid2))->setAlignment(Qt::AlignCenter);
new QLabel(grid2);
new QLabel(TR("unspecified,\nor 1"), grid2);
edcpp_attr_decl[0] = new MultiLineEdit(grid2);
new QLabel(TR("* or a..b"), grid2);
edcpp_attr_decl[1] = new MultiLineEdit(grid2);
new QLabel(TR("X (means [X])\nor [...]...[...]"), grid2);
edcpp_attr_decl[2] = new MultiLineEdit(grid2);
QFont font = edcpp_attr_decl[0]->font();
int i, j;
if (! hasCodec())
font.setFamily("Courier");
font.setFixedPitch(TRUE);
for (i = 0; i != 3; i += 1) {
edcpp_attr_decl[i]->setText(GenerationSettings::cpp_attr_decl[i]);
edcpp_attr_decl[i]->setFont(font);
}
new QLabel(grid);
new QLabel(grid);
new QLabel(TR("Association\nand\naggregation\ndefault\ndeclaration :"), grid);
grid2 = new QGrid(2, grid);
(new QLabel(TR("Multiplicity"), grid2))->setAlignment(Qt::AlignCenter);
htab = new QHBox(grid2);
htab->setStretchFactor(new QLabel(htab), 1000);
(new QLabel(TR("Association "), htab))->setAlignment(Qt::AlignCenter);
(new QLabel(htab))->setPixmap(*associationButton);
(new QLabel(TR(" and aggregation "), htab))->setAlignment(Qt::AlignCenter);
(new QLabel(htab))->setPixmap(*aggregationButton);
htab->setStretchFactor(new QLabel(htab), 1000);
new QLabel(TR("unspecified,\n1 or 0..1"), grid2);
edcpp_rel_decl[0][0] = new MultiLineEdit(grid2);
new QLabel(TR("* or a..b"), grid2);
edcpp_rel_decl[0][1] = new MultiLineEdit(grid2);
new QLabel(TR("X (means [X])\nor [...]...[...]"), grid2);
edcpp_rel_decl[0][2] = new MultiLineEdit(grid2);
new QLabel(grid);
new QLabel(grid);
new QLabel(TR("Composition\ndefault\ndeclaration :"), grid);
grid2 = new QGrid(2, grid);
(new QLabel(TR("Multiplicity"), grid2))->setAlignment(Qt::AlignCenter);
htab = new QHBox(grid2);
htab->setStretchFactor(new QLabel(htab), 1000);
(new QLabel(TR("Composition "), htab))->setAlignment(Qt::AlignCenter);
(new QLabel(htab))->setPixmap(*aggregationByValueButton);
htab->setStretchFactor(new QLabel(htab), 1000);
new QLabel(TR("unspecified\nor 1"), grid2);
edcpp_rel_decl[1][0] = new MultiLineEdit(grid2);
new QLabel(TR("* or a..b"), grid2);
edcpp_rel_decl[1][1] = new MultiLineEdit(grid2);
new QLabel(TR("X (means [X])\nor [...]...[...]"), grid2);
edcpp_rel_decl[1][2] = new MultiLineEdit(grid2);
for (i = 0; i != 2; i += 1) {
for (j = 0; j != 3; j += 1) {
edcpp_rel_decl[i][j]->setText(GenerationSettings::cpp_rel_decl[i][j]);
edcpp_rel_decl[i][j]->setFont(font);
}
}
addTab(grid, "C++[3]");
if (!GenerationSettings::cpp_get_default_defs())
removePage(grid);
}
void GenerationSettingsDialog::init_cpp4() {
QGrid * grid = new QGrid(2, this);
QVBox * vtab;
QHBox * htab;
QButtonGroup * bg;
grid->setMargin(3);
grid->setSpacing(3);
new QLabel(TR("Get operation\ndefault definition : "), grid);
vtab = new QVBox(grid);
htab = new QHBox(vtab);
cpp_get_visibility.init(htab, GenerationSettings::cpp_get_visibility,
FALSE, TR("Visibility"));
bg = new QButtonGroup(3, Qt::Horizontal, TR("Modifiers"), htab);
bg->setExclusive(FALSE);
cpp_get_inline_cb = new QCheckBox("inline", bg);
cpp_get_value_const_cb = new QCheckBox(TR("const value"), bg);
cpp_get_const_cb = new QCheckBox("const", bg);
cpp_get_inline_cb->setChecked(GenerationSettings::cpp_get_inline);
cpp_get_value_const_cb->setChecked(GenerationSettings::cpp_get_value_const);
cpp_get_const_cb->setChecked(GenerationSettings::cpp_get_const);
new QLabel(TR(" name : "), htab);
edcpp_get_name = new LineEdit(htab);
edcpp_get_name->setText(GenerationSettings::cpp_get_name);
QFont font = edcpp_get_name->font();
if (! hasCodec())
font.setFamily("Courier");
font.setFixedPitch(TRUE);
edcpp_get_name->setFont(font);
new QLabel(" ", htab);
uml_follow_cpp_get_name = new QCheckBox(TR("also in uml"), htab);
if (GenerationSettings::uml_get_name == CppView)
uml_follow_cpp_get_name->setChecked(TRUE);
connect(uml_follow_cpp_get_name, SIGNAL(toggled(bool)),
this, SLOT(follow_cpp_get_name()));
new QLabel(TR("Set operation\ndefault definition : "), grid);
vtab = new QVBox(grid);
htab = new QHBox(vtab);
cpp_set_visibility.init(htab, GenerationSettings::cpp_get_visibility,
FALSE, TR("Visibility"));
bg = new QButtonGroup(4, Qt::Horizontal, TR("Modifiers"), htab);
bg->setExclusive(FALSE);
cpp_set_inline_cb = new QCheckBox("inline", bg);
cpp_set_param_const_cb = new QCheckBox(TR("const param"), bg);
cpp_set_param_ref_cb = new QCheckBox(TR("by ref"), bg);
cpp_set_inline_cb->setChecked(GenerationSettings::cpp_set_inline);
cpp_set_param_const_cb->setChecked(GenerationSettings::cpp_set_param_const);
cpp_set_param_ref_cb->setChecked(GenerationSettings::cpp_set_param_ref);
new QLabel(TR(" name : "), htab);
edcpp_set_name = new LineEdit(htab);
edcpp_set_name->setText(GenerationSettings::cpp_set_name);
edcpp_set_name->setFont(font);
new QLabel(" ", htab);
uml_follow_cpp_set_name = new QCheckBox(TR("also in uml"), htab);
if (GenerationSettings::uml_set_name == CppView)
uml_follow_cpp_set_name->setChecked(TRUE);
connect(uml_follow_cpp_set_name, SIGNAL(toggled(bool)),
this, SLOT(follow_cpp_set_name()));
//new QLabel(grid);
//new QLabel(grid);
new QLabel(TR("Enumeration item \ndefault definition :"), grid);
edcpp_enum_item_decl = new MultiLineEdit(grid);
edcpp_enum_item_decl->setText(GenerationSettings::cpp_enum_item_decl);
edcpp_enum_item_decl->setFont(font);
//new QLabel(grid);
//new QLabel(grid);
new QLabel(TR("Default type forms\nfor the enums :"), grid);
htab = new QHBox(grid);
htab->setMargin(3);
new QLabel(TR("input\nparameter : "), htab);
cpp_enum_in = new LineEdit(htab);
cpp_enum_in->setText(GenerationSettings::cpp_enum_in);
cpp_enum_in->setFont(font);
new QLabel(TR(" output\n parameter : "), htab);
cpp_enum_out = new LineEdit(htab);
cpp_enum_out->setText(GenerationSettings::cpp_enum_out);
cpp_enum_out->setFont(font);
new QLabel(TR(" input output \n parameter : "), htab);
cpp_enum_inout = new LineEdit(htab);
cpp_enum_inout->setText(GenerationSettings::cpp_enum_inout);
cpp_enum_inout->setFont(font);
new QLabel(TR(" operation \n return : "), htab);
cpp_enum_return = new LineEdit(htab);
cpp_enum_return->setText(GenerationSettings::cpp_enum_return);
cpp_enum_return->setFont(font);
new QLabel(TR("Default type forms for\nthe types not given\nin the first tab:"), grid);
htab = new QHBox(grid);
htab->setMargin(3);
new QLabel(TR("input\nparameter : "), htab);
cpp_in = new LineEdit(htab);
cpp_in->setText(GenerationSettings::cpp_in);
cpp_in->setFont(font);
new QLabel(TR(" output\n parameter : "), htab);
cpp_out = new LineEdit(htab);
cpp_out->setText(GenerationSettings::cpp_out);
cpp_out->setFont(font);
new QLabel(TR(" input output \n parameter : "), htab);
cpp_inout = new LineEdit(htab);
cpp_inout->setText(GenerationSettings::cpp_inout);
cpp_inout->setFont(font);
new QLabel(TR(" operation \n return : "), htab);
cpp_return = new LineEdit(htab);
cpp_return->setText(GenerationSettings::cpp_return);
cpp_return->setFont(font);
//new QLabel(grid);
//new QLabel(grid);
new QLabel(TR("Operation default \ndeclaration :"), grid);
edcpp_oper_decl = new MultiLineEdit(grid);
edcpp_oper_decl->setText(GenerationSettings::cpp_oper_decl);
edcpp_oper_decl->setFont(font);
new QLabel(TR("Operation default \ndefinition :"), grid);
htab = new QHBox(grid);
edcpp_oper_def = new MultiLineEdit(htab);
edcpp_oper_def->setText(GenerationSettings::cpp_oper_def);
edcpp_oper_def->setFont(font);
new QLabel(" ", htab);
cpp_force_throw_cb = new QCheckBox("throw()", htab);
cpp_force_throw_cb->setChecked(GenerationSettings::cpp_force_throw);
addTab(grid, "C++[4]");
if (!GenerationSettings::cpp_get_default_defs())
removePage(grid);
}
void GenerationSettingsDialog::init_cpp5() {
QSplitter * split = new QSplitter(Qt::Vertical, this);
split->setOpaqueResize(TRUE);
QHBox * htab;
htab = new QHBox(split);
htab->setMargin(3);
QLabel * lbl1 =
new QLabel(TR("External classes : \nname making\n#include, using"), htab);
edcpp_external_class_decl = new MultiLineEdit(htab);
edcpp_external_class_decl->setText(GenerationSettings::cpp_external_class_decl);
htab = new QHBox(split);
htab->setMargin(3);
QLabel * lbl2 =
new QLabel(TR("External types :\n#include form(s),\nusing, etc..."), htab);
cpp_include_table =
new IncludeTable(htab, GenerationSettings::cpp_includes,
TR("Include etc..."), "#include <>");
same_width(lbl1, lbl2);
addTab(split, "C++[5]");
if (!GenerationSettings::cpp_get_default_defs())
removePage(split);
}
void GenerationSettingsDialog::init_java1() {
QGrid * grid = new QGrid(2, this);
grid->setMargin(3);
grid->setSpacing(3);
new QLabel(TR("file default \ncontent :"), grid);
QHBox * htab = new QHBox(grid);
htab->setMargin(3);
edjava_src_content = new MultiLineEdit(htab);
edjava_src_content->setText(GenerationSettings::java_src_content);
QFont font = edjava_src_content->font();
if (! hasCodec())
font.setFamily("Courier");
font.setFixedPitch(TRUE);
edjava_src_content->setFont(font);
QVBox * vtab = new QVBox(htab);
QHBox * htab2 = new QHBox(vtab);
vtab->setMargin(3);
htab2->setMargin(3);
new QLabel(TR(" generated/reversed file extension "), htab2);
edjava_extension = new QComboBox(TRUE, htab2);
edjava_extension->insertItem(GenerationSettings::java_extension);
edjava_extension->setCurrentItem(0);
edjava_extension->insertItem("java");
htab2 = new QHBox(vtab);
htab2->setMargin(3);
new QLabel(TR(" generate Javadoc style comment "), htab2);
java_javadoc_cb = new QCheckBox(htab2);
java_javadoc_cb->setChecked(GenerationSettings::java_javadoc_comment);
htab2 = new QHBox(vtab);
htab2->setMargin(3);
new QLabel(TR(" force package prefix generation "), htab2);
java_force_package_gen_cb = new QCheckBox(htab2);
java_force_package_gen_cb->setChecked(GenerationSettings::java_force_package_gen);
new QLabel(TR("Class default \ndeclaration :"), grid);
edjava_class_decl = new MultiLineEdit(grid);
edjava_class_decl->setText(GenerationSettings::java_class_decl);
edjava_class_decl->setFont(font);
new QLabel(TR("Interface default \ndeclaration :"), grid);
edjava_interface_decl = new MultiLineEdit(grid);
edjava_interface_decl->setText(GenerationSettings::java_interface_decl);
edjava_interface_decl->setFont(font);
new QLabel(TR("Enum default \ndeclaration :"), grid);
edjava_enum_decl = new MultiLineEdit(grid);
edjava_enum_decl->setText(GenerationSettings::java_enum_decl);
edjava_enum_decl->setFont(font);
new QLabel(TR("Enum pattern \ndefault declaration :"), grid);
edjava_enum_pattern_decl = new MultiLineEdit(grid);
edjava_enum_pattern_decl->setText(GenerationSettings::java_enum_pattern_decl);
edjava_enum_pattern_decl->setFont(font);
addTab(grid, "Java[1]");
if (!GenerationSettings::java_get_default_defs())
removePage(grid);
}
void GenerationSettingsDialog::init_java2() {
QGrid * grid = new QGrid(2, this);
QGrid * grid2;
grid->setMargin(3);
grid->setSpacing(3);
new QLabel(TR("Attribute \ndefault \ndeclaration :"), grid);
grid2 = new QGrid(2, grid);
new QLabel(TR("multiplicity '1'\nor unspecified"), grid2);
edjava_attr_decl[0] = new MultiLineEdit(grid2);
new QLabel(TR("multiplicity '*'\nor 'a..b'"), grid2);
edjava_attr_decl[1] = new MultiLineEdit(grid2);
new QLabel(TR("X (probably a\nnumber)"), grid2);
edjava_attr_decl[2] = new MultiLineEdit(grid2);
QFont font = edjava_attr_decl[0]->font();
int i;
if (! hasCodec())
font.setFamily("Courier");
font.setFixedPitch(TRUE);
for (i = 0; i != 3; i += 1) {
edjava_attr_decl[i]->setText(GenerationSettings::java_attr_decl[i]);
edjava_attr_decl[i]->setFont(font);
}
new QLabel(grid);
new QLabel(grid);
new QLabel(TR("Association and\naggregation\ndefault\ndeclaration :"), grid);
grid2 = new QGrid(2, grid);
new QLabel(TR("multiplicity '1'\nor unspecified"), grid2);
edjava_rel_decl[0] = new MultiLineEdit(grid2);
new QLabel(TR("multiplicity '*'\nor 'a..b'"), grid2);
edjava_rel_decl[1] = new MultiLineEdit(grid2);
new QLabel(TR("X (probably a\nnumber)"), grid2);
edjava_rel_decl[2] = new MultiLineEdit(grid2);
for (i = 0; i != 3; i += 1) {
edjava_rel_decl[i]->setText(GenerationSettings::java_rel_decl[i]);
edjava_rel_decl[i]->setFont(font);
}
addTab(grid, "Java[2]");
if (!GenerationSettings::java_get_default_defs())
removePage(grid);
}
void GenerationSettingsDialog::init_java3() {
QGrid * grid = new QGrid(2, this);
QHBox * htab;
QButtonGroup * bg;
grid->setMargin(3);
grid->setSpacing(3);
new QLabel(TR("Enumeration item \ndefault definition :"), grid);
edjava_enum_item_decl = new MultiLineEdit(grid);
edjava_enum_item_decl->setText(GenerationSettings::java_enum_item_decl);
QFont font = edjava_enum_item_decl->font();
if (! hasCodec())
font.setFamily("Courier");
font.setFixedPitch(TRUE);
edjava_enum_item_decl->setFont(font);
new QLabel(TR("Enum pattern item \ndefault definition :"), grid);
edjava_enum_pattern_item_decl = new MultiLineEdit(grid);
edjava_enum_pattern_item_decl->setText(GenerationSettings::java_enum_pattern_item_decl);
edjava_enum_pattern_item_decl->setFont(font);
new QLabel(TR("Enum pattern item \n'case' in 'from_int' :"), grid);
edjava_enum_pattern_item_case = new MultiLineEdit(grid);
edjava_enum_pattern_item_case->setText(GenerationSettings::java_enum_pattern_item_case);
edjava_enum_pattern_item_case->setFont(font);
new QLabel(TR("Get operation\ndefault definition : "), grid);
htab = new QHBox(grid);
htab->setMargin(3);
java_get_visibility.init(htab, GenerationSettings::noncpp_get_visibility,
TRUE, TR("Visibility (shared with Php)"));
java_get_visibility.connect(SIGNAL(clicked (int)), this, SLOT(java_get_visi_changed(int)));
bg = new QButtonGroup(1, Qt::Horizontal, TR("Modifiers"), htab);
bg->setExclusive(FALSE);
java_get_final_cb = new QCheckBox("final", bg);
java_get_final_cb->setChecked(GenerationSettings::java_get_final);
new QLabel(TR(" name : "), htab);
edjava_get_name = new LineEdit(htab);
edjava_get_name->setText(GenerationSettings::java_get_name);
edjava_get_name->setFont(font);
new QLabel(" ", htab);
uml_follow_java_get_name = new QCheckBox(TR("also in uml"), htab);
if (GenerationSettings::uml_get_name == JavaView)
uml_follow_java_get_name->setChecked(TRUE);
connect(uml_follow_java_get_name, SIGNAL(toggled(bool)),
this, SLOT(follow_java_get_name()));
new QLabel(TR("Set operation\ndefault definition : "), grid);
htab = new QHBox(grid);
htab->setMargin(3);
java_set_visibility.init(htab, GenerationSettings::noncpp_set_visibility,
TRUE, TR("Visibility (shared with Php)"));
java_set_visibility.connect(SIGNAL(clicked (int)), this, SLOT(java_set_visi_changed(int)));
bg = new QButtonGroup(2, Qt::Horizontal, TR("Modifiers"), htab);
bg->setExclusive(FALSE);
java_set_final_cb = new QCheckBox("final", bg);
java_set_param_final_cb = new QCheckBox(TR("final parameter"), bg);
java_set_final_cb->setChecked(GenerationSettings::java_set_final);
java_set_param_final_cb->setChecked(GenerationSettings::java_set_param_final);
new QLabel(TR(" name : "), htab);
edjava_set_name = new LineEdit(htab);
edjava_set_name->setText(GenerationSettings::java_set_name);
edjava_set_name->setFont(font);
new QLabel(" ", htab);
uml_follow_java_set_name = new QCheckBox(TR("also in uml"), htab);
if (GenerationSettings::uml_set_name == JavaView)
uml_follow_java_set_name->setChecked(TRUE);
connect(uml_follow_java_set_name, SIGNAL(toggled(bool)),
this, SLOT(follow_java_set_name()));
//new QLabel(grid);
//new QLabel(grid);
new QLabel(TR("Operation\ndefault definition :"), grid);
edjava_oper_def = new MultiLineEdit(grid);
edjava_oper_def->setText(GenerationSettings::java_oper_def);
edjava_oper_def->setFont(font);
addTab(grid, "Java[3]");
if (!GenerationSettings::java_get_default_defs())
removePage(grid);
}
void GenerationSettingsDialog::init_java4() {
QSplitter * split = new QSplitter(Qt::Vertical, this);
split->setOpaqueResize(TRUE);
QHBox * htab;
htab = new QHBox(split);
htab->setMargin(3);
QLabel * lbl1 =
new QLabel(TR("External classes : \nname making"), htab);
edjava_external_class_decl = new LineEdit(htab);
edjava_external_class_decl->setText(GenerationSettings::java_external_class_decl);
htab = new QHBox(split);
htab->setMargin(3);
QLabel * lbl2 =
new QLabel(TR("External types :\nimport form(s) etc..."), htab);
java_import_table =
new IncludeTable(htab, GenerationSettings::java_imports,
"Import etc...", "import ");
same_width(lbl1, lbl2);
addTab(split, "Java[4]");
if (!GenerationSettings::java_get_default_defs())
removePage(split);
}
void GenerationSettingsDialog::init_php1() {
QGrid * grid = new QGrid(2, this);
grid->setMargin(3);
grid->setSpacing(3);
new QLabel(TR("file default \ncontent :"), grid);
QHBox * htab = new QHBox(grid);
htab->setMargin(3);
edphp_src_content = new MultiLineEdit(htab);
edphp_src_content->setText(GenerationSettings::php_src_content);
QFont font = edphp_src_content->font();
if (! hasCodec())
font.setFamily("Courier");
font.setFixedPitch(TRUE);
edphp_src_content->setFont(font);
QVBox * vtab = new QVBox(htab);
QHBox * htab2 = new QHBox(vtab);
vtab->setMargin(3);
htab2->setMargin(3);
new QLabel(TR(" generated / reversed file extension : "), htab2);
edphp_extension = new QComboBox(TRUE, htab2);
edphp_extension->insertItem(GenerationSettings::php_extension);
edphp_extension->setCurrentItem(0);
edphp_extension->insertItem("php");
htab2 = new QHBox(vtab);
htab2->setMargin(3);
new QLabel(TR(" generate Javadoc style comment : "), htab2);
php_javadoc_cb = new QCheckBox(htab2);
php_javadoc_cb->setChecked(GenerationSettings::php_javadoc_comment);
htab2 = new QHBox(vtab);
htab2->setMargin(3);
new QLabel(TR(" require_once : "), htab2);
php_require_with_path_cb = new QComboBox(FALSE, htab2);
php_require_with_path_cb->insertItem(TR("without path"));
php_require_with_path_cb->insertItem(TR("with absolute path"));
php_require_with_path_cb->insertItem(TR("with relative path"));
php_require_with_path_cb->insertItem(TR("with root relative path"));
if (!GenerationSettings::php_req_with_path)
php_require_with_path_cb->setCurrentItem(0);
else if (GenerationSettings::php_relative_path)
php_require_with_path_cb->setCurrentItem(2);
else if (GenerationSettings::php_root_relative_path)
php_require_with_path_cb->setCurrentItem(3);
else
php_require_with_path_cb->setCurrentItem(1);
htab2 = new QHBox(vtab);
htab2->setMargin(3);
new QLabel(TR(" force namespace prefix generation : "), htab2);
php_force_namespace_gen_cb = new QCheckBox(htab2);
php_force_namespace_gen_cb->setChecked(GenerationSettings::php_force_namespace_gen);
new QLabel(TR("Class default \ndeclaration :"), grid);
edphp_class_decl = new MultiLineEdit(grid);
edphp_class_decl->setText(GenerationSettings::php_class_decl);
edphp_class_decl->setFont(font);
new QLabel(TR("Interface default \ndeclaration :"), grid);
edphp_interface_decl = new MultiLineEdit(grid);
edphp_interface_decl->setText(GenerationSettings::php_interface_decl);
edphp_interface_decl->setFont(font);
new QLabel(TR("Enum default \ndeclaration :"), grid);
edphp_enum_decl = new MultiLineEdit(grid);
edphp_enum_decl->setText(GenerationSettings::php_enum_decl);
edphp_enum_decl->setFont(font);
addTab(grid, "Php[1]");
if (!GenerationSettings::php_get_default_defs())
removePage(grid);
}
void GenerationSettingsDialog::init_php2() {
QGrid * grid = new QGrid(2, this);
grid->setMargin(3);
grid->setSpacing(3);
new QLabel(TR("Attribute default \ndeclaration :"), grid);
edphp_attr_decl = new MultiLineEdit(grid);
QFont font = edphp_attr_decl->font();
if (! hasCodec())
font.setFamily("Courier");
font.setFixedPitch(TRUE);
edphp_attr_decl->setText(GenerationSettings::php_attr_decl);
edphp_attr_decl->setFont(font);
new QLabel(TR("Association and\naggregation\ndefault\ndeclaration :"), grid);
edphp_rel_decl = new MultiLineEdit(grid);
edphp_rel_decl->setText(GenerationSettings::php_rel_decl);
edphp_rel_decl->setFont(font);
QHBox * htab;
QButtonGroup * bg;
new QLabel(TR("Enumeration item \ndefault definition :"), grid);
edphp_enum_item_decl = new MultiLineEdit(grid);
edphp_enum_item_decl->setText(GenerationSettings::php_enum_item_decl);
if (! hasCodec())
font.setFamily("Courier");
font.setFixedPitch(TRUE);
edphp_enum_item_decl->setFont(font);
new QLabel(TR("Get operation\ndefault definition : "), grid);
htab = new QHBox(grid);
htab->setMargin(3);
php_get_visibility.init(htab, GenerationSettings::noncpp_get_visibility,
FALSE, TR("Visibility (shared with Java)"));
php_get_visibility.connect(SIGNAL(clicked (int)), this, SLOT(php_get_visi_changed(int)));
bg = new QButtonGroup(1, Qt::Horizontal, TR("Modifiers"), htab);
bg->setExclusive(FALSE);
php_get_final_cb = new QCheckBox("final", bg);
php_get_final_cb->setChecked(GenerationSettings::php_get_final);
new QLabel(TR(" name : "), htab);
edphp_get_name = new LineEdit(htab);
edphp_get_name->setText(GenerationSettings::php_get_name);
edphp_get_name->setFont(font);
new QLabel(" ", htab);
uml_follow_php_get_name = new QCheckBox(TR("also in uml"), htab);
if (GenerationSettings::uml_get_name == PhpView)
uml_follow_php_get_name->setChecked(TRUE);
connect(uml_follow_php_get_name, SIGNAL(toggled(bool)),
this, SLOT(follow_php_get_name()));
new QLabel(TR("Set operation\ndefault definition : "), grid);
htab = new QHBox(grid);
htab->setMargin(3);
php_set_visibility.init(htab, GenerationSettings::noncpp_set_visibility,
FALSE, TR("Visibility (shared with Java)"));
php_set_visibility.connect(SIGNAL(clicked (int)), this, SLOT(php_set_visi_changed(int)));
bg = new QButtonGroup(2, Qt::Horizontal, TR("Modifiers"), htab);
bg->setExclusive(FALSE);
php_set_final_cb = new QCheckBox("final", bg);
php_set_final_cb->setChecked(GenerationSettings::php_set_final);
new QLabel(TR(" name : "), htab);
edphp_set_name = new LineEdit(htab);
edphp_set_name->setText(GenerationSettings::php_set_name);
edphp_set_name->setFont(font);
new QLabel(" ", htab);
uml_follow_php_set_name = new QCheckBox(TR("also in uml"), htab);
if (GenerationSettings::uml_set_name == PhpView)
uml_follow_php_set_name->setChecked(TRUE);
connect(uml_follow_php_set_name, SIGNAL(toggled(bool)),
this, SLOT(follow_php_set_name()));
//new QLabel(grid);
//new QLabel(grid);
new QLabel(TR("Operation\ndefault definition :"), grid);
edphp_oper_def = new MultiLineEdit(grid);
edphp_oper_def->setText(GenerationSettings::php_oper_def);
edphp_oper_def->setFont(font);
new QLabel(grid);
new QLabel(grid);
new QLabel(TR("External classes : \nname making"), grid);
edphp_external_class_decl = new LineEdit(grid);
edphp_external_class_decl->setText(GenerationSettings::php_external_class_decl);
addTab(grid, "Php[2]");
if (!GenerationSettings::php_get_default_defs())
removePage(grid);
}
void GenerationSettingsDialog::init_python1() {
QGrid * grid = new QGrid(2, this);
grid->setMargin(3);
grid->setSpacing(3);
new QLabel(TR("indent step :"), grid);
QHBox * htab = new QHBox(grid);
htab->setMargin(3);
indentstep_cb = new QComboBox(FALSE, htab);
init_indent(indentstep_cb, GenerationSettings::python_indent_step);
QLabel * lbl = new QLabel(htab);
QSizePolicy sp = lbl->sizePolicy();
sp.setHorData(QSizePolicy::Expanding);
lbl->setSizePolicy(sp);
new QLabel(TR("file default \ncontent :"), grid);
htab = new QHBox(grid);
htab->setMargin(3);
edpython_src_content = new MultiLineEdit(htab);
edpython_src_content->setText(GenerationSettings::python_src_content);
QFont font = edpython_src_content->font();
if (! hasCodec())
font.setFamily("Courier");
font.setFixedPitch(TRUE);
edpython_src_content->setFont(font);
new QLabel(TR(" generated /\n reversed\n file extension : "), htab);
edpython_extension = new QComboBox(TRUE, htab);
edpython_extension->insertItem(GenerationSettings::python_extension);
edpython_extension->setCurrentItem(0);
edpython_extension->insertItem("py");
new QLabel(TR("Class default \ndeclaration :"), grid);
htab = new QHBox(grid);
htab->setMargin(3);
edpython_class_decl = new MultiLineEdit(htab);
edpython_class_decl->setText(GenerationSettings::python_class_decl);
edpython_class_decl->setFont(font);
new QLabel(TR(" classes of Python 2.2 "), htab);
python_2_2_cb = new QCheckBox(htab);
python_2_2_cb->setChecked(GenerationSettings::python_2_2);
new QLabel(TR("Enum default \ndeclaration :"), grid);
edpython_enum_decl = new MultiLineEdit(grid);
edpython_enum_decl->setText(GenerationSettings::python_enum_decl);
edpython_enum_decl->setFont(font);
new QLabel(TR("Enumeration item \ndefault definition :"), grid);
edpython_enum_item_decl = new MultiLineEdit(grid);
edpython_enum_item_decl->setText(GenerationSettings::python_enum_item_decl);
edpython_enum_item_decl->setFont(font);
new QLabel(TR("Attribute \ndefault \ndeclaration :"), grid);
QGrid * grid2 = new QGrid(2, grid);
new QLabel(TR("multiplicity '1'\nor unspecified"), grid2);
edpython_attr_decl[0] = new MultiLineEdit(grid2);
new QLabel(TR("other\nmultiplicity"), grid2);
edpython_attr_decl[1] = new MultiLineEdit(grid2);
int i;
for (i = 0; i != 2; i += 1) {
edpython_attr_decl[i]->setText(GenerationSettings::python_attr_decl[i]);
edpython_attr_decl[i]->setFont(font);
}
addTab(grid, "Python[1]");
if (!GenerationSettings::python_get_default_defs())
removePage(grid);
}
void GenerationSettingsDialog::init_python2() {
QGrid * grid = new QGrid(2, this);
QGrid * grid2;
grid->setMargin(3);
grid->setSpacing(3);
new QLabel(TR("Association and\naggregation\ndefault\ndeclaration :"), grid);
grid2 = new QGrid(2, grid);
new QLabel(TR("multiplicity '1'\nor unspecified"), grid2);
edpython_rel_decl[0][0] = new MultiLineEdit(grid2);
QFont font = edpython_rel_decl[0][0]->font();
int i;
if (! hasCodec())
font.setFamily("Courier");
font.setFixedPitch(TRUE);
new QLabel(TR("other\nmultiplicity"), grid2);
edpython_rel_decl[0][1] = new MultiLineEdit(grid2);
for (i = 0; i != 2; i += 1) {
edpython_rel_decl[0][i]->setText(GenerationSettings::python_rel_decl[0][i]);
edpython_rel_decl[0][i]->setFont(font);
}
new QLabel(grid);
new QLabel(grid);
new QLabel(TR("Composition\ndefault\ndeclaration :"), grid);
grid2 = new QGrid(2, grid);
new QLabel(TR("multiplicity '1'\nor unspecified"), grid2);
edpython_rel_decl[1][0] = new MultiLineEdit(grid2);
new QLabel(TR("other\nmultiplicity"), grid2);
edpython_rel_decl[1][1] = new MultiLineEdit(grid2);
for (i = 0; i != 2; i += 1) {
edpython_rel_decl[1][i]->setText(GenerationSettings::python_rel_decl[1][i]);
edpython_rel_decl[1][i]->setFont(font);
}
QHBox * htab;
new QLabel(grid);
new QLabel(grid);
new QLabel(TR("Get operation\ndefault definition : "), grid);
htab = new QHBox(grid);
htab->setMargin(3);
new QLabel(TR(" name : "), htab);
edpython_get_name = new LineEdit(htab);
edpython_get_name->setText(GenerationSettings::python_get_name);
edpython_get_name->setFont(font);
new QLabel(" ", htab);
uml_follow_python_get_name = new QCheckBox(TR("also in uml"), htab);
if (GenerationSettings::uml_get_name == PythonView)
uml_follow_python_get_name->setChecked(TRUE);
connect(uml_follow_python_get_name, SIGNAL(toggled(bool)),
this, SLOT(follow_python_get_name()));
new QLabel(TR("Set operation\ndefault definition : "), grid);
htab = new QHBox(grid);
htab->setMargin(3);
new QLabel(TR(" name : "), htab);
edpython_set_name = new LineEdit(htab);
edpython_set_name->setText(GenerationSettings::python_set_name);
edpython_set_name->setFont(font);
new QLabel(" ", htab);
uml_follow_python_set_name = new QCheckBox(TR("also in uml"), htab);
if (GenerationSettings::uml_set_name == PythonView)
uml_follow_python_set_name->setChecked(TRUE);
connect(uml_follow_python_set_name, SIGNAL(toggled(bool)),
this, SLOT(follow_python_set_name()));
new QLabel(grid);
new QLabel(grid);
new QLabel(TR("Operation\ndefault definition :"), grid);
htab = new QHBox(grid);
htab->setMargin(3);
edpython_oper_def = new MultiLineEdit(htab);
edpython_oper_def->setText(GenerationSettings::python_oper_def);
edpython_oper_def->setFont(font);
new QLabel(TR(" operation of Python 3 (pep-3107) "), htab);
python_3_operation_cb = new QCheckBox(htab);
python_3_operation_cb->setChecked(GenerationSettings::python_3_operation);
new QLabel(TR("Operation __init__\ndefault definition :"), grid);
edpython_initoper_def = new MultiLineEdit(grid);
edpython_initoper_def->setText(GenerationSettings::python_initoper_def);
edpython_initoper_def->setFont(font);
addTab(grid, "Python[2]");
if (!GenerationSettings::python_get_default_defs())
removePage(grid);
}
void GenerationSettingsDialog::init_python3() {
QSplitter * split = new QSplitter(Qt::Vertical, this);
split->setOpaqueResize(TRUE);
QHBox * htab;
htab = new QHBox(split);
htab->setMargin(3);
QLabel * lbl1 =
new QLabel(TR("External classes : \nname making\nimport"), htab);
edpython_external_class_decl = new MultiLineEdit(htab);
edpython_external_class_decl->setText(GenerationSettings::python_external_class_decl);
htab = new QHBox(split);
htab->setMargin(3);
QLabel * lbl2 =
new QLabel(TR("External types :\nimport form(s)"), htab);
python_import_table =
new IncludeTable(htab, GenerationSettings::python_imports,
"Import", "import ");
same_width(lbl1, lbl2);
addTab(split, "Python[3]");
if (!GenerationSettings::python_get_default_defs())
removePage(split);
}
void GenerationSettingsDialog::init_idl1() {
QSplitter * split = new QSplitter(Qt::Vertical, this);
split->setOpaqueResize(TRUE);
QHBox * htab;
htab = new QHBox(split);
htab->setMargin(3);
QLabel * lbl1 =
new QLabel(TR("file default \ncontent :"), htab);
edidl_src_content = new MultiLineEdit(htab);
edidl_src_content->setText(GenerationSettings::idl_src_content);
QFont font = edidl_src_content->font();
if (! hasCodec())
font.setFamily("Courier");
font.setFixedPitch(TRUE);
edidl_src_content->setFont(font);
new QLabel(TR(" file extension : "), htab);
edidl_extension = new QComboBox(TRUE, htab);
edidl_extension->insertItem(GenerationSettings::idl_extension);
edidl_extension->setCurrentItem(0);
edidl_extension->insertItem("Idl");
QGrid * grid = new QGrid(2, split);
grid->setMargin(3);
grid->setSpacing(3);
new QLabel(TR("Interface default \ndeclaration :"), grid);
edidl_interface_decl = new MultiLineEdit(grid);
edidl_interface_decl->setText(GenerationSettings::idl_interface_decl);
edidl_interface_decl->setFont(font);
QLabel * lbl2 =
new QLabel(TR("Valuetype default \ndeclaration :"), grid);
same_width(lbl1, lbl2);
edidl_valuetype_decl = new MultiLineEdit(grid);
edidl_valuetype_decl->setText(GenerationSettings::idl_valuetype_decl);
edidl_valuetype_decl->setFont(font);
new QLabel(TR("Struct default \ndeclaration :"), grid);
edidl_struct_decl = new MultiLineEdit(grid);
edidl_struct_decl->setText(GenerationSettings::idl_struct_decl);
edidl_struct_decl->setFont(font);
new QLabel(TR("Union default \ndeclaration :"), grid);
edidl_union_decl = new MultiLineEdit(grid);
edidl_union_decl->setText(GenerationSettings::idl_union_decl);
edidl_union_decl->setFont(font);
new QLabel(TR("Enum default \ndeclaration :"), grid);
edidl_enum_decl = new MultiLineEdit(grid);
edidl_enum_decl->setText(GenerationSettings::idl_enum_decl);
edidl_enum_decl->setFont(font);
new QLabel(TR("Typedef default \ndeclaration :"), grid);
edidl_typedef_decl = new MultiLineEdit(grid);
edidl_typedef_decl->setText(GenerationSettings::idl_typedef_decl);
edidl_typedef_decl->setFont(font);
new QLabel(TR("Exception default \ndeclaration :"), grid);
edidl_exception_decl = new MultiLineEdit(grid);
edidl_exception_decl->setText(GenerationSettings::idl_exception_decl);
edidl_exception_decl->setFont(font);
addTab(split, "Idl[1]");
if (!GenerationSettings::idl_get_default_defs())
removePage(split);
}
void GenerationSettingsDialog::init_idl2() {
QGrid * grid = new QGrid(2, this);
QGrid * grid2;
grid->setMargin(3);
grid->setSpacing(3);
new QLabel(TR("Attribute default \ndeclaration :"), grid);
grid2 = new QGrid(2, grid);
new QLabel(TR("multiplicity '1'\nor unspecified"), grid2);
edidl_attr_decl[0] = new MultiLineEdit(grid2);
new QLabel(TR("multiplicity '*'\nor 'a..b'"), grid2);
edidl_attr_decl[1] = new MultiLineEdit(grid2);
new QLabel(TR("X (probably a\nnumber)"), grid2);
edidl_attr_decl[2] = new MultiLineEdit(grid2);
QFont font = edjava_attr_decl[0]->font();
int i;
if (! hasCodec())
font.setFamily("Courier");
font.setFixedPitch(TRUE);
for (i = 0; i != 3; i += 1) {
edidl_attr_decl[i]->setText(GenerationSettings::idl_attr_decl[i]);
edidl_attr_decl[i]->setFont(font);
}
new QLabel(grid);
new QLabel(grid);
new QLabel(TR("Attribute default \ndeclaration in\nvaluetype :"), grid);
grid2 = new QGrid(2, grid);
new QLabel(TR("multiplicity '1'\nor unspecified"), grid2);
edidl_valuetype_attr_decl[0] = new MultiLineEdit(grid2);
new QLabel(TR("multiplicity '*'\nor 'a..b'"), grid2);
edidl_valuetype_attr_decl[1] = new MultiLineEdit(grid2);
new QLabel(TR("X (probably a\nnumber)"), grid2);
edidl_valuetype_attr_decl[2] = new MultiLineEdit(grid2);
for (i = 0; i != 3; i += 1) {
edidl_valuetype_attr_decl[i]->setText(GenerationSettings::idl_valuetype_attr_decl[i]);
edidl_valuetype_attr_decl[i]->setFont(font);
}
new QLabel(grid);
new QLabel(grid);
new QLabel(TR("Constant default \ndeclaration :"), grid);
grid2 = new QGrid(2, grid);
new QLabel(TR("multiplicity '1'\nor unspecified"), grid2);
edidl_const_decl[0] = new MultiLineEdit(grid2);
new QLabel(TR("multiplicity '*'\nor 'a..b'"), grid2);
edidl_const_decl[1] = new MultiLineEdit(grid2);
new QLabel(TR("X (probably a\nnumber)"), grid2);
edidl_const_decl[2] = new MultiLineEdit(grid2);
for (i = 0; i != 3; i += 1) {
edidl_const_decl[i]->setText(GenerationSettings::idl_const_decl[i]);
edidl_const_decl[i]->setFont(font);
}
addTab(grid, "Idl[2]");
if (!GenerationSettings::idl_get_default_defs())
removePage(grid);
}
void GenerationSettingsDialog::init_idl3() {
QGrid * grid = new QGrid(2, this);
QGrid * grid2;
int i;
grid->setMargin(3);
grid->setSpacing(3);
new QLabel(TR("Association and\naggregation\ndefault\ndeclaration :"), grid);
grid2 = new QGrid(2, grid);
new QLabel(TR("multiplicity '1'\nor unspecified"), grid2);
edidl_rel_decl[0] = new MultiLineEdit(grid2);
new QLabel(TR("multiplicity '*'\nor 'a..b'"), grid2);
edidl_rel_decl[1] = new MultiLineEdit(grid2);
new QLabel(TR("X (probably a\nnumber)"), grid2);
edidl_rel_decl[2] = new MultiLineEdit(grid2);
QFont font = edidl_rel_decl[0]->font();
if (! hasCodec())
font.setFamily("Courier");
font.setFixedPitch(TRUE);
for (i = 0; i != 3; i += 1) {
edidl_rel_decl[i]->setText(GenerationSettings::idl_rel_decl[i]);
edidl_rel_decl[i]->setFont(font);
}
new QLabel(grid);
new QLabel(grid);
new QLabel(TR("Association and\naggregation\ndefault\ndeclaration in\nvaluetype :"), grid);
grid2 = new QGrid(2, grid);
new QLabel(TR("multiplicity '1'\nor unspecified"), grid2);
edidl_valuetype_rel_decl[0] = new MultiLineEdit(grid2);
new QLabel(TR("multiplicity '*'\nor 'a..b'"), grid2);
edidl_valuetype_rel_decl[1] = new MultiLineEdit(grid2);
new QLabel(TR("X (probably a\nnumber)"), grid2);
edidl_valuetype_rel_decl[2] = new MultiLineEdit(grid2);
for (i = 0; i != 3; i += 1) {
edidl_valuetype_rel_decl[i]->setText(GenerationSettings::idl_valuetype_rel_decl[i]);
edidl_valuetype_rel_decl[i]->setFont(font);
}
new QLabel(grid);
new QLabel(grid);
new QLabel(TR("Association and\naggregation\ndefault\ndeclaration in\nunion:"), grid);
grid2 = new QGrid(2, grid);
new QLabel(TR("multiplicity '1'\nor unspecified"), grid2);
edidl_union_rel_decl[0] = new MultiLineEdit(grid2);
new QLabel(TR("multiplicity '*'\nor 'a..b'"), grid2);
edidl_union_rel_decl[1] = new MultiLineEdit(grid2);
new QLabel(TR("X (probably a\nnumber)"), grid2);
edidl_union_rel_decl[2] = new MultiLineEdit(grid2);
for (i = 0; i != 3; i += 1) {
edidl_union_rel_decl[i]->setText(GenerationSettings::idl_union_rel_decl[i]);
edidl_union_rel_decl[i]->setFont(font);
}
addTab(grid, "Idl[3]");
if (!GenerationSettings::idl_get_default_defs())
removePage(grid);
}
void GenerationSettingsDialog::init_idl4() {
QGrid * grid = new QGrid(2, this);
QGrid * grid2;
QHBox * htab;
grid->setMargin(3);
grid->setSpacing(3);
new QLabel(TR("Union item \ndefault \ndeclaration :"), grid);
grid2 = new QGrid(2, grid);
new QLabel(TR("multiplicity '1'\nor unspecified"), grid2);
edidl_union_item_decl[0] = new MultiLineEdit(grid2);
new QLabel(TR("multiplicity '*'\nor 'a..b'"), grid2);
edidl_union_item_decl[1] = new MultiLineEdit(grid2);
new QLabel(TR("X (probably a\nnumber)"), grid2);
edidl_union_item_decl[2] = new MultiLineEdit(grid2);
QFont font = edidl_union_item_decl[0]->font();
int i;
if (! hasCodec())
font.setFamily("Courier");
font.setFixedPitch(TRUE);
for (i = 0; i != 3; i += 1) {
edidl_union_item_decl[i]->setText(GenerationSettings::idl_union_item_decl[i]);
edidl_union_item_decl[i]->setFont(font);
}
new QLabel(grid);
new QLabel(grid);
new QLabel(TR("Enumeration item \ndefault declaration :"), grid);
edidl_enum_item_decl = new MultiLineEdit(grid);
edidl_enum_item_decl->setText(GenerationSettings::idl_enum_item_decl);
edidl_enum_item_decl->setFont(font);
new QLabel(grid);
new QLabel(grid);
new QLabel(TR("Get operation\ndefault definition : "), grid);
htab = new QHBox(grid);
new QLabel(TR("name : "), htab);
edidl_get_name = new LineEdit(htab);
edidl_get_name->setText(GenerationSettings::idl_get_name);
edidl_get_name->setFont(font);
new QLabel(" ", htab);
uml_follow_idl_get_name = new QCheckBox(TR("also in uml"), htab);
if (GenerationSettings::uml_get_name == IdlView)
uml_follow_idl_get_name->setChecked(TRUE);
connect(uml_follow_idl_get_name, SIGNAL(toggled(bool)),
this, SLOT(follow_idl_get_name()));
new QLabel(TR("Set operation\ndefault definition : "), grid);
htab = new QHBox(grid);
idl_set_oneway_cb = new QCheckBox("oneway", htab);
idl_set_oneway_cb->setChecked(GenerationSettings::idl_set_oneway);
new QLabel(TR(" name : "), htab);
edidl_set_name = new LineEdit(htab);
edidl_set_name->setText(GenerationSettings::idl_set_name);
edidl_set_name->setFont(font);
new QLabel(" ", htab);
uml_follow_idl_set_name = new QCheckBox(TR("also in uml"), htab);
if (GenerationSettings::uml_set_name == IdlView)
uml_follow_idl_set_name->setChecked(TRUE);
connect(uml_follow_idl_set_name, SIGNAL(toggled(bool)),
this, SLOT(follow_idl_set_name()));
new QLabel(grid);
new QLabel(grid);
new QLabel(TR("Operation default \ndeclaration : "), grid);
edidl_oper_decl = new MultiLineEdit(grid);
edidl_oper_decl->setText(GenerationSettings::idl_oper_decl);
edidl_oper_decl->setFont(font);
addTab(grid, "Idl[4]");
if (!GenerationSettings::idl_get_default_defs())
removePage(grid);
}
void GenerationSettingsDialog::init_idl5() {
QSplitter * split = new QSplitter(Qt::Vertical, this);
split->setOpaqueResize(TRUE);
QHBox * htab;
htab = new QHBox(split);
htab->setMargin(3);
QLabel * lbl1 =
new QLabel(TR("External classes : \nname making\n#include"), htab);
edidl_external_class_decl = new MultiLineEdit(htab);
edidl_external_class_decl->setText(GenerationSettings::idl_external_class_decl);
htab = new QHBox(split);
htab->setMargin(3);
QLabel * lbl2 =
new QLabel(TR("External types :\n#include form(s)\netc..."), htab);
idl_include_table =
new IncludeTable(htab, GenerationSettings::idl_includes,
"Include etc...", "#include \"\"");
same_width(lbl1, lbl2);
addTab(split, "Idl[5]");
if (!GenerationSettings::idl_get_default_defs())
removePage(split);
}
void GenerationSettingsDialog::init_descriptions() {
QSplitter * split = new QSplitter(Qt::Vertical, this);
split->setOpaqueResize(TRUE);
QHBox * htab;
htab = new QHBox(split);
htab->setMargin(3);
new QLabel(TR("Artifact\ndefault\ndescription : "), htab);
edartifact_default_description = new MultiLineEdit(htab);
edartifact_default_description->setText(GenerationSettings::artifact_default_description);
htab = new QHBox(split);
htab->setMargin(3);
new QLabel(TR("Class\ndefault\ndescription : "), htab);
edclass_default_description = new MultiLineEdit(htab);
edclass_default_description->setText(GenerationSettings::class_default_description);
htab = new QHBox(split);
htab->setMargin(3);
new QLabel(TR("Operation\ndefault\ndescription : "), htab);
edoperation_default_description = new MultiLineEdit(htab);
edoperation_default_description->setText(GenerationSettings::operation_default_description);
htab = new QHBox(split);
htab->setMargin(3);
new QLabel(TR("Attribute\ndefault\ndescription : "), htab);
edattribute_default_description = new MultiLineEdit(htab);
edattribute_default_description->setText(GenerationSettings::attribute_default_description);
htab = new QHBox(split);
htab->setMargin(3);
new QLabel(TR("Relation\ndefault\ndescription : "), htab);
edrelation_default_description = new MultiLineEdit(htab);
edrelation_default_description->setText(GenerationSettings::relation_default_description);
addTab(split, TR("Description"));
}
static QString Relative;
static QString Absolute;
void GenerationSettingsDialog::init_dirs() {
Relative = TR("Set it relative");
Absolute = TR("Set it absolute");
QPushButton * button;
QVBox * vtab = new QVBox(this);
QHBox * htab;
vtab->setMargin(3);
htab = new QHBox(vtab);
htab->setMargin(3);
new QLabel(TR("Defining a project root directory allows to specify \
packages's generation directory relative to the root directory rather \
than absolute.\n"
"A root directory may itself be relative to the project path"),
htab);
htab = new QHBox(vtab);
htab->setMargin(3);
QLabel * lbl1 = new QLabel(TR("C++ root dir : "), htab);
edcpproot = new LineEdit(GenerationSettings::cpp_root_dir, htab);
new QLabel(" ", htab);
button = new SmallPushButton(TR("Browse"), htab);
connect(button, SIGNAL(clicked ()), this, SLOT(cpproot_browse()));
new QLabel("", htab);
cpprelbutton = new SmallPushButton((GenerationSettings::cpp_root_dir.isEmpty() ||
QDir::isRelativePath(GenerationSettings::cpp_root_dir))
? Absolute : Relative, htab);
connect(cpprelbutton, SIGNAL(clicked ()), this, SLOT(cpp_relative()));
new QLabel("", htab);
htab = new QHBox(vtab);
htab->setMargin(3);
new QLabel("", htab);
htab = new QHBox(vtab);
htab->setMargin(3);
QLabel * lbl2 = new QLabel(TR("Java root dir : "), htab);
edjavaroot = new LineEdit(GenerationSettings::java_root_dir, htab);
new QLabel(" ", htab);
button = new SmallPushButton(TR("Browse"), htab);
connect(button, SIGNAL(clicked ()), this, SLOT(javaroot_browse()));
new QLabel("", htab);
javarelbutton = new SmallPushButton((GenerationSettings::java_root_dir.isEmpty() ||
QDir::isRelativePath(GenerationSettings::java_root_dir))
? Absolute : Relative, htab);
connect(javarelbutton, SIGNAL(clicked ()), this, SLOT(java_relative()));
new QLabel("", htab);
htab = new QHBox(vtab);
htab->setMargin(3);
new QLabel("", htab);
htab = new QHBox(vtab);
htab->setMargin(3);
QLabel * lbl3 = new QLabel(TR("Php root dir : "), htab);
edphproot = new LineEdit(GenerationSettings::php_root_dir, htab);
new QLabel(" ", htab);
button = new SmallPushButton(TR("Browse"), htab);
connect(button, SIGNAL(clicked ()), this, SLOT(phproot_browse()));
new QLabel("", htab);
phprelbutton = new SmallPushButton((GenerationSettings::php_root_dir.isEmpty() ||
QDir::isRelativePath(GenerationSettings::php_root_dir))
? Absolute : Relative, htab);
connect(phprelbutton, SIGNAL(clicked ()), this, SLOT(php_relative()));
new QLabel("", htab);
htab = new QHBox(vtab);
htab->setMargin(3);
new QLabel("", htab);
htab = new QHBox(vtab);
htab->setMargin(3);
QLabel * lbl4 = new QLabel(TR("Python root dir : "), htab);
edpythonroot = new LineEdit(GenerationSettings::python_root_dir, htab);
new QLabel(" ", htab);
button = new SmallPushButton(TR("Browse"), htab);
connect(button, SIGNAL(clicked ()), this, SLOT(pythonroot_browse()));
new QLabel("", htab);
pythonrelbutton = new SmallPushButton((GenerationSettings::python_root_dir.isEmpty() ||
QDir::isRelativePath(GenerationSettings::python_root_dir))
? Absolute : Relative, htab);
connect(pythonrelbutton, SIGNAL(clicked ()), this, SLOT(python_relative()));
new QLabel("", htab);
htab = new QHBox(vtab);
htab->setMargin(3);
new QLabel("", htab);
htab = new QHBox(vtab);
htab->setMargin(3);
QLabel * lbl5 = new QLabel(TR("Idl root dir : "), htab);
edidlroot = new LineEdit(GenerationSettings::idl_root_dir, htab);
new QLabel(" ", htab);
button = new SmallPushButton(TR("Browse"), htab);
connect(button, SIGNAL(clicked ()), this, SLOT(idlroot_browse()));
new QLabel("", htab);
idlrelbutton = new SmallPushButton((GenerationSettings::idl_root_dir.isEmpty() ||
QDir::isRelativePath(GenerationSettings::idl_root_dir))
? Absolute : Relative, htab);
connect(idlrelbutton, SIGNAL(clicked ()), this, SLOT(idl_relative()));
new QLabel("", htab);
same_width(lbl1, lbl2, lbl3, lbl4, lbl5);
vtab->setStretchFactor(new QHBox(vtab), 1000);
addTab(vtab, TR("Directory"));
}
static QString add_last_slash(QString s)
{
if (!s.isEmpty()) {
int i = s.length() - 1;
switch (s.at(i).latin1()) {
case '/':
case '\\':
break;
default:
return QDir::convertSeparators(s + "/");
}
}
return s;
}
void GenerationSettingsDialog::follow_cpp_get_name() {
if (uml_follow_cpp_get_name->isChecked()) {
uml_follow_java_get_name->setChecked(FALSE);
uml_follow_php_get_name->setChecked(FALSE);
uml_follow_python_get_name->setChecked(FALSE);
uml_follow_idl_get_name->setChecked(FALSE);
}
}
void GenerationSettingsDialog::follow_cpp_set_name() {
if (uml_follow_cpp_set_name->isChecked()) {
uml_follow_java_set_name->setChecked(FALSE);
uml_follow_php_set_name->setChecked(FALSE);
uml_follow_python_set_name->setChecked(FALSE);
uml_follow_idl_set_name->setChecked(FALSE);
}
}
void GenerationSettingsDialog::follow_java_get_name() {
if (uml_follow_java_get_name->isChecked()) {
uml_follow_cpp_get_name->setChecked(FALSE);
uml_follow_php_get_name->setChecked(FALSE);
uml_follow_python_get_name->setChecked(FALSE);
uml_follow_idl_get_name->setChecked(FALSE);
}
}
void GenerationSettingsDialog::follow_java_set_name() {
if (uml_follow_java_set_name->isChecked()) {
uml_follow_cpp_set_name->setChecked(FALSE);
uml_follow_php_set_name->setChecked(FALSE);
uml_follow_python_set_name->setChecked(FALSE);
uml_follow_idl_set_name->setChecked(FALSE);
}
}
void GenerationSettingsDialog::follow_php_get_name() {
if (uml_follow_php_get_name->isChecked()) {
uml_follow_cpp_get_name->setChecked(FALSE);
uml_follow_java_get_name->setChecked(FALSE);
uml_follow_python_get_name->setChecked(FALSE);
uml_follow_idl_get_name->setChecked(FALSE);
}
}
void GenerationSettingsDialog::follow_php_set_name() {
if (uml_follow_php_set_name->isChecked()) {
uml_follow_cpp_set_name->setChecked(FALSE);
uml_follow_java_set_name->setChecked(FALSE);
uml_follow_python_set_name->setChecked(FALSE);
uml_follow_idl_set_name->setChecked(FALSE);
}
}
void GenerationSettingsDialog::follow_python_get_name() {
if (uml_follow_php_get_name->isChecked()) {
uml_follow_cpp_get_name->setChecked(FALSE);
uml_follow_java_get_name->setChecked(FALSE);
uml_follow_php_get_name->setChecked(FALSE);
uml_follow_idl_get_name->setChecked(FALSE);
}
}
void GenerationSettingsDialog::follow_python_set_name() {
if (uml_follow_php_set_name->isChecked()) {
uml_follow_cpp_set_name->setChecked(FALSE);
uml_follow_java_set_name->setChecked(FALSE);
uml_follow_php_set_name->setChecked(FALSE);
uml_follow_idl_set_name->setChecked(FALSE);
}
}
void GenerationSettingsDialog::follow_idl_get_name() {
if (uml_follow_idl_get_name->isChecked()) {
uml_follow_cpp_get_name->setChecked(FALSE);
uml_follow_java_get_name->setChecked(FALSE);
uml_follow_php_get_name->setChecked(FALSE);
uml_follow_python_get_name->setChecked(FALSE);
}
}
void GenerationSettingsDialog::follow_idl_set_name() {
if (uml_follow_idl_set_name->isChecked()) {
uml_follow_cpp_set_name->setChecked(FALSE);
uml_follow_java_set_name->setChecked(FALSE);
uml_follow_php_set_name->setChecked(FALSE);
uml_follow_python_set_name->setChecked(FALSE);
}
}
static const char * get_indent(QComboBox * cb)
{
int n = cb->currentItem();
return (n == 9)
? "\t"
: " " + (8 - n);
}
void GenerationSettingsDialog::accept() {
if (types_table->check()) {
QString enum_in = cpp_enum_in->text().stripWhiteSpace();
QString enum_out = cpp_enum_out->text().stripWhiteSpace();
QString enum_inout = cpp_enum_inout->text().stripWhiteSpace();
QString enum_return = cpp_enum_return->text().stripWhiteSpace();
if (enum_in.find("${type}") == -1) {
msg_critical(TR("Error"), TR("C++ 'in' enum argument default passing must contains ${type}"));
return;
}
if (enum_out.find("${type}") == -1) {
msg_critical(TR("Error"), TR("C++ 'out' enum argument default passing must contains ${type}"));
return;
}
if (enum_inout.find("${type}") == -1) {
msg_critical(TR("Error"), TR("C++ 'inout' enum argument default passing must contains ${type}"));
return;
}
if (enum_return.find("${type}") == -1) {
msg_critical(TR("Error"), TR("C++ 'return' enum argument default passing must contains ${type}"));
return;
}
QString in = cpp_in->text().stripWhiteSpace();
QString out = cpp_out->text().stripWhiteSpace();
QString inout = cpp_inout->text().stripWhiteSpace();
QString opreturn = cpp_return->text().stripWhiteSpace();
if (in.find("${type}") == -1) {
msg_critical(TR("Error"), TR("C++ 'in' argument default passing must contains ${type}"));
return;
}
if (out.find("${type}") == -1) {
msg_critical(TR("Error"), TR("C++ 'out' argument default passing must contains ${type}"));
return;
}
if (inout.find("${type}") == -1) {
msg_critical(TR("Error"), TR("C++ 'inout' argument default passing must contains ${type}"));
return;
}
if (opreturn.find("${type}") == -1) {
msg_critical(TR("Error"), TR("C++ 'return' argument default passing must contains ${type}"));
return;
}
types_table->update();
relation_stereotypes_table->update(GenerationSettings::nrelattrstereotypes,
GenerationSettings::relattr_stereotypes);
class_stereotypes_table->update(GenerationSettings::nclassstereotypes,
GenerationSettings::class_stereotypes);
cpp_include_table->update();
java_import_table->update();
python_import_table->update();
idl_include_table->update();
GenerationSettings::cpp_enum_in = enum_in;
GenerationSettings::cpp_enum_out = enum_out;
GenerationSettings::cpp_enum_inout = enum_inout;
GenerationSettings::cpp_enum_return = enum_return;
GenerationSettings::cpp_in = in;
GenerationSettings::cpp_out = out;
GenerationSettings::cpp_inout = inout;
GenerationSettings::cpp_return = opreturn;
GenerationSettings::cpp_h_extension = edcpp_h_extension->currentText().stripWhiteSpace();
GenerationSettings::cpp_src_extension = edcpp_src_extension->currentText().stripWhiteSpace();
GenerationSettings::java_extension = edjava_extension->currentText().stripWhiteSpace();
GenerationSettings::php_extension = edphp_extension->currentText().stripWhiteSpace();
GenerationSettings::python_extension = edpython_extension->currentText().stripWhiteSpace();
GenerationSettings::idl_extension = edidl_extension->currentText().stripWhiteSpace();
GenerationSettings::cpp_h_content = edcpp_h_content->text();
GenerationSettings::cpp_src_content = edcpp_src_content->text();
GenerationSettings::java_src_content = edjava_src_content->text();
GenerationSettings::php_src_content = edphp_src_content->text();
GenerationSettings::python_src_content = edpython_src_content->text();
GenerationSettings::idl_src_content = edidl_src_content->text();
switch (cpp_include_with_path_cb->currentItem()) {
case 0:
GenerationSettings::cpp_include_with_path = FALSE;
GenerationSettings::cpp_relative_path = FALSE;
GenerationSettings::cpp_root_relative_path = FALSE;
break;
case 1:
GenerationSettings::cpp_include_with_path = TRUE;
GenerationSettings::cpp_relative_path = FALSE;
GenerationSettings::cpp_root_relative_path = FALSE;
break;
case 2:
GenerationSettings::cpp_include_with_path = TRUE;
GenerationSettings::cpp_relative_path = TRUE;
GenerationSettings::cpp_root_relative_path = FALSE;
break;
default:
GenerationSettings::cpp_include_with_path = TRUE;
GenerationSettings::cpp_relative_path = FALSE;
GenerationSettings::cpp_root_relative_path = TRUE;
}
GenerationSettings::cpp_force_namespace_gen =
cpp_force_namespace_gen_cb->isChecked();
GenerationSettings::cpp_inline_force_incl_in_h =
cpp_inline_force_incl_in_h_cb->isChecked();
GenerationSettings::cpp_javadoc_comment = cpp_javadoc_cb->isChecked();
int i;
GenerationSettings::cpp_class_decl = edcpp_class_decl->text();
GenerationSettings::cpp_external_class_decl = edcpp_external_class_decl->text();
GenerationSettings::cpp_struct_decl = edcpp_struct_decl->text();
GenerationSettings::cpp_typedef_decl = edcpp_typedef_decl->text();
GenerationSettings::cpp_union_decl = edcpp_union_decl->text();
GenerationSettings::cpp_enum_decl = edcpp_enum_decl->text();
for (i = 0; i != 3; i += 1)
GenerationSettings::cpp_attr_decl[i] = edcpp_attr_decl[i]->text();
GenerationSettings::cpp_enum_item_decl = edcpp_enum_item_decl->text();
GenerationSettings::cpp_oper_decl = edcpp_oper_decl->text();
GenerationSettings::cpp_oper_def = edcpp_oper_def->text();
GenerationSettings::cpp_force_throw = cpp_force_throw_cb->isChecked();
GenerationSettings::cpp_indent_visibility = get_indent(indentvisi_cb);
GenerationSettings::java_class_decl = edjava_class_decl->text();
GenerationSettings::java_external_class_decl = edjava_external_class_decl->text();
GenerationSettings::java_interface_decl = edjava_interface_decl->text();
GenerationSettings::java_enum_decl = edjava_enum_decl->text();
GenerationSettings::java_enum_pattern_decl = edjava_enum_pattern_decl->text();
GenerationSettings::java_enum_item_decl = edjava_enum_item_decl->text();
GenerationSettings::java_enum_pattern_item_decl = edjava_enum_pattern_item_decl->text();
GenerationSettings::java_enum_pattern_item_case = edjava_enum_pattern_item_case->text();
for (i = 0; i != 3; i += 1)
GenerationSettings::java_attr_decl[i] = edjava_attr_decl[i]->text();
GenerationSettings::java_oper_def = edjava_oper_def->text();
GenerationSettings::java_javadoc_comment = java_javadoc_cb->isChecked();
GenerationSettings::java_force_package_gen = java_force_package_gen_cb->isChecked();
GenerationSettings::php_class_decl = edphp_class_decl->text();
GenerationSettings::php_external_class_decl = edphp_external_class_decl->text();
GenerationSettings::php_interface_decl = edphp_interface_decl->text();
GenerationSettings::php_enum_decl = edphp_enum_decl->text();
GenerationSettings::php_enum_item_decl = edphp_enum_item_decl->text();
GenerationSettings::php_attr_decl = edphp_attr_decl->text();
GenerationSettings::php_oper_def = edphp_oper_def->text();
GenerationSettings::php_javadoc_comment = php_javadoc_cb->isChecked();
switch (php_require_with_path_cb->currentItem()) {
case 0:
GenerationSettings::php_req_with_path = FALSE;
GenerationSettings::php_relative_path = FALSE;
GenerationSettings::php_root_relative_path = FALSE;
break;
case 1:
GenerationSettings::php_req_with_path = TRUE;
GenerationSettings::php_relative_path = FALSE;
GenerationSettings::php_root_relative_path = FALSE;
break;
case 2:
GenerationSettings::php_req_with_path = TRUE;
GenerationSettings::php_relative_path = TRUE;
GenerationSettings::php_root_relative_path = FALSE;
break;
default:
GenerationSettings::php_req_with_path = TRUE;
GenerationSettings::php_relative_path = FALSE;
GenerationSettings::php_root_relative_path = TRUE;
}
GenerationSettings::php_force_namespace_gen =
php_force_namespace_gen_cb->isChecked();
GenerationSettings::python_indent_step = get_indent(indentstep_cb);
GenerationSettings::python_2_2 = python_2_2_cb->isChecked();
GenerationSettings::python_3_operation = python_3_operation_cb->isChecked();
GenerationSettings::python_class_decl = edpython_class_decl->text();
GenerationSettings::python_external_class_decl = edpython_external_class_decl->text();
GenerationSettings::python_enum_decl = edpython_enum_decl->text();
GenerationSettings::python_enum_item_decl = edpython_enum_item_decl->text();
GenerationSettings::python_attr_decl[0] = edpython_attr_decl[0]->text();
GenerationSettings::python_attr_decl[1] = edpython_attr_decl[1]->text();
GenerationSettings::python_oper_def = edpython_oper_def->text();
GenerationSettings::python_initoper_def = edpython_initoper_def->text();
GenerationSettings::idl_interface_decl = edidl_interface_decl->text();
GenerationSettings::idl_valuetype_decl = edidl_valuetype_decl->text();
GenerationSettings::idl_struct_decl = edidl_struct_decl->text();
GenerationSettings::idl_union_decl = edidl_union_decl->text();
GenerationSettings::idl_enum_decl = edidl_enum_decl->text();
GenerationSettings::idl_exception_decl = edidl_exception_decl->text();
GenerationSettings::idl_typedef_decl = edidl_typedef_decl->text();
GenerationSettings::idl_external_class_decl = edidl_external_class_decl->text();
for (i = 0; i != 3; i += 1) {
GenerationSettings::idl_attr_decl[i] = edidl_attr_decl[i]->text();
GenerationSettings::idl_valuetype_attr_decl[i] = edidl_valuetype_attr_decl[i]->text();
GenerationSettings::idl_const_decl[i] = edidl_const_decl[i]->text();
GenerationSettings::idl_union_item_decl[i] = edidl_union_item_decl[i]->text();
}
GenerationSettings::idl_enum_item_decl = edidl_enum_item_decl->text();
GenerationSettings::idl_oper_decl = edidl_oper_decl->text();
int j;
for (i = 0; i != 2; i += 1)
for (j = 0; j != 3; j += 1)
GenerationSettings::cpp_rel_decl[i][j] =
edcpp_rel_decl[i][j]->text();
for (i = 0; i != 3; i += 1)
GenerationSettings::java_rel_decl[i] =
edjava_rel_decl[i]->text();
GenerationSettings::php_rel_decl = edphp_rel_decl->text();
for (i = 0; i != 3; i += 1) {
GenerationSettings::idl_rel_decl[i] =
edidl_rel_decl[i]->text();
GenerationSettings::idl_valuetype_rel_decl[i] =
edidl_valuetype_rel_decl[i]->text();
GenerationSettings::idl_union_rel_decl[i] =
edidl_union_rel_decl[i]->text();
}
for (i = 0; i != 2; i += 1)
for (j = 0; j != 2; j += 1)
GenerationSettings::python_rel_decl[i][j] =
edpython_rel_decl[i][j]->text();
//
GenerationSettings::cpp_get_visibility = cpp_get_visibility.value();
GenerationSettings::cpp_get_name = edcpp_get_name->text();
GenerationSettings::cpp_get_inline = cpp_get_inline_cb->isChecked();
GenerationSettings::cpp_get_const = cpp_get_const_cb->isChecked();
GenerationSettings::cpp_get_value_const = cpp_get_value_const_cb->isChecked();
GenerationSettings::cpp_set_visibility = cpp_set_visibility.value();
GenerationSettings::cpp_set_name = edcpp_set_name->text();
GenerationSettings::cpp_set_inline = cpp_set_inline_cb->isChecked();
GenerationSettings::cpp_set_param_const = cpp_set_param_const_cb->isChecked();
GenerationSettings::cpp_set_param_ref = cpp_set_param_ref_cb->isChecked();
GenerationSettings::noncpp_get_visibility = java_get_visibility.value();
GenerationSettings::java_get_name = edjava_get_name->text();
GenerationSettings::java_get_final = java_get_final_cb->isChecked();
GenerationSettings::noncpp_set_visibility = java_set_visibility.value();
GenerationSettings::java_set_name = edjava_set_name->text();
GenerationSettings::java_set_final = java_set_final_cb->isChecked();
GenerationSettings::java_set_param_final = java_set_param_final_cb->isChecked();
GenerationSettings::php_get_name = edphp_get_name->text();
GenerationSettings::php_get_final = php_get_final_cb->isChecked();
GenerationSettings::php_set_name = edphp_set_name->text();
GenerationSettings::php_set_final = php_set_final_cb->isChecked();
GenerationSettings::python_get_name = edpython_get_name->text();
GenerationSettings::python_set_name = edpython_set_name->text();
GenerationSettings::idl_get_name = edidl_get_name->text();
GenerationSettings::idl_set_name = edidl_set_name->text();
GenerationSettings::idl_set_oneway = idl_set_oneway_cb->isChecked();
//
GenerationSettings::umltypes.clear();
for (i = 0; i != GenerationSettings::nbuiltins; i += 1)
GenerationSettings::umltypes.append(GenerationSettings::builtins[i].uml);
//
GenerationSettings::artifact_default_description = edartifact_default_description->text();
GenerationSettings::class_default_description = edclass_default_description->text();
GenerationSettings::operation_default_description = edoperation_default_description->text();
GenerationSettings::attribute_default_description = edattribute_default_description->text();
GenerationSettings::relation_default_description = edrelation_default_description->text();
//
if (uml_follow_cpp_get_name->isChecked())
GenerationSettings::uml_get_name = CppView;
else if (uml_follow_java_get_name->isChecked())
GenerationSettings::uml_get_name = JavaView;
else if (uml_follow_php_get_name->isChecked())
GenerationSettings::uml_get_name = PhpView;
else if (uml_follow_python_get_name->isChecked())
GenerationSettings::uml_get_name = PythonView;
else if (uml_follow_idl_get_name->isChecked())
GenerationSettings::uml_get_name = IdlView;
else
GenerationSettings::uml_get_name = UmlView;
if (uml_follow_cpp_set_name->isChecked())
GenerationSettings::uml_set_name = CppView;
else if (uml_follow_java_set_name->isChecked())
GenerationSettings::uml_set_name = JavaView;
else if (uml_follow_php_set_name->isChecked())
GenerationSettings::uml_set_name = PhpView;
else if (uml_follow_python_set_name->isChecked())
GenerationSettings::uml_set_name = PythonView;
else if (uml_follow_idl_set_name->isChecked())
GenerationSettings::uml_set_name = IdlView;
else
GenerationSettings::uml_set_name = UmlView;
//
GenerationSettings::cpp_root_dir = add_last_slash(edcpproot->text());
GenerationSettings::java_root_dir = add_last_slash(edjavaroot->text());
GenerationSettings::php_root_dir = add_last_slash(edphproot->text());
GenerationSettings::python_root_dir = add_last_slash(edpythonroot->text());
GenerationSettings::idl_root_dir = add_last_slash(edidlroot->text());
//
QDialog::accept();
}
}
void GenerationSettingsDialog::cpproot_browse() {
QString dir =
QFileDialog::getExistingDirectory(edcpproot->text(), this, 0,
TR("C++ root directory"));
if (! dir.isNull()) {
edcpproot->setText(dir);
cpprelbutton->setText(Relative);
}
}
void GenerationSettingsDialog::javaroot_browse() {
QString dir =
QFileDialog::getExistingDirectory(edjavaroot->text(), this, 0,
TR("Java root directory"));
if (! dir.isNull()) {
edjavaroot->setText(dir);
javarelbutton->setText(Relative);
}
}
void GenerationSettingsDialog::phproot_browse() {
QString dir =
QFileDialog::getExistingDirectory(edphproot->text(), this, 0,
TR("Php root directory"));
if (! dir.isNull()) {
edphproot->setText(dir);
phprelbutton->setText(Relative);
}
}
void GenerationSettingsDialog::pythonroot_browse() {
QString dir =
QFileDialog::getExistingDirectory(edpythonroot->text(), this, 0,
TR("Python root directory"));
if (! dir.isNull()) {
edpythonroot->setText(dir);
pythonrelbutton->setText(Relative);
}
}
void GenerationSettingsDialog::idlroot_browse() {
QString dir =
QFileDialog::getExistingDirectory(edidlroot->text(), this, 0,
TR("Idl root directory"));
if (! dir.isNull()) {
edidlroot->setText(dir);
idlrelbutton->setText(Relative);
}
}
void GenerationSettingsDialog::relative(LineEdit * ed, QPushButton * button) {
QString root = BrowserView::get_dir().absPath();
const QString s = ed->text();
if (root.at(root.length() - 1) != QChar('/'))
root += '/';
if (button->text() == Relative) {
unsigned len = root.length();
if (
(s.find(root) == 0) &&
(s.length() >= len)) {
ed->setText(s.mid(len));
button->setText(Absolute);
}
}
else {
ed->setText(root + s);
button->setText(Relative);
}
}
void GenerationSettingsDialog::cpp_relative() {
relative(edcpproot, cpprelbutton);
}
void GenerationSettingsDialog::java_relative() {
relative(edjavaroot, javarelbutton);
}
void GenerationSettingsDialog::php_relative() {
relative(edphproot, phprelbutton);
}
void GenerationSettingsDialog::python_relative() {
relative(edpythonroot, pythonrelbutton);
}
void GenerationSettingsDialog::idl_relative() {
relative(edidlroot, idlrelbutton);
}
//
void GenerationSettingsDialog::java_get_visi_changed(int) {
php_get_visibility.follow(java_get_visibility);
python_get_visibility.follow(java_get_visibility);
}
void GenerationSettingsDialog::java_set_visi_changed(int) {
php_set_visibility.follow(java_set_visibility);
python_set_visibility.follow(java_set_visibility);
}
void GenerationSettingsDialog::php_get_visi_changed(int) {
java_get_visibility.follow(php_get_visibility);
python_get_visibility.follow(php_get_visibility);
}
void GenerationSettingsDialog::php_set_visi_changed(int) {
java_get_visibility.follow(php_set_visibility);
python_set_visibility.follow(php_set_visibility);
}
// TypesTable
TypesTable::TypesTable(QWidget * parent)
: StringTable(GenerationSettings::nbuiltins + 1, 9, parent, FALSE) {
horizontalHeader()->setLabel(0, "Uml");
horizontalHeader()->setLabel(1, "C++");
horizontalHeader()->setLabel(2, "Java");
horizontalHeader()->setLabel(3, "Idl");
horizontalHeader()->setLabel(4, TR("C++ in"));
horizontalHeader()->setLabel(5, TR("C++ out"));
horizontalHeader()->setLabel(6, TR("C++ in out"));
horizontalHeader()->setLabel(7, TR("C++ return"));
horizontalHeader()->setLabel(8, TR("do"));
int index;
for (index = 0; index < GenerationSettings::nbuiltins; index += 1){
Builtin & b = GenerationSettings::builtins[index];
setText(index, 0, b.uml);
setText(index, 1, b.cpp);
setText(index, 2, b.java);
setText(index, 3, b.idl);
setText(index, 4, b.cpp_in);
setText(index, 5, b.cpp_out);
setText(index, 6, b.cpp_inout);
setText(index, 7, b.cpp_return);
setText(index, 8, QString::null);
}
init_row(index);
for (index = 4; index < 8; index += 1)
setColumnStretchable (index, TRUE);
adjustColumn(8);
setColumnStretchable (8, FALSE);
}
void TypesTable::init_row(int index) {
setText(index, 0, QString::null);
setText(index, 1, QString::null);
setText(index, 2, QString::null);
setText(index, 3, QString::null);
setText(index, 4, "${type}");
setText(index, 5, "${type} &");
setText(index, 6, "${type} &");
setText(index, 7, "${type}");
}
void TypesTable::update() {
forceUpdateCells();
int n = numRows();
int index;
if (text(n - 1, 0).isEmpty())
n -= 1;
delete [] GenerationSettings::builtins;
GenerationSettings::nbuiltins = n;
GenerationSettings::builtins = new Builtin[n];
for (index = 0; index != n; index += 1) {
Builtin & b = GenerationSettings::builtins[index];
b.uml = text(index, 0).stripWhiteSpace();
b.cpp = text(index, 1).stripWhiteSpace();
b.java = text(index, 2).stripWhiteSpace();
b.idl = text(index, 3).stripWhiteSpace();
b.cpp_in = text(index, 4).stripWhiteSpace();
b.cpp_out = text(index, 5).stripWhiteSpace();
b.cpp_inout = text(index, 6).stripWhiteSpace();
b.cpp_return = text(index, 7).stripWhiteSpace();
}
}
bool TypesTable::check() {
int n = numRows();
int index;
if (text(n - 1, 0).isEmpty())
n -= 1;
for (index = 0; index != n; index += 1) {
int col;
for (col = 0; col != 4; col += 1) {
if (text(index, col).stripWhiteSpace().isEmpty()) {
char n[16];
sprintf(n, "%d", index + 1);
msg_critical(TR("Error"),
TR("row %1 : ", n) +
TR("%1 specification is mandatory", horizontalHeader()->label(col)));
return FALSE;
}
}
for (col = 4; col != 8; col += 1) {
if (text(index, col).find("${type}") == -1) {
char n[16];
sprintf(n, "%d", index + 1);
msg_critical(TR("Error"),
TR("row %1 : ", n) +
TR("%1 '%2' argument default passing does not contains ${type}",
(const char *) text(index, 0),
(const char *) horizontalHeader()->label(col)));
return FALSE;
}
}
}
return TRUE;
}
// StereotypesTable
StereotypesTable::StereotypesTable(QWidget * parent, int nst,
Stereotype * st, bool php)
: StringTable(nst + 1, (php) ? 7 : 6, parent, FALSE), with_php(php) {
horizontalHeader()->setLabel(0, "Uml");
horizontalHeader()->setLabel(1, "C++");
horizontalHeader()->setLabel(2, "Java");
if (with_php) {
horizontalHeader()->setLabel(3, "Php");
horizontalHeader()->setLabel(4, "Python");
horizontalHeader()->setLabel(5, "Idl");
horizontalHeader()->setLabel(6, TR("do"));
int index;
for (index = 0; index < nst; index += 1){
Stereotype & s = st[index];
setText(index, 0, s.uml);
setText(index, 1, s.cpp);
setText(index, 2, s.java);
setText(index, 3, s.php);
setText(index, 4, s.python);
setText(index, 5, s.idl);
setText(index, 6, QString::null);
}
init_row(index);
for (index = 0; index != 6; index += 1)
setColumnStretchable (index, TRUE);
adjustColumn(6);
setColumnStretchable (6, FALSE);
}
else {
horizontalHeader()->setLabel(3, "Python");
horizontalHeader()->setLabel(4, "Idl");
horizontalHeader()->setLabel(5, TR("do"));
int index;
for (index = 0; index < nst; index += 1){
Stereotype & s = st[index];
setText(index, 0, s.uml);
setText(index, 1, s.cpp);
setText(index, 2, s.java);
setText(index, 3, s.python);
setText(index, 4, s.idl);
setText(index, 5, QString::null);
}
init_row(index);
for (index = 0; index != 5; index += 1)
setColumnStretchable (index, TRUE);
adjustColumn(5);
setColumnStretchable (5, FALSE);
}
}
void StereotypesTable::init_row(int index) {
setText(index, 0, QString::null);
setText(index, 1, QString::null);
setText(index, 2, QString::null);
setText(index, 3, QString::null);
setText(index, 4, QString::null);
setText(index, 5, QString::null);
if (with_php)
setText(index, 6, QString::null);
}
void StereotypesTable::update(int & nst, Stereotype *& st) {
forceUpdateCells();
int n = numRows();
int index;
if (text(n - 1, 0).isEmpty())
n -= 1;
delete [] st;
nst = n;
st = new Stereotype[n];
if (with_php) {
for (index = 0; index != n; index += 1) {
Stereotype & s = st[index];
s.uml = text(index, 0).stripWhiteSpace();
s.cpp = text(index, 1).stripWhiteSpace();
s.java = text(index, 2).stripWhiteSpace();
s.php = text(index, 3).stripWhiteSpace();
s.python = text(index, 4).stripWhiteSpace();
s.idl = text(index, 5).stripWhiteSpace();
}
}
else {
for (index = 0; index != n; index += 1) {
Stereotype & s = st[index];
s.uml = text(index, 0).stripWhiteSpace();
s.cpp = text(index, 1).stripWhiteSpace();
s.java = text(index, 2).stripWhiteSpace();
s.python = text(index, 3).stripWhiteSpace();
s.idl = text(index, 4).stripWhiteSpace();
}
}
}
// IncludeTable
IncludeTable::IncludeTable(QWidget * parent, IncludesSpec & spc,
const char * title, const char * df)
: StringTable(spc.types.count() + 1, 3, parent, FALSE),
spec(spc), dflt(df) {
horizontalHeader()->setLabel(0, TR("External type"));
horizontalHeader()->setLabel(1, title);
horizontalHeader()->setLabel(2, TR("do"));
int index;
int sup = spc.types.count();
QStringList::Iterator it_type = spc.types.begin();
QStringList::Iterator it_incl = spc.includes.begin();
for (index = 0; index < sup; index += 1, it_type++, it_incl++) {
setText(index, 0, *it_type);
setItem(index, 1, new MLinesItem(this, *it_incl));
setText(index, 2, QString::null);
setRowStretchable(index, TRUE);
adjustRow(index);
}
setText(index, 0, QString::null);
setItem(index, 1, new MLinesItem(this, dflt));
setText(index, 2, QString::null);
setRowStretchable(index, TRUE);
adjustColumn(0);
setColumnStretchable(1, TRUE);
adjustColumn(2);
setColumnStretchable(2, FALSE);
connect(this, SIGNAL(pressed(int, int, int, const QPoint &)),
this, SLOT(button_pressed(int, int, int, const QPoint &)));
connect(this, SIGNAL(valueChanged(int, int)),
this, SLOT(value_changed(int, int)));
}
void IncludeTable::init_row(int index) {
setText(index, 0, QString::null);
setItem(index, 1, new MLinesItem(this, QString::null));
setText(index, 2, QString::null);
setRowStretchable(index, TRUE);
}
void IncludeTable::update() {
forceUpdateCells();
int n = numRows();
int index;
spec.types.clear();
spec.includes.clear();
for (index = 0; index != n; index += 1) {
QString t = text(index, 0).stripWhiteSpace();
if (! t.isEmpty()) {
spec.types.append(t);
spec.includes.append(text(index, 1));
}
}
}
|
gregsmirnov/bouml
|
src/dialog/GenerationSettingsDialog.cpp
|
C++
|
gpl-2.0
| 85,466
|
# coding=utf-8
import random
import time
import threading
import unittest
from lru_cache import LruCache
class TesLruCache(unittest.TestCase):
def test_cache_normal(self):
a = []
@LruCache(maxsize=2, timeout=1)
def foo(num):
a.append(num)
return num
foo(1)
foo(1)
self.assertEqual(a, [1])
def test_cache_none(self):
a = []
@LruCache(maxsize=2, timeout=1)
def foo(num):
a.append(num)
return None
foo(1)
foo(1)
self.assertEqual(a, [1])
def test_cache_when_timeout(self):
a = []
@LruCache(maxsize=2, timeout=1)
def foo(num):
a.append(num)
return num
foo(2)
time.sleep(2)
foo(2)
self.assertEqual(a, [2, 2])
def test_cache_when_cache_is_full(self):
a = []
@LruCache(maxsize=2, timeout=1)
def foo(num):
a.append(num)
return num
foo(1)
foo(2)
foo(3)
foo(1)
self.assertEqual(a, [1, 2, 3, 1])
def test_cache_with_multi_thread(self):
a = []
@LruCache(maxsize=10, timeout=1)
def foo(num):
a.append(num)
return num
for i in xrange(10):
threading.Thread(target=foo, args=(i, )).start()
main_thread = threading.currentThread()
for t in threading.enumerate():
if t is not main_thread:
t.join()
foo(random.randint(0, 9))
self.assertEqual(set(a), set(range(10)))
def test_cache_with_multi_thread_two_func(self):
a = []
@LruCache(maxsize=10, timeout=1)
def foo(num):
a.append(num)
return num
b = []
@LruCache(maxsize=10, timeout=1)
def bar(num):
b.append(num)
return num + 1
for i in xrange(10):
threading.Thread(target=foo, args=(i, )).start()
threading.Thread(target=bar, args=(i, )).start()
main_thread = threading.currentThread()
for t in threading.enumerate():
if t is not main_thread:
t.join()
feed = random.randint(0, 9)
self.assertEqual(foo(feed), feed)
self.assertEqual(bar(feed), feed + 1)
self.assertEqual(set(a), set(range(10)))
self.assertEqual(set(b), set(range(10)))
def test_cache_when_timeout_and_maxsize_is_none(self):
a = []
@LruCache()
def foo(num):
a.append(num)
return num
foo(1)
foo(1)
self.assertEqual(a, [1])
def test_cache_when_timeout_is_none(self):
a = []
@LruCache(maxsize=10)
def foo(num):
a.append(num)
return num
foo(1)
foo(1)
self.assertEqual(a, [1])
def test_cache_when_only_maxsize_is_none_normal(self):
a = []
@LruCache(timeout=2)
def foo(num):
a.append(num)
return num
foo(1)
foo(1)
self.assertEqual(a, [1])
def test_cache_when_only_maxsize_is_none_timeout(self):
a = []
@LruCache(timeout=1)
def foo(num):
a.append(num)
return num
foo(1)
time.sleep(2)
foo(1)
self.assertEqual(a, [1, 1])
def test_cache_when_only_maxsize_is_none_normal_method(self):
a = []
class Func(object):
@LruCache(timeout=2)
def foo(self, num):
a.append(num)
return num
fun = Func()
fun.foo(1)
fun.foo(1)
self.assertEqual(a, [1])
def test_cache_when_only_maxsize_is_none_normal_method_timeout(self):
a = []
class Func(object):
@LruCache(timeout=1)
def foo(self, num):
a.append(num)
return num
fun = Func()
fun.foo(1)
time.sleep(2)
fun.foo(1)
self.assertEqual(a, [1, 1])
def test_invalidate(self):
a = []
@LruCache()
def foo(num):
a.append(num)
return num
foo(1)
foo(1)
self.assertEqual(a, [1])
foo.invalidate(1)
foo(1)
self.assertEqual(a, [1, 1])
if __name__ == "__main__":
unittest.main()
|
Backflipz/plugin.video.excubed
|
resources/lib/cache/tests.py
|
Python
|
gpl-2.0
| 4,445
|
/////////////////////////////////////////////////////////////////////////////
// Name: src/dfb/dcclient.cpp
// Purpose: wxWindowDC, wxClientDC and wxPaintDC
// Author: Vaclav Slavik
// Created: 2006-08-10
// RCS-ID: $Id: dcclient.cpp 54748 2008-07-21 17:01:35Z VZ $
// Copyright: (c) 2006 REA Elektronik GmbH
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// ===========================================================================
// declarations
// ===========================================================================
// ---------------------------------------------------------------------------
// headers
// ---------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#include "wx/dcclient.h"
#ifndef WX_PRECOMP
#include "wx/toplevel.h"
#include "wx/window.h"
#endif
#include "wx/dfb/private.h"
#define TRACE_PAINT _T("paint")
// ===========================================================================
// implementation
// ===========================================================================
//-----------------------------------------------------------------------------
// helpers
//-----------------------------------------------------------------------------
// Returns subrect of the window that is not outside of its parent's
// boundaries ("hidden behind its borders"), recursively:
static wxRect GetUncoveredWindowArea(wxWindow *win)
{
wxRect r(win->GetSize());
if ( win->IsTopLevel() )
return r;
wxWindow *parent = win->GetParent();
if ( !parent )
return r;
// intersect with parent's uncovered area, after offsetting it into win's
// coordinates; this will remove parts of 'r' that are outside of the
// parent's area:
wxRect rp(GetUncoveredWindowArea(parent));
rp.Offset(-win->GetPosition());
rp.Offset(-parent->GetClientAreaOrigin());
r.Intersect(rp);
return r;
}
// creates a dummy surface that has the same format as the real window's
// surface, but is not visible and so can be painted on even if the window
// is hidden
static
wxIDirectFBSurfacePtr CreateDummySurface(wxWindow *win, const wxRect *rect)
{
wxLogTrace(TRACE_PAINT, _T("%p ('%s'): creating dummy DC surface"),
win, win->GetName().c_str());
wxSize size(rect ? rect->GetSize() : win->GetSize());
return win->GetDfbSurface()->CreateCompatible
(
size,
wxIDirectFBSurface::CreateCompatible_NoBackBuffer
);
}
//-----------------------------------------------------------------------------
// wxWindowDC
//-----------------------------------------------------------------------------
IMPLEMENT_DYNAMIC_CLASS(wxWindowDC, wxDC)
wxWindowDC::wxWindowDC(wxWindow *win)
{
InitForWin(win, NULL);
}
void wxWindowDC::InitForWin(wxWindow *win, const wxRect *rect)
{
wxCHECK_RET( win, _T("invalid window") );
m_win = win;
// obtain the surface used for painting:
wxPoint origin;
wxIDirectFBSurfacePtr surface;
wxRect rectOrig(rect ? *rect : wxRect(win->GetSize()));
wxRect r;
if ( !win->IsShownOnScreen() )
{
// leave 'r' rectangle empty to indicate the window is not visible,
// see below (below "create the surface:") for how is this case handled
}
else
{
// compute painting rectangle after clipping if we're in PaintWindow
// code, otherwise paint on the entire window:
r = rectOrig;
const wxRegion& updateRegion = win->GetUpdateRegion();
if ( win->GetTLW()->IsPainting() && !updateRegion.IsEmpty() )
{
r.Intersect(updateRegion.AsRect());
wxCHECK_RET( !r.IsEmpty(), _T("invalid painting rectangle") );
// parent TLW will flip the entire surface when painting is done
m_shouldFlip = false;
}
else
{
// One of two things happened:
// (1) the TLW is not being painted by PaintWindow() now; or
// (2) we're drawing on some window other than the one that is
// currently painted on by PaintWindow()
// In either case, we need to flip the surface when we're done
// painting and we don't have to use updateRegion for clipping.
// OTOH, if the window is (partially) hidden by being
// out of its parent's area, we must clip the surface accordingly.
r.Intersect(GetUncoveredWindowArea(win));
m_shouldFlip = true; // paint the results immediately
}
}
// create the surface:
if ( r.IsEmpty() )
{
// we're painting on invisible window: the changes won't have any
// effect, as the window will be repainted anyhow when it is shown,
// but we still need a valid DC so that e.g. text extents can be
// measured, so let's create a dummy surface that has the same
// format as the real one would have and let the code paint on it:
surface = CreateDummySurface(win, rect);
// painting on hidden window has no effect on TLW's surface, don't
// waste time flipping the dummy surface:
m_shouldFlip = false;
}
else
{
m_winRect = r;
DFBRectangle dfbrect = { r.x, r.y, r.width, r.height };
surface = win->GetDfbSurface()->GetSubSurface(&dfbrect);
// if the DC was clipped thanks to rectPaint, we must adjust the
// origin accordingly; but we do *not* adjust for 'rect', because
// rect.GetPosition() has coordinates (0,0) in the DC:
origin.x = rectOrig.x - r.x;
origin.y = rectOrig.y - r.y;
// m_shouldFlip was set in the "if" block above this one
}
if ( !surface )
return;
wxLogTrace(TRACE_PAINT,
_T("%p ('%s'): creating DC for area [%i,%i,%i,%i], clipped to [%i,%i,%i,%i], origin [%i,%i]"),
win, win->GetName().c_str(),
rectOrig.x, rectOrig.y, rectOrig.GetRight(), rectOrig.GetBottom(),
r.x, r.y, r.GetRight(), r.GetBottom(),
origin.x, origin.y);
DFBInit(surface);
SetFont(win->GetFont());
// offset coordinates to account for subsurface's origin coordinates:
SetDeviceOrigin(origin.x, origin.y);
}
wxWindowDC::~wxWindowDC()
{
wxIDirectFBSurfacePtr surface(GetDirectFBSurface());
if ( !surface )
return;
// if no painting was done on the DC, we don't have to flip the surface:
if ( !m_isBBoxValid )
return;
if ( m_shouldFlip )
{
// paint overlays on top of the surface being drawn to by this DC
// before showing anything on the screen:
m_win->PaintOverlays(m_winRect);
DFBSurfaceCapabilities caps = DSCAPS_NONE;
surface->GetCapabilities(&caps);
if ( caps & DSCAPS_DOUBLE )
{
// FIXME: flip only modified parts of the surface
surface->FlipToFront();
}
// else: the surface is not double-buffered and so cannot be flipped
}
// else: don't flip the surface, wxTLW will do it when it finishes
// painting of its invalidated areas
}
//-----------------------------------------------------------------------------
// wxClientDC
//-----------------------------------------------------------------------------
IMPLEMENT_DYNAMIC_CLASS(wxClientDC, wxWindowDC)
wxClientDC::wxClientDC(wxWindow *win)
{
wxCHECK_RET( win, _T("invalid window") );
wxRect rect = win->GetClientRect();
InitForWin(win, &rect);
}
//-----------------------------------------------------------------------------
// wxPaintDC
//-----------------------------------------------------------------------------
IMPLEMENT_DYNAMIC_CLASS(wxPaintDC, wxWindowDC)
|
hajuuk/R7000
|
ap/gpl/amule/wxWidgets-2.8.12/src/dfb/dcclient.cpp
|
C++
|
gpl-2.0
| 7,988
|
<?php
/**
* SlioPress AJAX Process Execution.
*
* @package SlioPress
* @subpackage Administration
*
* @link http://codex.wordpress.org/AJAX_in_Plugins
*/
/**
* Executing AJAX process.
*
* @since 2.1.0
*/
define( 'DOING_AJAX', true );
if ( ! defined( 'WP_ADMIN' ) ) {
define( 'WP_ADMIN', true );
}
/** Load SlioPress Bootstrap */
require_once( dirname( dirname( __FILE__ ) ) . '/load.php' );
/** Allow for cross-domain requests (from the frontend). */
send_origin_headers();
// Require an action parameter
if ( empty( $_REQUEST['action'] ) )
die( '0' );
/** Load SlioPress Administration APIs */
require_once( ABSPATH . 'admin/includes/admin.php' );
/** Load Ajax Handlers for SlioPress Core */
require_once( ABSPATH . 'admin/includes/ajax-actions.php' );
@header( 'Content-Type: text/html; charset=' . get_option( 'blog_charset' ) );
@header( 'X-Robots-Tag: noindex' );
send_nosniff_header();
nocache_headers();
/** This action is documented in admin/admin.php */
do_action( 'admin_init' );
$core_actions_get = array(
'fetch-list', 'ajax-tag-search', 'compression-test', 'imgedit-preview', 'oembed-cache',
'autocomplete-user', 'dashboard-widgets', 'logged-in',
);
$core_actions_post = array(
'oembed-cache', 'image-editor', 'delete-comment', 'delete-tag', 'delete-link',
'delete-meta', 'delete-post', 'trash-post', 'untrash-post', 'delete-page', 'dim-comment',
'add-link-category', 'add-tag', 'get-tagcloud', 'get-comments', 'replyto-comment',
'edit-comment', 'add-menu-item', 'add-meta', 'add-user', 'closed-postboxes',
'hidden-columns', 'update-welcome-panel', 'menu-get-metabox', 'link-ajax',
'menu-locations-save', 'menu-quick-search', 'meta-box-order', 'get-permalink',
'sample-permalink', 'inline-save', 'inline-save-tax', 'find_posts', 'widgets-order',
'save-widget', 'set-post-thumbnail', 'date_format', 'time_format', 'fullscreen-save-post',
'remove-post-lock', 'dismiss-pointer', 'upload-attachment', 'get-attachment',
'query-attachments', 'save-attachment', 'save-attachment-compat', 'send-link-to-editor',
'send-attachment-to-editor', 'save-attachment-order', 'heartbeat', 'get-revision-diffs',
'save-user-color-scheme', 'update-widget', 'query-themes', 'parse-embed', 'set-attachment-thumbnail',
'parse-media-shortcode', 'destroy-sessions'
);
// Register core Ajax calls.
if ( ! empty( $_GET['action'] ) && in_array( $_GET['action'], $core_actions_get ) )
add_action( 'wp_ajax_' . $_GET['action'], 'wp_ajax_' . str_replace( '-', '_', $_GET['action'] ), 1 );
if ( ! empty( $_POST['action'] ) && in_array( $_POST['action'], $core_actions_post ) )
add_action( 'wp_ajax_' . $_POST['action'], 'wp_ajax_' . str_replace( '-', '_', $_POST['action'] ), 1 );
add_action( 'wp_ajax_nopriv_heartbeat', 'wp_ajax_nopriv_heartbeat', 1 );
if ( is_user_logged_in() ) {
/**
* Fires authenticated AJAX actions for logged-in users.
*
* The dynamic portion of the hook name, `$_REQUEST['action']`,
* refers to the name of the AJAX action callback being fired.
*
* @since 2.1.0
*/
do_action( 'wp_ajax_' . $_REQUEST['action'] );
} else {
/**
* Fires non-authenticated AJAX actions for logged-out users.
*
* The dynamic portion of the hook name, `$_REQUEST['action']`,
* refers to the name of the AJAX action callback being fired.
*
* @since 2.8.0
*/
do_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] );
}
// Default status
die( '0' );
|
muhammadzulfikar/sliopress
|
admin/admin-ajax.php
|
PHP
|
gpl-2.0
| 3,402
|
/* RIPng routemap.
* Copyright (C) 1999 Kunihiro Ishiguro
*
* This file is part of GNU Kroute.
*
* GNU Kroute 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.
*
* GNU Kroute is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with GNU Kroute; see the file COPYING. If not, write to the Free
* Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
#include <kroute.h>
#include "if.h"
#include "memory.h"
#include "prefix.h"
#include "routemap.h"
#include "command.h"
#include "sockunion.h"
#include "ripngd/ripngd.h"
struct rip_metric_modifier
{
enum
{
metric_increment,
metric_decrement,
metric_absolute
} type;
u_char metric;
};
static int
ripng_route_match_add (struct vty *vty, struct route_map_index *index,
const char *command, const char *arg)
{
int ret;
ret = route_map_add_match (index, command, arg);
if (ret)
{
switch (ret)
{
case RMAP_RULE_MISSING:
vty_out (vty, "Can't find rule.%s", VTY_NEWLINE);
return CMD_WARNING;
case RMAP_COMPILE_ERROR:
vty_out (vty, "Argument is malformed.%s", VTY_NEWLINE);
return CMD_WARNING;
}
}
return CMD_SUCCESS;
}
static int
ripng_route_match_delete (struct vty *vty, struct route_map_index *index,
const char *command, const char *arg)
{
int ret;
ret = route_map_delete_match (index, command, arg);
if (ret)
{
switch (ret)
{
case RMAP_RULE_MISSING:
vty_out (vty, "Can't find rule.%s", VTY_NEWLINE);
return CMD_WARNING;
case RMAP_COMPILE_ERROR:
vty_out (vty, "Argument is malformed.%s", VTY_NEWLINE);
return CMD_WARNING;
}
}
return CMD_SUCCESS;
}
static int
ripng_route_set_add (struct vty *vty, struct route_map_index *index,
const char *command, const char *arg)
{
int ret;
ret = route_map_add_set (index, command, arg);
if (ret)
{
switch (ret)
{
case RMAP_RULE_MISSING:
vty_out (vty, "Can't find rule.%s", VTY_NEWLINE);
return CMD_WARNING;
case RMAP_COMPILE_ERROR:
vty_out (vty, "Argument is malformed.%s", VTY_NEWLINE);
return CMD_WARNING;
}
}
return CMD_SUCCESS;
}
static int
ripng_route_set_delete (struct vty *vty, struct route_map_index *index,
const char *command, const char *arg)
{
int ret;
ret = route_map_delete_set (index, command, arg);
if (ret)
{
switch (ret)
{
case RMAP_RULE_MISSING:
vty_out (vty, "Can't find rule.%s", VTY_NEWLINE);
return CMD_WARNING;
case RMAP_COMPILE_ERROR:
vty_out (vty, "Argument is malformed.%s", VTY_NEWLINE);
return CMD_WARNING;
}
}
return CMD_SUCCESS;
}
/* `match metric METRIC' */
/* Match function return 1 if match is success else return zero. */
static route_map_result_t
route_match_metric (void *rule, struct prefix *prefix,
route_map_object_t type, void *object)
{
u_int32_t *metric;
struct ripng_info *rinfo;
if (type == RMAP_RIPNG)
{
metric = rule;
rinfo = object;
if (rinfo->metric == *metric)
return RMAP_MATCH;
else
return RMAP_NOMATCH;
}
return RMAP_NOMATCH;
}
/* Route map `match metric' match statement. `arg' is METRIC value */
static void *
route_match_metric_compile (const char *arg)
{
u_int32_t *metric;
metric = XMALLOC (MTYPE_ROUTE_MAP_COMPILED, sizeof (u_int32_t));
*metric = atoi (arg);
if(*metric > 0)
return metric;
XFREE (MTYPE_ROUTE_MAP_COMPILED, metric);
return NULL;
}
/* Free route map's compiled `match metric' value. */
static void
route_match_metric_free (void *rule)
{
XFREE (MTYPE_ROUTE_MAP_COMPILED, rule);
}
/* Route map commands for metric matching. */
static struct route_map_rule_cmd route_match_metric_cmd =
{
"metric",
route_match_metric,
route_match_metric_compile,
route_match_metric_free
};
/* `match interface IFNAME' */
/* Match function return 1 if match is success else return zero. */
static route_map_result_t
route_match_interface (void *rule, struct prefix *prefix,
route_map_object_t type, void *object)
{
struct ripng_info *rinfo;
struct interface *ifp;
char *ifname;
if (type == RMAP_RIPNG)
{
ifname = rule;
ifp = if_lookup_by_name(ifname);
if (!ifp)
return RMAP_NOMATCH;
rinfo = object;
if (rinfo->ifindex == ifp->ifindex)
return RMAP_MATCH;
else
return RMAP_NOMATCH;
}
return RMAP_NOMATCH;
}
/* Route map `match interface' match statement. `arg' is IFNAME value */
static void *
route_match_interface_compile (const char *arg)
{
return XSTRDUP (MTYPE_ROUTE_MAP_COMPILED, arg);
}
static void
route_match_interface_free (void *rule)
{
XFREE (MTYPE_ROUTE_MAP_COMPILED, rule);
}
static struct route_map_rule_cmd route_match_interface_cmd =
{
"interface",
route_match_interface,
route_match_interface_compile,
route_match_interface_free
};
/* `match tag TAG' */
/* Match function return 1 if match is success else return zero. */
static route_map_result_t
route_match_tag (void *rule, struct prefix *prefix,
route_map_object_t type, void *object)
{
u_short *tag;
struct ripng_info *rinfo;
if (type == RMAP_RIPNG)
{
tag = rule;
rinfo = object;
/* The information stored by rinfo is host ordered. */
if (rinfo->tag == *tag)
return RMAP_MATCH;
else
return RMAP_NOMATCH;
}
return RMAP_NOMATCH;
}
/* Route map `match tag' match statement. `arg' is TAG value */
static void *
route_match_tag_compile (const char *arg)
{
u_short *tag;
tag = XMALLOC (MTYPE_ROUTE_MAP_COMPILED, sizeof (u_short));
*tag = atoi (arg);
return tag;
}
/* Free route map's compiled `match tag' value. */
static void
route_match_tag_free (void *rule)
{
XFREE (MTYPE_ROUTE_MAP_COMPILED, rule);
}
/* Route map commands for tag matching. */
static struct route_map_rule_cmd route_match_tag_cmd =
{
"tag",
route_match_tag,
route_match_tag_compile,
route_match_tag_free
};
/* `set metric METRIC' */
/* Set metric to attribute. */
static route_map_result_t
route_set_metric (void *rule, struct prefix *prefix,
route_map_object_t type, void *object)
{
if (type == RMAP_RIPNG)
{
struct rip_metric_modifier *mod;
struct ripng_info *rinfo;
mod = rule;
rinfo = object;
if (mod->type == metric_increment)
rinfo->metric_out += mod->metric;
else if (mod->type == metric_decrement)
rinfo->metric_out-= mod->metric;
else if (mod->type == metric_absolute)
rinfo->metric_out = mod->metric;
if (rinfo->metric_out < 1)
rinfo->metric_out = 1;
if (rinfo->metric_out > RIPNG_METRIC_INFINITY)
rinfo->metric_out = RIPNG_METRIC_INFINITY;
rinfo->metric_set = 1;
}
return RMAP_OKAY;
}
/* set metric compilation. */
static void *
route_set_metric_compile (const char *arg)
{
int len;
const char *pnt;
int type;
long metric;
char *endptr = NULL;
struct rip_metric_modifier *mod;
len = strlen (arg);
pnt = arg;
if (len == 0)
return NULL;
/* Examine first character. */
if (arg[0] == '+')
{
type = metric_increment;
pnt++;
}
else if (arg[0] == '-')
{
type = metric_decrement;
pnt++;
}
else
type = metric_absolute;
/* Check beginning with digit string. */
if (*pnt < '0' || *pnt > '9')
return NULL;
/* Convert string to integer. */
metric = strtol (pnt, &endptr, 10);
if (metric == LONG_MAX || *endptr != '\0')
return NULL;
/* Commented out by Hasso Tepper, to avoid problems in vtysh. */
/* if (metric < 0 || metric > RIPNG_METRIC_INFINITY) */
if (metric < 0)
return NULL;
mod = XMALLOC (MTYPE_ROUTE_MAP_COMPILED,
sizeof (struct rip_metric_modifier));
mod->type = type;
mod->metric = metric;
return mod;
}
/* Free route map's compiled `set metric' value. */
static void
route_set_metric_free (void *rule)
{
XFREE (MTYPE_ROUTE_MAP_COMPILED, rule);
}
static struct route_map_rule_cmd route_set_metric_cmd =
{
"metric",
route_set_metric,
route_set_metric_compile,
route_set_metric_free,
};
/* `set ipv6 next-hop local IP_ADDRESS' */
/* Set nexthop to object. ojbect must be pointer to struct attr. */
static route_map_result_t
route_set_ipv6_nexthop_local (void *rule, struct prefix *prefix,
route_map_object_t type, void *object)
{
struct in6_addr *address;
struct ripng_info *rinfo;
if(type == RMAP_RIPNG)
{
/* Fetch routemap's rule information. */
address = rule;
rinfo = object;
/* Set next hop value. */
rinfo->nexthop_out = *address;
}
return RMAP_OKAY;
}
/* Route map `ipv6 nexthop local' compile function. Given string is converted
to struct in6_addr structure. */
static void *
route_set_ipv6_nexthop_local_compile (const char *arg)
{
int ret;
struct in6_addr *address;
address = XMALLOC (MTYPE_ROUTE_MAP_COMPILED, sizeof (struct in6_addr));
ret = inet_pton (AF_INET6, arg, address);
if (ret == 0)
{
XFREE (MTYPE_ROUTE_MAP_COMPILED, address);
return NULL;
}
return address;
}
/* Free route map's compiled `ipv6 nexthop local' value. */
static void
route_set_ipv6_nexthop_local_free (void *rule)
{
XFREE (MTYPE_ROUTE_MAP_COMPILED, rule);
}
/* Route map commands for ipv6 nexthop local set. */
static struct route_map_rule_cmd route_set_ipv6_nexthop_local_cmd =
{
"ipv6 next-hop local",
route_set_ipv6_nexthop_local,
route_set_ipv6_nexthop_local_compile,
route_set_ipv6_nexthop_local_free
};
/* `set tag TAG' */
/* Set tag to object. ojbect must be pointer to struct attr. */
static route_map_result_t
route_set_tag (void *rule, struct prefix *prefix,
route_map_object_t type, void *object)
{
u_short *tag;
struct ripng_info *rinfo;
if(type == RMAP_RIPNG)
{
/* Fetch routemap's rule information. */
tag = rule;
rinfo = object;
/* Set next hop value. */
rinfo->tag_out = *tag;
}
return RMAP_OKAY;
}
/* Route map `tag' compile function. Given string is converted
to u_short. */
static void *
route_set_tag_compile (const char *arg)
{
u_short *tag;
tag = XMALLOC (MTYPE_ROUTE_MAP_COMPILED, sizeof (u_short));
*tag = atoi (arg);
return tag;
}
/* Free route map's compiled `ip nexthop' value. */
static void
route_set_tag_free (void *rule)
{
XFREE (MTYPE_ROUTE_MAP_COMPILED, rule);
}
/* Route map commands for tag set. */
static struct route_map_rule_cmd route_set_tag_cmd =
{
"tag",
route_set_tag,
route_set_tag_compile,
route_set_tag_free
};
#define MATCH_STR "Match values from routing table\n"
#define SET_STR "Set values in destination routing protocol\n"
DEFUN (match_metric,
match_metric_cmd,
"match metric <0-4294967295>",
MATCH_STR
"Match metric of route\n"
"Metric value\n")
{
return ripng_route_match_add (vty, vty->index, "metric", argv[0]);
}
DEFUN (no_match_metric,
no_match_metric_cmd,
"no match metric",
NO_STR
MATCH_STR
"Match metric of route\n")
{
if (argc == 0)
return ripng_route_match_delete (vty, vty->index, "metric", NULL);
return ripng_route_match_delete (vty, vty->index, "metric", argv[0]);
}
ALIAS (no_match_metric,
no_match_metric_val_cmd,
"no match metric <0-4294967295>",
NO_STR
MATCH_STR
"Match metric of route\n"
"Metric value\n")
DEFUN (match_interface,
match_interface_cmd,
"match interface WORD",
MATCH_STR
"Match first hop interface of route\n"
"Interface name\n")
{
return ripng_route_match_add (vty, vty->index, "interface", argv[0]);
}
DEFUN (no_match_interface,
no_match_interface_cmd,
"no match interface",
NO_STR
MATCH_STR
"Match first hop interface of route\n")
{
if (argc == 0)
return ripng_route_match_delete (vty, vty->index, "interface", NULL);
return ripng_route_match_delete (vty, vty->index, "interface", argv[0]);
}
ALIAS (no_match_interface,
no_match_interface_val_cmd,
"no match interface WORD",
NO_STR
MATCH_STR
"Match first hop interface of route\n"
"Interface name\n")
DEFUN (match_tag,
match_tag_cmd,
"match tag <0-65535>",
MATCH_STR
"Match tag of route\n"
"Metric value\n")
{
return ripng_route_match_add (vty, vty->index, "tag", argv[0]);
}
DEFUN (no_match_tag,
no_match_tag_cmd,
"no match tag",
NO_STR
MATCH_STR
"Match tag of route\n")
{
if (argc == 0)
return ripng_route_match_delete (vty, vty->index, "tag", NULL);
return ripng_route_match_delete (vty, vty->index, "tag", argv[0]);
}
ALIAS (no_match_tag,
no_match_tag_val_cmd,
"no match tag <0-65535>",
NO_STR
MATCH_STR
"Match tag of route\n"
"Metric value\n")
/* set functions */
DEFUN (set_metric,
set_metric_cmd,
"set metric <0-4294967295>",
"Set value\n"
"Metric value for destination routing protocol\n"
"Metric value\n")
{
return ripng_route_set_add (vty, vty->index, "metric", argv[0]);
}
DEFUN (no_set_metric,
no_set_metric_cmd,
"no set metric",
NO_STR
SET_STR
"Metric value for destination routing protocol\n")
{
if (argc == 0)
return ripng_route_set_delete (vty, vty->index, "metric", NULL);
return ripng_route_set_delete (vty, vty->index, "metric", argv[0]);
}
ALIAS (no_set_metric,
no_set_metric_val_cmd,
"no set metric <0-4294967295>",
NO_STR
SET_STR
"Metric value for destination routing protocol\n"
"Metric value\n")
DEFUN (set_ipv6_nexthop_local,
set_ipv6_nexthop_local_cmd,
"set ipv6 next-hop local X:X::X:X",
SET_STR
IPV6_STR
"IPv6 next-hop address\n"
"IPv6 local address\n"
"IPv6 address of next hop\n")
{
union sockunion su;
int ret;
ret = str2sockunion (argv[0], &su);
if (ret < 0)
{
vty_out (vty, "%% Malformed next-hop local address%s", VTY_NEWLINE);
return CMD_WARNING;
}
return ripng_route_set_add (vty, vty->index, "ipv6 next-hop local", argv[0]);
}
DEFUN (no_set_ipv6_nexthop_local,
no_set_ipv6_nexthop_local_cmd,
"no set ipv6 next-hop local",
NO_STR
SET_STR
IPV6_STR
"IPv6 next-hop address\n"
"IPv6 local address\n")
{
if (argc == 0)
return ripng_route_set_delete (vty, vty->index, "ipv6 next-hop local", NULL);
return ripng_route_set_delete (vty, vty->index, "ipv6 next-hop local", argv[0]);
}
ALIAS (no_set_ipv6_nexthop_local,
no_set_ipv6_nexthop_local_val_cmd,
"no set ipv6 next-hop local X:X::X:X",
NO_STR
SET_STR
IPV6_STR
"IPv6 next-hop address\n"
"IPv6 local address\n"
"IPv6 address of next hop\n")
DEFUN (set_tag,
set_tag_cmd,
"set tag <0-65535>",
SET_STR
"Tag value for routing protocol\n"
"Tag value\n")
{
return ripng_route_set_add (vty, vty->index, "tag", argv[0]);
}
DEFUN (no_set_tag,
no_set_tag_cmd,
"no set tag",
NO_STR
SET_STR
"Tag value for routing protocol\n")
{
if (argc == 0)
return ripng_route_set_delete (vty, vty->index, "tag", NULL);
return ripng_route_set_delete (vty, vty->index, "tag", argv[0]);
}
ALIAS (no_set_tag,
no_set_tag_val_cmd,
"no set tag <0-65535>",
NO_STR
SET_STR
"Tag value for routing protocol\n"
"Tag value\n")
void
ripng_route_map_reset ()
{
/* XXX ??? */
;
}
void
ripng_route_map_init ()
{
route_map_init ();
route_map_init_vty ();
route_map_install_match (&route_match_metric_cmd);
route_map_install_match (&route_match_interface_cmd);
route_map_install_match (&route_match_tag_cmd);
route_map_install_set (&route_set_metric_cmd);
route_map_install_set (&route_set_ipv6_nexthop_local_cmd);
route_map_install_set (&route_set_tag_cmd);
install_element (RMAP_NODE, &match_metric_cmd);
install_element (RMAP_NODE, &no_match_metric_cmd);
install_element (RMAP_NODE, &no_match_metric_val_cmd);
install_element (RMAP_NODE, &match_interface_cmd);
install_element (RMAP_NODE, &no_match_interface_cmd);
install_element (RMAP_NODE, &no_match_interface_val_cmd);
install_element (RMAP_NODE, &match_tag_cmd);
install_element (RMAP_NODE, &no_match_tag_cmd);
install_element (RMAP_NODE, &no_match_tag_val_cmd);
install_element (RMAP_NODE, &set_metric_cmd);
install_element (RMAP_NODE, &no_set_metric_cmd);
install_element (RMAP_NODE, &no_set_metric_val_cmd);
install_element (RMAP_NODE, &set_ipv6_nexthop_local_cmd);
install_element (RMAP_NODE, &no_set_ipv6_nexthop_local_cmd);
install_element (RMAP_NODE, &no_set_ipv6_nexthop_local_val_cmd);
install_element (RMAP_NODE, &set_tag_cmd);
install_element (RMAP_NODE, &no_set_tag_cmd);
install_element (RMAP_NODE, &no_set_tag_val_cmd);
}
|
AirbornWdd/qpimd
|
ripngd/ripng_routemap.c
|
C
|
gpl-2.0
| 17,312
|
<div class="header navbar navbar-default navbar-static-top">
<div class="container">
<div class="navbar-header">
<button class="navbar-toggle btn navbar-btn" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand logo-v1" href="http://www.keshenghl.com/">
<img src="../../assets/img/logo.png" id="logoimg" alt="科盛护栏,首页">
</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav" style="font-size:18px;">
<li class="{{= locals.navID == '1' ? 'active' : '' }}"><a href="http://www.keshenghl.com/"> 首 页 </a></li>
<li class="{{= locals.navID == '2' ? 'active' : '' }}"><a href="http://www.keshenghl.com/company/info"> 关于我们 </a></li>
<li class="{{= locals.navID == '3' ? 'active' : '' }}"><a href="http://www.keshenghl.com/list/chanpin"> 产品实例 </a></li>
<li class="{{= locals.navID == '4' ? 'active' : '' }}"><a href="http://www.keshenghl.com/list/xinwen"> 业内新闻 </a></li>
<li class="{{= locals.navID == '5' ? 'active' : '' }}"><a href="http://www.keshenghl.com/company/contact"> 联系我们 </a></li>
<li class="{{= locals.navID == '6' ? 'active' : '' }}"><a href="http://www.keshenghl.com/company/Honors"> 荣誉资质 </a></li>
</ul>
</div>
</div>
</div>
|
victzero/wanzi
|
wanzi/views/open/include/header.html
|
HTML
|
gpl-2.0
| 1,569
|
/*
* Copyright (C) 2006 The Concord Consortium, Inc.,
* 25 Love Lane, Concord, MA 01742
*
* 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
*
* END LICENSE */
/** Gamma function
*
* @author onnie Chen
* Concord Consortium 8/2/2003
*/
package org.nfunk.jep.function;
import java.util.Stack;
import org.nfunk.jep.ParseException;
public class Gamma extends PostfixMathCommand {
public Gamma() {
numberOfParameters = 1;
}
public String toString() {
return "The gamma function";
}
public void run(Stack inStack) throws ParseException {
checkStack(inStack);// check the stack
Object param = inStack.pop();
inStack.push(gamma(param));// push the result on the inStack
}
public Object gamma(Object param) throws ParseException {
if (param instanceof Number) {
double x = ((Number) param).doubleValue();
if (x > 0)
return new Double(compute(x));
return new Double(Double.NaN);
}
throw new ParseException("Invalid parameter type");
}
/**
* @param x
* a double value
* @return the Gamma function of the value.
* <P>
* Converted to Java from<BR>
* Cephes Math Library Release 2.2: July, 1992<BR>
* Copyright 1984, 1987, 1989, 1992 by Stephen L. Moshier<BR>
* Direct inquiries to 30 Frost Street, Cambridge, MA 02140<BR>
*/
public static double compute(double x) throws ArithmeticException {
double P[] = { 1.60119522476751861407E-4, 1.19135147006586384913E-3, 1.04213797561761569935E-2,
4.76367800457137231464E-2, 2.07448227648435975150E-1, 4.94214826801497100753E-1,
9.99999999999999996796E-1 };
double Q[] = { -2.31581873324120129819E-5, 5.39605580493303397842E-4, -4.45641913851797240494E-3,
1.18139785222060435552E-2, 3.58236398605498653373E-2, -2.34591795718243348568E-1,
7.14304917030273074085E-2, 1.00000000000000000320E0 };
double p, z;
double q = Math.abs(x);
if (q > 33.0) {
if (x < 0.0) {
p = Math.floor(q);
if (p == q)
throw new ArithmeticException("gamma: overflow");
z = q - p;
if (z > 0.5) {
p += 1.0;
z = q - p;
}
z = q * Math.sin(Math.PI * z);
if (z == 0.0)
throw new ArithmeticException("gamma: overflow");
z = Math.abs(z);
z = Math.PI / (z * stirf(q));
return -z;
}
return stirf(x);
}
z = 1.0;
while (x >= 3.0) {
x -= 1.0;
z *= x;
}
while (x < 0.0) {
if (x == 0.0) {
throw new ArithmeticException("gamma: singular");
}
else if (x > -1.E-9) {
return (z / ((1.0 + 0.5772156649015329 * x) * x));
}
z /= x;
x += 1.0;
}
while (x < 2.0) {
if (x == 0.0) {
throw new ArithmeticException("gamma: singular");
}
else if (x < 1.e-9) {
return (z / ((1.0 + 0.5772156649015329 * x) * x));
}
z /= x;
x += 1.0;
}
if ((x == 2.0) || (x == 3.0))
return z;
x -= 2.0;
p = polevl(x, P, 6);
q = polevl(x, Q, 7);
return z * p / q;
}
/*
* Gamma function computed by Stirling's formula. The polynomial STIR is valid for 33 <= x <= 172.
*
* Cephes Math Library Release 2.2: July, 1992 Copyright 1984, 1987, 1989, 1992 by Stephen L. Moshier Direct
* inquiries to 30 Frost Street, Cambridge, MA 02140
*/
static private double stirf(double x) throws ArithmeticException {
double STIR[] = { 7.87311395793093628397E-4, -2.29549961613378126380E-4, -2.68132617805781232825E-3,
3.47222221605458667310E-3, 8.33333333333482257126E-2, };
double MAXSTIR = 143.01608;
double SQTPI = 2.50662827463100050242E0;
double w = 1.0 / x;
double y = Math.exp(x);
w = 1.0 + w * polevl(w, STIR, 4);
if (x > MAXSTIR) {
/* Avoid overflow in Math.pow() */
double v = Math.pow(x, 0.5 * x - 0.25);
y = v * (v / y);
}
else {
y = Math.pow(x, x - 0.5) / y;
}
y = SQTPI * y * w;
return y;
}
static double polevl(double x, double coef[], int N) throws ArithmeticException {
double ans;
ans = coef[0];
for (int i = 1; i <= N; i++) {
ans = ans * x + coef[i];
}
return ans;
}
static double p1evl(double x, double coef[], int N) throws ArithmeticException {
double ans = x + coef[0];
for (int i = 1; i < N; i++) {
ans = ans * x + coef[i];
}
return ans;
}
}
|
concord-consortium/mw
|
src/org/nfunk/jep/function/Gamma.java
|
Java
|
gpl-2.0
| 4,904
|
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
/*
* gmtk.h
* Copyright (C) Kevin DeKorte 2006 <kdekorte@gmail.com>
*
* gmtk.h is free software.
*
* You may redistribute it and/or modify it under the terms of the
* GNU General Public License, as published by the Free Software
* Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* gmtk.h 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 playlist.c. If not, write to:
* The Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301, USA.
*/
#include "gmtk_audio_meter.h"
#include "gmtk_media_tracker.h"
#include "gmtk_media_player.h"
#include "gmtk_output_combo_box.h"
#include "gmtk_common.h"
|
kdekorte/gmtk
|
src/gmtk.h
|
C
|
gpl-2.0
| 1,032
|
<?php
/**
* @package Mambo
* @subpackage Installer
* @author Mambo Foundation Inc see README.php
* @copyright Mambo Foundation Inc.
* See COPYRIGHT.php for copyright notices and details.
* @license GNU/GPL Version 2, see LICENSE.php
* Mambo is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2 of the License.
*/
/** ensure this file is being included by a parent file */
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );
// ensure user has access to this function
if ( !$acl->acl_check( 'administration', 'install', 'users', $my->usertype, $element . 's', 'all' ) ) {
mosRedirect( 'index2.php', T_('You are not authorized to view this resource.') );
}
require_once( $mainframe->getPath( 'installer_html', 'module' ) );
showInstalledModules( $option );
/**
* @param string The URL option
*/
function showInstalledModules( $_option ) {
global $database, $mosConfig_absolute_path;
$filter = mosGetParam( $_POST, 'filter', '' );
$select[] = mosHTML::makeOption( '', T_('All') );
$select[] = mosHTML::makeOption( '0', T_('Site Modules') );
$select[] = mosHTML::makeOption( '1', T_('Admin Modules') );
$lists['filter'] = mosHTML::selectList( $select, 'filter', 'class="inputbox" size="1" onchange="document.adminForm.submit();"', 'value', 'text', $filter );
if ( $filter == NULL ) {
$_and = '';
} else if ( !$filter ) {
$_and = "\n AND client_id = '0'";
} else if ( $filter ) {
$_and = "\n AND client_id = '1'";
}
$database->setQuery( "SELECT id, module, client_id"
. "\n FROM #__modules"
. "\n WHERE module LIKE 'mod_%' AND iscore='0'"
. $_and
. "\n GROUP BY module, client_id"
. "\n ORDER BY client_id, module"
);
$rows = $database->loadObjectList();
$n = count( $rows );
for ($i = 0; $i < $n; $i++) {
$row =& $rows[$i];
// path to module directory
if ($row->client_id == "1"){
$moduleBaseDir = mosPathName($mosConfig_absolute_path.'/administrator/modules');
} else {
$moduleBaseDir = mosPathName($mosConfig_absolute_path.'/modules');
}
// xml file for module
$xmlfile = $moduleBaseDir.$row->module.".xml";
if (file_exists( $xmlfile )) {
$parser =& new mosXMLDescription($xmlfile);
if ($parser->getType() != 'module') continue;
$row->creationdate = $parser->getCreationDate('module');
$row->author = $parser->getAuthor('module');
$row->copyright = $parser->getCopyright('module');
$row->authorEmail = $parser->getAuthorEmail('module');
$row->authorUrl = $parser->getAuthorUrl('module');
$row->version = $parser->getVersion('module');
/*
$xmlDoc =& new DOMIT_Lite_Document();
$xmlDoc->resolveErrors( true );
if (!$xmlDoc->loadXML( $xmlfile, false, true )) {
continue;
}
$element = &$xmlDoc->documentElement;
if ($element->getTagName() != 'mosinstall') {
continue;
}
if ($element->getAttribute( "type" ) != "module") {
continue;
}
$element = &$xmlDoc->getElementsByPath( 'creationDate', 1 );
$row->creationdate = $element ? $element->getText() : '';
$element = &$xmlDoc->getElementsByPath( 'author', 1 );
$row->author = $element ? $element->getText() : '';
$element = &$xmlDoc->getElementsByPath( 'copyright', 1 );
$row->copyright = $element ? $element->getText() : '';
$element = &$xmlDoc->getElementsByPath( 'authorEmail', 1 );
$row->authorEmail = $element ? $element->getText() : '';
$element = &$xmlDoc->getElementsByPath( 'authorUrl', 1 );
$row->authorUrl = $element ? $element->getText() : '';
$element = &$xmlDoc->getElementsByPath( 'version', 1 );
$row->version = $element ? $element->getText() : '';
*/
}
}
HTML_module::showInstalledModules( $rows, $_option, $xmlfile, $lists );
}
?>
|
chanhong/mambo
|
administrator/components/com_installer/module/module.php
|
PHP
|
gpl-2.0
| 3,822
|
#include <zlib.h>
#include <stdio.h>
#include <ctype.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include "htslib/kstring.h"
#include "htslib/bgzf.h"
#include "htslib/vcf.h"
#include "htslib/tbx.h"
#include "htslib/hfile.h"
#include "htslib/khash.h"
KHASH_MAP_INIT_STR(vdict, bcf_idinfo_t)
typedef khash_t(vdict) vdict_t;
#include "htslib/kseq.h"
KSTREAM_DECLARE(gzFile, gzread)
uint32_t bcf_float_missing = 0x7F800001;
uint32_t bcf_float_vector_end = 0x7F800002;
uint8_t bcf_type_shift[] = { 0, 0, 1, 2, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
static bcf_idinfo_t bcf_idinfo_def = { .info = { 15, 15, 15 }, .hrec = { NULL, NULL, NULL}, .id = -1 };
/*************************
*** VCF header parser ***
*************************/
int bcf_hdr_sync(bcf_hdr_t *h);
int bcf_hdr_add_sample(bcf_hdr_t *h, const char *s)
{
const char *ss = s;
while ( !*ss && isspace(*ss) ) ss++;
if ( !*ss )
{
fprintf(stderr,"[W::%s] Empty sample name: trailing spaces/tabs in the header line?\n", __func__);
abort();
}
vdict_t *d = (vdict_t*)h->dict[BCF_DT_SAMPLE];
int ret;
char *sdup = strdup(s);
int k = kh_put(vdict, d, sdup, &ret);
if (ret) { // absent
kh_val(d, k) = bcf_idinfo_def;
kh_val(d, k).id = kh_size(d) - 1;
} else {
if (hts_verbose >= 2)
fprintf(stderr, "[W::%s] Duplicated sample name '%s'. Skipped.\n", __func__, s);
free(sdup);
return -1;
}
int n = kh_size(d);
h->samples = (char**) realloc(h->samples,sizeof(char*)*n);
h->samples[n-1] = sdup;
bcf_hdr_sync(h);
return 0;
}
void bcf_hdr_parse_sample_line(bcf_hdr_t *h, const char *str)
{
int i = 0;
const char *p, *q;
// add samples
for (p = q = str;; ++q) {
if (*q != '\t' && *q != 0 && *q != '\n') continue;
if (++i > 9) {
char *s = (char*)malloc(q - p + 1);
strncpy(s, p, q - p);
s[q - p] = 0;
bcf_hdr_add_sample(h,s);
free(s);
}
if (*q == 0 || *q == '\n') break;
p = q + 1;
}
}
int bcf_hdr_sync(bcf_hdr_t *h)
{
int i;
for (i = 0; i < 3; i++)
{
vdict_t *d = (vdict_t*)h->dict[i];
khint_t k;
// find out the largest id, there may be holes because of IDX
int max_id = -1;
for (k=kh_begin(d); k<kh_end(d); k++)
{
if (!kh_exist(d,k)) continue;
if ( max_id < kh_val(d,k).id ) max_id = kh_val(d,k).id;
}
if ( max_id >= h->n[i] )
{
h->id[i] = (bcf_idpair_t*)realloc(h->id[i], (max_id+1)*sizeof(bcf_idpair_t));
for (k=h->n[i]; k<=max_id; k++)
{
h->id[i][k].key = NULL;
h->id[i][k].val = NULL;
}
h->n[i] = max_id+1;
}
for (k=kh_begin(d); k<kh_end(d); k++)
{
if (!kh_exist(d,k)) continue;
h->id[i][kh_val(d,k).id].key = kh_key(d,k);
h->id[i][kh_val(d,k).id].val = &kh_val(d,k);
}
}
return 0;
}
void bcf_hrec_destroy(bcf_hrec_t *hrec)
{
free(hrec->key);
if ( hrec->value ) free(hrec->value);
int i;
for (i=0; i<hrec->nkeys; i++)
{
free(hrec->keys[i]);
free(hrec->vals[i]);
}
free(hrec->keys);
free(hrec->vals);
free(hrec);
}
// Copies all fields except IDX.
bcf_hrec_t *bcf_hrec_dup(bcf_hrec_t *hrec)
{
bcf_hrec_t *out = (bcf_hrec_t*) calloc(1,sizeof(bcf_hrec_t));
out->type = hrec->type;
if ( hrec->key ) out->key = strdup(hrec->key);
if ( hrec->value ) out->value = strdup(hrec->value);
out->nkeys = hrec->nkeys;
out->keys = (char**) malloc(sizeof(char*)*hrec->nkeys);
out->vals = (char**) malloc(sizeof(char*)*hrec->nkeys);
int i, j = 0;
for (i=0; i<hrec->nkeys; i++)
{
if ( hrec->keys[i] && !strcmp("IDX",hrec->keys[i]) ) continue;
if ( hrec->keys[i] ) out->keys[j] = strdup(hrec->keys[i]);
if ( hrec->vals[i] ) out->vals[j] = strdup(hrec->vals[i]);
j++;
}
if ( i!=j ) out->nkeys--; // IDX was omitted
return out;
}
void bcf_hrec_debug(FILE *fp, bcf_hrec_t *hrec)
{
fprintf(fp, "key=[%s] value=[%s]", hrec->key, hrec->value?hrec->value:"");
int i;
for (i=0; i<hrec->nkeys; i++)
fprintf(fp, "\t[%s]=[%s]", hrec->keys[i],hrec->vals[i]);
fprintf(fp, "\n");
}
void bcf_header_debug(bcf_hdr_t *hdr)
{
int i, j;
for (i=0; i<hdr->nhrec; i++)
{
if ( !hdr->hrec[i]->value )
{
fprintf(stderr, "##%s=<", hdr->hrec[i]->key);
fprintf(stderr,"%s=%s", hdr->hrec[i]->keys[0], hdr->hrec[i]->vals[0]);
for (j=1; j<hdr->hrec[i]->nkeys; j++)
fprintf(stderr,",%s=%s", hdr->hrec[i]->keys[j], hdr->hrec[i]->vals[j]);
fprintf(stderr,">\n");
}
else
fprintf(stderr,"##%s=%s\n", hdr->hrec[i]->key,hdr->hrec[i]->value);
}
}
void bcf_hrec_add_key(bcf_hrec_t *hrec, const char *str, int len)
{
int n = ++hrec->nkeys;
hrec->keys = (char**) realloc(hrec->keys, sizeof(char*)*n);
hrec->vals = (char**) realloc(hrec->vals, sizeof(char*)*n);
assert( len );
hrec->keys[n-1] = (char*) malloc((len+1)*sizeof(char));
memcpy(hrec->keys[n-1],str,len);
hrec->keys[n-1][len] = 0;
hrec->vals[n-1] = NULL;
}
void bcf_hrec_set_val(bcf_hrec_t *hrec, int i, const char *str, int len, int is_quoted)
{
if ( !str ) { hrec->vals[i] = NULL; return; }
if ( hrec->vals[i] ) free(hrec->vals[i]);
if ( is_quoted )
{
hrec->vals[i] = (char*) malloc((len+3)*sizeof(char));
hrec->vals[i][0] = '"';
memcpy(&hrec->vals[i][1],str,len);
hrec->vals[i][len+1] = '"';
hrec->vals[i][len+2] = 0;
}
else
{
hrec->vals[i] = (char*) malloc((len+1)*sizeof(char));
memcpy(hrec->vals[i],str,len);
hrec->vals[i][len] = 0;
}
}
void hrec_add_idx(bcf_hrec_t *hrec, int idx)
{
int n = ++hrec->nkeys;
hrec->keys = (char**) realloc(hrec->keys, sizeof(char*)*n);
hrec->vals = (char**) realloc(hrec->vals, sizeof(char*)*n);
hrec->keys[n-1] = strdup("IDX");
kstring_t str = {0,0,0};
kputw(idx, &str);
hrec->vals[n-1] = str.s;
}
int bcf_hrec_find_key(bcf_hrec_t *hrec, const char *key)
{
int i;
for (i=0; i<hrec->nkeys; i++)
if ( !strcasecmp(key,hrec->keys[i]) ) return i;
return -1;
}
static inline int is_escaped(const char *min, const char *str)
{
int n = 0;
while ( --str>=min && *str=='\\' ) n++;
return n%2;
}
bcf_hrec_t *bcf_hdr_parse_line(const bcf_hdr_t *h, const char *line, int *len)
{
const char *p = line;
if (p[0] != '#' || p[1] != '#') { *len = 0; return NULL; }
p += 2;
const char *q = p;
while ( *q && *q!='=' ) q++;
int n = q-p;
if ( *q!='=' || !n ) { *len = q-line+1; return NULL; } // wrong format
bcf_hrec_t *hrec = (bcf_hrec_t*) calloc(1,sizeof(bcf_hrec_t));
hrec->key = (char*) malloc(sizeof(char)*(n+1));
memcpy(hrec->key,p,n);
hrec->key[n] = 0;
p = ++q;
if ( *p!='<' ) // generic field, e.g. ##samtoolsVersion=0.1.18-r579
{
while ( *q && *q!='\n' ) q++;
hrec->value = (char*) malloc((q-p+1)*sizeof(char));
memcpy(hrec->value, p, q-p);
hrec->value[q-p] = 0;
*len = q-line+1;
return hrec;
}
// structured line, e.g. ##INFO=<ID=PV1,Number=1,Type=Float,Description="P-value for baseQ bias">
int nopen = 1;
while ( *q && *q!='\n' && nopen )
{
p = ++q;
while ( *q && *q!='=' ) q++;
n = q-p;
if ( *q!='=' || !n ) { *len = q-line+1; bcf_hrec_destroy(hrec); return NULL; } // wrong format
bcf_hrec_add_key(hrec, p, q-p);
p = ++q;
int quoted = *p=='"' ? 1 : 0;
if ( quoted ) p++, q++;
while (1)
{
if ( !*q ) break;
if ( quoted ) { if ( *q=='"' && !is_escaped(p,q) ) break; }
else
{
if ( *q=='<' ) nopen++;
if ( *q=='>' ) nopen--;
if ( !nopen ) break;
if ( *q==',' && nopen==1 ) break;
}
q++;
}
bcf_hrec_set_val(hrec, hrec->nkeys-1, p, q-p, quoted);
if ( quoted ) q++;
if ( *q=='>' ) { nopen--; q++; }
}
*len = q-line+1;
return hrec;
}
// returns: 1 when hdr needs to be synced, 0 otherwise
int bcf_hdr_register_hrec(bcf_hdr_t *hdr, bcf_hrec_t *hrec)
{
// contig
int i,j,k, ret;
char *str;
if ( !strcmp(hrec->key, "contig") )
{
hrec->type = BCF_HL_CTG;
// Get the contig ID ($str) and length ($j)
i = bcf_hrec_find_key(hrec,"length");
if ( i<0 ) return 0;
if ( sscanf(hrec->vals[i],"%d",&j)!=1 ) return 0;
i = bcf_hrec_find_key(hrec,"ID");
if ( i<0 ) return 0;
str = strdup(hrec->vals[i]);
// Register in the dictionary
vdict_t *d = (vdict_t*)hdr->dict[BCF_DT_CTG];
k = kh_put(vdict, d, str, &ret);
if ( !ret ) { free(str); return 0; } // already present
int idx = bcf_hrec_find_key(hrec,"IDX");
if ( idx!=-1 )
{
char *tmp = hrec->vals[idx];
idx = strtol(hrec->vals[idx], &tmp, 10);
if ( *tmp )
{
fprintf(stderr,"[%s:%d %s] Error parsing the IDX tag, skipping.\n", __FILE__,__LINE__,__FUNCTION__);
return 0;
}
}
else
{
idx = kh_size(d) - 1;
hrec_add_idx(hrec, idx);
}
kh_val(d, k) = bcf_idinfo_def;
kh_val(d, k).id = idx;
kh_val(d, k).info[0] = i;
kh_val(d, k).hrec[0] = hrec;
return 1;
}
if ( !strcmp(hrec->key, "INFO") ) hrec->type = BCF_HL_INFO;
else if ( !strcmp(hrec->key, "FILTER") ) hrec->type = BCF_HL_FLT;
else if ( !strcmp(hrec->key, "FORMAT") ) hrec->type = BCF_HL_FMT;
else if ( hrec->nkeys>0 ) { hrec->type = BCF_HL_STR; return 1; }
else return 0;
// INFO/FILTER/FORMAT
char *id = NULL;
int type = -1, num = -1, var = -1, idx = -1;
for (i=0; i<hrec->nkeys; i++)
{
if ( !strcmp(hrec->keys[i], "ID") ) id = hrec->vals[i];
else if ( !strcmp(hrec->keys[i], "IDX") )
{
char *tmp = hrec->vals[i];
idx = strtol(hrec->vals[i], &tmp, 10);
if ( *tmp )
{
fprintf(stderr,"[%s:%d %s] Error parsing the IDX tag, skipping.\n", __FILE__,__LINE__,__FUNCTION__);
return 0;
}
}
else if ( !strcmp(hrec->keys[i], "Type") )
{
if ( !strcmp(hrec->vals[i], "Integer") ) type = BCF_HT_INT;
else if ( !strcmp(hrec->vals[i], "Float") ) type = BCF_HT_REAL;
else if ( !strcmp(hrec->vals[i], "String") ) type = BCF_HT_STR;
else if ( !strcmp(hrec->vals[i], "Flag") ) type = BCF_HT_FLAG;
else
{
fprintf(stderr, "[E::%s] The type \"%s\" not supported, assuming \"String\"\n", __func__, hrec->vals[i]);
type = BCF_HT_STR;
}
}
else if ( !strcmp(hrec->keys[i], "Number") )
{
if ( !strcmp(hrec->vals[i],"A") ) var = BCF_VL_A;
else if ( !strcmp(hrec->vals[i],"R") ) var = BCF_VL_R;
else if ( !strcmp(hrec->vals[i],"G") ) var = BCF_VL_G;
else if ( !strcmp(hrec->vals[i],".") ) var = BCF_VL_VAR;
else
{
sscanf(hrec->vals[i],"%d",&num);
var = BCF_VL_FIXED;
}
if (var != BCF_VL_FIXED) num = 0xfffff;
}
}
uint32_t info = (uint32_t)num<<12 | var<<8 | type<<4 | hrec->type;
if ( !id ) return 0;
str = strdup(id);
vdict_t *d = (vdict_t*)hdr->dict[BCF_DT_ID];
k = kh_put(vdict, d, str, &ret);
if ( !ret )
{
// already present
free(str);
if ( kh_val(d, k).hrec[info&0xf] ) return 0;
kh_val(d, k).info[info&0xf] = info;
kh_val(d, k).hrec[info&0xf] = hrec;
return 1;
}
kh_val(d, k) = bcf_idinfo_def;
kh_val(d, k).info[info&0xf] = info;
kh_val(d, k).hrec[info&0xf] = hrec;
kh_val(d, k).id = idx==-1 ? kh_size(d) - 1 : idx;
if ( idx==-1 ) hrec_add_idx(hrec, kh_val(d, k).id);
return 1;
}
int bcf_hdr_add_hrec(bcf_hdr_t *hdr, bcf_hrec_t *hrec)
{
hrec->type = BCF_HL_GEN;
if ( !bcf_hdr_register_hrec(hdr,hrec) )
{
// If one of the hashed field, then it is already present
if ( hrec->type != BCF_HL_GEN )
{
bcf_hrec_destroy(hrec);
return 0;
}
// Is one of the generic fields and already present?
int i;
for (i=0; i<hdr->nhrec; i++)
{
if ( hdr->hrec[i]->type!=BCF_HL_GEN ) continue;
if ( !strcmp(hdr->hrec[i]->key,hrec->key) && !strcmp(hrec->key,"fileformat") ) break;
if ( !strcmp(hdr->hrec[i]->key,hrec->key) && !strcmp(hdr->hrec[i]->value,hrec->value) ) break;
}
if ( i<hdr->nhrec )
{
bcf_hrec_destroy(hrec);
return 0;
}
}
// New record, needs to be added
int n = ++hdr->nhrec;
hdr->hrec = (bcf_hrec_t**) realloc(hdr->hrec, n*sizeof(bcf_hrec_t*));
hdr->hrec[n-1] = hrec;
return hrec->type==BCF_HL_GEN ? 0 : 1;
}
bcf_hrec_t *bcf_hdr_get_hrec(bcf_hdr_t *hdr, int type, const char *id)
{
vdict_t *d = type==BCF_HL_CTG ? (vdict_t*)hdr->dict[BCF_DT_CTG] : (vdict_t*)hdr->dict[BCF_DT_ID];
khint_t k = kh_get(vdict, d, id);
if ( k == kh_end(d) ) return NULL;
return kh_val(d, k).hrec[type==BCF_HL_CTG?0:type];
}
void bcf_hdr_check_sanity(bcf_hdr_t *hdr)
{
static int PL_warned = 0, GL_warned = 0;
if ( !PL_warned )
{
int id = bcf_hdr_id2int(hdr, BCF_DT_ID, "PL");
if ( bcf_hdr_idinfo_exists(hdr,BCF_HL_FMT,id) && bcf_hdr_id2length(hdr,BCF_HL_FMT,id)!=BCF_VL_G )
{
fprintf(stderr,"[W::%s] PL should be declared as Number=G\n", __func__);
PL_warned = 1;
}
}
if ( !GL_warned )
{
int id = bcf_hdr_id2int(hdr, BCF_HL_FMT, "GL");
if ( bcf_hdr_idinfo_exists(hdr,BCF_HL_FMT,id) && bcf_hdr_id2length(hdr,BCF_HL_FMT,id)!=BCF_VL_G )
{
fprintf(stderr,"[W::%s] GL should be declared as Number=G\n", __func__);
PL_warned = 1;
}
}
}
int bcf_hdr_parse(bcf_hdr_t *hdr, char *htxt)
{
int len, needs_sync = 0;
char *p = htxt;
// Check sanity: "fileformat" string must come as first
bcf_hrec_t *hrec = bcf_hdr_parse_line(hdr,p,&len);
if ( !hrec->key || strcasecmp(hrec->key,"fileformat") )
fprintf(stderr, "[W::%s] The first line should be ##fileformat; is the VCF/BCF header broken?\n", __func__);
needs_sync += bcf_hdr_add_hrec(hdr, hrec);
// The filter PASS must appear first in the dictionary
hrec = bcf_hdr_parse_line(hdr,"##FILTER=<ID=PASS,Description=\"All filters passed\">",&len);
needs_sync += bcf_hdr_add_hrec(hdr, hrec);
// Parse the whole header
while ( (hrec=bcf_hdr_parse_line(hdr,p,&len)) )
{
needs_sync += bcf_hdr_add_hrec(hdr, hrec);
p += len;
}
bcf_hdr_parse_sample_line(hdr,p);
if ( needs_sync ) bcf_hdr_sync(hdr);
bcf_hdr_check_sanity(hdr);
return 0;
}
int bcf_hdr_append(bcf_hdr_t *hdr, const char *line)
{
int len;
bcf_hrec_t *hrec = bcf_hdr_parse_line(hdr, (char*) line, &len);
if ( !hrec ) return -1;
if ( bcf_hdr_add_hrec(hdr, hrec) )
bcf_hdr_sync(hdr);
return 0;
}
void bcf_hdr_remove(bcf_hdr_t *hdr, int type, const char *key)
{
int i;
bcf_hrec_t *hrec;
while (1)
{
if ( type==BCF_HL_FLT || type==BCF_HL_INFO || type==BCF_HL_FMT || type== BCF_HL_CTG )
{
hrec = bcf_hdr_get_hrec(hdr, type, key);
if ( !hrec ) return;
for (i=0; i<hdr->nhrec; i++)
if ( hdr->hrec[i]==hrec ) break;
assert( i<hdr->nhrec );
vdict_t *d = type==BCF_HL_CTG ? (vdict_t*)hdr->dict[BCF_DT_CTG] : (vdict_t*)hdr->dict[BCF_DT_ID];
khint_t k = kh_get(vdict, d, key);
kh_val(d, k).hrec[type==BCF_HL_CTG?0:type] = NULL;
}
else
{
for (i=0; i<hdr->nhrec; i++)
{
if ( hdr->hrec[i]->type!=type ) continue;
if ( !strcmp(hdr->hrec[i]->key,key) ) break;
}
if ( i==hdr->nhrec ) return;
hrec = hdr->hrec[i];
}
hdr->nhrec--;
if ( i < hdr->nhrec )
memmove(&hdr->hrec[i],&hdr->hrec[i+1],(hdr->nhrec-i)*sizeof(bcf_hrec_t*));
bcf_hrec_destroy(hrec);
bcf_hdr_sync(hdr);
}
}
int bcf_hdr_printf(bcf_hdr_t *hdr, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
int n = vsnprintf(NULL, 0, fmt, ap) + 2;
va_end(ap);
char *line = (char*)malloc(n);
va_start(ap, fmt);
vsnprintf(line, n, fmt, ap);
va_end(ap);
int ret = bcf_hdr_append(hdr, line);
free(line);
return ret;
}
/**********************
*** BCF header I/O ***
**********************/
bcf_hdr_t *bcf_hdr_init(const char *mode)
{
int i;
bcf_hdr_t *h;
h = (bcf_hdr_t*)calloc(1, sizeof(bcf_hdr_t));
for (i = 0; i < 3; ++i)
h->dict[i] = kh_init(vdict);
if ( strchr(mode,'w') )
{
bcf_hdr_append(h, "##fileformat=VCFv4.2");
// The filter PASS must appear first in the dictionary
bcf_hdr_append(h, "##FILTER=<ID=PASS,Description=\"All filters passed\">");
}
return h;
}
void bcf_hdr_destroy(bcf_hdr_t *h)
{
int i;
khint_t k;
for (i = 0; i < 3; ++i) {
vdict_t *d = (vdict_t*)h->dict[i];
if (d == 0) continue;
for (k = kh_begin(d); k != kh_end(d); ++k)
if (kh_exist(d, k)) free((char*)kh_key(d, k));
kh_destroy(vdict, d);
free(h->id[i]);
}
for (i=0; i<h->nhrec; i++)
bcf_hrec_destroy(h->hrec[i]);
if (h->nhrec) free(h->hrec);
if (h->samples) free(h->samples);
free(h->keep_samples);
free(h->transl[0]); free(h->transl[1]);
free(h->mem.s);
free(h);
}
bcf_hdr_t *bcf_hdr_read(htsFile *hfp)
{
if (!hfp->is_bin)
return vcf_hdr_read(hfp);
BGZF *fp = hfp->fp.bgzf;
uint8_t magic[5];
bcf_hdr_t *h;
h = bcf_hdr_init("r");
if ( bgzf_read(fp, magic, 5)<0 )
{
fprintf(stderr,"[%s:%d %s] Failed to read the header (reading BCF in text mode?)\n", __FILE__,__LINE__,__FUNCTION__);
return NULL;
}
if (strncmp((char*)magic, "BCF\2\2", 5) != 0)
{
if (!strncmp((char*)magic, "BCF", 3))
fprintf(stderr,"[%s:%d %s] invalid BCF2 magic string: only BCFv2.2 is supported.\n", __FILE__,__LINE__,__FUNCTION__);
else if (hts_verbose >= 2)
fprintf(stderr, "[E::%s] invalid BCF2 magic string\n", __func__);
bcf_hdr_destroy(h);
return 0;
}
int hlen;
char *htxt;
bgzf_read(fp, &hlen, 4);
htxt = (char*)malloc(hlen);
bgzf_read(fp, htxt, hlen);
bcf_hdr_parse(h, htxt);
free(htxt);
return h;
}
int bcf_hdr_write(htsFile *hfp, const bcf_hdr_t *h)
{
if (!hfp->is_bin) return vcf_hdr_write(hfp, h);
int hlen;
char *htxt = bcf_hdr_fmt_text(h, 1, &hlen);
hlen++; // include the \0 byte
BGZF *fp = hfp->fp.bgzf;
if ( bgzf_write(fp, "BCF\2\2", 5) !=5 ) return -1;
if ( bgzf_write(fp, &hlen, 4) !=4 ) return -1;
if ( bgzf_write(fp, htxt, hlen) != hlen ) return -1;
free(htxt);
return 0;
}
/********************
*** BCF site I/O ***
********************/
bcf1_t *bcf_init1()
{
bcf1_t *v;
v = (bcf1_t*)calloc(1, sizeof(bcf1_t));
return v;
}
void bcf_clear(bcf1_t *v)
{
int i;
for (i=0; i<v->d.m_info; i++)
{
if ( v->d.info[i].vptr_free )
{
free(v->d.info[i].vptr - v->d.info[i].vptr_off);
v->d.info[i].vptr_free = 0;
}
}
for (i=0; i<v->d.m_fmt; i++)
{
if ( v->d.fmt[i].p_free )
{
free(v->d.fmt[i].p - v->d.fmt[i].p_off);
v->d.fmt[i].p_free = 0;
}
}
v->rid = v->pos = v->rlen = v->unpacked = 0;
v->unpack_ptr = NULL;
bcf_float_set_missing(v->qual);
v->n_info = v->n_allele = v->n_fmt = v->n_sample = 0;
v->shared.l = v->indiv.l = 0;
v->d.var_type = -1;
v->d.shared_dirty = 0;
v->d.indiv_dirty = 0;
v->d.n_flt = 0;
v->errcode = 0;
if (v->d.m_als) v->d.als[0] = 0;
if (v->d.m_id) v->d.id[0] = 0;
}
void bcf_empty1(bcf1_t *v)
{
bcf_clear1(v);
free(v->d.id);
free(v->d.als);
free(v->d.allele); free(v->d.flt); free(v->d.info); free(v->d.fmt);
if (v->d.var ) free(v->d.var);
free(v->shared.s); free(v->indiv.s);
}
void bcf_destroy1(bcf1_t *v)
{
bcf_empty1(v);
free(v);
}
static inline int bcf_read1_core(BGZF *fp, bcf1_t *v)
{
uint32_t x[8];
int ret;
if ((ret = bgzf_read(fp, x, 32)) != 32) {
if (ret == 0) return -1;
return -2;
}
bcf_clear1(v);
x[0] -= 24; // to exclude six 32-bit integers
ks_resize(&v->shared, x[0]);
ks_resize(&v->indiv, x[1]);
memcpy(v, x + 2, 16);
v->n_allele = x[6]>>16; v->n_info = x[6]&0xffff;
v->n_fmt = x[7]>>24; v->n_sample = x[7]&0xffffff;
v->shared.l = x[0], v->indiv.l = x[1];
bgzf_read(fp, v->shared.s, v->shared.l);
bgzf_read(fp, v->indiv.s, v->indiv.l);
return 0;
}
#define bit_array_size(n) ((n)/8+1)
#define bit_array_set(a,i) ((a)[(i)/8] |= 1 << ((i)%8))
#define bit_array_clear(a,i) ((a)[(i)/8] &= ~(1 << ((i)%8)))
#define bit_array_test(a,i) ((a)[(i)/8] & (1 << ((i)%8)))
static inline uint8_t *bcf_unpack_fmt_core1(uint8_t *ptr, int n_sample, bcf_fmt_t *fmt);
int bcf_subset_format(const bcf_hdr_t *hdr, bcf1_t *rec)
{
if ( !hdr->keep_samples ) return 0;
if ( !bcf_hdr_nsamples(hdr) )
{
rec->indiv.l = rec->n_sample = 0;
return 0;
}
int i, j;
uint8_t *ptr = (uint8_t*)rec->indiv.s, *dst = NULL, *src;
bcf_dec_t *dec = &rec->d;
hts_expand(bcf_fmt_t, rec->n_fmt, dec->m_fmt, dec->fmt);
for (i=0; i<dec->m_fmt; ++i) dec->fmt[i].p_free = 0;
for (i=0; i<rec->n_fmt; i++)
{
ptr = bcf_unpack_fmt_core1(ptr, rec->n_sample, &dec->fmt[i]);
src = dec->fmt[i].p - dec->fmt[i].size;
if ( dst )
{
memmove(dec->fmt[i-1].p + dec->fmt[i-1].p_len, dec->fmt[i].p - dec->fmt[i].p_off, dec->fmt[i].p_off);
dec->fmt[i].p = dec->fmt[i-1].p + dec->fmt[i-1].p_len + dec->fmt[i].p_off;
}
dst = dec->fmt[i].p;
for (j=0; j<hdr->nsamples_ori; j++)
{
src += dec->fmt[i].size;
if ( !bit_array_test(hdr->keep_samples,j) ) continue;
memmove(dst, src, dec->fmt[i].size);
dst += dec->fmt[i].size;
}
rec->indiv.l -= dec->fmt[i].p_len - (dst - dec->fmt[i].p);
dec->fmt[i].p_len = dst - dec->fmt[i].p;
}
rec->unpacked |= BCF_UN_FMT;
rec->n_sample = bcf_hdr_nsamples(hdr);
return 0;
}
int bcf_read(htsFile *fp, const bcf_hdr_t *h, bcf1_t *v)
{
if (!fp->is_bin) return vcf_read(fp,h,v);
int ret = bcf_read1_core(fp->fp.bgzf, v);
if ( ret!=0 || !h->keep_samples ) return ret;
return bcf_subset_format(h,v);
}
int bcf_readrec(BGZF *fp, void *null, void *vv, int *tid, int *beg, int *end)
{
bcf1_t *v = (bcf1_t *) vv;
int ret;
if ((ret = bcf_read1_core(fp, v)) >= 0)
*tid = v->rid, *beg = v->pos, *end = v->pos + v->rlen;
return ret;
}
static inline void bcf1_sync_id(bcf1_t *line, kstring_t *str)
{
// single typed string
if ( line->d.id && strcmp(line->d.id, ".") ) bcf_enc_vchar(str, strlen(line->d.id), line->d.id);
else bcf_enc_size(str, 0, BCF_BT_CHAR);
}
static inline void bcf1_sync_alleles(bcf1_t *line, kstring_t *str)
{
// list of typed strings
int i;
for (i=0; i<line->n_allele; i++)
bcf_enc_vchar(str, strlen(line->d.allele[i]), line->d.allele[i]);
}
static inline void bcf1_sync_filter(bcf1_t *line, kstring_t *str)
{
// typed vector of integers
if ( line->d.n_flt ) bcf_enc_vint(str, line->d.n_flt, line->d.flt, -1);
else bcf_enc_vint(str, 0, 0, -1);
}
static inline void bcf1_sync_info(bcf1_t *line, kstring_t *str)
{
// pairs of typed vectors
int i, irm = -1;
for (i=0; i<line->n_info; i++)
{
bcf_info_t *info = &line->d.info[i];
if ( !info->vptr )
{
// marked for removal
if ( irm < 0 ) irm = i;
continue;
}
kputsn_(info->vptr - info->vptr_off, info->vptr_len + info->vptr_off, str);
if ( irm >=0 )
{
bcf_info_t tmp = line->d.info[irm]; line->d.info[irm] = line->d.info[i]; line->d.info[i] = tmp;
while ( irm<=i && line->d.info[irm].vptr ) irm++;
}
}
if ( irm>=0 ) line->n_info = irm;
}
static int bcf1_sync(bcf1_t *line)
{
kstring_t tmp = {0,0,0};
if ( !line->shared.l )
{
// New line, get ready for BCF output
tmp = line->shared;
bcf1_sync_id(line, &tmp);
bcf1_sync_alleles(line, &tmp);
bcf1_sync_filter(line, &tmp);
bcf1_sync_info(line, &tmp);
line->shared = tmp;
}
else if ( line->d.shared_dirty )
{
// The line was edited, update the BCF data block, ptr_ori points
// to the original unchanged BCF data.
uint8_t *ptr_ori = (uint8_t *) line->shared.s;
// ID: single typed string
if ( line->d.shared_dirty & BCF1_DIRTY_ID )
bcf1_sync_id(line, &tmp);
else
kputsn_(ptr_ori, line->unpack_size[0], &tmp);
ptr_ori += line->unpack_size[0];
// REF+ALT: list of typed strings
if ( line->d.shared_dirty & BCF1_DIRTY_ALS )
bcf1_sync_alleles(line, &tmp);
else
kputsn_(ptr_ori, line->unpack_size[1], &tmp);
line->rlen = line->n_allele ? strlen(line->d.allele[0]) : 0; // beware: this neglects SV's END tag
ptr_ori += line->unpack_size[1];
// FILTER: typed vector of integers
if ( line->d.shared_dirty & BCF1_DIRTY_FLT )
bcf1_sync_filter(line, &tmp);
else if ( line->d.n_flt )
kputsn_(ptr_ori, line->unpack_size[2], &tmp);
else
bcf_enc_vint(&tmp, 0, 0, -1);
ptr_ori += line->unpack_size[2];
// INFO: pairs of typed vectors
if ( line->d.shared_dirty & BCF1_DIRTY_INF )
bcf1_sync_info(line, &tmp);
else
{
int size = line->shared.l - (size_t)ptr_ori + (size_t)line->shared.s;
kputsn_(ptr_ori, size, &tmp);
}
free(line->shared.s);
line->shared = tmp;
}
if ( line->n_sample && line->n_fmt && (!line->indiv.l || line->d.indiv_dirty) )
{
// The genotype fields changed or are not present
tmp.l = tmp.m = 0; tmp.s = NULL;
int i, irm = -1;
for (i=0; i<line->n_fmt; i++)
{
bcf_fmt_t *fmt = &line->d.fmt[i];
if ( !fmt->p )
{
// marked for removal
if ( irm < 0 ) irm = i;
continue;
}
kputsn_(fmt->p - fmt->p_off, fmt->p_len + fmt->p_off, &tmp);
if ( irm >=0 )
{
bcf_fmt_t tfmt = line->d.fmt[irm]; line->d.fmt[irm] = line->d.fmt[i]; line->d.fmt[i] = tfmt;
while ( irm<=i && line->d.fmt[irm].p ) irm++;
}
}
if ( irm>=0 ) line->n_fmt = irm;
free(line->indiv.s);
line->indiv = tmp;
}
return 0;
}
int bcf_write(htsFile *hfp, const bcf_hdr_t *h, bcf1_t *v)
{
if ( !hfp->is_bin ) return vcf_write(hfp,h,v);
if ( v->errcode )
{
// vcf_parse1() encountered a new contig or tag, undeclared in the
// header. At this point, the header must have been printed,
// proceeding would lead to a broken BCF file. Errors must be checked
// and cleared by the caller before we can proceed.
fprintf(stderr,"[%s:%d %s] Unchecked error (%d), exiting.\n", __FILE__,__LINE__,__FUNCTION__,v->errcode);
exit(1);
}
bcf1_sync(v); // check if the BCF record was modified
BGZF *fp = hfp->fp.bgzf;
uint32_t x[8];
x[0] = v->shared.l + 24; // to include six 32-bit integers
x[1] = v->indiv.l;
memcpy(x + 2, v, 16);
x[6] = (uint32_t)v->n_allele<<16 | v->n_info;
x[7] = (uint32_t)v->n_fmt<<24 | v->n_sample;
if ( bgzf_write(fp, x, 32) != 32 ) return -1;
if ( bgzf_write(fp, v->shared.s, v->shared.l) != v->shared.l ) return -1;
if ( bgzf_write(fp, v->indiv.s, v->indiv.l) != v->indiv.l ) return -1;
return 0;
}
/**********************
*** VCF header I/O ***
**********************/
bcf_hdr_t *vcf_hdr_read(htsFile *fp)
{
kstring_t txt, *s = &fp->line;
bcf_hdr_t *h;
h = bcf_hdr_init("r");
txt.l = txt.m = 0; txt.s = 0;
while (hts_getline(fp, KS_SEP_LINE, s) >= 0) {
if (s->l == 0) continue;
if (s->s[0] != '#') {
if (hts_verbose >= 2)
fprintf(stderr, "[E::%s] no sample line\n", __func__);
free(txt.s);
bcf_hdr_destroy(h);
return 0;
}
if (s->s[1] != '#' && fp->fn_aux) { // insert contigs here
int dret;
gzFile f;
kstream_t *ks;
kstring_t tmp;
tmp.l = tmp.m = 0; tmp.s = 0;
f = gzopen(fp->fn_aux, "r");
ks = ks_init(f);
while (ks_getuntil(ks, 0, &tmp, &dret) >= 0) {
int c;
kputs("##contig=<ID=", &txt); kputs(tmp.s, &txt);
ks_getuntil(ks, 0, &tmp, &dret);
kputs(",length=", &txt); kputw(atol(tmp.s), &txt);
kputsn(">\n", 2, &txt);
if (dret != '\n')
while ((c = ks_getc(ks)) != '\n' && c != -1); // skip the rest of the line
}
free(tmp.s);
ks_destroy(ks);
gzclose(f);
}
kputsn(s->s, s->l, &txt);
kputc('\n', &txt);
if (s->s[1] != '#') break;
}
if ( !txt.s )
{
fprintf(stderr,"[%s:%d %s] Could not read the header\n", __FILE__,__LINE__,__FUNCTION__);
return NULL;
}
bcf_hdr_parse(h, txt.s);
// check tabix index, are all contigs listed in the header? add the missing ones
tbx_t *idx = tbx_index_load(fp->fn);
if ( idx )
{
int i, n, need_sync = 0;
const char **names = tbx_seqnames(idx, &n);
for (i=0; i<n; i++)
{
bcf_hrec_t *hrec = bcf_hdr_get_hrec(h, BCF_DT_CTG, (char*) names[i]);
if ( hrec ) continue;
hrec = (bcf_hrec_t*) calloc(1,sizeof(bcf_hrec_t));
hrec->key = strdup("contig");
bcf_hrec_add_key(hrec, "ID", strlen("ID"));
bcf_hrec_set_val(hrec, hrec->nkeys-1, (char*) names[i], strlen(names[i]), 0);
bcf_hrec_add_key(hrec, "length", strlen("length"));
bcf_hrec_set_val(hrec, hrec->nkeys-1, "2147483647", strlen("2147483647"), 0);
bcf_hdr_add_hrec(h, hrec);
need_sync = 1;
}
free(names);
tbx_destroy(idx);
if ( need_sync )
bcf_hdr_sync(h);
}
free(txt.s);
return h;
}
int bcf_hdr_set(bcf_hdr_t *hdr, const char *fname)
{
int i, n;
char **lines = hts_readlines(fname, &n);
if ( !lines ) return 1;
for (i=0; i<n-1; i++)
{
int k;
bcf_hrec_t *hrec = bcf_hdr_parse_line(hdr,lines[i],&k);
bcf_hdr_add_hrec(hdr, hrec);
free(lines[i]);
}
bcf_hdr_parse_sample_line(hdr,lines[n-1]);
free(lines[n-1]);
free(lines);
bcf_hdr_sync(hdr);
return 0;
}
static void _bcf_hrec_format(const bcf_hrec_t *hrec, int is_bcf, kstring_t *str)
{
if ( !hrec->value )
{
int j, nout = 0;
ksprintf(str, "##%s=<", hrec->key);
for (j=0; j<hrec->nkeys; j++)
{
// do not output IDX if output is VCF
if ( !is_bcf && !strcmp("IDX",hrec->keys[j]) ) continue;
if ( nout ) kputc(',',str);
ksprintf(str,"%s=%s", hrec->keys[j], hrec->vals[j]);
nout++;
}
ksprintf(str,">\n");
}
else
ksprintf(str,"##%s=%s\n", hrec->key,hrec->value);
}
void bcf_hrec_format(const bcf_hrec_t *hrec, kstring_t *str)
{
_bcf_hrec_format(hrec,0,str);
}
char *bcf_hdr_fmt_text(const bcf_hdr_t *hdr, int is_bcf, int *len)
{
int i;
kstring_t txt = {0,0,0};
for (i=0; i<hdr->nhrec; i++)
_bcf_hrec_format(hdr->hrec[i], is_bcf, &txt);
ksprintf(&txt,"#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO");
if ( bcf_hdr_nsamples(hdr) )
{
ksprintf(&txt,"\tFORMAT");
for (i=0; i<bcf_hdr_nsamples(hdr); i++)
ksprintf(&txt,"\t%s", hdr->samples[i]);
}
ksprintf(&txt,"\n");
if ( len ) *len = txt.l;
return txt.s;
}
const char **bcf_hdr_seqnames(const bcf_hdr_t *h, int *n)
{
vdict_t *d = (vdict_t*)h->dict[BCF_DT_CTG];
int tid, m = kh_size(d);
const char **names = (const char**) calloc(m,sizeof(const char*));
khint_t k;
for (k=kh_begin(d); k<kh_end(d); k++)
{
if ( !kh_exist(d,k) ) continue;
tid = kh_val(d,k).id;
assert( tid<m );
names[tid] = kh_key(d,k);
}
// sanity check: there should be no gaps
for (tid=0; tid<m; tid++)
assert(names[tid]);
*n = m;
return names;
}
int vcf_hdr_write(htsFile *fp, const bcf_hdr_t *h)
{
int hlen;
char *htxt = bcf_hdr_fmt_text(h, 0, &hlen);
while (hlen && htxt[hlen-1] == 0) --hlen; // kill trailing zeros
int ret;
if ( fp->is_compressed==1 )
ret = bgzf_write(fp->fp.bgzf, htxt, hlen);
else
ret = hwrite(fp->fp.hfile, htxt, hlen);
free(htxt);
return ret<0 ? -1 : 0;
}
/***********************
*** Typed value I/O ***
***********************/
void bcf_enc_vint(kstring_t *s, int n, int32_t *a, int wsize)
{
int32_t max = INT32_MIN + 1, min = INT32_MAX;
int i;
if (n == 0) bcf_enc_size(s, 0, BCF_BT_NULL);
else if (n == 1) bcf_enc_int1(s, a[0]);
else {
if (wsize <= 0) wsize = n;
for (i = 0; i < n; ++i) {
if (a[i] == bcf_int32_missing || a[i] == bcf_int32_vector_end ) continue;
if (max < a[i]) max = a[i];
if (min > a[i]) min = a[i];
}
if (max <= INT8_MAX && min > bcf_int8_vector_end) {
bcf_enc_size(s, wsize, BCF_BT_INT8);
for (i = 0; i < n; ++i)
if ( a[i]==bcf_int32_vector_end ) kputc(bcf_int8_vector_end, s);
else if ( a[i]==bcf_int32_missing ) kputc(bcf_int8_missing, s);
else kputc(a[i], s);
} else if (max <= INT16_MAX && min > bcf_int16_vector_end) {
bcf_enc_size(s, wsize, BCF_BT_INT16);
for (i = 0; i < n; ++i)
{
int16_t x;
if ( a[i]==bcf_int32_vector_end ) x = bcf_int16_vector_end;
else if ( a[i]==bcf_int32_missing ) x = bcf_int16_missing;
else x = a[i];
kputsn((char*)&x, 2, s);
}
} else {
bcf_enc_size(s, wsize, BCF_BT_INT32);
for (i = 0; i < n; ++i) {
int32_t x = a[i];
kputsn((char*)&x, 4, s);
}
}
}
}
void bcf_enc_vfloat(kstring_t *s, int n, float *a)
{
bcf_enc_size(s, n, BCF_BT_FLOAT);
kputsn((char*)a, n << 2, s);
}
void bcf_enc_vchar(kstring_t *s, int l, const char *a)
{
bcf_enc_size(s, l, BCF_BT_CHAR);
kputsn(a, l, s);
}
void bcf_fmt_array(kstring_t *s, int n, int type, void *data)
{
int j = 0;
if (n == 0) {
kputc('.', s);
return;
}
if (type == BCF_BT_CHAR)
{
char *p = (char*)data;
for (j = 0; j < n && *p; ++j, ++p)
{
if ( *p==bcf_str_missing ) kputc('.', s);
else kputc(*p, s);
}
}
else
{
#define BRANCH(type_t, is_missing, is_vector_end, kprint) { \
type_t *p = (type_t *) data; \
for (j=0; j<n; j++) \
{ \
if ( is_vector_end ) break; \
if ( j ) kputc(',', s); \
if ( is_missing ) kputc('.', s); \
else kprint; \
} \
}
switch (type) {
case BCF_BT_INT8: BRANCH(int8_t, p[j]==bcf_int8_missing, p[j]==bcf_int8_vector_end, kputw(p[j], s)); break;
case BCF_BT_INT16: BRANCH(int16_t, p[j]==bcf_int16_missing, p[j]==bcf_int16_vector_end, kputw(p[j], s)); break;
case BCF_BT_INT32: BRANCH(int32_t, p[j]==bcf_int32_missing, p[j]==bcf_int32_vector_end, kputw(p[j], s)); break;
case BCF_BT_FLOAT: BRANCH(float, bcf_float_is_missing(p[j]), bcf_float_is_vector_end(p[j]), ksprintf(s, "%g", p[j])); break;
default: fprintf(stderr,"todo: type %d\n", type); exit(1); break;
}
#undef BRANCH
}
}
uint8_t *bcf_fmt_sized_array(kstring_t *s, uint8_t *ptr)
{
int x, type;
x = bcf_dec_size(ptr, &ptr, &type);
bcf_fmt_array(s, x, type, ptr);
return ptr + (x << bcf_type_shift[type]);
}
/********************
*** VCF site I/O ***
********************/
typedef struct {
int key, max_m, size, offset;
uint32_t is_gt:1, max_g:15, max_l:16;
uint32_t y;
uint8_t *buf;
} fmt_aux_t;
static inline void align_mem(kstring_t *s)
{
if (s->l&7) {
uint64_t zero = 0;
int l = ((s->l + 7)>>3<<3) - s->l;
kputsn((char*)&zero, l, s);
}
}
// p,q is the start and the end of the FORMAT field
int _vcf_parse_format(kstring_t *s, const bcf_hdr_t *h, bcf1_t *v, char *p, char *q)
{
if ( !bcf_hdr_nsamples(h) ) return 0;
char *r, *t;
int j, l, m, g;
khint_t k;
ks_tokaux_t aux1;
vdict_t *d = (vdict_t*)h->dict[BCF_DT_ID];
kstring_t *mem = (kstring_t*)&h->mem;
mem->l = 0;
// count the number of format fields
for (r = p, v->n_fmt = 1; *r; ++r)
if (*r == ':') ++v->n_fmt;
char *end = s->s + s->l;
if ( q>=end )
{
fprintf(stderr,"[%s:%d %s] Error: FORMAT column with no sample columns starting at %s:%d\n", __FILE__,__LINE__,__FUNCTION__,s->s,v->pos+1);
return -1;
}
fmt_aux_t *fmt = (fmt_aux_t*)alloca(v->n_fmt * sizeof(fmt_aux_t));
// get format information from the dictionary
for (j = 0, t = kstrtok(p, ":", &aux1); t; t = kstrtok(0, 0, &aux1), ++j) {
*(char*)aux1.p = 0;
k = kh_get(vdict, d, t);
if (k == kh_end(d) || kh_val(d, k).info[BCF_HL_FMT] == 15) {
fprintf(stderr, "[W::%s] FORMAT '%s' is not defined in the header, assuming Type=String\n", __func__, t);
kstring_t tmp = {0,0,0};
int l;
ksprintf(&tmp, "##FORMAT=<ID=%s,Number=1,Type=String,Description=\"Dummy\">", t);
bcf_hrec_t *hrec = bcf_hdr_parse_line(h,tmp.s,&l);
free(tmp.s);
if ( bcf_hdr_add_hrec((bcf_hdr_t*)h, hrec) ) bcf_hdr_sync((bcf_hdr_t*)h);
k = kh_get(vdict, d, t);
v->errcode = BCF_ERR_TAG_UNDEF;
}
fmt[j].max_l = fmt[j].max_m = fmt[j].max_g = 0;
fmt[j].key = kh_val(d, k).id;
fmt[j].is_gt = !strcmp(t, "GT");
fmt[j].y = h->id[0][fmt[j].key].val->info[BCF_HL_FMT];
}
// compute max
int n_sample_ori = -1;
r = q + 1; // r: position in the format string
m = l = g = 1, v->n_sample = 0; // m: max vector size, l: max field len, g: max number of alleles
while ( r<end )
{
// can we skip some samples?
if ( h->keep_samples )
{
n_sample_ori++;
if ( !bit_array_test(h->keep_samples,n_sample_ori) )
{
while ( *r!='\t' && r<end ) r++;
if ( *r=='\t' ) { *r = 0; r++; }
continue;
}
}
// collect fmt stats: max vector size, length, number of alleles
j = 0; // j-th format field
for (;;)
{
if ( *r == '\t' ) *r = 0;
if ( *r == ':' || !*r ) // end of field or end of sample
{
if (fmt[j].max_m < m) fmt[j].max_m = m;
if (fmt[j].max_l < l - 1) fmt[j].max_l = l - 1;
if (fmt[j].is_gt && fmt[j].max_g < g) fmt[j].max_g = g;
l = 0, m = g = 1;
if ( *r==':' ) j++;
else break;
}
else if ( *r== ',' ) m++;
else if ( fmt[j].is_gt && (*r == '|' || *r == '/') ) g++;
if ( r>=end ) break;
r++; l++;
}
v->n_sample++;
if ( v->n_sample == bcf_hdr_nsamples(h) ) break;
r++;
}
// allocate memory for arrays
for (j = 0; j < v->n_fmt; ++j) {
fmt_aux_t *f = &fmt[j];
if ( !f->max_m ) f->max_m = 1; // omitted trailing format field
if ((f->y>>4&0xf) == BCF_HT_STR) {
f->size = f->is_gt? f->max_g << 2 : f->max_l;
} else if ((f->y>>4&0xf) == BCF_HT_REAL || (f->y>>4&0xf) == BCF_HT_INT) {
f->size = f->max_m << 2;
} else
{
fprintf(stderr, "[E::%s] the format type %d currently not supported\n", __func__, f->y>>4&0xf);
abort(); // I do not know how to do with Flag in the genotype fields
}
align_mem(mem);
f->offset = mem->l;
ks_resize(mem, mem->l + v->n_sample * f->size);
mem->l += v->n_sample * f->size;
}
for (j = 0; j < v->n_fmt; ++j)
fmt[j].buf = (uint8_t*)mem->s + fmt[j].offset;
// fill the sample fields; at beginning of the loop, t points to the first char of a format
n_sample_ori = -1;
t = q + 1; m = 0; // m: sample id
while ( t<end )
{
// can we skip some samples?
if ( h->keep_samples )
{
n_sample_ori++;
if ( !bit_array_test(h->keep_samples,n_sample_ori) )
{
while ( *t && t<end ) t++;
t++;
continue;
}
}
if ( m == bcf_hdr_nsamples(h) ) break;
j = 0; // j-th format field, m-th sample
while ( *t )
{
fmt_aux_t *z = &fmt[j];
if ((z->y>>4&0xf) == BCF_HT_STR) {
if (z->is_gt) { // genotypes
int32_t is_phased = 0, *x = (int32_t*)(z->buf + z->size * m);
for (l = 0;; ++t) {
if (*t == '.') ++t, x[l++] = is_phased;
else x[l++] = (strtol(t, &t, 10) + 1) << 1 | is_phased;
#if THOROUGH_SANITY_CHECKS
assert( 0 ); // success of strtol,strtod not checked
#endif
is_phased = (*t == '|');
if (*t == ':' || *t == 0) break;
}
if ( !l ) x[l++] = 0; // An empty field, insert missing value
for (; l < z->size>>2; ++l) x[l] = bcf_int32_vector_end;
} else {
char *x = (char*)z->buf + z->size * m;
for (r = t, l = 0; *t != ':' && *t; ++t) x[l++] = *t;
for (; l < z->size; ++l) x[l] = 0;
}
} else if ((z->y>>4&0xf) == BCF_HT_INT) {
int32_t *x = (int32_t*)(z->buf + z->size * m);
for (l = 0;; ++t) {
if (*t == '.') x[l++] = bcf_int32_missing, ++t; // ++t to skip "."
else x[l++] = strtol(t, &t, 10);
if (*t == ':' || *t == 0) break;
}
if ( !l ) x[l++] = bcf_int32_missing;
for (; l < z->size>>2; ++l) x[l] = bcf_int32_vector_end;
} else if ((z->y>>4&0xf) == BCF_HT_REAL) {
float *x = (float*)(z->buf + z->size * m);
for (l = 0;; ++t) {
if (*t == '.' && !isdigit(t[1])) bcf_float_set_missing(x[l++]), ++t; // ++t to skip "."
else x[l++] = strtod(t, &t);
if (*t == ':' || *t == 0) break;
}
if ( !l ) bcf_float_set_missing(x[l++]); // An empty field, insert missing value
for (; l < z->size>>2; ++l) bcf_float_set_vector_end(x[l]);
} else abort();
if (*t == 0) {
for (++j; j < v->n_fmt; ++j) { // fill end-of-vector values
z = &fmt[j];
if ((z->y>>4&0xf) == BCF_HT_STR) {
if (z->is_gt) {
int32_t *x = (int32_t*)(z->buf + z->size * m);
x[0] = bcf_int32_missing;
for (l = 1; l < z->size>>2; ++l) x[l] = bcf_int32_vector_end;
} else {
char *x = (char*)z->buf + z->size * m;
if ( z->size ) x[0] = '.';
for (l = 1; l < z->size; ++l) x[l] = 0;
}
} else if ((z->y>>4&0xf) == BCF_HT_INT) {
int32_t *x = (int32_t*)(z->buf + z->size * m);
x[0] = bcf_int32_missing;
for (l = 1; l < z->size>>2; ++l) x[l] = bcf_int32_vector_end;
} else if ((z->y>>4&0xf) == BCF_HT_REAL) {
float *x = (float*)(z->buf + z->size * m);
bcf_float_set_missing(x[0]);
for (l = 1; l < z->size>>2; ++l) bcf_float_set_vector_end(x[l]);
}
}
break;
}
else
{
if (*t == ':') ++j;
t++;
}
}
m++; t++;
}
// write individual genotype information
kstring_t *str = &v->indiv;
int i;
if (v->n_sample > 0) {
for (i = 0; i < v->n_fmt; ++i) {
fmt_aux_t *z = &fmt[i];
bcf_enc_int1(str, z->key);
if ((z->y>>4&0xf) == BCF_HT_STR && !z->is_gt) {
bcf_enc_size(str, z->size, BCF_BT_CHAR);
kputsn((char*)z->buf, z->size * v->n_sample, str);
} else if ((z->y>>4&0xf) == BCF_HT_INT || z->is_gt) {
bcf_enc_vint(str, (z->size>>2) * v->n_sample, (int32_t*)z->buf, z->size>>2);
} else {
bcf_enc_size(str, z->size>>2, BCF_BT_FLOAT);
kputsn((char*)z->buf, z->size * v->n_sample, str);
}
}
}
return 0;
}
int vcf_parse(kstring_t *s, const bcf_hdr_t *h, bcf1_t *v)
{
int i = 0;
char *p, *q, *r, *t;
kstring_t *str;
khint_t k;
ks_tokaux_t aux;
bcf_clear1(v);
str = &v->shared;
memset(&aux, 0, sizeof(ks_tokaux_t));
for (p = kstrtok(s->s, "\t", &aux), i = 0; p; p = kstrtok(0, 0, &aux), ++i) {
q = (char*)aux.p;
*q = 0;
if (i == 0) { // CHROM
vdict_t *d = (vdict_t*)h->dict[BCF_DT_CTG];
k = kh_get(vdict, d, p);
if (k == kh_end(d))
{
// Simple error recovery for chromosomes not defined in the header. It will not help when VCF header has
// been already printed, but will enable tools like vcfcheck to proceed.
fprintf(stderr, "[W::%s] contig '%s' is not defined in the header. (Quick workaround: index the file with tabix.)\n", __func__, p);
kstring_t tmp = {0,0,0};
int l;
ksprintf(&tmp, "##contig=<ID=%s,length=2147483647>", p);
bcf_hrec_t *hrec = bcf_hdr_parse_line(h,tmp.s,&l);
free(tmp.s);
if ( bcf_hdr_add_hrec((bcf_hdr_t*)h, hrec) ) bcf_hdr_sync((bcf_hdr_t*)h);
k = kh_get(vdict, d, p);
v->errcode = BCF_ERR_CTG_UNDEF;
}
v->rid = kh_val(d, k).id;
} else if (i == 1) { // POS
v->pos = atoi(p) - 1;
} else if (i == 2) { // ID
if (strcmp(p, ".")) bcf_enc_vchar(str, q - p, p);
else bcf_enc_size(str, 0, BCF_BT_CHAR);
} else if (i == 3) { // REF
bcf_enc_vchar(str, q - p, p);
v->n_allele = 1, v->rlen = q - p;
} else if (i == 4) { // ALT
if (strcmp(p, ".")) {
for (r = t = p;; ++r) {
if (*r == ',' || *r == 0) {
bcf_enc_vchar(str, r - t, t);
t = r + 1;
++v->n_allele;
}
if (r == q) break;
}
}
} else if (i == 5) { // QUAL
if (strcmp(p, ".")) v->qual = atof(p);
else memcpy(&v->qual, &bcf_float_missing, 4);
if ( v->max_unpack && !(v->max_unpack>>1) ) return 0; // BCF_UN_STR
} else if (i == 6) { // FILTER
if (strcmp(p, ".")) {
int32_t *a;
int n_flt = 1, i;
ks_tokaux_t aux1;
vdict_t *d = (vdict_t*)h->dict[BCF_DT_ID];
// count the number of filters
if (*(q-1) == ';') *(q-1) = 0;
for (r = p; *r; ++r)
if (*r == ';') ++n_flt;
a = (int32_t*)alloca(n_flt * 4);
// add filters
for (t = kstrtok(p, ";", &aux1), i = 0; t; t = kstrtok(0, 0, &aux1)) {
*(char*)aux1.p = 0;
k = kh_get(vdict, d, t);
if (k == kh_end(d))
{
// Simple error recovery for FILTERs not defined in the header. It will not help when VCF header has
// been already printed, but will enable tools like vcfcheck to proceed.
fprintf(stderr, "[W::%s] FILTER '%s' is not defined in the header\n", __func__, t);
kstring_t tmp = {0,0,0};
int l;
ksprintf(&tmp, "##FILTER=<ID=%s,Description=\"Dummy\">", t);
bcf_hrec_t *hrec = bcf_hdr_parse_line(h,tmp.s,&l);
free(tmp.s);
if ( bcf_hdr_add_hrec((bcf_hdr_t*)h, hrec) ) bcf_hdr_sync((bcf_hdr_t*)h);
k = kh_get(vdict, d, t);
v->errcode = BCF_ERR_TAG_UNDEF;
}
a[i++] = kh_val(d, k).id;
}
n_flt = i;
bcf_enc_vint(str, n_flt, a, -1);
} else bcf_enc_vint(str, 0, 0, -1);
if ( v->max_unpack && !(v->max_unpack>>2) ) return 0; // BCF_UN_FLT
} else if (i == 7) { // INFO
char *key;
vdict_t *d = (vdict_t*)h->dict[BCF_DT_ID];
v->n_info = 0;
if (strcmp(p, ".")) {
if (*(q-1) == ';') *(q-1) = 0;
for (r = key = p;; ++r) {
int c;
char *val, *end;
if (*r != ';' && *r != '=' && *r != 0) continue;
val = end = 0;
c = *r; *r = 0;
if (c == '=') {
val = r + 1;
for (end = val; *end != ';' && *end != 0; ++end);
c = *end; *end = 0;
} else end = r;
k = kh_get(vdict, d, key);
if (k == kh_end(d) || kh_val(d, k).info[BCF_HL_INFO] == 15)
{
fprintf(stderr, "[W::%s] INFO '%s' is not defined in the header, assuming Type=String\n", __func__, key);
kstring_t tmp = {0,0,0};
int l;
ksprintf(&tmp, "##INFO=<ID=%s,Number=1,Type=String,Description=\"Dummy\">", key);
bcf_hrec_t *hrec = bcf_hdr_parse_line(h,tmp.s,&l);
free(tmp.s);
if ( bcf_hdr_add_hrec((bcf_hdr_t*)h, hrec) ) bcf_hdr_sync((bcf_hdr_t*)h);
k = kh_get(vdict, d, key);
v->errcode = BCF_ERR_TAG_UNDEF;
}
uint32_t y = kh_val(d, k).info[BCF_HL_INFO];
++v->n_info;
bcf_enc_int1(str, kh_val(d, k).id);
if (val == 0) {
bcf_enc_size(str, 0, BCF_BT_NULL);
} else if ((y>>4&0xf) == BCF_HT_FLAG || (y>>4&0xf) == BCF_HT_STR) { // if Flag has a value, treat it as a string
bcf_enc_vchar(str, end - val, val);
} else { // int/float value/array
int i, n_val;
char *t;
for (t = val, n_val = 1; *t; ++t) // count the number of values
if (*t == ',') ++n_val;
if ((y>>4&0xf) == BCF_HT_INT) {
int32_t *z;
z = (int32_t*)alloca(n_val<<2);
for (i = 0, t = val; i < n_val; ++i, ++t)
z[i] = strtol(t, &t, 10);
bcf_enc_vint(str, n_val, z, -1);
if (strcmp(key, "END") == 0) v->rlen = z[0] - v->pos;
} else if ((y>>4&0xf) == BCF_HT_REAL) {
float *z;
z = (float*)alloca(n_val<<2);
for (i = 0, t = val; i < n_val; ++i, ++t)
z[i] = strtod(t, &t);
bcf_enc_vfloat(str, n_val, z);
}
}
if (c == 0) break;
r = end;
key = r + 1;
}
}
if ( v->max_unpack && !(v->max_unpack>>3) ) return 0;
} else if (i == 8) // FORMAT
return _vcf_parse_format(s, h, v, p, q);
}
return 0;
}
int vcf_read(htsFile *fp, const bcf_hdr_t *h, bcf1_t *v)
{
int ret;
ret = hts_getline(fp, KS_SEP_LINE, &fp->line);
if (ret < 0) return -1;
return vcf_parse1(&fp->line, h, v);
}
static inline uint8_t *bcf_unpack_fmt_core1(uint8_t *ptr, int n_sample, bcf_fmt_t *fmt)
{
uint8_t *ptr_start = ptr;
fmt->id = bcf_dec_typed_int1(ptr, &ptr);
fmt->n = bcf_dec_size(ptr, &ptr, &fmt->type);
fmt->size = fmt->n << bcf_type_shift[fmt->type];
fmt->p = ptr;
fmt->p_off = ptr - ptr_start;
fmt->p_free = 0;
ptr += n_sample * fmt->size;
fmt->p_len = ptr - fmt->p;
return ptr;
}
static inline uint8_t *bcf_unpack_info_core1(uint8_t *ptr, bcf_info_t *info)
{
uint8_t *ptr_start = ptr;
info->key = bcf_dec_typed_int1(ptr, &ptr);
info->len = bcf_dec_size(ptr, &ptr, &info->type);
info->vptr = ptr;
info->vptr_off = ptr - ptr_start;
info->vptr_free = 0;
info->v1.i = 0;
if (info->len == 1) {
if (info->type == BCF_BT_INT8 || info->type == BCF_BT_CHAR) info->v1.i = *(int8_t*)ptr;
else if (info->type == BCF_BT_INT32) info->v1.i = *(int32_t*)ptr;
else if (info->type == BCF_BT_FLOAT) info->v1.f = *(float*)ptr;
else if (info->type == BCF_BT_INT16) info->v1.i = *(int16_t*)ptr;
}
ptr += info->len << bcf_type_shift[info->type];
info->vptr_len = ptr - info->vptr;
return ptr;
}
int bcf_unpack(bcf1_t *b, int which)
{
if ( !b->shared.l ) return 0; // Building a new BCF record from scratch
uint8_t *ptr = (uint8_t*)b->shared.s, *ptr_ori;
int *offset, i;
bcf_dec_t *d = &b->d;
if (which & BCF_UN_FLT) which |= BCF_UN_STR;
if (which & BCF_UN_INFO) which |= BCF_UN_SHR;
if ((which&BCF_UN_STR) && !(b->unpacked&BCF_UN_STR))
{
kstring_t tmp;
// ID
tmp.l = 0; tmp.s = d->id; tmp.m = d->m_id;
ptr_ori = ptr;
ptr = bcf_fmt_sized_array(&tmp, ptr);
b->unpack_size[0] = ptr - ptr_ori;
kputc('\0', &tmp);
d->id = tmp.s; d->m_id = tmp.m;
// REF and ALT are in a single block (d->als) and d->alleles are pointers into this block
tmp.l = 0; tmp.s = d->als; tmp.m = d->m_als;
offset = (int*)alloca(b->n_allele * sizeof(int));
ptr_ori = ptr;
for (i = 0; i < b->n_allele; ++i) {
offset[i] = tmp.l;
ptr = bcf_fmt_sized_array(&tmp, ptr);
kputc('\0', &tmp);
}
b->unpack_size[1] = ptr - ptr_ori;
d->als = tmp.s; d->m_als = tmp.m;
hts_expand(char*, b->n_allele, d->m_allele, d->allele); // NM: hts_expand() is a macro
for (i = 0; i < b->n_allele; ++i)
d->allele[i] = d->als + offset[i];
b->unpack_ptr = ptr;
b->unpacked |= BCF_UN_STR;
}
if ((which&BCF_UN_FLT) && !(b->unpacked&BCF_UN_FLT)) { // FILTER
ptr = b->unpack_ptr;
ptr_ori = ptr;
if (*ptr>>4) {
int type;
d->n_flt = bcf_dec_size(ptr, &ptr, &type);
hts_expand(int, d->n_flt, d->m_flt, d->flt);
for (i = 0; i < d->n_flt; ++i)
d->flt[i] = bcf_dec_int1(ptr, type, &ptr);
} else ++ptr, d->n_flt = 0;
b->unpack_size[2] = ptr - ptr_ori;
b->unpack_ptr = ptr;
b->unpacked |= BCF_UN_FLT;
}
if ((which&BCF_UN_INFO) && !(b->unpacked&BCF_UN_INFO)) { // INFO
ptr = b->unpack_ptr;
hts_expand(bcf_info_t, b->n_info, d->m_info, d->info);
for (i = 0; i < d->m_info; ++i) d->info[i].vptr_free = 0;
for (i = 0; i < b->n_info; ++i)
ptr = bcf_unpack_info_core1(ptr, &d->info[i]);
b->unpacked |= BCF_UN_INFO;
}
if ((which&BCF_UN_FMT) && b->n_sample && !(b->unpacked&BCF_UN_FMT)) { // FORMAT
ptr = (uint8_t*)b->indiv.s;
hts_expand(bcf_fmt_t, b->n_fmt, d->m_fmt, d->fmt);
for (i = 0; i < d->m_fmt; ++i) d->fmt[i].p_free = 0;
for (i = 0; i < b->n_fmt; ++i)
ptr = bcf_unpack_fmt_core1(ptr, b->n_sample, &d->fmt[i]);
b->unpacked |= BCF_UN_FMT;
}
return 0;
}
int vcf_format(const bcf_hdr_t *h, const bcf1_t *v, kstring_t *s)
{
int i;
bcf_unpack((bcf1_t*)v, BCF_UN_ALL);
kputs(h->id[BCF_DT_CTG][v->rid].key, s); // CHROM
kputc('\t', s); kputw(v->pos + 1, s); // POS
kputc('\t', s); kputs(v->d.id ? v->d.id : ".", s); // ID
kputc('\t', s); // REF
if (v->n_allele > 0) kputs(v->d.allele[0], s);
else kputc('.', s);
kputc('\t', s); // ALT
if (v->n_allele > 1) {
for (i = 1; i < v->n_allele; ++i) {
if (i > 1) kputc(',', s);
kputs(v->d.allele[i], s);
}
} else kputc('.', s);
kputc('\t', s); // QUAL
if (memcmp(&v->qual, &bcf_float_missing, 4) == 0) kputc('.', s); // QUAL
else ksprintf(s, "%g", v->qual);
kputc('\t', s); // FILTER
if (v->d.n_flt) {
for (i = 0; i < v->d.n_flt; ++i) {
if (i) kputc(';', s);
kputs(h->id[BCF_DT_ID][v->d.flt[i]].key, s);
}
} else kputc('.', s);
kputc('\t', s); // INFO
if (v->n_info) {
int first = 1;
for (i = 0; i < v->n_info; ++i) {
bcf_info_t *z = &v->d.info[i];
if ( !z->vptr ) continue;
if ( !first ) kputc(';', s); first = 0;
kputs(h->id[BCF_DT_ID][z->key].key, s);
if (z->len <= 0) continue;
kputc('=', s);
if (z->len == 1) {
if (z->type == BCF_BT_FLOAT) ksprintf(s, "%g", z->v1.f);
else if (z->type != BCF_BT_CHAR) kputw(z->v1.i, s);
else kputc(z->v1.i, s);
} else bcf_fmt_array(s, z->len, z->type, z->vptr);
}
if ( first ) kputc('.', s);
} else kputc('.', s);
// FORMAT and individual information
if (v->n_sample)
{
int i,j;
if ( v->n_fmt)
{
int gt_i = -1;
bcf_fmt_t *fmt = v->d.fmt;
int first = 1;
for (i = 0; i < (int)v->n_fmt; ++i) {
if ( !fmt[i].p ) continue;
kputc(!first ? ':' : '\t', s); first = 0;
if ( fmt[i].id<0 ) //!bcf_hdr_idinfo_exists(h,BCF_HL_FMT,fmt[i].id) )
{
fprintf(stderr, "[E::%s] invalid BCF, the FORMAT tag id=%d not present in the header.\n", __func__, fmt[i].id);
abort();
}
kputs(h->id[BCF_DT_ID][fmt[i].id].key, s);
if (strcmp(h->id[BCF_DT_ID][fmt[i].id].key, "GT") == 0) gt_i = i;
}
if ( first ) kputs("\t.", s);
for (j = 0; j < v->n_sample; ++j) {
kputc('\t', s);
first = 1;
for (i = 0; i < (int)v->n_fmt; ++i) {
bcf_fmt_t *f = &fmt[i];
if ( !f->p ) continue;
if (!first) kputc(':', s); first = 0;
if (gt_i == i)
bcf_format_gt(f,j,s);
else
bcf_fmt_array(s, f->n, f->type, f->p + j * f->size);
}
if ( first ) kputc('.', s);
}
}
else
for (j=0; j<=v->n_sample; j++)
kputs("\t.", s);
}
kputc('\n', s);
return 0;
}
int vcf_write_line(htsFile *fp, kstring_t *line)
{
int ret;
if ( line->s[line->l-1]!='\n' ) kputc('\n',line);
if ( fp->is_compressed==1 )
ret = bgzf_write(fp->fp.bgzf, line->s, line->l);
else
ret = hwrite(fp->fp.hfile, line->s, line->l);
return ret==line->l ? 0 : -1;
}
int vcf_write(htsFile *fp, const bcf_hdr_t *h, bcf1_t *v)
{
int ret;
fp->line.l = 0;
vcf_format1(h, v, &fp->line);
if ( fp->is_compressed==1 )
ret = bgzf_write(fp->fp.bgzf, fp->line.s, fp->line.l);
else
ret = hwrite(fp->fp.hfile, fp->line.s, fp->line.l);
return ret==fp->line.l ? 0 : -1;
}
/************************
* Data access routines *
************************/
int bcf_hdr_id2int(const bcf_hdr_t *h, int which, const char *id)
{
khint_t k;
vdict_t *d = (vdict_t*)h->dict[which];
k = kh_get(vdict, d, id);
return k == kh_end(d)? -1 : kh_val(d, k).id;
}
/********************
*** BCF indexing ***
********************/
hts_idx_t *bcf_index(htsFile *fp, int min_shift)
{
int n_lvls, i;
bcf1_t *b;
hts_idx_t *idx;
bcf_hdr_t *h;
int64_t max_len = 0, s;
h = bcf_hdr_read(fp);
if ( !h ) return NULL;
int nids = 0;
for (i = 0; i < h->n[BCF_DT_CTG]; ++i)
{
if ( !h->id[BCF_DT_CTG][i].val ) continue;
if ( max_len < h->id[BCF_DT_CTG][i].val->info[0] ) max_len = h->id[BCF_DT_CTG][i].val->info[0];
nids++;
}
if ( !max_len ) max_len = ((int64_t)1<<31) - 1; // In case contig line is broken.
max_len += 256;
for (n_lvls = 0, s = 1<<min_shift; max_len > s; ++n_lvls, s <<= 3);
idx = hts_idx_init(nids, HTS_FMT_CSI, bgzf_tell(fp->fp.bgzf), min_shift, n_lvls);
b = bcf_init1();
while (bcf_read1(fp,h, b) >= 0) {
int ret;
ret = hts_idx_push(idx, b->rid, b->pos, b->pos + b->rlen, bgzf_tell(fp->fp.bgzf), 1);
if (ret < 0) break;
}
hts_idx_finish(idx, bgzf_tell(fp->fp.bgzf));
bcf_destroy1(b);
bcf_hdr_destroy(h);
return idx;
}
int bcf_index_build(const char *fn, int min_shift)
{
htsFile *fp;
hts_idx_t *idx;
if ((fp = hts_open(fn, "rb")) == 0) return -1;
if ( !fp->fp.bgzf->is_compressed ) { hts_close(fp); return -1; }
idx = bcf_index(fp, min_shift);
hts_close(fp);
if ( !idx ) return -1;
hts_idx_save(idx, fn, HTS_FMT_CSI);
hts_idx_destroy(idx);
return 0;
}
/*****************
*** Utilities ***
*****************/
void bcf_hdr_combine(bcf_hdr_t *dst, const bcf_hdr_t *src)
{
int i, ndst_ori = dst->nhrec, need_sync = 0;
for (i=0; i<src->nhrec; i++)
{
if ( src->hrec[i]->type==BCF_HL_GEN && src->hrec[i]->value )
{
int j;
for (j=0; j<ndst_ori; j++)
{
if ( dst->hrec[j]->type!=BCF_HL_GEN ) continue;
if ( !strcmp(src->hrec[i]->key,dst->hrec[j]->key) && !strcmp(src->hrec[i]->value,dst->hrec[j]->value) ) break;
}
if ( j>=ndst_ori )
need_sync += bcf_hdr_add_hrec(dst, bcf_hrec_dup(src->hrec[i]));
}
else
{
bcf_hrec_t *rec = bcf_hdr_get_hrec(dst, src->hrec[i]->type, src->hrec[i]->vals[0]);
if ( !rec )
need_sync += bcf_hdr_add_hrec(dst, bcf_hrec_dup(src->hrec[i]));
}
}
if ( need_sync ) bcf_hdr_sync(dst);
}
int bcf_translate(const bcf_hdr_t *dst_hdr, bcf_hdr_t *src_hdr, bcf1_t *line)
{
int i;
if ( line->errcode )
{
fprintf(stderr,"[%s:%d %s] Unchecked error (%d), exiting.\n", __FILE__,__LINE__,__FUNCTION__,line->errcode);
exit(1);
}
if ( src_hdr->ntransl==-1 ) return 0; // no need to translate, all tags have the same id
if ( !src_hdr->ntransl ) // called for the first time, see what needs translating
{
int dict;
for (dict=0; dict<2; dict++) // BCF_DT_ID and BCF_DT_CTG
{
src_hdr->transl[dict] = (int*) malloc(src_hdr->n[dict]*sizeof(int));
for (i=0; i<src_hdr->n[dict]; i++)
{
if ( i>=dst_hdr->n[dict] || strcmp(src_hdr->id[dict][i].key,dst_hdr->id[dict][i].key) )
{
src_hdr->transl[dict][i] = bcf_hdr_id2int(dst_hdr,dict,src_hdr->id[dict][i].key);
src_hdr->ntransl++;
}
else
src_hdr->transl[dict][i] = -1;
}
}
if ( !src_hdr->ntransl )
{
free(src_hdr->transl[0]); src_hdr->transl[0] = NULL;
free(src_hdr->transl[1]); src_hdr->transl[1] = NULL;
src_hdr->ntransl = -1;
}
if ( src_hdr->ntransl==-1 ) return 0;
}
bcf_unpack(line,BCF_UN_ALL);
// CHROM
if ( src_hdr->transl[BCF_DT_CTG][line->rid] >=0 ) line->rid = src_hdr->transl[BCF_DT_CTG][line->rid];
// FILTER
for (i=0; i<line->d.n_flt; i++)
{
int src_id = line->d.flt[i];
if ( src_hdr->transl[BCF_DT_ID][src_id] >=0 )
line->d.flt[i] = src_hdr->transl[BCF_DT_ID][src_id];
}
// INFO
for (i=0; i<line->n_info; i++)
{
int src_id = line->d.info[i].key;
int dst_id = src_hdr->transl[BCF_DT_ID][src_id];
if ( dst_id<0 ) continue;
int src_size = src_id>>7 ? ( src_id>>15 ? BCF_BT_INT32 : BCF_BT_INT16) : BCF_BT_INT8;
int dst_size = dst_id>>7 ? ( dst_id>>15 ? BCF_BT_INT32 : BCF_BT_INT16) : BCF_BT_INT8;
if ( src_size==dst_size ) // can overwrite
{
line->d.info[i].key = dst_id;
uint8_t *vptr = line->d.info[i].vptr - line->d.info[i].vptr_off;
if ( dst_size==BCF_BT_INT8 ) { vptr[1] = (uint8_t)dst_id; }
else if ( dst_size==BCF_BT_INT16 ) { *(uint16_t*)vptr = (uint16_t)dst_id; }
else { *(uint32_t*)vptr = (uint32_t)dst_id; }
}
else // must realloc
{
bcf_info_t *info = &line->d.info[i];
assert( !info->vptr_free );
kstring_t str = {0,0,0};
bcf_enc_int1(&str, dst_id);
info->vptr_off = str.l;
kputsn((char*)info->vptr, info->vptr_len, &str);
info->vptr = (uint8_t*)str.s + info->vptr_off;
info->vptr_free = 1;
info->key = dst_id;
line->d.shared_dirty |= BCF1_DIRTY_INF;
}
}
// FORMAT
for (i=0; i<line->n_fmt; i++)
{
int src_id = line->d.fmt[i].id;
int dst_id = src_hdr->transl[BCF_DT_ID][src_id];
if ( dst_id<0 ) continue;
int src_size = src_id>>7 ? ( src_id>>15 ? BCF_BT_INT32 : BCF_BT_INT16) : BCF_BT_INT8;
int dst_size = dst_id>>7 ? ( dst_id>>15 ? BCF_BT_INT32 : BCF_BT_INT16) : BCF_BT_INT8;
if ( src_size==dst_size ) // can overwrite
{
line->d.fmt[i].id = dst_id;
uint8_t *p = line->d.fmt[i].p - line->d.fmt[i].p_off; // pointer to the vector size (4bits) and BT type (4bits)
if ( dst_size==BCF_BT_INT8 ) { p[1] = dst_id; }
else if ( dst_size==BCF_BT_INT16 ) { uint8_t *x = (uint8_t*) &dst_id; p[1] = x[0]; p[2] = x[1]; }
else { uint8_t *x = (uint8_t*) &dst_id; p[1] = x[0]; p[2] = x[1]; p[3] = x[2]; p[4] = x[3]; }
}
else // must realloc
{
bcf_fmt_t *fmt = &line->d.fmt[i];
assert( !fmt->p_free );
kstring_t str = {0,0,0};
bcf_enc_int1(&str, dst_id);
fmt->p_off = str.l;
kputsn((char*)fmt->p, fmt->p_len, &str);
fmt->p = (uint8_t*)str.s + fmt->p_off;
fmt->p_free = 1;
fmt->id = dst_id;
line->d.indiv_dirty = 1;
}
}
return 0;
}
bcf_hdr_t *bcf_hdr_dup(const bcf_hdr_t *hdr)
{
bcf_hdr_t *hout = bcf_hdr_init("r");
char *htxt = bcf_hdr_fmt_text(hdr, 1, NULL);
bcf_hdr_parse(hout, htxt);
free(htxt);
return hout;
}
bcf_hdr_t *bcf_hdr_subset(const bcf_hdr_t *h0, int n, char *const* samples, int *imap)
{
int hlen;
char *htxt = bcf_hdr_fmt_text(h0, 1, &hlen);
kstring_t str;
bcf_hdr_t *h;
str.l = str.m = 0; str.s = 0;
h = bcf_hdr_init("w");
int j;
for (j=0; j<n; j++) imap[j] = -1;
if ( bcf_hdr_nsamples(h0) > 0) {
char *p;
int i = 0, end = n? 8 : 7;
while ((p = strstr(htxt, "#CHROM\t")) != 0)
if (p > htxt && *(p-1) == '\n') break;
while ((p = strchr(p, '\t')) != 0 && i < end) ++i, ++p;
if (i != end) {
free(h); free(str.s);
return 0; // malformated header
}
kputsn(htxt, p - htxt, &str);
for (i = 0; i < n; ++i) {
imap[i] = bcf_hdr_id2int(h0, BCF_DT_SAMPLE, samples[i]);
if (imap[i] < 0) continue;
kputc('\t', &str);
kputs(samples[i], &str);
}
} else kputsn(htxt, hlen, &str);
while (str.l && (!str.s[str.l-1] || str.s[str.l-1]=='\n') ) str.l--; // kill trailing zeros and newlines
kputc('\n',&str);
bcf_hdr_parse(h, str.s);
free(str.s);
free(htxt);
return h;
}
int bcf_hdr_set_samples(bcf_hdr_t *hdr, const char *samples, int is_file)
{
if ( samples && !strcmp("-",samples) ) return 0; // keep all samples
hdr->nsamples_ori = bcf_hdr_nsamples(hdr);
if ( !samples ) { bcf_hdr_nsamples(hdr) = 0; return 0; } // exclude all samples
int i, narr = bit_array_size(bcf_hdr_nsamples(hdr));
hdr->keep_samples = (uint8_t*) calloc(narr,1);
if ( samples[0]=='^' )
for (i=0; i<bcf_hdr_nsamples(hdr); i++) bit_array_set(hdr->keep_samples,i);
int idx, n, ret = 0;
char **smpls = hts_readlist(samples[0]=='^'?samples+1:samples, is_file, &n);
if ( !smpls ) return -1;
for (i=0; i<n; i++)
{
idx = bcf_hdr_id2int(hdr,BCF_DT_SAMPLE,smpls[i]);
if ( idx<0 )
{
if ( !ret ) ret = i+1;
continue;
}
assert( idx<bcf_hdr_nsamples(hdr) );
if ( samples[0]=='^' )
bit_array_clear(hdr->keep_samples, idx);
else
bit_array_set(hdr->keep_samples, idx);
}
for (i=0; i<n; i++) free(smpls[i]);
free(smpls);
bcf_hdr_nsamples(hdr) = 0;
for (i=0; i<hdr->nsamples_ori; i++)
if ( bit_array_test(hdr->keep_samples,i) ) bcf_hdr_nsamples(hdr)++;
if ( !bcf_hdr_nsamples(hdr) ) { free(hdr->keep_samples); hdr->keep_samples=NULL; }
else
{
char **samples = (char**) malloc(sizeof(char*)*bcf_hdr_nsamples(hdr));
idx = 0;
for (i=0; i<hdr->nsamples_ori; i++)
if ( bit_array_test(hdr->keep_samples,i) ) samples[idx++] = strdup(hdr->samples[i]);
free(hdr->samples);
hdr->samples = samples;
// delete original samples from the dictionary
vdict_t *d = (vdict_t*)hdr->dict[BCF_DT_SAMPLE];
int k;
for (k = kh_begin(d); k != kh_end(d); ++k)
if (kh_exist(d, k)) free((char*)kh_key(d, k));
kh_destroy(vdict, d);
// add the subset back
hdr->dict[BCF_DT_SAMPLE] = d = kh_init(vdict);
for (i=0; i<bcf_hdr_nsamples(hdr); i++)
{
int ignore, k = kh_put(vdict, d, hdr->samples[i], &ignore);
kh_val(d, k) = bcf_idinfo_def;
kh_val(d, k).id = kh_size(d) - 1;
}
bcf_hdr_sync(hdr);
}
return ret;
}
int bcf_subset(const bcf_hdr_t *h, bcf1_t *v, int n, int *imap)
{
kstring_t ind;
ind.s = 0; ind.l = ind.m = 0;
if (n) {
bcf_fmt_t *fmt;
int i, j;
fmt = (bcf_fmt_t*)alloca(v->n_fmt * sizeof(bcf_fmt_t));
uint8_t *ptr = (uint8_t*)v->indiv.s;
for (i = 0; i < v->n_fmt; ++i)
ptr = bcf_unpack_fmt_core1(ptr, v->n_sample, &fmt[i]);
for (i = 0; i < (int)v->n_fmt; ++i) {
bcf_fmt_t *f = &fmt[i];
bcf_enc_int1(&ind, f->id);
bcf_enc_size(&ind, f->n, f->type);
for (j = 0; j < n; ++j)
if (imap[j] >= 0) kputsn((char*)(f->p + imap[j] * f->size), f->size, &ind);
}
for (i = j = 0; j < n; ++j) if (imap[j] >= 0) ++i;
v->n_sample = i;
} else v->n_sample = 0;
free(v->indiv.s);
v->indiv = ind;
v->unpacked &= ~BCF_UN_FMT; // only BCF is ready for output, VCF will need to unpack again
return 0;
}
int bcf_is_snp(bcf1_t *v)
{
int i;
bcf_unpack(v, BCF_UN_STR);
for (i = 0; i < v->n_allele; ++i)
if (strlen(v->d.allele[i]) != 1) break;
return i == v->n_allele;
}
static void bcf_set_variant_type(const char *ref, const char *alt, variant_t *var)
{
// The most frequent case
if ( !ref[1] && !alt[1] )
{
if ( *alt == '.' || *ref==*alt ) { var->n = 0; var->type = VCF_REF; return; }
if ( *alt == 'X' ) { var->n = 0; var->type = VCF_REF; return; } // mpileup's X allele shouldn't be treated as variant
var->n = 1; var->type = VCF_SNP; return;
}
const char *r = ref, *a = alt;
while (*r && *a && *r==*a ) { r++; a++; }
if ( *a && !*r )
{
while ( *a ) a++;
var->n = (a-alt)-(r-ref); var->type = VCF_INDEL; return;
}
else if ( *r && !*a )
{
while ( *r ) r++;
var->n = (a-alt)-(r-ref); var->type = VCF_INDEL; return;
}
else if ( !*r && !*a )
{
var->n = 0; var->type = VCF_REF; return;
}
const char *re = r, *ae = a;
while ( re[1] ) re++;
while ( ae[1] ) ae++;
while ( *re==*ae && re>r && ae>a ) { re--; ae--; }
if ( ae==a )
{
if ( re==r ) { var->n = 1; var->type = VCF_SNP; return; }
var->n = -(re-r);
if ( *re==*ae ) { var->type = VCF_INDEL; return; }
var->type = VCF_OTHER; return;
}
else if ( re==r )
{
var->n = ae-a;
if ( *re==*ae ) { var->type = VCF_INDEL; return; }
var->type = VCF_OTHER; return;
}
var->type = ( re-r == ae-a ) ? VCF_MNP : VCF_OTHER;
var->n = ( re-r > ae-a ) ? -(re-r+1) : ae-a+1;
// should do also complex events, SVs, etc...
}
static void bcf_set_variant_types(bcf1_t *b)
{
if ( !(b->unpacked & BCF_UN_STR) ) bcf_unpack(b, BCF_UN_STR);
bcf_dec_t *d = &b->d;
if ( d->n_var < b->n_allele )
{
d->var = (variant_t *) realloc(d->var, sizeof(variant_t)*b->n_allele);
d->n_var = b->n_allele;
}
int i;
b->d.var_type = 0;
for (i=1; i<b->n_allele; i++)
{
bcf_set_variant_type(d->allele[0],d->allele[i], &d->var[i]);
b->d.var_type |= d->var[i].type;
//fprintf(stderr,"[set_variant_type] %d %s %s -> %d %d .. %d\n", b->pos+1,d->allele[0],d->allele[i],d->var[i].type,d->var[i].n, b->d.var_type);
}
}
int bcf_get_variant_types(bcf1_t *rec)
{
if ( rec->d.var_type==-1 ) bcf_set_variant_types(rec);
return rec->d.var_type;
}
int bcf_get_variant_type(bcf1_t *rec, int ith_allele)
{
if ( rec->d.var_type==-1 ) bcf_set_variant_types(rec);
return rec->d.var[ith_allele].type;
}
int bcf_update_info(const bcf_hdr_t *hdr, bcf1_t *line, const char *key, const void *values, int n, int type)
{
// Is the field already present?
int i, inf_id = bcf_hdr_id2int(hdr,BCF_DT_ID,key);
if ( !bcf_hdr_idinfo_exists(hdr,BCF_HL_INFO,inf_id) ) return -1; // No such INFO field in the header
if ( !(line->unpacked & BCF_UN_INFO) ) bcf_unpack(line, BCF_UN_INFO);
for (i=0; i<line->n_info; i++)
if ( inf_id==line->d.info[i].key ) break;
bcf_info_t *inf = i==line->n_info ? NULL : &line->d.info[i];
if ( !n || (type==BCF_HT_STR && !values) )
{
if ( inf )
{
// Mark the tag for removal, free existing memory if necessary
if ( inf->vptr_free )
{
free(inf->vptr - inf->vptr_off);
inf->vptr_free = 0;
}
line->d.shared_dirty |= BCF1_DIRTY_INF;
inf->vptr = NULL;
}
return 0;
}
// Encode the values and determine the size required to accommodate the values
kstring_t str = {0,0,0};
bcf_enc_int1(&str, inf_id);
if ( type==BCF_HT_INT )
bcf_enc_vint(&str, n, (int32_t*)values, -1);
else if ( type==BCF_HT_REAL )
bcf_enc_vfloat(&str, n, (float*)values);
else if ( type==BCF_HT_FLAG || type==BCF_HT_STR )
{
if ( values==NULL )
bcf_enc_size(&str, 0, BCF_BT_NULL);
else
bcf_enc_vchar(&str, strlen((char*)values), (char*)values);
}
else
{
fprintf(stderr, "[E::%s] the type %d not implemented yet\n", __func__, type);
abort();
}
// Is the INFO tag already present
if ( inf )
{
// Is it big enough to accommodate new block?
if ( str.l <= inf->vptr_len + inf->vptr_off )
{
if ( str.l != inf->vptr_len + inf->vptr_off ) line->d.shared_dirty |= BCF1_DIRTY_INF;
uint8_t *ptr = inf->vptr - inf->vptr_off;
memcpy(ptr, str.s, str.l);
free(str.s);
int vptr_free = inf->vptr_free;
bcf_unpack_info_core1(ptr, inf);
inf->vptr_free = vptr_free;
}
else
{
assert( !inf->vptr_free ); // fix the caller or improve here: this has been modified before
bcf_unpack_info_core1((uint8_t*)str.s, inf);
inf->vptr_free = 1;
line->d.shared_dirty |= BCF1_DIRTY_INF;
}
}
else
{
// The tag is not present, create new one
line->n_info++;
hts_expand0(bcf_info_t, line->n_info, line->d.m_info , line->d.info);
inf = &line->d.info[line->n_info-1];
bcf_unpack_info_core1((uint8_t*)str.s, inf);
inf->vptr_free = 1;
line->d.shared_dirty |= BCF1_DIRTY_INF;
}
line->unpacked |= BCF_UN_INFO;
return 0;
}
int bcf_update_format_string(const bcf_hdr_t *hdr, bcf1_t *line, const char *key, const char **values, int n)
{
if ( !n )
return bcf_update_format(hdr,line,key,NULL,0,BCF_HT_STR);
int i, max_len = 0;
for (i=0; i<n; i++)
{
int len = strlen(values[i]);
if ( len > max_len ) max_len = len;
}
char *out = (char*) malloc(max_len*n);
if ( !out ) return -2;
for (i=0; i<n; i++)
{
char *dst = out+i*max_len;
const char *src = values[i];
int j = 0;
while ( src[j] ) { dst[j] = src[j]; j++; }
for (; j<max_len; j++) dst[j] = 0;
}
int ret = bcf_update_format(hdr,line,key,out,max_len*n,BCF_HT_STR);
free(out);
return ret;
}
int bcf_update_format(const bcf_hdr_t *hdr, bcf1_t *line, const char *key, const void *values, int n, int type)
{
// Is the field already present?
int i, fmt_id = bcf_hdr_id2int(hdr,BCF_DT_ID,key);
if ( !bcf_hdr_idinfo_exists(hdr,BCF_HL_FMT,fmt_id) )
{
if ( !n ) return 0;
return -1; // the key not present in the header
}
if ( !(line->unpacked & BCF_UN_FMT) ) bcf_unpack(line, BCF_UN_FMT);
for (i=0; i<line->n_fmt; i++)
if ( line->d.fmt[i].id==fmt_id ) break;
bcf_fmt_t *fmt = i==line->n_fmt ? NULL : &line->d.fmt[i];
if ( !n )
{
if ( fmt )
{
// Mark the tag for removal, free existing memory if necessary
if ( fmt->p_free )
{
free(fmt->p - fmt->p_off);
fmt->p_free = 0;
}
line->d.indiv_dirty = 1;
fmt->p = NULL;
}
return 0;
}
line->n_sample = bcf_hdr_nsamples(hdr);
int nps = n / line->n_sample; // number of values per sample
assert( nps && nps*line->n_sample==n ); // must be divisible by n_sample
// Encode the values and determine the size required to accommodate the values
kstring_t str = {0,0,0};
bcf_enc_int1(&str, fmt_id);
if ( type==BCF_HT_INT )
bcf_enc_vint(&str, n, (int32_t*)values, nps);
else if ( type==BCF_HT_REAL )
{
bcf_enc_size(&str, nps, BCF_BT_FLOAT);
kputsn((char*)values, nps*line->n_sample*sizeof(float), &str);
}
else if ( type==BCF_HT_STR )
{
bcf_enc_size(&str, nps, BCF_BT_CHAR);
kputsn((char*)values, nps*line->n_sample, &str);
}
else
{
fprintf(stderr, "[E::%s] the type %d not implemented yet\n", __func__, type);
abort();
}
if ( !fmt )
{
// Not present, new format field
line->n_fmt++;
hts_expand0(bcf_fmt_t, line->n_fmt, line->d.m_fmt, line->d.fmt);
// Special case: VCF specification requires that GT is always first
if ( line->n_fmt > 1 && key[0]=='G' && key[1]=='T' && !key[2] )
{
for (i=line->n_fmt-1; i>0; i--)
line->d.fmt[i] = line->d.fmt[i-1];
fmt = &line->d.fmt[0];
}
else
fmt = &line->d.fmt[line->n_fmt-1];
bcf_unpack_fmt_core1((uint8_t*)str.s, line->n_sample, fmt);
line->d.indiv_dirty = 1;
fmt->p_free = 1;
}
else
{
// The tag is already present, check if it is big enough to accomodate the new block
if ( str.l <= fmt->p_len + fmt->p_off )
{
// good, the block is big enough
if ( str.l != fmt->p_len + fmt->p_off ) line->d.indiv_dirty = 1;
uint8_t *ptr = fmt->p - fmt->p_off;
memcpy(ptr, str.s, str.l);
free(str.s);
int p_free = fmt->p_free;
bcf_unpack_fmt_core1(ptr, line->n_sample, fmt);
fmt->p_free = p_free;
}
else
{
assert( !fmt->p_free ); // fix the caller or improve here: this has been modified before
bcf_unpack_fmt_core1((uint8_t*)str.s, line->n_sample, fmt);
fmt->p_free = 1;
line->d.indiv_dirty = 1;
}
}
line->unpacked |= BCF_UN_FMT;
return 0;
}
int bcf_update_filter(const bcf_hdr_t *hdr, bcf1_t *line, int *flt_ids, int n)
{
if ( !(line->unpacked & BCF_UN_FLT) ) bcf_unpack(line, BCF_UN_FLT);
line->d.shared_dirty |= BCF1_DIRTY_FLT;
line->d.n_flt = n;
if ( !n ) return 0;
hts_expand(int, line->d.n_flt, line->d.m_flt, line->d.flt);
int i;
for (i=0; i<n; i++)
line->d.flt[i] = flt_ids[i];
return 0;
}
int bcf_add_filter(const bcf_hdr_t *hdr, bcf1_t *line, int flt_id)
{
if ( !(line->unpacked & BCF_UN_FLT) ) bcf_unpack(line, BCF_UN_FLT);
int i;
for (i=0; i<line->d.n_flt; i++)
if ( flt_id==line->d.flt[i] ) break;
if ( i<line->d.n_flt ) return 0; // this filter is already set
line->d.shared_dirty |= BCF1_DIRTY_FLT;
if ( flt_id==0 ) // set to PASS
line->d.n_flt = 1;
else if ( line->d.n_flt==1 && line->d.flt[0]==0 )
line->d.n_flt = 1;
else
line->d.n_flt++;
hts_expand(int, line->d.n_flt, line->d.m_flt, line->d.flt);
line->d.flt[line->d.n_flt-1] = flt_id;
return 1;
}
int bcf_remove_filter(const bcf_hdr_t *hdr, bcf1_t *line, int flt_id, int pass)
{
if ( !(line->unpacked & BCF_UN_FLT) ) bcf_unpack(line, BCF_UN_FLT);
int i;
for (i=0; i<line->d.n_flt; i++)
if ( flt_id==line->d.flt[i] ) break;
if ( i==line->d.n_flt ) return 0; // the filter is not present
line->d.shared_dirty |= BCF1_DIRTY_FLT;
if ( i!=line->d.n_flt-1 ) memmove(line->d.flt+i,line->d.flt+i+1,line->d.n_flt-i);
line->d.n_flt--;
if ( !line->d.n_flt && pass ) bcf_add_filter(hdr,line,0);
return 0;
}
int bcf_has_filter(const bcf_hdr_t *hdr, bcf1_t *line, char *filter)
{
if ( filter[0]=='.' && !filter[1] ) filter = "PASS";
int id = bcf_hdr_id2int(hdr, BCF_DT_ID, filter);
if ( !bcf_hdr_idinfo_exists(hdr,BCF_HL_FLT,id) ) return -1; // not defined in the header
if ( !(line->unpacked & BCF_UN_FLT) ) bcf_unpack(line, BCF_UN_FLT);
if ( id==0 && !line->d.n_flt) return 1; // PASS
int i;
for (i=0; i<line->d.n_flt; i++)
if ( line->d.flt[i]==id ) return 1;
return 0;
}
static inline int _bcf1_sync_alleles(const bcf_hdr_t *hdr, bcf1_t *line, int nals)
{
line->d.shared_dirty |= BCF1_DIRTY_ALS;
line->n_allele = nals;
hts_expand(char*, line->n_allele, line->d.m_allele, line->d.allele);
char *als = line->d.als;
int n = 0;
while (n<nals)
{
line->d.allele[n] = als;
while ( *als ) als++;
als++;
n++;
}
return 0;
}
int bcf_update_alleles(const bcf_hdr_t *hdr, bcf1_t *line, const char **alleles, int nals)
{
kstring_t tmp = {0,0,0};
char *free_old = NULL;
// If the supplied alleles are not pointers to line->d.als, the existing block can be reused.
int i;
for (i=0; i<nals; i++)
if ( alleles[i]>=line->d.als && alleles[i]<line->d.als+line->d.m_als ) break;
if ( i==nals )
{
// all alleles point elsewhere, reuse the existing block
tmp.l = 0; tmp.s = line->d.als; tmp.m = line->d.m_als;
}
else
free_old = line->d.als;
for (i=0; i<nals; i++)
{
kputs(alleles[i], &tmp);
kputc(0, &tmp);
}
line->d.als = tmp.s; line->d.m_als = tmp.m;
free(free_old);
return _bcf1_sync_alleles(hdr,line,nals);
}
int bcf_update_alleles_str(const bcf_hdr_t *hdr, bcf1_t *line, const char *alleles_string)
{
kstring_t tmp;
tmp.l = 0; tmp.s = line->d.als; tmp.m = line->d.m_als;
kputs(alleles_string, &tmp);
line->d.als = tmp.s; line->d.m_als = tmp.m;
int nals = 1;
char *t = line->d.als;
while (*t)
{
if ( *t==',' ) { *t = 0; nals++; }
t++;
}
return _bcf1_sync_alleles(hdr, line, nals);
}
int bcf_update_id(const bcf_hdr_t *hdr, bcf1_t *line, const char *id)
{
kstring_t tmp;
tmp.l = 0; tmp.s = line->d.id; tmp.m = line->d.m_id;
if ( id )
kputs(id, &tmp);
else
kputs(".", &tmp);
line->d.id = tmp.s; line->d.m_id = tmp.m;
line->d.shared_dirty |= BCF1_DIRTY_ID;
return 0;
}
bcf_fmt_t *bcf_get_fmt(const bcf_hdr_t *hdr, bcf1_t *line, const char *key)
{
int i, id = bcf_hdr_id2int(hdr, BCF_DT_ID, key);
if ( !bcf_hdr_idinfo_exists(hdr,BCF_HL_FMT,id) ) return NULL; // no such FMT field in the header
if ( !(line->unpacked & BCF_UN_FMT) ) bcf_unpack(line, BCF_UN_FMT);
for (i=0; i<line->n_fmt; i++)
{
if ( line->d.fmt[i].id==id ) return &line->d.fmt[i];
}
return NULL;
}
bcf_info_t *bcf_get_info(const bcf_hdr_t *hdr, bcf1_t *line, const char *key)
{
int i, id = bcf_hdr_id2int(hdr, BCF_DT_ID, key);
if ( !bcf_hdr_idinfo_exists(hdr,BCF_HL_INFO,id) ) return NULL; // no such INFO field in the header
if ( !(line->unpacked & BCF_UN_INFO) ) bcf_unpack(line, BCF_UN_INFO);
for (i=0; i<line->n_info; i++)
{
if ( line->d.info[i].key==id ) return &line->d.info[i];
}
return NULL;
}
int bcf_get_info_values(const bcf_hdr_t *hdr, bcf1_t *line, const char *tag, void **dst, int *ndst, int type)
{
int i,j, tag_id = bcf_hdr_id2int(hdr, BCF_DT_ID, tag);
if ( !bcf_hdr_idinfo_exists(hdr,BCF_HL_INFO,tag_id) ) return -1; // no such INFO field in the header
if ( bcf_hdr_id2type(hdr,BCF_HL_INFO,tag_id)!=type ) return -2; // expected different type
if ( !(line->unpacked & BCF_UN_INFO) ) bcf_unpack(line, BCF_UN_INFO);
for (i=0; i<line->n_info; i++)
if ( line->d.info[i].key==tag_id ) break;
if ( i==line->n_info ) return ( type==BCF_HT_FLAG ) ? 0 : -3; // the tag is not present in this record
if ( type==BCF_HT_FLAG ) return 1;
bcf_info_t *info = &line->d.info[i];
if ( type==BCF_HT_STR )
{
if ( *ndst < info->len+1 )
{
*ndst = info->len + 1;
*dst = realloc(*dst, *ndst);
}
memcpy(*dst,info->vptr,info->len);
((uint8_t*)*dst)[info->len] = 0;
return info->len;
}
// Make sure the buffer is big enough
int size1 = type==BCF_HT_INT ? sizeof(int32_t) : sizeof(float);
if ( *ndst < info->len )
{
*ndst = info->len;
*dst = realloc(*dst, *ndst * size1);
}
if ( info->len == 1 )
{
if ( info->type==BCF_BT_FLOAT ) *((float*)*dst) = info->v1.f;
else *((int32_t*)*dst) = info->v1.i;
return 1;
}
#define BRANCH(type_t, is_missing, is_vector_end, set_missing, out_type_t) { \
out_type_t *tmp = (out_type_t *) *dst; \
type_t *p = (type_t *) info->vptr; \
for (j=0; j<info->len; j++) \
{ \
if ( is_vector_end ) return j; \
if ( is_missing ) set_missing; \
else *tmp = p[j]; \
tmp++; \
} \
return j; \
}
switch (info->type) {
case BCF_BT_INT8: BRANCH(int8_t, p[j]==bcf_int8_missing, p[j]==bcf_int8_vector_end, *tmp=bcf_int32_missing, int32_t); break;
case BCF_BT_INT16: BRANCH(int16_t, p[j]==bcf_int16_missing, p[j]==bcf_int16_vector_end, *tmp=bcf_int32_missing, int32_t); break;
case BCF_BT_INT32: BRANCH(int32_t, p[j]==bcf_int32_missing, p[j]==bcf_int32_vector_end, *tmp=bcf_int32_missing, int32_t); break;
case BCF_BT_FLOAT: BRANCH(float, bcf_float_is_missing(p[j]), bcf_float_is_vector_end(p[j]), bcf_float_set_missing(*tmp), float); break;
default: fprintf(stderr,"TODO: %s:%d .. info->type=%d\n", __FILE__,__LINE__, info->type); exit(1);
}
#undef BRANCH
return -4; // this can never happen
}
int bcf_get_format_string(const bcf_hdr_t *hdr, bcf1_t *line, const char *tag, char ***dst, int *ndst)
{
int i,tag_id = bcf_hdr_id2int(hdr, BCF_DT_ID, tag);
if ( !bcf_hdr_idinfo_exists(hdr,BCF_HL_FMT,tag_id) ) return -1; // no such FORMAT field in the header
if ( bcf_hdr_id2type(hdr,BCF_HL_FMT,tag_id)!=BCF_HT_STR ) return -2; // expected different type
if ( !(line->unpacked & BCF_UN_FMT) ) bcf_unpack(line, BCF_UN_FMT);
for (i=0; i<line->n_fmt; i++)
if ( line->d.fmt[i].id==tag_id ) break;
if ( i==line->n_fmt ) return -3; // the tag is not present in this record
bcf_fmt_t *fmt = &line->d.fmt[i];
int nsmpl = bcf_hdr_nsamples(hdr);
if ( !*dst )
{
*dst = (char**) malloc(sizeof(char*)*nsmpl);
if ( !*dst ) return -4; // could not alloc
(*dst)[0] = NULL;
}
int n = (fmt->n+1)*nsmpl;
if ( *ndst < n )
{
(*dst)[0] = realloc((*dst)[0], n);
if ( !(*dst)[0] ) return -4; // could not alloc
*ndst = n;
}
for (i=0; i<nsmpl; i++)
{
uint8_t *src = fmt->p + i*fmt->n;
uint8_t *tmp = (uint8_t*)(*dst)[0] + i*(fmt->n+1);
memcpy(tmp,src,fmt->n);
tmp[fmt->n] = 0;
(*dst)[i] = (char*) tmp;
}
return n;
}
int bcf_get_format_values(const bcf_hdr_t *hdr, bcf1_t *line, const char *tag, void **dst, int *ndst, int type)
{
int i,j, tag_id = bcf_hdr_id2int(hdr, BCF_DT_ID, tag);
if ( !bcf_hdr_idinfo_exists(hdr,BCF_HL_FMT,tag_id) ) return -1; // no such FORMAT field in the header
if ( tag[0]=='G' && tag[1]=='T' && tag[2]==0 )
{
// Ugly: GT field is considered to be a string by the VCF header but BCF represents it as INT.
if ( bcf_hdr_id2type(hdr,BCF_HL_FMT,tag_id)!=BCF_HT_STR ) return -2;
}
else if ( bcf_hdr_id2type(hdr,BCF_HL_FMT,tag_id)!=type ) return -2; // expected different type
if ( !(line->unpacked & BCF_UN_FMT) ) bcf_unpack(line, BCF_UN_FMT);
for (i=0; i<line->n_fmt; i++)
if ( line->d.fmt[i].id==tag_id ) break;
if ( i==line->n_fmt ) return -3; // the tag is not present in this record
bcf_fmt_t *fmt = &line->d.fmt[i];
if ( type==BCF_HT_STR )
{
int n = fmt->n*bcf_hdr_nsamples(hdr);
if ( *ndst < n )
{
*dst = realloc(*dst, n);
if ( !*dst ) return -4; // could not alloc
*ndst = n;
}
memcpy(*dst,fmt->p,n);
return n;
}
// Make sure the buffer is big enough
int nsmpl = bcf_hdr_nsamples(hdr);
int size1 = type==BCF_HT_INT ? sizeof(int32_t) : sizeof(float);
if ( *ndst < fmt->n*nsmpl )
{
*ndst = fmt->n*nsmpl;
*dst = realloc(*dst, *ndst*size1);
if ( !dst ) return -4; // could not alloc
}
#define BRANCH(type_t, is_missing, is_vector_end, set_missing, set_vector_end, out_type_t) { \
out_type_t *tmp = (out_type_t *) *dst; \
type_t *p = (type_t*) fmt->p; \
for (i=0; i<nsmpl; i++) \
{ \
for (j=0; j<fmt->n; j++) \
{ \
if ( is_missing ) set_missing; \
else if ( is_vector_end ) { set_vector_end; break; } \
else *tmp = p[j]; \
tmp++; \
} \
for (; j<fmt->n; j++) { set_vector_end; tmp++; } \
p = (type_t *)((char *)p + fmt->size); \
} \
}
switch (fmt->type) {
case BCF_BT_INT8: BRANCH(int8_t, p[j]==bcf_int8_missing, p[j]==bcf_int8_vector_end, *tmp=bcf_int32_missing, *tmp=bcf_int32_vector_end, int32_t); break;
case BCF_BT_INT16: BRANCH(int16_t, p[j]==bcf_int16_missing, p[j]==bcf_int16_vector_end, *tmp=bcf_int32_missing, *tmp=bcf_int32_vector_end, int32_t); break;
case BCF_BT_INT32: BRANCH(int32_t, p[j]==bcf_int32_missing, p[j]==bcf_int32_vector_end, *tmp=bcf_int32_missing, *tmp=bcf_int32_vector_end, int32_t); break;
case BCF_BT_FLOAT: BRANCH(float, bcf_float_is_missing(p[j]), bcf_float_is_vector_end(p[j]), bcf_float_set_missing(*tmp), bcf_float_set_vector_end(*tmp), float); break;
default: fprintf(stderr,"TODO: %s:%d .. fmt->type=%d\n", __FILE__,__LINE__, fmt->type); exit(1);
}
#undef BRANCH
return nsmpl*fmt->n;
}
|
ckockan/tardis_core
|
htslib/vcf.c
|
C
|
gpl-2.0
| 93,107
|
EasySocial.module( 'oauth/facebook', function($) {
var module = this;
EasySocial.require()
.done(function() {
EasySocial.Controller( 'OAuth.Facebook',
{
defaultOptions :
{
"{login}" : "[data-oauth-facebook-login]",
"{revoke}" : "[data-oauth-facebook-revoke]",
"{pushInput}" : "[data-oauth-facebook-push]"
}
},
function( self )
{
return {
init : function()
{
},
openDialog : function( url )
{
var left = (screen.width/2)-( 300 /2),
top = (screen.height/2)-( 300 /2);
window.open( url , "" , 'scrollbars=no,resizable=no,width=300,height=300,left=' + left + ',top=' + top );
},
"{pushInput} change" : function( el )
{
var enabled = $(el).val();
if( enabled == 1 && self.options.requestPush )
{
self.openDialog( self.options.addPublishURL )
}
if( enabled == 0 )
{
self.openDialog( self.options.revokePublishURL );
}
},
"{login} click" : function()
{
self.openDialog( self.options.url );
},
"{revoke} click" : function()
{
var callback = self.element.data( 'callback' );
EasySocial.dialog(
{
content : EasySocial.ajax( 'site/views/oauth/confirmRevoke' , { "client" : 'facebook' , "callbackUrl" : callback } )
});
}
}
});
module.resolve();
});
}); // module end
|
cuongnd/test_pro
|
media/com_easysocial/scripts/oauth/facebook.js
|
JavaScript
|
gpl-2.0
| 1,390
|
/*****************************************************************************
* vlc_es_out.h: es_out (demuxer output) descriptor, queries and methods
*****************************************************************************
* Copyright (C) 1999-2004 the VideoLAN team
* $Id$
*
* Authors: Laurent Aimar <fenrir@via.ecp.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifndef VLC_ES_OUT_H
#define VLC_ES_OUT_H 1
/**
* \file
* This file defines functions and structures for handling es_out in stream output
*/
/**
* \defgroup es out Es Out
* @{
*/
enum es_out_mode_e
{
ES_OUT_MODE_NONE, /* don't select anything */
ES_OUT_MODE_ALL, /* eg for stream output */
ES_OUT_MODE_AUTO, /* best audio/video or for input follow audio-track, sub-track */
ES_OUT_MODE_PARTIAL /* select programs given after --programs */
};
enum es_out_query_e
{
/* activate application of mode */
ES_OUT_SET_ACTIVE, /* arg1= bool */
/* see if mode is currently aplied or not */
ES_OUT_GET_ACTIVE, /* arg1= bool* */
/* set/get mode */
ES_OUT_SET_MODE, /* arg1= int */
ES_OUT_GET_MODE, /* arg2= int* */
/* set ES selected for the es category (audio/video/spu) */
ES_OUT_SET_ES, /* arg1= es_out_id_t* */
/* set 'default' tag on ES (copied across from container) */
ES_OUT_SET_DEFAULT, /* arg1= es_out_id_t* */
/* force selection/unselection of the ES (bypass current mode) */
ES_OUT_SET_ES_STATE,/* arg1= es_out_id_t* arg2=bool */
ES_OUT_GET_ES_STATE,/* arg1= es_out_id_t* arg2=bool* */
/* */
ES_OUT_SET_GROUP, /* arg1= int */
ES_OUT_GET_GROUP, /* arg1= int* */
/* PCR handling, DTS/PTS will be automatically computed using thoses PCR
* XXX: SET_PCR(_GROUP) are in charge of the pace control. They will wait
* to slow down the demuxer so that it reads at the right speed.
* XXX: if you want PREROLL just call RESET_PCR and
* ES_OUT_SET_NEXT_DISPLAY_TIME and send data to the decoder *without*
* calling SET_PCR until preroll is finished.
*/
ES_OUT_SET_PCR, /* arg1=int64_t i_pcr(microsecond!) (using default group 0)*/
ES_OUT_SET_GROUP_PCR, /* arg1= int i_group, arg2=int64_t i_pcr(microsecond!)*/
ES_OUT_RESET_PCR, /* no arg */
/* Timestamp handling, convert an input timestamp to a global clock one.
* (shouldn't have to be used by input plugins directly) */
ES_OUT_GET_TS, /* arg1=int64_t i_ts(microsecond!) (using default group 0), arg2=int64_t* converted i_ts */
/* Try not to use this one as it is a bit hacky */
ES_OUT_SET_FMT, /* arg1= es_out_id_t* arg2=es_format_t* */
/* Allow preroll of data (data with dts/pts < i_pts for one ES will be decoded but not displayed */
ES_OUT_SET_NEXT_DISPLAY_TIME, /* arg1=es_out_id_t* arg2=int64_t i_pts(microsecond) */
/* Set meta data for group (dynamic) */
ES_OUT_SET_GROUP_META, /* arg1=int i_group arg2=vlc_meta_t */
/* Set epg for group (dynamic) */
ES_OUT_SET_GROUP_EPG, /* arg1=int i_group arg2=vlc_epg_t */
/* */
ES_OUT_DEL_GROUP /* arg1=int i_group */
};
struct es_out_t
{
es_out_id_t *(*pf_add) ( es_out_t *, es_format_t * );
int (*pf_send) ( es_out_t *, es_out_id_t *, block_t * );
void (*pf_del) ( es_out_t *, es_out_id_t * );
int (*pf_control)( es_out_t *, int i_query, va_list );
bool b_sout;
es_out_sys_t *p_sys;
};
static inline es_out_id_t * es_out_Add( es_out_t *out, es_format_t *fmt )
{
return out->pf_add( out, fmt );
}
static inline void es_out_Del( es_out_t *out, es_out_id_t *id )
{
out->pf_del( out, id );
}
static inline int es_out_Send( es_out_t *out, es_out_id_t *id,
block_t *p_block )
{
return out->pf_send( out, id, p_block );
}
static inline int es_out_vaControl( es_out_t *out, int i_query, va_list args )
{
return out->pf_control( out, i_query, args );
}
static inline int es_out_Control( es_out_t *out, int i_query, ... )
{
va_list args;
int i_result;
va_start( args, i_query );
i_result = es_out_vaControl( out, i_query, args );
va_end( args );
return i_result;
}
/**
* @}
*/
#endif
|
squadette/vlc
|
include/vlc_es_out.h
|
C
|
gpl-2.0
| 5,216
|
# -*- coding: utf-8; -*-
"""
Copyright (C) 2007-2013 Guake authors
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
"""
import inspect
import time
# You can put calls to p() everywhere in this page to inspect timing
# g_start = time.time()
# def p():
# print(time.time() - g_start, __file__, inspect.currentframe().f_back.f_lineno)
import logging
import os
import signal
import subprocess
import sys
import uuid
from locale import gettext as _
from optparse import OptionParser
log = logging.getLogger(__name__)
from guake.globals import NAME
from guake.globals import bindtextdomain
from guake.support import print_support
from guake.utils import restore_preferences
from guake.utils import save_preferences
# When we are in the document generation on readthedocs, we do not have paths.py generated
try:
from guake.paths import LOCALE_DIR
bindtextdomain(NAME, LOCALE_DIR)
except: # pylint: disable=bare-except
pass
def main():
"""Parses the command line parameters and decide if dbus methods
should be called or not. If there is already a guake instance
running it will be used and a True value will be returned,
otherwise, false will be returned.
"""
# Force to xterm-256 colors for compatibility with some old command line programs
os.environ["TERM"] = "xterm-256color"
# Force use X11 backend underwayland
os.environ["GDK_BACKEND"] = "x11"
# do not use version keywords here, pbr might be slow to find the version of Guake module
parser = OptionParser()
parser.add_option(
'-V',
'--version',
dest='version',
action='store_true',
default=False,
help=_('Show Guake version number and exit')
)
parser.add_option(
'-v',
'--verbose',
dest='verbose',
action='store_true',
default=False,
help=_('Enable verbose logging')
)
parser.add_option(
'-f',
'--fullscreen',
dest='fullscreen',
action='store_true',
default=False,
help=_('Put Guake in fullscreen mode')
)
parser.add_option(
'-t',
'--toggle-visibility',
dest='show_hide',
action='store_true',
default=False,
help=_('Toggles the visibility of the terminal window')
)
parser.add_option(
'--show',
dest="show",
action='store_true',
default=False,
help=_('Shows Guake main window')
)
parser.add_option(
'--hide',
dest='hide',
action='store_true',
default=False,
help=_('Hides Guake main window')
)
parser.add_option(
'-p',
'--preferences',
dest='show_preferences',
action='store_true',
default=False,
help=_('Shows Guake preference window')
)
parser.add_option(
'-a',
'--about',
dest='show_about',
action='store_true',
default=False,
help=_('Shows Guake\'s about info')
)
parser.add_option(
'-n',
'--new-tab',
dest='new_tab',
action='store',
default='',
help=_('Add a new tab (with current directory set to NEW_TAB)')
)
parser.add_option(
'-s',
'--select-tab',
dest='select_tab',
action='store',
default='',
help=_('Select a tab (SELECT_TAB is the index of the tab)')
)
parser.add_option(
'-g',
'--selected-tab',
dest='selected_tab',
action='store_true',
default=False,
help=_('Return the selected tab index.')
)
parser.add_option(
'-l',
'--selected-tablabel',
dest='selected_tablabel',
action='store_true',
default=False,
help=_('Return the selected tab label.')
)
parser.add_option(
'--split-vertical',
dest='split_vertical',
action='store_true',
default=False,
help=_('Split the selected tab vertically.')
)
parser.add_option(
'--split-horizontal',
dest='split_horizontal',
action='store_true',
default=False,
help=_('Split the selected tab horizontally.')
)
parser.add_option(
'-e',
'--execute-command',
dest='command',
action='store',
default='',
help=_('Execute an arbitrary command in the selected tab.')
)
parser.add_option(
'-i',
'--tab-index',
dest='tab_index',
action='store',
default='0',
help=_('Specify the tab to rename. Default is 0. Can be used to select tab by UUID.')
)
parser.add_option(
'--bgcolor',
dest='bgcolor',
action='store',
default='',
help=_('Set the hexadecimal (#rrggbb) background color of '
'the selected tab.')
)
parser.add_option(
'--fgcolor',
dest='fgcolor',
action='store',
default='',
help=_('Set the hexadecimal (#rrggbb) foreground color of the '
'selected tab.')
)
parser.add_option(
'--change-palette',
dest='palette_name',
action='store',
default='',
help=_('Change Guake palette scheme')
)
parser.add_option(
'--rename-tab',
dest='rename_tab',
metavar='TITLE',
action='store',
default='',
help=_(
'Rename the specified tab by --tab-index. Reset to default if TITLE is '
'a single dash "-".'
)
)
parser.add_option(
'-r',
'--rename-current-tab',
dest='rename_current_tab',
metavar='TITLE',
action='store',
default='',
help=_('Rename the current tab. Reset to default if TITLE is a '
'single dash "-".')
)
parser.add_option(
'-q',
'--quit',
dest='quit',
action='store_true',
default=False,
help=_('Says to Guake go away =(')
)
parser.add_option(
'-u',
'--no-startup-script',
dest='execute_startup_script',
action='store_false',
default=True,
help=_('Do not execute the start up script')
)
parser.add_option(
'--save-preferences',
dest='save_preferences',
action='store',
default=None,
help=_('Save Guake preferences to this filename')
)
parser.add_option(
'--restore-preferences',
dest='restore_preferences',
action='store',
default=None,
help=_('Restore Guake preferences from this file')
)
parser.add_option(
'--support',
dest='support',
action='store_true',
default=False,
help=_('Show support infomations')
)
# checking mandatory dependencies
missing_deps = False
try:
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('Gdk', '3.0')
except ValueError:
print("[ERROR] missing mandatory dependency: GtK 3.0")
missing_deps = True
try:
gi.require_version('Vte', '2.91') # vte-0.42
except ValueError:
print("[ERROR] missing mandatory dependency: Vte >= 0.42")
missing_deps = True
try:
gi.require_version('Keybinder', '3.0')
except ValueError:
print("[ERROR] missing mandatory dependency: Keybinder 3")
missing_deps = True
try:
import cairo
except ImportError:
print("[ERROR] missing mandatory dependency: cairo")
missing_deps = True
if missing_deps:
print(
"[ERROR] missing at least one system dependencies. "
"You need to install additional packages for Guake to run"
)
print(
"[ERROR] On Debian/Ubuntu you need to install the following libraries:\n"
" sudo apt-get install -y --no-install-recommends \\\n"
" gir1.2-keybinder-3.0 \\\n"
" gir1.2-notify-0.7 \\\n"
" gir1.2-vte-2.91 \\\n"
" gir1.2-wnck-3.0 \\\n"
" libkeybinder-3.0-0 \\\n"
" libutempter0 \\\n"
" python3 \\\n"
" python3-cairo \\\n"
" python3-dbus \\\n"
" python3-gi \\\n"
" python3-pbr \\\n"
" python3-pip"
)
sys.exit(1)
options = parser.parse_args()[0]
if options.version:
from guake import gtk_version
from guake import guake_version
from guake import vte_version
from guake import vte_runtime_version
print('Guake Terminal: {}'.format(guake_version()))
print('VTE: {}'.format(vte_version()))
print('VTE runtime: {}'.format(vte_runtime_version()))
print('Gtk: {}'.format(gtk_version()))
sys.exit(0)
if options.save_preferences and options.restore_preferences:
parser.error('options --save-preferences and --restore-preferences are mutually exclusive')
if options.save_preferences:
save_preferences(options.save_preferences)
sys.exit(0)
elif options.restore_preferences:
restore_preferences(options.restore_preferences)
sys.exit(0)
if options.support:
print_support()
sys.exit(0)
import dbus
from guake.dbusiface import DBUS_NAME
from guake.dbusiface import DBUS_PATH
from guake.dbusiface import DbusManager
from guake.guake_logging import setupLogging
instance = None
# Trying to get an already running instance of guake. If it is not
# possible, lets create a new instance. This function will return
# a boolean value depending on this decision.
try:
bus = dbus.SessionBus()
remote_object = bus.get_object(DBUS_NAME, DBUS_PATH)
already_running = True
except dbus.DBusException:
# can now configure the logging
setupLogging(options.verbose)
# COLORTERM is an environment variable set by some terminal emulators such as
# gnome-terminal.
# To avoid confusing applications running inside Guake, clean up COLORTERM at startup.
if "COLORTERM" in os.environ:
del os.environ['COLORTERM']
log.info("Guake not running, starting it")
# late loading of the Guake object, to speed up dbus comm
from guake.guake_app import Guake
instance = Guake()
remote_object = DbusManager(instance)
already_running = False
only_show_hide = True
if options.fullscreen:
remote_object.fullscreen()
if options.show:
remote_object.show_from_remote()
if options.hide:
remote_object.hide_from_remote()
if options.show_preferences:
remote_object.show_prefs()
only_show_hide = options.show
if options.new_tab:
remote_object.add_tab(options.new_tab)
only_show_hide = options.show
if options.select_tab:
selected = int(options.select_tab)
tab_count = int(remote_object.get_tab_count())
if 0 <= selected < tab_count:
remote_object.select_tab(selected)
else:
sys.stderr.write('invalid index: %d\n' % selected)
only_show_hide = options.show
if options.selected_tab:
selected = remote_object.get_selected_tab()
sys.stdout.write('%d\n' % selected)
only_show_hide = options.show
if options.selected_tablabel:
selectedlabel = remote_object.get_selected_tablabel()
sys.stdout.write('%s\n' % selectedlabel)
only_show_hide = options.show
if options.split_vertical:
remote_object.v_split_current_terminal()
only_show_hide = options.show
if options.split_horizontal:
remote_object.h_split_current_terminal()
only_show_hide = options.show
if options.command:
remote_object.execute_command(options.command)
only_show_hide = options.show
if options.tab_index and options.rename_tab:
try:
remote_object.rename_tab_uuid(str(uuid.UUID(options.tab_index)), options.rename_tab)
except ValueError:
remote_object.rename_tab(int(options.tab_index), options.rename_tab)
only_show_hide = options.show
if options.bgcolor:
remote_object.set_bgcolor(options.bgcolor)
only_show_hide = options.show
if options.fgcolor:
remote_object.set_fgcolor(options.fgcolor)
only_show_hide = options.show
if options.palette_name:
remote_object.change_palette_name(options.palette_name)
only_show_hide = options.show
if options.rename_current_tab:
remote_object.rename_current_tab(options.rename_current_tab)
only_show_hide = options.show
if options.show_about:
remote_object.show_about()
only_show_hide = options.show
if options.quit:
try:
remote_object.quit()
return True
except dbus.DBusException:
return True
if already_running and only_show_hide:
# here we know that guake was called without any parameter and
# it is already running, so, lets toggle its visibility.
remote_object.show_hide()
if options.execute_startup_script:
if not already_running:
startup_script = instance.settings.general.get_string("startup-script")
if startup_script:
log.info("Calling startup script: %s", startup_script)
pid = subprocess.Popen([startup_script],
shell=True,
stdin=None,
stdout=None,
stderr=None,
close_fds=True)
log.info("Startup script started with pid: %s", pid)
# Please ensure this is the last line !!!!
else:
log.info("--no-startup-script argument defined, so don't execute the startup script")
if already_running:
log.info("Guake is already running")
return already_running
def exec_main():
if not main():
log.debug("Running main gtk loop")
signal.signal(signal.SIGINT, signal.SIG_DFL)
# Load gi pretty late, to speed up as much as possible the parsing of the option for DBus
# comm through command line
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
Gtk.main()
if __name__ == '__main__':
exec_main()
|
mouseratti/guake
|
guake/main.py
|
Python
|
gpl-2.0
| 15,344
|
/* -*- Mode: c++; -*- */
/* --------------------------------------------------------------------
* Filename:
* operator-append.cc
*
* Description:
* Implementation of the APPEND command.
*
* Authors:
* Andreas Aardal Hanssen <andreas-binc curly bincimap spot org>
*
* Bugs:
*
* ChangeLog:
*
* --------------------------------------------------------------------
* Copyright 2002-2004 Andreas Aardal Hanssen
*
* 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 Street #330, Boston, MA 02111-1307, USA.
* --------------------------------------------------------------------
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <algorithm>
#include <string>
#include <fcntl.h>
#include "depot.h"
#include "io.h"
#include "mailbox.h"
#include "operators.h"
#include "recursivedescent.h"
#include "pendingupdates.h"
#include "session.h"
using namespace ::std;
using namespace Binc;
//----------------------------------------------------------------------
AppendOperator::AppendOperator(void)
{
}
//----------------------------------------------------------------------
AppendOperator::~AppendOperator(void)
{
}
//----------------------------------------------------------------------
const string AppendOperator::getName(void) const
{
return "APPEND";
}
//----------------------------------------------------------------------
int AppendOperator::getState(void) const
{
return Session::AUTHENTICATED | Session::SELECTED;
}
//------------------------------------------------------------------------
Operator::ProcessResult AppendOperator::process(Depot &depot,
Request &command)
{
IO &com = IOFactory::getInstance().get(1);
Session &session = Session::getInstance();
const string &srcmailbox = command.getMailbox();
const string &canonmailbox = toCanonMailbox(srcmailbox);
Mailbox *mailbox = 0;
if ((mailbox = depot.get(canonmailbox)) == 0) {
session.setResponseCode("TRYCREATE");
session.setLastError("invalid destination mailbox "
+ toImapString(srcmailbox));
return NO;
}
// mask all passed flags together
unsigned int newflags = (unsigned int) Message::F_NONE;
vector<string>::const_iterator f_i = command.flags.begin();
while (f_i != command.flags.end()) {
if (*f_i == "\\Deleted") newflags |= Message::F_DELETED;
if (*f_i == "\\Answered") newflags |= Message::F_ANSWERED;
if (*f_i == "\\Seen") newflags |= Message::F_SEEN;
if (*f_i == "\\Draft") newflags |= Message::F_DRAFT;
if (*f_i == "\\Flagged") newflags |= Message::F_FLAGGED;
++f_i;
}
int mday, year, hour, minute, second;
char month[4];
struct tm mytm;
if (command.getDate() != "") {
sscanf(command.getDate().c_str(), "%2i-%3s-%4i %2i:%2i:%2i",
&mday, month, &year, &hour, &minute, &second);
month[3] = '\0';
string monthstr = month;
lowercase(monthstr);
mytm.tm_sec = second;
mytm.tm_min = minute;
mytm.tm_hour = hour;
mytm.tm_year = year - 1900;
mytm.tm_mday = mday;
if (monthstr == "jan") mytm.tm_mon = 0;
else if (monthstr == "feb") mytm.tm_mon = 1;
else if (monthstr == "mar") mytm.tm_mon = 2;
else if (monthstr == "apr") mytm.tm_mon = 3;
else if (monthstr == "may") mytm.tm_mon = 4;
else if (monthstr == "jun") mytm.tm_mon = 5;
else if (monthstr == "jul") mytm.tm_mon = 6;
else if (monthstr == "aug") mytm.tm_mon = 7;
else if (monthstr == "sep") mytm.tm_mon = 8;
else if (monthstr == "oct") mytm.tm_mon = 9;
else if (monthstr == "nov") mytm.tm_mon = 10;
else if (monthstr == "dec") mytm.tm_mon = 11;
mytm.tm_isdst = -1;
}
// Read number of characters in literal. Literal is required here.
if (com.readChar() != '{') {
session.setLastError("expected literal");
return BAD;
}
string nr;
while (1) {
int c = com.readChar();
if (c == -1) {
session.setLastError("unexcepted EOF");
return BAD;
}
if (c == '}')
break;
nr += (char) c;
}
int nchars = atoi(nr.c_str());
if (nchars < 0) {
session.setLastError("expected positive size of appended message");
return BAD;
}
if (com.readChar() != '\r') {
session.setLastError("expected CR");
return BAD;
}
if (com.readChar() != '\n') {
session.setLastError("expected LF");
return BAD;
}
time_t newtime = (command.getDate() != "") ? mktime(&mytm) : time(0);
if (newtime == -1) newtime = time(0);
Message *dest = mailbox->createMessage(depot.mailboxToFilename(canonmailbox),
newtime);
if (!dest) {
session.setLastError(mailbox->getLastError());
return NO;
}
com << "+ go ahead with " << nchars << " characters" << endl;
com.flushContent();
com.disableInputLimit();
while (nchars > 0) {
// Read in chunks of 8192, followed by an optional chunk at the
// end which is < 8192 bytes.
string s;
int bytesToRead = nchars > 8192 ? 8192 : nchars;
int readBytes = com.readStr(s, bytesToRead);
if (readBytes <= 0) {
mailbox->rollBackNewMessages();
session.setLastError(com.getLastError());
return NO;
}
// Expect the exact number of bytes from readStr.
if (readBytes != bytesToRead) {
mailbox->rollBackNewMessages();
session.setLastError("expected " + toString(nchars)
+ " bytes, but got " + toString(readBytes));
return NO;
}
// Write the chunk to the message.
if (!dest->appendChunk(s)) {
mailbox->rollBackNewMessages();
session.setLastError(dest->getLastError());
return NO;
}
// Update the message count.
nchars -= readBytes;
}
// Read the trailing CRLF after the message data.
if (com.readChar() != '\r') {
mailbox->rollBackNewMessages();
session.setLastError("expected CR");
return BAD;
}
if (com.readChar() != '\n') {
mailbox->rollBackNewMessages();
session.setLastError("expected LF");
return BAD;
}
// Commit the message.
dest->close();
dest->setStdFlag(newflags);
dest->setInternalDate(mktime(&mytm));
if (!mailbox->commitNewMessages(depot.mailboxToFilename(canonmailbox))) {
session.setLastError("failed to commit after successful APPEND: "
+ mailbox->getLastError());
return NO;
}
if (mailbox == depot.getSelected()) {
pendingUpdates(mailbox, PendingUpdates::EXISTS
| PendingUpdates::RECENT
| PendingUpdates::FLAGS, true, false, true);
}
return OK;
}
//----------------------------------------------------------------------
Operator::ParseResult AppendOperator::parse(Request &c_in) const
{
Session &session = Session::getInstance();
Operator::ParseResult res;
if (c_in.getUidMode())
return REJECT;
if ((res = expectSPACE()) != ACCEPT) {
session.setLastError("Expected SPACE after APPEND");
return res;
}
string mailbox;
if ((res = expectMailbox(mailbox)) != ACCEPT) {
session.setLastError("Expected mailbox after APPEND SPACE");
return res;
}
c_in.setMailbox(mailbox);
if ((res = expectSPACE()) != ACCEPT) {
session.setLastError("Expected SPACE after APPEND SPACE mailbox");
return res;
}
if ((res = expectThisString("(")) == ACCEPT) {
if ((res = expectFlag(c_in.getFlags())) == ACCEPT)
while (1) {
if ((res = expectSPACE()) != ACCEPT)
break;
if ((res = expectFlag(c_in.getFlags())) != ACCEPT) {
session.setLastError("expected a flag after the '('");
return res;
}
}
if ((res = expectThisString(")")) != ACCEPT) {
session.setLastError("expected a ')'");
return res;
}
if ((res = expectSPACE()) != ACCEPT) {
session.setLastError("expected a SPACE after the flag list");
return res;
}
}
string date;
if ((res = expectDateTime(date)) == ACCEPT)
if ((res = expectSPACE()) != ACCEPT) {
session.setLastError("expected a SPACE after date_time");
return res;
}
c_in.setDate(date);
c_in.setName("APPEND");
return ACCEPT;
}
|
bitbrat/bincimap
|
src/operator-append.cc
|
C++
|
gpl-2.0
| 8,594
|
/*
* include/asm-arm/arch-tegra/include/mach/sdhci.h
*
* Copyright (C) 2009 Palm, Inc.
* Author: Yvonne Yip <y@palm.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.
*
*/
#ifndef __ASM_ARM_ARCH_TEGRA_SDHCI_H
#define __ASM_ARM_ARCH_TEGRA_SDHCI_H
#include <linux/mmc/host.h>
#include <asm/mach/mmc.h>
/*
* MMC_OCR_1V8_MASK will be used in board sdhci file
* Example for cardhu it will be used in board-cardhu-sdhci.c
* for built_in = 0 devices enabling ocr_mask to MMC_OCR_1V8_MASK
* sets the voltage to 1.8V
*/
#define MMC_OCR_1V8_MASK 0x8
struct tegra_sdhci_platform_data {
int cd_gpio;
int cd_polarity;
int wp_gpio;
int power_gpio;
int is_8bit;
int async_suspend;
int pm_flags;
int pm_caps;
unsigned int max_clk_limit;
unsigned int ddr_clk_limit;
unsigned int tap_delay;
struct mmc_platform_data mmc_data;
};
#endif
|
sloanyang/android_kernel_zte_u950
|
arch/arm/mach-tegra/include/mach/sdhci.h
|
C
|
gpl-2.0
| 1,260
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.