repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
frtmelody/shadowsocks-android | src/main/jni/openssl/crypto/ecdh/ech_ossl.c | 597 | 6329 | /* crypto/ecdh/ech_ossl.c */
/* ====================================================================
* Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
*
* The Elliptic Curve Public-Key Crypto Library (ECC Code) included
* herein is developed by SUN MICROSYSTEMS, INC., and is contributed
* to the OpenSSL project.
*
* The ECC Code is licensed pursuant to the OpenSSL open source
* license provided below.
*
* The ECDH software is originally written by Douglas Stebila of
* Sun Microsystems Laboratories.
*
*/
/* ====================================================================
* Copyright (c) 1998-2003 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED 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 OpenSSL PROJECT OR
* ITS 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.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <string.h>
#include <limits.h>
#include "cryptlib.h"
#include "ech_locl.h"
#include <openssl/err.h>
#include <openssl/sha.h>
#include <openssl/obj_mac.h>
#include <openssl/bn.h>
static int ecdh_compute_key(void *out, size_t len, const EC_POINT *pub_key,
EC_KEY *ecdh,
void *(*KDF)(const void *in, size_t inlen, void *out, size_t *outlen));
static ECDH_METHOD openssl_ecdh_meth = {
"OpenSSL ECDH method",
ecdh_compute_key,
#if 0
NULL, /* init */
NULL, /* finish */
#endif
0, /* flags */
NULL /* app_data */
};
const ECDH_METHOD *ECDH_OpenSSL(void)
{
return &openssl_ecdh_meth;
}
/* This implementation is based on the following primitives in the IEEE 1363 standard:
* - ECKAS-DH1
* - ECSVDP-DH
* Finally an optional KDF is applied.
*/
static int ecdh_compute_key(void *out, size_t outlen, const EC_POINT *pub_key,
EC_KEY *ecdh,
void *(*KDF)(const void *in, size_t inlen, void *out, size_t *outlen))
{
BN_CTX *ctx;
EC_POINT *tmp=NULL;
BIGNUM *x=NULL, *y=NULL;
const BIGNUM *priv_key;
const EC_GROUP* group;
int ret= -1;
size_t buflen, len;
unsigned char *buf=NULL;
if (outlen > INT_MAX)
{
ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ERR_R_MALLOC_FAILURE); /* sort of, anyway */
return -1;
}
if ((ctx = BN_CTX_new()) == NULL) goto err;
BN_CTX_start(ctx);
x = BN_CTX_get(ctx);
y = BN_CTX_get(ctx);
priv_key = EC_KEY_get0_private_key(ecdh);
if (priv_key == NULL)
{
ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ECDH_R_NO_PRIVATE_VALUE);
goto err;
}
group = EC_KEY_get0_group(ecdh);
if ((tmp=EC_POINT_new(group)) == NULL)
{
ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ERR_R_MALLOC_FAILURE);
goto err;
}
if (!EC_POINT_mul(group, tmp, NULL, pub_key, priv_key, ctx))
{
ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ECDH_R_POINT_ARITHMETIC_FAILURE);
goto err;
}
if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) == NID_X9_62_prime_field)
{
if (!EC_POINT_get_affine_coordinates_GFp(group, tmp, x, y, ctx))
{
ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ECDH_R_POINT_ARITHMETIC_FAILURE);
goto err;
}
}
#ifndef OPENSSL_NO_EC2M
else
{
if (!EC_POINT_get_affine_coordinates_GF2m(group, tmp, x, y, ctx))
{
ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ECDH_R_POINT_ARITHMETIC_FAILURE);
goto err;
}
}
#endif
buflen = (EC_GROUP_get_degree(group) + 7)/8;
len = BN_num_bytes(x);
if (len > buflen)
{
ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ERR_R_INTERNAL_ERROR);
goto err;
}
if ((buf = OPENSSL_malloc(buflen)) == NULL)
{
ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ERR_R_MALLOC_FAILURE);
goto err;
}
memset(buf, 0, buflen - len);
if (len != (size_t)BN_bn2bin(x, buf + buflen - len))
{
ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ERR_R_BN_LIB);
goto err;
}
if (KDF != 0)
{
if (KDF(buf, buflen, out, &outlen) == NULL)
{
ECDHerr(ECDH_F_ECDH_COMPUTE_KEY,ECDH_R_KDF_FAILED);
goto err;
}
ret = outlen;
}
else
{
/* no KDF, just copy as much as we can */
if (outlen > buflen)
outlen = buflen;
memcpy(out, buf, outlen);
ret = outlen;
}
err:
if (tmp) EC_POINT_free(tmp);
if (ctx) BN_CTX_end(ctx);
if (ctx) BN_CTX_free(ctx);
if (buf) OPENSSL_free(buf);
return(ret);
}
| gpl-3.0 |
DevSonw/shadowsocks-android | src/main/jni/openssl/crypto/cmac/cm_ameth.c | 599 | 3192 | /* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
* project 2010.
*/
/* ====================================================================
* Copyright (c) 2010 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED 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 OpenSSL PROJECT OR
* ITS 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 "cryptlib.h"
#include <openssl/evp.h>
#include <openssl/cmac.h>
#include "asn1_locl.h"
/* CMAC "ASN1" method. This is just here to indicate the
* maximum CMAC output length and to free up a CMAC
* key.
*/
static int cmac_size(const EVP_PKEY *pkey)
{
return EVP_MAX_BLOCK_LENGTH;
}
static void cmac_key_free(EVP_PKEY *pkey)
{
CMAC_CTX *cmctx = (CMAC_CTX *)pkey->pkey.ptr;
if (cmctx)
CMAC_CTX_free(cmctx);
}
const EVP_PKEY_ASN1_METHOD cmac_asn1_meth =
{
EVP_PKEY_CMAC,
EVP_PKEY_CMAC,
0,
"CMAC",
"OpenSSL CMAC method",
0,0,0,0,
0,0,0,
cmac_size,
0,
0,0,0,0,0,0,0,
cmac_key_free,
0,
0,0
};
| gpl-3.0 |
mirror/freedownload | MediaConverter/ffmpeg/libs/lame-3.99.5/libmp3lame/VbrTag.c | 88 | 31613 | /*
* Xing VBR tagging for LAME.
*
* Copyright (c) 1999 A.L. Faber
* Copyright (c) 2001 Jonathan Dee
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
/* $Id: VbrTag.c,v 1.103.2.1 2011/11/18 09:18:28 robert Exp $ */
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include "lame.h"
#include "machine.h"
#include "encoder.h"
#include "util.h"
#include "bitstream.h"
#include "VbrTag.h"
#include "lame_global_flags.h"
#include "tables.h"
#ifdef __sun__
/* woraround for SunOS 4.x, it has SEEK_* defined here */
#include <unistd.h>
#endif
#ifdef _DEBUG
/* #define DEBUG_VBRTAG */
#endif
/*
* 4 bytes for Header Tag
* 4 bytes for Header Flags
* 100 bytes for entry (NUMTOCENTRIES)
* 4 bytes for FRAME SIZE
* 4 bytes for STREAM_SIZE
* 4 bytes for VBR SCALE. a VBR quality indicator: 0=best 100=worst
* 20 bytes for LAME tag. for example, "LAME3.12 (beta 6)"
* ___________
* 140 bytes
*/
#define VBRHEADERSIZE (NUMTOCENTRIES+4+4+4+4+4)
#define LAMEHEADERSIZE (VBRHEADERSIZE + 9 + 1 + 1 + 8 + 1 + 1 + 3 + 1 + 1 + 2 + 4 + 2 + 2)
/* the size of the Xing header (MPEG1 and MPEG2) in kbps */
#define XING_BITRATE1 128
#define XING_BITRATE2 64
#define XING_BITRATE25 32
extern const char* get_lame_tag_encoder_short_version(void);
static const char VBRTag0[] = { "Xing" };
static const char VBRTag1[] = { "Info" };
/* Lookup table for fast CRC computation
* See 'CRC_update_lookup'
* Uses the polynomial x^16+x^15+x^2+1 */
static const unsigned int crc16_lookup[256] = {
0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040
};
/***********************************************************************
* Robert Hegemann 2001-01-17
***********************************************************************/
static void
addVbr(VBR_seek_info_t * v, int bitrate)
{
int i;
v->nVbrNumFrames++;
v->sum += bitrate;
v->seen++;
if (v->seen < v->want) {
return;
}
if (v->pos < v->size) {
v->bag[v->pos] = v->sum;
v->pos++;
v->seen = 0;
}
if (v->pos == v->size) {
for (i = 1; i < v->size; i += 2) {
v->bag[i / 2] = v->bag[i];
}
v->want *= 2;
v->pos /= 2;
}
}
static void
Xing_seek_table(VBR_seek_info_t const* v, unsigned char *t)
{
int i, indx;
int seek_point;
if (v->pos <= 0)
return;
for (i = 1; i < NUMTOCENTRIES; ++i) {
float j = i / (float) NUMTOCENTRIES, act, sum;
indx = (int) (floor(j * v->pos));
if (indx > v->pos - 1)
indx = v->pos - 1;
act = v->bag[indx];
sum = v->sum;
seek_point = (int) (256. * act / sum);
if (seek_point > 255)
seek_point = 255;
t[i] = seek_point;
}
}
#ifdef DEBUG_VBR_SEEKING_TABLE
static void
print_seeking(unsigned char *t)
{
int i;
printf("seeking table ");
for (i = 0; i < NUMTOCENTRIES; ++i) {
printf(" %d ", t[i]);
}
printf("\n");
}
#endif
/****************************************************************************
* AddVbrFrame: Add VBR entry, used to fill the VBR the TOC entries
* Paramters:
* nStreamPos: how many bytes did we write to the bitstream so far
* (in Bytes NOT Bits)
****************************************************************************
*/
void
AddVbrFrame(lame_internal_flags * gfc)
{
int kbps = bitrate_table[gfc->cfg.version][gfc->ov_enc.bitrate_index];
assert(gfc->VBR_seek_table.bag);
addVbr(&gfc->VBR_seek_table, kbps);
}
/*-------------------------------------------------------------*/
static int
ExtractI4(const unsigned char *buf)
{
int x;
/* big endian extract */
x = buf[0];
x <<= 8;
x |= buf[1];
x <<= 8;
x |= buf[2];
x <<= 8;
x |= buf[3];
return x;
}
static void
CreateI4(unsigned char *buf, uint32_t nValue)
{
/* big endian create */
buf[0] = (nValue >> 24) & 0xff;
buf[1] = (nValue >> 16) & 0xff;
buf[2] = (nValue >> 8) & 0xff;
buf[3] = (nValue) & 0xff;
}
static void
CreateI2(unsigned char *buf, int nValue)
{
/* big endian create */
buf[0] = (nValue >> 8) & 0xff;
buf[1] = (nValue) & 0xff;
}
/* check for magic strings*/
static int
IsVbrTag(const unsigned char *buf)
{
int isTag0, isTag1;
isTag0 = ((buf[0] == VBRTag0[0]) && (buf[1] == VBRTag0[1]) && (buf[2] == VBRTag0[2])
&& (buf[3] == VBRTag0[3]));
isTag1 = ((buf[0] == VBRTag1[0]) && (buf[1] == VBRTag1[1]) && (buf[2] == VBRTag1[2])
&& (buf[3] == VBRTag1[3]));
return (isTag0 || isTag1);
}
#define SHIFT_IN_BITS_VALUE(x,n,v) ( x = (x << (n)) | ( (v) & ~(-1 << (n)) ) )
static void
setLameTagFrameHeader(lame_internal_flags const *gfc, unsigned char *buffer)
{
SessionConfig_t const *const cfg = &gfc->cfg;
EncResult_t const *const eov = &gfc->ov_enc;
char abyte, bbyte;
SHIFT_IN_BITS_VALUE(buffer[0], 8u, 0xffu);
SHIFT_IN_BITS_VALUE(buffer[1], 3u, 7);
SHIFT_IN_BITS_VALUE(buffer[1], 1u, (cfg->samplerate_out < 16000) ? 0 : 1);
SHIFT_IN_BITS_VALUE(buffer[1], 1u, cfg->version);
SHIFT_IN_BITS_VALUE(buffer[1], 2u, 4 - 3);
SHIFT_IN_BITS_VALUE(buffer[1], 1u, (!cfg->error_protection) ? 1 : 0);
SHIFT_IN_BITS_VALUE(buffer[2], 4u, eov->bitrate_index);
SHIFT_IN_BITS_VALUE(buffer[2], 2u, cfg->samplerate_index);
SHIFT_IN_BITS_VALUE(buffer[2], 1u, 0);
SHIFT_IN_BITS_VALUE(buffer[2], 1u, cfg->extension);
SHIFT_IN_BITS_VALUE(buffer[3], 2u, cfg->mode);
SHIFT_IN_BITS_VALUE(buffer[3], 2u, eov->mode_ext);
SHIFT_IN_BITS_VALUE(buffer[3], 1u, cfg->copyright);
SHIFT_IN_BITS_VALUE(buffer[3], 1u, cfg->original);
SHIFT_IN_BITS_VALUE(buffer[3], 2u, cfg->emphasis);
/* the default VBR header. 48 kbps layer III, no padding, no crc */
/* but sampling freq, mode andy copyright/copy protection taken */
/* from first valid frame */
buffer[0] = (uint8_t) 0xff;
abyte = (buffer[1] & (unsigned char) 0xf1);
{
int bitrate;
if (1 == cfg->version) {
bitrate = XING_BITRATE1;
}
else {
if (cfg->samplerate_out < 16000)
bitrate = XING_BITRATE25;
else
bitrate = XING_BITRATE2;
}
if (cfg->vbr == vbr_off)
bitrate = cfg->avg_bitrate;
if (cfg->free_format)
bbyte = 0x00;
else
bbyte = 16 * BitrateIndex(bitrate, cfg->version, cfg->samplerate_out);
}
/* Use as much of the info from the real frames in the
* Xing header: samplerate, channels, crc, etc...
*/
if (cfg->version == 1) {
/* MPEG1 */
buffer[1] = abyte | (char) 0x0a; /* was 0x0b; */
abyte = buffer[2] & (char) 0x0d; /* AF keep also private bit */
buffer[2] = (char) bbyte | abyte; /* 64kbs MPEG1 frame */
}
else {
/* MPEG2 */
buffer[1] = abyte | (char) 0x02; /* was 0x03; */
abyte = buffer[2] & (char) 0x0d; /* AF keep also private bit */
buffer[2] = (char) bbyte | abyte; /* 64kbs MPEG2 frame */
}
}
#if 0
static int CheckVbrTag(unsigned char *buf);
/*-------------------------------------------------------------*/
/* Same as GetVbrTag below, but only checks for the Xing tag.
requires buf to contain only 40 bytes */
/*-------------------------------------------------------------*/
int
CheckVbrTag(unsigned char *buf)
{
int h_id, h_mode;
/* get selected MPEG header data */
h_id = (buf[1] >> 3) & 1;
h_mode = (buf[3] >> 6) & 3;
/* determine offset of header */
if (h_id) {
/* mpeg1 */
if (h_mode != 3)
buf += (32 + 4);
else
buf += (17 + 4);
}
else {
/* mpeg2 */
if (h_mode != 3)
buf += (17 + 4);
else
buf += (9 + 4);
}
return IsVbrTag(buf);
}
#endif
int
GetVbrTag(VBRTAGDATA * pTagData, const unsigned char *buf)
{
int i, head_flags;
int h_bitrate, h_id, h_mode, h_sr_index, h_layer;
int enc_delay, enc_padding;
/* get Vbr header data */
pTagData->flags = 0;
/* get selected MPEG header data */
h_layer = (buf[1] >> 1) & 3;
if ( h_layer != 0x01 ) {
/* the following code assumes Layer-3, so give up here */
return 0;
}
h_id = (buf[1] >> 3) & 1;
h_sr_index = (buf[2] >> 2) & 3;
h_mode = (buf[3] >> 6) & 3;
h_bitrate = ((buf[2] >> 4) & 0xf);
h_bitrate = bitrate_table[h_id][h_bitrate];
/* check for FFE syncword */
if ((buf[1] >> 4) == 0xE)
pTagData->samprate = samplerate_table[2][h_sr_index];
else
pTagData->samprate = samplerate_table[h_id][h_sr_index];
/* if( h_id == 0 ) */
/* pTagData->samprate >>= 1; */
/* determine offset of header */
if (h_id) {
/* mpeg1 */
if (h_mode != 3)
buf += (32 + 4);
else
buf += (17 + 4);
}
else {
/* mpeg2 */
if (h_mode != 3)
buf += (17 + 4);
else
buf += (9 + 4);
}
if (!IsVbrTag(buf))
return 0;
buf += 4;
pTagData->h_id = h_id;
head_flags = pTagData->flags = ExtractI4(buf);
buf += 4; /* get flags */
if (head_flags & FRAMES_FLAG) {
pTagData->frames = ExtractI4(buf);
buf += 4;
}
if (head_flags & BYTES_FLAG) {
pTagData->bytes = ExtractI4(buf);
buf += 4;
}
if (head_flags & TOC_FLAG) {
if (pTagData->toc != NULL) {
for (i = 0; i < NUMTOCENTRIES; i++)
pTagData->toc[i] = buf[i];
}
buf += NUMTOCENTRIES;
}
pTagData->vbr_scale = -1;
if (head_flags & VBR_SCALE_FLAG) {
pTagData->vbr_scale = ExtractI4(buf);
buf += 4;
}
pTagData->headersize = ((h_id + 1) * 72000 * h_bitrate) / pTagData->samprate;
buf += 21;
enc_delay = buf[0] << 4;
enc_delay += buf[1] >> 4;
enc_padding = (buf[1] & 0x0F) << 8;
enc_padding += buf[2];
/* check for reasonable values (this may be an old Xing header, */
/* not a INFO tag) */
if (enc_delay < 0 || enc_delay > 3000)
enc_delay = -1;
if (enc_padding < 0 || enc_padding > 3000)
enc_padding = -1;
pTagData->enc_delay = enc_delay;
pTagData->enc_padding = enc_padding;
#ifdef DEBUG_VBRTAG
fprintf(stderr, "\n\n********************* VBR TAG INFO *****************\n");
fprintf(stderr, "tag :%s\n", VBRTag);
fprintf(stderr, "head_flags :%d\n", head_flags);
fprintf(stderr, "bytes :%d\n", pTagData->bytes);
fprintf(stderr, "frames :%d\n", pTagData->frames);
fprintf(stderr, "VBR Scale :%d\n", pTagData->vbr_scale);
fprintf(stderr, "enc_delay = %i \n", enc_delay);
fprintf(stderr, "enc_padding= %i \n", enc_padding);
fprintf(stderr, "toc:\n");
if (pTagData->toc != NULL) {
for (i = 0; i < NUMTOCENTRIES; i++) {
if ((i % 10) == 0)
fprintf(stderr, "\n");
fprintf(stderr, " %3d", (int) (pTagData->toc[i]));
}
}
fprintf(stderr, "\n***************** END OF VBR TAG INFO ***************\n");
#endif
return 1; /* success */
}
/****************************************************************************
* InitVbrTag: Initializes the header, and write empty frame to stream
* Paramters:
* fpStream: pointer to output file stream
* nMode : Channel Mode: 0=STEREO 1=JS 2=DS 3=MONO
****************************************************************************
*/
int
InitVbrTag(lame_global_flags * gfp)
{
lame_internal_flags *gfc = gfp->internal_flags;
SessionConfig_t const *const cfg = &gfc->cfg;
int kbps_header;
#define MAXFRAMESIZE 2880 /* or 0xB40, the max freeformat 640 32kHz framesize */
/*
* Xing VBR pretends to be a 48kbs layer III frame. (at 44.1kHz).
* (at 48kHz they use 56kbs since 48kbs frame not big enough for
* table of contents)
* let's always embed Xing header inside a 64kbs layer III frame.
* this gives us enough room for a LAME version string too.
* size determined by sampling frequency (MPEG1)
* 32kHz: 216 bytes@48kbs 288bytes@ 64kbs
* 44.1kHz: 156 bytes 208bytes@64kbs (+1 if padding = 1)
* 48kHz: 144 bytes 192
*
* MPEG 2 values are the same since the framesize and samplerate
* are each reduced by a factor of 2.
*/
if (1 == cfg->version) {
kbps_header = XING_BITRATE1;
}
else {
if (cfg->samplerate_out < 16000)
kbps_header = XING_BITRATE25;
else
kbps_header = XING_BITRATE2;
}
if (cfg->vbr == vbr_off)
kbps_header = cfg->avg_bitrate;
/** make sure LAME Header fits into Frame
*/
{
int total_frame_size = ((cfg->version + 1) * 72000 * kbps_header) / cfg->samplerate_out;
int header_size = (cfg->sideinfo_len + LAMEHEADERSIZE);
gfc->VBR_seek_table.TotalFrameSize = total_frame_size;
if (total_frame_size < header_size || total_frame_size > MAXFRAMESIZE) {
/* disable tag, it wont fit */
gfc->cfg.write_lame_tag = 0;
return 0;
}
}
gfc->VBR_seek_table.nVbrNumFrames = 0;
gfc->VBR_seek_table.nBytesWritten = 0;
gfc->VBR_seek_table.sum = 0;
gfc->VBR_seek_table.seen = 0;
gfc->VBR_seek_table.want = 1;
gfc->VBR_seek_table.pos = 0;
if (gfc->VBR_seek_table.bag == NULL) {
gfc->VBR_seek_table.bag = malloc(400 * sizeof(int));
if (gfc->VBR_seek_table.bag != NULL) {
gfc->VBR_seek_table.size = 400;
}
else {
gfc->VBR_seek_table.size = 0;
ERRORF(gfc, "Error: can't allocate VbrFrames buffer\n");
gfc->cfg.write_lame_tag = 0;
return -1;
}
}
/* write dummy VBR tag of all 0's into bitstream */
{
uint8_t buffer[MAXFRAMESIZE];
size_t i, n;
memset(buffer, 0, sizeof(buffer));
setLameTagFrameHeader(gfc, buffer);
n = gfc->VBR_seek_table.TotalFrameSize;
for (i = 0; i < n; ++i) {
add_dummy_byte(gfc, buffer[i], 1);
}
}
/* Success */
return 0;
}
/* fast CRC-16 computation - uses table crc16_lookup 8*/
static uint16_t
CRC_update_lookup(uint16_t value, uint16_t crc)
{
uint16_t tmp;
tmp = crc ^ value;
crc = (crc >> 8) ^ crc16_lookup[tmp & 0xff];
return crc;
}
void
UpdateMusicCRC(uint16_t * crc, unsigned char const *buffer, int size)
{
int i;
for (i = 0; i < size; ++i)
*crc = CRC_update_lookup(buffer[i], *crc);
}
/****************************************************************************
* Jonathan Dee 2001/08/31
*
* PutLameVBR: Write LAME info: mini version + info on various switches used
* Paramters:
* pbtStreamBuffer : pointer to output buffer
* id3v2size : size of id3v2 tag in bytes
* crc : computation of crc-16 of Lame Tag so far (starting at frame sync)
*
****************************************************************************
*/
static int
PutLameVBR(lame_global_flags const *gfp, size_t nMusicLength, uint8_t * pbtStreamBuffer, uint16_t crc)
{
lame_internal_flags const *gfc = gfp->internal_flags;
SessionConfig_t const *const cfg = &gfc->cfg;
int nBytesWritten = 0;
int i;
int enc_delay = gfc->ov_enc.encoder_delay; /* encoder delay */
int enc_padding = gfc->ov_enc.encoder_padding; /* encoder padding */
/*recall: cfg->vbr_q is for example set by the switch -V */
/* gfp->quality by -q, -h, -f, etc */
int nQuality = (100 - 10 * gfp->VBR_q - gfp->quality);
/*
NOTE:
Even though the specification for the LAME VBR tag
did explicitly mention other encoders than LAME,
many SW/HW decoder seem to be able to make use of
this tag only, if the encoder version starts with LAME.
To be compatible with such decoders, ANY encoder will
be forced to write a fake LAME version string!
As a result, the encoder version info becomes worthless.
*/
const char *szVersion = get_lame_tag_encoder_short_version();
uint8_t nVBR;
uint8_t nRevision = 0x00;
uint8_t nRevMethod;
uint8_t vbr_type_translator[] = { 1, 5, 3, 2, 4, 0, 3 }; /*numbering different in vbr_mode vs. Lame tag */
uint8_t nLowpass =
(((cfg->lowpassfreq / 100.0) + .5) > 255 ? 255 : (cfg->lowpassfreq / 100.0) + .5);
uint32_t nPeakSignalAmplitude = 0;
uint16_t nRadioReplayGain = 0;
uint16_t nAudiophileReplayGain = 0;
uint8_t nNoiseShaping = cfg->noise_shaping;
uint8_t nStereoMode = 0;
int bNonOptimal = 0;
uint8_t nSourceFreq = 0;
uint8_t nMisc = 0;
uint16_t nMusicCRC = 0;
/*psy model type: Gpsycho or NsPsytune */
unsigned char bExpNPsyTune = 1; /* only NsPsytune */
unsigned char bSafeJoint = (cfg->use_safe_joint_stereo) != 0;
unsigned char bNoGapMore = 0;
unsigned char bNoGapPrevious = 0;
int nNoGapCount = gfp->nogap_total;
int nNoGapCurr = gfp->nogap_current;
uint8_t nAthType = cfg->ATHtype; /*4 bits. */
uint8_t nFlags = 0;
/* if ABR, {store bitrate <=255} else { store "-b"} */
int nABRBitrate;
switch (cfg->vbr) {
case vbr_abr:{
nABRBitrate = cfg->vbr_avg_bitrate_kbps;
break;
}
case vbr_off:{
nABRBitrate = cfg->avg_bitrate;
break;
}
default:{ /*vbr modes */
nABRBitrate = bitrate_table[cfg->version][cfg->vbr_min_bitrate_index];;
}
}
/*revision and vbr method */
if (cfg->vbr < sizeof(vbr_type_translator))
nVBR = vbr_type_translator[cfg->vbr];
else
nVBR = 0x00; /*unknown. */
nRevMethod = 0x10 * nRevision + nVBR;
/* ReplayGain */
if (cfg->findReplayGain) {
int RadioGain = gfc->ov_rpg.RadioGain;
if (RadioGain > 0x1FE)
RadioGain = 0x1FE;
if (RadioGain < -0x1FE)
RadioGain = -0x1FE;
nRadioReplayGain = 0x2000; /* set name code */
nRadioReplayGain |= 0xC00; /* set originator code to `determined automatically' */
if (RadioGain >= 0)
nRadioReplayGain |= RadioGain; /* set gain adjustment */
else {
nRadioReplayGain |= 0x200; /* set the sign bit */
nRadioReplayGain |= -RadioGain; /* set gain adjustment */
}
}
/* peak sample */
if (cfg->findPeakSample)
nPeakSignalAmplitude =
abs((int) ((((FLOAT) gfc->ov_rpg.PeakSample) / 32767.0) * pow(2, 23) + .5));
/*nogap */
if (nNoGapCount != -1) {
if (nNoGapCurr > 0)
bNoGapPrevious = 1;
if (nNoGapCurr < nNoGapCount - 1)
bNoGapMore = 1;
}
/*flags */
nFlags = nAthType + (bExpNPsyTune << 4)
+ (bSafeJoint << 5)
+ (bNoGapMore << 6)
+ (bNoGapPrevious << 7);
if (nQuality < 0)
nQuality = 0;
/*stereo mode field... a bit ugly. */
switch (cfg->mode) {
case MONO:
nStereoMode = 0;
break;
case STEREO:
nStereoMode = 1;
break;
case DUAL_CHANNEL:
nStereoMode = 2;
break;
case JOINT_STEREO:
if (cfg->force_ms)
nStereoMode = 4;
else
nStereoMode = 3;
break;
case NOT_SET:
/* FALLTHROUGH */
default:
nStereoMode = 7;
break;
}
/*Intensity stereo : nStereoMode = 6. IS is not implemented */
if (cfg->samplerate_in <= 32000)
nSourceFreq = 0x00;
else if (cfg->samplerate_in == 48000)
nSourceFreq = 0x02;
else if (cfg->samplerate_in > 48000)
nSourceFreq = 0x03;
else
nSourceFreq = 0x01; /*default is 44100Hz. */
/*Check if the user overrided the default LAME behaviour with some nasty options */
if (cfg->short_blocks == short_block_forced || cfg->short_blocks == short_block_dispensed || ((cfg->lowpassfreq == -1) && (cfg->highpassfreq == -1)) || /* "-k" */
(cfg->disable_reservoir && cfg->avg_bitrate < 320) ||
cfg->noATH || cfg->ATHonly || (nAthType == 0) || cfg->samplerate_in <= 32000)
bNonOptimal = 1;
nMisc = nNoiseShaping + (nStereoMode << 2)
+ (bNonOptimal << 5)
+ (nSourceFreq << 6);
nMusicCRC = gfc->nMusicCRC;
/*Write all this information into the stream */
CreateI4(&pbtStreamBuffer[nBytesWritten], nQuality);
nBytesWritten += 4;
strncpy((char *) &pbtStreamBuffer[nBytesWritten], szVersion, 9);
nBytesWritten += 9;
pbtStreamBuffer[nBytesWritten] = nRevMethod;
nBytesWritten++;
pbtStreamBuffer[nBytesWritten] = nLowpass;
nBytesWritten++;
CreateI4(&pbtStreamBuffer[nBytesWritten], nPeakSignalAmplitude);
nBytesWritten += 4;
CreateI2(&pbtStreamBuffer[nBytesWritten], nRadioReplayGain);
nBytesWritten += 2;
CreateI2(&pbtStreamBuffer[nBytesWritten], nAudiophileReplayGain);
nBytesWritten += 2;
pbtStreamBuffer[nBytesWritten] = nFlags;
nBytesWritten++;
if (nABRBitrate >= 255)
pbtStreamBuffer[nBytesWritten] = 0xFF;
else
pbtStreamBuffer[nBytesWritten] = nABRBitrate;
nBytesWritten++;
pbtStreamBuffer[nBytesWritten] = enc_delay >> 4; /* works for win32, does it for unix? */
pbtStreamBuffer[nBytesWritten + 1] = (enc_delay << 4) + (enc_padding >> 8);
pbtStreamBuffer[nBytesWritten + 2] = enc_padding;
nBytesWritten += 3;
pbtStreamBuffer[nBytesWritten] = nMisc;
nBytesWritten++;
pbtStreamBuffer[nBytesWritten++] = 0; /*unused in rev0 */
CreateI2(&pbtStreamBuffer[nBytesWritten], cfg->preset);
nBytesWritten += 2;
CreateI4(&pbtStreamBuffer[nBytesWritten], (int) nMusicLength);
nBytesWritten += 4;
CreateI2(&pbtStreamBuffer[nBytesWritten], nMusicCRC);
nBytesWritten += 2;
/*Calculate tag CRC.... must be done here, since it includes
*previous information*/
for (i = 0; i < nBytesWritten; i++)
crc = CRC_update_lookup(pbtStreamBuffer[i], crc);
CreateI2(&pbtStreamBuffer[nBytesWritten], crc);
nBytesWritten += 2;
return nBytesWritten;
}
static long
skipId3v2(FILE * fpStream)
{
size_t nbytes;
long id3v2TagSize;
unsigned char id3v2Header[10];
/* seek to the beginning of the stream */
if (fseek(fpStream, 0, SEEK_SET) != 0) {
return -2; /* not seekable, abort */
}
/* read 10 bytes in case there's an ID3 version 2 header here */
nbytes = fread(id3v2Header, 1, sizeof(id3v2Header), fpStream);
if (nbytes != sizeof(id3v2Header)) {
return -3; /* not readable, maybe opened Write-Only */
}
/* does the stream begin with the ID3 version 2 file identifier? */
if (!strncmp((char *) id3v2Header, "ID3", 3)) {
/* the tag size (minus the 10-byte header) is encoded into four
* bytes where the most significant bit is clear in each byte */
id3v2TagSize = (((id3v2Header[6] & 0x7f) << 21)
| ((id3v2Header[7] & 0x7f) << 14)
| ((id3v2Header[8] & 0x7f) << 7)
| (id3v2Header[9] & 0x7f))
+ sizeof id3v2Header;
}
else {
/* no ID3 version 2 tag in this stream */
id3v2TagSize = 0;
}
return id3v2TagSize;
}
size_t
lame_get_lametag_frame(lame_global_flags const *gfp, unsigned char *buffer, size_t size)
{
lame_internal_flags *gfc;
SessionConfig_t const *cfg;
unsigned long stream_size;
unsigned int nStreamIndex;
uint8_t btToc[NUMTOCENTRIES];
if (gfp == 0) {
return 0;
}
gfc = gfp->internal_flags;
if (gfc == 0) {
return 0;
}
if (gfc->class_id != LAME_ID) {
return 0;
}
cfg = &gfc->cfg;
if (cfg->write_lame_tag == 0) {
return 0;
}
if (gfc->VBR_seek_table.pos <= 0) {
return 0;
}
if (size < gfc->VBR_seek_table.TotalFrameSize) {
return gfc->VBR_seek_table.TotalFrameSize;
}
if (buffer == 0) {
return 0;
}
memset(buffer, 0, gfc->VBR_seek_table.TotalFrameSize);
/* 4 bytes frame header */
setLameTagFrameHeader(gfc, buffer);
/* Clear all TOC entries */
memset(btToc, 0, sizeof(btToc));
if (cfg->free_format) {
int i;
for (i = 1; i < NUMTOCENTRIES; ++i)
btToc[i] = 255 * i / 100;
}
else {
Xing_seek_table(&gfc->VBR_seek_table, btToc);
}
#ifdef DEBUG_VBR_SEEKING_TABLE
print_seeking(btToc);
#endif
/* Start writing the tag after the zero frame */
nStreamIndex = cfg->sideinfo_len;
/* note! Xing header specifies that Xing data goes in the
* ancillary data with NO ERROR PROTECTION. If error protecton
* in enabled, the Xing data still starts at the same offset,
* and now it is in sideinfo data block, and thus will not
* decode correctly by non-Xing tag aware players */
if (cfg->error_protection)
nStreamIndex -= 2;
/* Put Vbr tag */
if (cfg->vbr == vbr_off) {
buffer[nStreamIndex++] = VBRTag1[0];
buffer[nStreamIndex++] = VBRTag1[1];
buffer[nStreamIndex++] = VBRTag1[2];
buffer[nStreamIndex++] = VBRTag1[3];
}
else {
buffer[nStreamIndex++] = VBRTag0[0];
buffer[nStreamIndex++] = VBRTag0[1];
buffer[nStreamIndex++] = VBRTag0[2];
buffer[nStreamIndex++] = VBRTag0[3];
}
/* Put header flags */
CreateI4(&buffer[nStreamIndex], FRAMES_FLAG + BYTES_FLAG + TOC_FLAG + VBR_SCALE_FLAG);
nStreamIndex += 4;
/* Put Total Number of frames */
CreateI4(&buffer[nStreamIndex], gfc->VBR_seek_table.nVbrNumFrames);
nStreamIndex += 4;
/* Put total audio stream size, including Xing/LAME Header */
stream_size = gfc->VBR_seek_table.nBytesWritten + gfc->VBR_seek_table.TotalFrameSize;
CreateI4(&buffer[nStreamIndex], stream_size);
nStreamIndex += 4;
/* Put TOC */
memcpy(&buffer[nStreamIndex], btToc, sizeof(btToc));
nStreamIndex += sizeof(btToc);
if (cfg->error_protection) {
/* (jo) error_protection: add crc16 information to header */
CRC_writeheader(gfc, (char *) buffer);
}
{
/*work out CRC so far: initially crc = 0 */
uint16_t crc = 0x00;
unsigned int i;
for (i = 0; i < nStreamIndex; i++)
crc = CRC_update_lookup(buffer[i], crc);
/*Put LAME VBR info */
nStreamIndex += PutLameVBR(gfp, stream_size, buffer + nStreamIndex, crc);
}
#ifdef DEBUG_VBRTAG
{
VBRTAGDATA TestHeader;
GetVbrTag(&TestHeader, buffer);
}
#endif
return gfc->VBR_seek_table.TotalFrameSize;
}
/***********************************************************************
*
* PutVbrTag: Write final VBR tag to the file
* Paramters:
* lpszFileName: filename of MP3 bit stream
* nVbrScale : encoder quality indicator (0..100)
****************************************************************************
*/
int
PutVbrTag(lame_global_flags const *gfp, FILE * fpStream)
{
lame_internal_flags *gfc = gfp->internal_flags;
long lFileSize;
long id3v2TagSize;
size_t nbytes;
uint8_t buffer[MAXFRAMESIZE];
if (gfc->VBR_seek_table.pos <= 0)
return -1;
/* Seek to end of file */
fseek(fpStream, 0, SEEK_END);
/* Get file size */
lFileSize = ftell(fpStream);
/* Abort if file has zero length. Yes, it can happen :) */
if (lFileSize == 0)
return -1;
/*
* The VBR tag may NOT be located at the beginning of the stream.
* If an ID3 version 2 tag was added, then it must be skipped to write
* the VBR tag data.
*/
id3v2TagSize = skipId3v2(fpStream);
if (id3v2TagSize < 0) {
return id3v2TagSize;
}
/*Seek to the beginning of the stream */
fseek(fpStream, id3v2TagSize, SEEK_SET);
nbytes = lame_get_lametag_frame(gfp, buffer, sizeof(buffer));
if (nbytes > sizeof(buffer)) {
return -1;
}
if (nbytes < 1) {
return 0;
}
/* Put it all to disk again */
if (fwrite(buffer, nbytes, 1, fpStream) != 1) {
return -1;
}
return 0; /* success */
}
| gpl-3.0 |
yukixz/shadowsocks-libev | libev/ev_win32.c | 347 | 5245 | /*
* libev win32 compatibility cruft (_not_ a backend)
*
* Copyright (c) 2007,2008,2009 Marc Alexander Lehmann <libev@schmorp.de>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modifica-
* tion, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MER-
* CHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPE-
* CIAL, 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 OTH-
* ERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License ("GPL") version 2 or any later version,
* in which case the provisions of the GPL are applicable instead of
* the above. If you wish to allow the use of your version of this file
* only under the terms of the GPL and not to allow others to use your
* version of this file under the BSD license, indicate your decision
* by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL. If you do not delete the
* provisions above, a recipient may use your version of this file under
* either the BSD or the GPL.
*/
#ifdef _WIN32
/* timeb.h is actually xsi legacy functionality */
#include <sys/timeb.h>
/* note: the comment below could not be substantiated, but what would I care */
/* MSDN says this is required to handle SIGFPE */
/* my wild guess would be that using something floating-pointy is required */
/* for the crt to do something about it */
volatile double SIGFPE_REQ = 0.0f;
static SOCKET
ev_tcp_socket (void)
{
#if EV_USE_WSASOCKET
return WSASocket (AF_INET, SOCK_STREAM, 0, 0, 0, 0);
#else
return socket (AF_INET, SOCK_STREAM, 0);
#endif
}
/* oh, the humanity! */
static int
ev_pipe (int filedes [2])
{
struct sockaddr_in addr = { 0 };
int addr_size = sizeof (addr);
struct sockaddr_in adr2;
int adr2_size = sizeof (adr2);
SOCKET listener;
SOCKET sock [2] = { -1, -1 };
if ((listener = ev_tcp_socket ()) == INVALID_SOCKET)
return -1;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);
addr.sin_port = 0;
if (bind (listener, (struct sockaddr *)&addr, addr_size))
goto fail;
if (getsockname (listener, (struct sockaddr *)&addr, &addr_size))
goto fail;
if (listen (listener, 1))
goto fail;
if ((sock [0] = ev_tcp_socket ()) == INVALID_SOCKET)
goto fail;
if (connect (sock [0], (struct sockaddr *)&addr, addr_size))
goto fail;
if ((sock [1] = accept (listener, 0, 0)) < 0)
goto fail;
/* windows vista returns fantasy port numbers for sockets:
* example for two interconnected tcp sockets:
*
* (Socket::unpack_sockaddr_in getsockname $sock0)[0] == 53364
* (Socket::unpack_sockaddr_in getpeername $sock0)[0] == 53363
* (Socket::unpack_sockaddr_in getsockname $sock1)[0] == 53363
* (Socket::unpack_sockaddr_in getpeername $sock1)[0] == 53365
*
* wow! tridirectional sockets!
*
* this way of checking ports seems to work:
*/
if (getpeername (sock [0], (struct sockaddr *)&addr, &addr_size))
goto fail;
if (getsockname (sock [1], (struct sockaddr *)&adr2, &adr2_size))
goto fail;
errno = WSAEINVAL;
if (addr_size != adr2_size
|| addr.sin_addr.s_addr != adr2.sin_addr.s_addr /* just to be sure, I mean, it's windows */
|| addr.sin_port != adr2.sin_port)
goto fail;
closesocket (listener);
#if EV_SELECT_IS_WINSOCKET
filedes [0] = EV_WIN32_HANDLE_TO_FD (sock [0]);
filedes [1] = EV_WIN32_HANDLE_TO_FD (sock [1]);
#else
/* when select isn't winsocket, we also expect socket, connect, accept etc.
* to work on fds */
filedes [0] = sock [0];
filedes [1] = sock [1];
#endif
return 0;
fail:
closesocket (listener);
if (sock [0] != INVALID_SOCKET) closesocket (sock [0]);
if (sock [1] != INVALID_SOCKET) closesocket (sock [1]);
return -1;
}
#undef pipe
#define pipe(filedes) ev_pipe (filedes)
#define EV_HAVE_EV_TIME 1
ev_tstamp
ev_time (void)
{
FILETIME ft;
ULARGE_INTEGER ui;
GetSystemTimeAsFileTime (&ft);
ui.u.LowPart = ft.dwLowDateTime;
ui.u.HighPart = ft.dwHighDateTime;
/* msvc cannot convert ulonglong to double... yes, it is that sucky */
return (LONGLONG)(ui.QuadPart - 116444736000000000) * 1e-7;
}
#endif
| gpl-3.0 |
CertifiedBlyndGuy/ewok-onyx | drivers/gud/MobiCoreDriver/api.c | 1376 | 2733 | /* MobiCore driver module.(interface to the secure world SWD)
* MobiCore Driver Kernel Module.
*
* <-- Copyright Giesecke & Devrient GmbH 2009-2012 -->
* <-- Copyright Trustonic Limited 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.
*/
#include <linux/module.h>
#include "main.h"
#include "mem.h"
#include "debug.h"
int mobicore_map_vmem(struct mc_instance *instance, void *addr,
uint32_t len, uint32_t *handle)
{
phys_addr_t phys;
return mc_register_wsm_mmu(instance, addr, len,
handle, &phys);
}
EXPORT_SYMBOL(mobicore_map_vmem);
/*
* Unmap a virtual memory buffer from mobicore
* @param instance
* @param handle
*
* @return 0 if no error
*
*/
int mobicore_unmap_vmem(struct mc_instance *instance, uint32_t handle)
{
return mc_unregister_wsm_mmu(instance, handle);
}
EXPORT_SYMBOL(mobicore_unmap_vmem);
/*
* Free a WSM buffer allocated with mobicore_allocate_wsm
* @param instance
* @param handle handle of the buffer
*
* @return 0 if no error
*
*/
int mobicore_free_wsm(struct mc_instance *instance, uint32_t handle)
{
return mc_free_buffer(instance, handle);
}
EXPORT_SYMBOL(mobicore_free_wsm);
/*
* Allocate WSM for given instance
*
* @param instance instance
* @param requested_size size of the WSM
* @param handle pointer where the handle will be saved
* @param virt_kernel_addr pointer for the kernel virtual address
*
* @return error code or 0 for success
*/
int mobicore_allocate_wsm(struct mc_instance *instance,
unsigned long requested_size, uint32_t *handle, void **virt_kernel_addr)
{
struct mc_buffer *buffer = NULL;
/* Setup the WSM buffer structure! */
if (mc_get_buffer(instance, &buffer, requested_size))
return -EFAULT;
*handle = buffer->handle;
*virt_kernel_addr = buffer->addr;
return 0;
}
EXPORT_SYMBOL(mobicore_allocate_wsm);
/*
* Initialize a new mobicore API instance object
*
* @return Instance or NULL if no allocation was possible.
*/
struct mc_instance *mobicore_open(void)
{
struct mc_instance *instance = mc_alloc_instance();
if(instance) {
instance->admin = true;
}
return instance;
}
EXPORT_SYMBOL(mobicore_open);
/*
* Release a mobicore instance object and all objects related to it
* @param instance instance
* @return 0 if Ok or -E ERROR
*/
int mobicore_release(struct mc_instance *instance)
{
return mc_release_instance(instance);
}
EXPORT_SYMBOL(mobicore_release);
/*
* Test if mobicore can sleep
*
* @return true if mobicore can sleep, false if it can't sleep
*/
bool mobicore_sleep_ready(void)
{
return mc_sleep_ready();
}
EXPORT_SYMBOL(mobicore_sleep_ready);
| gpl-3.0 |
yangpeiyong/shadowsocks-android | src/main/jni/openssl/crypto/x509v3/v3_asid.c | 614 | 24159 | /*
* Contributed to the OpenSSL Project by the American Registry for
* Internet Numbers ("ARIN").
*/
/* ====================================================================
* Copyright (c) 2006 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED 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 OpenSSL PROJECT OR
* ITS 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.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*/
/*
* Implementation of RFC 3779 section 3.2.
*/
#include <stdio.h>
#include <string.h>
#include "cryptlib.h"
#include <openssl/conf.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/x509v3.h>
#include <openssl/x509.h>
#include <openssl/bn.h>
#ifndef OPENSSL_NO_RFC3779
/*
* OpenSSL ASN.1 template translation of RFC 3779 3.2.3.
*/
ASN1_SEQUENCE(ASRange) = {
ASN1_SIMPLE(ASRange, min, ASN1_INTEGER),
ASN1_SIMPLE(ASRange, max, ASN1_INTEGER)
} ASN1_SEQUENCE_END(ASRange)
ASN1_CHOICE(ASIdOrRange) = {
ASN1_SIMPLE(ASIdOrRange, u.id, ASN1_INTEGER),
ASN1_SIMPLE(ASIdOrRange, u.range, ASRange)
} ASN1_CHOICE_END(ASIdOrRange)
ASN1_CHOICE(ASIdentifierChoice) = {
ASN1_SIMPLE(ASIdentifierChoice, u.inherit, ASN1_NULL),
ASN1_SEQUENCE_OF(ASIdentifierChoice, u.asIdsOrRanges, ASIdOrRange)
} ASN1_CHOICE_END(ASIdentifierChoice)
ASN1_SEQUENCE(ASIdentifiers) = {
ASN1_EXP_OPT(ASIdentifiers, asnum, ASIdentifierChoice, 0),
ASN1_EXP_OPT(ASIdentifiers, rdi, ASIdentifierChoice, 1)
} ASN1_SEQUENCE_END(ASIdentifiers)
IMPLEMENT_ASN1_FUNCTIONS(ASRange)
IMPLEMENT_ASN1_FUNCTIONS(ASIdOrRange)
IMPLEMENT_ASN1_FUNCTIONS(ASIdentifierChoice)
IMPLEMENT_ASN1_FUNCTIONS(ASIdentifiers)
/*
* i2r method for an ASIdentifierChoice.
*/
static int i2r_ASIdentifierChoice(BIO *out,
ASIdentifierChoice *choice,
int indent,
const char *msg)
{
int i;
char *s;
if (choice == NULL)
return 1;
BIO_printf(out, "%*s%s:\n", indent, "", msg);
switch (choice->type) {
case ASIdentifierChoice_inherit:
BIO_printf(out, "%*sinherit\n", indent + 2, "");
break;
case ASIdentifierChoice_asIdsOrRanges:
for (i = 0; i < sk_ASIdOrRange_num(choice->u.asIdsOrRanges); i++) {
ASIdOrRange *aor = sk_ASIdOrRange_value(choice->u.asIdsOrRanges, i);
switch (aor->type) {
case ASIdOrRange_id:
if ((s = i2s_ASN1_INTEGER(NULL, aor->u.id)) == NULL)
return 0;
BIO_printf(out, "%*s%s\n", indent + 2, "", s);
OPENSSL_free(s);
break;
case ASIdOrRange_range:
if ((s = i2s_ASN1_INTEGER(NULL, aor->u.range->min)) == NULL)
return 0;
BIO_printf(out, "%*s%s-", indent + 2, "", s);
OPENSSL_free(s);
if ((s = i2s_ASN1_INTEGER(NULL, aor->u.range->max)) == NULL)
return 0;
BIO_printf(out, "%s\n", s);
OPENSSL_free(s);
break;
default:
return 0;
}
}
break;
default:
return 0;
}
return 1;
}
/*
* i2r method for an ASIdentifier extension.
*/
static int i2r_ASIdentifiers(const X509V3_EXT_METHOD *method,
void *ext,
BIO *out,
int indent)
{
ASIdentifiers *asid = ext;
return (i2r_ASIdentifierChoice(out, asid->asnum, indent,
"Autonomous System Numbers") &&
i2r_ASIdentifierChoice(out, asid->rdi, indent,
"Routing Domain Identifiers"));
}
/*
* Sort comparision function for a sequence of ASIdOrRange elements.
*/
static int ASIdOrRange_cmp(const ASIdOrRange * const *a_,
const ASIdOrRange * const *b_)
{
const ASIdOrRange *a = *a_, *b = *b_;
OPENSSL_assert((a->type == ASIdOrRange_id && a->u.id != NULL) ||
(a->type == ASIdOrRange_range && a->u.range != NULL &&
a->u.range->min != NULL && a->u.range->max != NULL));
OPENSSL_assert((b->type == ASIdOrRange_id && b->u.id != NULL) ||
(b->type == ASIdOrRange_range && b->u.range != NULL &&
b->u.range->min != NULL && b->u.range->max != NULL));
if (a->type == ASIdOrRange_id && b->type == ASIdOrRange_id)
return ASN1_INTEGER_cmp(a->u.id, b->u.id);
if (a->type == ASIdOrRange_range && b->type == ASIdOrRange_range) {
int r = ASN1_INTEGER_cmp(a->u.range->min, b->u.range->min);
return r != 0 ? r : ASN1_INTEGER_cmp(a->u.range->max, b->u.range->max);
}
if (a->type == ASIdOrRange_id)
return ASN1_INTEGER_cmp(a->u.id, b->u.range->min);
else
return ASN1_INTEGER_cmp(a->u.range->min, b->u.id);
}
/*
* Add an inherit element.
*/
int v3_asid_add_inherit(ASIdentifiers *asid, int which)
{
ASIdentifierChoice **choice;
if (asid == NULL)
return 0;
switch (which) {
case V3_ASID_ASNUM:
choice = &asid->asnum;
break;
case V3_ASID_RDI:
choice = &asid->rdi;
break;
default:
return 0;
}
if (*choice == NULL) {
if ((*choice = ASIdentifierChoice_new()) == NULL)
return 0;
OPENSSL_assert((*choice)->u.inherit == NULL);
if (((*choice)->u.inherit = ASN1_NULL_new()) == NULL)
return 0;
(*choice)->type = ASIdentifierChoice_inherit;
}
return (*choice)->type == ASIdentifierChoice_inherit;
}
/*
* Add an ID or range to an ASIdentifierChoice.
*/
int v3_asid_add_id_or_range(ASIdentifiers *asid,
int which,
ASN1_INTEGER *min,
ASN1_INTEGER *max)
{
ASIdentifierChoice **choice;
ASIdOrRange *aor;
if (asid == NULL)
return 0;
switch (which) {
case V3_ASID_ASNUM:
choice = &asid->asnum;
break;
case V3_ASID_RDI:
choice = &asid->rdi;
break;
default:
return 0;
}
if (*choice != NULL && (*choice)->type == ASIdentifierChoice_inherit)
return 0;
if (*choice == NULL) {
if ((*choice = ASIdentifierChoice_new()) == NULL)
return 0;
OPENSSL_assert((*choice)->u.asIdsOrRanges == NULL);
(*choice)->u.asIdsOrRanges = sk_ASIdOrRange_new(ASIdOrRange_cmp);
if ((*choice)->u.asIdsOrRanges == NULL)
return 0;
(*choice)->type = ASIdentifierChoice_asIdsOrRanges;
}
if ((aor = ASIdOrRange_new()) == NULL)
return 0;
if (max == NULL) {
aor->type = ASIdOrRange_id;
aor->u.id = min;
} else {
aor->type = ASIdOrRange_range;
if ((aor->u.range = ASRange_new()) == NULL)
goto err;
ASN1_INTEGER_free(aor->u.range->min);
aor->u.range->min = min;
ASN1_INTEGER_free(aor->u.range->max);
aor->u.range->max = max;
}
if (!(sk_ASIdOrRange_push((*choice)->u.asIdsOrRanges, aor)))
goto err;
return 1;
err:
ASIdOrRange_free(aor);
return 0;
}
/*
* Extract min and max values from an ASIdOrRange.
*/
static void extract_min_max(ASIdOrRange *aor,
ASN1_INTEGER **min,
ASN1_INTEGER **max)
{
OPENSSL_assert(aor != NULL && min != NULL && max != NULL);
switch (aor->type) {
case ASIdOrRange_id:
*min = aor->u.id;
*max = aor->u.id;
return;
case ASIdOrRange_range:
*min = aor->u.range->min;
*max = aor->u.range->max;
return;
}
}
/*
* Check whether an ASIdentifierChoice is in canonical form.
*/
static int ASIdentifierChoice_is_canonical(ASIdentifierChoice *choice)
{
ASN1_INTEGER *a_max_plus_one = NULL;
BIGNUM *bn = NULL;
int i, ret = 0;
/*
* Empty element or inheritance is canonical.
*/
if (choice == NULL || choice->type == ASIdentifierChoice_inherit)
return 1;
/*
* If not a list, or if empty list, it's broken.
*/
if (choice->type != ASIdentifierChoice_asIdsOrRanges ||
sk_ASIdOrRange_num(choice->u.asIdsOrRanges) == 0)
return 0;
/*
* It's a list, check it.
*/
for (i = 0; i < sk_ASIdOrRange_num(choice->u.asIdsOrRanges) - 1; i++) {
ASIdOrRange *a = sk_ASIdOrRange_value(choice->u.asIdsOrRanges, i);
ASIdOrRange *b = sk_ASIdOrRange_value(choice->u.asIdsOrRanges, i + 1);
ASN1_INTEGER *a_min, *a_max, *b_min, *b_max;
extract_min_max(a, &a_min, &a_max);
extract_min_max(b, &b_min, &b_max);
/*
* Punt misordered list, overlapping start, or inverted range.
*/
if (ASN1_INTEGER_cmp(a_min, b_min) >= 0 ||
ASN1_INTEGER_cmp(a_min, a_max) > 0 ||
ASN1_INTEGER_cmp(b_min, b_max) > 0)
goto done;
/*
* Calculate a_max + 1 to check for adjacency.
*/
if ((bn == NULL && (bn = BN_new()) == NULL) ||
ASN1_INTEGER_to_BN(a_max, bn) == NULL ||
!BN_add_word(bn, 1) ||
(a_max_plus_one = BN_to_ASN1_INTEGER(bn, a_max_plus_one)) == NULL) {
X509V3err(X509V3_F_ASIDENTIFIERCHOICE_IS_CANONICAL,
ERR_R_MALLOC_FAILURE);
goto done;
}
/*
* Punt if adjacent or overlapping.
*/
if (ASN1_INTEGER_cmp(a_max_plus_one, b_min) >= 0)
goto done;
}
/*
* Check for inverted range.
*/
i = sk_ASIdOrRange_num(choice->u.asIdsOrRanges) - 1;
{
ASIdOrRange *a = sk_ASIdOrRange_value(choice->u.asIdsOrRanges, i);
ASN1_INTEGER *a_min, *a_max;
if (a != NULL && a->type == ASIdOrRange_range) {
extract_min_max(a, &a_min, &a_max);
if (ASN1_INTEGER_cmp(a_min, a_max) > 0)
goto done;
}
}
ret = 1;
done:
ASN1_INTEGER_free(a_max_plus_one);
BN_free(bn);
return ret;
}
/*
* Check whether an ASIdentifier extension is in canonical form.
*/
int v3_asid_is_canonical(ASIdentifiers *asid)
{
return (asid == NULL ||
(ASIdentifierChoice_is_canonical(asid->asnum) &&
ASIdentifierChoice_is_canonical(asid->rdi)));
}
/*
* Whack an ASIdentifierChoice into canonical form.
*/
static int ASIdentifierChoice_canonize(ASIdentifierChoice *choice)
{
ASN1_INTEGER *a_max_plus_one = NULL;
BIGNUM *bn = NULL;
int i, ret = 0;
/*
* Nothing to do for empty element or inheritance.
*/
if (choice == NULL || choice->type == ASIdentifierChoice_inherit)
return 1;
/*
* If not a list, or if empty list, it's broken.
*/
if (choice->type != ASIdentifierChoice_asIdsOrRanges ||
sk_ASIdOrRange_num(choice->u.asIdsOrRanges) == 0) {
X509V3err(X509V3_F_ASIDENTIFIERCHOICE_CANONIZE,
X509V3_R_EXTENSION_VALUE_ERROR);
return 0;
}
/*
* We have a non-empty list. Sort it.
*/
sk_ASIdOrRange_sort(choice->u.asIdsOrRanges);
/*
* Now check for errors and suboptimal encoding, rejecting the
* former and fixing the latter.
*/
for (i = 0; i < sk_ASIdOrRange_num(choice->u.asIdsOrRanges) - 1; i++) {
ASIdOrRange *a = sk_ASIdOrRange_value(choice->u.asIdsOrRanges, i);
ASIdOrRange *b = sk_ASIdOrRange_value(choice->u.asIdsOrRanges, i + 1);
ASN1_INTEGER *a_min, *a_max, *b_min, *b_max;
extract_min_max(a, &a_min, &a_max);
extract_min_max(b, &b_min, &b_max);
/*
* Make sure we're properly sorted (paranoia).
*/
OPENSSL_assert(ASN1_INTEGER_cmp(a_min, b_min) <= 0);
/*
* Punt inverted ranges.
*/
if (ASN1_INTEGER_cmp(a_min, a_max) > 0 ||
ASN1_INTEGER_cmp(b_min, b_max) > 0)
goto done;
/*
* Check for overlaps.
*/
if (ASN1_INTEGER_cmp(a_max, b_min) >= 0) {
X509V3err(X509V3_F_ASIDENTIFIERCHOICE_CANONIZE,
X509V3_R_EXTENSION_VALUE_ERROR);
goto done;
}
/*
* Calculate a_max + 1 to check for adjacency.
*/
if ((bn == NULL && (bn = BN_new()) == NULL) ||
ASN1_INTEGER_to_BN(a_max, bn) == NULL ||
!BN_add_word(bn, 1) ||
(a_max_plus_one = BN_to_ASN1_INTEGER(bn, a_max_plus_one)) == NULL) {
X509V3err(X509V3_F_ASIDENTIFIERCHOICE_CANONIZE, ERR_R_MALLOC_FAILURE);
goto done;
}
/*
* If a and b are adjacent, merge them.
*/
if (ASN1_INTEGER_cmp(a_max_plus_one, b_min) == 0) {
ASRange *r;
switch (a->type) {
case ASIdOrRange_id:
if ((r = OPENSSL_malloc(sizeof(ASRange))) == NULL) {
X509V3err(X509V3_F_ASIDENTIFIERCHOICE_CANONIZE,
ERR_R_MALLOC_FAILURE);
goto done;
}
r->min = a_min;
r->max = b_max;
a->type = ASIdOrRange_range;
a->u.range = r;
break;
case ASIdOrRange_range:
ASN1_INTEGER_free(a->u.range->max);
a->u.range->max = b_max;
break;
}
switch (b->type) {
case ASIdOrRange_id:
b->u.id = NULL;
break;
case ASIdOrRange_range:
b->u.range->max = NULL;
break;
}
ASIdOrRange_free(b);
(void) sk_ASIdOrRange_delete(choice->u.asIdsOrRanges, i + 1);
i--;
continue;
}
}
/*
* Check for final inverted range.
*/
i = sk_ASIdOrRange_num(choice->u.asIdsOrRanges) - 1;
{
ASIdOrRange *a = sk_ASIdOrRange_value(choice->u.asIdsOrRanges, i);
ASN1_INTEGER *a_min, *a_max;
if (a != NULL && a->type == ASIdOrRange_range) {
extract_min_max(a, &a_min, &a_max);
if (ASN1_INTEGER_cmp(a_min, a_max) > 0)
goto done;
}
}
OPENSSL_assert(ASIdentifierChoice_is_canonical(choice)); /* Paranoia */
ret = 1;
done:
ASN1_INTEGER_free(a_max_plus_one);
BN_free(bn);
return ret;
}
/*
* Whack an ASIdentifier extension into canonical form.
*/
int v3_asid_canonize(ASIdentifiers *asid)
{
return (asid == NULL ||
(ASIdentifierChoice_canonize(asid->asnum) &&
ASIdentifierChoice_canonize(asid->rdi)));
}
/*
* v2i method for an ASIdentifier extension.
*/
static void *v2i_ASIdentifiers(const struct v3_ext_method *method,
struct v3_ext_ctx *ctx,
STACK_OF(CONF_VALUE) *values)
{
ASN1_INTEGER *min = NULL, *max = NULL;
ASIdentifiers *asid = NULL;
int i;
if ((asid = ASIdentifiers_new()) == NULL) {
X509V3err(X509V3_F_V2I_ASIDENTIFIERS, ERR_R_MALLOC_FAILURE);
return NULL;
}
for (i = 0; i < sk_CONF_VALUE_num(values); i++) {
CONF_VALUE *val = sk_CONF_VALUE_value(values, i);
int i1, i2, i3, is_range, which;
/*
* Figure out whether this is an AS or an RDI.
*/
if ( !name_cmp(val->name, "AS")) {
which = V3_ASID_ASNUM;
} else if (!name_cmp(val->name, "RDI")) {
which = V3_ASID_RDI;
} else {
X509V3err(X509V3_F_V2I_ASIDENTIFIERS, X509V3_R_EXTENSION_NAME_ERROR);
X509V3_conf_err(val);
goto err;
}
/*
* Handle inheritance.
*/
if (!strcmp(val->value, "inherit")) {
if (v3_asid_add_inherit(asid, which))
continue;
X509V3err(X509V3_F_V2I_ASIDENTIFIERS, X509V3_R_INVALID_INHERITANCE);
X509V3_conf_err(val);
goto err;
}
/*
* Number, range, or mistake, pick it apart and figure out which.
*/
i1 = strspn(val->value, "0123456789");
if (val->value[i1] == '\0') {
is_range = 0;
} else {
is_range = 1;
i2 = i1 + strspn(val->value + i1, " \t");
if (val->value[i2] != '-') {
X509V3err(X509V3_F_V2I_ASIDENTIFIERS, X509V3_R_INVALID_ASNUMBER);
X509V3_conf_err(val);
goto err;
}
i2++;
i2 = i2 + strspn(val->value + i2, " \t");
i3 = i2 + strspn(val->value + i2, "0123456789");
if (val->value[i3] != '\0') {
X509V3err(X509V3_F_V2I_ASIDENTIFIERS, X509V3_R_INVALID_ASRANGE);
X509V3_conf_err(val);
goto err;
}
}
/*
* Syntax is ok, read and add it.
*/
if (!is_range) {
if (!X509V3_get_value_int(val, &min)) {
X509V3err(X509V3_F_V2I_ASIDENTIFIERS, ERR_R_MALLOC_FAILURE);
goto err;
}
} else {
char *s = BUF_strdup(val->value);
if (s == NULL) {
X509V3err(X509V3_F_V2I_ASIDENTIFIERS, ERR_R_MALLOC_FAILURE);
goto err;
}
s[i1] = '\0';
min = s2i_ASN1_INTEGER(NULL, s);
max = s2i_ASN1_INTEGER(NULL, s + i2);
OPENSSL_free(s);
if (min == NULL || max == NULL) {
X509V3err(X509V3_F_V2I_ASIDENTIFIERS, ERR_R_MALLOC_FAILURE);
goto err;
}
if (ASN1_INTEGER_cmp(min, max) > 0) {
X509V3err(X509V3_F_V2I_ASIDENTIFIERS, X509V3_R_EXTENSION_VALUE_ERROR);
goto err;
}
}
if (!v3_asid_add_id_or_range(asid, which, min, max)) {
X509V3err(X509V3_F_V2I_ASIDENTIFIERS, ERR_R_MALLOC_FAILURE);
goto err;
}
min = max = NULL;
}
/*
* Canonize the result, then we're done.
*/
if (!v3_asid_canonize(asid))
goto err;
return asid;
err:
ASIdentifiers_free(asid);
ASN1_INTEGER_free(min);
ASN1_INTEGER_free(max);
return NULL;
}
/*
* OpenSSL dispatch.
*/
const X509V3_EXT_METHOD v3_asid = {
NID_sbgp_autonomousSysNum, /* nid */
0, /* flags */
ASN1_ITEM_ref(ASIdentifiers), /* template */
0, 0, 0, 0, /* old functions, ignored */
0, /* i2s */
0, /* s2i */
0, /* i2v */
v2i_ASIdentifiers, /* v2i */
i2r_ASIdentifiers, /* i2r */
0, /* r2i */
NULL /* extension-specific data */
};
/*
* Figure out whether extension uses inheritance.
*/
int v3_asid_inherits(ASIdentifiers *asid)
{
return (asid != NULL &&
((asid->asnum != NULL &&
asid->asnum->type == ASIdentifierChoice_inherit) ||
(asid->rdi != NULL &&
asid->rdi->type == ASIdentifierChoice_inherit)));
}
/*
* Figure out whether parent contains child.
*/
static int asid_contains(ASIdOrRanges *parent, ASIdOrRanges *child)
{
ASN1_INTEGER *p_min, *p_max, *c_min, *c_max;
int p, c;
if (child == NULL || parent == child)
return 1;
if (parent == NULL)
return 0;
p = 0;
for (c = 0; c < sk_ASIdOrRange_num(child); c++) {
extract_min_max(sk_ASIdOrRange_value(child, c), &c_min, &c_max);
for (;; p++) {
if (p >= sk_ASIdOrRange_num(parent))
return 0;
extract_min_max(sk_ASIdOrRange_value(parent, p), &p_min, &p_max);
if (ASN1_INTEGER_cmp(p_max, c_max) < 0)
continue;
if (ASN1_INTEGER_cmp(p_min, c_min) > 0)
return 0;
break;
}
}
return 1;
}
/*
* Test whether a is a subet of b.
*/
int v3_asid_subset(ASIdentifiers *a, ASIdentifiers *b)
{
return (a == NULL ||
a == b ||
(b != NULL &&
!v3_asid_inherits(a) &&
!v3_asid_inherits(b) &&
asid_contains(b->asnum->u.asIdsOrRanges,
a->asnum->u.asIdsOrRanges) &&
asid_contains(b->rdi->u.asIdsOrRanges,
a->rdi->u.asIdsOrRanges)));
}
/*
* Validation error handling via callback.
*/
#define validation_err(_err_) \
do { \
if (ctx != NULL) { \
ctx->error = _err_; \
ctx->error_depth = i; \
ctx->current_cert = x; \
ret = ctx->verify_cb(0, ctx); \
} else { \
ret = 0; \
} \
if (!ret) \
goto done; \
} while (0)
/*
* Core code for RFC 3779 3.3 path validation.
*/
static int v3_asid_validate_path_internal(X509_STORE_CTX *ctx,
STACK_OF(X509) *chain,
ASIdentifiers *ext)
{
ASIdOrRanges *child_as = NULL, *child_rdi = NULL;
int i, ret = 1, inherit_as = 0, inherit_rdi = 0;
X509 *x;
OPENSSL_assert(chain != NULL && sk_X509_num(chain) > 0);
OPENSSL_assert(ctx != NULL || ext != NULL);
OPENSSL_assert(ctx == NULL || ctx->verify_cb != NULL);
/*
* Figure out where to start. If we don't have an extension to
* check, we're done. Otherwise, check canonical form and
* set up for walking up the chain.
*/
if (ext != NULL) {
i = -1;
x = NULL;
} else {
i = 0;
x = sk_X509_value(chain, i);
OPENSSL_assert(x != NULL);
if ((ext = x->rfc3779_asid) == NULL)
goto done;
}
if (!v3_asid_is_canonical(ext))
validation_err(X509_V_ERR_INVALID_EXTENSION);
if (ext->asnum != NULL) {
switch (ext->asnum->type) {
case ASIdentifierChoice_inherit:
inherit_as = 1;
break;
case ASIdentifierChoice_asIdsOrRanges:
child_as = ext->asnum->u.asIdsOrRanges;
break;
}
}
if (ext->rdi != NULL) {
switch (ext->rdi->type) {
case ASIdentifierChoice_inherit:
inherit_rdi = 1;
break;
case ASIdentifierChoice_asIdsOrRanges:
child_rdi = ext->rdi->u.asIdsOrRanges;
break;
}
}
/*
* Now walk up the chain. Extensions must be in canonical form, no
* cert may list resources that its parent doesn't list.
*/
for (i++; i < sk_X509_num(chain); i++) {
x = sk_X509_value(chain, i);
OPENSSL_assert(x != NULL);
if (x->rfc3779_asid == NULL) {
if (child_as != NULL || child_rdi != NULL)
validation_err(X509_V_ERR_UNNESTED_RESOURCE);
continue;
}
if (!v3_asid_is_canonical(x->rfc3779_asid))
validation_err(X509_V_ERR_INVALID_EXTENSION);
if (x->rfc3779_asid->asnum == NULL && child_as != NULL) {
validation_err(X509_V_ERR_UNNESTED_RESOURCE);
child_as = NULL;
inherit_as = 0;
}
if (x->rfc3779_asid->asnum != NULL &&
x->rfc3779_asid->asnum->type == ASIdentifierChoice_asIdsOrRanges) {
if (inherit_as ||
asid_contains(x->rfc3779_asid->asnum->u.asIdsOrRanges, child_as)) {
child_as = x->rfc3779_asid->asnum->u.asIdsOrRanges;
inherit_as = 0;
} else {
validation_err(X509_V_ERR_UNNESTED_RESOURCE);
}
}
if (x->rfc3779_asid->rdi == NULL && child_rdi != NULL) {
validation_err(X509_V_ERR_UNNESTED_RESOURCE);
child_rdi = NULL;
inherit_rdi = 0;
}
if (x->rfc3779_asid->rdi != NULL &&
x->rfc3779_asid->rdi->type == ASIdentifierChoice_asIdsOrRanges) {
if (inherit_rdi ||
asid_contains(x->rfc3779_asid->rdi->u.asIdsOrRanges, child_rdi)) {
child_rdi = x->rfc3779_asid->rdi->u.asIdsOrRanges;
inherit_rdi = 0;
} else {
validation_err(X509_V_ERR_UNNESTED_RESOURCE);
}
}
}
/*
* Trust anchor can't inherit.
*/
OPENSSL_assert(x != NULL);
if (x->rfc3779_asid != NULL) {
if (x->rfc3779_asid->asnum != NULL &&
x->rfc3779_asid->asnum->type == ASIdentifierChoice_inherit)
validation_err(X509_V_ERR_UNNESTED_RESOURCE);
if (x->rfc3779_asid->rdi != NULL &&
x->rfc3779_asid->rdi->type == ASIdentifierChoice_inherit)
validation_err(X509_V_ERR_UNNESTED_RESOURCE);
}
done:
return ret;
}
#undef validation_err
/*
* RFC 3779 3.3 path validation -- called from X509_verify_cert().
*/
int v3_asid_validate_path(X509_STORE_CTX *ctx)
{
return v3_asid_validate_path_internal(ctx, ctx->chain, NULL);
}
/*
* RFC 3779 3.3 path validation of an extension.
* Test whether chain covers extension.
*/
int v3_asid_validate_resource_set(STACK_OF(X509) *chain,
ASIdentifiers *ext,
int allow_inheritance)
{
if (ext == NULL)
return 1;
if (chain == NULL || sk_X509_num(chain) == 0)
return 0;
if (!allow_inheritance && v3_asid_inherits(ext))
return 0;
return v3_asid_validate_path_internal(NULL, chain, ext);
}
#endif /* OPENSSL_NO_RFC3779 */
| gpl-3.0 |
WisniaPL/LeEco-Le1S-Kernel | drivers/net/irda/vlsi_ir.c | 2153 | 51779 | /*********************************************************************
*
* vlsi_ir.c: VLSI82C147 PCI IrDA controller driver for Linux
*
* Copyright (c) 2001-2003 Martin Diehl
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
********************************************************************/
#include <linux/module.h>
#define DRIVER_NAME "vlsi_ir"
#define DRIVER_VERSION "v0.5"
#define DRIVER_DESCRIPTION "IrDA SIR/MIR/FIR driver for VLSI 82C147"
#define DRIVER_AUTHOR "Martin Diehl <info@mdiehl.de>"
MODULE_DESCRIPTION(DRIVER_DESCRIPTION);
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_LICENSE("GPL");
/********************************************************/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/pci.h>
#include <linux/slab.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <linux/delay.h>
#include <linux/time.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/mutex.h>
#include <asm/uaccess.h>
#include <asm/byteorder.h>
#include <net/irda/irda.h>
#include <net/irda/irda_device.h>
#include <net/irda/wrapper.h>
#include <net/irda/crc.h>
#include "vlsi_ir.h"
/********************************************************/
static /* const */ char drivername[] = DRIVER_NAME;
static DEFINE_PCI_DEVICE_TABLE(vlsi_irda_table) = {
{
.class = PCI_CLASS_WIRELESS_IRDA << 8,
.class_mask = PCI_CLASS_SUBCLASS_MASK << 8,
.vendor = PCI_VENDOR_ID_VLSI,
.device = PCI_DEVICE_ID_VLSI_82C147,
.subvendor = PCI_ANY_ID,
.subdevice = PCI_ANY_ID,
},
{ /* all zeroes */ }
};
MODULE_DEVICE_TABLE(pci, vlsi_irda_table);
/********************************************************/
/* clksrc: which clock source to be used
* 0: auto - try PLL, fallback to 40MHz XCLK
* 1: on-chip 48MHz PLL
* 2: external 48MHz XCLK
* 3: external 40MHz XCLK (HP OB-800)
*/
static int clksrc = 0; /* default is 0(auto) */
module_param(clksrc, int, 0);
MODULE_PARM_DESC(clksrc, "clock input source selection");
/* ringsize: size of the tx and rx descriptor rings
* independent for tx and rx
* specify as ringsize=tx[,rx]
* allowed values: 4, 8, 16, 32, 64
* Due to the IrDA 1.x max. allowed window size=7,
* there should be no gain when using rings larger than 8
*/
static int ringsize[] = {8,8}; /* default is tx=8 / rx=8 */
module_param_array(ringsize, int, NULL, 0);
MODULE_PARM_DESC(ringsize, "TX, RX ring descriptor size");
/* sirpulse: tuning of the SIR pulse width within IrPHY 1.3 limits
* 0: very short, 1.5us (exception: 6us at 2.4 kbaud)
* 1: nominal 3/16 bittime width
* note: IrDA compliant peer devices should be happy regardless
* which one is used. Primary goal is to save some power
* on the sender's side - at 9.6kbaud for example the short
* pulse width saves more than 90% of the transmitted IR power.
*/
static int sirpulse = 1; /* default is 3/16 bittime */
module_param(sirpulse, int, 0);
MODULE_PARM_DESC(sirpulse, "SIR pulse width tuning");
/* qos_mtt_bits: encoded min-turn-time value we require the peer device
* to use before transmitting to us. "Type 1" (per-station)
* bitfield according to IrLAP definition (section 6.6.8)
* Don't know which transceiver is used by my OB800 - the
* pretty common HP HDLS-1100 requires 1 msec - so lets use this.
*/
static int qos_mtt_bits = 0x07; /* default is 1 ms or more */
module_param(qos_mtt_bits, int, 0);
MODULE_PARM_DESC(qos_mtt_bits, "IrLAP bitfield representing min-turn-time");
/********************************************************/
static void vlsi_reg_debug(unsigned iobase, const char *s)
{
int i;
printk(KERN_DEBUG "%s: ", s);
for (i = 0; i < 0x20; i++)
printk("%02x", (unsigned)inb((iobase+i)));
printk("\n");
}
static void vlsi_ring_debug(struct vlsi_ring *r)
{
struct ring_descr *rd;
unsigned i;
printk(KERN_DEBUG "%s - ring %p / size %u / mask 0x%04x / len %u / dir %d / hw %p\n",
__func__, r, r->size, r->mask, r->len, r->dir, r->rd[0].hw);
printk(KERN_DEBUG "%s - head = %d / tail = %d\n", __func__,
atomic_read(&r->head) & r->mask, atomic_read(&r->tail) & r->mask);
for (i = 0; i < r->size; i++) {
rd = &r->rd[i];
printk(KERN_DEBUG "%s - ring descr %u: ", __func__, i);
printk("skb=%p data=%p hw=%p\n", rd->skb, rd->buf, rd->hw);
printk(KERN_DEBUG "%s - hw: status=%02x count=%u addr=0x%08x\n",
__func__, (unsigned) rd_get_status(rd),
(unsigned) rd_get_count(rd), (unsigned) rd_get_addr(rd));
}
}
/********************************************************/
/* needed regardless of CONFIG_PROC_FS */
static struct proc_dir_entry *vlsi_proc_root = NULL;
#ifdef CONFIG_PROC_FS
static void vlsi_proc_pdev(struct seq_file *seq, struct pci_dev *pdev)
{
unsigned iobase = pci_resource_start(pdev, 0);
unsigned i;
seq_printf(seq, "\n%s (vid/did: [%04x:%04x])\n",
pci_name(pdev), (int)pdev->vendor, (int)pdev->device);
seq_printf(seq, "pci-power-state: %u\n", (unsigned) pdev->current_state);
seq_printf(seq, "resources: irq=%u / io=0x%04x / dma_mask=0x%016Lx\n",
pdev->irq, (unsigned)pci_resource_start(pdev, 0), (unsigned long long)pdev->dma_mask);
seq_printf(seq, "hw registers: ");
for (i = 0; i < 0x20; i++)
seq_printf(seq, "%02x", (unsigned)inb((iobase+i)));
seq_printf(seq, "\n");
}
static void vlsi_proc_ndev(struct seq_file *seq, struct net_device *ndev)
{
vlsi_irda_dev_t *idev = netdev_priv(ndev);
u8 byte;
u16 word;
unsigned delta1, delta2;
struct timeval now;
unsigned iobase = ndev->base_addr;
seq_printf(seq, "\n%s link state: %s / %s / %s / %s\n", ndev->name,
netif_device_present(ndev) ? "attached" : "detached",
netif_running(ndev) ? "running" : "not running",
netif_carrier_ok(ndev) ? "carrier ok" : "no carrier",
netif_queue_stopped(ndev) ? "queue stopped" : "queue running");
if (!netif_running(ndev))
return;
seq_printf(seq, "\nhw-state:\n");
pci_read_config_byte(idev->pdev, VLSI_PCI_IRMISC, &byte);
seq_printf(seq, "IRMISC:%s%s%s uart%s",
(byte&IRMISC_IRRAIL) ? " irrail" : "",
(byte&IRMISC_IRPD) ? " irpd" : "",
(byte&IRMISC_UARTTST) ? " uarttest" : "",
(byte&IRMISC_UARTEN) ? "@" : " disabled\n");
if (byte&IRMISC_UARTEN) {
seq_printf(seq, "0x%s\n",
(byte&2) ? ((byte&1) ? "3e8" : "2e8")
: ((byte&1) ? "3f8" : "2f8"));
}
pci_read_config_byte(idev->pdev, VLSI_PCI_CLKCTL, &byte);
seq_printf(seq, "CLKCTL: PLL %s%s%s / clock %s / wakeup %s\n",
(byte&CLKCTL_PD_INV) ? "powered" : "down",
(byte&CLKCTL_LOCK) ? " locked" : "",
(byte&CLKCTL_EXTCLK) ? ((byte&CLKCTL_XCKSEL)?" / 40 MHz XCLK":" / 48 MHz XCLK") : "",
(byte&CLKCTL_CLKSTP) ? "stopped" : "running",
(byte&CLKCTL_WAKE) ? "enabled" : "disabled");
pci_read_config_byte(idev->pdev, VLSI_PCI_MSTRPAGE, &byte);
seq_printf(seq, "MSTRPAGE: 0x%02x\n", (unsigned)byte);
byte = inb(iobase+VLSI_PIO_IRINTR);
seq_printf(seq, "IRINTR:%s%s%s%s%s%s%s%s\n",
(byte&IRINTR_ACTEN) ? " ACTEN" : "",
(byte&IRINTR_RPKTEN) ? " RPKTEN" : "",
(byte&IRINTR_TPKTEN) ? " TPKTEN" : "",
(byte&IRINTR_OE_EN) ? " OE_EN" : "",
(byte&IRINTR_ACTIVITY) ? " ACTIVITY" : "",
(byte&IRINTR_RPKTINT) ? " RPKTINT" : "",
(byte&IRINTR_TPKTINT) ? " TPKTINT" : "",
(byte&IRINTR_OE_INT) ? " OE_INT" : "");
word = inw(iobase+VLSI_PIO_RINGPTR);
seq_printf(seq, "RINGPTR: rx=%u / tx=%u\n", RINGPTR_GET_RX(word), RINGPTR_GET_TX(word));
word = inw(iobase+VLSI_PIO_RINGBASE);
seq_printf(seq, "RINGBASE: busmap=0x%08x\n",
((unsigned)word << 10)|(MSTRPAGE_VALUE<<24));
word = inw(iobase+VLSI_PIO_RINGSIZE);
seq_printf(seq, "RINGSIZE: rx=%u / tx=%u\n", RINGSIZE_TO_RXSIZE(word),
RINGSIZE_TO_TXSIZE(word));
word = inw(iobase+VLSI_PIO_IRCFG);
seq_printf(seq, "IRCFG:%s%s%s%s%s%s%s%s%s%s%s%s%s\n",
(word&IRCFG_LOOP) ? " LOOP" : "",
(word&IRCFG_ENTX) ? " ENTX" : "",
(word&IRCFG_ENRX) ? " ENRX" : "",
(word&IRCFG_MSTR) ? " MSTR" : "",
(word&IRCFG_RXANY) ? " RXANY" : "",
(word&IRCFG_CRC16) ? " CRC16" : "",
(word&IRCFG_FIR) ? " FIR" : "",
(word&IRCFG_MIR) ? " MIR" : "",
(word&IRCFG_SIR) ? " SIR" : "",
(word&IRCFG_SIRFILT) ? " SIRFILT" : "",
(word&IRCFG_SIRTEST) ? " SIRTEST" : "",
(word&IRCFG_TXPOL) ? " TXPOL" : "",
(word&IRCFG_RXPOL) ? " RXPOL" : "");
word = inw(iobase+VLSI_PIO_IRENABLE);
seq_printf(seq, "IRENABLE:%s%s%s%s%s%s%s%s\n",
(word&IRENABLE_PHYANDCLOCK) ? " PHYANDCLOCK" : "",
(word&IRENABLE_CFGER) ? " CFGERR" : "",
(word&IRENABLE_FIR_ON) ? " FIR_ON" : "",
(word&IRENABLE_MIR_ON) ? " MIR_ON" : "",
(word&IRENABLE_SIR_ON) ? " SIR_ON" : "",
(word&IRENABLE_ENTXST) ? " ENTXST" : "",
(word&IRENABLE_ENRXST) ? " ENRXST" : "",
(word&IRENABLE_CRC16_ON) ? " CRC16_ON" : "");
word = inw(iobase+VLSI_PIO_PHYCTL);
seq_printf(seq, "PHYCTL: baud-divisor=%u / pulsewidth=%u / preamble=%u\n",
(unsigned)PHYCTL_TO_BAUD(word),
(unsigned)PHYCTL_TO_PLSWID(word),
(unsigned)PHYCTL_TO_PREAMB(word));
word = inw(iobase+VLSI_PIO_NPHYCTL);
seq_printf(seq, "NPHYCTL: baud-divisor=%u / pulsewidth=%u / preamble=%u\n",
(unsigned)PHYCTL_TO_BAUD(word),
(unsigned)PHYCTL_TO_PLSWID(word),
(unsigned)PHYCTL_TO_PREAMB(word));
word = inw(iobase+VLSI_PIO_MAXPKT);
seq_printf(seq, "MAXPKT: max. rx packet size = %u\n", word);
word = inw(iobase+VLSI_PIO_RCVBCNT) & RCVBCNT_MASK;
seq_printf(seq, "RCVBCNT: rx-fifo filling level = %u\n", word);
seq_printf(seq, "\nsw-state:\n");
seq_printf(seq, "IrPHY setup: %d baud - %s encoding\n", idev->baud,
(idev->mode==IFF_SIR)?"SIR":((idev->mode==IFF_MIR)?"MIR":"FIR"));
do_gettimeofday(&now);
if (now.tv_usec >= idev->last_rx.tv_usec) {
delta2 = now.tv_usec - idev->last_rx.tv_usec;
delta1 = 0;
}
else {
delta2 = 1000000 + now.tv_usec - idev->last_rx.tv_usec;
delta1 = 1;
}
seq_printf(seq, "last rx: %lu.%06u sec\n",
now.tv_sec - idev->last_rx.tv_sec - delta1, delta2);
seq_printf(seq, "RX: packets=%lu / bytes=%lu / errors=%lu / dropped=%lu",
ndev->stats.rx_packets, ndev->stats.rx_bytes, ndev->stats.rx_errors,
ndev->stats.rx_dropped);
seq_printf(seq, " / overrun=%lu / length=%lu / frame=%lu / crc=%lu\n",
ndev->stats.rx_over_errors, ndev->stats.rx_length_errors,
ndev->stats.rx_frame_errors, ndev->stats.rx_crc_errors);
seq_printf(seq, "TX: packets=%lu / bytes=%lu / errors=%lu / dropped=%lu / fifo=%lu\n",
ndev->stats.tx_packets, ndev->stats.tx_bytes, ndev->stats.tx_errors,
ndev->stats.tx_dropped, ndev->stats.tx_fifo_errors);
}
static void vlsi_proc_ring(struct seq_file *seq, struct vlsi_ring *r)
{
struct ring_descr *rd;
unsigned i, j;
int h, t;
seq_printf(seq, "size %u / mask 0x%04x / len %u / dir %d / hw %p\n",
r->size, r->mask, r->len, r->dir, r->rd[0].hw);
h = atomic_read(&r->head) & r->mask;
t = atomic_read(&r->tail) & r->mask;
seq_printf(seq, "head = %d / tail = %d ", h, t);
if (h == t)
seq_printf(seq, "(empty)\n");
else {
if (((t+1)&r->mask) == h)
seq_printf(seq, "(full)\n");
else
seq_printf(seq, "(level = %d)\n", ((unsigned)(t-h) & r->mask));
rd = &r->rd[h];
j = (unsigned) rd_get_count(rd);
seq_printf(seq, "current: rd = %d / status = %02x / len = %u\n",
h, (unsigned)rd_get_status(rd), j);
if (j > 0) {
seq_printf(seq, " data:");
if (j > 20)
j = 20;
for (i = 0; i < j; i++)
seq_printf(seq, " %02x", (unsigned)((unsigned char *)rd->buf)[i]);
seq_printf(seq, "\n");
}
}
for (i = 0; i < r->size; i++) {
rd = &r->rd[i];
seq_printf(seq, "> ring descr %u: ", i);
seq_printf(seq, "skb=%p data=%p hw=%p\n", rd->skb, rd->buf, rd->hw);
seq_printf(seq, " hw: status=%02x count=%u busaddr=0x%08x\n",
(unsigned) rd_get_status(rd),
(unsigned) rd_get_count(rd), (unsigned) rd_get_addr(rd));
}
}
static int vlsi_seq_show(struct seq_file *seq, void *v)
{
struct net_device *ndev = seq->private;
vlsi_irda_dev_t *idev = netdev_priv(ndev);
unsigned long flags;
seq_printf(seq, "\n%s %s\n\n", DRIVER_NAME, DRIVER_VERSION);
seq_printf(seq, "clksrc: %s\n",
(clksrc>=2) ? ((clksrc==3)?"40MHz XCLK":"48MHz XCLK")
: ((clksrc==1)?"48MHz PLL":"autodetect"));
seq_printf(seq, "ringsize: tx=%d / rx=%d\n",
ringsize[0], ringsize[1]);
seq_printf(seq, "sirpulse: %s\n", (sirpulse)?"3/16 bittime":"short");
seq_printf(seq, "qos_mtt_bits: 0x%02x\n", (unsigned)qos_mtt_bits);
spin_lock_irqsave(&idev->lock, flags);
if (idev->pdev != NULL) {
vlsi_proc_pdev(seq, idev->pdev);
if (idev->pdev->current_state == 0)
vlsi_proc_ndev(seq, ndev);
else
seq_printf(seq, "\nPCI controller down - resume_ok = %d\n",
idev->resume_ok);
if (netif_running(ndev) && idev->rx_ring && idev->tx_ring) {
seq_printf(seq, "\n--------- RX ring -----------\n\n");
vlsi_proc_ring(seq, idev->rx_ring);
seq_printf(seq, "\n--------- TX ring -----------\n\n");
vlsi_proc_ring(seq, idev->tx_ring);
}
}
seq_printf(seq, "\n");
spin_unlock_irqrestore(&idev->lock, flags);
return 0;
}
static int vlsi_seq_open(struct inode *inode, struct file *file)
{
return single_open(file, vlsi_seq_show, PDE_DATA(inode));
}
static const struct file_operations vlsi_proc_fops = {
.owner = THIS_MODULE,
.open = vlsi_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
#define VLSI_PROC_FOPS (&vlsi_proc_fops)
#else /* CONFIG_PROC_FS */
#define VLSI_PROC_FOPS NULL
#endif
/********************************************************/
static struct vlsi_ring *vlsi_alloc_ring(struct pci_dev *pdev, struct ring_descr_hw *hwmap,
unsigned size, unsigned len, int dir)
{
struct vlsi_ring *r;
struct ring_descr *rd;
unsigned i, j;
dma_addr_t busaddr;
if (!size || ((size-1)&size)!=0) /* must be >0 and power of 2 */
return NULL;
r = kmalloc(sizeof(*r) + size * sizeof(struct ring_descr), GFP_KERNEL);
if (!r)
return NULL;
memset(r, 0, sizeof(*r));
r->pdev = pdev;
r->dir = dir;
r->len = len;
r->rd = (struct ring_descr *)(r+1);
r->mask = size - 1;
r->size = size;
atomic_set(&r->head, 0);
atomic_set(&r->tail, 0);
for (i = 0; i < size; i++) {
rd = r->rd + i;
memset(rd, 0, sizeof(*rd));
rd->hw = hwmap + i;
rd->buf = kmalloc(len, GFP_KERNEL|GFP_DMA);
if (rd->buf == NULL ||
!(busaddr = pci_map_single(pdev, rd->buf, len, dir))) {
if (rd->buf) {
IRDA_ERROR("%s: failed to create PCI-MAP for %p",
__func__, rd->buf);
kfree(rd->buf);
rd->buf = NULL;
}
for (j = 0; j < i; j++) {
rd = r->rd + j;
busaddr = rd_get_addr(rd);
rd_set_addr_status(rd, 0, 0);
if (busaddr)
pci_unmap_single(pdev, busaddr, len, dir);
kfree(rd->buf);
rd->buf = NULL;
}
kfree(r);
return NULL;
}
rd_set_addr_status(rd, busaddr, 0);
/* initially, the dma buffer is owned by the CPU */
rd->skb = NULL;
}
return r;
}
static int vlsi_free_ring(struct vlsi_ring *r)
{
struct ring_descr *rd;
unsigned i;
dma_addr_t busaddr;
for (i = 0; i < r->size; i++) {
rd = r->rd + i;
if (rd->skb)
dev_kfree_skb_any(rd->skb);
busaddr = rd_get_addr(rd);
rd_set_addr_status(rd, 0, 0);
if (busaddr)
pci_unmap_single(r->pdev, busaddr, r->len, r->dir);
kfree(rd->buf);
}
kfree(r);
return 0;
}
static int vlsi_create_hwif(vlsi_irda_dev_t *idev)
{
char *ringarea;
struct ring_descr_hw *hwmap;
idev->virtaddr = NULL;
idev->busaddr = 0;
ringarea = pci_alloc_consistent(idev->pdev, HW_RING_AREA_SIZE, &idev->busaddr);
if (!ringarea) {
IRDA_ERROR("%s: insufficient memory for descriptor rings\n",
__func__);
goto out;
}
memset(ringarea, 0, HW_RING_AREA_SIZE);
hwmap = (struct ring_descr_hw *)ringarea;
idev->rx_ring = vlsi_alloc_ring(idev->pdev, hwmap, ringsize[1],
XFER_BUF_SIZE, PCI_DMA_FROMDEVICE);
if (idev->rx_ring == NULL)
goto out_unmap;
hwmap += MAX_RING_DESCR;
idev->tx_ring = vlsi_alloc_ring(idev->pdev, hwmap, ringsize[0],
XFER_BUF_SIZE, PCI_DMA_TODEVICE);
if (idev->tx_ring == NULL)
goto out_free_rx;
idev->virtaddr = ringarea;
return 0;
out_free_rx:
vlsi_free_ring(idev->rx_ring);
out_unmap:
idev->rx_ring = idev->tx_ring = NULL;
pci_free_consistent(idev->pdev, HW_RING_AREA_SIZE, ringarea, idev->busaddr);
idev->busaddr = 0;
out:
return -ENOMEM;
}
static int vlsi_destroy_hwif(vlsi_irda_dev_t *idev)
{
vlsi_free_ring(idev->rx_ring);
vlsi_free_ring(idev->tx_ring);
idev->rx_ring = idev->tx_ring = NULL;
if (idev->busaddr)
pci_free_consistent(idev->pdev,HW_RING_AREA_SIZE,idev->virtaddr,idev->busaddr);
idev->virtaddr = NULL;
idev->busaddr = 0;
return 0;
}
/********************************************************/
static int vlsi_process_rx(struct vlsi_ring *r, struct ring_descr *rd)
{
u16 status;
int crclen, len = 0;
struct sk_buff *skb;
int ret = 0;
struct net_device *ndev = (struct net_device *)pci_get_drvdata(r->pdev);
vlsi_irda_dev_t *idev = netdev_priv(ndev);
pci_dma_sync_single_for_cpu(r->pdev, rd_get_addr(rd), r->len, r->dir);
/* dma buffer now owned by the CPU */
status = rd_get_status(rd);
if (status & RD_RX_ERROR) {
if (status & RD_RX_OVER)
ret |= VLSI_RX_OVER;
if (status & RD_RX_LENGTH)
ret |= VLSI_RX_LENGTH;
if (status & RD_RX_PHYERR)
ret |= VLSI_RX_FRAME;
if (status & RD_RX_CRCERR)
ret |= VLSI_RX_CRC;
goto done;
}
len = rd_get_count(rd);
crclen = (idev->mode==IFF_FIR) ? sizeof(u32) : sizeof(u16);
len -= crclen; /* remove trailing CRC */
if (len <= 0) {
IRDA_DEBUG(0, "%s: strange frame (len=%d)\n", __func__, len);
ret |= VLSI_RX_DROP;
goto done;
}
if (idev->mode == IFF_SIR) { /* hw checks CRC in MIR, FIR mode */
/* rd->buf is a streaming PCI_DMA_FROMDEVICE map. Doing the
* endian-adjustment there just in place will dirty a cache line
* which belongs to the map and thus we must be sure it will
* get flushed before giving the buffer back to hardware.
* vlsi_fill_rx() will do this anyway - but here we rely on.
*/
le16_to_cpus(rd->buf+len);
if (irda_calc_crc16(INIT_FCS,rd->buf,len+crclen) != GOOD_FCS) {
IRDA_DEBUG(0, "%s: crc error\n", __func__);
ret |= VLSI_RX_CRC;
goto done;
}
}
if (!rd->skb) {
IRDA_WARNING("%s: rx packet lost\n", __func__);
ret |= VLSI_RX_DROP;
goto done;
}
skb = rd->skb;
rd->skb = NULL;
skb->dev = ndev;
memcpy(skb_put(skb,len), rd->buf, len);
skb_reset_mac_header(skb);
if (in_interrupt())
netif_rx(skb);
else
netif_rx_ni(skb);
done:
rd_set_status(rd, 0);
rd_set_count(rd, 0);
/* buffer still owned by CPU */
return (ret) ? -ret : len;
}
static void vlsi_fill_rx(struct vlsi_ring *r)
{
struct ring_descr *rd;
for (rd = ring_last(r); rd != NULL; rd = ring_put(r)) {
if (rd_is_active(rd)) {
IRDA_WARNING("%s: driver bug: rx descr race with hw\n",
__func__);
vlsi_ring_debug(r);
break;
}
if (!rd->skb) {
rd->skb = dev_alloc_skb(IRLAP_SKB_ALLOCSIZE);
if (rd->skb) {
skb_reserve(rd->skb,1);
rd->skb->protocol = htons(ETH_P_IRDA);
}
else
break; /* probably not worth logging? */
}
/* give dma buffer back to busmaster */
pci_dma_sync_single_for_device(r->pdev, rd_get_addr(rd), r->len, r->dir);
rd_activate(rd);
}
}
static void vlsi_rx_interrupt(struct net_device *ndev)
{
vlsi_irda_dev_t *idev = netdev_priv(ndev);
struct vlsi_ring *r = idev->rx_ring;
struct ring_descr *rd;
int ret;
for (rd = ring_first(r); rd != NULL; rd = ring_get(r)) {
if (rd_is_active(rd))
break;
ret = vlsi_process_rx(r, rd);
if (ret < 0) {
ret = -ret;
ndev->stats.rx_errors++;
if (ret & VLSI_RX_DROP)
ndev->stats.rx_dropped++;
if (ret & VLSI_RX_OVER)
ndev->stats.rx_over_errors++;
if (ret & VLSI_RX_LENGTH)
ndev->stats.rx_length_errors++;
if (ret & VLSI_RX_FRAME)
ndev->stats.rx_frame_errors++;
if (ret & VLSI_RX_CRC)
ndev->stats.rx_crc_errors++;
}
else if (ret > 0) {
ndev->stats.rx_packets++;
ndev->stats.rx_bytes += ret;
}
}
do_gettimeofday(&idev->last_rx); /* remember "now" for later mtt delay */
vlsi_fill_rx(r);
if (ring_first(r) == NULL) {
/* we are in big trouble, if this should ever happen */
IRDA_ERROR("%s: rx ring exhausted!\n", __func__);
vlsi_ring_debug(r);
}
else
outw(0, ndev->base_addr+VLSI_PIO_PROMPT);
}
/* caller must have stopped the controller from busmastering */
static void vlsi_unarm_rx(vlsi_irda_dev_t *idev)
{
struct net_device *ndev = pci_get_drvdata(idev->pdev);
struct vlsi_ring *r = idev->rx_ring;
struct ring_descr *rd;
int ret;
for (rd = ring_first(r); rd != NULL; rd = ring_get(r)) {
ret = 0;
if (rd_is_active(rd)) {
rd_set_status(rd, 0);
if (rd_get_count(rd)) {
IRDA_DEBUG(0, "%s - dropping rx packet\n", __func__);
ret = -VLSI_RX_DROP;
}
rd_set_count(rd, 0);
pci_dma_sync_single_for_cpu(r->pdev, rd_get_addr(rd), r->len, r->dir);
if (rd->skb) {
dev_kfree_skb_any(rd->skb);
rd->skb = NULL;
}
}
else
ret = vlsi_process_rx(r, rd);
if (ret < 0) {
ret = -ret;
ndev->stats.rx_errors++;
if (ret & VLSI_RX_DROP)
ndev->stats.rx_dropped++;
if (ret & VLSI_RX_OVER)
ndev->stats.rx_over_errors++;
if (ret & VLSI_RX_LENGTH)
ndev->stats.rx_length_errors++;
if (ret & VLSI_RX_FRAME)
ndev->stats.rx_frame_errors++;
if (ret & VLSI_RX_CRC)
ndev->stats.rx_crc_errors++;
}
else if (ret > 0) {
ndev->stats.rx_packets++;
ndev->stats.rx_bytes += ret;
}
}
}
/********************************************************/
static int vlsi_process_tx(struct vlsi_ring *r, struct ring_descr *rd)
{
u16 status;
int len;
int ret;
pci_dma_sync_single_for_cpu(r->pdev, rd_get_addr(rd), r->len, r->dir);
/* dma buffer now owned by the CPU */
status = rd_get_status(rd);
if (status & RD_TX_UNDRN)
ret = VLSI_TX_FIFO;
else
ret = 0;
rd_set_status(rd, 0);
if (rd->skb) {
len = rd->skb->len;
dev_kfree_skb_any(rd->skb);
rd->skb = NULL;
}
else /* tx-skb already freed? - should never happen */
len = rd_get_count(rd); /* incorrect for SIR! (due to wrapping) */
rd_set_count(rd, 0);
/* dma buffer still owned by the CPU */
return (ret) ? -ret : len;
}
static int vlsi_set_baud(vlsi_irda_dev_t *idev, unsigned iobase)
{
u16 nphyctl;
u16 config;
unsigned mode;
int ret;
int baudrate;
int fifocnt;
baudrate = idev->new_baud;
IRDA_DEBUG(2, "%s: %d -> %d\n", __func__, idev->baud, idev->new_baud);
if (baudrate == 4000000) {
mode = IFF_FIR;
config = IRCFG_FIR;
nphyctl = PHYCTL_FIR;
}
else if (baudrate == 1152000) {
mode = IFF_MIR;
config = IRCFG_MIR | IRCFG_CRC16;
nphyctl = PHYCTL_MIR(clksrc==3);
}
else {
mode = IFF_SIR;
config = IRCFG_SIR | IRCFG_SIRFILT | IRCFG_RXANY;
switch(baudrate) {
default:
IRDA_WARNING("%s: undefined baudrate %d - fallback to 9600!\n",
__func__, baudrate);
baudrate = 9600;
/* fallthru */
case 2400:
case 9600:
case 19200:
case 38400:
case 57600:
case 115200:
nphyctl = PHYCTL_SIR(baudrate,sirpulse,clksrc==3);
break;
}
}
config |= IRCFG_MSTR | IRCFG_ENRX;
fifocnt = inw(iobase+VLSI_PIO_RCVBCNT) & RCVBCNT_MASK;
if (fifocnt != 0) {
IRDA_DEBUG(0, "%s: rx fifo not empty(%d)\n", __func__, fifocnt);
}
outw(0, iobase+VLSI_PIO_IRENABLE);
outw(config, iobase+VLSI_PIO_IRCFG);
outw(nphyctl, iobase+VLSI_PIO_NPHYCTL);
wmb();
outw(IRENABLE_PHYANDCLOCK, iobase+VLSI_PIO_IRENABLE);
mb();
udelay(1); /* chip applies IRCFG on next rising edge of its 8MHz clock */
/* read back settings for validation */
config = inw(iobase+VLSI_PIO_IRENABLE) & IRENABLE_MASK;
if (mode == IFF_FIR)
config ^= IRENABLE_FIR_ON;
else if (mode == IFF_MIR)
config ^= (IRENABLE_MIR_ON|IRENABLE_CRC16_ON);
else
config ^= IRENABLE_SIR_ON;
if (config != (IRENABLE_PHYANDCLOCK|IRENABLE_ENRXST)) {
IRDA_WARNING("%s: failed to set %s mode!\n", __func__,
(mode==IFF_SIR)?"SIR":((mode==IFF_MIR)?"MIR":"FIR"));
ret = -1;
}
else {
if (inw(iobase+VLSI_PIO_PHYCTL) != nphyctl) {
IRDA_WARNING("%s: failed to apply baudrate %d\n",
__func__, baudrate);
ret = -1;
}
else {
idev->mode = mode;
idev->baud = baudrate;
idev->new_baud = 0;
ret = 0;
}
}
if (ret)
vlsi_reg_debug(iobase,__func__);
return ret;
}
static netdev_tx_t vlsi_hard_start_xmit(struct sk_buff *skb,
struct net_device *ndev)
{
vlsi_irda_dev_t *idev = netdev_priv(ndev);
struct vlsi_ring *r = idev->tx_ring;
struct ring_descr *rd;
unsigned long flags;
unsigned iobase = ndev->base_addr;
u8 status;
u16 config;
int mtt;
int len, speed;
struct timeval now, ready;
char *msg = NULL;
speed = irda_get_next_speed(skb);
spin_lock_irqsave(&idev->lock, flags);
if (speed != -1 && speed != idev->baud) {
netif_stop_queue(ndev);
idev->new_baud = speed;
status = RD_TX_CLRENTX; /* stop tx-ring after this frame */
}
else
status = 0;
if (skb->len == 0) {
/* handle zero packets - should be speed change */
if (status == 0) {
msg = "bogus zero-length packet";
goto drop_unlock;
}
/* due to the completely asynch tx operation we might have
* IrLAP racing with the hardware here, f.e. if the controller
* is just sending the last packet with current speed while
* the LAP is already switching the speed using synchronous
* len=0 packet. Immediate execution would lead to hw lockup
* requiring a powercycle to reset. Good candidate to trigger
* this is the final UA:RSP packet after receiving a DISC:CMD
* when getting the LAP down.
* Note that we are not protected by the queue_stop approach
* because the final UA:RSP arrives _without_ request to apply
* new-speed-after-this-packet - hence the driver doesn't know
* this was the last packet and doesn't stop the queue. So the
* forced switch to default speed from LAP gets through as fast
* as only some 10 usec later while the UA:RSP is still processed
* by the hardware and we would get screwed.
*/
if (ring_first(idev->tx_ring) == NULL) {
/* no race - tx-ring already empty */
vlsi_set_baud(idev, iobase);
netif_wake_queue(ndev);
}
else
;
/* keep the speed change pending like it would
* for any len>0 packet. tx completion interrupt
* will apply it when the tx ring becomes empty.
*/
spin_unlock_irqrestore(&idev->lock, flags);
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
/* sanity checks - simply drop the packet */
rd = ring_last(r);
if (!rd) {
msg = "ring full, but queue wasn't stopped";
goto drop_unlock;
}
if (rd_is_active(rd)) {
msg = "entry still owned by hw";
goto drop_unlock;
}
if (!rd->buf) {
msg = "tx ring entry without pci buffer";
goto drop_unlock;
}
if (rd->skb) {
msg = "ring entry with old skb still attached";
goto drop_unlock;
}
/* no need for serialization or interrupt disable during mtt */
spin_unlock_irqrestore(&idev->lock, flags);
if ((mtt = irda_get_mtt(skb)) > 0) {
ready.tv_usec = idev->last_rx.tv_usec + mtt;
ready.tv_sec = idev->last_rx.tv_sec;
if (ready.tv_usec >= 1000000) {
ready.tv_usec -= 1000000;
ready.tv_sec++; /* IrLAP 1.1: mtt always < 1 sec */
}
for(;;) {
do_gettimeofday(&now);
if (now.tv_sec > ready.tv_sec ||
(now.tv_sec==ready.tv_sec && now.tv_usec>=ready.tv_usec))
break;
udelay(100);
/* must not sleep here - called under netif_tx_lock! */
}
}
/* tx buffer already owned by CPU due to pci_dma_sync_single_for_cpu()
* after subsequent tx-completion
*/
if (idev->mode == IFF_SIR) {
status |= RD_TX_DISCRC; /* no hw-crc creation */
len = async_wrap_skb(skb, rd->buf, r->len);
/* Some rare worst case situation in SIR mode might lead to
* potential buffer overflow. The wrapper detects this, returns
* with a shortened frame (without FCS/EOF) but doesn't provide
* any error indication about the invalid packet which we are
* going to transmit.
* Therefore we log if the buffer got filled to the point, where the
* wrapper would abort, i.e. when there are less than 5 bytes left to
* allow appending the FCS/EOF.
*/
if (len >= r->len-5)
IRDA_WARNING("%s: possible buffer overflow with SIR wrapping!\n",
__func__);
}
else {
/* hw deals with MIR/FIR mode wrapping */
status |= RD_TX_PULSE; /* send 2 us highspeed indication pulse */
len = skb->len;
if (len > r->len) {
msg = "frame exceeds tx buffer length";
goto drop;
}
else
skb_copy_from_linear_data(skb, rd->buf, len);
}
rd->skb = skb; /* remember skb for tx-complete stats */
rd_set_count(rd, len);
rd_set_status(rd, status); /* not yet active! */
/* give dma buffer back to busmaster-hw (flush caches to make
* CPU-driven changes visible from the pci bus).
*/
pci_dma_sync_single_for_device(r->pdev, rd_get_addr(rd), r->len, r->dir);
/* Switching to TX mode here races with the controller
* which may stop TX at any time when fetching an inactive descriptor
* or one with CLR_ENTX set. So we switch on TX only, if TX was not running
* _after_ the new descriptor was activated on the ring. This ensures
* we will either find TX already stopped or we can be sure, there
* will be a TX-complete interrupt even if the chip stopped doing
* TX just after we found it still running. The ISR will then find
* the non-empty ring and restart TX processing. The enclosing
* spinlock provides the correct serialization to prevent race with isr.
*/
spin_lock_irqsave(&idev->lock,flags);
rd_activate(rd);
if (!(inw(iobase+VLSI_PIO_IRENABLE) & IRENABLE_ENTXST)) {
int fifocnt;
fifocnt = inw(ndev->base_addr+VLSI_PIO_RCVBCNT) & RCVBCNT_MASK;
if (fifocnt != 0) {
IRDA_DEBUG(0, "%s: rx fifo not empty(%d)\n", __func__, fifocnt);
}
config = inw(iobase+VLSI_PIO_IRCFG);
mb();
outw(config | IRCFG_ENTX, iobase+VLSI_PIO_IRCFG);
wmb();
outw(0, iobase+VLSI_PIO_PROMPT);
}
if (ring_put(r) == NULL) {
netif_stop_queue(ndev);
IRDA_DEBUG(3, "%s: tx ring full - queue stopped\n", __func__);
}
spin_unlock_irqrestore(&idev->lock, flags);
return NETDEV_TX_OK;
drop_unlock:
spin_unlock_irqrestore(&idev->lock, flags);
drop:
IRDA_WARNING("%s: dropping packet - %s\n", __func__, msg);
dev_kfree_skb_any(skb);
ndev->stats.tx_errors++;
ndev->stats.tx_dropped++;
/* Don't even think about returning NET_XMIT_DROP (=1) here!
* In fact any retval!=0 causes the packet scheduler to requeue the
* packet for later retry of transmission - which isn't exactly
* what we want after we've just called dev_kfree_skb_any ;-)
*/
return NETDEV_TX_OK;
}
static void vlsi_tx_interrupt(struct net_device *ndev)
{
vlsi_irda_dev_t *idev = netdev_priv(ndev);
struct vlsi_ring *r = idev->tx_ring;
struct ring_descr *rd;
unsigned iobase;
int ret;
u16 config;
for (rd = ring_first(r); rd != NULL; rd = ring_get(r)) {
if (rd_is_active(rd))
break;
ret = vlsi_process_tx(r, rd);
if (ret < 0) {
ret = -ret;
ndev->stats.tx_errors++;
if (ret & VLSI_TX_DROP)
ndev->stats.tx_dropped++;
if (ret & VLSI_TX_FIFO)
ndev->stats.tx_fifo_errors++;
}
else if (ret > 0){
ndev->stats.tx_packets++;
ndev->stats.tx_bytes += ret;
}
}
iobase = ndev->base_addr;
if (idev->new_baud && rd == NULL) /* tx ring empty and speed change pending */
vlsi_set_baud(idev, iobase);
config = inw(iobase+VLSI_PIO_IRCFG);
if (rd == NULL) /* tx ring empty: re-enable rx */
outw((config & ~IRCFG_ENTX) | IRCFG_ENRX, iobase+VLSI_PIO_IRCFG);
else if (!(inw(iobase+VLSI_PIO_IRENABLE) & IRENABLE_ENTXST)) {
int fifocnt;
fifocnt = inw(iobase+VLSI_PIO_RCVBCNT) & RCVBCNT_MASK;
if (fifocnt != 0) {
IRDA_DEBUG(0, "%s: rx fifo not empty(%d)\n",
__func__, fifocnt);
}
outw(config | IRCFG_ENTX, iobase+VLSI_PIO_IRCFG);
}
outw(0, iobase+VLSI_PIO_PROMPT);
if (netif_queue_stopped(ndev) && !idev->new_baud) {
netif_wake_queue(ndev);
IRDA_DEBUG(3, "%s: queue awoken\n", __func__);
}
}
/* caller must have stopped the controller from busmastering */
static void vlsi_unarm_tx(vlsi_irda_dev_t *idev)
{
struct net_device *ndev = pci_get_drvdata(idev->pdev);
struct vlsi_ring *r = idev->tx_ring;
struct ring_descr *rd;
int ret;
for (rd = ring_first(r); rd != NULL; rd = ring_get(r)) {
ret = 0;
if (rd_is_active(rd)) {
rd_set_status(rd, 0);
rd_set_count(rd, 0);
pci_dma_sync_single_for_cpu(r->pdev, rd_get_addr(rd), r->len, r->dir);
if (rd->skb) {
dev_kfree_skb_any(rd->skb);
rd->skb = NULL;
}
IRDA_DEBUG(0, "%s - dropping tx packet\n", __func__);
ret = -VLSI_TX_DROP;
}
else
ret = vlsi_process_tx(r, rd);
if (ret < 0) {
ret = -ret;
ndev->stats.tx_errors++;
if (ret & VLSI_TX_DROP)
ndev->stats.tx_dropped++;
if (ret & VLSI_TX_FIFO)
ndev->stats.tx_fifo_errors++;
}
else if (ret > 0){
ndev->stats.tx_packets++;
ndev->stats.tx_bytes += ret;
}
}
}
/********************************************************/
static int vlsi_start_clock(struct pci_dev *pdev)
{
u8 clkctl, lock;
int i, count;
if (clksrc < 2) { /* auto or PLL: try PLL */
clkctl = CLKCTL_PD_INV | CLKCTL_CLKSTP;
pci_write_config_byte(pdev, VLSI_PCI_CLKCTL, clkctl);
/* procedure to detect PLL lock synchronisation:
* after 0.5 msec initial delay we expect to find 3 PLL lock
* indications within 10 msec for successful PLL detection.
*/
udelay(500);
count = 0;
for (i = 500; i <= 10000; i += 50) { /* max 10 msec */
pci_read_config_byte(pdev, VLSI_PCI_CLKCTL, &lock);
if (lock&CLKCTL_LOCK) {
if (++count >= 3)
break;
}
udelay(50);
}
if (count < 3) {
if (clksrc == 1) { /* explicitly asked for PLL hence bail out */
IRDA_ERROR("%s: no PLL or failed to lock!\n",
__func__);
clkctl = CLKCTL_CLKSTP;
pci_write_config_byte(pdev, VLSI_PCI_CLKCTL, clkctl);
return -1;
}
else /* was: clksrc=0(auto) */
clksrc = 3; /* fallback to 40MHz XCLK (OB800) */
IRDA_DEBUG(0, "%s: PLL not locked, fallback to clksrc=%d\n",
__func__, clksrc);
}
else
clksrc = 1; /* got successful PLL lock */
}
if (clksrc != 1) {
/* we get here if either no PLL detected in auto-mode or
an external clock source was explicitly specified */
clkctl = CLKCTL_EXTCLK | CLKCTL_CLKSTP;
if (clksrc == 3)
clkctl |= CLKCTL_XCKSEL;
pci_write_config_byte(pdev, VLSI_PCI_CLKCTL, clkctl);
/* no way to test for working XCLK */
}
else
pci_read_config_byte(pdev, VLSI_PCI_CLKCTL, &clkctl);
/* ok, now going to connect the chip with the clock source */
clkctl &= ~CLKCTL_CLKSTP;
pci_write_config_byte(pdev, VLSI_PCI_CLKCTL, clkctl);
return 0;
}
static void vlsi_stop_clock(struct pci_dev *pdev)
{
u8 clkctl;
/* disconnect chip from clock source */
pci_read_config_byte(pdev, VLSI_PCI_CLKCTL, &clkctl);
clkctl |= CLKCTL_CLKSTP;
pci_write_config_byte(pdev, VLSI_PCI_CLKCTL, clkctl);
/* disable all clock sources */
clkctl &= ~(CLKCTL_EXTCLK | CLKCTL_PD_INV);
pci_write_config_byte(pdev, VLSI_PCI_CLKCTL, clkctl);
}
/********************************************************/
/* writing all-zero to the VLSI PCI IO register area seems to prevent
* some occasional situations where the hardware fails (symptoms are
* what appears as stalled tx/rx state machines, i.e. everything ok for
* receive or transmit but hw makes no progress or is unable to access
* the bus memory locations).
* Best place to call this is immediately after/before the internal clock
* gets started/stopped.
*/
static inline void vlsi_clear_regs(unsigned iobase)
{
unsigned i;
const unsigned chip_io_extent = 32;
for (i = 0; i < chip_io_extent; i += sizeof(u16))
outw(0, iobase + i);
}
static int vlsi_init_chip(struct pci_dev *pdev)
{
struct net_device *ndev = pci_get_drvdata(pdev);
vlsi_irda_dev_t *idev = netdev_priv(ndev);
unsigned iobase;
u16 ptr;
/* start the clock and clean the registers */
if (vlsi_start_clock(pdev)) {
IRDA_ERROR("%s: no valid clock source\n", __func__);
return -1;
}
iobase = ndev->base_addr;
vlsi_clear_regs(iobase);
outb(IRINTR_INT_MASK, iobase+VLSI_PIO_IRINTR); /* w/c pending IRQ, disable all INT */
outw(0, iobase+VLSI_PIO_IRENABLE); /* disable IrPHY-interface */
/* disable everything, particularly IRCFG_MSTR - (also resetting the RING_PTR) */
outw(0, iobase+VLSI_PIO_IRCFG);
wmb();
outw(MAX_PACKET_LENGTH, iobase+VLSI_PIO_MAXPKT); /* max possible value=0x0fff */
outw(BUS_TO_RINGBASE(idev->busaddr), iobase+VLSI_PIO_RINGBASE);
outw(TX_RX_TO_RINGSIZE(idev->tx_ring->size, idev->rx_ring->size),
iobase+VLSI_PIO_RINGSIZE);
ptr = inw(iobase+VLSI_PIO_RINGPTR);
atomic_set(&idev->rx_ring->head, RINGPTR_GET_RX(ptr));
atomic_set(&idev->rx_ring->tail, RINGPTR_GET_RX(ptr));
atomic_set(&idev->tx_ring->head, RINGPTR_GET_TX(ptr));
atomic_set(&idev->tx_ring->tail, RINGPTR_GET_TX(ptr));
vlsi_set_baud(idev, iobase); /* idev->new_baud used as provided by caller */
outb(IRINTR_INT_MASK, iobase+VLSI_PIO_IRINTR); /* just in case - w/c pending IRQ's */
wmb();
/* DO NOT BLINDLY ENABLE IRINTR_ACTEN!
* basically every received pulse fires an ACTIVITY-INT
* leading to >>1000 INT's per second instead of few 10
*/
outb(IRINTR_RPKTEN|IRINTR_TPKTEN, iobase+VLSI_PIO_IRINTR);
return 0;
}
static int vlsi_start_hw(vlsi_irda_dev_t *idev)
{
struct pci_dev *pdev = idev->pdev;
struct net_device *ndev = pci_get_drvdata(pdev);
unsigned iobase = ndev->base_addr;
u8 byte;
/* we don't use the legacy UART, disable its address decoding */
pci_read_config_byte(pdev, VLSI_PCI_IRMISC, &byte);
byte &= ~(IRMISC_UARTEN | IRMISC_UARTTST);
pci_write_config_byte(pdev, VLSI_PCI_IRMISC, byte);
/* enable PCI busmaster access to our 16MB page */
pci_write_config_byte(pdev, VLSI_PCI_MSTRPAGE, MSTRPAGE_VALUE);
pci_set_master(pdev);
if (vlsi_init_chip(pdev) < 0) {
pci_disable_device(pdev);
return -1;
}
vlsi_fill_rx(idev->rx_ring);
do_gettimeofday(&idev->last_rx); /* first mtt may start from now on */
outw(0, iobase+VLSI_PIO_PROMPT); /* kick hw state machine */
return 0;
}
static int vlsi_stop_hw(vlsi_irda_dev_t *idev)
{
struct pci_dev *pdev = idev->pdev;
struct net_device *ndev = pci_get_drvdata(pdev);
unsigned iobase = ndev->base_addr;
unsigned long flags;
spin_lock_irqsave(&idev->lock,flags);
outw(0, iobase+VLSI_PIO_IRENABLE);
outw(0, iobase+VLSI_PIO_IRCFG); /* disable everything */
/* disable and w/c irqs */
outb(0, iobase+VLSI_PIO_IRINTR);
wmb();
outb(IRINTR_INT_MASK, iobase+VLSI_PIO_IRINTR);
spin_unlock_irqrestore(&idev->lock,flags);
vlsi_unarm_tx(idev);
vlsi_unarm_rx(idev);
vlsi_clear_regs(iobase);
vlsi_stop_clock(pdev);
pci_disable_device(pdev);
return 0;
}
/**************************************************************/
static void vlsi_tx_timeout(struct net_device *ndev)
{
vlsi_irda_dev_t *idev = netdev_priv(ndev);
vlsi_reg_debug(ndev->base_addr, __func__);
vlsi_ring_debug(idev->tx_ring);
if (netif_running(ndev))
netif_stop_queue(ndev);
vlsi_stop_hw(idev);
/* now simply restart the whole thing */
if (!idev->new_baud)
idev->new_baud = idev->baud; /* keep current baudrate */
if (vlsi_start_hw(idev))
IRDA_ERROR("%s: failed to restart hw - %s(%s) unusable!\n",
__func__, pci_name(idev->pdev), ndev->name);
else
netif_start_queue(ndev);
}
static int vlsi_ioctl(struct net_device *ndev, struct ifreq *rq, int cmd)
{
vlsi_irda_dev_t *idev = netdev_priv(ndev);
struct if_irda_req *irq = (struct if_irda_req *) rq;
unsigned long flags;
u16 fifocnt;
int ret = 0;
switch (cmd) {
case SIOCSBANDWIDTH:
if (!capable(CAP_NET_ADMIN)) {
ret = -EPERM;
break;
}
spin_lock_irqsave(&idev->lock, flags);
idev->new_baud = irq->ifr_baudrate;
/* when called from userland there might be a minor race window here
* if the stack tries to change speed concurrently - which would be
* pretty strange anyway with the userland having full control...
*/
vlsi_set_baud(idev, ndev->base_addr);
spin_unlock_irqrestore(&idev->lock, flags);
break;
case SIOCSMEDIABUSY:
if (!capable(CAP_NET_ADMIN)) {
ret = -EPERM;
break;
}
irda_device_set_media_busy(ndev, TRUE);
break;
case SIOCGRECEIVING:
/* the best we can do: check whether there are any bytes in rx fifo.
* The trustable window (in case some data arrives just afterwards)
* may be as short as 1usec or so at 4Mbps.
*/
fifocnt = inw(ndev->base_addr+VLSI_PIO_RCVBCNT) & RCVBCNT_MASK;
irq->ifr_receiving = (fifocnt!=0) ? 1 : 0;
break;
default:
IRDA_WARNING("%s: notsupp - cmd=%04x\n",
__func__, cmd);
ret = -EOPNOTSUPP;
}
return ret;
}
/********************************************************/
static irqreturn_t vlsi_interrupt(int irq, void *dev_instance)
{
struct net_device *ndev = dev_instance;
vlsi_irda_dev_t *idev = netdev_priv(ndev);
unsigned iobase;
u8 irintr;
int boguscount = 5;
unsigned long flags;
int handled = 0;
iobase = ndev->base_addr;
spin_lock_irqsave(&idev->lock,flags);
do {
irintr = inb(iobase+VLSI_PIO_IRINTR);
mb();
outb(irintr, iobase+VLSI_PIO_IRINTR); /* acknowledge asap */
if (!(irintr&=IRINTR_INT_MASK)) /* not our INT - probably shared */
break;
handled = 1;
if (unlikely(!(irintr & ~IRINTR_ACTIVITY)))
break; /* nothing todo if only activity */
if (irintr&IRINTR_RPKTINT)
vlsi_rx_interrupt(ndev);
if (irintr&IRINTR_TPKTINT)
vlsi_tx_interrupt(ndev);
} while (--boguscount > 0);
spin_unlock_irqrestore(&idev->lock,flags);
if (boguscount <= 0)
IRDA_MESSAGE("%s: too much work in interrupt!\n",
__func__);
return IRQ_RETVAL(handled);
}
/********************************************************/
static int vlsi_open(struct net_device *ndev)
{
vlsi_irda_dev_t *idev = netdev_priv(ndev);
int err = -EAGAIN;
char hwname[32];
if (pci_request_regions(idev->pdev, drivername)) {
IRDA_WARNING("%s: io resource busy\n", __func__);
goto errout;
}
ndev->base_addr = pci_resource_start(idev->pdev,0);
ndev->irq = idev->pdev->irq;
/* under some rare occasions the chip apparently comes up with
* IRQ's pending. We better w/c pending IRQ and disable them all
*/
outb(IRINTR_INT_MASK, ndev->base_addr+VLSI_PIO_IRINTR);
if (request_irq(ndev->irq, vlsi_interrupt, IRQF_SHARED,
drivername, ndev)) {
IRDA_WARNING("%s: couldn't get IRQ: %d\n",
__func__, ndev->irq);
goto errout_io;
}
if ((err = vlsi_create_hwif(idev)) != 0)
goto errout_irq;
sprintf(hwname, "VLSI-FIR @ 0x%04x", (unsigned)ndev->base_addr);
idev->irlap = irlap_open(ndev,&idev->qos,hwname);
if (!idev->irlap)
goto errout_free_ring;
do_gettimeofday(&idev->last_rx); /* first mtt may start from now on */
idev->new_baud = 9600; /* start with IrPHY using 9600(SIR) mode */
if ((err = vlsi_start_hw(idev)) != 0)
goto errout_close_irlap;
netif_start_queue(ndev);
IRDA_MESSAGE("%s: device %s operational\n", __func__, ndev->name);
return 0;
errout_close_irlap:
irlap_close(idev->irlap);
errout_free_ring:
vlsi_destroy_hwif(idev);
errout_irq:
free_irq(ndev->irq,ndev);
errout_io:
pci_release_regions(idev->pdev);
errout:
return err;
}
static int vlsi_close(struct net_device *ndev)
{
vlsi_irda_dev_t *idev = netdev_priv(ndev);
netif_stop_queue(ndev);
if (idev->irlap)
irlap_close(idev->irlap);
idev->irlap = NULL;
vlsi_stop_hw(idev);
vlsi_destroy_hwif(idev);
free_irq(ndev->irq,ndev);
pci_release_regions(idev->pdev);
IRDA_MESSAGE("%s: device %s stopped\n", __func__, ndev->name);
return 0;
}
static const struct net_device_ops vlsi_netdev_ops = {
.ndo_open = vlsi_open,
.ndo_stop = vlsi_close,
.ndo_start_xmit = vlsi_hard_start_xmit,
.ndo_do_ioctl = vlsi_ioctl,
.ndo_tx_timeout = vlsi_tx_timeout,
};
static int vlsi_irda_init(struct net_device *ndev)
{
vlsi_irda_dev_t *idev = netdev_priv(ndev);
struct pci_dev *pdev = idev->pdev;
ndev->irq = pdev->irq;
ndev->base_addr = pci_resource_start(pdev,0);
/* PCI busmastering
* see include file for details why we need these 2 masks, in this order!
*/
if (pci_set_dma_mask(pdev,DMA_MASK_USED_BY_HW) ||
pci_set_dma_mask(pdev,DMA_MASK_MSTRPAGE)) {
IRDA_ERROR("%s: aborting due to PCI BM-DMA address limitations\n", __func__);
return -1;
}
irda_init_max_qos_capabilies(&idev->qos);
/* the VLSI82C147 does not support 576000! */
idev->qos.baud_rate.bits = IR_2400 | IR_9600
| IR_19200 | IR_38400 | IR_57600 | IR_115200
| IR_1152000 | (IR_4000000 << 8);
idev->qos.min_turn_time.bits = qos_mtt_bits;
irda_qos_bits_to_value(&idev->qos);
/* currently no public media definitions for IrDA */
ndev->flags |= IFF_PORTSEL | IFF_AUTOMEDIA;
ndev->if_port = IF_PORT_UNKNOWN;
ndev->netdev_ops = &vlsi_netdev_ops;
ndev->watchdog_timeo = 500*HZ/1000; /* max. allowed turn time for IrLAP */
SET_NETDEV_DEV(ndev, &pdev->dev);
return 0;
}
/**************************************************************/
static int
vlsi_irda_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{
struct net_device *ndev;
vlsi_irda_dev_t *idev;
if (pci_enable_device(pdev))
goto out;
else
pdev->current_state = 0; /* hw must be running now */
IRDA_MESSAGE("%s: IrDA PCI controller %s detected\n",
drivername, pci_name(pdev));
if ( !pci_resource_start(pdev,0) ||
!(pci_resource_flags(pdev,0) & IORESOURCE_IO) ) {
IRDA_ERROR("%s: bar 0 invalid", __func__);
goto out_disable;
}
ndev = alloc_irdadev(sizeof(*idev));
if (ndev==NULL) {
IRDA_ERROR("%s: Unable to allocate device memory.\n",
__func__);
goto out_disable;
}
idev = netdev_priv(ndev);
spin_lock_init(&idev->lock);
mutex_init(&idev->mtx);
mutex_lock(&idev->mtx);
idev->pdev = pdev;
if (vlsi_irda_init(ndev) < 0)
goto out_freedev;
if (register_netdev(ndev) < 0) {
IRDA_ERROR("%s: register_netdev failed\n", __func__);
goto out_freedev;
}
if (vlsi_proc_root != NULL) {
struct proc_dir_entry *ent;
ent = proc_create_data(ndev->name, S_IFREG|S_IRUGO,
vlsi_proc_root, VLSI_PROC_FOPS, ndev);
if (!ent) {
IRDA_WARNING("%s: failed to create proc entry\n",
__func__);
} else {
proc_set_size(ent, 0);
}
idev->proc_entry = ent;
}
IRDA_MESSAGE("%s: registered device %s\n", drivername, ndev->name);
pci_set_drvdata(pdev, ndev);
mutex_unlock(&idev->mtx);
return 0;
out_freedev:
mutex_unlock(&idev->mtx);
free_netdev(ndev);
out_disable:
pci_disable_device(pdev);
out:
pci_set_drvdata(pdev, NULL);
return -ENODEV;
}
static void vlsi_irda_remove(struct pci_dev *pdev)
{
struct net_device *ndev = pci_get_drvdata(pdev);
vlsi_irda_dev_t *idev;
if (!ndev) {
IRDA_ERROR("%s: lost netdevice?\n", drivername);
return;
}
unregister_netdev(ndev);
idev = netdev_priv(ndev);
mutex_lock(&idev->mtx);
if (idev->proc_entry) {
remove_proc_entry(ndev->name, vlsi_proc_root);
idev->proc_entry = NULL;
}
mutex_unlock(&idev->mtx);
free_netdev(ndev);
pci_set_drvdata(pdev, NULL);
IRDA_MESSAGE("%s: %s removed\n", drivername, pci_name(pdev));
}
#ifdef CONFIG_PM
/* The Controller doesn't provide PCI PM capabilities as defined by PCI specs.
* Some of the Linux PCI-PM code however depends on this, for example in
* pci_set_power_state(). So we have to take care to perform the required
* operations on our own (particularly reflecting the pdev->current_state)
* otherwise we might get cheated by pci-pm.
*/
static int vlsi_irda_suspend(struct pci_dev *pdev, pm_message_t state)
{
struct net_device *ndev = pci_get_drvdata(pdev);
vlsi_irda_dev_t *idev;
if (!ndev) {
IRDA_ERROR("%s - %s: no netdevice\n",
__func__, pci_name(pdev));
return 0;
}
idev = netdev_priv(ndev);
mutex_lock(&idev->mtx);
if (pdev->current_state != 0) { /* already suspended */
if (state.event > pdev->current_state) { /* simply go deeper */
pci_set_power_state(pdev, pci_choose_state(pdev, state));
pdev->current_state = state.event;
}
else
IRDA_ERROR("%s - %s: invalid suspend request %u -> %u\n", __func__, pci_name(pdev), pdev->current_state, state.event);
mutex_unlock(&idev->mtx);
return 0;
}
if (netif_running(ndev)) {
netif_device_detach(ndev);
vlsi_stop_hw(idev);
pci_save_state(pdev);
if (!idev->new_baud)
/* remember speed settings to restore on resume */
idev->new_baud = idev->baud;
}
pci_set_power_state(pdev, pci_choose_state(pdev, state));
pdev->current_state = state.event;
idev->resume_ok = 1;
mutex_unlock(&idev->mtx);
return 0;
}
static int vlsi_irda_resume(struct pci_dev *pdev)
{
struct net_device *ndev = pci_get_drvdata(pdev);
vlsi_irda_dev_t *idev;
if (!ndev) {
IRDA_ERROR("%s - %s: no netdevice\n",
__func__, pci_name(pdev));
return 0;
}
idev = netdev_priv(ndev);
mutex_lock(&idev->mtx);
if (pdev->current_state == 0) {
mutex_unlock(&idev->mtx);
IRDA_WARNING("%s - %s: already resumed\n",
__func__, pci_name(pdev));
return 0;
}
pci_set_power_state(pdev, PCI_D0);
pdev->current_state = PM_EVENT_ON;
if (!idev->resume_ok) {
/* should be obsolete now - but used to happen due to:
* - pci layer initially setting pdev->current_state = 4 (unknown)
* - pci layer did not walk the save_state-tree (might be APM problem)
* so we could not refuse to suspend from undefined state
* - vlsi_irda_suspend detected invalid state and refused to save
* configuration for resume - but was too late to stop suspending
* - vlsi_irda_resume got screwed when trying to resume from garbage
*
* now we explicitly set pdev->current_state = 0 after enabling the
* device and independently resume_ok should catch any garbage config.
*/
IRDA_WARNING("%s - hm, nothing to resume?\n", __func__);
mutex_unlock(&idev->mtx);
return 0;
}
if (netif_running(ndev)) {
pci_restore_state(pdev);
vlsi_start_hw(idev);
netif_device_attach(ndev);
}
idev->resume_ok = 0;
mutex_unlock(&idev->mtx);
return 0;
}
#endif /* CONFIG_PM */
/*********************************************************/
static struct pci_driver vlsi_irda_driver = {
.name = drivername,
.id_table = vlsi_irda_table,
.probe = vlsi_irda_probe,
.remove = vlsi_irda_remove,
#ifdef CONFIG_PM
.suspend = vlsi_irda_suspend,
.resume = vlsi_irda_resume,
#endif
};
#define PROC_DIR ("driver/" DRIVER_NAME)
static int __init vlsi_mod_init(void)
{
int i, ret;
if (clksrc < 0 || clksrc > 3) {
IRDA_ERROR("%s: invalid clksrc=%d\n", drivername, clksrc);
return -1;
}
for (i = 0; i < 2; i++) {
switch(ringsize[i]) {
case 4:
case 8:
case 16:
case 32:
case 64:
break;
default:
IRDA_WARNING("%s: invalid %s ringsize %d, using default=8", drivername, (i)?"rx":"tx", ringsize[i]);
ringsize[i] = 8;
break;
}
}
sirpulse = !!sirpulse;
/* proc_mkdir returns NULL if !CONFIG_PROC_FS.
* Failure to create the procfs entry is handled like running
* without procfs - it's not required for the driver to work.
*/
vlsi_proc_root = proc_mkdir(PROC_DIR, NULL);
ret = pci_register_driver(&vlsi_irda_driver);
if (ret && vlsi_proc_root)
remove_proc_entry(PROC_DIR, NULL);
return ret;
}
static void __exit vlsi_mod_exit(void)
{
pci_unregister_driver(&vlsi_irda_driver);
if (vlsi_proc_root)
remove_proc_entry(PROC_DIR, NULL);
}
module_init(vlsi_mod_init);
module_exit(vlsi_mod_exit);
| gpl-3.0 |
gahoo/shadowsocks-android | src/main/jni/badvpn/system/BReactor_glib.c | 368 | 13479 | /**
* @file BReactor_glib.c
* @author Ambroz Bizjak <ambrop7@gmail.com>
*
* @section LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the author 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 AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdlib.h>
#include <string.h>
#include <misc/offset.h>
#include <base/BLog.h>
#include "BReactor_glib.h"
#include <generated/blog_channel_BReactor.h>
struct fd_source {
GSource source;
BFileDescriptor *bfd;
};
static void assert_timer (BSmallTimer *bt)
{
ASSERT(bt->is_small == 0 || bt->is_small == 1)
ASSERT(bt->active == 0 || bt->active == 1)
ASSERT(!bt->active || bt->reactor)
ASSERT(!bt->active || bt->source)
}
static void dispatch_pending (BReactor *o)
{
while (!o->exiting && BPendingGroup_HasJobs(&o->pending_jobs)) {
BPendingGroup_ExecuteJob(&o->pending_jobs);
}
}
static void reset_limits (BReactor *o)
{
LinkedList1Node *list_node;
while (list_node = LinkedList1_GetFirst(&o->active_limits_list)) {
BReactorLimit *limit = UPPER_OBJECT(list_node, BReactorLimit, active_limits_list_node);
ASSERT(limit->count > 0)
limit->count = 0;
LinkedList1_Remove(&o->active_limits_list, &limit->active_limits_list_node);
}
}
static gushort get_glib_wait_events (int ev)
{
gushort gev = G_IO_ERR | G_IO_HUP;
if (ev & BREACTOR_READ) {
gev |= G_IO_IN;
}
if (ev & BREACTOR_WRITE) {
gev |= G_IO_OUT;
}
return gev;
}
static int get_fd_dispatchable_events (BFileDescriptor *bfd)
{
ASSERT(bfd->active)
int ev = 0;
if ((bfd->waitEvents & BREACTOR_READ) && (bfd->pollfd.revents & G_IO_IN)) {
ev |= BREACTOR_READ;
}
if ((bfd->waitEvents & BREACTOR_WRITE) && (bfd->pollfd.revents & G_IO_OUT)) {
ev |= BREACTOR_WRITE;
}
if ((bfd->pollfd.revents & G_IO_ERR)) {
ev |= BREACTOR_ERROR;
}
if ((bfd->pollfd.revents & G_IO_HUP)) {
ev |= BREACTOR_HUP;
}
return ev;
}
static gboolean timer_source_handler (gpointer data)
{
BSmallTimer *bt = (void *)data;
assert_timer(bt);
ASSERT(bt->active)
BReactor *reactor = bt->reactor;
if (reactor->exiting) {
return FALSE;
}
g_source_destroy(bt->source);
g_source_unref(bt->source);
bt->active = 0;
DebugCounter_Decrement(&reactor->d_timers_ctr);
if (bt->is_small) {
bt->handler.smalll(bt);
} else {
BTimer *btimer = UPPER_OBJECT(bt, BTimer, base);
bt->handler.heavy(btimer->user);
}
dispatch_pending(reactor);
reset_limits(reactor);
return FALSE;
}
static gboolean fd_source_func_prepare (GSource *source, gint *timeout)
{
BFileDescriptor *bfd = ((struct fd_source *)source)->bfd;
ASSERT(bfd->active)
ASSERT(bfd->source == source)
*timeout = -1;
return FALSE;
}
static gboolean fd_source_func_check (GSource *source)
{
BFileDescriptor *bfd = ((struct fd_source *)source)->bfd;
ASSERT(bfd->active)
ASSERT(bfd->source == source)
return (get_fd_dispatchable_events(bfd) ? TRUE : FALSE);
}
static gboolean fd_source_func_dispatch (GSource *source, GSourceFunc callback, gpointer user_data)
{
BFileDescriptor *bfd = ((struct fd_source *)source)->bfd;
BReactor *reactor = bfd->reactor;
ASSERT(bfd->active)
ASSERT(bfd->source == source)
if (reactor->exiting) {
return TRUE;
}
int events = get_fd_dispatchable_events(bfd);
if (!events) {
return TRUE;
}
bfd->handler(bfd->user, events);
dispatch_pending(reactor);
reset_limits(reactor);
return TRUE;
}
void BSmallTimer_Init (BSmallTimer *bt, BSmallTimer_handler handler)
{
bt->handler.smalll = handler;
bt->active = 0;
bt->is_small = 1;
}
int BSmallTimer_IsRunning (BSmallTimer *bt)
{
assert_timer(bt);
return bt->active;
}
void BTimer_Init (BTimer *bt, btime_t msTime, BTimer_handler handler, void *user)
{
bt->base.handler.heavy = handler;
bt->base.active = 0;
bt->base.is_small = 0;
bt->user = user;
bt->msTime = msTime;
}
int BTimer_IsRunning (BTimer *bt)
{
return BSmallTimer_IsRunning(&bt->base);
}
void BFileDescriptor_Init (BFileDescriptor *bs, int fd, BFileDescriptor_handler handler, void *user)
{
bs->fd = fd;
bs->handler = handler;
bs->user = user;
bs->active = 0;
}
int BReactor_Init (BReactor *bsys)
{
return BReactor_InitFromExistingGMainLoop(bsys, g_main_loop_new(NULL, FALSE), 1);
}
void BReactor_Free (BReactor *bsys)
{
DebugObject_Free(&bsys->d_obj);
DebugCounter_Free(&bsys->d_timers_ctr);
DebugCounter_Free(&bsys->d_limits_ctr);
DebugCounter_Free(&bsys->d_fds_counter);
ASSERT(!BPendingGroup_HasJobs(&bsys->pending_jobs))
ASSERT(LinkedList1_IsEmpty(&bsys->active_limits_list))
// free job queue
BPendingGroup_Free(&bsys->pending_jobs);
// unref main loop if needed
if (bsys->unref_gloop_on_free) {
g_main_loop_unref(bsys->gloop);
}
}
int BReactor_Exec (BReactor *bsys)
{
DebugObject_Access(&bsys->d_obj);
// dispatch pending jobs (until exiting) and reset limits
dispatch_pending(bsys);
reset_limits(bsys);
// if exiting, do not enter glib loop
if (bsys->exiting) {
return bsys->exit_code;
}
// enter glib loop
g_main_loop_run(bsys->gloop);
ASSERT(bsys->exiting)
return bsys->exit_code;
}
void BReactor_Quit (BReactor *bsys, int code)
{
DebugObject_Access(&bsys->d_obj);
// remember exiting
bsys->exiting = 1;
bsys->exit_code = code;
// request termination of glib loop
g_main_loop_quit(bsys->gloop);
}
void BReactor_SetSmallTimer (BReactor *bsys, BSmallTimer *bt, int mode, btime_t time)
{
DebugObject_Access(&bsys->d_obj);
assert_timer(bt);
// remove timer if it's already set
BReactor_RemoveSmallTimer(bsys, bt);
// if mode is absolute, subtract current time
if (mode == BTIMER_SET_ABSOLUTE) {
btime_t now = btime_gettime();
time = (time < now ? 0 : time - now);
}
// set active and reactor
bt->active = 1;
bt->reactor = bsys;
// init source
bt->source = g_timeout_source_new(time);
g_source_set_callback(bt->source, timer_source_handler, bt, NULL);
g_source_attach(bt->source, g_main_loop_get_context(bsys->gloop));
DebugCounter_Increment(&bsys->d_timers_ctr);
}
void BReactor_RemoveSmallTimer (BReactor *bsys, BSmallTimer *bt)
{
DebugObject_Access(&bsys->d_obj);
assert_timer(bt);
// do nothing if timer is not active
if (!bt->active) {
return;
}
// free source
g_source_destroy(bt->source);
g_source_unref(bt->source);
// set not active
bt->active = 0;
DebugCounter_Decrement(&bsys->d_timers_ctr);
}
void BReactor_SetTimer (BReactor *bsys, BTimer *bt)
{
BReactor_SetSmallTimer(bsys, &bt->base, BTIMER_SET_RELATIVE, bt->msTime);
}
void BReactor_SetTimerAfter (BReactor *bsys, BTimer *bt, btime_t after)
{
BReactor_SetSmallTimer(bsys, &bt->base, BTIMER_SET_RELATIVE, after);
}
void BReactor_SetTimerAbsolute (BReactor *bsys, BTimer *bt, btime_t time)
{
BReactor_SetSmallTimer(bsys, &bt->base, BTIMER_SET_ABSOLUTE, time);
}
void BReactor_RemoveTimer (BReactor *bsys, BTimer *bt)
{
return BReactor_RemoveSmallTimer(bsys, &bt->base);
}
BPendingGroup * BReactor_PendingGroup (BReactor *bsys)
{
DebugObject_Access(&bsys->d_obj);
return &bsys->pending_jobs;
}
int BReactor_Synchronize (BReactor *bsys, BSmallPending *ref)
{
DebugObject_Access(&bsys->d_obj);
ASSERT(ref)
while (!bsys->exiting) {
ASSERT(BPendingGroup_HasJobs(&bsys->pending_jobs))
if (BPendingGroup_PeekJob(&bsys->pending_jobs) == ref) {
return 1;
}
BPendingGroup_ExecuteJob(&bsys->pending_jobs);
}
return 0;
}
int BReactor_AddFileDescriptor (BReactor *bsys, BFileDescriptor *bs)
{
DebugObject_Access(&bsys->d_obj);
ASSERT(!bs->active)
// set active, no wait events, and set reactor
bs->active = 1;
bs->waitEvents = 0;
bs->reactor = bsys;
// create source
bs->source = g_source_new(&bsys->fd_source_funcs, sizeof(struct fd_source));
((struct fd_source *)bs->source)->bfd = bs;
// init pollfd
bs->pollfd.fd = bs->fd;
bs->pollfd.events = get_glib_wait_events(bs->waitEvents);
bs->pollfd.revents = 0;
// start source
g_source_add_poll(bs->source, &bs->pollfd);
g_source_attach(bs->source, g_main_loop_get_context(bsys->gloop));
DebugCounter_Increment(&bsys->d_fds_counter);
return 1;
}
void BReactor_RemoveFileDescriptor (BReactor *bsys, BFileDescriptor *bs)
{
DebugObject_Access(&bsys->d_obj);
DebugCounter_Decrement(&bsys->d_fds_counter);
ASSERT(bs->active)
// free source
g_source_destroy(bs->source);
g_source_unref(bs->source);
// set not active
bs->active = 0;
}
void BReactor_SetFileDescriptorEvents (BReactor *bsys, BFileDescriptor *bs, int events)
{
DebugObject_Access(&bsys->d_obj);
ASSERT(bs->active)
ASSERT(!(events&~(BREACTOR_READ|BREACTOR_WRITE)))
// set new wait events
bs->waitEvents = events;
// update pollfd wait events
bs->pollfd.events = get_glib_wait_events(bs->waitEvents);
}
int BReactor_InitFromExistingGMainLoop (BReactor *bsys, GMainLoop *gloop, int unref_gloop_on_free)
{
ASSERT(gloop)
ASSERT(unref_gloop_on_free == !!unref_gloop_on_free)
// set not exiting
bsys->exiting = 0;
// set gloop and unref on free flag
bsys->gloop = gloop;
bsys->unref_gloop_on_free = unref_gloop_on_free;
// init fd source functions table
memset(&bsys->fd_source_funcs, 0, sizeof(bsys->fd_source_funcs));
bsys->fd_source_funcs.prepare = fd_source_func_prepare;
bsys->fd_source_funcs.check = fd_source_func_check;
bsys->fd_source_funcs.dispatch = fd_source_func_dispatch;
bsys->fd_source_funcs.finalize = NULL;
// init job queue
BPendingGroup_Init(&bsys->pending_jobs);
// init active limits list
LinkedList1_Init(&bsys->active_limits_list);
DebugCounter_Init(&bsys->d_fds_counter);
DebugCounter_Init(&bsys->d_limits_ctr);
DebugCounter_Init(&bsys->d_timers_ctr);
DebugObject_Init(&bsys->d_obj);
return 1;
}
GMainLoop * BReactor_GetGMainLoop (BReactor *bsys)
{
DebugObject_Access(&bsys->d_obj);
return bsys->gloop;
}
int BReactor_SynchronizeAll (BReactor *bsys)
{
DebugObject_Access(&bsys->d_obj);
dispatch_pending(bsys);
return !bsys->exiting;
}
void BReactorLimit_Init (BReactorLimit *o, BReactor *reactor, int limit)
{
DebugObject_Access(&reactor->d_obj);
ASSERT(limit > 0)
// init arguments
o->reactor = reactor;
o->limit = limit;
// set count zero
o->count = 0;
DebugCounter_Increment(&reactor->d_limits_ctr);
DebugObject_Init(&o->d_obj);
}
void BReactorLimit_Free (BReactorLimit *o)
{
BReactor *reactor = o->reactor;
DebugObject_Free(&o->d_obj);
DebugCounter_Decrement(&reactor->d_limits_ctr);
// remove from active limits list
if (o->count > 0) {
LinkedList1_Remove(&reactor->active_limits_list, &o->active_limits_list_node);
}
}
int BReactorLimit_Increment (BReactorLimit *o)
{
BReactor *reactor = o->reactor;
DebugObject_Access(&o->d_obj);
// check count against limit
if (o->count >= o->limit) {
return 0;
}
// increment count
o->count++;
// if limit was zero, add to active limits list
if (o->count == 1) {
LinkedList1_Append(&reactor->active_limits_list, &o->active_limits_list_node);
}
return 1;
}
void BReactorLimit_SetLimit (BReactorLimit *o, int limit)
{
DebugObject_Access(&o->d_obj);
ASSERT(limit > 0)
// set limit
o->limit = limit;
}
| gpl-3.0 |
shines77/shadowsocks-android | src/main/jni/badvpn/client/SPProtoEncoder.c | 368 | 12842 | /**
* @file SPProtoEncoder.c
* @author Ambroz Bizjak <ambrop7@gmail.com>
*
* @section LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the author 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 AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <string.h>
#include <stdlib.h>
#include <misc/balign.h>
#include <misc/offset.h>
#include <misc/byteorder.h>
#include <security/BRandom.h>
#include <security/BHash.h>
#include "SPProtoEncoder.h"
static int can_encode (SPProtoEncoder *o);
static void encode_packet (SPProtoEncoder *o);
static void encode_work_func (SPProtoEncoder *o);
static void encode_work_handler (SPProtoEncoder *o);
static void maybe_encode (SPProtoEncoder *o);
static void output_handler_recv (SPProtoEncoder *o, uint8_t *data);
static void input_handler_done (SPProtoEncoder *o, int data_len);
static void handler_job_hander (SPProtoEncoder *o);
static void otpgenerator_handler (SPProtoEncoder *o);
static void maybe_stop_work (SPProtoEncoder *o);
static int can_encode (SPProtoEncoder *o)
{
ASSERT(o->in_len >= 0)
ASSERT(o->out_have)
ASSERT(!o->tw_have)
return (
(!SPPROTO_HAVE_OTP(o->sp_params) || OTPGenerator_GetPosition(&o->otpgen) < o->sp_params.otp_num) &&
(!SPPROTO_HAVE_ENCRYPTION(o->sp_params) || o->have_encryption_key)
);
}
static void encode_packet (SPProtoEncoder *o)
{
ASSERT(o->in_len >= 0)
ASSERT(o->out_have)
ASSERT(!o->tw_have)
ASSERT(can_encode(o))
// generate OTP, remember seed ID
if (SPPROTO_HAVE_OTP(o->sp_params)) {
o->tw_seed_id = o->otpgen_seed_id;
o->tw_otp = OTPGenerator_GetOTP(&o->otpgen);
}
// start work
BThreadWork_Init(&o->tw, o->twd, (BThreadWork_handler_done)encode_work_handler, o, (BThreadWork_work_func)encode_work_func, o);
o->tw_have = 1;
// schedule OTP warning handler
if (SPPROTO_HAVE_OTP(o->sp_params) && OTPGenerator_GetPosition(&o->otpgen) == o->otp_warning_count) {
BPending_Set(&o->handler_job);
}
}
static void encode_work_func (SPProtoEncoder *o)
{
ASSERT(o->in_len >= 0)
ASSERT(o->out_have)
ASSERT(!SPPROTO_HAVE_ENCRYPTION(o->sp_params) || o->have_encryption_key)
ASSERT(o->in_len <= o->input_mtu)
// determine plaintext location
uint8_t *plaintext = (SPPROTO_HAVE_ENCRYPTION(o->sp_params) ? o->buf : o->out);
// plaintext begins with header
uint8_t *header = plaintext;
// plaintext is header + payload
int plaintext_len = SPPROTO_HEADER_LEN(o->sp_params) + o->in_len;
// write OTP
if (SPPROTO_HAVE_OTP(o->sp_params)) {
struct spproto_otpdata header_otpd;
header_otpd.seed_id = htol16(o->tw_seed_id);
header_otpd.otp = o->tw_otp;
memcpy(header + SPPROTO_HEADER_OTPDATA_OFF(o->sp_params), &header_otpd, sizeof(header_otpd));
}
// write hash
if (SPPROTO_HAVE_HASH(o->sp_params)) {
uint8_t *header_hash = header + SPPROTO_HEADER_HASH_OFF(o->sp_params);
// zero hash field
memset(header_hash, 0, o->hash_size);
// calculate hash
uint8_t hash[BHASH_MAX_SIZE];
BHash_calculate(o->sp_params.hash_mode, plaintext, plaintext_len, hash);
// set hash field
memcpy(header_hash, hash, o->hash_size);
}
int out_len;
if (SPPROTO_HAVE_ENCRYPTION(o->sp_params)) {
// encrypting pad(header + payload)
int cyphertext_len = balign_up((plaintext_len + 1), o->enc_block_size);
// write padding
plaintext[plaintext_len] = 1;
for (int i = plaintext_len + 1; i < cyphertext_len; i++) {
plaintext[i] = 0;
}
// generate IV
BRandom_randomize(o->out, o->enc_block_size);
// copy IV because BEncryption_Encrypt changes the IV
uint8_t iv[BENCRYPTION_MAX_BLOCK_SIZE];
memcpy(iv, o->out, o->enc_block_size);
// encrypt
BEncryption_Encrypt(&o->encryptor, plaintext, o->out + o->enc_block_size, cyphertext_len, iv);
out_len = o->enc_block_size + cyphertext_len;
} else {
out_len = plaintext_len;
}
// remember length
o->tw_out_len = out_len;
}
static void encode_work_handler (SPProtoEncoder *o)
{
ASSERT(o->in_len >= 0)
ASSERT(o->out_have)
ASSERT(o->tw_have)
// free work
BThreadWork_Free(&o->tw);
o->tw_have = 0;
// finish packet
o->in_len = -1;
o->out_have = 0;
PacketRecvInterface_Done(&o->output, o->tw_out_len);
}
static void maybe_encode (SPProtoEncoder *o)
{
if (o->in_len >= 0 && o->out_have && !o->tw_have && can_encode(o)) {
encode_packet(o);
}
}
static void output_handler_recv (SPProtoEncoder *o, uint8_t *data)
{
ASSERT(o->in_len == -1)
ASSERT(!o->out_have)
ASSERT(!o->tw_have)
DebugObject_Access(&o->d_obj);
// remember output packet
o->out_have = 1;
o->out = data;
// determine plaintext location
uint8_t *plaintext = (SPPROTO_HAVE_ENCRYPTION(o->sp_params) ? o->buf : o->out);
// schedule receive
PacketRecvInterface_Receiver_Recv(o->input, plaintext + SPPROTO_HEADER_LEN(o->sp_params));
}
static void input_handler_done (SPProtoEncoder *o, int data_len)
{
ASSERT(data_len >= 0)
ASSERT(data_len <= o->input_mtu)
ASSERT(o->in_len == -1)
ASSERT(o->out_have)
ASSERT(!o->tw_have)
DebugObject_Access(&o->d_obj);
// remember input packet
o->in_len = data_len;
// encode if possible
if (can_encode(o)) {
encode_packet(o);
}
}
static void handler_job_hander (SPProtoEncoder *o)
{
ASSERT(SPPROTO_HAVE_OTP(o->sp_params))
DebugObject_Access(&o->d_obj);
if (o->handler) {
o->handler(o->user);
return;
}
}
static void otpgenerator_handler (SPProtoEncoder *o)
{
ASSERT(SPPROTO_HAVE_OTP(o->sp_params))
DebugObject_Access(&o->d_obj);
// remember seed ID
o->otpgen_seed_id = o->otpgen_pending_seed_id;
// possibly continue I/O
maybe_encode(o);
}
static void maybe_stop_work (SPProtoEncoder *o)
{
// stop existing work
if (o->tw_have) {
BThreadWork_Free(&o->tw);
o->tw_have = 0;
}
}
int SPProtoEncoder_Init (SPProtoEncoder *o, PacketRecvInterface *input, struct spproto_security_params sp_params, int otp_warning_count, BPendingGroup *pg, BThreadWorkDispatcher *twd)
{
spproto_assert_security_params(sp_params);
ASSERT(spproto_carrier_mtu_for_payload_mtu(sp_params, PacketRecvInterface_GetMTU(input)) >= 0)
if (SPPROTO_HAVE_OTP(sp_params)) {
ASSERT(otp_warning_count > 0)
ASSERT(otp_warning_count <= sp_params.otp_num)
}
// init arguments
o->input = input;
o->sp_params = sp_params;
o->otp_warning_count = otp_warning_count;
o->twd = twd;
// set no handlers
o->handler = NULL;
// calculate hash size
if (SPPROTO_HAVE_HASH(o->sp_params)) {
o->hash_size = BHash_size(o->sp_params.hash_mode);
}
// calculate encryption block and key sizes
if (SPPROTO_HAVE_ENCRYPTION(o->sp_params)) {
o->enc_block_size = BEncryption_cipher_block_size(o->sp_params.encryption_mode);
o->enc_key_size = BEncryption_cipher_key_size(o->sp_params.encryption_mode);
}
// init otp generator
if (SPPROTO_HAVE_OTP(o->sp_params)) {
if (!OTPGenerator_Init(&o->otpgen, o->sp_params.otp_num, o->sp_params.otp_mode, o->twd, (OTPGenerator_handler)otpgenerator_handler, o)) {
goto fail0;
}
}
// have no encryption key
if (SPPROTO_HAVE_ENCRYPTION(o->sp_params)) {
o->have_encryption_key = 0;
}
// remember input MTU
o->input_mtu = PacketRecvInterface_GetMTU(o->input);
// calculate output MTU
o->output_mtu = spproto_carrier_mtu_for_payload_mtu(o->sp_params, o->input_mtu);
// init input
PacketRecvInterface_Receiver_Init(o->input, (PacketRecvInterface_handler_done)input_handler_done, o);
// have no input in buffer
o->in_len = -1;
// init output
PacketRecvInterface_Init(&o->output, o->output_mtu, (PacketRecvInterface_handler_recv)output_handler_recv, o, pg);
// have no output available
o->out_have = 0;
// allocate plaintext buffer
if (SPPROTO_HAVE_ENCRYPTION(o->sp_params)) {
int buf_size = balign_up((SPPROTO_HEADER_LEN(o->sp_params) + o->input_mtu + 1), o->enc_block_size);
if (!(o->buf = (uint8_t *)malloc(buf_size))) {
goto fail1;
}
}
// init handler job
BPending_Init(&o->handler_job, pg, (BPending_handler)handler_job_hander, o);
// have no work
o->tw_have = 0;
DebugObject_Init(&o->d_obj);
return 1;
fail1:
PacketRecvInterface_Free(&o->output);
if (SPPROTO_HAVE_OTP(o->sp_params)) {
OTPGenerator_Free(&o->otpgen);
}
fail0:
return 0;
}
void SPProtoEncoder_Free (SPProtoEncoder *o)
{
DebugObject_Free(&o->d_obj);
// free work
if (o->tw_have) {
BThreadWork_Free(&o->tw);
}
// free handler job
BPending_Free(&o->handler_job);
// free plaintext buffer
if (SPPROTO_HAVE_ENCRYPTION(o->sp_params)) {
free(o->buf);
}
// free output
PacketRecvInterface_Free(&o->output);
// free encryptor
if (SPPROTO_HAVE_ENCRYPTION(o->sp_params) && o->have_encryption_key) {
BEncryption_Free(&o->encryptor);
}
// free otp generator
if (SPPROTO_HAVE_OTP(o->sp_params)) {
OTPGenerator_Free(&o->otpgen);
}
}
PacketRecvInterface * SPProtoEncoder_GetOutput (SPProtoEncoder *o)
{
DebugObject_Access(&o->d_obj);
return &o->output;
}
void SPProtoEncoder_SetEncryptionKey (SPProtoEncoder *o, uint8_t *encryption_key)
{
ASSERT(SPPROTO_HAVE_ENCRYPTION(o->sp_params))
DebugObject_Access(&o->d_obj);
// stop existing work
maybe_stop_work(o);
// free encryptor
if (o->have_encryption_key) {
BEncryption_Free(&o->encryptor);
}
// init encryptor
BEncryption_Init(&o->encryptor, BENCRYPTION_MODE_ENCRYPT, o->sp_params.encryption_mode, encryption_key);
// have encryption key
o->have_encryption_key = 1;
// possibly continue I/O
maybe_encode(o);
}
void SPProtoEncoder_RemoveEncryptionKey (SPProtoEncoder *o)
{
ASSERT(SPPROTO_HAVE_ENCRYPTION(o->sp_params))
DebugObject_Access(&o->d_obj);
// stop existing work
maybe_stop_work(o);
if (o->have_encryption_key) {
// free encryptor
BEncryption_Free(&o->encryptor);
// have no encryption key
o->have_encryption_key = 0;
}
}
void SPProtoEncoder_SetOTPSeed (SPProtoEncoder *o, uint16_t seed_id, uint8_t *key, uint8_t *iv)
{
ASSERT(SPPROTO_HAVE_OTP(o->sp_params))
DebugObject_Access(&o->d_obj);
// give seed to OTP generator
OTPGenerator_SetSeed(&o->otpgen, key, iv);
// remember seed ID
o->otpgen_pending_seed_id = seed_id;
}
void SPProtoEncoder_RemoveOTPSeed (SPProtoEncoder *o)
{
ASSERT(SPPROTO_HAVE_OTP(o->sp_params))
DebugObject_Access(&o->d_obj);
// reset OTP generator
OTPGenerator_Reset(&o->otpgen);
}
void SPProtoEncoder_SetHandlers (SPProtoEncoder *o, SPProtoEncoder_handler handler, void *user)
{
DebugObject_Access(&o->d_obj);
o->handler = handler;
o->user = user;
}
| gpl-3.0 |
jinxiao/shadowsocks-android | src/main/jni/openssl/crypto/des/cfb64ede.c | 885 | 6962 | /* crypto/des/cfb64ede.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include "des_locl.h"
#include "e_os.h"
/* The input and output encrypted as though 64bit cfb mode is being
* used. The extra state information to record how much of the
* 64bit block we have used is contained in *num;
*/
void DES_ede3_cfb64_encrypt(const unsigned char *in, unsigned char *out,
long length, DES_key_schedule *ks1,
DES_key_schedule *ks2, DES_key_schedule *ks3,
DES_cblock *ivec, int *num, int enc)
{
register DES_LONG v0,v1;
register long l=length;
register int n= *num;
DES_LONG ti[2];
unsigned char *iv,c,cc;
iv=&(*ivec)[0];
if (enc)
{
while (l--)
{
if (n == 0)
{
c2l(iv,v0);
c2l(iv,v1);
ti[0]=v0;
ti[1]=v1;
DES_encrypt3(ti,ks1,ks2,ks3);
v0=ti[0];
v1=ti[1];
iv = &(*ivec)[0];
l2c(v0,iv);
l2c(v1,iv);
iv = &(*ivec)[0];
}
c= *(in++)^iv[n];
*(out++)=c;
iv[n]=c;
n=(n+1)&0x07;
}
}
else
{
while (l--)
{
if (n == 0)
{
c2l(iv,v0);
c2l(iv,v1);
ti[0]=v0;
ti[1]=v1;
DES_encrypt3(ti,ks1,ks2,ks3);
v0=ti[0];
v1=ti[1];
iv = &(*ivec)[0];
l2c(v0,iv);
l2c(v1,iv);
iv = &(*ivec)[0];
}
cc= *(in++);
c=iv[n];
iv[n]=cc;
*(out++)=c^cc;
n=(n+1)&0x07;
}
}
v0=v1=ti[0]=ti[1]=c=cc=0;
*num=n;
}
#ifdef undef /* MACRO */
void DES_ede2_cfb64_encrypt(unsigned char *in, unsigned char *out, long length,
DES_key_schedule ks1, DES_key_schedule ks2, DES_cblock (*ivec),
int *num, int enc)
{
DES_ede3_cfb64_encrypt(in,out,length,ks1,ks2,ks1,ivec,num,enc);
}
#endif
/* This is compatible with the single key CFB-r for DES, even thought that's
* not what EVP needs.
*/
void DES_ede3_cfb_encrypt(const unsigned char *in,unsigned char *out,
int numbits,long length,DES_key_schedule *ks1,
DES_key_schedule *ks2,DES_key_schedule *ks3,
DES_cblock *ivec,int enc)
{
register DES_LONG d0,d1,v0,v1;
register unsigned long l=length,n=((unsigned int)numbits+7)/8;
register int num=numbits,i;
DES_LONG ti[2];
unsigned char *iv;
unsigned char ovec[16];
if (num > 64) return;
iv = &(*ivec)[0];
c2l(iv,v0);
c2l(iv,v1);
if (enc)
{
while (l >= n)
{
l-=n;
ti[0]=v0;
ti[1]=v1;
DES_encrypt3(ti,ks1,ks2,ks3);
c2ln(in,d0,d1,n);
in+=n;
d0^=ti[0];
d1^=ti[1];
l2cn(d0,d1,out,n);
out+=n;
/* 30-08-94 - eay - changed because l>>32 and
* l<<32 are bad under gcc :-( */
if (num == 32)
{ v0=v1; v1=d0; }
else if (num == 64)
{ v0=d0; v1=d1; }
else
{
iv=&ovec[0];
l2c(v0,iv);
l2c(v1,iv);
l2c(d0,iv);
l2c(d1,iv);
/* shift ovec left most of the bits... */
memmove(ovec,ovec+num/8,8+(num%8 ? 1 : 0));
/* now the remaining bits */
if(num%8 != 0)
for(i=0 ; i < 8 ; ++i)
{
ovec[i]<<=num%8;
ovec[i]|=ovec[i+1]>>(8-num%8);
}
iv=&ovec[0];
c2l(iv,v0);
c2l(iv,v1);
}
}
}
else
{
while (l >= n)
{
l-=n;
ti[0]=v0;
ti[1]=v1;
DES_encrypt3(ti,ks1,ks2,ks3);
c2ln(in,d0,d1,n);
in+=n;
/* 30-08-94 - eay - changed because l>>32 and
* l<<32 are bad under gcc :-( */
if (num == 32)
{ v0=v1; v1=d0; }
else if (num == 64)
{ v0=d0; v1=d1; }
else
{
iv=&ovec[0];
l2c(v0,iv);
l2c(v1,iv);
l2c(d0,iv);
l2c(d1,iv);
/* shift ovec left most of the bits... */
memmove(ovec,ovec+num/8,8+(num%8 ? 1 : 0));
/* now the remaining bits */
if(num%8 != 0)
for(i=0 ; i < 8 ; ++i)
{
ovec[i]<<=num%8;
ovec[i]|=ovec[i+1]>>(8-num%8);
}
iv=&ovec[0];
c2l(iv,v0);
c2l(iv,v1);
}
d0^=ti[0];
d1^=ti[1];
l2cn(d0,d1,out,n);
out+=n;
}
}
iv = &(*ivec)[0];
l2c(v0,iv);
l2c(v1,iv);
v0=v1=d0=d1=ti[0]=ti[1]=0;
}
| gpl-3.0 |
Teiske/rt2d | external/glfw-3.0.3/src/clipboard.c | 139 | 1906 | //========================================================================
// GLFW 3.0 - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2010 Camilla Berglund <elmindreda@elmindreda.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#include "internal.h"
#include <math.h>
#include <string.h>
//////////////////////////////////////////////////////////////////////////
////// GLFW public API //////
//////////////////////////////////////////////////////////////////////////
GLFWAPI void glfwSetClipboardString(GLFWwindow* handle, const char* string)
{
_GLFWwindow* window = (_GLFWwindow*) handle;
_GLFW_REQUIRE_INIT();
_glfwPlatformSetClipboardString(window, string);
}
GLFWAPI const char* glfwGetClipboardString(GLFWwindow* handle)
{
_GLFWwindow* window = (_GLFWwindow*) handle;
_GLFW_REQUIRE_INIT_OR_RETURN(NULL);
return _glfwPlatformGetClipboardString(window);
}
| gpl-3.0 |
VenJie/linux_2.6.36 | drivers/acpi/apei/hest.c | 139 | 6068 | /*
* APEI Hardware Error Souce Table support
*
* HEST describes error sources in detail; communicates operational
* parameters (i.e. severity levels, masking bits, and threshold
* values) to Linux as necessary. It also allows the BIOS to report
* non-standard error sources to Linux (for example, chipset-specific
* error registers).
*
* For more information about HEST, please refer to ACPI Specification
* version 4.0, section 17.3.2.
*
* Copyright 2009 Intel Corp.
* Author: Huang Ying <ying.huang@intel.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version
* 2 as published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/acpi.h>
#include <linux/kdebug.h>
#include <linux/highmem.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include <acpi/apei.h>
#include "apei-internal.h"
#define HEST_PFX "HEST: "
int hest_disable;
EXPORT_SYMBOL_GPL(hest_disable);
/* HEST table parsing */
static struct acpi_table_hest *hest_tab;
static int hest_esrc_len_tab[ACPI_HEST_TYPE_RESERVED] = {
[ACPI_HEST_TYPE_IA32_CHECK] = -1, /* need further calculation */
[ACPI_HEST_TYPE_IA32_CORRECTED_CHECK] = -1,
[ACPI_HEST_TYPE_IA32_NMI] = sizeof(struct acpi_hest_ia_nmi),
[ACPI_HEST_TYPE_AER_ROOT_PORT] = sizeof(struct acpi_hest_aer_root),
[ACPI_HEST_TYPE_AER_ENDPOINT] = sizeof(struct acpi_hest_aer),
[ACPI_HEST_TYPE_AER_BRIDGE] = sizeof(struct acpi_hest_aer_bridge),
[ACPI_HEST_TYPE_GENERIC_ERROR] = sizeof(struct acpi_hest_generic),
};
static int hest_esrc_len(struct acpi_hest_header *hest_hdr)
{
u16 hest_type = hest_hdr->type;
int len;
if (hest_type >= ACPI_HEST_TYPE_RESERVED)
return 0;
len = hest_esrc_len_tab[hest_type];
if (hest_type == ACPI_HEST_TYPE_IA32_CORRECTED_CHECK) {
struct acpi_hest_ia_corrected *cmc;
cmc = (struct acpi_hest_ia_corrected *)hest_hdr;
len = sizeof(*cmc) + cmc->num_hardware_banks *
sizeof(struct acpi_hest_ia_error_bank);
} else if (hest_type == ACPI_HEST_TYPE_IA32_CHECK) {
struct acpi_hest_ia_machine_check *mc;
mc = (struct acpi_hest_ia_machine_check *)hest_hdr;
len = sizeof(*mc) + mc->num_hardware_banks *
sizeof(struct acpi_hest_ia_error_bank);
}
BUG_ON(len == -1);
return len;
};
int apei_hest_parse(apei_hest_func_t func, void *data)
{
struct acpi_hest_header *hest_hdr;
int i, rc, len;
if (hest_disable)
return -EINVAL;
hest_hdr = (struct acpi_hest_header *)(hest_tab + 1);
for (i = 0; i < hest_tab->error_source_count; i++) {
len = hest_esrc_len(hest_hdr);
if (!len) {
pr_warning(FW_WARN HEST_PFX
"Unknown or unused hardware error source "
"type: %d for hardware error source: %d.\n",
hest_hdr->type, hest_hdr->source_id);
return -EINVAL;
}
if ((void *)hest_hdr + len >
(void *)hest_tab + hest_tab->header.length) {
pr_warning(FW_BUG HEST_PFX
"Table contents overflow for hardware error source: %d.\n",
hest_hdr->source_id);
return -EINVAL;
}
rc = func(hest_hdr, data);
if (rc)
return rc;
hest_hdr = (void *)hest_hdr + len;
}
return 0;
}
EXPORT_SYMBOL_GPL(apei_hest_parse);
struct ghes_arr {
struct platform_device **ghes_devs;
unsigned int count;
};
static int hest_parse_ghes_count(struct acpi_hest_header *hest_hdr, void *data)
{
int *count = data;
if (hest_hdr->type == ACPI_HEST_TYPE_GENERIC_ERROR)
(*count)++;
return 0;
}
static int hest_parse_ghes(struct acpi_hest_header *hest_hdr, void *data)
{
struct platform_device *ghes_dev;
struct ghes_arr *ghes_arr = data;
int rc;
if (hest_hdr->type != ACPI_HEST_TYPE_GENERIC_ERROR)
return 0;
if (!((struct acpi_hest_generic *)hest_hdr)->enabled)
return 0;
ghes_dev = platform_device_alloc("GHES", hest_hdr->source_id);
if (!ghes_dev)
return -ENOMEM;
rc = platform_device_add_data(ghes_dev, &hest_hdr, sizeof(void *));
if (rc)
goto err;
rc = platform_device_add(ghes_dev);
if (rc)
goto err;
ghes_arr->ghes_devs[ghes_arr->count++] = ghes_dev;
return 0;
err:
platform_device_put(ghes_dev);
return rc;
}
static int hest_ghes_dev_register(unsigned int ghes_count)
{
int rc, i;
struct ghes_arr ghes_arr;
ghes_arr.count = 0;
ghes_arr.ghes_devs = kmalloc(sizeof(void *) * ghes_count, GFP_KERNEL);
if (!ghes_arr.ghes_devs)
return -ENOMEM;
rc = apei_hest_parse(hest_parse_ghes, &ghes_arr);
if (rc)
goto err;
out:
kfree(ghes_arr.ghes_devs);
return rc;
err:
for (i = 0; i < ghes_arr.count; i++)
platform_device_unregister(ghes_arr.ghes_devs[i]);
goto out;
}
static int __init setup_hest_disable(char *str)
{
hest_disable = 1;
return 0;
}
__setup("hest_disable", setup_hest_disable);
static int __init hest_init(void)
{
acpi_status status;
int rc = -ENODEV;
unsigned int ghes_count = 0;
if (acpi_disabled)
goto err;
if (hest_disable) {
pr_info(HEST_PFX "HEST tabling parsing is disabled.\n");
goto err;
}
status = acpi_get_table(ACPI_SIG_HEST, 0,
(struct acpi_table_header **)&hest_tab);
if (status == AE_NOT_FOUND) {
pr_info(HEST_PFX "Table is not found!\n");
goto err;
} else if (ACPI_FAILURE(status)) {
const char *msg = acpi_format_exception(status);
pr_err(HEST_PFX "Failed to get table, %s\n", msg);
rc = -EINVAL;
goto err;
}
rc = apei_hest_parse(hest_parse_ghes_count, &ghes_count);
if (rc)
goto err;
rc = hest_ghes_dev_register(ghes_count);
if (rc)
goto err;
pr_info(HEST_PFX "HEST table parsing is initialized.\n");
return 0;
err:
hest_disable = 1;
return rc;
}
subsys_initcall(hest_init);
| gpl-3.0 |
chuncky/nuc900kernel | linux-2.6.35.4/drivers/usb/core/hub.c | 144 | 111306 | /*
* USB hub driver.
*
* (C) Copyright 1999 Linus Torvalds
* (C) Copyright 1999 Johannes Erdfelt
* (C) Copyright 1999 Gregory P. Smith
* (C) Copyright 2001 Brad Hards (bhards@bigpond.net.au)
*
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/completion.h>
#include <linux/sched.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <linux/ioctl.h>
#include <linux/usb.h>
#include <linux/usbdevice_fs.h>
#include <linux/usb/hcd.h>
#include <linux/usb/quirks.h>
#include <linux/kthread.h>
#include <linux/mutex.h>
#include <linux/freezer.h>
#include <linux/pm_runtime.h>
#include <asm/uaccess.h>
#include <asm/byteorder.h>
#include "usb.h"
/* if we are in debug mode, always announce new devices */
#ifdef DEBUG
#ifndef CONFIG_USB_ANNOUNCE_NEW_DEVICES
#define CONFIG_USB_ANNOUNCE_NEW_DEVICES
#endif
#endif
struct usb_hub {
struct device *intfdev; /* the "interface" device */
struct usb_device *hdev;
struct kref kref;
struct urb *urb; /* for interrupt polling pipe */
/* buffer for urb ... with extra space in case of babble */
char (*buffer)[8];
union {
struct usb_hub_status hub;
struct usb_port_status port;
} *status; /* buffer for status reports */
struct mutex status_mutex; /* for the status buffer */
int error; /* last reported error */
int nerrors; /* track consecutive errors */
struct list_head event_list; /* hubs w/data or errs ready */
unsigned long event_bits[1]; /* status change bitmask */
unsigned long change_bits[1]; /* ports with logical connect
status change */
unsigned long busy_bits[1]; /* ports being reset or
resumed */
unsigned long removed_bits[1]; /* ports with a "removed"
device present */
#if USB_MAXCHILDREN > 31 /* 8*sizeof(unsigned long) - 1 */
#error event_bits[] is too short!
#endif
struct usb_hub_descriptor *descriptor; /* class descriptor */
struct usb_tt tt; /* Transaction Translator */
unsigned mA_per_port; /* current for each child */
unsigned limited_power:1;
unsigned quiescing:1;
unsigned disconnected:1;
unsigned has_indicators:1;
u8 indicator[USB_MAXCHILDREN];
struct delayed_work leds;
struct delayed_work init_work;
void **port_owners;
};
/* Protect struct usb_device->state and ->children members
* Note: Both are also protected by ->dev.sem, except that ->state can
* change to USB_STATE_NOTATTACHED even when the semaphore isn't held. */
static DEFINE_SPINLOCK(device_state_lock);
/* khubd's worklist and its lock */
static DEFINE_SPINLOCK(hub_event_lock);
static LIST_HEAD(hub_event_list); /* List of hubs needing servicing */
/* Wakes up khubd */
static DECLARE_WAIT_QUEUE_HEAD(khubd_wait);
static struct task_struct *khubd_task;
/* cycle leds on hubs that aren't blinking for attention */
static int blinkenlights = 0;
module_param (blinkenlights, bool, S_IRUGO);
MODULE_PARM_DESC (blinkenlights, "true to cycle leds on hubs");
/*
* Device SATA8000 FW1.0 from DATAST0R Technology Corp requires about
* 10 seconds to send reply for the initial 64-byte descriptor request.
*/
/* define initial 64-byte descriptor request timeout in milliseconds */
static int initial_descriptor_timeout = USB_CTRL_GET_TIMEOUT;
module_param(initial_descriptor_timeout, int, S_IRUGO|S_IWUSR);
MODULE_PARM_DESC(initial_descriptor_timeout,
"initial 64-byte descriptor request timeout in milliseconds "
"(default 5000 - 5.0 seconds)");
/*
* As of 2.6.10 we introduce a new USB device initialization scheme which
* closely resembles the way Windows works. Hopefully it will be compatible
* with a wider range of devices than the old scheme. However some previously
* working devices may start giving rise to "device not accepting address"
* errors; if that happens the user can try the old scheme by adjusting the
* following module parameters.
*
* For maximum flexibility there are two boolean parameters to control the
* hub driver's behavior. On the first initialization attempt, if the
* "old_scheme_first" parameter is set then the old scheme will be used,
* otherwise the new scheme is used. If that fails and "use_both_schemes"
* is set, then the driver will make another attempt, using the other scheme.
*/
static int old_scheme_first = 0;
module_param(old_scheme_first, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(old_scheme_first,
"start with the old device initialization scheme");
static int use_both_schemes = 1;
module_param(use_both_schemes, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(use_both_schemes,
"try the other device initialization scheme if the "
"first one fails");
/* Mutual exclusion for EHCI CF initialization. This interferes with
* port reset on some companion controllers.
*/
DECLARE_RWSEM(ehci_cf_port_reset_rwsem);
EXPORT_SYMBOL_GPL(ehci_cf_port_reset_rwsem);
#define HUB_DEBOUNCE_TIMEOUT 1500
#define HUB_DEBOUNCE_STEP 25
#define HUB_DEBOUNCE_STABLE 100
static int usb_reset_and_verify_device(struct usb_device *udev);
static inline char *portspeed(int portstatus)
{
if (portstatus & USB_PORT_STAT_HIGH_SPEED)
return "480 Mb/s";
else if (portstatus & USB_PORT_STAT_LOW_SPEED)
return "1.5 Mb/s";
else if (portstatus & USB_PORT_STAT_SUPER_SPEED)
return "5.0 Gb/s";
else
return "12 Mb/s";
}
/* Note that hdev or one of its children must be locked! */
static struct usb_hub *hdev_to_hub(struct usb_device *hdev)
{
if (!hdev || !hdev->actconfig)
return NULL;
return usb_get_intfdata(hdev->actconfig->interface[0]);
}
/* USB 2.0 spec Section 11.24.4.5 */
static int get_hub_descriptor(struct usb_device *hdev, void *data, int size)
{
int i, ret;
for (i = 0; i < 3; i++) {
ret = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
USB_REQ_GET_DESCRIPTOR, USB_DIR_IN | USB_RT_HUB,
USB_DT_HUB << 8, 0, data, size,
USB_CTRL_GET_TIMEOUT);
if (ret >= (USB_DT_HUB_NONVAR_SIZE + 2))
return ret;
}
return -EINVAL;
}
/*
* USB 2.0 spec Section 11.24.2.1
*/
static int clear_hub_feature(struct usb_device *hdev, int feature)
{
return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
USB_REQ_CLEAR_FEATURE, USB_RT_HUB, feature, 0, NULL, 0, 1000);
}
/*
* USB 2.0 spec Section 11.24.2.2
*/
static int clear_port_feature(struct usb_device *hdev, int port1, int feature)
{
return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
USB_REQ_CLEAR_FEATURE, USB_RT_PORT, feature, port1,
NULL, 0, 1000);
}
/*
* USB 2.0 spec Section 11.24.2.13
*/
static int set_port_feature(struct usb_device *hdev, int port1, int feature)
{
return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
USB_REQ_SET_FEATURE, USB_RT_PORT, feature, port1,
NULL, 0, 1000);
}
/*
* USB 2.0 spec Section 11.24.2.7.1.10 and table 11-7
* for info about using port indicators
*/
static void set_port_led(
struct usb_hub *hub,
int port1,
int selector
)
{
int status = set_port_feature(hub->hdev, (selector << 8) | port1,
USB_PORT_FEAT_INDICATOR);
if (status < 0)
dev_dbg (hub->intfdev,
"port %d indicator %s status %d\n",
port1,
({ char *s; switch (selector) {
case HUB_LED_AMBER: s = "amber"; break;
case HUB_LED_GREEN: s = "green"; break;
case HUB_LED_OFF: s = "off"; break;
case HUB_LED_AUTO: s = "auto"; break;
default: s = "??"; break;
}; s; }),
status);
}
#define LED_CYCLE_PERIOD ((2*HZ)/3)
static void led_work (struct work_struct *work)
{
struct usb_hub *hub =
container_of(work, struct usb_hub, leds.work);
struct usb_device *hdev = hub->hdev;
unsigned i;
unsigned changed = 0;
int cursor = -1;
if (hdev->state != USB_STATE_CONFIGURED || hub->quiescing)
return;
for (i = 0; i < hub->descriptor->bNbrPorts; i++) {
unsigned selector, mode;
/* 30%-50% duty cycle */
switch (hub->indicator[i]) {
/* cycle marker */
case INDICATOR_CYCLE:
cursor = i;
selector = HUB_LED_AUTO;
mode = INDICATOR_AUTO;
break;
/* blinking green = sw attention */
case INDICATOR_GREEN_BLINK:
selector = HUB_LED_GREEN;
mode = INDICATOR_GREEN_BLINK_OFF;
break;
case INDICATOR_GREEN_BLINK_OFF:
selector = HUB_LED_OFF;
mode = INDICATOR_GREEN_BLINK;
break;
/* blinking amber = hw attention */
case INDICATOR_AMBER_BLINK:
selector = HUB_LED_AMBER;
mode = INDICATOR_AMBER_BLINK_OFF;
break;
case INDICATOR_AMBER_BLINK_OFF:
selector = HUB_LED_OFF;
mode = INDICATOR_AMBER_BLINK;
break;
/* blink green/amber = reserved */
case INDICATOR_ALT_BLINK:
selector = HUB_LED_GREEN;
mode = INDICATOR_ALT_BLINK_OFF;
break;
case INDICATOR_ALT_BLINK_OFF:
selector = HUB_LED_AMBER;
mode = INDICATOR_ALT_BLINK;
break;
default:
continue;
}
if (selector != HUB_LED_AUTO)
changed = 1;
set_port_led(hub, i + 1, selector);
hub->indicator[i] = mode;
}
if (!changed && blinkenlights) {
cursor++;
cursor %= hub->descriptor->bNbrPorts;
set_port_led(hub, cursor + 1, HUB_LED_GREEN);
hub->indicator[cursor] = INDICATOR_CYCLE;
changed++;
}
if (changed)
schedule_delayed_work(&hub->leds, LED_CYCLE_PERIOD);
}
/* use a short timeout for hub/port status fetches */
#define USB_STS_TIMEOUT 1000
#define USB_STS_RETRIES 5
/*
* USB 2.0 spec Section 11.24.2.6
*/
static int get_hub_status(struct usb_device *hdev,
struct usb_hub_status *data)
{
int i, status = -ETIMEDOUT;
for (i = 0; i < USB_STS_RETRIES && status == -ETIMEDOUT; i++) {
status = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_HUB, 0, 0,
data, sizeof(*data), USB_STS_TIMEOUT);
}
return status;
}
/*
* USB 2.0 spec Section 11.24.2.7
*/
static int get_port_status(struct usb_device *hdev, int port1,
struct usb_port_status *data)
{
int i, status = -ETIMEDOUT;
for (i = 0; i < USB_STS_RETRIES && status == -ETIMEDOUT; i++) {
status = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_PORT, 0, port1,
data, sizeof(*data), USB_STS_TIMEOUT);
}
return status;
}
static int hub_port_status(struct usb_hub *hub, int port1,
u16 *status, u16 *change)
{
int ret;
mutex_lock(&hub->status_mutex);
ret = get_port_status(hub->hdev, port1, &hub->status->port);
if (ret < 4) {
dev_err(hub->intfdev,
"%s failed (err = %d)\n", __func__, ret);
if (ret >= 0)
ret = -EIO;
} else {
*status = le16_to_cpu(hub->status->port.wPortStatus);
*change = le16_to_cpu(hub->status->port.wPortChange);
ret = 0;
}
mutex_unlock(&hub->status_mutex);
return ret;
}
static void kick_khubd(struct usb_hub *hub)
{
unsigned long flags;
spin_lock_irqsave(&hub_event_lock, flags);
if (!hub->disconnected && list_empty(&hub->event_list)) {
list_add_tail(&hub->event_list, &hub_event_list);
/* Suppress autosuspend until khubd runs */
usb_autopm_get_interface_no_resume(
to_usb_interface(hub->intfdev));
wake_up(&khubd_wait);
}
spin_unlock_irqrestore(&hub_event_lock, flags);
}
void usb_kick_khubd(struct usb_device *hdev)
{
struct usb_hub *hub = hdev_to_hub(hdev);
if (hub)
kick_khubd(hub);
}
/* completion function, fires on port status changes and various faults */
static void hub_irq(struct urb *urb)
{
struct usb_hub *hub = urb->context;
int status = urb->status;
unsigned i;
unsigned long bits;
switch (status) {
case -ENOENT: /* synchronous unlink */
case -ECONNRESET: /* async unlink */
case -ESHUTDOWN: /* hardware going away */
return;
default: /* presumably an error */
/* Cause a hub reset after 10 consecutive errors */
dev_dbg (hub->intfdev, "transfer --> %d\n", status);
if ((++hub->nerrors < 10) || hub->error)
goto resubmit;
hub->error = status;
/* FALL THROUGH */
/* let khubd handle things */
case 0: /* we got data: port status changed */
bits = 0;
for (i = 0; i < urb->actual_length; ++i)
bits |= ((unsigned long) ((*hub->buffer)[i]))
<< (i*8);
hub->event_bits[0] = bits;
break;
}
hub->nerrors = 0;
/* Something happened, let khubd figure it out */
kick_khubd(hub);
resubmit:
if (hub->quiescing)
return;
if ((status = usb_submit_urb (hub->urb, GFP_ATOMIC)) != 0
&& status != -ENODEV && status != -EPERM)
dev_err (hub->intfdev, "resubmit --> %d\n", status);
}
/* USB 2.0 spec Section 11.24.2.3 */
static inline int
hub_clear_tt_buffer (struct usb_device *hdev, u16 devinfo, u16 tt)
{
return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
HUB_CLEAR_TT_BUFFER, USB_RT_PORT, devinfo,
tt, NULL, 0, 1000);
}
/*
* enumeration blocks khubd for a long time. we use keventd instead, since
* long blocking there is the exception, not the rule. accordingly, HCDs
* talking to TTs must queue control transfers (not just bulk and iso), so
* both can talk to the same hub concurrently.
*/
static void hub_tt_work(struct work_struct *work)
{
struct usb_hub *hub =
container_of(work, struct usb_hub, tt.clear_work);
unsigned long flags;
int limit = 100;
spin_lock_irqsave (&hub->tt.lock, flags);
while (--limit && !list_empty (&hub->tt.clear_list)) {
struct list_head *next;
struct usb_tt_clear *clear;
struct usb_device *hdev = hub->hdev;
const struct hc_driver *drv;
int status;
next = hub->tt.clear_list.next;
clear = list_entry (next, struct usb_tt_clear, clear_list);
list_del (&clear->clear_list);
/* drop lock so HCD can concurrently report other TT errors */
spin_unlock_irqrestore (&hub->tt.lock, flags);
status = hub_clear_tt_buffer (hdev, clear->devinfo, clear->tt);
if (status)
dev_err (&hdev->dev,
"clear tt %d (%04x) error %d\n",
clear->tt, clear->devinfo, status);
/* Tell the HCD, even if the operation failed */
drv = clear->hcd->driver;
if (drv->clear_tt_buffer_complete)
(drv->clear_tt_buffer_complete)(clear->hcd, clear->ep);
kfree(clear);
spin_lock_irqsave(&hub->tt.lock, flags);
}
spin_unlock_irqrestore (&hub->tt.lock, flags);
}
/**
* usb_hub_clear_tt_buffer - clear control/bulk TT state in high speed hub
* @urb: an URB associated with the failed or incomplete split transaction
*
* High speed HCDs use this to tell the hub driver that some split control or
* bulk transaction failed in a way that requires clearing internal state of
* a transaction translator. This is normally detected (and reported) from
* interrupt context.
*
* It may not be possible for that hub to handle additional full (or low)
* speed transactions until that state is fully cleared out.
*/
int usb_hub_clear_tt_buffer(struct urb *urb)
{
struct usb_device *udev = urb->dev;
int pipe = urb->pipe;
struct usb_tt *tt = udev->tt;
unsigned long flags;
struct usb_tt_clear *clear;
/* we've got to cope with an arbitrary number of pending TT clears,
* since each TT has "at least two" buffers that can need it (and
* there can be many TTs per hub). even if they're uncommon.
*/
if ((clear = kmalloc (sizeof *clear, GFP_ATOMIC)) == NULL) {
dev_err (&udev->dev, "can't save CLEAR_TT_BUFFER state\n");
/* FIXME recover somehow ... RESET_TT? */
return -ENOMEM;
}
/* info that CLEAR_TT_BUFFER needs */
clear->tt = tt->multi ? udev->ttport : 1;
clear->devinfo = usb_pipeendpoint (pipe);
clear->devinfo |= udev->devnum << 4;
clear->devinfo |= usb_pipecontrol (pipe)
? (USB_ENDPOINT_XFER_CONTROL << 11)
: (USB_ENDPOINT_XFER_BULK << 11);
if (usb_pipein (pipe))
clear->devinfo |= 1 << 15;
/* info for completion callback */
clear->hcd = bus_to_hcd(udev->bus);
clear->ep = urb->ep;
/* tell keventd to clear state for this TT */
spin_lock_irqsave (&tt->lock, flags);
list_add_tail (&clear->clear_list, &tt->clear_list);
schedule_work(&tt->clear_work);
spin_unlock_irqrestore (&tt->lock, flags);
return 0;
}
EXPORT_SYMBOL_GPL(usb_hub_clear_tt_buffer);
/* If do_delay is false, return the number of milliseconds the caller
* needs to delay.
*/
static unsigned hub_power_on(struct usb_hub *hub, bool do_delay)
{
int port1;
unsigned pgood_delay = hub->descriptor->bPwrOn2PwrGood * 2;
unsigned delay;
u16 wHubCharacteristics =
le16_to_cpu(hub->descriptor->wHubCharacteristics);
/* Enable power on each port. Some hubs have reserved values
* of LPSM (> 2) in their descriptors, even though they are
* USB 2.0 hubs. Some hubs do not implement port-power switching
* but only emulate it. In all cases, the ports won't work
* unless we send these messages to the hub.
*/
if ((wHubCharacteristics & HUB_CHAR_LPSM) < 2)
dev_dbg(hub->intfdev, "enabling power on all ports\n");
else
dev_dbg(hub->intfdev, "trying to enable port power on "
"non-switchable hub\n");
for (port1 = 1; port1 <= hub->descriptor->bNbrPorts; port1++)
set_port_feature(hub->hdev, port1, USB_PORT_FEAT_POWER);
/* Wait at least 100 msec for power to become stable */
delay = max(pgood_delay, (unsigned) 100);
if (do_delay)
msleep(delay);
return delay;
}
static int hub_hub_status(struct usb_hub *hub,
u16 *status, u16 *change)
{
int ret;
mutex_lock(&hub->status_mutex);
ret = get_hub_status(hub->hdev, &hub->status->hub);
if (ret < 0)
dev_err (hub->intfdev,
"%s failed (err = %d)\n", __func__, ret);
else {
*status = le16_to_cpu(hub->status->hub.wHubStatus);
*change = le16_to_cpu(hub->status->hub.wHubChange);
ret = 0;
}
mutex_unlock(&hub->status_mutex);
return ret;
}
static int hub_port_disable(struct usb_hub *hub, int port1, int set_state)
{
struct usb_device *hdev = hub->hdev;
int ret = 0;
if (hdev->children[port1-1] && set_state)
usb_set_device_state(hdev->children[port1-1],
USB_STATE_NOTATTACHED);
if (!hub->error)
ret = clear_port_feature(hdev, port1, USB_PORT_FEAT_ENABLE);
if (ret)
dev_err(hub->intfdev, "cannot disable port %d (err = %d)\n",
port1, ret);
return ret;
}
/*
* Disable a port and mark a logical connnect-change event, so that some
* time later khubd will disconnect() any existing usb_device on the port
* and will re-enumerate if there actually is a device attached.
*/
static void hub_port_logical_disconnect(struct usb_hub *hub, int port1)
{
dev_dbg(hub->intfdev, "logical disconnect on port %d\n", port1);
hub_port_disable(hub, port1, 1);
/* FIXME let caller ask to power down the port:
* - some devices won't enumerate without a VBUS power cycle
* - SRP saves power that way
* - ... new call, TBD ...
* That's easy if this hub can switch power per-port, and
* khubd reactivates the port later (timer, SRP, etc).
* Powerdown must be optional, because of reset/DFU.
*/
set_bit(port1, hub->change_bits);
kick_khubd(hub);
}
/**
* usb_remove_device - disable a device's port on its parent hub
* @udev: device to be disabled and removed
* Context: @udev locked, must be able to sleep.
*
* After @udev's port has been disabled, khubd is notified and it will
* see that the device has been disconnected. When the device is
* physically unplugged and something is plugged in, the events will
* be received and processed normally.
*/
int usb_remove_device(struct usb_device *udev)
{
struct usb_hub *hub;
struct usb_interface *intf;
if (!udev->parent) /* Can't remove a root hub */
return -EINVAL;
hub = hdev_to_hub(udev->parent);
intf = to_usb_interface(hub->intfdev);
usb_autopm_get_interface(intf);
set_bit(udev->portnum, hub->removed_bits);
hub_port_logical_disconnect(hub, udev->portnum);
usb_autopm_put_interface(intf);
return 0;
}
enum hub_activation_type {
HUB_INIT, HUB_INIT2, HUB_INIT3, /* INITs must come first */
HUB_POST_RESET, HUB_RESUME, HUB_RESET_RESUME,
};
static void hub_init_func2(struct work_struct *ws);
static void hub_init_func3(struct work_struct *ws);
static void hub_activate(struct usb_hub *hub, enum hub_activation_type type)
{
struct usb_device *hdev = hub->hdev;
int port1;
int status;
bool need_debounce_delay = false;
unsigned delay;
/* Continue a partial initialization */
if (type == HUB_INIT2)
goto init2;
if (type == HUB_INIT3)
goto init3;
/* After a resume, port power should still be on.
* For any other type of activation, turn it on.
*/
if (type != HUB_RESUME) {
/* Speed up system boot by using a delayed_work for the
* hub's initial power-up delays. This is pretty awkward
* and the implementation looks like a home-brewed sort of
* setjmp/longjmp, but it saves at least 100 ms for each
* root hub (assuming usbcore is compiled into the kernel
* rather than as a module). It adds up.
*
* This can't be done for HUB_RESUME or HUB_RESET_RESUME
* because for those activation types the ports have to be
* operational when we return. In theory this could be done
* for HUB_POST_RESET, but it's easier not to.
*/
if (type == HUB_INIT) {
delay = hub_power_on(hub, false);
PREPARE_DELAYED_WORK(&hub->init_work, hub_init_func2);
schedule_delayed_work(&hub->init_work,
msecs_to_jiffies(delay));
/* Suppress autosuspend until init is done */
usb_autopm_get_interface_no_resume(
to_usb_interface(hub->intfdev));
return; /* Continues at init2: below */
} else {
hub_power_on(hub, true);
}
}
init2:
/* Check each port and set hub->change_bits to let khubd know
* which ports need attention.
*/
for (port1 = 1; port1 <= hdev->maxchild; ++port1) {
struct usb_device *udev = hdev->children[port1-1];
u16 portstatus, portchange;
portstatus = portchange = 0;
status = hub_port_status(hub, port1, &portstatus, &portchange);
if (udev || (portstatus & USB_PORT_STAT_CONNECTION))
dev_dbg(hub->intfdev,
"port %d: status %04x change %04x\n",
port1, portstatus, portchange);
/* After anything other than HUB_RESUME (i.e., initialization
* or any sort of reset), every port should be disabled.
* Unconnected ports should likewise be disabled (paranoia),
* and so should ports for which we have no usb_device.
*/
if ((portstatus & USB_PORT_STAT_ENABLE) && (
type != HUB_RESUME ||
!(portstatus & USB_PORT_STAT_CONNECTION) ||
!udev ||
udev->state == USB_STATE_NOTATTACHED)) {
/*
* USB3 protocol ports will automatically transition
* to Enabled state when detect an USB3.0 device attach.
* Do not disable USB3 protocol ports.
* FIXME: USB3 root hub and external hubs are treated
* differently here.
*/
if (hdev->descriptor.bDeviceProtocol != 3 ||
(!hdev->parent &&
!(portstatus & USB_PORT_STAT_SUPER_SPEED))) {
clear_port_feature(hdev, port1,
USB_PORT_FEAT_ENABLE);
portstatus &= ~USB_PORT_STAT_ENABLE;
}
}
/* Clear status-change flags; we'll debounce later */
if (portchange & USB_PORT_STAT_C_CONNECTION) {
need_debounce_delay = true;
clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_CONNECTION);
}
if (portchange & USB_PORT_STAT_C_ENABLE) {
need_debounce_delay = true;
clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_ENABLE);
}
/* We can forget about a "removed" device when there's a
* physical disconnect or the connect status changes.
*/
if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
(portchange & USB_PORT_STAT_C_CONNECTION))
clear_bit(port1, hub->removed_bits);
if (!udev || udev->state == USB_STATE_NOTATTACHED) {
/* Tell khubd to disconnect the device or
* check for a new connection
*/
if (udev || (portstatus & USB_PORT_STAT_CONNECTION))
set_bit(port1, hub->change_bits);
} else if (portstatus & USB_PORT_STAT_ENABLE) {
/* The power session apparently survived the resume.
* If there was an overcurrent or suspend change
* (i.e., remote wakeup request), have khubd
* take care of it.
*/
if (portchange)
set_bit(port1, hub->change_bits);
} else if (udev->persist_enabled) {
#ifdef CONFIG_PM
udev->reset_resume = 1;
#endif
set_bit(port1, hub->change_bits);
} else {
/* The power session is gone; tell khubd */
usb_set_device_state(udev, USB_STATE_NOTATTACHED);
set_bit(port1, hub->change_bits);
}
}
/* If no port-status-change flags were set, we don't need any
* debouncing. If flags were set we can try to debounce the
* ports all at once right now, instead of letting khubd do them
* one at a time later on.
*
* If any port-status changes do occur during this delay, khubd
* will see them later and handle them normally.
*/
if (need_debounce_delay) {
delay = HUB_DEBOUNCE_STABLE;
/* Don't do a long sleep inside a workqueue routine */
if (type == HUB_INIT2) {
PREPARE_DELAYED_WORK(&hub->init_work, hub_init_func3);
schedule_delayed_work(&hub->init_work,
msecs_to_jiffies(delay));
return; /* Continues at init3: below */
} else {
msleep(delay);
}
}
init3:
hub->quiescing = 0;
status = usb_submit_urb(hub->urb, GFP_NOIO);
if (status < 0)
dev_err(hub->intfdev, "activate --> %d\n", status);
if (hub->has_indicators && blinkenlights)
schedule_delayed_work(&hub->leds, LED_CYCLE_PERIOD);
/* Scan all ports that need attention */
kick_khubd(hub);
/* Allow autosuspend if it was suppressed */
if (type <= HUB_INIT3)
usb_autopm_put_interface_async(to_usb_interface(hub->intfdev));
}
/* Implement the continuations for the delays above */
static void hub_init_func2(struct work_struct *ws)
{
struct usb_hub *hub = container_of(ws, struct usb_hub, init_work.work);
hub_activate(hub, HUB_INIT2);
}
static void hub_init_func3(struct work_struct *ws)
{
struct usb_hub *hub = container_of(ws, struct usb_hub, init_work.work);
hub_activate(hub, HUB_INIT3);
}
enum hub_quiescing_type {
HUB_DISCONNECT, HUB_PRE_RESET, HUB_SUSPEND
};
static void hub_quiesce(struct usb_hub *hub, enum hub_quiescing_type type)
{
struct usb_device *hdev = hub->hdev;
int i;
cancel_delayed_work_sync(&hub->init_work);
/* khubd and related activity won't re-trigger */
hub->quiescing = 1;
if (type != HUB_SUSPEND) {
/* Disconnect all the children */
for (i = 0; i < hdev->maxchild; ++i) {
if (hdev->children[i])
usb_disconnect(&hdev->children[i]);
}
}
/* Stop khubd and related activity */
usb_kill_urb(hub->urb);
if (hub->has_indicators)
cancel_delayed_work_sync(&hub->leds);
if (hub->tt.hub)
cancel_work_sync(&hub->tt.clear_work);
}
/* caller has locked the hub device */
static int hub_pre_reset(struct usb_interface *intf)
{
struct usb_hub *hub = usb_get_intfdata(intf);
hub_quiesce(hub, HUB_PRE_RESET);
return 0;
}
/* caller has locked the hub device */
static int hub_post_reset(struct usb_interface *intf)
{
struct usb_hub *hub = usb_get_intfdata(intf);
hub_activate(hub, HUB_POST_RESET);
return 0;
}
static int hub_configure(struct usb_hub *hub,
struct usb_endpoint_descriptor *endpoint)
{
struct usb_hcd *hcd;
struct usb_device *hdev = hub->hdev;
struct device *hub_dev = hub->intfdev;
u16 hubstatus, hubchange;
u16 wHubCharacteristics;
unsigned int pipe;
int maxp, ret;
char *message = "out of memory";
hub->buffer = kmalloc(sizeof(*hub->buffer), GFP_KERNEL);
if (!hub->buffer) {
ret = -ENOMEM;
goto fail;
}
hub->status = kmalloc(sizeof(*hub->status), GFP_KERNEL);
if (!hub->status) {
ret = -ENOMEM;
goto fail;
}
mutex_init(&hub->status_mutex);
hub->descriptor = kmalloc(sizeof(*hub->descriptor), GFP_KERNEL);
if (!hub->descriptor) {
ret = -ENOMEM;
goto fail;
}
/* Request the entire hub descriptor.
* hub->descriptor can handle USB_MAXCHILDREN ports,
* but the hub can/will return fewer bytes here.
*/
ret = get_hub_descriptor(hdev, hub->descriptor,
sizeof(*hub->descriptor));
if (ret < 0) {
message = "can't read hub descriptor";
goto fail;
} else if (hub->descriptor->bNbrPorts > USB_MAXCHILDREN) {
message = "hub has too many ports!";
ret = -ENODEV;
goto fail;
}
hdev->maxchild = hub->descriptor->bNbrPorts;
dev_info (hub_dev, "%d port%s detected\n", hdev->maxchild,
(hdev->maxchild == 1) ? "" : "s");
hub->port_owners = kzalloc(hdev->maxchild * sizeof(void *), GFP_KERNEL);
if (!hub->port_owners) {
ret = -ENOMEM;
goto fail;
}
wHubCharacteristics = le16_to_cpu(hub->descriptor->wHubCharacteristics);
if (wHubCharacteristics & HUB_CHAR_COMPOUND) {
int i;
char portstr [USB_MAXCHILDREN + 1];
for (i = 0; i < hdev->maxchild; i++)
portstr[i] = hub->descriptor->DeviceRemovable
[((i + 1) / 8)] & (1 << ((i + 1) % 8))
? 'F' : 'R';
portstr[hdev->maxchild] = 0;
dev_dbg(hub_dev, "compound device; port removable status: %s\n", portstr);
} else
dev_dbg(hub_dev, "standalone hub\n");
switch (wHubCharacteristics & HUB_CHAR_LPSM) {
case 0x00:
dev_dbg(hub_dev, "ganged power switching\n");
break;
case 0x01:
dev_dbg(hub_dev, "individual port power switching\n");
break;
case 0x02:
case 0x03:
dev_dbg(hub_dev, "no power switching (usb 1.0)\n");
break;
}
switch (wHubCharacteristics & HUB_CHAR_OCPM) {
case 0x00:
dev_dbg(hub_dev, "global over-current protection\n");
break;
case 0x08:
dev_dbg(hub_dev, "individual port over-current protection\n");
break;
case 0x10:
case 0x18:
dev_dbg(hub_dev, "no over-current protection\n");
break;
}
spin_lock_init (&hub->tt.lock);
INIT_LIST_HEAD (&hub->tt.clear_list);
INIT_WORK(&hub->tt.clear_work, hub_tt_work);
switch (hdev->descriptor.bDeviceProtocol) {
case 0:
break;
case 1:
dev_dbg(hub_dev, "Single TT\n");
hub->tt.hub = hdev;
break;
case 2:
ret = usb_set_interface(hdev, 0, 1);
if (ret == 0) {
dev_dbg(hub_dev, "TT per port\n");
hub->tt.multi = 1;
} else
dev_err(hub_dev, "Using single TT (err %d)\n",
ret);
hub->tt.hub = hdev;
break;
case 3:
/* USB 3.0 hubs don't have a TT */
break;
default:
dev_dbg(hub_dev, "Unrecognized hub protocol %d\n",
hdev->descriptor.bDeviceProtocol);
break;
}
/* Note 8 FS bit times == (8 bits / 12000000 bps) ~= 666ns */
switch (wHubCharacteristics & HUB_CHAR_TTTT) {
case HUB_TTTT_8_BITS:
if (hdev->descriptor.bDeviceProtocol != 0) {
hub->tt.think_time = 666;
dev_dbg(hub_dev, "TT requires at most %d "
"FS bit times (%d ns)\n",
8, hub->tt.think_time);
}
break;
case HUB_TTTT_16_BITS:
hub->tt.think_time = 666 * 2;
dev_dbg(hub_dev, "TT requires at most %d "
"FS bit times (%d ns)\n",
16, hub->tt.think_time);
break;
case HUB_TTTT_24_BITS:
hub->tt.think_time = 666 * 3;
dev_dbg(hub_dev, "TT requires at most %d "
"FS bit times (%d ns)\n",
24, hub->tt.think_time);
break;
case HUB_TTTT_32_BITS:
hub->tt.think_time = 666 * 4;
dev_dbg(hub_dev, "TT requires at most %d "
"FS bit times (%d ns)\n",
32, hub->tt.think_time);
break;
}
/* probe() zeroes hub->indicator[] */
if (wHubCharacteristics & HUB_CHAR_PORTIND) {
hub->has_indicators = 1;
dev_dbg(hub_dev, "Port indicators are supported\n");
}
dev_dbg(hub_dev, "power on to power good time: %dms\n",
hub->descriptor->bPwrOn2PwrGood * 2);
/* power budgeting mostly matters with bus-powered hubs,
* and battery-powered root hubs (may provide just 8 mA).
*/
ret = usb_get_status(hdev, USB_RECIP_DEVICE, 0, &hubstatus);
if (ret < 2) {
message = "can't get hub status";
goto fail;
}
le16_to_cpus(&hubstatus);
if (hdev == hdev->bus->root_hub) {
if (hdev->bus_mA == 0 || hdev->bus_mA >= 500)
hub->mA_per_port = 500;
else {
hub->mA_per_port = hdev->bus_mA;
hub->limited_power = 1;
}
} else if ((hubstatus & (1 << USB_DEVICE_SELF_POWERED)) == 0) {
dev_dbg(hub_dev, "hub controller current requirement: %dmA\n",
hub->descriptor->bHubContrCurrent);
hub->limited_power = 1;
if (hdev->maxchild > 0) {
int remaining = hdev->bus_mA -
hub->descriptor->bHubContrCurrent;
if (remaining < hdev->maxchild * 100)
dev_warn(hub_dev,
"insufficient power available "
"to use all downstream ports\n");
hub->mA_per_port = 100; /* 7.2.1.1 */
}
} else { /* Self-powered external hub */
/* FIXME: What about battery-powered external hubs that
* provide less current per port? */
hub->mA_per_port = 500;
}
if (hub->mA_per_port < 500)
dev_dbg(hub_dev, "%umA bus power budget for each child\n",
hub->mA_per_port);
/* Update the HCD's internal representation of this hub before khubd
* starts getting port status changes for devices under the hub.
*/
hcd = bus_to_hcd(hdev->bus);
if (hcd->driver->update_hub_device) {
ret = hcd->driver->update_hub_device(hcd, hdev,
&hub->tt, GFP_KERNEL);
if (ret < 0) {
message = "can't update HCD hub info";
goto fail;
}
}
ret = hub_hub_status(hub, &hubstatus, &hubchange);
if (ret < 0) {
message = "can't get hub status";
goto fail;
}
/* local power status reports aren't always correct */
if (hdev->actconfig->desc.bmAttributes & USB_CONFIG_ATT_SELFPOWER)
dev_dbg(hub_dev, "local power source is %s\n",
(hubstatus & HUB_STATUS_LOCAL_POWER)
? "lost (inactive)" : "good");
if ((wHubCharacteristics & HUB_CHAR_OCPM) == 0)
dev_dbg(hub_dev, "%sover-current condition exists\n",
(hubstatus & HUB_STATUS_OVERCURRENT) ? "" : "no ");
/* set up the interrupt endpoint
* We use the EP's maxpacket size instead of (PORTS+1+7)/8
* bytes as USB2.0[11.12.3] says because some hubs are known
* to send more data (and thus cause overflow). For root hubs,
* maxpktsize is defined in hcd.c's fake endpoint descriptors
* to be big enough for at least USB_MAXCHILDREN ports. */
pipe = usb_rcvintpipe(hdev, endpoint->bEndpointAddress);
maxp = usb_maxpacket(hdev, pipe, usb_pipeout(pipe));
if (maxp > sizeof(*hub->buffer))
maxp = sizeof(*hub->buffer);
hub->urb = usb_alloc_urb(0, GFP_KERNEL);
if (!hub->urb) {
ret = -ENOMEM;
goto fail;
}
usb_fill_int_urb(hub->urb, hdev, pipe, *hub->buffer, maxp, hub_irq,
hub, endpoint->bInterval);
/* maybe cycle the hub leds */
if (hub->has_indicators && blinkenlights)
hub->indicator [0] = INDICATOR_CYCLE;
hub_activate(hub, HUB_INIT);
return 0;
fail:
dev_err (hub_dev, "config failed, %s (err %d)\n",
message, ret);
/* hub_disconnect() frees urb and descriptor */
return ret;
}
static void hub_release(struct kref *kref)
{
struct usb_hub *hub = container_of(kref, struct usb_hub, kref);
usb_put_intf(to_usb_interface(hub->intfdev));
kfree(hub);
}
static unsigned highspeed_hubs;
static void hub_disconnect(struct usb_interface *intf)
{
struct usb_hub *hub = usb_get_intfdata (intf);
/* Take the hub off the event list and don't let it be added again */
spin_lock_irq(&hub_event_lock);
if (!list_empty(&hub->event_list)) {
list_del_init(&hub->event_list);
usb_autopm_put_interface_no_suspend(intf);
}
hub->disconnected = 1;
spin_unlock_irq(&hub_event_lock);
/* Disconnect all children and quiesce the hub */
hub->error = 0;
hub_quiesce(hub, HUB_DISCONNECT);
usb_set_intfdata (intf, NULL);
hub->hdev->maxchild = 0;
if (hub->hdev->speed == USB_SPEED_HIGH)
highspeed_hubs--;
usb_free_urb(hub->urb);
kfree(hub->port_owners);
kfree(hub->descriptor);
kfree(hub->status);
kfree(hub->buffer);
kref_put(&hub->kref, hub_release);
}
static int hub_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct usb_host_interface *desc;
struct usb_endpoint_descriptor *endpoint;
struct usb_device *hdev;
struct usb_hub *hub;
desc = intf->cur_altsetting;
hdev = interface_to_usbdev(intf);
/* Hubs have proper suspend/resume support */
usb_enable_autosuspend(hdev);
if (hdev->level == MAX_TOPO_LEVEL) {
dev_err(&intf->dev,
"Unsupported bus topology: hub nested too deep\n");
return -E2BIG;
}
#ifdef CONFIG_USB_OTG_BLACKLIST_HUB
if (hdev->parent) {
dev_warn(&intf->dev, "ignoring external hub\n");
return -ENODEV;
}
#endif
/* Some hubs have a subclass of 1, which AFAICT according to the */
/* specs is not defined, but it works */
if ((desc->desc.bInterfaceSubClass != 0) &&
(desc->desc.bInterfaceSubClass != 1)) {
descriptor_error:
dev_err (&intf->dev, "bad descriptor, ignoring hub\n");
return -EIO;
}
/* Multiple endpoints? What kind of mutant ninja-hub is this? */
if (desc->desc.bNumEndpoints != 1)
goto descriptor_error;
endpoint = &desc->endpoint[0].desc;
/* If it's not an interrupt in endpoint, we'd better punt! */
if (!usb_endpoint_is_int_in(endpoint))
goto descriptor_error;
/* We found a hub */
dev_info (&intf->dev, "USB hub found\n");
hub = kzalloc(sizeof(*hub), GFP_KERNEL);
if (!hub) {
dev_dbg (&intf->dev, "couldn't kmalloc hub struct\n");
return -ENOMEM;
}
kref_init(&hub->kref);
INIT_LIST_HEAD(&hub->event_list);
hub->intfdev = &intf->dev;
hub->hdev = hdev;
INIT_DELAYED_WORK(&hub->leds, led_work);
INIT_DELAYED_WORK(&hub->init_work, NULL);
usb_get_intf(intf);
usb_set_intfdata (intf, hub);
intf->needs_remote_wakeup = 1;
if (hdev->speed == USB_SPEED_HIGH)
highspeed_hubs++;
if (hub_configure(hub, endpoint) >= 0)
return 0;
hub_disconnect (intf);
return -ENODEV;
}
static int
hub_ioctl(struct usb_interface *intf, unsigned int code, void *user_data)
{
struct usb_device *hdev = interface_to_usbdev (intf);
/* assert ifno == 0 (part of hub spec) */
switch (code) {
case USBDEVFS_HUB_PORTINFO: {
struct usbdevfs_hub_portinfo *info = user_data;
int i;
spin_lock_irq(&device_state_lock);
if (hdev->devnum <= 0)
info->nports = 0;
else {
info->nports = hdev->maxchild;
for (i = 0; i < info->nports; i++) {
if (hdev->children[i] == NULL)
info->port[i] = 0;
else
info->port[i] =
hdev->children[i]->devnum;
}
}
spin_unlock_irq(&device_state_lock);
return info->nports + 1;
}
default:
return -ENOSYS;
}
}
/*
* Allow user programs to claim ports on a hub. When a device is attached
* to one of these "claimed" ports, the program will "own" the device.
*/
static int find_port_owner(struct usb_device *hdev, unsigned port1,
void ***ppowner)
{
if (hdev->state == USB_STATE_NOTATTACHED)
return -ENODEV;
if (port1 == 0 || port1 > hdev->maxchild)
return -EINVAL;
/* This assumes that devices not managed by the hub driver
* will always have maxchild equal to 0.
*/
*ppowner = &(hdev_to_hub(hdev)->port_owners[port1 - 1]);
return 0;
}
/* In the following three functions, the caller must hold hdev's lock */
int usb_hub_claim_port(struct usb_device *hdev, unsigned port1, void *owner)
{
int rc;
void **powner;
rc = find_port_owner(hdev, port1, &powner);
if (rc)
return rc;
if (*powner)
return -EBUSY;
*powner = owner;
return rc;
}
int usb_hub_release_port(struct usb_device *hdev, unsigned port1, void *owner)
{
int rc;
void **powner;
rc = find_port_owner(hdev, port1, &powner);
if (rc)
return rc;
if (*powner != owner)
return -ENOENT;
*powner = NULL;
return rc;
}
void usb_hub_release_all_ports(struct usb_device *hdev, void *owner)
{
int n;
void **powner;
n = find_port_owner(hdev, 1, &powner);
if (n == 0) {
for (; n < hdev->maxchild; (++n, ++powner)) {
if (*powner == owner)
*powner = NULL;
}
}
}
/* The caller must hold udev's lock */
bool usb_device_is_owned(struct usb_device *udev)
{
struct usb_hub *hub;
if (udev->state == USB_STATE_NOTATTACHED || !udev->parent)
return false;
hub = hdev_to_hub(udev->parent);
return !!hub->port_owners[udev->portnum - 1];
}
static void recursively_mark_NOTATTACHED(struct usb_device *udev)
{
int i;
for (i = 0; i < udev->maxchild; ++i) {
if (udev->children[i])
recursively_mark_NOTATTACHED(udev->children[i]);
}
if (udev->state == USB_STATE_SUSPENDED)
udev->active_duration -= jiffies;
udev->state = USB_STATE_NOTATTACHED;
}
/**
* usb_set_device_state - change a device's current state (usbcore, hcds)
* @udev: pointer to device whose state should be changed
* @new_state: new state value to be stored
*
* udev->state is _not_ fully protected by the device lock. Although
* most transitions are made only while holding the lock, the state can
* can change to USB_STATE_NOTATTACHED at almost any time. This
* is so that devices can be marked as disconnected as soon as possible,
* without having to wait for any semaphores to be released. As a result,
* all changes to any device's state must be protected by the
* device_state_lock spinlock.
*
* Once a device has been added to the device tree, all changes to its state
* should be made using this routine. The state should _not_ be set directly.
*
* If udev->state is already USB_STATE_NOTATTACHED then no change is made.
* Otherwise udev->state is set to new_state, and if new_state is
* USB_STATE_NOTATTACHED then all of udev's descendants' states are also set
* to USB_STATE_NOTATTACHED.
*/
void usb_set_device_state(struct usb_device *udev,
enum usb_device_state new_state)
{
unsigned long flags;
spin_lock_irqsave(&device_state_lock, flags);
if (udev->state == USB_STATE_NOTATTACHED)
; /* do nothing */
else if (new_state != USB_STATE_NOTATTACHED) {
/* root hub wakeup capabilities are managed out-of-band
* and may involve silicon errata ... ignore them here.
*/
if (udev->parent) {
if (udev->state == USB_STATE_SUSPENDED
|| new_state == USB_STATE_SUSPENDED)
; /* No change to wakeup settings */
else if (new_state == USB_STATE_CONFIGURED)
device_set_wakeup_capable(&udev->dev,
(udev->actconfig->desc.bmAttributes
& USB_CONFIG_ATT_WAKEUP));
else
device_set_wakeup_capable(&udev->dev, 0);
}
if (udev->state == USB_STATE_SUSPENDED &&
new_state != USB_STATE_SUSPENDED)
udev->active_duration -= jiffies;
else if (new_state == USB_STATE_SUSPENDED &&
udev->state != USB_STATE_SUSPENDED)
udev->active_duration += jiffies;
udev->state = new_state;
} else
recursively_mark_NOTATTACHED(udev);
spin_unlock_irqrestore(&device_state_lock, flags);
}
EXPORT_SYMBOL_GPL(usb_set_device_state);
/*
* WUSB devices are simple: they have no hubs behind, so the mapping
* device <-> virtual port number becomes 1:1. Why? to simplify the
* life of the device connection logic in
* drivers/usb/wusbcore/devconnect.c. When we do the initial secret
* handshake we need to assign a temporary address in the unauthorized
* space. For simplicity we use the first virtual port number found to
* be free [drivers/usb/wusbcore/devconnect.c:wusbhc_devconnect_ack()]
* and that becomes it's address [X < 128] or its unauthorized address
* [X | 0x80].
*
* We add 1 as an offset to the one-based USB-stack port number
* (zero-based wusb virtual port index) for two reasons: (a) dev addr
* 0 is reserved by USB for default address; (b) Linux's USB stack
* uses always #1 for the root hub of the controller. So USB stack's
* port #1, which is wusb virtual-port #0 has address #2.
*
* Devices connected under xHCI are not as simple. The host controller
* supports virtualization, so the hardware assigns device addresses and
* the HCD must setup data structures before issuing a set address
* command to the hardware.
*/
static void choose_address(struct usb_device *udev)
{
int devnum;
struct usb_bus *bus = udev->bus;
/* If khubd ever becomes multithreaded, this will need a lock */
if (udev->wusb) {
devnum = udev->portnum + 1;
BUG_ON(test_bit(devnum, bus->devmap.devicemap));
} else {
/* Try to allocate the next devnum beginning at
* bus->devnum_next. */
devnum = find_next_zero_bit(bus->devmap.devicemap, 128,
bus->devnum_next);
if (devnum >= 128)
devnum = find_next_zero_bit(bus->devmap.devicemap,
128, 1);
bus->devnum_next = ( devnum >= 127 ? 1 : devnum + 1);
}
if (devnum < 128) {
set_bit(devnum, bus->devmap.devicemap);
udev->devnum = devnum;
}
}
static void release_address(struct usb_device *udev)
{
if (udev->devnum > 0) {
clear_bit(udev->devnum, udev->bus->devmap.devicemap);
udev->devnum = -1;
}
}
static void update_address(struct usb_device *udev, int devnum)
{
/* The address for a WUSB device is managed by wusbcore. */
if (!udev->wusb)
udev->devnum = devnum;
}
static void hub_free_dev(struct usb_device *udev)
{
struct usb_hcd *hcd = bus_to_hcd(udev->bus);
/* Root hubs aren't real devices, so don't free HCD resources */
if (hcd->driver->free_dev && udev->parent)
hcd->driver->free_dev(hcd, udev);
}
/**
* usb_disconnect - disconnect a device (usbcore-internal)
* @pdev: pointer to device being disconnected
* Context: !in_interrupt ()
*
* Something got disconnected. Get rid of it and all of its children.
*
* If *pdev is a normal device then the parent hub must already be locked.
* If *pdev is a root hub then this routine will acquire the
* usb_bus_list_lock on behalf of the caller.
*
* Only hub drivers (including virtual root hub drivers for host
* controllers) should ever call this.
*
* This call is synchronous, and may not be used in an interrupt context.
*/
void usb_disconnect(struct usb_device **pdev)
{
struct usb_device *udev = *pdev;
int i;
if (!udev) {
pr_debug ("%s nodev\n", __func__);
return;
}
/* mark the device as inactive, so any further urb submissions for
* this device (and any of its children) will fail immediately.
* this quiesces everyting except pending urbs.
*/
usb_set_device_state(udev, USB_STATE_NOTATTACHED);
dev_info (&udev->dev, "USB disconnect, address %d\n", udev->devnum);
usb_lock_device(udev);
/* Free up all the children before we remove this device */
for (i = 0; i < USB_MAXCHILDREN; i++) {
if (udev->children[i])
usb_disconnect(&udev->children[i]);
}
/* deallocate hcd/hardware state ... nuking all pending urbs and
* cleaning up all state associated with the current configuration
* so that the hardware is now fully quiesced.
*/
dev_dbg (&udev->dev, "unregistering device\n");
usb_disable_device(udev, 0);
usb_hcd_synchronize_unlinks(udev);
usb_remove_ep_devs(&udev->ep0);
usb_unlock_device(udev);
/* Unregister the device. The device driver is responsible
* for de-configuring the device and invoking the remove-device
* notifier chain (used by usbfs and possibly others).
*/
device_del(&udev->dev);
/* Free the device number and delete the parent's children[]
* (or root_hub) pointer.
*/
release_address(udev);
/* Avoid races with recursively_mark_NOTATTACHED() */
spin_lock_irq(&device_state_lock);
*pdev = NULL;
spin_unlock_irq(&device_state_lock);
hub_free_dev(udev);
put_device(&udev->dev);
}
#ifdef CONFIG_USB_ANNOUNCE_NEW_DEVICES
static void show_string(struct usb_device *udev, char *id, char *string)
{
if (!string)
return;
dev_printk(KERN_INFO, &udev->dev, "%s: %s\n", id, string);
}
static void announce_device(struct usb_device *udev)
{
dev_info(&udev->dev, "New USB device found, idVendor=%04x, idProduct=%04x\n",
le16_to_cpu(udev->descriptor.idVendor),
le16_to_cpu(udev->descriptor.idProduct));
dev_info(&udev->dev,
"New USB device strings: Mfr=%d, Product=%d, SerialNumber=%d\n",
udev->descriptor.iManufacturer,
udev->descriptor.iProduct,
udev->descriptor.iSerialNumber);
show_string(udev, "Product", udev->product);
show_string(udev, "Manufacturer", udev->manufacturer);
show_string(udev, "SerialNumber", udev->serial);
}
#else
static inline void announce_device(struct usb_device *udev) { }
#endif
#ifdef CONFIG_USB_OTG
#include "otg_whitelist.h"
#endif
/**
* usb_enumerate_device_otg - FIXME (usbcore-internal)
* @udev: newly addressed device (in ADDRESS state)
*
* Finish enumeration for On-The-Go devices
*/
static int usb_enumerate_device_otg(struct usb_device *udev)
{
int err = 0;
#ifdef CONFIG_USB_OTG
/*
* OTG-aware devices on OTG-capable root hubs may be able to use SRP,
* to wake us after we've powered off VBUS; and HNP, switching roles
* "host" to "peripheral". The OTG descriptor helps figure this out.
*/
if (!udev->bus->is_b_host
&& udev->config
&& udev->parent == udev->bus->root_hub) {
struct usb_otg_descriptor *desc = NULL;
struct usb_bus *bus = udev->bus;
/* descriptor may appear anywhere in config */
if (__usb_get_extra_descriptor (udev->rawdescriptors[0],
le16_to_cpu(udev->config[0].desc.wTotalLength),
USB_DT_OTG, (void **) &desc) == 0) {
if (desc->bmAttributes & USB_OTG_HNP) {
unsigned port1 = udev->portnum;
dev_info(&udev->dev,
"Dual-Role OTG device on %sHNP port\n",
(port1 == bus->otg_port)
? "" : "non-");
/* enable HNP before suspend, it's simpler */
if (port1 == bus->otg_port)
bus->b_hnp_enable = 1;
err = usb_control_msg(udev,
usb_sndctrlpipe(udev, 0),
USB_REQ_SET_FEATURE, 0,
bus->b_hnp_enable
? USB_DEVICE_B_HNP_ENABLE
: USB_DEVICE_A_ALT_HNP_SUPPORT,
0, NULL, 0, USB_CTRL_SET_TIMEOUT);
if (err < 0) {
/* OTG MESSAGE: report errors here,
* customize to match your product.
*/
dev_info(&udev->dev,
"can't set HNP mode: %d\n",
err);
bus->b_hnp_enable = 0;
}
}
}
}
if (!is_targeted(udev)) {
/* Maybe it can talk to us, though we can't talk to it.
* (Includes HNP test device.)
*/
if (udev->bus->b_hnp_enable || udev->bus->is_b_host) {
err = usb_port_suspend(udev, PMSG_SUSPEND);
if (err < 0)
dev_dbg(&udev->dev, "HNP fail, %d\n", err);
}
err = -ENOTSUPP;
goto fail;
}
fail:
#endif
return err;
}
/**
* usb_enumerate_device - Read device configs/intfs/otg (usbcore-internal)
* @udev: newly addressed device (in ADDRESS state)
*
* This is only called by usb_new_device() and usb_authorize_device()
* and FIXME -- all comments that apply to them apply here wrt to
* environment.
*
* If the device is WUSB and not authorized, we don't attempt to read
* the string descriptors, as they will be errored out by the device
* until it has been authorized.
*/
static int usb_enumerate_device(struct usb_device *udev)
{
int err;
if (udev->config == NULL) {
err = usb_get_configuration(udev);
if (err < 0) {
dev_err(&udev->dev, "can't read configurations, error %d\n",
err);
goto fail;
}
}
if (udev->wusb == 1 && udev->authorized == 0) {
udev->product = kstrdup("n/a (unauthorized)", GFP_KERNEL);
udev->manufacturer = kstrdup("n/a (unauthorized)", GFP_KERNEL);
udev->serial = kstrdup("n/a (unauthorized)", GFP_KERNEL);
}
else {
/* read the standard strings and cache them if present */
udev->product = usb_cache_string(udev, udev->descriptor.iProduct);
udev->manufacturer = usb_cache_string(udev,
udev->descriptor.iManufacturer);
udev->serial = usb_cache_string(udev, udev->descriptor.iSerialNumber);
}
err = usb_enumerate_device_otg(udev);
fail:
return err;
}
/**
* usb_new_device - perform initial device setup (usbcore-internal)
* @udev: newly addressed device (in ADDRESS state)
*
* This is called with devices which have been detected but not fully
* enumerated. The device descriptor is available, but not descriptors
* for any device configuration. The caller must have locked either
* the parent hub (if udev is a normal device) or else the
* usb_bus_list_lock (if udev is a root hub). The parent's pointer to
* udev has already been installed, but udev is not yet visible through
* sysfs or other filesystem code.
*
* It will return if the device is configured properly or not. Zero if
* the interface was registered with the driver core; else a negative
* errno value.
*
* This call is synchronous, and may not be used in an interrupt context.
*
* Only the hub driver or root-hub registrar should ever call this.
*/
int usb_new_device(struct usb_device *udev)
{
int err;
if (udev->parent) {
/* Initialize non-root-hub device wakeup to disabled;
* device (un)configuration controls wakeup capable
* sysfs power/wakeup controls wakeup enabled/disabled
*/
device_init_wakeup(&udev->dev, 0);
}
/* Tell the runtime-PM framework the device is active */
pm_runtime_set_active(&udev->dev);
pm_runtime_enable(&udev->dev);
err = usb_enumerate_device(udev); /* Read descriptors */
if (err < 0)
goto fail;
dev_dbg(&udev->dev, "udev %d, busnum %d, minor = %d\n",
udev->devnum, udev->bus->busnum,
(((udev->bus->busnum-1) * 128) + (udev->devnum-1)));
/* export the usbdev device-node for libusb */
udev->dev.devt = MKDEV(USB_DEVICE_MAJOR,
(((udev->bus->busnum-1) * 128) + (udev->devnum-1)));
/* Tell the world! */
announce_device(udev);
device_enable_async_suspend(&udev->dev);
/* Register the device. The device driver is responsible
* for configuring the device and invoking the add-device
* notifier chain (used by usbfs and possibly others).
*/
err = device_add(&udev->dev);
if (err) {
dev_err(&udev->dev, "can't device_add, error %d\n", err);
goto fail;
}
(void) usb_create_ep_devs(&udev->dev, &udev->ep0, udev);
return err;
fail:
usb_set_device_state(udev, USB_STATE_NOTATTACHED);
pm_runtime_disable(&udev->dev);
pm_runtime_set_suspended(&udev->dev);
return err;
}
/**
* usb_deauthorize_device - deauthorize a device (usbcore-internal)
* @usb_dev: USB device
*
* Move the USB device to a very basic state where interfaces are disabled
* and the device is in fact unconfigured and unusable.
*
* We share a lock (that we have) with device_del(), so we need to
* defer its call.
*/
int usb_deauthorize_device(struct usb_device *usb_dev)
{
usb_lock_device(usb_dev);
if (usb_dev->authorized == 0)
goto out_unauthorized;
usb_dev->authorized = 0;
usb_set_configuration(usb_dev, -1);
kfree(usb_dev->product);
usb_dev->product = kstrdup("n/a (unauthorized)", GFP_KERNEL);
kfree(usb_dev->manufacturer);
usb_dev->manufacturer = kstrdup("n/a (unauthorized)", GFP_KERNEL);
kfree(usb_dev->serial);
usb_dev->serial = kstrdup("n/a (unauthorized)", GFP_KERNEL);
usb_destroy_configuration(usb_dev);
usb_dev->descriptor.bNumConfigurations = 0;
out_unauthorized:
usb_unlock_device(usb_dev);
return 0;
}
int usb_authorize_device(struct usb_device *usb_dev)
{
int result = 0, c;
usb_lock_device(usb_dev);
if (usb_dev->authorized == 1)
goto out_authorized;
result = usb_autoresume_device(usb_dev);
if (result < 0) {
dev_err(&usb_dev->dev,
"can't autoresume for authorization: %d\n", result);
goto error_autoresume;
}
result = usb_get_device_descriptor(usb_dev, sizeof(usb_dev->descriptor));
if (result < 0) {
dev_err(&usb_dev->dev, "can't re-read device descriptor for "
"authorization: %d\n", result);
goto error_device_descriptor;
}
kfree(usb_dev->product);
usb_dev->product = NULL;
kfree(usb_dev->manufacturer);
usb_dev->manufacturer = NULL;
kfree(usb_dev->serial);
usb_dev->serial = NULL;
usb_dev->authorized = 1;
result = usb_enumerate_device(usb_dev);
if (result < 0)
goto error_enumerate;
/* Choose and set the configuration. This registers the interfaces
* with the driver core and lets interface drivers bind to them.
*/
c = usb_choose_configuration(usb_dev);
if (c >= 0) {
result = usb_set_configuration(usb_dev, c);
if (result) {
dev_err(&usb_dev->dev,
"can't set config #%d, error %d\n", c, result);
/* This need not be fatal. The user can try to
* set other configurations. */
}
}
dev_info(&usb_dev->dev, "authorized to connect\n");
error_enumerate:
error_device_descriptor:
usb_autosuspend_device(usb_dev);
error_autoresume:
out_authorized:
usb_unlock_device(usb_dev); // complements locktree
return result;
}
/* Returns 1 if @hub is a WUSB root hub, 0 otherwise */
static unsigned hub_is_wusb(struct usb_hub *hub)
{
struct usb_hcd *hcd;
if (hub->hdev->parent != NULL) /* not a root hub? */
return 0;
hcd = container_of(hub->hdev->bus, struct usb_hcd, self);
return hcd->wireless;
}
#define PORT_RESET_TRIES 5
#define SET_ADDRESS_TRIES 2
#define GET_DESCRIPTOR_TRIES 2
#define SET_CONFIG_TRIES (2 * (use_both_schemes + 1))
#define USE_NEW_SCHEME(i) ((i) / 2 == old_scheme_first)
#define HUB_ROOT_RESET_TIME 50 /* times are in msec */
#define HUB_SHORT_RESET_TIME 10
#define HUB_LONG_RESET_TIME 200
#define HUB_RESET_TIMEOUT 500
static int hub_port_wait_reset(struct usb_hub *hub, int port1,
struct usb_device *udev, unsigned int delay)
{
int delay_time, ret;
u16 portstatus;
u16 portchange;
for (delay_time = 0;
delay_time < HUB_RESET_TIMEOUT;
delay_time += delay) {
/* wait to give the device a chance to reset */
msleep(delay);
/* read and decode port status */
ret = hub_port_status(hub, port1, &portstatus, &portchange);
if (ret < 0)
return ret;
/* Device went away? */
if (!(portstatus & USB_PORT_STAT_CONNECTION))
return -ENOTCONN;
/* bomb out completely if the connection bounced */
if ((portchange & USB_PORT_STAT_C_CONNECTION))
return -ENOTCONN;
/* if we`ve finished resetting, then break out of the loop */
if (!(portstatus & USB_PORT_STAT_RESET) &&
(portstatus & USB_PORT_STAT_ENABLE)) {
if (hub_is_wusb(hub))
udev->speed = USB_SPEED_WIRELESS;
else if (portstatus & USB_PORT_STAT_SUPER_SPEED)
udev->speed = USB_SPEED_SUPER;
else if (portstatus & USB_PORT_STAT_HIGH_SPEED)
udev->speed = USB_SPEED_HIGH;
else if (portstatus & USB_PORT_STAT_LOW_SPEED)
udev->speed = USB_SPEED_LOW;
else
udev->speed = USB_SPEED_FULL;
return 0;
}
/* switch to the long delay after two short delay failures */
if (delay_time >= 2 * HUB_SHORT_RESET_TIME)
delay = HUB_LONG_RESET_TIME;
dev_dbg (hub->intfdev,
"port %d not reset yet, waiting %dms\n",
port1, delay);
}
return -EBUSY;
}
static int hub_port_reset(struct usb_hub *hub, int port1,
struct usb_device *udev, unsigned int delay)
{
int i, status;
struct usb_hcd *hcd;
hcd = bus_to_hcd(udev->bus);
/* Block EHCI CF initialization during the port reset.
* Some companion controllers don't like it when they mix.
*/
down_read(&ehci_cf_port_reset_rwsem);
/* Reset the port */
for (i = 0; i < PORT_RESET_TRIES; i++) {
status = set_port_feature(hub->hdev,
port1, USB_PORT_FEAT_RESET);
if (status)
dev_err(hub->intfdev,
"cannot reset port %d (err = %d)\n",
port1, status);
else {
status = hub_port_wait_reset(hub, port1, udev, delay);
if (status && status != -ENOTCONN)
dev_dbg(hub->intfdev,
"port_wait_reset: err = %d\n",
status);
}
/* return on disconnect or reset */
switch (status) {
case 0:
/* TRSTRCY = 10 ms; plus some extra */
msleep(10 + 40);
update_address(udev, 0);
if (hcd->driver->reset_device) {
status = hcd->driver->reset_device(hcd, udev);
if (status < 0) {
dev_err(&udev->dev, "Cannot reset "
"HCD device state\n");
break;
}
}
/* FALL THROUGH */
case -ENOTCONN:
case -ENODEV:
clear_port_feature(hub->hdev,
port1, USB_PORT_FEAT_C_RESET);
/* FIXME need disconnect() for NOTATTACHED device */
usb_set_device_state(udev, status
? USB_STATE_NOTATTACHED
: USB_STATE_DEFAULT);
goto done;
}
dev_dbg (hub->intfdev,
"port %d not enabled, trying reset again...\n",
port1);
delay = HUB_LONG_RESET_TIME;
}
dev_err (hub->intfdev,
"Cannot enable port %i. Maybe the USB cable is bad?\n",
port1);
done:
up_read(&ehci_cf_port_reset_rwsem);
return status;
}
#ifdef CONFIG_PM
#define MASK_BITS (USB_PORT_STAT_POWER | USB_PORT_STAT_CONNECTION | \
USB_PORT_STAT_SUSPEND)
#define WANT_BITS (USB_PORT_STAT_POWER | USB_PORT_STAT_CONNECTION)
/* Determine whether the device on a port is ready for a normal resume,
* is ready for a reset-resume, or should be disconnected.
*/
static int check_port_resume_type(struct usb_device *udev,
struct usb_hub *hub, int port1,
int status, unsigned portchange, unsigned portstatus)
{
/* Is the device still present? */
if (status || (portstatus & MASK_BITS) != WANT_BITS) {
if (status >= 0)
status = -ENODEV;
}
/* Can't do a normal resume if the port isn't enabled,
* so try a reset-resume instead.
*/
else if (!(portstatus & USB_PORT_STAT_ENABLE) && !udev->reset_resume) {
if (udev->persist_enabled)
udev->reset_resume = 1;
else
status = -ENODEV;
}
if (status) {
dev_dbg(hub->intfdev,
"port %d status %04x.%04x after resume, %d\n",
port1, portchange, portstatus, status);
} else if (udev->reset_resume) {
/* Late port handoff can set status-change bits */
if (portchange & USB_PORT_STAT_C_CONNECTION)
clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_CONNECTION);
if (portchange & USB_PORT_STAT_C_ENABLE)
clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_ENABLE);
}
return status;
}
#ifdef CONFIG_USB_SUSPEND
/*
* usb_port_suspend - suspend a usb device's upstream port
* @udev: device that's no longer in active use, not a root hub
* Context: must be able to sleep; device not locked; pm locks held
*
* Suspends a USB device that isn't in active use, conserving power.
* Devices may wake out of a suspend, if anything important happens,
* using the remote wakeup mechanism. They may also be taken out of
* suspend by the host, using usb_port_resume(). It's also routine
* to disconnect devices while they are suspended.
*
* This only affects the USB hardware for a device; its interfaces
* (and, for hubs, child devices) must already have been suspended.
*
* Selective port suspend reduces power; most suspended devices draw
* less than 500 uA. It's also used in OTG, along with remote wakeup.
* All devices below the suspended port are also suspended.
*
* Devices leave suspend state when the host wakes them up. Some devices
* also support "remote wakeup", where the device can activate the USB
* tree above them to deliver data, such as a keypress or packet. In
* some cases, this wakes the USB host.
*
* Suspending OTG devices may trigger HNP, if that's been enabled
* between a pair of dual-role devices. That will change roles, such
* as from A-Host to A-Peripheral or from B-Host back to B-Peripheral.
*
* Devices on USB hub ports have only one "suspend" state, corresponding
* to ACPI D2, "may cause the device to lose some context".
* State transitions include:
*
* - suspend, resume ... when the VBUS power link stays live
* - suspend, disconnect ... VBUS lost
*
* Once VBUS drop breaks the circuit, the port it's using has to go through
* normal re-enumeration procedures, starting with enabling VBUS power.
* Other than re-initializing the hub (plug/unplug, except for root hubs),
* Linux (2.6) currently has NO mechanisms to initiate that: no khubd
* timer, no SRP, no requests through sysfs.
*
* If CONFIG_USB_SUSPEND isn't enabled, devices only really suspend when
* the root hub for their bus goes into global suspend ... so we don't
* (falsely) update the device power state to say it suspended.
*
* Returns 0 on success, else negative errno.
*/
int usb_port_suspend(struct usb_device *udev, pm_message_t msg)
{
struct usb_hub *hub = hdev_to_hub(udev->parent);
int port1 = udev->portnum;
int status;
// dev_dbg(hub->intfdev, "suspend port %d\n", port1);
/* enable remote wakeup when appropriate; this lets the device
* wake up the upstream hub (including maybe the root hub).
*
* NOTE: OTG devices may issue remote wakeup (or SRP) even when
* we don't explicitly enable it here.
*/
if (udev->do_remote_wakeup) {
status = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
USB_REQ_SET_FEATURE, USB_RECIP_DEVICE,
USB_DEVICE_REMOTE_WAKEUP, 0,
NULL, 0,
USB_CTRL_SET_TIMEOUT);
if (status) {
dev_dbg(&udev->dev, "won't remote wakeup, status %d\n",
status);
/* bail if autosuspend is requested */
if (msg.event & PM_EVENT_AUTO)
return status;
}
}
/* see 7.1.7.6 */
status = set_port_feature(hub->hdev, port1, USB_PORT_FEAT_SUSPEND);
if (status) {
dev_dbg(hub->intfdev, "can't suspend port %d, status %d\n",
port1, status);
/* paranoia: "should not happen" */
if (udev->do_remote_wakeup)
(void) usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
USB_REQ_CLEAR_FEATURE, USB_RECIP_DEVICE,
USB_DEVICE_REMOTE_WAKEUP, 0,
NULL, 0,
USB_CTRL_SET_TIMEOUT);
} else {
/* device has up to 10 msec to fully suspend */
dev_dbg(&udev->dev, "usb %ssuspend\n",
(msg.event & PM_EVENT_AUTO ? "auto-" : ""));
usb_set_device_state(udev, USB_STATE_SUSPENDED);
msleep(10);
}
return status;
}
/*
* If the USB "suspend" state is in use (rather than "global suspend"),
* many devices will be individually taken out of suspend state using
* special "resume" signaling. This routine kicks in shortly after
* hardware resume signaling is finished, either because of selective
* resume (by host) or remote wakeup (by device) ... now see what changed
* in the tree that's rooted at this device.
*
* If @udev->reset_resume is set then the device is reset before the
* status check is done.
*/
static int finish_port_resume(struct usb_device *udev)
{
int status = 0;
u16 devstatus;
/* caller owns the udev device lock */
dev_dbg(&udev->dev, "%s\n",
udev->reset_resume ? "finish reset-resume" : "finish resume");
/* usb ch9 identifies four variants of SUSPENDED, based on what
* state the device resumes to. Linux currently won't see the
* first two on the host side; they'd be inside hub_port_init()
* during many timeouts, but khubd can't suspend until later.
*/
usb_set_device_state(udev, udev->actconfig
? USB_STATE_CONFIGURED
: USB_STATE_ADDRESS);
/* 10.5.4.5 says not to reset a suspended port if the attached
* device is enabled for remote wakeup. Hence the reset
* operation is carried out here, after the port has been
* resumed.
*/
if (udev->reset_resume)
retry_reset_resume:
status = usb_reset_and_verify_device(udev);
/* 10.5.4.5 says be sure devices in the tree are still there.
* For now let's assume the device didn't go crazy on resume,
* and device drivers will know about any resume quirks.
*/
if (status == 0) {
devstatus = 0;
status = usb_get_status(udev, USB_RECIP_DEVICE, 0, &devstatus);
if (status >= 0)
status = (status > 0 ? 0 : -ENODEV);
/* If a normal resume failed, try doing a reset-resume */
if (status && !udev->reset_resume && udev->persist_enabled) {
dev_dbg(&udev->dev, "retry with reset-resume\n");
udev->reset_resume = 1;
goto retry_reset_resume;
}
}
if (status) {
dev_dbg(&udev->dev, "gone after usb resume? status %d\n",
status);
} else if (udev->actconfig) {
le16_to_cpus(&devstatus);
if (devstatus & (1 << USB_DEVICE_REMOTE_WAKEUP)) {
status = usb_control_msg(udev,
usb_sndctrlpipe(udev, 0),
USB_REQ_CLEAR_FEATURE,
USB_RECIP_DEVICE,
USB_DEVICE_REMOTE_WAKEUP, 0,
NULL, 0,
USB_CTRL_SET_TIMEOUT);
if (status)
dev_dbg(&udev->dev,
"disable remote wakeup, status %d\n",
status);
}
status = 0;
}
return status;
}
/*
* usb_port_resume - re-activate a suspended usb device's upstream port
* @udev: device to re-activate, not a root hub
* Context: must be able to sleep; device not locked; pm locks held
*
* This will re-activate the suspended device, increasing power usage
* while letting drivers communicate again with its endpoints.
* USB resume explicitly guarantees that the power session between
* the host and the device is the same as it was when the device
* suspended.
*
* If @udev->reset_resume is set then this routine won't check that the
* port is still enabled. Furthermore, finish_port_resume() above will
* reset @udev. The end result is that a broken power session can be
* recovered and @udev will appear to persist across a loss of VBUS power.
*
* For example, if a host controller doesn't maintain VBUS suspend current
* during a system sleep or is reset when the system wakes up, all the USB
* power sessions below it will be broken. This is especially troublesome
* for mass-storage devices containing mounted filesystems, since the
* device will appear to have disconnected and all the memory mappings
* to it will be lost. Using the USB_PERSIST facility, the device can be
* made to appear as if it had not disconnected.
*
* This facility can be dangerous. Although usb_reset_and_verify_device() makes
* every effort to insure that the same device is present after the
* reset as before, it cannot provide a 100% guarantee. Furthermore it's
* quite possible for a device to remain unaltered but its media to be
* changed. If the user replaces a flash memory card while the system is
* asleep, he will have only himself to blame when the filesystem on the
* new card is corrupted and the system crashes.
*
* Returns 0 on success, else negative errno.
*/
int usb_port_resume(struct usb_device *udev, pm_message_t msg)
{
struct usb_hub *hub = hdev_to_hub(udev->parent);
int port1 = udev->portnum;
int status;
u16 portchange, portstatus;
/* Skip the initial Clear-Suspend step for a remote wakeup */
status = hub_port_status(hub, port1, &portstatus, &portchange);
if (status == 0 && !(portstatus & USB_PORT_STAT_SUSPEND))
goto SuspendCleared;
// dev_dbg(hub->intfdev, "resume port %d\n", port1);
set_bit(port1, hub->busy_bits);
/* see 7.1.7.7; affects power usage, but not budgeting */
status = clear_port_feature(hub->hdev,
port1, USB_PORT_FEAT_SUSPEND);
if (status) {
dev_dbg(hub->intfdev, "can't resume port %d, status %d\n",
port1, status);
} else {
/* drive resume for at least 20 msec */
dev_dbg(&udev->dev, "usb %sresume\n",
(msg.event & PM_EVENT_AUTO ? "auto-" : ""));
msleep(25);
/* Virtual root hubs can trigger on GET_PORT_STATUS to
* stop resume signaling. Then finish the resume
* sequence.
*/
status = hub_port_status(hub, port1, &portstatus, &portchange);
/* TRSMRCY = 10 msec */
msleep(10);
}
SuspendCleared:
if (status == 0) {
if (portchange & USB_PORT_STAT_C_SUSPEND)
clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_SUSPEND);
}
clear_bit(port1, hub->busy_bits);
status = check_port_resume_type(udev,
hub, port1, status, portchange, portstatus);
if (status == 0)
status = finish_port_resume(udev);
if (status < 0) {
dev_dbg(&udev->dev, "can't resume, status %d\n", status);
hub_port_logical_disconnect(hub, port1);
}
return status;
}
/* caller has locked udev */
int usb_remote_wakeup(struct usb_device *udev)
{
int status = 0;
if (udev->state == USB_STATE_SUSPENDED) {
dev_dbg(&udev->dev, "usb %sresume\n", "wakeup-");
status = usb_autoresume_device(udev);
if (status == 0) {
/* Let the drivers do their thing, then... */
usb_autosuspend_device(udev);
}
}
return status;
}
#else /* CONFIG_USB_SUSPEND */
/* When CONFIG_USB_SUSPEND isn't set, we never suspend or resume any ports. */
int usb_port_suspend(struct usb_device *udev, pm_message_t msg)
{
return 0;
}
/* However we may need to do a reset-resume */
int usb_port_resume(struct usb_device *udev, pm_message_t msg)
{
struct usb_hub *hub = hdev_to_hub(udev->parent);
int port1 = udev->portnum;
int status;
u16 portchange, portstatus;
status = hub_port_status(hub, port1, &portstatus, &portchange);
status = check_port_resume_type(udev,
hub, port1, status, portchange, portstatus);
if (status) {
dev_dbg(&udev->dev, "can't resume, status %d\n", status);
hub_port_logical_disconnect(hub, port1);
} else if (udev->reset_resume) {
dev_dbg(&udev->dev, "reset-resume\n");
status = usb_reset_and_verify_device(udev);
}
return status;
}
#endif
static int hub_suspend(struct usb_interface *intf, pm_message_t msg)
{
struct usb_hub *hub = usb_get_intfdata (intf);
struct usb_device *hdev = hub->hdev;
unsigned port1;
/* fail if children aren't already suspended */
for (port1 = 1; port1 <= hdev->maxchild; port1++) {
struct usb_device *udev;
udev = hdev->children [port1-1];
if (udev && udev->can_submit) {
if (!(msg.event & PM_EVENT_AUTO))
dev_dbg(&intf->dev, "port %d nyet suspended\n",
port1);
return -EBUSY;
}
}
dev_dbg(&intf->dev, "%s\n", __func__);
/* stop khubd and related activity */
hub_quiesce(hub, HUB_SUSPEND);
return 0;
}
static int hub_resume(struct usb_interface *intf)
{
struct usb_hub *hub = usb_get_intfdata(intf);
dev_dbg(&intf->dev, "%s\n", __func__);
hub_activate(hub, HUB_RESUME);
return 0;
}
static int hub_reset_resume(struct usb_interface *intf)
{
struct usb_hub *hub = usb_get_intfdata(intf);
dev_dbg(&intf->dev, "%s\n", __func__);
hub_activate(hub, HUB_RESET_RESUME);
return 0;
}
/**
* usb_root_hub_lost_power - called by HCD if the root hub lost Vbus power
* @rhdev: struct usb_device for the root hub
*
* The USB host controller driver calls this function when its root hub
* is resumed and Vbus power has been interrupted or the controller
* has been reset. The routine marks @rhdev as having lost power.
* When the hub driver is resumed it will take notice and carry out
* power-session recovery for all the "USB-PERSIST"-enabled child devices;
* the others will be disconnected.
*/
void usb_root_hub_lost_power(struct usb_device *rhdev)
{
dev_warn(&rhdev->dev, "root hub lost power or was reset\n");
rhdev->reset_resume = 1;
}
EXPORT_SYMBOL_GPL(usb_root_hub_lost_power);
#else /* CONFIG_PM */
#define hub_suspend NULL
#define hub_resume NULL
#define hub_reset_resume NULL
#endif
/* USB 2.0 spec, 7.1.7.3 / fig 7-29:
*
* Between connect detection and reset signaling there must be a delay
* of 100ms at least for debounce and power-settling. The corresponding
* timer shall restart whenever the downstream port detects a disconnect.
*
* Apparently there are some bluetooth and irda-dongles and a number of
* low-speed devices for which this debounce period may last over a second.
* Not covered by the spec - but easy to deal with.
*
* This implementation uses a 1500ms total debounce timeout; if the
* connection isn't stable by then it returns -ETIMEDOUT. It checks
* every 25ms for transient disconnects. When the port status has been
* unchanged for 100ms it returns the port status.
*/
static int hub_port_debounce(struct usb_hub *hub, int port1)
{
int ret;
int total_time, stable_time = 0;
u16 portchange, portstatus;
unsigned connection = 0xffff;
for (total_time = 0; ; total_time += HUB_DEBOUNCE_STEP) {
ret = hub_port_status(hub, port1, &portstatus, &portchange);
if (ret < 0)
return ret;
if (!(portchange & USB_PORT_STAT_C_CONNECTION) &&
(portstatus & USB_PORT_STAT_CONNECTION) == connection) {
stable_time += HUB_DEBOUNCE_STEP;
if (stable_time >= HUB_DEBOUNCE_STABLE)
break;
} else {
stable_time = 0;
connection = portstatus & USB_PORT_STAT_CONNECTION;
}
if (portchange & USB_PORT_STAT_C_CONNECTION) {
clear_port_feature(hub->hdev, port1,
USB_PORT_FEAT_C_CONNECTION);
}
if (total_time >= HUB_DEBOUNCE_TIMEOUT)
break;
msleep(HUB_DEBOUNCE_STEP);
}
dev_dbg (hub->intfdev,
"debounce: port %d: total %dms stable %dms status 0x%x\n",
port1, total_time, stable_time, portstatus);
if (stable_time < HUB_DEBOUNCE_STABLE)
return -ETIMEDOUT;
return portstatus;
}
void usb_ep0_reinit(struct usb_device *udev)
{
usb_disable_endpoint(udev, 0 + USB_DIR_IN, true);
usb_disable_endpoint(udev, 0 + USB_DIR_OUT, true);
usb_enable_endpoint(udev, &udev->ep0, true);
}
EXPORT_SYMBOL_GPL(usb_ep0_reinit);
#define usb_sndaddr0pipe() (PIPE_CONTROL << 30)
#define usb_rcvaddr0pipe() ((PIPE_CONTROL << 30) | USB_DIR_IN)
static int hub_set_address(struct usb_device *udev, int devnum)
{
int retval;
struct usb_hcd *hcd = bus_to_hcd(udev->bus);
/*
* The host controller will choose the device address,
* instead of the core having chosen it earlier
*/
if (!hcd->driver->address_device && devnum <= 1)
return -EINVAL;
if (udev->state == USB_STATE_ADDRESS)
return 0;
if (udev->state != USB_STATE_DEFAULT)
return -EINVAL;
if (hcd->driver->address_device) {
retval = hcd->driver->address_device(hcd, udev);
} else {
retval = usb_control_msg(udev, usb_sndaddr0pipe(),
USB_REQ_SET_ADDRESS, 0, devnum, 0,
NULL, 0, USB_CTRL_SET_TIMEOUT);
if (retval == 0)
update_address(udev, devnum);
}
if (retval == 0) {
/* Device now using proper address. */
usb_set_device_state(udev, USB_STATE_ADDRESS);
usb_ep0_reinit(udev);
}
return retval;
}
/* Reset device, (re)assign address, get device descriptor.
* Device connection must be stable, no more debouncing needed.
* Returns device in USB_STATE_ADDRESS, except on error.
*
* If this is called for an already-existing device (as part of
* usb_reset_and_verify_device), the caller must own the device lock. For a
* newly detected device that is not accessible through any global
* pointers, it's not necessary to lock the device.
*/
static int
hub_port_init (struct usb_hub *hub, struct usb_device *udev, int port1,
int retry_counter)
{
static DEFINE_MUTEX(usb_address0_mutex);
struct usb_device *hdev = hub->hdev;
struct usb_hcd *hcd = bus_to_hcd(hdev->bus);
int i, j, retval;
unsigned delay = HUB_SHORT_RESET_TIME;
enum usb_device_speed oldspeed = udev->speed;
char *speed, *type;
int devnum = udev->devnum;
/* root hub ports have a slightly longer reset period
* (from USB 2.0 spec, section 7.1.7.5)
*/
if (!hdev->parent) {
delay = HUB_ROOT_RESET_TIME;
if (port1 == hdev->bus->otg_port)
hdev->bus->b_hnp_enable = 0;
}
/* Some low speed devices have problems with the quick delay, so */
/* be a bit pessimistic with those devices. RHbug #23670 */
if (oldspeed == USB_SPEED_LOW)
delay = HUB_LONG_RESET_TIME;
mutex_lock(&usb_address0_mutex);
if (!udev->config && oldspeed == USB_SPEED_SUPER) {
/* Don't reset USB 3.0 devices during an initial setup */
usb_set_device_state(udev, USB_STATE_DEFAULT);
} else {
/* Reset the device; full speed may morph to high speed */
/* FIXME a USB 2.0 device may morph into SuperSpeed on reset. */
retval = hub_port_reset(hub, port1, udev, delay);
if (retval < 0) /* error or disconnect */
goto fail;
/* success, speed is known */
}
retval = -ENODEV;
if (oldspeed != USB_SPEED_UNKNOWN && oldspeed != udev->speed) {
dev_dbg(&udev->dev, "device reset changed speed!\n");
goto fail;
}
oldspeed = udev->speed;
/* USB 2.0 section 5.5.3 talks about ep0 maxpacket ...
* it's fixed size except for full speed devices.
* For Wireless USB devices, ep0 max packet is always 512 (tho
* reported as 0xff in the device descriptor). WUSB1.0[4.8.1].
*/
switch (udev->speed) {
case USB_SPEED_SUPER:
case USB_SPEED_WIRELESS: /* fixed at 512 */
udev->ep0.desc.wMaxPacketSize = cpu_to_le16(512);
break;
case USB_SPEED_HIGH: /* fixed at 64 */
udev->ep0.desc.wMaxPacketSize = cpu_to_le16(64);
break;
case USB_SPEED_FULL: /* 8, 16, 32, or 64 */
/* to determine the ep0 maxpacket size, try to read
* the device descriptor to get bMaxPacketSize0 and
* then correct our initial guess.
*/
udev->ep0.desc.wMaxPacketSize = cpu_to_le16(64);
break;
case USB_SPEED_LOW: /* fixed at 8 */
udev->ep0.desc.wMaxPacketSize = cpu_to_le16(8);
break;
default:
goto fail;
}
type = "";
switch (udev->speed) {
case USB_SPEED_LOW: speed = "low"; break;
case USB_SPEED_FULL: speed = "full"; break;
case USB_SPEED_HIGH: speed = "high"; break;
case USB_SPEED_SUPER:
speed = "super";
break;
case USB_SPEED_WIRELESS:
speed = "variable";
type = "Wireless ";
break;
default: speed = "?"; break;
}
if (udev->speed != USB_SPEED_SUPER)
dev_info(&udev->dev,
"%s %s speed %sUSB device using %s and address %d\n",
(udev->config) ? "reset" : "new", speed, type,
udev->bus->controller->driver->name, devnum);
/* Set up TT records, if needed */
if (hdev->tt) {
udev->tt = hdev->tt;
udev->ttport = hdev->ttport;
} else if (udev->speed != USB_SPEED_HIGH
&& hdev->speed == USB_SPEED_HIGH) {
udev->tt = &hub->tt;
udev->ttport = port1;
}
/* Why interleave GET_DESCRIPTOR and SET_ADDRESS this way?
* Because device hardware and firmware is sometimes buggy in
* this area, and this is how Linux has done it for ages.
* Change it cautiously.
*
* NOTE: If USE_NEW_SCHEME() is true we will start by issuing
* a 64-byte GET_DESCRIPTOR request. This is what Windows does,
* so it may help with some non-standards-compliant devices.
* Otherwise we start with SET_ADDRESS and then try to read the
* first 8 bytes of the device descriptor to get the ep0 maxpacket
* value.
*/
for (i = 0; i < GET_DESCRIPTOR_TRIES; (++i, msleep(100))) {
/*
* An xHCI controller cannot send any packets to a device until
* a set address command successfully completes.
*/
if (USE_NEW_SCHEME(retry_counter) && !(hcd->driver->flags & HCD_USB3)) {
struct usb_device_descriptor *buf;
int r = 0;
#define GET_DESCRIPTOR_BUFSIZE 64
buf = kmalloc(GET_DESCRIPTOR_BUFSIZE, GFP_NOIO);
if (!buf) {
retval = -ENOMEM;
continue;
}
/* Retry on all errors; some devices are flakey.
* 255 is for WUSB devices, we actually need to use
* 512 (WUSB1.0[4.8.1]).
*/
for (j = 0; j < 3; ++j) {
buf->bMaxPacketSize0 = 0;
r = usb_control_msg(udev, usb_rcvaddr0pipe(),
USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
USB_DT_DEVICE << 8, 0,
buf, GET_DESCRIPTOR_BUFSIZE,
initial_descriptor_timeout);
switch (buf->bMaxPacketSize0) {
case 8: case 16: case 32: case 64: case 255:
if (buf->bDescriptorType ==
USB_DT_DEVICE) {
r = 0;
break;
}
/* FALL THROUGH */
default:
if (r == 0)
r = -EPROTO;
break;
}
if (r == 0)
break;
}
udev->descriptor.bMaxPacketSize0 =
buf->bMaxPacketSize0;
kfree(buf);
retval = hub_port_reset(hub, port1, udev, delay);
if (retval < 0) /* error or disconnect */
goto fail;
if (oldspeed != udev->speed) {
dev_dbg(&udev->dev,
"device reset changed speed!\n");
retval = -ENODEV;
goto fail;
}
if (r) {
dev_err(&udev->dev,
"device descriptor read/64, error %d\n",
r);
retval = -EMSGSIZE;
continue;
}
#undef GET_DESCRIPTOR_BUFSIZE
}
/*
* If device is WUSB, we already assigned an
* unauthorized address in the Connect Ack sequence;
* authorization will assign the final address.
*/
if (udev->wusb == 0) {
for (j = 0; j < SET_ADDRESS_TRIES; ++j) {
retval = hub_set_address(udev, devnum);
if (retval >= 0)
break;
msleep(200);
}
if (retval < 0) {
dev_err(&udev->dev,
"device not accepting address %d, error %d\n",
devnum, retval);
goto fail;
}
if (udev->speed == USB_SPEED_SUPER) {
devnum = udev->devnum;
dev_info(&udev->dev,
"%s SuperSpeed USB device using %s and address %d\n",
(udev->config) ? "reset" : "new",
udev->bus->controller->driver->name, devnum);
}
/* cope with hardware quirkiness:
* - let SET_ADDRESS settle, some device hardware wants it
* - read ep0 maxpacket even for high and low speed,
*/
msleep(10);
if (USE_NEW_SCHEME(retry_counter) && !(hcd->driver->flags & HCD_USB3))
break;
}
retval = usb_get_device_descriptor(udev, 8);
if (retval < 8) {
dev_err(&udev->dev,
"device descriptor read/8, error %d\n",
retval);
if (retval >= 0)
retval = -EMSGSIZE;
} else {
retval = 0;
break;
}
}
if (retval)
goto fail;
if (udev->descriptor.bMaxPacketSize0 == 0xff ||
udev->speed == USB_SPEED_SUPER)
i = 512;
else
i = udev->descriptor.bMaxPacketSize0;
if (le16_to_cpu(udev->ep0.desc.wMaxPacketSize) != i) {
if (udev->speed != USB_SPEED_FULL ||
!(i == 8 || i == 16 || i == 32 || i == 64)) {
dev_err(&udev->dev, "ep0 maxpacket = %d\n", i);
retval = -EMSGSIZE;
goto fail;
}
dev_dbg(&udev->dev, "ep0 maxpacket = %d\n", i);
udev->ep0.desc.wMaxPacketSize = cpu_to_le16(i);
usb_ep0_reinit(udev);
}
retval = usb_get_device_descriptor(udev, USB_DT_DEVICE_SIZE);
if (retval < (signed)sizeof(udev->descriptor)) {
dev_err(&udev->dev, "device descriptor read/all, error %d\n",
retval);
if (retval >= 0)
retval = -ENOMSG;
goto fail;
}
retval = 0;
fail:
if (retval) {
hub_port_disable(hub, port1, 0);
update_address(udev, devnum); /* for disconnect processing */
}
mutex_unlock(&usb_address0_mutex);
return retval;
}
static void
check_highspeed (struct usb_hub *hub, struct usb_device *udev, int port1)
{
struct usb_qualifier_descriptor *qual;
int status;
qual = kmalloc (sizeof *qual, GFP_KERNEL);
if (qual == NULL)
return;
status = usb_get_descriptor (udev, USB_DT_DEVICE_QUALIFIER, 0,
qual, sizeof *qual);
if (status == sizeof *qual) {
dev_info(&udev->dev, "not running at top speed; "
"connect to a high speed hub\n");
/* hub LEDs are probably harder to miss than syslog */
if (hub->has_indicators) {
hub->indicator[port1-1] = INDICATOR_GREEN_BLINK;
schedule_delayed_work (&hub->leds, 0);
}
}
kfree(qual);
}
static unsigned
hub_power_remaining (struct usb_hub *hub)
{
struct usb_device *hdev = hub->hdev;
int remaining;
int port1;
if (!hub->limited_power)
return 0;
remaining = hdev->bus_mA - hub->descriptor->bHubContrCurrent;
for (port1 = 1; port1 <= hdev->maxchild; ++port1) {
struct usb_device *udev = hdev->children[port1 - 1];
int delta;
if (!udev)
continue;
/* Unconfigured devices may not use more than 100mA,
* or 8mA for OTG ports */
if (udev->actconfig)
delta = udev->actconfig->desc.bMaxPower * 2;
else if (port1 != udev->bus->otg_port || hdev->parent)
delta = 100;
else
delta = 8;
if (delta > hub->mA_per_port)
dev_warn(&udev->dev,
"%dmA is over %umA budget for port %d!\n",
delta, hub->mA_per_port, port1);
remaining -= delta;
}
if (remaining < 0) {
dev_warn(hub->intfdev, "%dmA over power budget!\n",
- remaining);
remaining = 0;
}
return remaining;
}
/* Handle physical or logical connection change events.
* This routine is called when:
* a port connection-change occurs;
* a port enable-change occurs (often caused by EMI);
* usb_reset_and_verify_device() encounters changed descriptors (as from
* a firmware download)
* caller already locked the hub
*/
static void hub_port_connect_change(struct usb_hub *hub, int port1,
u16 portstatus, u16 portchange)
{
struct usb_device *hdev = hub->hdev;
struct device *hub_dev = hub->intfdev;
struct usb_hcd *hcd = bus_to_hcd(hdev->bus);
unsigned wHubCharacteristics =
le16_to_cpu(hub->descriptor->wHubCharacteristics);
struct usb_device *udev;
int status, i;
dev_dbg (hub_dev,
"port %d, status %04x, change %04x, %s\n",
port1, portstatus, portchange, portspeed (portstatus));
if (hub->has_indicators) {
set_port_led(hub, port1, HUB_LED_AUTO);
hub->indicator[port1-1] = INDICATOR_AUTO;
}
#ifdef CONFIG_USB_OTG
/* during HNP, don't repeat the debounce */
if (hdev->bus->is_b_host)
portchange &= ~(USB_PORT_STAT_C_CONNECTION |
USB_PORT_STAT_C_ENABLE);
#endif
/* Try to resuscitate an existing device */
udev = hdev->children[port1-1];
if ((portstatus & USB_PORT_STAT_CONNECTION) && udev &&
udev->state != USB_STATE_NOTATTACHED) {
usb_lock_device(udev);
if (portstatus & USB_PORT_STAT_ENABLE) {
status = 0; /* Nothing to do */
#ifdef CONFIG_USB_SUSPEND
} else if (udev->state == USB_STATE_SUSPENDED &&
udev->persist_enabled) {
/* For a suspended device, treat this as a
* remote wakeup event.
*/
status = usb_remote_wakeup(udev);
#endif
} else {
status = -ENODEV; /* Don't resuscitate */
}
usb_unlock_device(udev);
if (status == 0) {
clear_bit(port1, hub->change_bits);
return;
}
}
/* Disconnect any existing devices under this port */
if (udev)
usb_disconnect(&hdev->children[port1-1]);
clear_bit(port1, hub->change_bits);
/* We can forget about a "removed" device when there's a physical
* disconnect or the connect status changes.
*/
if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
(portchange & USB_PORT_STAT_C_CONNECTION))
clear_bit(port1, hub->removed_bits);
if (portchange & (USB_PORT_STAT_C_CONNECTION |
USB_PORT_STAT_C_ENABLE)) {
status = hub_port_debounce(hub, port1);
if (status < 0) {
if (printk_ratelimit())
dev_err(hub_dev, "connect-debounce failed, "
"port %d disabled\n", port1);
portstatus &= ~USB_PORT_STAT_CONNECTION;
} else {
portstatus = status;
}
}
/* Return now if debouncing failed or nothing is connected or
* the device was "removed".
*/
if (!(portstatus & USB_PORT_STAT_CONNECTION) ||
test_bit(port1, hub->removed_bits)) {
/* maybe switch power back on (e.g. root hub was reset) */
if ((wHubCharacteristics & HUB_CHAR_LPSM) < 2
&& !(portstatus & USB_PORT_STAT_POWER))
set_port_feature(hdev, port1, USB_PORT_FEAT_POWER);
if (portstatus & USB_PORT_STAT_ENABLE)
goto done;
return;
}
for (i = 0; i < SET_CONFIG_TRIES; i++) {
/* reallocate for each attempt, since references
* to the previous one can escape in various ways
*/
udev = usb_alloc_dev(hdev, hdev->bus, port1);
if (!udev) {
dev_err (hub_dev,
"couldn't allocate port %d usb_device\n",
port1);
goto done;
}
usb_set_device_state(udev, USB_STATE_POWERED);
udev->bus_mA = hub->mA_per_port;
udev->level = hdev->level + 1;
udev->wusb = hub_is_wusb(hub);
/*
* USB 3.0 devices are reset automatically before the connect
* port status change appears, and the root hub port status
* shows the correct speed. We also get port change
* notifications for USB 3.0 devices from the USB 3.0 portion of
* an external USB 3.0 hub, but this isn't handled correctly yet
* FIXME.
*/
if (!(hcd->driver->flags & HCD_USB3))
udev->speed = USB_SPEED_UNKNOWN;
else if ((hdev->parent == NULL) &&
(portstatus & USB_PORT_STAT_SUPER_SPEED))
udev->speed = USB_SPEED_SUPER;
else
udev->speed = USB_SPEED_UNKNOWN;
/*
* xHCI needs to issue an address device command later
* in the hub_port_init sequence for SS/HS/FS/LS devices.
*/
if (!(hcd->driver->flags & HCD_USB3)) {
/* set the address */
choose_address(udev);
if (udev->devnum <= 0) {
status = -ENOTCONN; /* Don't retry */
goto loop;
}
}
/* reset (non-USB 3.0 devices) and get descriptor */
status = hub_port_init(hub, udev, port1, i);
if (status < 0)
goto loop;
usb_detect_quirks(udev);
if (udev->quirks & USB_QUIRK_DELAY_INIT)
msleep(1000);
/* consecutive bus-powered hubs aren't reliable; they can
* violate the voltage drop budget. if the new child has
* a "powered" LED, users should notice we didn't enable it
* (without reading syslog), even without per-port LEDs
* on the parent.
*/
if (udev->descriptor.bDeviceClass == USB_CLASS_HUB
&& udev->bus_mA <= 100) {
u16 devstat;
status = usb_get_status(udev, USB_RECIP_DEVICE, 0,
&devstat);
if (status < 2) {
dev_dbg(&udev->dev, "get status %d ?\n", status);
goto loop_disable;
}
le16_to_cpus(&devstat);
if ((devstat & (1 << USB_DEVICE_SELF_POWERED)) == 0) {
dev_err(&udev->dev,
"can't connect bus-powered hub "
"to this port\n");
if (hub->has_indicators) {
hub->indicator[port1-1] =
INDICATOR_AMBER_BLINK;
schedule_delayed_work (&hub->leds, 0);
}
status = -ENOTCONN; /* Don't retry */
goto loop_disable;
}
}
/* check for devices running slower than they could */
if (le16_to_cpu(udev->descriptor.bcdUSB) >= 0x0200
&& udev->speed == USB_SPEED_FULL
&& highspeed_hubs != 0)
check_highspeed (hub, udev, port1);
/* Store the parent's children[] pointer. At this point
* udev becomes globally accessible, although presumably
* no one will look at it until hdev is unlocked.
*/
status = 0;
/* We mustn't add new devices if the parent hub has
* been disconnected; we would race with the
* recursively_mark_NOTATTACHED() routine.
*/
spin_lock_irq(&device_state_lock);
if (hdev->state == USB_STATE_NOTATTACHED)
status = -ENOTCONN;
else
hdev->children[port1-1] = udev;
spin_unlock_irq(&device_state_lock);
/* Run it through the hoops (find a driver, etc) */
if (!status) {
status = usb_new_device(udev);
if (status) {
spin_lock_irq(&device_state_lock);
hdev->children[port1-1] = NULL;
spin_unlock_irq(&device_state_lock);
}
}
if (status)
goto loop_disable;
status = hub_power_remaining(hub);
if (status)
dev_dbg(hub_dev, "%dmA power budget left\n", status);
return;
loop_disable:
hub_port_disable(hub, port1, 1);
loop:
usb_ep0_reinit(udev);
release_address(udev);
hub_free_dev(udev);
usb_put_dev(udev);
if ((status == -ENOTCONN) || (status == -ENOTSUPP))
break;
}
if (hub->hdev->parent ||
!hcd->driver->port_handed_over ||
!(hcd->driver->port_handed_over)(hcd, port1))
dev_err(hub_dev, "unable to enumerate USB device on port %d\n",
port1);
done:
hub_port_disable(hub, port1, 1);
if (hcd->driver->relinquish_port && !hub->hdev->parent)
hcd->driver->relinquish_port(hcd, port1);
}
static void hub_events(void)
{
struct list_head *tmp;
struct usb_device *hdev;
struct usb_interface *intf;
struct usb_hub *hub;
struct device *hub_dev;
u16 hubstatus;
u16 hubchange;
u16 portstatus;
u16 portchange;
int i, ret;
int connect_change;
/*
* We restart the list every time to avoid a deadlock with
* deleting hubs downstream from this one. This should be
* safe since we delete the hub from the event list.
* Not the most efficient, but avoids deadlocks.
*/
while (1) {
/* Grab the first entry at the beginning of the list */
spin_lock_irq(&hub_event_lock);
if (list_empty(&hub_event_list)) {
spin_unlock_irq(&hub_event_lock);
break;
}
tmp = hub_event_list.next;
list_del_init(tmp);
hub = list_entry(tmp, struct usb_hub, event_list);
kref_get(&hub->kref);
spin_unlock_irq(&hub_event_lock);
hdev = hub->hdev;
hub_dev = hub->intfdev;
intf = to_usb_interface(hub_dev);
dev_dbg(hub_dev, "state %d ports %d chg %04x evt %04x\n",
hdev->state, hub->descriptor
? hub->descriptor->bNbrPorts
: 0,
/* NOTE: expects max 15 ports... */
(u16) hub->change_bits[0],
(u16) hub->event_bits[0]);
/* Lock the device, then check to see if we were
* disconnected while waiting for the lock to succeed. */
usb_lock_device(hdev);
if (unlikely(hub->disconnected))
goto loop_disconnected;
/* If the hub has died, clean up after it */
if (hdev->state == USB_STATE_NOTATTACHED) {
hub->error = -ENODEV;
hub_quiesce(hub, HUB_DISCONNECT);
goto loop;
}
/* Autoresume */
ret = usb_autopm_get_interface(intf);
if (ret) {
dev_dbg(hub_dev, "Can't autoresume: %d\n", ret);
goto loop;
}
/* If this is an inactive hub, do nothing */
if (hub->quiescing)
goto loop_autopm;
if (hub->error) {
dev_dbg (hub_dev, "resetting for error %d\n",
hub->error);
ret = usb_reset_device(hdev);
if (ret) {
dev_dbg (hub_dev,
"error resetting hub: %d\n", ret);
goto loop_autopm;
}
hub->nerrors = 0;
hub->error = 0;
}
/* deal with port status changes */
for (i = 1; i <= hub->descriptor->bNbrPorts; i++) {
if (test_bit(i, hub->busy_bits))
continue;
connect_change = test_bit(i, hub->change_bits);
if (!test_and_clear_bit(i, hub->event_bits) &&
!connect_change)
continue;
ret = hub_port_status(hub, i,
&portstatus, &portchange);
if (ret < 0)
continue;
if (portchange & USB_PORT_STAT_C_CONNECTION) {
clear_port_feature(hdev, i,
USB_PORT_FEAT_C_CONNECTION);
connect_change = 1;
}
if (portchange & USB_PORT_STAT_C_ENABLE) {
if (!connect_change)
dev_dbg (hub_dev,
"port %d enable change, "
"status %08x\n",
i, portstatus);
clear_port_feature(hdev, i,
USB_PORT_FEAT_C_ENABLE);
/*
* EM interference sometimes causes badly
* shielded USB devices to be shutdown by
* the hub, this hack enables them again.
* Works at least with mouse driver.
*/
if (!(portstatus & USB_PORT_STAT_ENABLE)
&& !connect_change
&& hdev->children[i-1]) {
dev_err (hub_dev,
"port %i "
"disabled by hub (EMI?), "
"re-enabling...\n",
i);
connect_change = 1;
}
}
if (portchange & USB_PORT_STAT_C_SUSPEND) {
struct usb_device *udev;
clear_port_feature(hdev, i,
USB_PORT_FEAT_C_SUSPEND);
udev = hdev->children[i-1];
if (udev) {
/* TRSMRCY = 10 msec */
msleep(10);
usb_lock_device(udev);
ret = usb_remote_wakeup(hdev->
children[i-1]);
usb_unlock_device(udev);
if (ret < 0)
connect_change = 1;
} else {
ret = -ENODEV;
hub_port_disable(hub, i, 1);
}
dev_dbg (hub_dev,
"resume on port %d, status %d\n",
i, ret);
}
if (portchange & USB_PORT_STAT_C_OVERCURRENT) {
dev_err (hub_dev,
"over-current change on port %d\n",
i);
clear_port_feature(hdev, i,
USB_PORT_FEAT_C_OVER_CURRENT);
hub_power_on(hub, true);
}
if (portchange & USB_PORT_STAT_C_RESET) {
dev_dbg (hub_dev,
"reset change on port %d\n",
i);
clear_port_feature(hdev, i,
USB_PORT_FEAT_C_RESET);
}
if (connect_change)
hub_port_connect_change(hub, i,
portstatus, portchange);
} /* end for i */
/* deal with hub status changes */
if (test_and_clear_bit(0, hub->event_bits) == 0)
; /* do nothing */
else if (hub_hub_status(hub, &hubstatus, &hubchange) < 0)
dev_err (hub_dev, "get_hub_status failed\n");
else {
if (hubchange & HUB_CHANGE_LOCAL_POWER) {
dev_dbg (hub_dev, "power change\n");
clear_hub_feature(hdev, C_HUB_LOCAL_POWER);
if (hubstatus & HUB_STATUS_LOCAL_POWER)
/* FIXME: Is this always true? */
hub->limited_power = 1;
else
hub->limited_power = 0;
}
if (hubchange & HUB_CHANGE_OVERCURRENT) {
dev_dbg (hub_dev, "overcurrent change\n");
msleep(500); /* Cool down */
clear_hub_feature(hdev, C_HUB_OVER_CURRENT);
hub_power_on(hub, true);
}
}
loop_autopm:
/* Balance the usb_autopm_get_interface() above */
usb_autopm_put_interface_no_suspend(intf);
loop:
/* Balance the usb_autopm_get_interface_no_resume() in
* kick_khubd() and allow autosuspend.
*/
usb_autopm_put_interface(intf);
loop_disconnected:
usb_unlock_device(hdev);
kref_put(&hub->kref, hub_release);
} /* end while (1) */
}
static int hub_thread(void *__unused)
{
/* khubd needs to be freezable to avoid intefering with USB-PERSIST
* port handover. Otherwise it might see that a full-speed device
* was gone before the EHCI controller had handed its port over to
* the companion full-speed controller.
*/
set_freezable();
do {
hub_events();
wait_event_freezable(khubd_wait,
!list_empty(&hub_event_list) ||
kthread_should_stop());
} while (!kthread_should_stop() || !list_empty(&hub_event_list));
pr_debug("%s: khubd exiting\n", usbcore_name);
return 0;
}
static const struct usb_device_id hub_id_table[] = {
{ .match_flags = USB_DEVICE_ID_MATCH_DEV_CLASS,
.bDeviceClass = USB_CLASS_HUB},
{ .match_flags = USB_DEVICE_ID_MATCH_INT_CLASS,
.bInterfaceClass = USB_CLASS_HUB},
{ } /* Terminating entry */
};
MODULE_DEVICE_TABLE (usb, hub_id_table);
static struct usb_driver hub_driver = {
.name = "hub",
.probe = hub_probe,
.disconnect = hub_disconnect,
.suspend = hub_suspend,
.resume = hub_resume,
.reset_resume = hub_reset_resume,
.pre_reset = hub_pre_reset,
.post_reset = hub_post_reset,
.ioctl = hub_ioctl,
.id_table = hub_id_table,
.supports_autosuspend = 1,
};
int usb_hub_init(void)
{
if (usb_register(&hub_driver) < 0) {
printk(KERN_ERR "%s: can't register hub driver\n",
usbcore_name);
return -1;
}
khubd_task = kthread_run(hub_thread, NULL, "khubd");
if (!IS_ERR(khubd_task))
return 0;
/* Fall through if kernel_thread failed */
usb_deregister(&hub_driver);
printk(KERN_ERR "%s: can't start khubd\n", usbcore_name);
return -1;
}
void usb_hub_cleanup(void)
{
kthread_stop(khubd_task);
/*
* Hub resources are freed for us by usb_deregister. It calls
* usb_driver_purge on every device which in turn calls that
* devices disconnect function if it is using this driver.
* The hub_disconnect function takes care of releasing the
* individual hub resources. -greg
*/
usb_deregister(&hub_driver);
} /* usb_hub_cleanup() */
static int descriptors_changed(struct usb_device *udev,
struct usb_device_descriptor *old_device_descriptor)
{
int changed = 0;
unsigned index;
unsigned serial_len = 0;
unsigned len;
unsigned old_length;
int length;
char *buf;
if (memcmp(&udev->descriptor, old_device_descriptor,
sizeof(*old_device_descriptor)) != 0)
return 1;
/* Since the idVendor, idProduct, and bcdDevice values in the
* device descriptor haven't changed, we will assume the
* Manufacturer and Product strings haven't changed either.
* But the SerialNumber string could be different (e.g., a
* different flash card of the same brand).
*/
if (udev->serial)
serial_len = strlen(udev->serial) + 1;
len = serial_len;
for (index = 0; index < udev->descriptor.bNumConfigurations; index++) {
old_length = le16_to_cpu(udev->config[index].desc.wTotalLength);
len = max(len, old_length);
}
buf = kmalloc(len, GFP_NOIO);
if (buf == NULL) {
dev_err(&udev->dev, "no mem to re-read configs after reset\n");
/* assume the worst */
return 1;
}
for (index = 0; index < udev->descriptor.bNumConfigurations; index++) {
old_length = le16_to_cpu(udev->config[index].desc.wTotalLength);
length = usb_get_descriptor(udev, USB_DT_CONFIG, index, buf,
old_length);
if (length != old_length) {
dev_dbg(&udev->dev, "config index %d, error %d\n",
index, length);
changed = 1;
break;
}
if (memcmp (buf, udev->rawdescriptors[index], old_length)
!= 0) {
dev_dbg(&udev->dev, "config index %d changed (#%d)\n",
index,
((struct usb_config_descriptor *) buf)->
bConfigurationValue);
changed = 1;
break;
}
}
if (!changed && serial_len) {
length = usb_string(udev, udev->descriptor.iSerialNumber,
buf, serial_len);
if (length + 1 != serial_len) {
dev_dbg(&udev->dev, "serial string error %d\n",
length);
changed = 1;
} else if (memcmp(buf, udev->serial, length) != 0) {
dev_dbg(&udev->dev, "serial string changed\n");
changed = 1;
}
}
kfree(buf);
return changed;
}
/**
* usb_reset_and_verify_device - perform a USB port reset to reinitialize a device
* @udev: device to reset (not in SUSPENDED or NOTATTACHED state)
*
* WARNING - don't use this routine to reset a composite device
* (one with multiple interfaces owned by separate drivers)!
* Use usb_reset_device() instead.
*
* Do a port reset, reassign the device's address, and establish its
* former operating configuration. If the reset fails, or the device's
* descriptors change from their values before the reset, or the original
* configuration and altsettings cannot be restored, a flag will be set
* telling khubd to pretend the device has been disconnected and then
* re-connected. All drivers will be unbound, and the device will be
* re-enumerated and probed all over again.
*
* Returns 0 if the reset succeeded, -ENODEV if the device has been
* flagged for logical disconnection, or some other negative error code
* if the reset wasn't even attempted.
*
* The caller must own the device lock. For example, it's safe to use
* this from a driver probe() routine after downloading new firmware.
* For calls that might not occur during probe(), drivers should lock
* the device using usb_lock_device_for_reset().
*
* Locking exception: This routine may also be called from within an
* autoresume handler. Such usage won't conflict with other tasks
* holding the device lock because these tasks should always call
* usb_autopm_resume_device(), thereby preventing any unwanted autoresume.
*/
static int usb_reset_and_verify_device(struct usb_device *udev)
{
struct usb_device *parent_hdev = udev->parent;
struct usb_hub *parent_hub;
struct usb_hcd *hcd = bus_to_hcd(udev->bus);
struct usb_device_descriptor descriptor = udev->descriptor;
int i, ret = 0;
int port1 = udev->portnum;
if (udev->state == USB_STATE_NOTATTACHED ||
udev->state == USB_STATE_SUSPENDED) {
dev_dbg(&udev->dev, "device reset not allowed in state %d\n",
udev->state);
return -EINVAL;
}
if (!parent_hdev) {
/* this requires hcd-specific logic; see OHCI hc_restart() */
dev_dbg(&udev->dev, "%s for root hub!\n", __func__);
return -EISDIR;
}
parent_hub = hdev_to_hub(parent_hdev);
set_bit(port1, parent_hub->busy_bits);
for (i = 0; i < SET_CONFIG_TRIES; ++i) {
/* ep0 maxpacket size may change; let the HCD know about it.
* Other endpoints will be handled by re-enumeration. */
usb_ep0_reinit(udev);
ret = hub_port_init(parent_hub, udev, port1, i);
if (ret >= 0 || ret == -ENOTCONN || ret == -ENODEV)
break;
}
clear_bit(port1, parent_hub->busy_bits);
if (ret < 0)
goto re_enumerate;
/* Device might have changed firmware (DFU or similar) */
if (descriptors_changed(udev, &descriptor)) {
dev_info(&udev->dev, "device firmware changed\n");
udev->descriptor = descriptor; /* for disconnect() calls */
goto re_enumerate;
}
/* Restore the device's previous configuration */
if (!udev->actconfig)
goto done;
mutex_lock(&hcd->bandwidth_mutex);
ret = usb_hcd_alloc_bandwidth(udev, udev->actconfig, NULL, NULL);
if (ret < 0) {
dev_warn(&udev->dev,
"Busted HC? Not enough HCD resources for "
"old configuration.\n");
mutex_unlock(&hcd->bandwidth_mutex);
goto re_enumerate;
}
ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
USB_REQ_SET_CONFIGURATION, 0,
udev->actconfig->desc.bConfigurationValue, 0,
NULL, 0, USB_CTRL_SET_TIMEOUT);
if (ret < 0) {
dev_err(&udev->dev,
"can't restore configuration #%d (error=%d)\n",
udev->actconfig->desc.bConfigurationValue, ret);
mutex_unlock(&hcd->bandwidth_mutex);
goto re_enumerate;
}
mutex_unlock(&hcd->bandwidth_mutex);
usb_set_device_state(udev, USB_STATE_CONFIGURED);
/* Put interfaces back into the same altsettings as before.
* Don't bother to send the Set-Interface request for interfaces
* that were already in altsetting 0; besides being unnecessary,
* many devices can't handle it. Instead just reset the host-side
* endpoint state.
*/
for (i = 0; i < udev->actconfig->desc.bNumInterfaces; i++) {
struct usb_host_config *config = udev->actconfig;
struct usb_interface *intf = config->interface[i];
struct usb_interface_descriptor *desc;
desc = &intf->cur_altsetting->desc;
if (desc->bAlternateSetting == 0) {
usb_disable_interface(udev, intf, true);
usb_enable_interface(udev, intf, true);
ret = 0;
} else {
/* Let the bandwidth allocation function know that this
* device has been reset, and it will have to use
* alternate setting 0 as the current alternate setting.
*/
intf->resetting_device = 1;
ret = usb_set_interface(udev, desc->bInterfaceNumber,
desc->bAlternateSetting);
intf->resetting_device = 0;
}
if (ret < 0) {
dev_err(&udev->dev, "failed to restore interface %d "
"altsetting %d (error=%d)\n",
desc->bInterfaceNumber,
desc->bAlternateSetting,
ret);
goto re_enumerate;
}
}
done:
return 0;
re_enumerate:
hub_port_logical_disconnect(parent_hub, port1);
return -ENODEV;
}
/**
* usb_reset_device - warn interface drivers and perform a USB port reset
* @udev: device to reset (not in SUSPENDED or NOTATTACHED state)
*
* Warns all drivers bound to registered interfaces (using their pre_reset
* method), performs the port reset, and then lets the drivers know that
* the reset is over (using their post_reset method).
*
* Return value is the same as for usb_reset_and_verify_device().
*
* The caller must own the device lock. For example, it's safe to use
* this from a driver probe() routine after downloading new firmware.
* For calls that might not occur during probe(), drivers should lock
* the device using usb_lock_device_for_reset().
*
* If an interface is currently being probed or disconnected, we assume
* its driver knows how to handle resets. For all other interfaces,
* if the driver doesn't have pre_reset and post_reset methods then
* we attempt to unbind it and rebind afterward.
*/
int usb_reset_device(struct usb_device *udev)
{
int ret;
int i;
struct usb_host_config *config = udev->actconfig;
if (udev->state == USB_STATE_NOTATTACHED ||
udev->state == USB_STATE_SUSPENDED) {
dev_dbg(&udev->dev, "device reset not allowed in state %d\n",
udev->state);
return -EINVAL;
}
/* Prevent autosuspend during the reset */
usb_autoresume_device(udev);
if (config) {
for (i = 0; i < config->desc.bNumInterfaces; ++i) {
struct usb_interface *cintf = config->interface[i];
struct usb_driver *drv;
int unbind = 0;
if (cintf->dev.driver) {
drv = to_usb_driver(cintf->dev.driver);
if (drv->pre_reset && drv->post_reset)
unbind = (drv->pre_reset)(cintf);
else if (cintf->condition ==
USB_INTERFACE_BOUND)
unbind = 1;
if (unbind)
usb_forced_unbind_intf(cintf);
}
}
}
ret = usb_reset_and_verify_device(udev);
if (config) {
for (i = config->desc.bNumInterfaces - 1; i >= 0; --i) {
struct usb_interface *cintf = config->interface[i];
struct usb_driver *drv;
int rebind = cintf->needs_binding;
if (!rebind && cintf->dev.driver) {
drv = to_usb_driver(cintf->dev.driver);
if (drv->post_reset)
rebind = (drv->post_reset)(cintf);
else if (cintf->condition ==
USB_INTERFACE_BOUND)
rebind = 1;
}
if (ret == 0 && rebind)
usb_rebind_intf(cintf);
}
}
usb_autosuspend_device(udev);
return ret;
}
EXPORT_SYMBOL_GPL(usb_reset_device);
/**
* usb_queue_reset_device - Reset a USB device from an atomic context
* @iface: USB interface belonging to the device to reset
*
* This function can be used to reset a USB device from an atomic
* context, where usb_reset_device() won't work (as it blocks).
*
* Doing a reset via this method is functionally equivalent to calling
* usb_reset_device(), except for the fact that it is delayed to a
* workqueue. This means that any drivers bound to other interfaces
* might be unbound, as well as users from usbfs in user space.
*
* Corner cases:
*
* - Scheduling two resets at the same time from two different drivers
* attached to two different interfaces of the same device is
* possible; depending on how the driver attached to each interface
* handles ->pre_reset(), the second reset might happen or not.
*
* - If a driver is unbound and it had a pending reset, the reset will
* be cancelled.
*
* - This function can be called during .probe() or .disconnect()
* times. On return from .disconnect(), any pending resets will be
* cancelled.
*
* There is no no need to lock/unlock the @reset_ws as schedule_work()
* does its own.
*
* NOTE: We don't do any reference count tracking because it is not
* needed. The lifecycle of the work_struct is tied to the
* usb_interface. Before destroying the interface we cancel the
* work_struct, so the fact that work_struct is queued and or
* running means the interface (and thus, the device) exist and
* are referenced.
*/
void usb_queue_reset_device(struct usb_interface *iface)
{
schedule_work(&iface->reset_ws);
}
EXPORT_SYMBOL_GPL(usb_queue_reset_device);
| gpl-3.0 |
kordano/samba-ldb-mdb | lib/replace/repdir_getdirentries.c | 154 | 4499 | /*
Unix SMB/CIFS implementation.
Copyright (C) Andrew Tridgell 2005
** NOTE! The following LGPL license applies to the replace
** library. This does NOT imply that all of Samba is released
** under the LGPL
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, see <http://www.gnu.org/licenses/>.
*/
/*
a replacement for opendir/readdir/telldir/seekdir/closedir for BSD
systems using getdirentries
This is needed because the existing directory handling in FreeBSD
and OpenBSD (and possibly NetBSD) doesn't correctly handle unlink()
on files in a directory where telldir() has been used. On a block
boundary it will occasionally miss a file when seekdir() is used to
return to a position previously recorded with telldir().
This also fixes a severe performance and memory usage problem with
telldir() on BSD systems. Each call to telldir() in BSD adds an
entry to a linked list, and those entries are cleaned up on
closedir(). This means with a large directory closedir() can take an
arbitrary amount of time, causing network timeouts as millions of
telldir() entries are freed
Note! This replacement code is not portable. It relies on
getdirentries() always leaving the file descriptor at a seek offset
that is a multiple of DIR_BUF_SIZE. If the code detects that this
doesn't happen then it will abort(). It also does not handle
directories with offsets larger than can be stored in a long,
This code is available under other free software licenses as
well. Contact the author.
*/
#include "replace.h"
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <dirent.h>
#define DIR_BUF_BITS 9
#define DIR_BUF_SIZE (1<<DIR_BUF_BITS)
struct dir_buf {
int fd;
int nbytes, ofs;
off_t seekpos;
char buf[DIR_BUF_SIZE];
};
DIR *opendir(const char *dname)
{
struct dir_buf *d;
struct stat sb;
d = malloc(sizeof(*d));
if (d == NULL) {
errno = ENOMEM;
return NULL;
}
d->fd = open(dname, O_RDONLY);
if (d->fd == -1) {
free(d);
return NULL;
}
if (fstat(d->fd, &sb) < 0) {
close(d->fd);
free(d);
return NULL;
}
if (!S_ISDIR(sb.st_mode)) {
close(d->fd);
free(d);
errno = ENOTDIR;
return NULL;
}
d->ofs = 0;
d->seekpos = 0;
d->nbytes = 0;
return (DIR *)d;
}
struct dirent *readdir(DIR *dir)
{
struct dir_buf *d = (struct dir_buf *)dir;
struct dirent *de;
if (d->ofs >= d->nbytes) {
long pos;
d->nbytes = getdirentries(d->fd, d->buf, DIR_BUF_SIZE, &pos);
d->seekpos = pos;
d->ofs = 0;
}
if (d->ofs >= d->nbytes) {
return NULL;
}
de = (struct dirent *)&d->buf[d->ofs];
d->ofs += de->d_reclen;
return de;
}
#ifdef TELLDIR_TAKES_CONST_DIR
long telldir(const DIR *dir)
#else
long telldir(DIR *dir)
#endif
{
struct dir_buf *d = (struct dir_buf *)dir;
if (d->ofs >= d->nbytes) {
d->seekpos = lseek(d->fd, 0, SEEK_CUR);
d->ofs = 0;
d->nbytes = 0;
}
/* this relies on seekpos always being a multiple of
DIR_BUF_SIZE. Is that always true on BSD systems? */
if (d->seekpos & (DIR_BUF_SIZE-1)) {
abort();
}
return d->seekpos + d->ofs;
}
#ifdef SEEKDIR_RETURNS_INT
int seekdir(DIR *dir, long ofs)
#else
void seekdir(DIR *dir, long ofs)
#endif
{
struct dir_buf *d = (struct dir_buf *)dir;
long pos;
d->seekpos = lseek(d->fd, ofs & ~(DIR_BUF_SIZE-1), SEEK_SET);
d->nbytes = getdirentries(d->fd, d->buf, DIR_BUF_SIZE, &pos);
d->ofs = 0;
while (d->ofs < (ofs & (DIR_BUF_SIZE-1))) {
if (readdir(dir) == NULL) break;
}
#ifdef SEEKDIR_RETURNS_INT
return -1;
#endif
}
void rewinddir(DIR *dir)
{
seekdir(dir, 0);
}
int closedir(DIR *dir)
{
struct dir_buf *d = (struct dir_buf *)dir;
int r = close(d->fd);
if (r != 0) {
return r;
}
free(d);
return 0;
}
#ifndef dirfd
/* darn, this is a macro on some systems. */
int dirfd(DIR *dir)
{
struct dir_buf *d = (struct dir_buf *)dir;
return d->fd;
}
#endif
| gpl-3.0 |
ih24n69/android_kernel_samsung_young23g | arch/alpha/kernel/pc873xx.c | 12989 | 1696 | #include <linux/ioport.h>
#include <asm/io.h>
#include "pc873xx.h"
static unsigned pc873xx_probelist[] = {0x398, 0x26e, 0};
static char *pc873xx_names[] = {
"PC87303", "PC87306", "PC87312", "PC87332", "PC87334"
};
static unsigned int base, model;
unsigned int __init pc873xx_get_base()
{
return base;
}
char *__init pc873xx_get_model()
{
return pc873xx_names[model];
}
static unsigned char __init pc873xx_read(unsigned int base, int reg)
{
outb(reg, base);
return inb(base + 1);
}
static void __init pc873xx_write(unsigned int base, int reg, unsigned char data)
{
unsigned long flags;
local_irq_save(flags);
outb(reg, base);
outb(data, base + 1);
outb(data, base + 1); /* Must be written twice */
local_irq_restore(flags);
}
int __init pc873xx_probe(void)
{
int val, index = 0;
while ((base = pc873xx_probelist[index++])) {
if (request_region(base, 2, "Super IO PC873xx") == NULL)
continue;
val = pc873xx_read(base, REG_SID);
if ((val & 0xf0) == 0x10) {
model = PC87332;
break;
} else if ((val & 0xf8) == 0x70) {
model = PC87306;
break;
} else if ((val & 0xf8) == 0x50) {
model = PC87334;
break;
} else if ((val & 0xf8) == 0x40) {
model = PC87303;
break;
}
release_region(base, 2);
}
return (base == 0) ? -1 : 1;
}
void __init pc873xx_enable_epp19(void)
{
unsigned char data;
printk(KERN_INFO "PC873xx enabling EPP v1.9\n");
data = pc873xx_read(base, REG_PCR);
pc873xx_write(base, REG_PCR, (data & 0xFC) | 0x02);
}
void __init pc873xx_enable_ide(void)
{
unsigned char data;
printk(KERN_INFO "PC873xx enabling IDE interrupt\n");
data = pc873xx_read(base, REG_FER);
pc873xx_write(base, REG_FER, data | 0x40);
}
| gpl-3.0 |
adomasalcore3/android_kernel_Vodafone_VDF600 | arch/ia64/sn/kernel/sn2/timer.c | 8904 | 1525 | /*
* linux/arch/ia64/sn/kernel/sn2/timer.c
*
* Copyright (C) 2003 Silicon Graphics, Inc.
* Copyright (C) 2003 Hewlett-Packard Co
* David Mosberger <davidm@hpl.hp.com>: updated for new timer-interpolation infrastructure
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/time.h>
#include <linux/interrupt.h>
#include <linux/clocksource.h>
#include <asm/hw_irq.h>
#include <asm/timex.h>
#include <asm/sn/leds.h>
#include <asm/sn/shub_mmr.h>
#include <asm/sn/clksupport.h>
extern unsigned long sn_rtc_cycles_per_second;
static cycle_t read_sn2(struct clocksource *cs)
{
return (cycle_t)readq(RTC_COUNTER_ADDR);
}
static struct clocksource clocksource_sn2 = {
.name = "sn2_rtc",
.rating = 450,
.read = read_sn2,
.mask = (1LL << 55) - 1,
.flags = CLOCK_SOURCE_IS_CONTINUOUS,
};
/*
* sn udelay uses the RTC instead of the ITC because the ITC is not
* synchronized across all CPUs, and the thread may migrate to another CPU
* if preemption is enabled.
*/
static void
ia64_sn_udelay (unsigned long usecs)
{
unsigned long start = rtc_time();
unsigned long end = start +
usecs * sn_rtc_cycles_per_second / 1000000;
while (time_before((unsigned long)rtc_time(), end))
cpu_relax();
}
void __init sn_timer_init(void)
{
clocksource_sn2.archdata.fsys_mmio = RTC_COUNTER_ADDR;
clocksource_register_hz(&clocksource_sn2, sn_rtc_cycles_per_second);
ia64_udelay = &ia64_sn_udelay;
}
| gpl-3.0 |
jhonatajh/mtasa-blue | vendor/pcre/pcre_ord2utf8.c | 204 | 3200 | /*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2008 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* This file contains a private PCRE function that converts an ordinal
character value into a UTF8 string. */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "pcre_internal.h"
/*************************************************
* Convert character value to UTF-8 *
*************************************************/
/* This function takes an integer value in the range 0 - 0x7fffffff
and encodes it as a UTF-8 character in 0 to 6 bytes.
Arguments:
cvalue the character value
buffer pointer to buffer for result - at least 6 bytes long
Returns: number of characters placed in the buffer
*/
int
_pcre_ord2utf8(int cvalue, uschar *buffer)
{
#ifdef SUPPORT_UTF8
register int i, j;
for (i = 0; i < _pcre_utf8_table1_size; i++)
if (cvalue <= _pcre_utf8_table1[i]) break;
buffer += i;
for (j = i; j > 0; j--)
{
*buffer-- = 0x80 | (cvalue & 0x3f);
cvalue >>= 6;
}
*buffer = _pcre_utf8_table2[i] | cvalue;
return i + 1;
#else
(void)(cvalue); /* Keep compiler happy; this function won't ever be */
(void)(buffer); /* called when SUPPORT_UTF8 is not defined. */
return 0;
#endif
}
/* End of pcre_ord2utf8.c */
| gpl-3.0 |
k0nane/R915_kernel_GB | Kernel/drivers/eisa/eisa-bus.c | 9420 | 10851 | /*
* EISA bus support functions for sysfs.
*
* (C) 2002, 2003 Marc Zyngier <maz@wild-wind.fr.eu.org>
*
* This code is released under the GPL version 2.
*/
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/eisa.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/ioport.h>
#include <asm/io.h>
#define SLOT_ADDRESS(r,n) (r->bus_base_addr + (0x1000 * n))
#define EISA_DEVINFO(i,s) { .id = { .sig = i }, .name = s }
struct eisa_device_info {
struct eisa_device_id id;
char name[50];
};
#ifdef CONFIG_EISA_NAMES
static struct eisa_device_info __initdata eisa_table[] = {
#include "devlist.h"
};
#define EISA_INFOS (sizeof (eisa_table) / (sizeof (struct eisa_device_info)))
#endif
#define EISA_MAX_FORCED_DEV 16
static int enable_dev[EISA_MAX_FORCED_DEV];
static unsigned int enable_dev_count;
static int disable_dev[EISA_MAX_FORCED_DEV];
static unsigned int disable_dev_count;
static int is_forced_dev(int *forced_tab,
int forced_count,
struct eisa_root_device *root,
struct eisa_device *edev)
{
int i, x;
for (i = 0; i < forced_count; i++) {
x = (root->bus_nr << 8) | edev->slot;
if (forced_tab[i] == x)
return 1;
}
return 0;
}
static void __init eisa_name_device(struct eisa_device *edev)
{
#ifdef CONFIG_EISA_NAMES
int i;
for (i = 0; i < EISA_INFOS; i++) {
if (!strcmp(edev->id.sig, eisa_table[i].id.sig)) {
strlcpy(edev->pretty_name,
eisa_table[i].name,
sizeof(edev->pretty_name));
return;
}
}
/* No name was found */
sprintf(edev->pretty_name, "EISA device %.7s", edev->id.sig);
#endif
}
static char __init *decode_eisa_sig(unsigned long addr)
{
static char sig_str[EISA_SIG_LEN];
u8 sig[4];
u16 rev;
int i;
for (i = 0; i < 4; i++) {
#ifdef CONFIG_EISA_VLB_PRIMING
/*
* This ugly stuff is used to wake up VL-bus cards
* (AHA-284x is the only known example), so we can
* read the EISA id.
*
* Thankfully, this only exists on x86...
*/
outb(0x80 + i, addr);
#endif
sig[i] = inb(addr + i);
if (!i && (sig[0] & 0x80))
return NULL;
}
sig_str[0] = ((sig[0] >> 2) & 0x1f) + ('A' - 1);
sig_str[1] = (((sig[0] & 3) << 3) | (sig[1] >> 5)) + ('A' - 1);
sig_str[2] = (sig[1] & 0x1f) + ('A' - 1);
rev = (sig[2] << 8) | sig[3];
sprintf(sig_str + 3, "%04X", rev);
return sig_str;
}
static int eisa_bus_match(struct device *dev, struct device_driver *drv)
{
struct eisa_device *edev = to_eisa_device(dev);
struct eisa_driver *edrv = to_eisa_driver(drv);
const struct eisa_device_id *eids = edrv->id_table;
if (!eids)
return 0;
while (strlen(eids->sig)) {
if (!strcmp(eids->sig, edev->id.sig) &&
edev->state & EISA_CONFIG_ENABLED) {
edev->id.driver_data = eids->driver_data;
return 1;
}
eids++;
}
return 0;
}
static int eisa_bus_uevent(struct device *dev, struct kobj_uevent_env *env)
{
struct eisa_device *edev = to_eisa_device(dev);
add_uevent_var(env, "MODALIAS=" EISA_DEVICE_MODALIAS_FMT, edev->id.sig);
return 0;
}
struct bus_type eisa_bus_type = {
.name = "eisa",
.match = eisa_bus_match,
.uevent = eisa_bus_uevent,
};
EXPORT_SYMBOL(eisa_bus_type);
int eisa_driver_register(struct eisa_driver *edrv)
{
edrv->driver.bus = &eisa_bus_type;
return driver_register(&edrv->driver);
}
EXPORT_SYMBOL(eisa_driver_register);
void eisa_driver_unregister(struct eisa_driver *edrv)
{
driver_unregister(&edrv->driver);
}
EXPORT_SYMBOL(eisa_driver_unregister);
static ssize_t eisa_show_sig(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct eisa_device *edev = to_eisa_device(dev);
return sprintf(buf, "%s\n", edev->id.sig);
}
static DEVICE_ATTR(signature, S_IRUGO, eisa_show_sig, NULL);
static ssize_t eisa_show_state(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct eisa_device *edev = to_eisa_device(dev);
return sprintf(buf, "%d\n", edev->state & EISA_CONFIG_ENABLED);
}
static DEVICE_ATTR(enabled, S_IRUGO, eisa_show_state, NULL);
static ssize_t eisa_show_modalias(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct eisa_device *edev = to_eisa_device(dev);
return sprintf(buf, EISA_DEVICE_MODALIAS_FMT "\n", edev->id.sig);
}
static DEVICE_ATTR(modalias, S_IRUGO, eisa_show_modalias, NULL);
static int __init eisa_init_device(struct eisa_root_device *root,
struct eisa_device *edev,
int slot)
{
char *sig;
unsigned long sig_addr;
int i;
sig_addr = SLOT_ADDRESS(root, slot) + EISA_VENDOR_ID_OFFSET;
sig = decode_eisa_sig(sig_addr);
if (!sig)
return -1; /* No EISA device here */
memcpy(edev->id.sig, sig, EISA_SIG_LEN);
edev->slot = slot;
edev->state = inb(SLOT_ADDRESS(root, slot) + EISA_CONFIG_OFFSET)
& EISA_CONFIG_ENABLED;
edev->base_addr = SLOT_ADDRESS(root, slot);
edev->dma_mask = root->dma_mask; /* Default DMA mask */
eisa_name_device(edev);
edev->dev.parent = root->dev;
edev->dev.bus = &eisa_bus_type;
edev->dev.dma_mask = &edev->dma_mask;
edev->dev.coherent_dma_mask = edev->dma_mask;
dev_set_name(&edev->dev, "%02X:%02X", root->bus_nr, slot);
for (i = 0; i < EISA_MAX_RESOURCES; i++) {
#ifdef CONFIG_EISA_NAMES
edev->res[i].name = edev->pretty_name;
#else
edev->res[i].name = edev->id.sig;
#endif
}
if (is_forced_dev(enable_dev, enable_dev_count, root, edev))
edev->state = EISA_CONFIG_ENABLED | EISA_CONFIG_FORCED;
if (is_forced_dev(disable_dev, disable_dev_count, root, edev))
edev->state = EISA_CONFIG_FORCED;
return 0;
}
static int __init eisa_register_device(struct eisa_device *edev)
{
int rc = device_register(&edev->dev);
if (rc)
return rc;
rc = device_create_file(&edev->dev, &dev_attr_signature);
if (rc)
goto err_devreg;
rc = device_create_file(&edev->dev, &dev_attr_enabled);
if (rc)
goto err_sig;
rc = device_create_file(&edev->dev, &dev_attr_modalias);
if (rc)
goto err_enab;
return 0;
err_enab:
device_remove_file(&edev->dev, &dev_attr_enabled);
err_sig:
device_remove_file(&edev->dev, &dev_attr_signature);
err_devreg:
device_unregister(&edev->dev);
return rc;
}
static int __init eisa_request_resources(struct eisa_root_device *root,
struct eisa_device *edev,
int slot)
{
int i;
for (i = 0; i < EISA_MAX_RESOURCES; i++) {
/* Don't register resource for slot 0, since this is
* very likely to fail... :-( Instead, grab the EISA
* id, now we can display something in /proc/ioports.
*/
/* Only one region for mainboard */
if (!slot && i > 0) {
edev->res[i].start = edev->res[i].end = 0;
continue;
}
if (slot) {
edev->res[i].name = NULL;
edev->res[i].start = SLOT_ADDRESS(root, slot)
+ (i * 0x400);
edev->res[i].end = edev->res[i].start + 0xff;
edev->res[i].flags = IORESOURCE_IO;
} else {
edev->res[i].name = NULL;
edev->res[i].start = SLOT_ADDRESS(root, slot)
+ EISA_VENDOR_ID_OFFSET;
edev->res[i].end = edev->res[i].start + 3;
edev->res[i].flags = IORESOURCE_BUSY;
}
if (request_resource(root->res, &edev->res[i]))
goto failed;
}
return 0;
failed:
while (--i >= 0)
release_resource(&edev->res[i]);
return -1;
}
static void __init eisa_release_resources(struct eisa_device *edev)
{
int i;
for (i = 0; i < EISA_MAX_RESOURCES; i++)
if (edev->res[i].start || edev->res[i].end)
release_resource(&edev->res[i]);
}
static int __init eisa_probe(struct eisa_root_device *root)
{
int i, c;
struct eisa_device *edev;
printk(KERN_INFO "EISA: Probing bus %d at %s\n",
root->bus_nr, dev_name(root->dev));
/* First try to get hold of slot 0. If there is no device
* here, simply fail, unless root->force_probe is set. */
edev = kzalloc(sizeof(*edev), GFP_KERNEL);
if (!edev) {
printk(KERN_ERR "EISA: Couldn't allocate mainboard slot\n");
return -ENOMEM;
}
if (eisa_request_resources(root, edev, 0)) {
printk(KERN_WARNING \
"EISA: Cannot allocate resource for mainboard\n");
kfree(edev);
if (!root->force_probe)
return -EBUSY;
goto force_probe;
}
if (eisa_init_device(root, edev, 0)) {
eisa_release_resources(edev);
kfree(edev);
if (!root->force_probe)
return -ENODEV;
goto force_probe;
}
printk(KERN_INFO "EISA: Mainboard %s detected.\n", edev->id.sig);
if (eisa_register_device(edev)) {
printk(KERN_ERR "EISA: Failed to register %s\n",
edev->id.sig);
eisa_release_resources(edev);
kfree(edev);
}
force_probe:
for (c = 0, i = 1; i <= root->slots; i++) {
edev = kzalloc(sizeof(*edev), GFP_KERNEL);
if (!edev) {
printk(KERN_ERR "EISA: Out of memory for slot %d\n", i);
continue;
}
if (eisa_request_resources(root, edev, i)) {
printk(KERN_WARNING \
"Cannot allocate resource for EISA slot %d\n",
i);
kfree(edev);
continue;
}
if (eisa_init_device(root, edev, i)) {
eisa_release_resources(edev);
kfree(edev);
continue;
}
printk(KERN_INFO "EISA: slot %d : %s detected",
i, edev->id.sig);
switch (edev->state) {
case EISA_CONFIG_ENABLED | EISA_CONFIG_FORCED:
printk(" (forced enabled)");
break;
case EISA_CONFIG_FORCED:
printk(" (forced disabled)");
break;
case 0:
printk(" (disabled)");
break;
}
printk (".\n");
c++;
if (eisa_register_device(edev)) {
printk(KERN_ERR "EISA: Failed to register %s\n",
edev->id.sig);
eisa_release_resources(edev);
kfree(edev);
}
}
printk(KERN_INFO "EISA: Detected %d card%s.\n", c, c == 1 ? "" : "s");
return 0;
}
static struct resource eisa_root_res = {
.name = "EISA root resource",
.start = 0,
.end = 0xffffffff,
.flags = IORESOURCE_IO,
};
static int eisa_bus_count;
int __init eisa_root_register(struct eisa_root_device *root)
{
int err;
/* Use our own resources to check if this bus base address has
* been already registered. This prevents the virtual root
* device from registering after the real one has, for
* example... */
root->eisa_root_res.name = eisa_root_res.name;
root->eisa_root_res.start = root->res->start;
root->eisa_root_res.end = root->res->end;
root->eisa_root_res.flags = IORESOURCE_BUSY;
err = request_resource(&eisa_root_res, &root->eisa_root_res);
if (err)
return err;
root->bus_nr = eisa_bus_count++;
err = eisa_probe(root);
if (err)
release_resource(&root->eisa_root_res);
return err;
}
static int __init eisa_init(void)
{
int r;
r = bus_register(&eisa_bus_type);
if (r)
return r;
printk(KERN_INFO "EISA bus registered\n");
return 0;
}
module_param_array(enable_dev, int, &enable_dev_count, 0444);
module_param_array(disable_dev, int, &disable_dev_count, 0444);
postcore_initcall(eisa_init);
int EISA_bus; /* for legacy drivers */
EXPORT_SYMBOL(EISA_bus);
| gpl-3.0 |
fusion809/fusion809.github.io-old | vendor/bundle/ruby/2.1.0/gems/nokogiri-1.6.6.4/ext/nokogiri/xml_sax_push_parser.c | 213 | 2751 | #include <xml_sax_push_parser.h>
static void deallocate(xmlParserCtxtPtr ctx)
{
NOKOGIRI_DEBUG_START(ctx);
if(ctx != NULL) {
NOKOGIRI_SAX_TUPLE_DESTROY(ctx->userData);
xmlFreeParserCtxt(ctx);
}
NOKOGIRI_DEBUG_END(ctx);
}
static VALUE allocate(VALUE klass)
{
return Data_Wrap_Struct(klass, NULL, deallocate, NULL);
}
/*
* call-seq:
* native_write(chunk, last_chunk)
*
* Write +chunk+ to PushParser. +last_chunk+ triggers the end_document handle
*/
static VALUE native_write(VALUE self, VALUE _chunk, VALUE _last_chunk)
{
xmlParserCtxtPtr ctx;
const char * chunk = NULL;
int size = 0;
Data_Get_Struct(self, xmlParserCtxt, ctx);
if(Qnil != _chunk) {
chunk = StringValuePtr(_chunk);
size = (int)RSTRING_LEN(_chunk);
}
if(xmlParseChunk(ctx, chunk, size, Qtrue == _last_chunk ? 1 : 0)) {
if (!(ctx->options & XML_PARSE_RECOVER)) {
xmlErrorPtr e = xmlCtxtGetLastError(ctx);
Nokogiri_error_raise(NULL, e);
}
}
return self;
}
/*
* call-seq:
* initialize_native(xml_sax, filename)
*
* Initialize the push parser with +xml_sax+ using +filename+
*/
static VALUE initialize_native(VALUE self, VALUE _xml_sax, VALUE _filename)
{
xmlSAXHandlerPtr sax;
const char * filename = NULL;
xmlParserCtxtPtr ctx;
Data_Get_Struct(_xml_sax, xmlSAXHandler, sax);
if(_filename != Qnil) filename = StringValuePtr(_filename);
ctx = xmlCreatePushParserCtxt(
sax,
NULL,
NULL,
0,
filename
);
if(ctx == NULL)
rb_raise(rb_eRuntimeError, "Could not create a parser context");
ctx->userData = NOKOGIRI_SAX_TUPLE_NEW(ctx, self);
ctx->sax2 = 1;
DATA_PTR(self) = ctx;
return self;
}
static VALUE get_options(VALUE self)
{
xmlParserCtxtPtr ctx;
Data_Get_Struct(self, xmlParserCtxt, ctx);
return INT2NUM(ctx->options);
}
static VALUE set_options(VALUE self, VALUE options)
{
xmlParserCtxtPtr ctx;
Data_Get_Struct(self, xmlParserCtxt, ctx);
if (xmlCtxtUseOptions(ctx, (int)NUM2INT(options)) != 0)
rb_raise(rb_eRuntimeError, "Cannot set XML parser context options");
return Qnil;
}
VALUE cNokogiriXmlSaxPushParser ;
void init_xml_sax_push_parser()
{
VALUE nokogiri = rb_define_module("Nokogiri");
VALUE xml = rb_define_module_under(nokogiri, "XML");
VALUE sax = rb_define_module_under(xml, "SAX");
VALUE klass = rb_define_class_under(sax, "PushParser", rb_cObject);
cNokogiriXmlSaxPushParser = klass;
rb_define_alloc_func(klass, allocate);
rb_define_private_method(klass, "initialize_native", initialize_native, 2);
rb_define_private_method(klass, "native_write", native_write, 2);
rb_define_method(klass, "options", get_options, 0);
rb_define_method(klass, "options=", set_options, 1);
}
| gpl-3.0 |
huueikmz/shadowsocks-android | src/main/jni/openssl/crypto/x509v3/v3_extku.c | 727 | 4964 | /* v3_extku.c */
/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
* project 1999.
*/
/* ====================================================================
* Copyright (c) 1999 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED 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 OpenSSL PROJECT OR
* ITS 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.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/asn1t.h>
#include <openssl/conf.h>
#include <openssl/x509v3.h>
static void *v2i_EXTENDED_KEY_USAGE(const X509V3_EXT_METHOD *method,
X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *nval);
static STACK_OF(CONF_VALUE) *i2v_EXTENDED_KEY_USAGE(const X509V3_EXT_METHOD *method,
void *eku, STACK_OF(CONF_VALUE) *extlist);
const X509V3_EXT_METHOD v3_ext_ku = {
NID_ext_key_usage, 0,
ASN1_ITEM_ref(EXTENDED_KEY_USAGE),
0,0,0,0,
0,0,
i2v_EXTENDED_KEY_USAGE,
v2i_EXTENDED_KEY_USAGE,
0,0,
NULL
};
/* NB OCSP acceptable responses also is a SEQUENCE OF OBJECT */
const X509V3_EXT_METHOD v3_ocsp_accresp = {
NID_id_pkix_OCSP_acceptableResponses, 0,
ASN1_ITEM_ref(EXTENDED_KEY_USAGE),
0,0,0,0,
0,0,
i2v_EXTENDED_KEY_USAGE,
v2i_EXTENDED_KEY_USAGE,
0,0,
NULL
};
ASN1_ITEM_TEMPLATE(EXTENDED_KEY_USAGE) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, EXTENDED_KEY_USAGE, ASN1_OBJECT)
ASN1_ITEM_TEMPLATE_END(EXTENDED_KEY_USAGE)
IMPLEMENT_ASN1_FUNCTIONS(EXTENDED_KEY_USAGE)
static STACK_OF(CONF_VALUE) *
i2v_EXTENDED_KEY_USAGE(const X509V3_EXT_METHOD *method, void *a,
STACK_OF(CONF_VALUE) *ext_list)
{
EXTENDED_KEY_USAGE *eku = a;
int i;
ASN1_OBJECT *obj;
char obj_tmp[80];
for(i = 0; i < sk_ASN1_OBJECT_num(eku); i++) {
obj = sk_ASN1_OBJECT_value(eku, i);
i2t_ASN1_OBJECT(obj_tmp, 80, obj);
X509V3_add_value(NULL, obj_tmp, &ext_list);
}
return ext_list;
}
static void *v2i_EXTENDED_KEY_USAGE(const X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval)
{
EXTENDED_KEY_USAGE *extku;
char *extval;
ASN1_OBJECT *objtmp;
CONF_VALUE *val;
int i;
if(!(extku = sk_ASN1_OBJECT_new_null())) {
X509V3err(X509V3_F_V2I_EXTENDED_KEY_USAGE,ERR_R_MALLOC_FAILURE);
return NULL;
}
for(i = 0; i < sk_CONF_VALUE_num(nval); i++) {
val = sk_CONF_VALUE_value(nval, i);
if(val->value) extval = val->value;
else extval = val->name;
if(!(objtmp = OBJ_txt2obj(extval, 0))) {
sk_ASN1_OBJECT_pop_free(extku, ASN1_OBJECT_free);
X509V3err(X509V3_F_V2I_EXTENDED_KEY_USAGE,X509V3_R_INVALID_OBJECT_IDENTIFIER);
X509V3_conf_err(val);
return NULL;
}
sk_ASN1_OBJECT_push(extku, objtmp);
}
return extku;
}
| gpl-3.0 |
netnetnet2/shadowsocks-android | src/main/jni/openssl/crypto/pem/pem_pkey.c | 727 | 7827 | /* crypto/pem/pem_pkey.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/buffer.h>
#include <openssl/objects.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/x509.h>
#include <openssl/pkcs12.h>
#include <openssl/pem.h>
#ifndef OPENSSL_NO_ENGINE
#include <openssl/engine.h>
#endif
#include "asn1_locl.h"
int pem_check_suffix(const char *pem_str, const char *suffix);
EVP_PKEY *PEM_read_bio_PrivateKey(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u)
{
char *nm=NULL;
const unsigned char *p=NULL;
unsigned char *data=NULL;
long len;
int slen;
EVP_PKEY *ret=NULL;
if (!PEM_bytes_read_bio(&data, &len, &nm, PEM_STRING_EVP_PKEY, bp, cb, u))
return NULL;
p = data;
if (strcmp(nm,PEM_STRING_PKCS8INF) == 0) {
PKCS8_PRIV_KEY_INFO *p8inf;
p8inf=d2i_PKCS8_PRIV_KEY_INFO(NULL, &p, len);
if(!p8inf) goto p8err;
ret = EVP_PKCS82PKEY(p8inf);
if(x) {
if(*x) EVP_PKEY_free((EVP_PKEY *)*x);
*x = ret;
}
PKCS8_PRIV_KEY_INFO_free(p8inf);
} else if (strcmp(nm,PEM_STRING_PKCS8) == 0) {
PKCS8_PRIV_KEY_INFO *p8inf;
X509_SIG *p8;
int klen;
char psbuf[PEM_BUFSIZE];
p8 = d2i_X509_SIG(NULL, &p, len);
if(!p8) goto p8err;
if (cb) klen=cb(psbuf,PEM_BUFSIZE,0,u);
else klen=PEM_def_callback(psbuf,PEM_BUFSIZE,0,u);
if (klen <= 0) {
PEMerr(PEM_F_PEM_READ_BIO_PRIVATEKEY,
PEM_R_BAD_PASSWORD_READ);
X509_SIG_free(p8);
goto err;
}
p8inf = PKCS8_decrypt(p8, psbuf, klen);
X509_SIG_free(p8);
if(!p8inf) goto p8err;
ret = EVP_PKCS82PKEY(p8inf);
if(x) {
if(*x) EVP_PKEY_free((EVP_PKEY *)*x);
*x = ret;
}
PKCS8_PRIV_KEY_INFO_free(p8inf);
} else if ((slen = pem_check_suffix(nm, "PRIVATE KEY")) > 0)
{
const EVP_PKEY_ASN1_METHOD *ameth;
ameth = EVP_PKEY_asn1_find_str(NULL, nm, slen);
if (!ameth || !ameth->old_priv_decode)
goto p8err;
ret=d2i_PrivateKey(ameth->pkey_id,x,&p,len);
}
p8err:
if (ret == NULL)
PEMerr(PEM_F_PEM_READ_BIO_PRIVATEKEY,ERR_R_ASN1_LIB);
err:
OPENSSL_free(nm);
OPENSSL_cleanse(data, len);
OPENSSL_free(data);
return(ret);
}
int PEM_write_bio_PrivateKey(BIO *bp, EVP_PKEY *x, const EVP_CIPHER *enc,
unsigned char *kstr, int klen,
pem_password_cb *cb, void *u)
{
char pem_str[80];
if (!x->ameth || x->ameth->priv_encode)
return PEM_write_bio_PKCS8PrivateKey(bp, x, enc,
(char *)kstr, klen,
cb, u);
BIO_snprintf(pem_str, 80, "%s PRIVATE KEY", x->ameth->pem_str);
return PEM_ASN1_write_bio((i2d_of_void *)i2d_PrivateKey,
pem_str,bp,x,enc,kstr,klen,cb,u);
}
EVP_PKEY *PEM_read_bio_Parameters(BIO *bp, EVP_PKEY **x)
{
char *nm=NULL;
const unsigned char *p=NULL;
unsigned char *data=NULL;
long len;
int slen;
EVP_PKEY *ret=NULL;
if (!PEM_bytes_read_bio(&data, &len, &nm, PEM_STRING_PARAMETERS,
bp, 0, NULL))
return NULL;
p = data;
if ((slen = pem_check_suffix(nm, "PARAMETERS")) > 0)
{
ret = EVP_PKEY_new();
if (!ret)
goto err;
if (!EVP_PKEY_set_type_str(ret, nm, slen)
|| !ret->ameth->param_decode
|| !ret->ameth->param_decode(ret, &p, len))
{
EVP_PKEY_free(ret);
ret = NULL;
goto err;
}
if(x)
{
if(*x) EVP_PKEY_free((EVP_PKEY *)*x);
*x = ret;
}
}
err:
if (ret == NULL)
PEMerr(PEM_F_PEM_READ_BIO_PARAMETERS,ERR_R_ASN1_LIB);
OPENSSL_free(nm);
OPENSSL_free(data);
return(ret);
}
int PEM_write_bio_Parameters(BIO *bp, EVP_PKEY *x)
{
char pem_str[80];
if (!x->ameth || !x->ameth->param_encode)
return 0;
BIO_snprintf(pem_str, 80, "%s PARAMETERS", x->ameth->pem_str);
return PEM_ASN1_write_bio(
(i2d_of_void *)x->ameth->param_encode,
pem_str,bp,x,NULL,NULL,0,0,NULL);
}
#ifndef OPENSSL_NO_FP_API
EVP_PKEY *PEM_read_PrivateKey(FILE *fp, EVP_PKEY **x, pem_password_cb *cb, void *u)
{
BIO *b;
EVP_PKEY *ret;
if ((b=BIO_new(BIO_s_file())) == NULL)
{
PEMerr(PEM_F_PEM_READ_PRIVATEKEY,ERR_R_BUF_LIB);
return(0);
}
BIO_set_fp(b,fp,BIO_NOCLOSE);
ret=PEM_read_bio_PrivateKey(b,x,cb,u);
BIO_free(b);
return(ret);
}
int PEM_write_PrivateKey(FILE *fp, EVP_PKEY *x, const EVP_CIPHER *enc,
unsigned char *kstr, int klen,
pem_password_cb *cb, void *u)
{
BIO *b;
int ret;
if ((b=BIO_new_fp(fp, BIO_NOCLOSE)) == NULL)
{
PEMerr(PEM_F_PEM_WRITE_PRIVATEKEY,ERR_R_BUF_LIB);
return 0;
}
ret=PEM_write_bio_PrivateKey(b, x, enc, kstr, klen, cb, u);
BIO_free(b);
return ret;
}
#endif
| gpl-3.0 |
ccw808/mtasa-blue | vendor/portaudio/pa_debugprint.c | 224 | 3879 | /*
* $Id: pa_log.c $
* Portable Audio I/O Library Multi-Host API front end
* Validate function parameters and manage multiple host APIs.
*
* Based on the Open Source API proposed by Ross Bencina
* Copyright (c) 1999-2006 Ross Bencina, Phil Burk
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
* The text above constitutes the entire PortAudio license; however,
* the PortAudio community also makes the following non-binding requests:
*
* Any person wishing to distribute modifications to the Software is
* requested to send the modifications to the original developer so that
* they can be incorporated into the canonical version. It is also
* requested that these non-binding requests be included along with the
* license above.
*/
/** @file
@ingroup common_src
@brief Implements log function.
PaUtil_SetLogPrintFunction can be user called to replace the provided
DefaultLogPrint function, which writes to stderr.
One can NOT pass var_args across compiler/dll boundaries as it is not
"byte code/abi portable". So the technique used here is to allocate a local
a static array, write in it, then callback the user with a pointer to its
start.
*/
#include <stdio.h>
#include <stdarg.h>
#include "pa_debugprint.h"
// for OutputDebugStringA
#if defined(_MSC_VER) && defined(PA_ENABLE_MSVC_DEBUG_OUTPUT)
#define WIN32_LEAN_AND_MEAN // exclude rare headers
#include "windows.h"
#endif
// User callback
static PaUtilLogCallback userCB = NULL;
// Sets user callback
void PaUtil_SetDebugPrintFunction(PaUtilLogCallback cb)
{
userCB = cb;
}
/*
If your platform doesnt have vsnprintf, you are stuck with a
VERY dangerous alternative, vsprintf (with no n)
*/
#if _MSC_VER
/* Some Windows Mobile SDKs don't define vsnprintf but all define _vsnprintf (hopefully).
According to MSDN "vsnprintf is identical to _vsnprintf". So we use _vsnprintf with MSC.
*/
#define VSNPRINTF _vsnprintf
#else
#define VSNPRINTF vsnprintf
#endif
#define PA_LOG_BUF_SIZE 2048
void PaUtil_DebugPrint( const char *format, ... )
{
// Optional logging into Output console of Visual Studio
#if defined(_MSC_VER) && defined(PA_ENABLE_MSVC_DEBUG_OUTPUT)
{
char buf[PA_LOG_BUF_SIZE];
va_list ap;
va_start(ap, format);
VSNPRINTF(buf, sizeof(buf), format, ap);
buf[sizeof(buf)-1] = 0;
OutputDebugStringA(buf);
va_end(ap);
}
#endif
// Output to User-Callback
if (userCB != NULL)
{
char strdump[PA_LOG_BUF_SIZE];
va_list ap;
va_start(ap, format);
VSNPRINTF(strdump, sizeof(strdump), format, ap);
strdump[sizeof(strdump)-1] = 0;
userCB(strdump);
va_end(ap);
}
else
// Standard output to stderr
{
va_list ap;
va_start(ap, format);
vfprintf(stderr, format, ap);
va_end(ap);
fflush(stderr);
}
}
| gpl-3.0 |
geminy/aidear | oss/linux/linux-4.7/arch/frv/mm/init.c | 2272 | 4584 | /* init.c: memory initialisation for FRV
*
* Copyright (C) 2004 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* Derived from:
* - linux/arch/m68knommu/mm/init.c
* - Copyright (C) 1998 D. Jeff Dionne <jeff@lineo.ca>, Kenneth Albanowski <kjahds@kjahds.com>,
* - Copyright (C) 2000 Lineo, Inc. (www.lineo.com)
* - linux/arch/m68k/mm/init.c
* - Copyright (C) 1995 Hamish Macdonald
*/
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/pagemap.h>
#include <linux/gfp.h>
#include <linux/swap.h>
#include <linux/mm.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/types.h>
#include <linux/bootmem.h>
#include <linux/highmem.h>
#include <linux/module.h>
#include <asm/setup.h>
#include <asm/segment.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/mmu_context.h>
#include <asm/virtconvert.h>
#include <asm/sections.h>
#include <asm/tlb.h>
#undef DEBUG
/*
* BAD_PAGE is the page that is used for page faults when linux
* is out-of-memory. Older versions of linux just did a
* do_exit(), but using this instead means there is less risk
* for a process dying in kernel mode, possibly leaving a inode
* unused etc..
*
* BAD_PAGETABLE is the accompanying page-table: it is initialized
* to point to BAD_PAGE entries.
*
* ZERO_PAGE is a special page that is used for zero-initialized
* data and COW.
*/
static unsigned long empty_bad_page_table;
static unsigned long empty_bad_page;
unsigned long empty_zero_page;
EXPORT_SYMBOL(empty_zero_page);
/*****************************************************************************/
/*
* paging_init() continues the virtual memory environment setup which
* was begun by the code in arch/head.S.
* The parameters are pointers to where to stick the starting and ending
* addresses of available kernel virtual memory.
*/
void __init paging_init(void)
{
unsigned long zones_size[MAX_NR_ZONES] = {0, };
/* allocate some pages for kernel housekeeping tasks */
empty_bad_page_table = (unsigned long) alloc_bootmem_pages(PAGE_SIZE);
empty_bad_page = (unsigned long) alloc_bootmem_pages(PAGE_SIZE);
empty_zero_page = (unsigned long) alloc_bootmem_pages(PAGE_SIZE);
memset((void *) empty_zero_page, 0, PAGE_SIZE);
#ifdef CONFIG_HIGHMEM
if (get_num_physpages() - num_mappedpages) {
pgd_t *pge;
pud_t *pue;
pmd_t *pme;
pkmap_page_table = alloc_bootmem_pages(PAGE_SIZE);
pge = swapper_pg_dir + pgd_index_k(PKMAP_BASE);
pue = pud_offset(pge, PKMAP_BASE);
pme = pmd_offset(pue, PKMAP_BASE);
__set_pmd(pme, virt_to_phys(pkmap_page_table) | _PAGE_TABLE);
}
#endif
/* distribute the allocatable pages across the various zones and pass them to the allocator
*/
zones_size[ZONE_NORMAL] = max_low_pfn - min_low_pfn;
#ifdef CONFIG_HIGHMEM
zones_size[ZONE_HIGHMEM] = get_num_physpages() - num_mappedpages;
#endif
free_area_init(zones_size);
#ifdef CONFIG_MMU
/* initialise init's MMU context */
init_new_context(&init_task, &init_mm);
#endif
} /* end paging_init() */
/*****************************************************************************/
/*
*
*/
void __init mem_init(void)
{
unsigned long code_size = _etext - _stext;
/* this will put all low memory onto the freelists */
free_all_bootmem();
#if defined(CONFIG_MMU) && defined(CONFIG_HIGHMEM)
{
unsigned long pfn;
for (pfn = get_num_physpages() - 1;
pfn >= num_mappedpages; pfn--)
free_highmem_page(&mem_map[pfn]);
}
#endif
mem_init_print_info(NULL);
if (rom_length > 0 && rom_length >= code_size)
printk("Memory available: %luKiB/%luKiB ROM\n",
(rom_length - code_size) >> 10, rom_length >> 10);
} /* end mem_init() */
/*****************************************************************************/
/*
* free the memory that was only required for initialisation
*/
void free_initmem(void)
{
#if defined(CONFIG_RAMKERNEL) && !defined(CONFIG_PROTECT_KERNEL)
free_initmem_default(-1);
#endif
} /* end free_initmem() */
/*****************************************************************************/
/*
* free the initial ramdisk memory
*/
#ifdef CONFIG_BLK_DEV_INITRD
void __init free_initrd_mem(unsigned long start, unsigned long end)
{
free_reserved_area((void *)start, (void *)end, -1, "initrd");
} /* end free_initrd_mem() */
#endif
| gpl-3.0 |
geminy/aidear | oss/linux/linux-4.7/drivers/mfd/si476x-prop.c | 4584 | 5911 | /*
* drivers/mfd/si476x-prop.c -- Subroutines to access
* properties of si476x chips
*
* Copyright (C) 2012 Innovative Converged Devices(ICD)
* Copyright (C) 2013 Andrey Smirnov
*
* Author: Andrey Smirnov <andrew.smirnov@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* 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/mfd/si476x-core.h>
struct si476x_property_range {
u16 low, high;
};
static bool si476x_core_element_is_in_array(u16 element,
const u16 array[],
size_t size)
{
int i;
for (i = 0; i < size; i++)
if (element == array[i])
return true;
return false;
}
static bool si476x_core_element_is_in_range(u16 element,
const struct si476x_property_range range[],
size_t size)
{
int i;
for (i = 0; i < size; i++)
if (element <= range[i].high && element >= range[i].low)
return true;
return false;
}
static bool si476x_core_is_valid_property_a10(struct si476x_core *core,
u16 property)
{
static const u16 valid_properties[] = {
0x0000,
0x0500, 0x0501,
0x0600,
0x0709, 0x070C, 0x070D, 0x70E, 0x710,
0x0718,
0x1207, 0x1208,
0x2007,
0x2300,
};
static const struct si476x_property_range valid_ranges[] = {
{ 0x0200, 0x0203 },
{ 0x0300, 0x0303 },
{ 0x0400, 0x0404 },
{ 0x0700, 0x0707 },
{ 0x1100, 0x1102 },
{ 0x1200, 0x1204 },
{ 0x1300, 0x1306 },
{ 0x2000, 0x2005 },
{ 0x2100, 0x2104 },
{ 0x2106, 0x2106 },
{ 0x2200, 0x220E },
{ 0x3100, 0x3104 },
{ 0x3207, 0x320F },
{ 0x3300, 0x3304 },
{ 0x3500, 0x3517 },
{ 0x3600, 0x3617 },
{ 0x3700, 0x3717 },
{ 0x4000, 0x4003 },
};
return si476x_core_element_is_in_range(property, valid_ranges,
ARRAY_SIZE(valid_ranges)) ||
si476x_core_element_is_in_array(property, valid_properties,
ARRAY_SIZE(valid_properties));
}
static bool si476x_core_is_valid_property_a20(struct si476x_core *core,
u16 property)
{
static const u16 valid_properties[] = {
0x071B,
0x1006,
0x2210,
0x3401,
};
static const struct si476x_property_range valid_ranges[] = {
{ 0x2215, 0x2219 },
};
return si476x_core_is_valid_property_a10(core, property) ||
si476x_core_element_is_in_range(property, valid_ranges,
ARRAY_SIZE(valid_ranges)) ||
si476x_core_element_is_in_array(property, valid_properties,
ARRAY_SIZE(valid_properties));
}
static bool si476x_core_is_valid_property_a30(struct si476x_core *core,
u16 property)
{
static const u16 valid_properties[] = {
0x071C, 0x071D,
0x1007, 0x1008,
0x220F, 0x2214,
0x2301,
0x3105, 0x3106,
0x3402,
};
static const struct si476x_property_range valid_ranges[] = {
{ 0x0405, 0x0411 },
{ 0x2008, 0x200B },
{ 0x2220, 0x2223 },
{ 0x3100, 0x3106 },
};
return si476x_core_is_valid_property_a20(core, property) ||
si476x_core_element_is_in_range(property, valid_ranges,
ARRAY_SIZE(valid_ranges)) ||
si476x_core_element_is_in_array(property, valid_properties,
ARRAY_SIZE(valid_properties));
}
typedef bool (*valid_property_pred_t) (struct si476x_core *, u16);
static bool si476x_core_is_valid_property(struct si476x_core *core,
u16 property)
{
static const valid_property_pred_t is_valid_property[] = {
[SI476X_REVISION_A10] = si476x_core_is_valid_property_a10,
[SI476X_REVISION_A20] = si476x_core_is_valid_property_a20,
[SI476X_REVISION_A30] = si476x_core_is_valid_property_a30,
};
BUG_ON(core->revision > SI476X_REVISION_A30 ||
core->revision == -1);
return is_valid_property[core->revision](core, property);
}
static bool si476x_core_is_readonly_property(struct si476x_core *core,
u16 property)
{
BUG_ON(core->revision > SI476X_REVISION_A30 ||
core->revision == -1);
switch (core->revision) {
case SI476X_REVISION_A10:
return (property == 0x3200);
case SI476X_REVISION_A20:
return (property == 0x1006 ||
property == 0x2210 ||
property == 0x3200);
case SI476X_REVISION_A30:
return false;
}
return false;
}
static bool si476x_core_regmap_readable_register(struct device *dev,
unsigned int reg)
{
struct i2c_client *client = to_i2c_client(dev);
struct si476x_core *core = i2c_get_clientdata(client);
return si476x_core_is_valid_property(core, (u16) reg);
}
static bool si476x_core_regmap_writable_register(struct device *dev,
unsigned int reg)
{
struct i2c_client *client = to_i2c_client(dev);
struct si476x_core *core = i2c_get_clientdata(client);
return si476x_core_is_valid_property(core, (u16) reg) &&
!si476x_core_is_readonly_property(core, (u16) reg);
}
static int si476x_core_regmap_write(void *context, unsigned int reg,
unsigned int val)
{
return si476x_core_cmd_set_property(context, reg, val);
}
static int si476x_core_regmap_read(void *context, unsigned int reg,
unsigned *val)
{
struct si476x_core *core = context;
int err;
err = si476x_core_cmd_get_property(core, reg);
if (err < 0)
return err;
*val = err;
return 0;
}
static const struct regmap_config si476x_regmap_config = {
.reg_bits = 16,
.val_bits = 16,
.max_register = 0x4003,
.writeable_reg = si476x_core_regmap_writable_register,
.readable_reg = si476x_core_regmap_readable_register,
.reg_read = si476x_core_regmap_read,
.reg_write = si476x_core_regmap_write,
.cache_type = REGCACHE_RBTREE,
};
struct regmap *devm_regmap_init_si476x(struct si476x_core *core)
{
return devm_regmap_init(&core->client->dev, NULL,
core, &si476x_regmap_config);
}
EXPORT_SYMBOL_GPL(devm_regmap_init_si476x);
| gpl-3.0 |
AKuHAK/xcover3ltexx_custom_kernel | kernel/relay.c | 489 | 33424 | /*
* Public API and common code for kernel->userspace relay file support.
*
* See Documentation/filesystems/relay.txt for an overview.
*
* Copyright (C) 2002-2005 - Tom Zanussi (zanussi@us.ibm.com), IBM Corp
* Copyright (C) 1999-2005 - Karim Yaghmour (karim@opersys.com)
*
* Moved to kernel/relay.c by Paul Mundt, 2006.
* November 2006 - CPU hotplug support by Mathieu Desnoyers
* (mathieu.desnoyers@polymtl.ca)
*
* This file is released under the GPL.
*/
#include <linux/errno.h>
#include <linux/stddef.h>
#include <linux/slab.h>
#include <linux/export.h>
#include <linux/string.h>
#include <linux/relay.h>
#include <linux/vmalloc.h>
#include <linux/mm.h>
#include <linux/cpu.h>
#include <linux/splice.h>
/* list of open channels, for cpu hotplug */
static DEFINE_MUTEX(relay_channels_mutex);
static LIST_HEAD(relay_channels);
/*
* close() vm_op implementation for relay file mapping.
*/
static void relay_file_mmap_close(struct vm_area_struct *vma)
{
struct rchan_buf *buf = vma->vm_private_data;
buf->chan->cb->buf_unmapped(buf, vma->vm_file);
}
/*
* fault() vm_op implementation for relay file mapping.
*/
static int relay_buf_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
struct page *page;
struct rchan_buf *buf = vma->vm_private_data;
pgoff_t pgoff = vmf->pgoff;
if (!buf)
return VM_FAULT_OOM;
page = vmalloc_to_page(buf->start + (pgoff << PAGE_SHIFT));
if (!page)
return VM_FAULT_SIGBUS;
get_page(page);
vmf->page = page;
return 0;
}
/*
* vm_ops for relay file mappings.
*/
static const struct vm_operations_struct relay_file_mmap_ops = {
.fault = relay_buf_fault,
.close = relay_file_mmap_close,
};
/*
* allocate an array of pointers of struct page
*/
static struct page **relay_alloc_page_array(unsigned int n_pages)
{
const size_t pa_size = n_pages * sizeof(struct page *);
if (pa_size > PAGE_SIZE)
return vzalloc(pa_size);
return kzalloc(pa_size, GFP_KERNEL);
}
/*
* free an array of pointers of struct page
*/
static void relay_free_page_array(struct page **array)
{
if (is_vmalloc_addr(array))
vfree(array);
else
kfree(array);
}
/**
* relay_mmap_buf: - mmap channel buffer to process address space
* @buf: relay channel buffer
* @vma: vm_area_struct describing memory to be mapped
*
* Returns 0 if ok, negative on error
*
* Caller should already have grabbed mmap_sem.
*/
static int relay_mmap_buf(struct rchan_buf *buf, struct vm_area_struct *vma)
{
unsigned long length = vma->vm_end - vma->vm_start;
struct file *filp = vma->vm_file;
if (!buf)
return -EBADF;
if (length != (unsigned long)buf->chan->alloc_size)
return -EINVAL;
vma->vm_ops = &relay_file_mmap_ops;
vma->vm_flags |= VM_DONTEXPAND;
vma->vm_private_data = buf;
buf->chan->cb->buf_mapped(buf, filp);
return 0;
}
/**
* relay_alloc_buf - allocate a channel buffer
* @buf: the buffer struct
* @size: total size of the buffer
*
* Returns a pointer to the resulting buffer, %NULL if unsuccessful. The
* passed in size will get page aligned, if it isn't already.
*/
static void *relay_alloc_buf(struct rchan_buf *buf, size_t *size)
{
void *mem;
unsigned int i, j, n_pages;
*size = PAGE_ALIGN(*size);
n_pages = *size >> PAGE_SHIFT;
buf->page_array = relay_alloc_page_array(n_pages);
if (!buf->page_array)
return NULL;
for (i = 0; i < n_pages; i++) {
buf->page_array[i] = alloc_page(GFP_KERNEL);
if (unlikely(!buf->page_array[i]))
goto depopulate;
set_page_private(buf->page_array[i], (unsigned long)buf);
}
mem = vmap(buf->page_array, n_pages, VM_MAP, PAGE_KERNEL);
if (!mem)
goto depopulate;
memset(mem, 0, *size);
buf->page_count = n_pages;
return mem;
depopulate:
for (j = 0; j < i; j++)
__free_page(buf->page_array[j]);
relay_free_page_array(buf->page_array);
return NULL;
}
/**
* relay_create_buf - allocate and initialize a channel buffer
* @chan: the relay channel
*
* Returns channel buffer if successful, %NULL otherwise.
*/
static struct rchan_buf *relay_create_buf(struct rchan *chan)
{
struct rchan_buf *buf;
if (chan->n_subbufs > UINT_MAX / sizeof(size_t *))
return NULL;
buf = kzalloc(sizeof(struct rchan_buf), GFP_KERNEL);
if (!buf)
return NULL;
buf->padding = kmalloc(chan->n_subbufs * sizeof(size_t *), GFP_KERNEL);
if (!buf->padding)
goto free_buf;
buf->start = relay_alloc_buf(buf, &chan->alloc_size);
if (!buf->start)
goto free_buf;
buf->chan = chan;
kref_get(&buf->chan->kref);
return buf;
free_buf:
kfree(buf->padding);
kfree(buf);
return NULL;
}
/**
* relay_destroy_channel - free the channel struct
* @kref: target kernel reference that contains the relay channel
*
* Should only be called from kref_put().
*/
static void relay_destroy_channel(struct kref *kref)
{
struct rchan *chan = container_of(kref, struct rchan, kref);
kfree(chan);
}
/**
* relay_destroy_buf - destroy an rchan_buf struct and associated buffer
* @buf: the buffer struct
*/
static void relay_destroy_buf(struct rchan_buf *buf)
{
struct rchan *chan = buf->chan;
unsigned int i;
if (likely(buf->start)) {
vunmap(buf->start);
for (i = 0; i < buf->page_count; i++)
__free_page(buf->page_array[i]);
relay_free_page_array(buf->page_array);
}
chan->buf[buf->cpu] = NULL;
kfree(buf->padding);
kfree(buf);
kref_put(&chan->kref, relay_destroy_channel);
}
/**
* relay_remove_buf - remove a channel buffer
* @kref: target kernel reference that contains the relay buffer
*
* Removes the file from the fileystem, which also frees the
* rchan_buf_struct and the channel buffer. Should only be called from
* kref_put().
*/
static void relay_remove_buf(struct kref *kref)
{
struct rchan_buf *buf = container_of(kref, struct rchan_buf, kref);
relay_destroy_buf(buf);
}
/**
* relay_buf_empty - boolean, is the channel buffer empty?
* @buf: channel buffer
*
* Returns 1 if the buffer is empty, 0 otherwise.
*/
static int relay_buf_empty(struct rchan_buf *buf)
{
return (buf->subbufs_produced - buf->subbufs_consumed) ? 0 : 1;
}
/**
* relay_buf_full - boolean, is the channel buffer full?
* @buf: channel buffer
*
* Returns 1 if the buffer is full, 0 otherwise.
*/
int relay_buf_full(struct rchan_buf *buf)
{
size_t ready = buf->subbufs_produced - buf->subbufs_consumed;
return (ready >= buf->chan->n_subbufs) ? 1 : 0;
}
EXPORT_SYMBOL_GPL(relay_buf_full);
/*
* High-level relay kernel API and associated functions.
*/
/*
* rchan_callback implementations defining default channel behavior. Used
* in place of corresponding NULL values in client callback struct.
*/
/*
* subbuf_start() default callback. Does nothing.
*/
static int subbuf_start_default_callback (struct rchan_buf *buf,
void *subbuf,
void *prev_subbuf,
size_t prev_padding)
{
if (relay_buf_full(buf))
return 0;
return 1;
}
/*
* buf_mapped() default callback. Does nothing.
*/
static void buf_mapped_default_callback(struct rchan_buf *buf,
struct file *filp)
{
}
/*
* buf_unmapped() default callback. Does nothing.
*/
static void buf_unmapped_default_callback(struct rchan_buf *buf,
struct file *filp)
{
}
/*
* create_buf_file_create() default callback. Does nothing.
*/
static struct dentry *create_buf_file_default_callback(const char *filename,
struct dentry *parent,
umode_t mode,
struct rchan_buf *buf,
int *is_global)
{
return NULL;
}
/*
* remove_buf_file() default callback. Does nothing.
*/
static int remove_buf_file_default_callback(struct dentry *dentry)
{
return -EINVAL;
}
/* relay channel default callbacks */
static struct rchan_callbacks default_channel_callbacks = {
.subbuf_start = subbuf_start_default_callback,
.buf_mapped = buf_mapped_default_callback,
.buf_unmapped = buf_unmapped_default_callback,
.create_buf_file = create_buf_file_default_callback,
.remove_buf_file = remove_buf_file_default_callback,
};
/**
* wakeup_readers - wake up readers waiting on a channel
* @data: contains the channel buffer
*
* This is the timer function used to defer reader waking.
*/
static void wakeup_readers(unsigned long data)
{
struct rchan_buf *buf = (struct rchan_buf *)data;
wake_up_interruptible(&buf->read_wait);
}
/**
* __relay_reset - reset a channel buffer
* @buf: the channel buffer
* @init: 1 if this is a first-time initialization
*
* See relay_reset() for description of effect.
*/
static void __relay_reset(struct rchan_buf *buf, unsigned int init)
{
size_t i;
if (init) {
init_waitqueue_head(&buf->read_wait);
kref_init(&buf->kref);
setup_timer(&buf->timer, wakeup_readers, (unsigned long)buf);
} else
del_timer_sync(&buf->timer);
buf->subbufs_produced = 0;
buf->subbufs_consumed = 0;
buf->bytes_consumed = 0;
buf->finalized = 0;
buf->data = buf->start;
buf->offset = 0;
for (i = 0; i < buf->chan->n_subbufs; i++)
buf->padding[i] = 0;
buf->chan->cb->subbuf_start(buf, buf->data, NULL, 0);
}
/**
* relay_reset - reset the channel
* @chan: the channel
*
* This has the effect of erasing all data from all channel buffers
* and restarting the channel in its initial state. The buffers
* are not freed, so any mappings are still in effect.
*
* NOTE. Care should be taken that the channel isn't actually
* being used by anything when this call is made.
*/
void relay_reset(struct rchan *chan)
{
unsigned int i;
if (!chan)
return;
if (chan->is_global && chan->buf[0]) {
__relay_reset(chan->buf[0], 0);
return;
}
mutex_lock(&relay_channels_mutex);
for_each_possible_cpu(i)
if (chan->buf[i])
__relay_reset(chan->buf[i], 0);
mutex_unlock(&relay_channels_mutex);
}
EXPORT_SYMBOL_GPL(relay_reset);
static inline void relay_set_buf_dentry(struct rchan_buf *buf,
struct dentry *dentry)
{
buf->dentry = dentry;
buf->dentry->d_inode->i_size = buf->early_bytes;
}
static struct dentry *relay_create_buf_file(struct rchan *chan,
struct rchan_buf *buf,
unsigned int cpu)
{
struct dentry *dentry;
char *tmpname;
tmpname = kzalloc(NAME_MAX + 1, GFP_KERNEL);
if (!tmpname)
return NULL;
snprintf(tmpname, NAME_MAX, "%s%d", chan->base_filename, cpu);
/* Create file in fs */
dentry = chan->cb->create_buf_file(tmpname, chan->parent,
S_IRUSR, buf,
&chan->is_global);
kfree(tmpname);
return dentry;
}
/*
* relay_open_buf - create a new relay channel buffer
*
* used by relay_open() and CPU hotplug.
*/
static struct rchan_buf *relay_open_buf(struct rchan *chan, unsigned int cpu)
{
struct rchan_buf *buf = NULL;
struct dentry *dentry;
if (chan->is_global)
return chan->buf[0];
buf = relay_create_buf(chan);
if (!buf)
return NULL;
if (chan->has_base_filename) {
dentry = relay_create_buf_file(chan, buf, cpu);
if (!dentry)
goto free_buf;
relay_set_buf_dentry(buf, dentry);
}
buf->cpu = cpu;
__relay_reset(buf, 1);
if(chan->is_global) {
chan->buf[0] = buf;
buf->cpu = 0;
}
return buf;
free_buf:
relay_destroy_buf(buf);
return NULL;
}
/**
* relay_close_buf - close a channel buffer
* @buf: channel buffer
*
* Marks the buffer finalized and restores the default callbacks.
* The channel buffer and channel buffer data structure are then freed
* automatically when the last reference is given up.
*/
static void relay_close_buf(struct rchan_buf *buf)
{
buf->finalized = 1;
del_timer_sync(&buf->timer);
buf->chan->cb->remove_buf_file(buf->dentry);
kref_put(&buf->kref, relay_remove_buf);
}
static void setup_callbacks(struct rchan *chan,
struct rchan_callbacks *cb)
{
if (!cb) {
chan->cb = &default_channel_callbacks;
return;
}
if (!cb->subbuf_start)
cb->subbuf_start = subbuf_start_default_callback;
if (!cb->buf_mapped)
cb->buf_mapped = buf_mapped_default_callback;
if (!cb->buf_unmapped)
cb->buf_unmapped = buf_unmapped_default_callback;
if (!cb->create_buf_file)
cb->create_buf_file = create_buf_file_default_callback;
if (!cb->remove_buf_file)
cb->remove_buf_file = remove_buf_file_default_callback;
chan->cb = cb;
}
/**
* relay_hotcpu_callback - CPU hotplug callback
* @nb: notifier block
* @action: hotplug action to take
* @hcpu: CPU number
*
* Returns the success/failure of the operation. (%NOTIFY_OK, %NOTIFY_BAD)
*/
static int relay_hotcpu_callback(struct notifier_block *nb,
unsigned long action,
void *hcpu)
{
unsigned int hotcpu = (unsigned long)hcpu;
struct rchan *chan;
switch(action) {
case CPU_UP_PREPARE:
case CPU_UP_PREPARE_FROZEN:
mutex_lock(&relay_channels_mutex);
list_for_each_entry(chan, &relay_channels, list) {
if (chan->buf[hotcpu])
continue;
chan->buf[hotcpu] = relay_open_buf(chan, hotcpu);
if(!chan->buf[hotcpu]) {
printk(KERN_ERR
"relay_hotcpu_callback: cpu %d buffer "
"creation failed\n", hotcpu);
mutex_unlock(&relay_channels_mutex);
return notifier_from_errno(-ENOMEM);
}
}
mutex_unlock(&relay_channels_mutex);
break;
case CPU_DEAD:
case CPU_DEAD_FROZEN:
/* No need to flush the cpu : will be flushed upon
* final relay_flush() call. */
break;
}
return NOTIFY_OK;
}
/**
* relay_open - create a new relay channel
* @base_filename: base name of files to create, %NULL for buffering only
* @parent: dentry of parent directory, %NULL for root directory or buffer
* @subbuf_size: size of sub-buffers
* @n_subbufs: number of sub-buffers
* @cb: client callback functions
* @private_data: user-defined data
*
* Returns channel pointer if successful, %NULL otherwise.
*
* Creates a channel buffer for each cpu using the sizes and
* attributes specified. The created channel buffer files
* will be named base_filename0...base_filenameN-1. File
* permissions will be %S_IRUSR.
*/
struct rchan *relay_open(const char *base_filename,
struct dentry *parent,
size_t subbuf_size,
size_t n_subbufs,
struct rchan_callbacks *cb,
void *private_data)
{
unsigned int i;
struct rchan *chan;
if (!(subbuf_size && n_subbufs))
return NULL;
if (subbuf_size > UINT_MAX / n_subbufs)
return NULL;
chan = kzalloc(sizeof(struct rchan), GFP_KERNEL);
if (!chan)
return NULL;
chan->version = RELAYFS_CHANNEL_VERSION;
chan->n_subbufs = n_subbufs;
chan->subbuf_size = subbuf_size;
chan->alloc_size = PAGE_ALIGN(subbuf_size * n_subbufs);
chan->parent = parent;
chan->private_data = private_data;
if (base_filename) {
chan->has_base_filename = 1;
strlcpy(chan->base_filename, base_filename, NAME_MAX);
}
setup_callbacks(chan, cb);
kref_init(&chan->kref);
mutex_lock(&relay_channels_mutex);
for_each_online_cpu(i) {
chan->buf[i] = relay_open_buf(chan, i);
if (!chan->buf[i])
goto free_bufs;
}
list_add(&chan->list, &relay_channels);
mutex_unlock(&relay_channels_mutex);
return chan;
free_bufs:
for_each_possible_cpu(i) {
if (chan->buf[i])
relay_close_buf(chan->buf[i]);
}
kref_put(&chan->kref, relay_destroy_channel);
mutex_unlock(&relay_channels_mutex);
return NULL;
}
EXPORT_SYMBOL_GPL(relay_open);
struct rchan_percpu_buf_dispatcher {
struct rchan_buf *buf;
struct dentry *dentry;
};
/* Called in atomic context. */
static void __relay_set_buf_dentry(void *info)
{
struct rchan_percpu_buf_dispatcher *p = info;
relay_set_buf_dentry(p->buf, p->dentry);
}
/**
* relay_late_setup_files - triggers file creation
* @chan: channel to operate on
* @base_filename: base name of files to create
* @parent: dentry of parent directory, %NULL for root directory
*
* Returns 0 if successful, non-zero otherwise.
*
* Use to setup files for a previously buffer-only channel.
* Useful to do early tracing in kernel, before VFS is up, for example.
*/
int relay_late_setup_files(struct rchan *chan,
const char *base_filename,
struct dentry *parent)
{
int err = 0;
unsigned int i, curr_cpu;
unsigned long flags;
struct dentry *dentry;
struct rchan_percpu_buf_dispatcher disp;
if (!chan || !base_filename)
return -EINVAL;
strlcpy(chan->base_filename, base_filename, NAME_MAX);
mutex_lock(&relay_channels_mutex);
/* Is chan already set up? */
if (unlikely(chan->has_base_filename)) {
mutex_unlock(&relay_channels_mutex);
return -EEXIST;
}
chan->has_base_filename = 1;
chan->parent = parent;
curr_cpu = get_cpu();
/*
* The CPU hotplug notifier ran before us and created buffers with
* no files associated. So it's safe to call relay_setup_buf_file()
* on all currently online CPUs.
*/
for_each_online_cpu(i) {
if (unlikely(!chan->buf[i])) {
WARN_ONCE(1, KERN_ERR "CPU has no buffer!\n");
err = -EINVAL;
break;
}
dentry = relay_create_buf_file(chan, chan->buf[i], i);
if (unlikely(!dentry)) {
err = -EINVAL;
break;
}
if (curr_cpu == i) {
local_irq_save(flags);
relay_set_buf_dentry(chan->buf[i], dentry);
local_irq_restore(flags);
} else {
disp.buf = chan->buf[i];
disp.dentry = dentry;
smp_mb();
/* relay_channels_mutex must be held, so wait. */
err = smp_call_function_single(i,
__relay_set_buf_dentry,
&disp, 1);
}
if (unlikely(err))
break;
}
put_cpu();
mutex_unlock(&relay_channels_mutex);
return err;
}
/**
* relay_switch_subbuf - switch to a new sub-buffer
* @buf: channel buffer
* @length: size of current event
*
* Returns either the length passed in or 0 if full.
*
* Performs sub-buffer-switch tasks such as invoking callbacks,
* updating padding counts, waking up readers, etc.
*/
size_t relay_switch_subbuf(struct rchan_buf *buf, size_t length)
{
void *old, *new;
size_t old_subbuf, new_subbuf;
if (unlikely(length > buf->chan->subbuf_size))
goto toobig;
if (buf->offset != buf->chan->subbuf_size + 1) {
buf->prev_padding = buf->chan->subbuf_size - buf->offset;
old_subbuf = buf->subbufs_produced % buf->chan->n_subbufs;
buf->padding[old_subbuf] = buf->prev_padding;
buf->subbufs_produced++;
if (buf->dentry)
buf->dentry->d_inode->i_size +=
buf->chan->subbuf_size -
buf->padding[old_subbuf];
else
buf->early_bytes += buf->chan->subbuf_size -
buf->padding[old_subbuf];
smp_mb();
if (waitqueue_active(&buf->read_wait))
/*
* Calling wake_up_interruptible() from here
* will deadlock if we happen to be logging
* from the scheduler (trying to re-grab
* rq->lock), so defer it.
*/
mod_timer(&buf->timer, jiffies + 1);
}
old = buf->data;
new_subbuf = buf->subbufs_produced % buf->chan->n_subbufs;
new = buf->start + new_subbuf * buf->chan->subbuf_size;
buf->offset = 0;
if (!buf->chan->cb->subbuf_start(buf, new, old, buf->prev_padding)) {
buf->offset = buf->chan->subbuf_size + 1;
return 0;
}
buf->data = new;
buf->padding[new_subbuf] = 0;
if (unlikely(length + buf->offset > buf->chan->subbuf_size))
goto toobig;
return length;
toobig:
buf->chan->last_toobig = length;
return 0;
}
EXPORT_SYMBOL_GPL(relay_switch_subbuf);
/**
* relay_subbufs_consumed - update the buffer's sub-buffers-consumed count
* @chan: the channel
* @cpu: the cpu associated with the channel buffer to update
* @subbufs_consumed: number of sub-buffers to add to current buf's count
*
* Adds to the channel buffer's consumed sub-buffer count.
* subbufs_consumed should be the number of sub-buffers newly consumed,
* not the total consumed.
*
* NOTE. Kernel clients don't need to call this function if the channel
* mode is 'overwrite'.
*/
void relay_subbufs_consumed(struct rchan *chan,
unsigned int cpu,
size_t subbufs_consumed)
{
struct rchan_buf *buf;
if (!chan)
return;
if (cpu >= NR_CPUS || !chan->buf[cpu] ||
subbufs_consumed > chan->n_subbufs)
return;
buf = chan->buf[cpu];
if (subbufs_consumed > buf->subbufs_produced - buf->subbufs_consumed)
buf->subbufs_consumed = buf->subbufs_produced;
else
buf->subbufs_consumed += subbufs_consumed;
}
EXPORT_SYMBOL_GPL(relay_subbufs_consumed);
/**
* relay_close - close the channel
* @chan: the channel
*
* Closes all channel buffers and frees the channel.
*/
void relay_close(struct rchan *chan)
{
unsigned int i;
if (!chan)
return;
mutex_lock(&relay_channels_mutex);
if (chan->is_global && chan->buf[0])
relay_close_buf(chan->buf[0]);
else
for_each_possible_cpu(i)
if (chan->buf[i])
relay_close_buf(chan->buf[i]);
if (chan->last_toobig)
printk(KERN_WARNING "relay: one or more items not logged "
"[item size (%Zd) > sub-buffer size (%Zd)]\n",
chan->last_toobig, chan->subbuf_size);
list_del(&chan->list);
kref_put(&chan->kref, relay_destroy_channel);
mutex_unlock(&relay_channels_mutex);
}
EXPORT_SYMBOL_GPL(relay_close);
/**
* relay_flush - close the channel
* @chan: the channel
*
* Flushes all channel buffers, i.e. forces buffer switch.
*/
void relay_flush(struct rchan *chan)
{
unsigned int i;
if (!chan)
return;
if (chan->is_global && chan->buf[0]) {
relay_switch_subbuf(chan->buf[0], 0);
return;
}
mutex_lock(&relay_channels_mutex);
for_each_possible_cpu(i)
if (chan->buf[i])
relay_switch_subbuf(chan->buf[i], 0);
mutex_unlock(&relay_channels_mutex);
}
EXPORT_SYMBOL_GPL(relay_flush);
/**
* relay_file_open - open file op for relay files
* @inode: the inode
* @filp: the file
*
* Increments the channel buffer refcount.
*/
static int relay_file_open(struct inode *inode, struct file *filp)
{
struct rchan_buf *buf = inode->i_private;
kref_get(&buf->kref);
filp->private_data = buf;
return nonseekable_open(inode, filp);
}
/**
* relay_file_mmap - mmap file op for relay files
* @filp: the file
* @vma: the vma describing what to map
*
* Calls upon relay_mmap_buf() to map the file into user space.
*/
static int relay_file_mmap(struct file *filp, struct vm_area_struct *vma)
{
struct rchan_buf *buf = filp->private_data;
return relay_mmap_buf(buf, vma);
}
/**
* relay_file_poll - poll file op for relay files
* @filp: the file
* @wait: poll table
*
* Poll implemention.
*/
static unsigned int relay_file_poll(struct file *filp, poll_table *wait)
{
unsigned int mask = 0;
struct rchan_buf *buf = filp->private_data;
if (buf->finalized)
return POLLERR;
if (filp->f_mode & FMODE_READ) {
poll_wait(filp, &buf->read_wait, wait);
if (!relay_buf_empty(buf))
mask |= POLLIN | POLLRDNORM;
}
return mask;
}
/**
* relay_file_release - release file op for relay files
* @inode: the inode
* @filp: the file
*
* Decrements the channel refcount, as the filesystem is
* no longer using it.
*/
static int relay_file_release(struct inode *inode, struct file *filp)
{
struct rchan_buf *buf = filp->private_data;
kref_put(&buf->kref, relay_remove_buf);
return 0;
}
/*
* relay_file_read_consume - update the consumed count for the buffer
*/
static void relay_file_read_consume(struct rchan_buf *buf,
size_t read_pos,
size_t bytes_consumed)
{
size_t subbuf_size = buf->chan->subbuf_size;
size_t n_subbufs = buf->chan->n_subbufs;
size_t read_subbuf;
if (buf->subbufs_produced == buf->subbufs_consumed &&
buf->offset == buf->bytes_consumed)
return;
if (buf->bytes_consumed + bytes_consumed > subbuf_size) {
relay_subbufs_consumed(buf->chan, buf->cpu, 1);
buf->bytes_consumed = 0;
}
buf->bytes_consumed += bytes_consumed;
if (!read_pos)
read_subbuf = buf->subbufs_consumed % n_subbufs;
else
read_subbuf = read_pos / buf->chan->subbuf_size;
if (buf->bytes_consumed + buf->padding[read_subbuf] == subbuf_size) {
if ((read_subbuf == buf->subbufs_produced % n_subbufs) &&
(buf->offset == subbuf_size))
return;
relay_subbufs_consumed(buf->chan, buf->cpu, 1);
buf->bytes_consumed = 0;
}
}
/*
* relay_file_read_avail - boolean, are there unconsumed bytes available?
*/
static int relay_file_read_avail(struct rchan_buf *buf, size_t read_pos)
{
size_t subbuf_size = buf->chan->subbuf_size;
size_t n_subbufs = buf->chan->n_subbufs;
size_t produced = buf->subbufs_produced;
size_t consumed = buf->subbufs_consumed;
relay_file_read_consume(buf, read_pos, 0);
consumed = buf->subbufs_consumed;
if (unlikely(buf->offset > subbuf_size)) {
if (produced == consumed)
return 0;
return 1;
}
if (unlikely(produced - consumed >= n_subbufs)) {
consumed = produced - n_subbufs + 1;
buf->subbufs_consumed = consumed;
buf->bytes_consumed = 0;
}
produced = (produced % n_subbufs) * subbuf_size + buf->offset;
consumed = (consumed % n_subbufs) * subbuf_size + buf->bytes_consumed;
if (consumed > produced)
produced += n_subbufs * subbuf_size;
if (consumed == produced) {
if (buf->offset == subbuf_size &&
buf->subbufs_produced > buf->subbufs_consumed)
return 1;
return 0;
}
return 1;
}
/**
* relay_file_read_subbuf_avail - return bytes available in sub-buffer
* @read_pos: file read position
* @buf: relay channel buffer
*/
static size_t relay_file_read_subbuf_avail(size_t read_pos,
struct rchan_buf *buf)
{
size_t padding, avail = 0;
size_t read_subbuf, read_offset, write_subbuf, write_offset;
size_t subbuf_size = buf->chan->subbuf_size;
write_subbuf = (buf->data - buf->start) / subbuf_size;
write_offset = buf->offset > subbuf_size ? subbuf_size : buf->offset;
read_subbuf = read_pos / subbuf_size;
read_offset = read_pos % subbuf_size;
padding = buf->padding[read_subbuf];
if (read_subbuf == write_subbuf) {
if (read_offset + padding < write_offset)
avail = write_offset - (read_offset + padding);
} else
avail = (subbuf_size - padding) - read_offset;
return avail;
}
/**
* relay_file_read_start_pos - find the first available byte to read
* @read_pos: file read position
* @buf: relay channel buffer
*
* If the @read_pos is in the middle of padding, return the
* position of the first actually available byte, otherwise
* return the original value.
*/
static size_t relay_file_read_start_pos(size_t read_pos,
struct rchan_buf *buf)
{
size_t read_subbuf, padding, padding_start, padding_end;
size_t subbuf_size = buf->chan->subbuf_size;
size_t n_subbufs = buf->chan->n_subbufs;
size_t consumed = buf->subbufs_consumed % n_subbufs;
if (!read_pos)
read_pos = consumed * subbuf_size + buf->bytes_consumed;
read_subbuf = read_pos / subbuf_size;
padding = buf->padding[read_subbuf];
padding_start = (read_subbuf + 1) * subbuf_size - padding;
padding_end = (read_subbuf + 1) * subbuf_size;
if (read_pos >= padding_start && read_pos < padding_end) {
read_subbuf = (read_subbuf + 1) % n_subbufs;
read_pos = read_subbuf * subbuf_size;
}
return read_pos;
}
/**
* relay_file_read_end_pos - return the new read position
* @read_pos: file read position
* @buf: relay channel buffer
* @count: number of bytes to be read
*/
static size_t relay_file_read_end_pos(struct rchan_buf *buf,
size_t read_pos,
size_t count)
{
size_t read_subbuf, padding, end_pos;
size_t subbuf_size = buf->chan->subbuf_size;
size_t n_subbufs = buf->chan->n_subbufs;
read_subbuf = read_pos / subbuf_size;
padding = buf->padding[read_subbuf];
if (read_pos % subbuf_size + count + padding == subbuf_size)
end_pos = (read_subbuf + 1) * subbuf_size;
else
end_pos = read_pos + count;
if (end_pos >= subbuf_size * n_subbufs)
end_pos = 0;
return end_pos;
}
/*
* subbuf_read_actor - read up to one subbuf's worth of data
*/
static int subbuf_read_actor(size_t read_start,
struct rchan_buf *buf,
size_t avail,
read_descriptor_t *desc)
{
void *from;
int ret = 0;
from = buf->start + read_start;
ret = avail;
if (copy_to_user(desc->arg.buf, from, avail)) {
desc->error = -EFAULT;
ret = 0;
}
desc->arg.data += ret;
desc->written += ret;
desc->count -= ret;
return ret;
}
typedef int (*subbuf_actor_t) (size_t read_start,
struct rchan_buf *buf,
size_t avail,
read_descriptor_t *desc);
/*
* relay_file_read_subbufs - read count bytes, bridging subbuf boundaries
*/
static ssize_t relay_file_read_subbufs(struct file *filp, loff_t *ppos,
subbuf_actor_t subbuf_actor,
read_descriptor_t *desc)
{
struct rchan_buf *buf = filp->private_data;
size_t read_start, avail;
int ret;
if (!desc->count)
return 0;
mutex_lock(&file_inode(filp)->i_mutex);
do {
if (!relay_file_read_avail(buf, *ppos))
break;
read_start = relay_file_read_start_pos(*ppos, buf);
avail = relay_file_read_subbuf_avail(read_start, buf);
if (!avail)
break;
avail = min(desc->count, avail);
ret = subbuf_actor(read_start, buf, avail, desc);
if (desc->error < 0)
break;
if (ret) {
relay_file_read_consume(buf, read_start, ret);
*ppos = relay_file_read_end_pos(buf, read_start, ret);
}
} while (desc->count && ret);
mutex_unlock(&file_inode(filp)->i_mutex);
return desc->written;
}
static ssize_t relay_file_read(struct file *filp,
char __user *buffer,
size_t count,
loff_t *ppos)
{
read_descriptor_t desc;
desc.written = 0;
desc.count = count;
desc.arg.buf = buffer;
desc.error = 0;
return relay_file_read_subbufs(filp, ppos, subbuf_read_actor, &desc);
}
static void relay_consume_bytes(struct rchan_buf *rbuf, int bytes_consumed)
{
rbuf->bytes_consumed += bytes_consumed;
if (rbuf->bytes_consumed >= rbuf->chan->subbuf_size) {
relay_subbufs_consumed(rbuf->chan, rbuf->cpu, 1);
rbuf->bytes_consumed %= rbuf->chan->subbuf_size;
}
}
static void relay_pipe_buf_release(struct pipe_inode_info *pipe,
struct pipe_buffer *buf)
{
struct rchan_buf *rbuf;
rbuf = (struct rchan_buf *)page_private(buf->page);
relay_consume_bytes(rbuf, buf->private);
}
static const struct pipe_buf_operations relay_pipe_buf_ops = {
.can_merge = 0,
.map = generic_pipe_buf_map,
.unmap = generic_pipe_buf_unmap,
.confirm = generic_pipe_buf_confirm,
.release = relay_pipe_buf_release,
.steal = generic_pipe_buf_steal,
.get = generic_pipe_buf_get,
};
static void relay_page_release(struct splice_pipe_desc *spd, unsigned int i)
{
}
/*
* subbuf_splice_actor - splice up to one subbuf's worth of data
*/
static ssize_t subbuf_splice_actor(struct file *in,
loff_t *ppos,
struct pipe_inode_info *pipe,
size_t len,
unsigned int flags,
int *nonpad_ret)
{
unsigned int pidx, poff, total_len, subbuf_pages, nr_pages;
struct rchan_buf *rbuf = in->private_data;
unsigned int subbuf_size = rbuf->chan->subbuf_size;
uint64_t pos = (uint64_t) *ppos;
uint32_t alloc_size = (uint32_t) rbuf->chan->alloc_size;
size_t read_start = (size_t) do_div(pos, alloc_size);
size_t read_subbuf = read_start / subbuf_size;
size_t padding = rbuf->padding[read_subbuf];
size_t nonpad_end = read_subbuf * subbuf_size + subbuf_size - padding;
struct page *pages[PIPE_DEF_BUFFERS];
struct partial_page partial[PIPE_DEF_BUFFERS];
struct splice_pipe_desc spd = {
.pages = pages,
.nr_pages = 0,
.nr_pages_max = PIPE_DEF_BUFFERS,
.partial = partial,
.flags = flags,
.ops = &relay_pipe_buf_ops,
.spd_release = relay_page_release,
};
ssize_t ret;
if (rbuf->subbufs_produced == rbuf->subbufs_consumed)
return 0;
if (splice_grow_spd(pipe, &spd))
return -ENOMEM;
/*
* Adjust read len, if longer than what is available
*/
if (len > (subbuf_size - read_start % subbuf_size))
len = subbuf_size - read_start % subbuf_size;
subbuf_pages = rbuf->chan->alloc_size >> PAGE_SHIFT;
pidx = (read_start / PAGE_SIZE) % subbuf_pages;
poff = read_start & ~PAGE_MASK;
nr_pages = min_t(unsigned int, subbuf_pages, pipe->buffers);
for (total_len = 0; spd.nr_pages < nr_pages; spd.nr_pages++) {
unsigned int this_len, this_end, private;
unsigned int cur_pos = read_start + total_len;
if (!len)
break;
this_len = min_t(unsigned long, len, PAGE_SIZE - poff);
private = this_len;
spd.pages[spd.nr_pages] = rbuf->page_array[pidx];
spd.partial[spd.nr_pages].offset = poff;
this_end = cur_pos + this_len;
if (this_end >= nonpad_end) {
this_len = nonpad_end - cur_pos;
private = this_len + padding;
}
spd.partial[spd.nr_pages].len = this_len;
spd.partial[spd.nr_pages].private = private;
len -= this_len;
total_len += this_len;
poff = 0;
pidx = (pidx + 1) % subbuf_pages;
if (this_end >= nonpad_end) {
spd.nr_pages++;
break;
}
}
ret = 0;
if (!spd.nr_pages)
goto out;
ret = *nonpad_ret = splice_to_pipe(pipe, &spd);
if (ret < 0 || ret < total_len)
goto out;
if (read_start + ret == nonpad_end)
ret += padding;
out:
splice_shrink_spd(&spd);
return ret;
}
static ssize_t relay_file_splice_read(struct file *in,
loff_t *ppos,
struct pipe_inode_info *pipe,
size_t len,
unsigned int flags)
{
ssize_t spliced;
int ret;
int nonpad_ret = 0;
ret = 0;
spliced = 0;
while (len && !spliced) {
ret = subbuf_splice_actor(in, ppos, pipe, len, flags, &nonpad_ret);
if (ret < 0)
break;
else if (!ret) {
if (flags & SPLICE_F_NONBLOCK)
ret = -EAGAIN;
break;
}
*ppos += ret;
if (ret > len)
len = 0;
else
len -= ret;
spliced += nonpad_ret;
nonpad_ret = 0;
}
if (spliced)
return spliced;
return ret;
}
const struct file_operations relay_file_operations = {
.open = relay_file_open,
.poll = relay_file_poll,
.mmap = relay_file_mmap,
.read = relay_file_read,
.llseek = no_llseek,
.release = relay_file_release,
.splice_read = relay_file_splice_read,
};
EXPORT_SYMBOL_GPL(relay_file_operations);
static __init int relay_init(void)
{
hotcpu_notifier(relay_hotcpu_callback, 0);
return 0;
}
early_initcall(relay_init);
| gpl-3.0 |
sdphome/UHF_Reader | linux-3.14.52/drivers/gpu/drm/radeon/rv770_smc.c | 2281 | 15434 | /*
* Copyright 2011 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Authors: Alex Deucher
*/
#include <linux/firmware.h>
#include "drmP.h"
#include "radeon.h"
#include "rv770d.h"
#include "rv770_dpm.h"
#include "rv770_smc.h"
#include "atom.h"
#include "radeon_ucode.h"
#define FIRST_SMC_INT_VECT_REG 0xFFD8
#define FIRST_INT_VECT_S19 0xFFC0
static const u8 rv770_smc_int_vectors[] =
{
0x08, 0x10, 0x08, 0x10,
0x08, 0x10, 0x08, 0x10,
0x08, 0x10, 0x08, 0x10,
0x08, 0x10, 0x08, 0x10,
0x08, 0x10, 0x08, 0x10,
0x08, 0x10, 0x08, 0x10,
0x08, 0x10, 0x08, 0x10,
0x08, 0x10, 0x08, 0x10,
0x08, 0x10, 0x08, 0x10,
0x08, 0x10, 0x08, 0x10,
0x08, 0x10, 0x08, 0x10,
0x08, 0x10, 0x08, 0x10,
0x08, 0x10, 0x0C, 0xD7,
0x08, 0x2B, 0x08, 0x10,
0x03, 0x51, 0x03, 0x51,
0x03, 0x51, 0x03, 0x51
};
static const u8 rv730_smc_int_vectors[] =
{
0x08, 0x15, 0x08, 0x15,
0x08, 0x15, 0x08, 0x15,
0x08, 0x15, 0x08, 0x15,
0x08, 0x15, 0x08, 0x15,
0x08, 0x15, 0x08, 0x15,
0x08, 0x15, 0x08, 0x15,
0x08, 0x15, 0x08, 0x15,
0x08, 0x15, 0x08, 0x15,
0x08, 0x15, 0x08, 0x15,
0x08, 0x15, 0x08, 0x15,
0x08, 0x15, 0x08, 0x15,
0x08, 0x15, 0x08, 0x15,
0x08, 0x15, 0x0C, 0xBB,
0x08, 0x30, 0x08, 0x15,
0x03, 0x56, 0x03, 0x56,
0x03, 0x56, 0x03, 0x56
};
static const u8 rv710_smc_int_vectors[] =
{
0x08, 0x04, 0x08, 0x04,
0x08, 0x04, 0x08, 0x04,
0x08, 0x04, 0x08, 0x04,
0x08, 0x04, 0x08, 0x04,
0x08, 0x04, 0x08, 0x04,
0x08, 0x04, 0x08, 0x04,
0x08, 0x04, 0x08, 0x04,
0x08, 0x04, 0x08, 0x04,
0x08, 0x04, 0x08, 0x04,
0x08, 0x04, 0x08, 0x04,
0x08, 0x04, 0x08, 0x04,
0x08, 0x04, 0x08, 0x04,
0x08, 0x04, 0x0C, 0xCB,
0x08, 0x1F, 0x08, 0x04,
0x03, 0x51, 0x03, 0x51,
0x03, 0x51, 0x03, 0x51
};
static const u8 rv740_smc_int_vectors[] =
{
0x08, 0x10, 0x08, 0x10,
0x08, 0x10, 0x08, 0x10,
0x08, 0x10, 0x08, 0x10,
0x08, 0x10, 0x08, 0x10,
0x08, 0x10, 0x08, 0x10,
0x08, 0x10, 0x08, 0x10,
0x08, 0x10, 0x08, 0x10,
0x08, 0x10, 0x08, 0x10,
0x08, 0x10, 0x08, 0x10,
0x08, 0x10, 0x08, 0x10,
0x08, 0x10, 0x08, 0x10,
0x08, 0x10, 0x08, 0x10,
0x08, 0x10, 0x0C, 0xD7,
0x08, 0x2B, 0x08, 0x10,
0x03, 0x51, 0x03, 0x51,
0x03, 0x51, 0x03, 0x51
};
static const u8 cedar_smc_int_vectors[] =
{
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x11, 0x8B,
0x0B, 0x20, 0x0B, 0x05,
0x04, 0xF6, 0x04, 0xF6,
0x04, 0xF6, 0x04, 0xF6
};
static const u8 redwood_smc_int_vectors[] =
{
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x11, 0x8B,
0x0B, 0x20, 0x0B, 0x05,
0x04, 0xF6, 0x04, 0xF6,
0x04, 0xF6, 0x04, 0xF6
};
static const u8 juniper_smc_int_vectors[] =
{
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x11, 0x8B,
0x0B, 0x20, 0x0B, 0x05,
0x04, 0xF6, 0x04, 0xF6,
0x04, 0xF6, 0x04, 0xF6
};
static const u8 cypress_smc_int_vectors[] =
{
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x0B, 0x05,
0x0B, 0x05, 0x11, 0x8B,
0x0B, 0x20, 0x0B, 0x05,
0x04, 0xF6, 0x04, 0xF6,
0x04, 0xF6, 0x04, 0xF6
};
static const u8 barts_smc_int_vectors[] =
{
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x12, 0xAA,
0x0C, 0x2F, 0x15, 0xF6,
0x15, 0xF6, 0x05, 0x0A,
0x05, 0x0A, 0x05, 0x0A
};
static const u8 turks_smc_int_vectors[] =
{
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x12, 0xAA,
0x0C, 0x2F, 0x15, 0xF6,
0x15, 0xF6, 0x05, 0x0A,
0x05, 0x0A, 0x05, 0x0A
};
static const u8 caicos_smc_int_vectors[] =
{
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x0C, 0x14,
0x0C, 0x14, 0x12, 0xAA,
0x0C, 0x2F, 0x15, 0xF6,
0x15, 0xF6, 0x05, 0x0A,
0x05, 0x0A, 0x05, 0x0A
};
static const u8 cayman_smc_int_vectors[] =
{
0x12, 0x05, 0x12, 0x05,
0x12, 0x05, 0x12, 0x05,
0x12, 0x05, 0x12, 0x05,
0x12, 0x05, 0x12, 0x05,
0x12, 0x05, 0x12, 0x05,
0x12, 0x05, 0x12, 0x05,
0x12, 0x05, 0x12, 0x05,
0x12, 0x05, 0x12, 0x05,
0x12, 0x05, 0x12, 0x05,
0x12, 0x05, 0x12, 0x05,
0x12, 0x05, 0x12, 0x05,
0x12, 0x05, 0x12, 0x05,
0x12, 0x05, 0x18, 0xEA,
0x12, 0x20, 0x1C, 0x34,
0x1C, 0x34, 0x08, 0x72,
0x08, 0x72, 0x08, 0x72
};
static int rv770_set_smc_sram_address(struct radeon_device *rdev,
u16 smc_address, u16 limit)
{
u32 addr;
if (smc_address & 3)
return -EINVAL;
if ((smc_address + 3) > limit)
return -EINVAL;
addr = smc_address;
addr |= SMC_SRAM_AUTO_INC_DIS;
WREG32(SMC_SRAM_ADDR, addr);
return 0;
}
int rv770_copy_bytes_to_smc(struct radeon_device *rdev,
u16 smc_start_address, const u8 *src,
u16 byte_count, u16 limit)
{
unsigned long flags;
u32 data, original_data, extra_shift;
u16 addr;
int ret = 0;
if (smc_start_address & 3)
return -EINVAL;
if ((smc_start_address + byte_count) > limit)
return -EINVAL;
addr = smc_start_address;
spin_lock_irqsave(&rdev->smc_idx_lock, flags);
while (byte_count >= 4) {
/* SMC address space is BE */
data = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3];
ret = rv770_set_smc_sram_address(rdev, addr, limit);
if (ret)
goto done;
WREG32(SMC_SRAM_DATA, data);
src += 4;
byte_count -= 4;
addr += 4;
}
/* RMW for final bytes */
if (byte_count > 0) {
data = 0;
ret = rv770_set_smc_sram_address(rdev, addr, limit);
if (ret)
goto done;
original_data = RREG32(SMC_SRAM_DATA);
extra_shift = 8 * (4 - byte_count);
while (byte_count > 0) {
/* SMC address space is BE */
data = (data << 8) + *src++;
byte_count--;
}
data <<= extra_shift;
data |= (original_data & ~((~0UL) << extra_shift));
ret = rv770_set_smc_sram_address(rdev, addr, limit);
if (ret)
goto done;
WREG32(SMC_SRAM_DATA, data);
}
done:
spin_unlock_irqrestore(&rdev->smc_idx_lock, flags);
return ret;
}
static int rv770_program_interrupt_vectors(struct radeon_device *rdev,
u32 smc_first_vector, const u8 *src,
u32 byte_count)
{
u32 tmp, i;
if (byte_count % 4)
return -EINVAL;
if (smc_first_vector < FIRST_SMC_INT_VECT_REG) {
tmp = FIRST_SMC_INT_VECT_REG - smc_first_vector;
if (tmp > byte_count)
return 0;
byte_count -= tmp;
src += tmp;
smc_first_vector = FIRST_SMC_INT_VECT_REG;
}
for (i = 0; i < byte_count; i += 4) {
/* SMC address space is BE */
tmp = (src[i] << 24) | (src[i + 1] << 16) | (src[i + 2] << 8) | src[i + 3];
WREG32(SMC_ISR_FFD8_FFDB + i, tmp);
}
return 0;
}
void rv770_start_smc(struct radeon_device *rdev)
{
WREG32_P(SMC_IO, SMC_RST_N, ~SMC_RST_N);
}
void rv770_reset_smc(struct radeon_device *rdev)
{
WREG32_P(SMC_IO, 0, ~SMC_RST_N);
}
void rv770_stop_smc_clock(struct radeon_device *rdev)
{
WREG32_P(SMC_IO, 0, ~SMC_CLK_EN);
}
void rv770_start_smc_clock(struct radeon_device *rdev)
{
WREG32_P(SMC_IO, SMC_CLK_EN, ~SMC_CLK_EN);
}
bool rv770_is_smc_running(struct radeon_device *rdev)
{
u32 tmp;
tmp = RREG32(SMC_IO);
if ((tmp & SMC_RST_N) && (tmp & SMC_CLK_EN))
return true;
else
return false;
}
PPSMC_Result rv770_send_msg_to_smc(struct radeon_device *rdev, PPSMC_Msg msg)
{
u32 tmp;
int i;
PPSMC_Result result;
if (!rv770_is_smc_running(rdev))
return PPSMC_Result_Failed;
WREG32_P(SMC_MSG, HOST_SMC_MSG(msg), ~HOST_SMC_MSG_MASK);
for (i = 0; i < rdev->usec_timeout; i++) {
tmp = RREG32(SMC_MSG) & HOST_SMC_RESP_MASK;
tmp >>= HOST_SMC_RESP_SHIFT;
if (tmp != 0)
break;
udelay(1);
}
tmp = RREG32(SMC_MSG) & HOST_SMC_RESP_MASK;
tmp >>= HOST_SMC_RESP_SHIFT;
result = (PPSMC_Result)tmp;
return result;
}
PPSMC_Result rv770_wait_for_smc_inactive(struct radeon_device *rdev)
{
int i;
PPSMC_Result result = PPSMC_Result_OK;
if (!rv770_is_smc_running(rdev))
return result;
for (i = 0; i < rdev->usec_timeout; i++) {
if (RREG32(SMC_IO) & SMC_STOP_MODE)
break;
udelay(1);
}
return result;
}
static void rv770_clear_smc_sram(struct radeon_device *rdev, u16 limit)
{
unsigned long flags;
u16 i;
spin_lock_irqsave(&rdev->smc_idx_lock, flags);
for (i = 0; i < limit; i += 4) {
rv770_set_smc_sram_address(rdev, i, limit);
WREG32(SMC_SRAM_DATA, 0);
}
spin_unlock_irqrestore(&rdev->smc_idx_lock, flags);
}
int rv770_load_smc_ucode(struct radeon_device *rdev,
u16 limit)
{
int ret;
const u8 *int_vect;
u16 int_vect_start_address;
u16 int_vect_size;
const u8 *ucode_data;
u16 ucode_start_address;
u16 ucode_size;
if (!rdev->smc_fw)
return -EINVAL;
rv770_clear_smc_sram(rdev, limit);
switch (rdev->family) {
case CHIP_RV770:
ucode_start_address = RV770_SMC_UCODE_START;
ucode_size = RV770_SMC_UCODE_SIZE;
int_vect = (const u8 *)&rv770_smc_int_vectors;
int_vect_start_address = RV770_SMC_INT_VECTOR_START;
int_vect_size = RV770_SMC_INT_VECTOR_SIZE;
break;
case CHIP_RV730:
ucode_start_address = RV730_SMC_UCODE_START;
ucode_size = RV730_SMC_UCODE_SIZE;
int_vect = (const u8 *)&rv730_smc_int_vectors;
int_vect_start_address = RV730_SMC_INT_VECTOR_START;
int_vect_size = RV730_SMC_INT_VECTOR_SIZE;
break;
case CHIP_RV710:
ucode_start_address = RV710_SMC_UCODE_START;
ucode_size = RV710_SMC_UCODE_SIZE;
int_vect = (const u8 *)&rv710_smc_int_vectors;
int_vect_start_address = RV710_SMC_INT_VECTOR_START;
int_vect_size = RV710_SMC_INT_VECTOR_SIZE;
break;
case CHIP_RV740:
ucode_start_address = RV740_SMC_UCODE_START;
ucode_size = RV740_SMC_UCODE_SIZE;
int_vect = (const u8 *)&rv740_smc_int_vectors;
int_vect_start_address = RV740_SMC_INT_VECTOR_START;
int_vect_size = RV740_SMC_INT_VECTOR_SIZE;
break;
case CHIP_CEDAR:
ucode_start_address = CEDAR_SMC_UCODE_START;
ucode_size = CEDAR_SMC_UCODE_SIZE;
int_vect = (const u8 *)&cedar_smc_int_vectors;
int_vect_start_address = CEDAR_SMC_INT_VECTOR_START;
int_vect_size = CEDAR_SMC_INT_VECTOR_SIZE;
break;
case CHIP_REDWOOD:
ucode_start_address = REDWOOD_SMC_UCODE_START;
ucode_size = REDWOOD_SMC_UCODE_SIZE;
int_vect = (const u8 *)&redwood_smc_int_vectors;
int_vect_start_address = REDWOOD_SMC_INT_VECTOR_START;
int_vect_size = REDWOOD_SMC_INT_VECTOR_SIZE;
break;
case CHIP_JUNIPER:
ucode_start_address = JUNIPER_SMC_UCODE_START;
ucode_size = JUNIPER_SMC_UCODE_SIZE;
int_vect = (const u8 *)&juniper_smc_int_vectors;
int_vect_start_address = JUNIPER_SMC_INT_VECTOR_START;
int_vect_size = JUNIPER_SMC_INT_VECTOR_SIZE;
break;
case CHIP_CYPRESS:
case CHIP_HEMLOCK:
ucode_start_address = CYPRESS_SMC_UCODE_START;
ucode_size = CYPRESS_SMC_UCODE_SIZE;
int_vect = (const u8 *)&cypress_smc_int_vectors;
int_vect_start_address = CYPRESS_SMC_INT_VECTOR_START;
int_vect_size = CYPRESS_SMC_INT_VECTOR_SIZE;
break;
case CHIP_BARTS:
ucode_start_address = BARTS_SMC_UCODE_START;
ucode_size = BARTS_SMC_UCODE_SIZE;
int_vect = (const u8 *)&barts_smc_int_vectors;
int_vect_start_address = BARTS_SMC_INT_VECTOR_START;
int_vect_size = BARTS_SMC_INT_VECTOR_SIZE;
break;
case CHIP_TURKS:
ucode_start_address = TURKS_SMC_UCODE_START;
ucode_size = TURKS_SMC_UCODE_SIZE;
int_vect = (const u8 *)&turks_smc_int_vectors;
int_vect_start_address = TURKS_SMC_INT_VECTOR_START;
int_vect_size = TURKS_SMC_INT_VECTOR_SIZE;
break;
case CHIP_CAICOS:
ucode_start_address = CAICOS_SMC_UCODE_START;
ucode_size = CAICOS_SMC_UCODE_SIZE;
int_vect = (const u8 *)&caicos_smc_int_vectors;
int_vect_start_address = CAICOS_SMC_INT_VECTOR_START;
int_vect_size = CAICOS_SMC_INT_VECTOR_SIZE;
break;
case CHIP_CAYMAN:
ucode_start_address = CAYMAN_SMC_UCODE_START;
ucode_size = CAYMAN_SMC_UCODE_SIZE;
int_vect = (const u8 *)&cayman_smc_int_vectors;
int_vect_start_address = CAYMAN_SMC_INT_VECTOR_START;
int_vect_size = CAYMAN_SMC_INT_VECTOR_SIZE;
break;
default:
DRM_ERROR("unknown asic in smc ucode loader\n");
BUG();
}
/* load the ucode */
ucode_data = (const u8 *)rdev->smc_fw->data;
ret = rv770_copy_bytes_to_smc(rdev, ucode_start_address,
ucode_data, ucode_size, limit);
if (ret)
return ret;
/* set up the int vectors */
ret = rv770_program_interrupt_vectors(rdev, int_vect_start_address,
int_vect, int_vect_size);
if (ret)
return ret;
return 0;
}
int rv770_read_smc_sram_dword(struct radeon_device *rdev,
u16 smc_address, u32 *value, u16 limit)
{
unsigned long flags;
int ret;
spin_lock_irqsave(&rdev->smc_idx_lock, flags);
ret = rv770_set_smc_sram_address(rdev, smc_address, limit);
if (ret == 0)
*value = RREG32(SMC_SRAM_DATA);
spin_unlock_irqrestore(&rdev->smc_idx_lock, flags);
return ret;
}
int rv770_write_smc_sram_dword(struct radeon_device *rdev,
u16 smc_address, u32 value, u16 limit)
{
unsigned long flags;
int ret;
spin_lock_irqsave(&rdev->smc_idx_lock, flags);
ret = rv770_set_smc_sram_address(rdev, smc_address, limit);
if (ret == 0)
WREG32(SMC_SRAM_DATA, value);
spin_unlock_irqrestore(&rdev->smc_idx_lock, flags);
return ret;
}
| gpl-3.0 |
zenglongtest/zengl_SDL | android/jni/SDL_ttf/external/freetype-2.4.12/src/base/ftfstype.c | 749 | 2244 | /***************************************************************************/
/* */
/* ftfstype.c */
/* */
/* FreeType utility file to access FSType data (body). */
/* */
/* Copyright 2008, 2009 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#include <ft2build.h>
#include FT_TYPE1_TABLES_H
#include FT_TRUETYPE_TABLES_H
#include FT_INTERNAL_SERVICE_H
#include FT_SERVICE_POSTSCRIPT_INFO_H
/* documentation is in freetype.h */
FT_EXPORT_DEF( FT_UShort )
FT_Get_FSType_Flags( FT_Face face )
{
TT_OS2* os2;
/* first, try to get the fs_type directly from the font */
if ( face )
{
FT_Service_PsInfo service = NULL;
FT_FACE_FIND_SERVICE( face, service, POSTSCRIPT_INFO );
if ( service && service->ps_get_font_extra )
{
PS_FontExtraRec extra;
if ( !service->ps_get_font_extra( face, &extra ) &&
extra.fs_type != 0 )
return extra.fs_type;
}
}
/* look at FSType before fsType for Type42 */
if ( ( os2 = (TT_OS2*)FT_Get_Sfnt_Table( face, ft_sfnt_os2 ) ) != NULL &&
os2->version != 0xFFFFU )
return os2->fsType;
return 0;
}
/* END */
| gpl-3.0 |
maoze/linux-3-14-for-arm | linux-3.14/drivers/mfd/twl6030-irq.c | 241 | 14136 | /*
* twl6030-irq.c - TWL6030 irq support
*
* Copyright (C) 2005-2009 Texas Instruments, Inc.
*
* Modifications to defer interrupt handling to a kernel thread:
* Copyright (C) 2006 MontaVista Software, Inc.
*
* Based on tlv320aic23.c:
* Copyright (c) by Kai Svahn <kai.svahn@nokia.com>
*
* Code cleanup and modifications to IRQ handler.
* by syed khasim <x0khasim@ti.com>
*
* TWL6030 specific code and IRQ handling changes by
* Jagadeesh Bhaskar Pakaravoor <j-pakaravoor@ti.com>
* Balaji T K <balajitk@ti.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/init.h>
#include <linux/export.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/kthread.h>
#include <linux/i2c/twl.h>
#include <linux/platform_device.h>
#include <linux/suspend.h>
#include <linux/of.h>
#include <linux/irqdomain.h>
#include <linux/of_device.h>
#include "twl-core.h"
/*
* TWL6030 (unlike its predecessors, which had two level interrupt handling)
* three interrupt registers INT_STS_A, INT_STS_B and INT_STS_C.
* It exposes status bits saying who has raised an interrupt. There are
* three mask registers that corresponds to these status registers, that
* enables/disables these interrupts.
*
* We set up IRQs starting at a platform-specified base. An interrupt map table,
* specifies mapping between interrupt number and the associated module.
*/
#define TWL6030_NR_IRQS 20
static int twl6030_interrupt_mapping[24] = {
PWR_INTR_OFFSET, /* Bit 0 PWRON */
PWR_INTR_OFFSET, /* Bit 1 RPWRON */
PWR_INTR_OFFSET, /* Bit 2 BAT_VLOW */
RTC_INTR_OFFSET, /* Bit 3 RTC_ALARM */
RTC_INTR_OFFSET, /* Bit 4 RTC_PERIOD */
HOTDIE_INTR_OFFSET, /* Bit 5 HOT_DIE */
SMPSLDO_INTR_OFFSET, /* Bit 6 VXXX_SHORT */
SMPSLDO_INTR_OFFSET, /* Bit 7 VMMC_SHORT */
SMPSLDO_INTR_OFFSET, /* Bit 8 VUSIM_SHORT */
BATDETECT_INTR_OFFSET, /* Bit 9 BAT */
SIMDETECT_INTR_OFFSET, /* Bit 10 SIM */
MMCDETECT_INTR_OFFSET, /* Bit 11 MMC */
RSV_INTR_OFFSET, /* Bit 12 Reserved */
MADC_INTR_OFFSET, /* Bit 13 GPADC_RT_EOC */
MADC_INTR_OFFSET, /* Bit 14 GPADC_SW_EOC */
GASGAUGE_INTR_OFFSET, /* Bit 15 CC_AUTOCAL */
USBOTG_INTR_OFFSET, /* Bit 16 ID_WKUP */
USBOTG_INTR_OFFSET, /* Bit 17 VBUS_WKUP */
USBOTG_INTR_OFFSET, /* Bit 18 ID */
USB_PRES_INTR_OFFSET, /* Bit 19 VBUS */
CHARGER_INTR_OFFSET, /* Bit 20 CHRG_CTRL */
CHARGERFAULT_INTR_OFFSET, /* Bit 21 EXT_CHRG */
CHARGERFAULT_INTR_OFFSET, /* Bit 22 INT_CHRG */
RSV_INTR_OFFSET, /* Bit 23 Reserved */
};
static int twl6032_interrupt_mapping[24] = {
PWR_INTR_OFFSET, /* Bit 0 PWRON */
PWR_INTR_OFFSET, /* Bit 1 RPWRON */
PWR_INTR_OFFSET, /* Bit 2 SYS_VLOW */
RTC_INTR_OFFSET, /* Bit 3 RTC_ALARM */
RTC_INTR_OFFSET, /* Bit 4 RTC_PERIOD */
HOTDIE_INTR_OFFSET, /* Bit 5 HOT_DIE */
SMPSLDO_INTR_OFFSET, /* Bit 6 VXXX_SHORT */
PWR_INTR_OFFSET, /* Bit 7 SPDURATION */
PWR_INTR_OFFSET, /* Bit 8 WATCHDOG */
BATDETECT_INTR_OFFSET, /* Bit 9 BAT */
SIMDETECT_INTR_OFFSET, /* Bit 10 SIM */
MMCDETECT_INTR_OFFSET, /* Bit 11 MMC */
MADC_INTR_OFFSET, /* Bit 12 GPADC_RT_EOC */
MADC_INTR_OFFSET, /* Bit 13 GPADC_SW_EOC */
GASGAUGE_INTR_OFFSET, /* Bit 14 CC_EOC */
GASGAUGE_INTR_OFFSET, /* Bit 15 CC_AUTOCAL */
USBOTG_INTR_OFFSET, /* Bit 16 ID_WKUP */
USBOTG_INTR_OFFSET, /* Bit 17 VBUS_WKUP */
USBOTG_INTR_OFFSET, /* Bit 18 ID */
USB_PRES_INTR_OFFSET, /* Bit 19 VBUS */
CHARGER_INTR_OFFSET, /* Bit 20 CHRG_CTRL */
CHARGERFAULT_INTR_OFFSET, /* Bit 21 EXT_CHRG */
CHARGERFAULT_INTR_OFFSET, /* Bit 22 INT_CHRG */
RSV_INTR_OFFSET, /* Bit 23 Reserved */
};
/*----------------------------------------------------------------------*/
struct twl6030_irq {
unsigned int irq_base;
int twl_irq;
bool irq_wake_enabled;
atomic_t wakeirqs;
struct notifier_block pm_nb;
struct irq_chip irq_chip;
struct irq_domain *irq_domain;
const int *irq_mapping_tbl;
};
static struct twl6030_irq *twl6030_irq;
static int twl6030_irq_pm_notifier(struct notifier_block *notifier,
unsigned long pm_event, void *unused)
{
int chained_wakeups;
struct twl6030_irq *pdata = container_of(notifier, struct twl6030_irq,
pm_nb);
switch (pm_event) {
case PM_SUSPEND_PREPARE:
chained_wakeups = atomic_read(&pdata->wakeirqs);
if (chained_wakeups && !pdata->irq_wake_enabled) {
if (enable_irq_wake(pdata->twl_irq))
pr_err("twl6030 IRQ wake enable failed\n");
else
pdata->irq_wake_enabled = true;
} else if (!chained_wakeups && pdata->irq_wake_enabled) {
disable_irq_wake(pdata->twl_irq);
pdata->irq_wake_enabled = false;
}
disable_irq(pdata->twl_irq);
break;
case PM_POST_SUSPEND:
enable_irq(pdata->twl_irq);
break;
default:
break;
}
return NOTIFY_DONE;
}
/*
* Threaded irq handler for the twl6030 interrupt.
* We query the interrupt controller in the twl6030 to determine
* which module is generating the interrupt request and call
* handle_nested_irq for that module.
*/
static irqreturn_t twl6030_irq_thread(int irq, void *data)
{
int i, ret;
union {
u8 bytes[4];
__le32 int_sts;
} sts;
u32 int_sts; /* sts.int_sts converted to CPU endianness */
struct twl6030_irq *pdata = data;
/* read INT_STS_A, B and C in one shot using a burst read */
ret = twl_i2c_read(TWL_MODULE_PIH, sts.bytes, REG_INT_STS_A, 3);
if (ret) {
pr_warn("twl6030_irq: I2C error %d reading PIH ISR\n", ret);
return IRQ_HANDLED;
}
sts.bytes[3] = 0; /* Only 24 bits are valid*/
/*
* Since VBUS status bit is not reliable for VBUS disconnect
* use CHARGER VBUS detection status bit instead.
*/
if (sts.bytes[2] & 0x10)
sts.bytes[2] |= 0x08;
int_sts = le32_to_cpu(sts.int_sts);
for (i = 0; int_sts; int_sts >>= 1, i++)
if (int_sts & 0x1) {
int module_irq =
irq_find_mapping(pdata->irq_domain,
pdata->irq_mapping_tbl[i]);
if (module_irq)
handle_nested_irq(module_irq);
else
pr_err("twl6030_irq: Unmapped PIH ISR %u detected\n",
i);
pr_debug("twl6030_irq: PIH ISR %u, virq%u\n",
i, module_irq);
}
/*
* NOTE:
* Simulation confirms that documentation is wrong w.r.t the
* interrupt status clear operation. A single *byte* write to
* any one of STS_A to STS_C register results in all three
* STS registers being reset. Since it does not matter which
* value is written, all three registers are cleared on a
* single byte write, so we just use 0x0 to clear.
*/
ret = twl_i2c_write_u8(TWL_MODULE_PIH, 0x00, REG_INT_STS_A);
if (ret)
pr_warn("twl6030_irq: I2C error in clearing PIH ISR\n");
return IRQ_HANDLED;
}
/*----------------------------------------------------------------------*/
static int twl6030_irq_set_wake(struct irq_data *d, unsigned int on)
{
struct twl6030_irq *pdata = irq_get_chip_data(d->irq);
if (on)
atomic_inc(&pdata->wakeirqs);
else
atomic_dec(&pdata->wakeirqs);
return 0;
}
int twl6030_interrupt_unmask(u8 bit_mask, u8 offset)
{
int ret;
u8 unmask_value;
ret = twl_i2c_read_u8(TWL_MODULE_PIH, &unmask_value,
REG_INT_STS_A + offset);
unmask_value &= (~(bit_mask));
ret |= twl_i2c_write_u8(TWL_MODULE_PIH, unmask_value,
REG_INT_STS_A + offset); /* unmask INT_MSK_A/B/C */
return ret;
}
EXPORT_SYMBOL(twl6030_interrupt_unmask);
int twl6030_interrupt_mask(u8 bit_mask, u8 offset)
{
int ret;
u8 mask_value;
ret = twl_i2c_read_u8(TWL_MODULE_PIH, &mask_value,
REG_INT_STS_A + offset);
mask_value |= (bit_mask);
ret |= twl_i2c_write_u8(TWL_MODULE_PIH, mask_value,
REG_INT_STS_A + offset); /* mask INT_MSK_A/B/C */
return ret;
}
EXPORT_SYMBOL(twl6030_interrupt_mask);
int twl6030_mmc_card_detect_config(void)
{
int ret;
u8 reg_val = 0;
/* Unmasking the Card detect Interrupt line for MMC1 from Phoenix */
twl6030_interrupt_unmask(TWL6030_MMCDETECT_INT_MASK,
REG_INT_MSK_LINE_B);
twl6030_interrupt_unmask(TWL6030_MMCDETECT_INT_MASK,
REG_INT_MSK_STS_B);
/*
* Initially Configuring MMC_CTRL for receiving interrupts &
* Card status on TWL6030 for MMC1
*/
ret = twl_i2c_read_u8(TWL6030_MODULE_ID0, ®_val, TWL6030_MMCCTRL);
if (ret < 0) {
pr_err("twl6030: Failed to read MMCCTRL, error %d\n", ret);
return ret;
}
reg_val &= ~VMMC_AUTO_OFF;
reg_val |= SW_FC;
ret = twl_i2c_write_u8(TWL6030_MODULE_ID0, reg_val, TWL6030_MMCCTRL);
if (ret < 0) {
pr_err("twl6030: Failed to write MMCCTRL, error %d\n", ret);
return ret;
}
/* Configuring PullUp-PullDown register */
ret = twl_i2c_read_u8(TWL6030_MODULE_ID0, ®_val,
TWL6030_CFG_INPUT_PUPD3);
if (ret < 0) {
pr_err("twl6030: Failed to read CFG_INPUT_PUPD3, error %d\n",
ret);
return ret;
}
reg_val &= ~(MMC_PU | MMC_PD);
ret = twl_i2c_write_u8(TWL6030_MODULE_ID0, reg_val,
TWL6030_CFG_INPUT_PUPD3);
if (ret < 0) {
pr_err("twl6030: Failed to write CFG_INPUT_PUPD3, error %d\n",
ret);
return ret;
}
return irq_find_mapping(twl6030_irq->irq_domain,
MMCDETECT_INTR_OFFSET);
}
EXPORT_SYMBOL(twl6030_mmc_card_detect_config);
int twl6030_mmc_card_detect(struct device *dev, int slot)
{
int ret = -EIO;
u8 read_reg = 0;
struct platform_device *pdev = to_platform_device(dev);
if (pdev->id) {
/* TWL6030 provide's Card detect support for
* only MMC1 controller.
*/
pr_err("Unknown MMC controller %d in %s\n", pdev->id, __func__);
return ret;
}
/*
* BIT0 of MMC_CTRL on TWL6030 provides card status for MMC1
* 0 - Card not present ,1 - Card present
*/
ret = twl_i2c_read_u8(TWL6030_MODULE_ID0, &read_reg,
TWL6030_MMCCTRL);
if (ret >= 0)
ret = read_reg & STS_MMC;
return ret;
}
EXPORT_SYMBOL(twl6030_mmc_card_detect);
static int twl6030_irq_map(struct irq_domain *d, unsigned int virq,
irq_hw_number_t hwirq)
{
struct twl6030_irq *pdata = d->host_data;
irq_set_chip_data(virq, pdata);
irq_set_chip_and_handler(virq, &pdata->irq_chip, handle_simple_irq);
irq_set_nested_thread(virq, true);
irq_set_parent(virq, pdata->twl_irq);
#ifdef CONFIG_ARM
/*
* ARM requires an extra step to clear IRQ_NOREQUEST, which it
* sets on behalf of every irq_chip. Also sets IRQ_NOPROBE.
*/
set_irq_flags(virq, IRQF_VALID);
#else
/* same effect on other architectures */
irq_set_noprobe(virq);
#endif
return 0;
}
static void twl6030_irq_unmap(struct irq_domain *d, unsigned int virq)
{
#ifdef CONFIG_ARM
set_irq_flags(virq, 0);
#endif
irq_set_chip_and_handler(virq, NULL, NULL);
irq_set_chip_data(virq, NULL);
}
static struct irq_domain_ops twl6030_irq_domain_ops = {
.map = twl6030_irq_map,
.unmap = twl6030_irq_unmap,
.xlate = irq_domain_xlate_onetwocell,
};
static const struct of_device_id twl6030_of_match[] = {
{.compatible = "ti,twl6030", &twl6030_interrupt_mapping},
{.compatible = "ti,twl6032", &twl6032_interrupt_mapping},
{ },
};
int twl6030_init_irq(struct device *dev, int irq_num)
{
struct device_node *node = dev->of_node;
int nr_irqs;
int status;
u8 mask[3];
const struct of_device_id *of_id;
of_id = of_match_device(twl6030_of_match, dev);
if (!of_id || !of_id->data) {
dev_err(dev, "Unknown TWL device model\n");
return -EINVAL;
}
nr_irqs = TWL6030_NR_IRQS;
twl6030_irq = devm_kzalloc(dev, sizeof(*twl6030_irq), GFP_KERNEL);
if (!twl6030_irq) {
dev_err(dev, "twl6030_irq: Memory allocation failed\n");
return -ENOMEM;
}
mask[0] = 0xFF;
mask[1] = 0xFF;
mask[2] = 0xFF;
/* mask all int lines */
status = twl_i2c_write(TWL_MODULE_PIH, &mask[0], REG_INT_MSK_LINE_A, 3);
/* mask all int sts */
status |= twl_i2c_write(TWL_MODULE_PIH, &mask[0], REG_INT_MSK_STS_A, 3);
/* clear INT_STS_A,B,C */
status |= twl_i2c_write(TWL_MODULE_PIH, &mask[0], REG_INT_STS_A, 3);
if (status < 0) {
dev_err(dev, "I2C err writing TWL_MODULE_PIH: %d\n", status);
return status;
}
/*
* install an irq handler for each of the modules;
* clone dummy irq_chip since PIH can't *do* anything
*/
twl6030_irq->irq_chip = dummy_irq_chip;
twl6030_irq->irq_chip.name = "twl6030";
twl6030_irq->irq_chip.irq_set_type = NULL;
twl6030_irq->irq_chip.irq_set_wake = twl6030_irq_set_wake;
twl6030_irq->pm_nb.notifier_call = twl6030_irq_pm_notifier;
atomic_set(&twl6030_irq->wakeirqs, 0);
twl6030_irq->irq_mapping_tbl = of_id->data;
twl6030_irq->irq_domain =
irq_domain_add_linear(node, nr_irqs,
&twl6030_irq_domain_ops, twl6030_irq);
if (!twl6030_irq->irq_domain) {
dev_err(dev, "Can't add irq_domain\n");
return -ENOMEM;
}
dev_info(dev, "PIH (irq %d) nested IRQs\n", irq_num);
/* install an irq handler to demultiplex the TWL6030 interrupt */
status = request_threaded_irq(irq_num, NULL, twl6030_irq_thread,
IRQF_ONESHOT, "TWL6030-PIH", twl6030_irq);
if (status < 0) {
dev_err(dev, "could not claim irq %d: %d\n", irq_num, status);
goto fail_irq;
}
twl6030_irq->twl_irq = irq_num;
register_pm_notifier(&twl6030_irq->pm_nb);
return 0;
fail_irq:
irq_domain_remove(twl6030_irq->irq_domain);
return status;
}
int twl6030_exit_irq(void)
{
if (twl6030_irq && twl6030_irq->twl_irq) {
unregister_pm_notifier(&twl6030_irq->pm_nb);
free_irq(twl6030_irq->twl_irq, NULL);
/*
* TODO: IRQ domain and allocated nested IRQ descriptors
* should be freed somehow here. Now It can't be done, because
* child devices will not be deleted during removing of
* TWL Core driver and they will still contain allocated
* virt IRQs in their Resources tables.
* The same prevents us from using devm_request_threaded_irq()
* in this module.
*/
}
return 0;
}
| gpl-3.0 |
virtmedia/ultramicron | STM32L1xx_StdPeriph_Lib_V1.2.0/Project/STM32L1xx_StdPeriph_Examples/SPI/SPI_TwoBoards/DataExchangeInterrupt/system_stm32l1xx.c | 255 | 19642 | /**
******************************************************************************
* @file system_stm32l1xx.c
* @author MCD Application Team
* @version V1.1.1
* @date 13-April-2012
* @brief CMSIS Cortex-M3 Device Peripheral Access Layer System Source File.
* This file contains the system clock configuration for STM32L1xx Ultra
* Low Power devices, and is generated by the clock configuration
* tool "STM32L1xx_Clock_Configuration_V1.1.0.xls".
*
* 1. This file provides two functions and one global variable to be called from
* user application:
* - SystemInit(): Setups the system clock (System clock source, PLL Multiplier
* and Divider factors, AHB/APBx prescalers and Flash settings),
* depending on the configuration made in the clock xls tool.
* This function is called at startup just after reset and
* before branch to main program. This call is made inside
* the "startup_stm32l1xx_xx.s" file.
*
* - SystemCoreClock variable: Contains the core clock (HCLK), it can be used
* by the user application to setup the SysTick
* timer or configure other parameters.
*
* - SystemCoreClockUpdate(): Updates the variable SystemCoreClock and must
* be called whenever the core clock is changed
* during program execution.
*
* 2. After each device reset the MSI (2.1 MHz Range) is used as system clock source.
* Then SystemInit() function is called, in "startup_stm32l1xx_xx.s" file, to
* configure the system clock before to branch to main program.
*
* 3. If the system clock source selected by user fails to startup, the SystemInit()
* function will do nothing and MSI still used as system clock source. User can
* add some code to deal with this issue inside the SetSysClock() function.
*
* 4. The default value of HSE crystal is set to 8MHz, refer to "HSE_VALUE" define
* in "stm32l1xx.h" file. When HSE is used as system clock source, directly or
* through PLL, and you are using different crystal you have to adapt the HSE
* value to your own configuration.
*
* 5. This file configures the system clock as follows:
*=============================================================================
* System Clock Configuration
*=============================================================================
* System Clock source | PLL(HSE)
*-----------------------------------------------------------------------------
* SYSCLK | 32000000 Hz
*-----------------------------------------------------------------------------
* HCLK | 32000000 Hz
*-----------------------------------------------------------------------------
* AHB Prescaler | 1
*-----------------------------------------------------------------------------
* APB1 Prescaler | 1
*-----------------------------------------------------------------------------
* APB2 Prescaler | 1
*-----------------------------------------------------------------------------
* HSE Frequency | 8000000 Hz
*-----------------------------------------------------------------------------
* PLL DIV | 3
*-----------------------------------------------------------------------------
* PLL MUL | 12
*-----------------------------------------------------------------------------
* VDD | 3.3 V
*-----------------------------------------------------------------------------
* Vcore | 1.8 V (Range 1)
*-----------------------------------------------------------------------------
* Flash Latency | 1 WS
*-----------------------------------------------------------------------------
* SDIO clock (SDIOCLK) | 48000000 Hz
*-----------------------------------------------------------------------------
* Require 48MHz for USB clock | Disabled
*-----------------------------------------------------------------------------
*=============================================================================
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT 2012 STMicroelectronics</center></h2>
*
* Licensed under MCD-ST Liberty SW License Agreement V2, (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.st.com/software_license_agreement_liberty_v2
*
* 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.
*
******************************************************************************
*/
/** @addtogroup CMSIS
* @{
*/
/** @addtogroup stm32l1xx_system
* @{
*/
/** @addtogroup STM32L1xx_System_Private_Includes
* @{
*/
#include "stm32l1xx.h"
/**
* @}
*/
/** @addtogroup STM32L1xx_System_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @addtogroup STM32L1xx_System_Private_Defines
* @{
*/
/*!< Uncomment the following line if you need to use external SRAM mounted
on STM32L152D_EVAL board as data memory */
/* #define DATA_IN_ExtSRAM */
/*!< Uncomment the following line if you need to relocate your vector Table in
Internal SRAM. */
/* #define VECT_TAB_SRAM */
#define VECT_TAB_OFFSET 0x0 /*!< Vector Table base offset field.
This value must be a multiple of 0x200. */
/**
* @}
*/
/** @addtogroup STM32L1xx_System_Private_Macros
* @{
*/
/**
* @}
*/
/** @addtogroup STM32L1xx_System_Private_Variables
* @{
*/
uint32_t SystemCoreClock = 32000000;
__I uint8_t PLLMulTable[9] = {3, 4, 6, 8, 12, 16, 24, 32, 48};
__I uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9};
/**
* @}
*/
/** @addtogroup STM32L1xx_System_Private_FunctionPrototypes
* @{
*/
static void SetSysClock(void);
#ifdef DATA_IN_ExtSRAM
static void SystemInit_ExtMemCtl(void);
#endif /* DATA_IN_ExtSRAM */
/**
* @}
*/
/** @addtogroup STM32L1xx_System_Private_Functions
* @{
*/
/**
* @brief Setup the microcontroller system.
* Initialize the Embedded Flash Interface, the PLL and update the
* SystemCoreClock variable.
* @param None
* @retval None
*/
void SystemInit (void)
{
/*!< Set MSION bit */
RCC->CR |= (uint32_t)0x00000100;
/*!< Reset SW[1:0], HPRE[3:0], PPRE1[2:0], PPRE2[2:0], MCOSEL[2:0] and MCOPRE[2:0] bits */
RCC->CFGR &= (uint32_t)0x88FFC00C;
/*!< Reset HSION, HSEON, CSSON and PLLON bits */
RCC->CR &= (uint32_t)0xEEFEFFFE;
/*!< Reset HSEBYP bit */
RCC->CR &= (uint32_t)0xFFFBFFFF;
/*!< Reset PLLSRC, PLLMUL[3:0] and PLLDIV[1:0] bits */
RCC->CFGR &= (uint32_t)0xFF02FFFF;
/*!< Disable all interrupts */
RCC->CIR = 0x00000000;
#ifdef DATA_IN_ExtSRAM
SystemInit_ExtMemCtl();
#endif /* DATA_IN_ExtSRAM */
/* Configure the System clock frequency, AHB/APBx prescalers and Flash settings */
SetSysClock();
#ifdef VECT_TAB_SRAM
SCB->VTOR = SRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM. */
#else
SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH. */
#endif
}
/**
* @brief Update SystemCoreClock according to Clock Register Values
* The SystemCoreClock variable contains the core clock (HCLK), it can
* be used by the user application to setup the SysTick timer or configure
* other parameters.
*
* @note Each time the core clock (HCLK) changes, this function must be called
* to update SystemCoreClock variable value. Otherwise, any configuration
* based on this variable will be incorrect.
*
* @note - The system frequency computed by this function is not the real
* frequency in the chip. It is calculated based on the predefined
* constant and the selected clock source:
*
* - If SYSCLK source is MSI, SystemCoreClock will contain the MSI
* value as defined by the MSI range.
*
* - If SYSCLK source is HSI, SystemCoreClock will contain the HSI_VALUE(*)
*
* - If SYSCLK source is HSE, SystemCoreClock will contain the HSE_VALUE(**)
*
* - If SYSCLK source is PLL, SystemCoreClock will contain the HSE_VALUE(**)
* or HSI_VALUE(*) multiplied/divided by the PLL factors.
*
* (*) HSI_VALUE is a constant defined in stm32l1xx.h file (default value
* 16 MHz) but the real value may vary depending on the variations
* in voltage and temperature.
*
* (**) HSE_VALUE is a constant defined in stm32l1xx.h file (default value
* 8 MHz), user has to ensure that HSE_VALUE is same as the real
* frequency of the crystal used. Otherwise, this function may
* have wrong result.
*
* - The result of this function could be not correct when using fractional
* value for HSE crystal.
* @param None
* @retval None
*/
void SystemCoreClockUpdate (void)
{
uint32_t tmp = 0, pllmul = 0, plldiv = 0, pllsource = 0, msirange = 0;
/* Get SYSCLK source -------------------------------------------------------*/
tmp = RCC->CFGR & RCC_CFGR_SWS;
switch (tmp)
{
case 0x00: /* MSI used as system clock */
msirange = (RCC->ICSCR & RCC_ICSCR_MSIRANGE) >> 13;
SystemCoreClock = (32768 * (1 << (msirange + 1)));
break;
case 0x04: /* HSI used as system clock */
SystemCoreClock = HSI_VALUE;
break;
case 0x08: /* HSE used as system clock */
SystemCoreClock = HSE_VALUE;
break;
case 0x0C: /* PLL used as system clock */
/* Get PLL clock source and multiplication factor ----------------------*/
pllmul = RCC->CFGR & RCC_CFGR_PLLMUL;
plldiv = RCC->CFGR & RCC_CFGR_PLLDIV;
pllmul = PLLMulTable[(pllmul >> 18)];
plldiv = (plldiv >> 22) + 1;
pllsource = RCC->CFGR & RCC_CFGR_PLLSRC;
if (pllsource == 0x00)
{
/* HSI oscillator clock selected as PLL clock entry */
SystemCoreClock = (((HSI_VALUE) * pllmul) / plldiv);
}
else
{
/* HSE selected as PLL clock entry */
SystemCoreClock = (((HSE_VALUE) * pllmul) / plldiv);
}
break;
default: /* MSI used as system clock */
msirange = (RCC->ICSCR & RCC_ICSCR_MSIRANGE) >> 13;
SystemCoreClock = (32768 * (1 << (msirange + 1)));
break;
}
/* Compute HCLK clock frequency --------------------------------------------*/
/* Get HCLK prescaler */
tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4)];
/* HCLK clock frequency */
SystemCoreClock >>= tmp;
}
/**
* @brief Configures the System clock frequency, AHB/APBx prescalers and Flash
* settings.
* @note This function should be called only once the RCC clock configuration
* is reset to the default reset state (done in SystemInit() function).
* @param None
* @retval None
*/
static void SetSysClock(void)
{
__IO uint32_t StartUpCounter = 0, HSEStatus = 0;
/* SYSCLK, HCLK, PCLK2 and PCLK1 configuration ---------------------------*/
/* Enable HSE */
RCC->CR |= ((uint32_t)RCC_CR_HSEON);
/* Wait till HSE is ready and if Time out is reached exit */
do
{
HSEStatus = RCC->CR & RCC_CR_HSERDY;
StartUpCounter++;
} while((HSEStatus == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT));
if ((RCC->CR & RCC_CR_HSERDY) != RESET)
{
HSEStatus = (uint32_t)0x01;
}
else
{
HSEStatus = (uint32_t)0x00;
}
if (HSEStatus == (uint32_t)0x01)
{
/* Enable 64-bit access */
FLASH->ACR |= FLASH_ACR_ACC64;
/* Enable Prefetch Buffer */
FLASH->ACR |= FLASH_ACR_PRFTEN;
/* Flash 1 wait state */
FLASH->ACR |= FLASH_ACR_LATENCY;
/* Power enable */
RCC->APB1ENR |= RCC_APB1ENR_PWREN;
/* Select the Voltage Range 1 (1.8 V) */
PWR->CR = PWR_CR_VOS_0;
/* Wait Until the Voltage Regulator is ready */
while((PWR->CSR & PWR_CSR_VOSF) != RESET)
{
}
/* HCLK = SYSCLK /1*/
RCC->CFGR |= (uint32_t)RCC_CFGR_HPRE_DIV1;
/* PCLK2 = HCLK /1*/
RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE2_DIV1;
/* PCLK1 = HCLK /1*/
RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE1_DIV1;
/* PLL configuration */
RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_PLLSRC | RCC_CFGR_PLLMUL |
RCC_CFGR_PLLDIV));
RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLSRC_HSE | RCC_CFGR_PLLMUL12 | RCC_CFGR_PLLDIV3);
/* Enable PLL */
RCC->CR |= RCC_CR_PLLON;
/* Wait till PLL is ready */
while((RCC->CR & RCC_CR_PLLRDY) == 0)
{
}
/* Select PLL as system clock source */
RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_SW));
RCC->CFGR |= (uint32_t)RCC_CFGR_SW_PLL;
/* Wait till PLL is used as system clock source */
while ((RCC->CFGR & (uint32_t)RCC_CFGR_SWS) != (uint32_t)RCC_CFGR_SWS_PLL)
{
}
}
else
{
/* If HSE fails to start-up, the application will have wrong clock
configuration. User can add here some code to deal with this error */
}
}
#ifdef DATA_IN_ExtSRAM
/**
* @brief Setup the external memory controller.
* Called in SystemInit() function before jump to main.
* This function configures the external SRAM mounted on STM32L152D_EVAL board
* This SRAM will be used as program data memory (including heap and stack).
* @param None
* @retval None
*/
void SystemInit_ExtMemCtl(void)
{
/*-- GPIOs Configuration -----------------------------------------------------*/
/*
+-------------------+--------------------+------------------+------------------+
+ SRAM pins assignment +
+-------------------+--------------------+------------------+------------------+
| PD0 <-> FSMC_D2 | PE0 <-> FSMC_NBL0 | PF0 <-> FSMC_A0 | PG0 <-> FSMC_A10 |
| PD1 <-> FSMC_D3 | PE1 <-> FSMC_NBL1 | PF1 <-> FSMC_A1 | PG1 <-> FSMC_A11 |
| PD4 <-> FSMC_NOE | PE7 <-> FSMC_D4 | PF2 <-> FSMC_A2 | PG2 <-> FSMC_A12 |
| PD5 <-> FSMC_NWE | PE8 <-> FSMC_D5 | PF3 <-> FSMC_A3 | PG3 <-> FSMC_A13 |
| PD8 <-> FSMC_D13 | PE9 <-> FSMC_D6 | PF4 <-> FSMC_A4 | PG4 <-> FSMC_A14 |
| PD9 <-> FSMC_D14 | PE10 <-> FSMC_D7 | PF5 <-> FSMC_A5 | PG5 <-> FSMC_A15 |
| PD10 <-> FSMC_D15 | PE11 <-> FSMC_D8 | PF12 <-> FSMC_A6 | PG10<-> FSMC_NE2 |
| PD11 <-> FSMC_A16 | PE12 <-> FSMC_D9 | PF13 <-> FSMC_A7 |------------------+
| PD12 <-> FSMC_A17 | PE13 <-> FSMC_D10 | PF14 <-> FSMC_A8 |
| PD13 <-> FSMC_A18 | PE14 <-> FSMC_D11 | PF15 <-> FSMC_A9 |
| PD14 <-> FSMC_D0 | PE15 <-> FSMC_D12 |------------------+
| PD15 <-> FSMC_D1 |--------------------+
+-------------------+
*/
/* Enable GPIOD, GPIOE, GPIOF and GPIOG interface clock */
RCC->AHBENR = 0x000080D8;
/* Connect PDx pins to FSMC Alternate function */
GPIOD->AFR[0] = 0x00CC00CC;
GPIOD->AFR[1] = 0xCCCCCCCC;
/* Configure PDx pins in Alternate function mode */
GPIOD->MODER = 0xAAAA0A0A;
/* Configure PDx pins speed to 40 MHz */
GPIOD->OSPEEDR = 0xFFFF0F0F;
/* Configure PDx pins Output type to push-pull */
GPIOD->OTYPER = 0x00000000;
/* No pull-up, pull-down for PDx pins */
GPIOD->PUPDR = 0x00000000;
/* Connect PEx pins to FSMC Alternate function */
GPIOE->AFR[0] = 0xC00000CC;
GPIOE->AFR[1] = 0xCCCCCCCC;
/* Configure PEx pins in Alternate function mode */
GPIOE->MODER = 0xAAAA800A;
/* Configure PEx pins speed to 40 MHz */
GPIOE->OSPEEDR = 0xFFFFC00F;
/* Configure PEx pins Output type to push-pull */
GPIOE->OTYPER = 0x00000000;
/* No pull-up, pull-down for PEx pins */
GPIOE->PUPDR = 0x00000000;
/* Connect PFx pins to FSMC Alternate function */
GPIOF->AFR[0] = 0x00CCCCCC;
GPIOF->AFR[1] = 0xCCCC0000;
/* Configure PFx pins in Alternate function mode */
GPIOF->MODER = 0xAA000AAA;
/* Configure PFx pins speed to 40 MHz */
GPIOF->OSPEEDR = 0xFF000FFF;
/* Configure PFx pins Output type to push-pull */
GPIOF->OTYPER = 0x00000000;
/* No pull-up, pull-down for PFx pins */
GPIOF->PUPDR = 0x00000000;
/* Connect PGx pins to FSMC Alternate function */
GPIOG->AFR[0] = 0x00CCCCCC;
GPIOG->AFR[1] = 0x00000C00;
/* Configure PGx pins in Alternate function mode */
GPIOG->MODER = 0x00200AAA;
/* Configure PGx pins speed to 40 MHz */
GPIOG->OSPEEDR = 0x00300FFF;
/* Configure PGx pins Output type to push-pull */
GPIOG->OTYPER = 0x00000000;
/* No pull-up, pull-down for PGx pins */
GPIOG->PUPDR = 0x00000000;
/*-- FSMC Configuration ------------------------------------------------------*/
/* Enable the FSMC interface clock */
RCC->AHBENR = 0x400080D8;
/* Configure and enable Bank1_SRAM3 */
FSMC_Bank1->BTCR[4] = 0x00001011;
FSMC_Bank1->BTCR[5] = 0x00000300;
FSMC_Bank1E->BWTR[4] = 0x0FFFFFFF;
/*
Bank1_SRAM3 is configured as follow:
p.FSMC_AddressSetupTime = 0;
p.FSMC_AddressHoldTime = 0;
p.FSMC_DataSetupTime = 3;
p.FSMC_BusTurnAroundDuration = 0;
p.FSMC_CLKDivision = 0;
p.FSMC_DataLatency = 0;
p.FSMC_AccessMode = FSMC_AccessMode_A;
FSMC_NORSRAMInitStructure.FSMC_Bank = FSMC_Bank1_NORSRAM3;
FSMC_NORSRAMInitStructure.FSMC_DataAddressMux = FSMC_DataAddressMux_Disable;
FSMC_NORSRAMInitStructure.FSMC_MemoryType = FSMC_MemoryType_SRAM;
FSMC_NORSRAMInitStructure.FSMC_MemoryDataWidth = FSMC_MemoryDataWidth_16b;
FSMC_NORSRAMInitStructure.FSMC_BurstAccessMode = FSMC_BurstAccessMode_Disable;
FSMC_NORSRAMInitStructure.FSMC_AsynchronousWait = FSMC_AsynchronousWait_Disable;
FSMC_NORSRAMInitStructure.FSMC_WaitSignalPolarity = FSMC_WaitSignalPolarity_Low;
FSMC_NORSRAMInitStructure.FSMC_WrapMode = FSMC_WrapMode_Disable;
FSMC_NORSRAMInitStructure.FSMC_WaitSignalActive = FSMC_WaitSignalActive_BeforeWaitState;
FSMC_NORSRAMInitStructure.FSMC_WriteOperation = FSMC_WriteOperation_Enable;
FSMC_NORSRAMInitStructure.FSMC_WaitSignal = FSMC_WaitSignal_Disable;
FSMC_NORSRAMInitStructure.FSMC_ExtendedMode = FSMC_ExtendedMode_Disable;
FSMC_NORSRAMInitStructure.FSMC_WriteBurst = FSMC_WriteBurst_Disable;
FSMC_NORSRAMInitStructure.FSMC_ReadWriteTimingStruct = &p;
FSMC_NORSRAMInitStructure.FSMC_WriteTimingStruct = &p;
FSMC_NORSRAMInit(&FSMC_NORSRAMInitStructure);
FSMC_NORSRAMCmd(FSMC_Bank1_NORSRAM3, ENABLE);
*/
}
#endif /* DATA_IN_ExtSRAM */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| gpl-3.0 |
Anty-Lemon/mgba | src/core/sync.c | 5 | 2609 | /* Copyright (c) 2013-2015 Jeffrey Pfau
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <mgba/core/sync.h>
static void _changeVideoSync(struct mCoreSync* sync, bool frameOn) {
// Make sure the video thread can process events while the GBA thread is paused
MutexLock(&sync->videoFrameMutex);
if (frameOn != sync->videoFrameOn) {
sync->videoFrameOn = frameOn;
ConditionWake(&sync->videoFrameAvailableCond);
}
MutexUnlock(&sync->videoFrameMutex);
}
void mCoreSyncPostFrame(struct mCoreSync* sync) {
if (!sync) {
return;
}
MutexLock(&sync->videoFrameMutex);
++sync->videoFramePending;
do {
ConditionWake(&sync->videoFrameAvailableCond);
if (sync->videoFrameWait) {
ConditionWait(&sync->videoFrameRequiredCond, &sync->videoFrameMutex);
}
} while (sync->videoFrameWait && sync->videoFramePending);
MutexUnlock(&sync->videoFrameMutex);
}
void mCoreSyncForceFrame(struct mCoreSync* sync) {
if (!sync) {
return;
}
MutexLock(&sync->videoFrameMutex);
ConditionWake(&sync->videoFrameAvailableCond);
MutexUnlock(&sync->videoFrameMutex);
}
bool mCoreSyncWaitFrameStart(struct mCoreSync* sync) {
if (!sync) {
return true;
}
MutexLock(&sync->videoFrameMutex);
ConditionWake(&sync->videoFrameRequiredCond);
if (!sync->videoFrameOn && !sync->videoFramePending) {
return false;
}
if (sync->videoFrameOn) {
if (ConditionWaitTimed(&sync->videoFrameAvailableCond, &sync->videoFrameMutex, 50)) {
return false;
}
}
sync->videoFramePending = 0;
return true;
}
void mCoreSyncWaitFrameEnd(struct mCoreSync* sync) {
if (!sync) {
return;
}
MutexUnlock(&sync->videoFrameMutex);
}
void mCoreSyncSetVideoSync(struct mCoreSync* sync, bool wait) {
if (!sync) {
return;
}
_changeVideoSync(sync, wait);
}
void mCoreSyncProduceAudio(struct mCoreSync* sync, bool wait) {
if (!sync) {
return;
}
if (sync->audioWait && wait) {
// TODO loop properly in event of spurious wakeups
ConditionWait(&sync->audioRequiredCond, &sync->audioBufferMutex);
}
MutexUnlock(&sync->audioBufferMutex);
}
void mCoreSyncLockAudio(struct mCoreSync* sync) {
if (!sync) {
return;
}
MutexLock(&sync->audioBufferMutex);
}
void mCoreSyncUnlockAudio(struct mCoreSync* sync) {
if (!sync) {
return;
}
MutexUnlock(&sync->audioBufferMutex);
}
void mCoreSyncConsumeAudio(struct mCoreSync* sync) {
if (!sync) {
return;
}
ConditionWake(&sync->audioRequiredCond);
MutexUnlock(&sync->audioBufferMutex);
}
| mpl-2.0 |
SlateScience/MozillaJS | js/src/jit/BitSet.cpp | 5 | 2436 | /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sts=4 et sw=4 tw=99:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "jsutil.h"
#include "BitSet.h"
#include "jsscriptinlines.h"
using namespace js;
using namespace js::jit;
BitSet *
BitSet::New(unsigned int max)
{
BitSet *result = new BitSet(max);
if (!result->init())
return NULL;
return result;
}
bool
BitSet::init()
{
size_t sizeRequired = numWords() * sizeof(*bits_);
TempAllocator *alloc = GetIonContext()->temp;
bits_ = (uint32_t *)alloc->allocate(sizeRequired);
if (!bits_)
return false;
memset(bits_, 0, sizeRequired);
return true;
}
bool
BitSet::empty() const
{
JS_ASSERT(bits_);
for (unsigned int i = 0; i < numWords(); i++) {
if (bits_[i])
return false;
}
return true;
}
void
BitSet::insertAll(const BitSet *other)
{
JS_ASSERT(bits_);
JS_ASSERT(other->max_ == max_);
JS_ASSERT(other->bits_);
for (unsigned int i = 0; i < numWords(); i++)
bits_[i] |= other->bits_[i];
}
void
BitSet::removeAll(const BitSet *other)
{
JS_ASSERT(bits_);
JS_ASSERT(other->max_ == max_);
JS_ASSERT(other->bits_);
for (unsigned int i = 0; i < numWords(); i++)
bits_[i] &= ~other->bits_[i];
}
void
BitSet::intersect(const BitSet *other)
{
JS_ASSERT(bits_);
JS_ASSERT(other->max_ == max_);
JS_ASSERT(other->bits_);
for (unsigned int i = 0; i < numWords(); i++)
bits_[i] &= other->bits_[i];
}
// returns true if the intersection caused the contents of the set to change.
bool
BitSet::fixedPointIntersect(const BitSet *other)
{
JS_ASSERT(bits_);
JS_ASSERT(other->max_ == max_);
JS_ASSERT(other->bits_);
bool changed = false;
for (unsigned int i = 0; i < numWords(); i++) {
uint32_t old = bits_[i];
bits_[i] &= other->bits_[i];
if (!changed && old != bits_[i])
changed = true;
}
return changed;
}
void
BitSet::complement()
{
JS_ASSERT(bits_);
for (unsigned int i = 0; i < numWords(); i++)
bits_[i] = ~bits_[i];
}
void
BitSet::clear()
{
JS_ASSERT(bits_);
for (unsigned int i = 0; i < numWords(); i++)
bits_[i] = 0;
}
| mpl-2.0 |
tav/keyspace | src/Application/EchoServer/TCPEchoConn.cpp | 3 | 1369 | #include "TCPEchoConn.h"
TCPEchoConn::TCPEchoConn() :
onWelcome(this, &TCPEchoConn::OnWelcome),
onRead(this, &TCPEchoConn::OnRead),
onWrite(this, &TCPEchoConn::OnWrite),
onCloseRead(this, &TCPEchoConn::OnCloseRead),
onCloseWrite(this, &TCPEchoConn::OnCloseWrite)
{
}
bool TCPEchoConn::Init(IOProcessor* ioproc_)
{
ioproc = ioproc_;
tcpwrite.fd = socket.fd;
tcpwrite.data = data;
#define WELCOME_MSG "Welcome to TCPEchoServer!\n\n"
sprintf(tcpwrite.data.buffer, WELCOME_MSG);
tcpwrite.data.length = strlen(WELCOME_MSG);
tcpwrite.onComplete = &onWelcome;
tcpwrite.onClose = &onCloseWrite;
ioproc->Add(&tcpwrite);
return true;
}
void TCPEchoConn::OnWelcome()
{
Log_Trace();
tcpread.fd = socket.fd;
tcpread.data = data;
tcpread.requested = IO_READ_ANY;
tcpread.onComplete = &onRead;
tcpread.onClose = &onCloseRead;
ioproc->Add(&tcpread);
tcpwrite.onComplete = &onWrite;
}
void TCPEchoConn::Shutdown()
{
Log_Trace();
socket.Close();
}
void TCPEchoConn::OnRead()
{
Log_Trace();
tcpwrite.data.length = tcpread.data.length;
tcpwrite.transferred = 0;
ioproc->Add(&tcpwrite);
}
void TCPEchoConn::OnWrite()
{
Log_Trace();
tcpread.data.length = 0;
ioproc->Add(&tcpread);
}
void TCPEchoConn::OnCloseRead()
{
Log_Trace();
Shutdown();
delete this;
}
void TCPEchoConn::OnCloseWrite()
{
Log_Trace();
Shutdown();
delete this;
}
| agpl-3.0 |
hoangton/mobile | plugins/org.apache.cordova.crypt/src/ios/openssl-1.0.1m/crypto/conf/conf_lib.c | 179 | 10262 | /* conf_lib.c */
/*
* Written by Richard Levitte (richard@levitte.org) for the OpenSSL project
* 2000.
*/
/* ====================================================================
* Copyright (c) 2000 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED 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 OpenSSL PROJECT OR
* ITS 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.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include <openssl/crypto.h>
#include <openssl/err.h>
#include <openssl/conf.h>
#include <openssl/conf_api.h>
#include <openssl/lhash.h>
const char CONF_version[] = "CONF" OPENSSL_VERSION_PTEXT;
static CONF_METHOD *default_CONF_method = NULL;
/* Init a 'CONF' structure from an old LHASH */
void CONF_set_nconf(CONF *conf, LHASH_OF(CONF_VALUE) *hash)
{
if (default_CONF_method == NULL)
default_CONF_method = NCONF_default();
default_CONF_method->init(conf);
conf->data = hash;
}
/*
* The following section contains the "CONF classic" functions, rewritten in
* terms of the new CONF interface.
*/
int CONF_set_default_method(CONF_METHOD *meth)
{
default_CONF_method = meth;
return 1;
}
LHASH_OF(CONF_VALUE) *CONF_load(LHASH_OF(CONF_VALUE) *conf, const char *file,
long *eline)
{
LHASH_OF(CONF_VALUE) *ltmp;
BIO *in = NULL;
#ifdef OPENSSL_SYS_VMS
in = BIO_new_file(file, "r");
#else
in = BIO_new_file(file, "rb");
#endif
if (in == NULL) {
CONFerr(CONF_F_CONF_LOAD, ERR_R_SYS_LIB);
return NULL;
}
ltmp = CONF_load_bio(conf, in, eline);
BIO_free(in);
return ltmp;
}
#ifndef OPENSSL_NO_FP_API
LHASH_OF(CONF_VALUE) *CONF_load_fp(LHASH_OF(CONF_VALUE) *conf, FILE *fp,
long *eline)
{
BIO *btmp;
LHASH_OF(CONF_VALUE) *ltmp;
if (!(btmp = BIO_new_fp(fp, BIO_NOCLOSE))) {
CONFerr(CONF_F_CONF_LOAD_FP, ERR_R_BUF_LIB);
return NULL;
}
ltmp = CONF_load_bio(conf, btmp, eline);
BIO_free(btmp);
return ltmp;
}
#endif
LHASH_OF(CONF_VALUE) *CONF_load_bio(LHASH_OF(CONF_VALUE) *conf, BIO *bp,
long *eline)
{
CONF ctmp;
int ret;
CONF_set_nconf(&ctmp, conf);
ret = NCONF_load_bio(&ctmp, bp, eline);
if (ret)
return ctmp.data;
return NULL;
}
STACK_OF(CONF_VALUE) *CONF_get_section(LHASH_OF(CONF_VALUE) *conf,
const char *section)
{
if (conf == NULL) {
return NULL;
} else {
CONF ctmp;
CONF_set_nconf(&ctmp, conf);
return NCONF_get_section(&ctmp, section);
}
}
char *CONF_get_string(LHASH_OF(CONF_VALUE) *conf, const char *group,
const char *name)
{
if (conf == NULL) {
return NCONF_get_string(NULL, group, name);
} else {
CONF ctmp;
CONF_set_nconf(&ctmp, conf);
return NCONF_get_string(&ctmp, group, name);
}
}
long CONF_get_number(LHASH_OF(CONF_VALUE) *conf, const char *group,
const char *name)
{
int status;
long result = 0;
if (conf == NULL) {
status = NCONF_get_number_e(NULL, group, name, &result);
} else {
CONF ctmp;
CONF_set_nconf(&ctmp, conf);
status = NCONF_get_number_e(&ctmp, group, name, &result);
}
if (status == 0) {
/* This function does not believe in errors... */
ERR_clear_error();
}
return result;
}
void CONF_free(LHASH_OF(CONF_VALUE) *conf)
{
CONF ctmp;
CONF_set_nconf(&ctmp, conf);
NCONF_free_data(&ctmp);
}
#ifndef OPENSSL_NO_FP_API
int CONF_dump_fp(LHASH_OF(CONF_VALUE) *conf, FILE *out)
{
BIO *btmp;
int ret;
if (!(btmp = BIO_new_fp(out, BIO_NOCLOSE))) {
CONFerr(CONF_F_CONF_DUMP_FP, ERR_R_BUF_LIB);
return 0;
}
ret = CONF_dump_bio(conf, btmp);
BIO_free(btmp);
return ret;
}
#endif
int CONF_dump_bio(LHASH_OF(CONF_VALUE) *conf, BIO *out)
{
CONF ctmp;
CONF_set_nconf(&ctmp, conf);
return NCONF_dump_bio(&ctmp, out);
}
/*
* The following section contains the "New CONF" functions. They are
* completely centralised around a new CONF structure that may contain
* basically anything, but at least a method pointer and a table of data.
* These functions are also written in terms of the bridge functions used by
* the "CONF classic" functions, for consistency.
*/
CONF *NCONF_new(CONF_METHOD *meth)
{
CONF *ret;
if (meth == NULL)
meth = NCONF_default();
ret = meth->create(meth);
if (ret == NULL) {
CONFerr(CONF_F_NCONF_NEW, ERR_R_MALLOC_FAILURE);
return (NULL);
}
return ret;
}
void NCONF_free(CONF *conf)
{
if (conf == NULL)
return;
conf->meth->destroy(conf);
}
void NCONF_free_data(CONF *conf)
{
if (conf == NULL)
return;
conf->meth->destroy_data(conf);
}
int NCONF_load(CONF *conf, const char *file, long *eline)
{
if (conf == NULL) {
CONFerr(CONF_F_NCONF_LOAD, CONF_R_NO_CONF);
return 0;
}
return conf->meth->load(conf, file, eline);
}
#ifndef OPENSSL_NO_FP_API
int NCONF_load_fp(CONF *conf, FILE *fp, long *eline)
{
BIO *btmp;
int ret;
if (!(btmp = BIO_new_fp(fp, BIO_NOCLOSE))) {
CONFerr(CONF_F_NCONF_LOAD_FP, ERR_R_BUF_LIB);
return 0;
}
ret = NCONF_load_bio(conf, btmp, eline);
BIO_free(btmp);
return ret;
}
#endif
int NCONF_load_bio(CONF *conf, BIO *bp, long *eline)
{
if (conf == NULL) {
CONFerr(CONF_F_NCONF_LOAD_BIO, CONF_R_NO_CONF);
return 0;
}
return conf->meth->load_bio(conf, bp, eline);
}
STACK_OF(CONF_VALUE) *NCONF_get_section(const CONF *conf, const char *section)
{
if (conf == NULL) {
CONFerr(CONF_F_NCONF_GET_SECTION, CONF_R_NO_CONF);
return NULL;
}
if (section == NULL) {
CONFerr(CONF_F_NCONF_GET_SECTION, CONF_R_NO_SECTION);
return NULL;
}
return _CONF_get_section_values(conf, section);
}
char *NCONF_get_string(const CONF *conf, const char *group, const char *name)
{
char *s = _CONF_get_string(conf, group, name);
/*
* Since we may get a value from an environment variable even if conf is
* NULL, let's check the value first
*/
if (s)
return s;
if (conf == NULL) {
CONFerr(CONF_F_NCONF_GET_STRING,
CONF_R_NO_CONF_OR_ENVIRONMENT_VARIABLE);
return NULL;
}
CONFerr(CONF_F_NCONF_GET_STRING, CONF_R_NO_VALUE);
ERR_add_error_data(4, "group=", group, " name=", name);
return NULL;
}
int NCONF_get_number_e(const CONF *conf, const char *group, const char *name,
long *result)
{
char *str;
if (result == NULL) {
CONFerr(CONF_F_NCONF_GET_NUMBER_E, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
str = NCONF_get_string(conf, group, name);
if (str == NULL)
return 0;
for (*result = 0; conf->meth->is_number(conf, *str);) {
*result = (*result) * 10 + conf->meth->to_int(conf, *str);
str++;
}
return 1;
}
#ifndef OPENSSL_NO_FP_API
int NCONF_dump_fp(const CONF *conf, FILE *out)
{
BIO *btmp;
int ret;
if (!(btmp = BIO_new_fp(out, BIO_NOCLOSE))) {
CONFerr(CONF_F_NCONF_DUMP_FP, ERR_R_BUF_LIB);
return 0;
}
ret = NCONF_dump_bio(conf, btmp);
BIO_free(btmp);
return ret;
}
#endif
int NCONF_dump_bio(const CONF *conf, BIO *out)
{
if (conf == NULL) {
CONFerr(CONF_F_NCONF_DUMP_BIO, CONF_R_NO_CONF);
return 0;
}
return conf->meth->dump(conf, out);
}
/* This function should be avoided */
#if 0
long NCONF_get_number(CONF *conf, char *group, char *name)
{
int status;
long ret = 0;
status = NCONF_get_number_e(conf, group, name, &ret);
if (status == 0) {
/* This function does not believe in errors... */
ERR_get_error();
}
return ret;
}
#endif
| agpl-3.0 |
ONLYOFFICE/core | DesktopEditor/cximage/jpeg/cdjpeg.c | 205 | 4863 | /*
* cdjpeg.c
*
* Copyright (C) 1991-1997, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains common support routines used by the IJG application
* programs (cjpeg, djpeg, jpegtran).
*/
#include "cdjpeg.h" /* Common decls for cjpeg/djpeg applications */
#include <ctype.h> /* to declare isupper(), tolower() */
#ifdef NEED_SIGNAL_CATCHER
#include <signal.h> /* to declare signal() */
#endif
#ifdef USE_SETMODE
#include <fcntl.h> /* to declare setmode()'s parameter macros */
/* If you have setmode() but not <io.h>, just delete this line: */
#include <io.h> /* to declare setmode() */
#endif
/*
* Signal catcher to ensure that temporary files are removed before aborting.
* NB: for Amiga Manx C this is actually a global routine named _abort();
* we put "#define signal_catcher _abort" in jconfig.h. Talk about bogus...
*/
#ifdef NEED_SIGNAL_CATCHER
static j_common_ptr sig_cinfo;
void /* must be global for Manx C */
signal_catcher (int signum)
{
if (sig_cinfo != NULL) {
if (sig_cinfo->err != NULL) /* turn off trace output */
sig_cinfo->err->trace_level = 0;
jpeg_destroy(sig_cinfo); /* clean up memory allocation & temp files */
}
exit(EXIT_FAILURE);
}
GLOBAL(void)
enable_signal_catcher (j_common_ptr cinfo)
{
sig_cinfo = cinfo;
#ifdef SIGINT /* not all systems have SIGINT */
signal(SIGINT, signal_catcher);
#endif
#ifdef SIGTERM /* not all systems have SIGTERM */
signal(SIGTERM, signal_catcher);
#endif
}
#endif
/*
* Optional progress monitor: display a percent-done figure on stderr.
*/
#ifdef PROGRESS_REPORT
METHODDEF(void)
progress_monitor (j_common_ptr cinfo)
{
cd_progress_ptr prog = (cd_progress_ptr) cinfo->progress;
int total_passes = prog->pub.total_passes + prog->total_extra_passes;
int percent_done = (int) (prog->pub.pass_counter*100L/prog->pub.pass_limit);
if (percent_done != prog->percent_done) {
prog->percent_done = percent_done;
if (total_passes > 1) {
fprintf(stderr, "\rPass %d/%d: %3d%% ",
prog->pub.completed_passes + prog->completed_extra_passes + 1,
total_passes, percent_done);
} else {
fprintf(stderr, "\r %3d%% ", percent_done);
}
fflush(stderr);
}
}
GLOBAL(void)
start_progress_monitor (j_common_ptr cinfo, cd_progress_ptr progress)
{
/* Enable progress display, unless trace output is on */
if (cinfo->err->trace_level == 0) {
progress->pub.progress_monitor = progress_monitor;
progress->completed_extra_passes = 0;
progress->total_extra_passes = 0;
progress->percent_done = -1;
cinfo->progress = &progress->pub;
}
}
GLOBAL(void)
end_progress_monitor (j_common_ptr cinfo)
{
/* Clear away progress display */
if (cinfo->err->trace_level == 0) {
fprintf(stderr, "\r \r");
fflush(stderr);
}
}
#endif
/*
* Case-insensitive matching of possibly-abbreviated keyword switches.
* keyword is the constant keyword (must be lower case already),
* minchars is length of minimum legal abbreviation.
*/
GLOBAL(boolean)
keymatch (char * arg, const char * keyword, int minchars)
{
register int ca, ck;
register int nmatched = 0;
while ((ca = *arg++) != '\0') {
if ((ck = *keyword++) == '\0')
return FALSE; /* arg longer than keyword, no good */
if (isupper(ca)) /* force arg to lcase (assume ck is already) */
ca = tolower(ca);
if (ca != ck)
return FALSE; /* no good */
nmatched++; /* count matched characters */
}
/* reached end of argument; fail if it's too short for unique abbrev */
if (nmatched < minchars)
return FALSE;
return TRUE; /* A-OK */
}
/*
* Routines to establish binary I/O mode for stdin and stdout.
* Non-Unix systems often require some hacking to get out of text mode.
*/
GLOBAL(FILE *)
read_stdin (void)
{
FILE * input_file = stdin;
#ifdef USE_SETMODE /* need to hack file mode? */
setmode(fileno(stdin), O_BINARY);
#endif
#ifdef USE_FDOPEN /* need to re-open in binary mode? */
if ((input_file = fdopen(fileno(stdin), READ_BINARY)) == NULL) {
fprintf(stderr, "Cannot reopen stdin\n");
exit(EXIT_FAILURE);
}
#endif
return input_file;
}
GLOBAL(FILE *)
write_stdout (void)
{
FILE * output_file = stdout;
#ifdef USE_SETMODE /* need to hack file mode? */
setmode(fileno(stdout), O_BINARY);
#endif
#ifdef USE_FDOPEN /* need to re-open in binary mode? */
if ((output_file = fdopen(fileno(stdout), WRITE_BINARY)) == NULL) {
fprintf(stderr, "Cannot reopen stdout\n");
exit(EXIT_FAILURE);
}
#endif
return output_file;
}
| agpl-3.0 |
ARSekkat/gpac | src/compositor/audio_render.c | 1 | 24336 | /*
* GPAC - Multimedia Framework C SDK
*
* Authors: Jean Le Feuvre
* Copyright (c) Telecom ParisTech 2000-2012
* All rights reserved
*
* This file is part of GPAC / Scene Compositor sub-project
*
* GPAC is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* GPAC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
#include <gpac/internal/compositor_dev.h>
GF_Err gf_afc_load(GF_AudioFilterChain *afc, GF_User *user, char *filterstring)
{
struct _audiofilterentry *prev_filter = NULL;
while (filterstring) {
u32 i, count;
GF_AudioFilter *filter;
char *sep = strstr(filterstring, ";;");
if (sep) sep[0] = 0;
count = gf_modules_get_count(user->modules);
filter = NULL;
for (i=0; i<count; i++) {
filter = (GF_AudioFilter *)gf_modules_load_interface(user->modules, i, GF_AUDIO_FILTER_INTERFACE);
if (filter) {
if (filter->SetFilter
&& filter->Configure
&& filter->Process
&& filter->Reset
&& filter->SetOption
&& filter->GetOption
&& filter->SetFilter(filter, filterstring)
)
break;
gf_modules_close_interface((GF_BaseInterface *)filter);
}
filter = NULL;
}
if (filter) {
struct _audiofilterentry *entry;
GF_SAFEALLOC(entry, struct _audiofilterentry);
if (!entry) {
GF_LOG(GF_LOG_ERROR, GF_LOG_COMPOSE, ("[Compositor] Failed to allocate audio filter entry\n"));
} else {
entry->filter = filter;
if (prev_filter) prev_filter->next = entry;
else afc->filters = entry;
prev_filter = entry;
}
}
if (sep) {
sep[0] = ';';
filterstring = sep + 2;
} else {
break;
}
}
return GF_OK;
}
GF_Err gf_afc_setup(GF_AudioFilterChain *afc, u32 bps, u32 sr, u32 chan, u32 ch_cfg, u32 *ch_out, u32 *ch_cfg_out)
{
struct _audiofilterentry *entry;
u32 block_len;
u32 och, ocfg, in_ch;
Bool not_in_place;
if (afc->tmp_block1) gf_free(afc->tmp_block1);
afc->tmp_block1 = NULL;
if (afc->tmp_block2) gf_free(afc->tmp_block2);
afc->tmp_block2 = NULL;
*ch_out = *ch_cfg_out = 0;
in_ch = chan;
afc->min_block_size = 0;
afc->max_block_size = 0;
afc->delay_ms = 0;
not_in_place = GF_FALSE;
entry = afc->filters;
while (entry) {
if (entry->in_block) {
gf_free(entry->in_block);
entry->in_block = NULL;
}
if (entry->filter->Configure(entry->filter, sr, bps, chan, ch_cfg, &och, &ocfg, &block_len, &entry->delay_ms, &entry->in_place)==GF_OK) {
u32 out_block_size;
entry->in_block_size = chan * bps * block_len / 8;
if (!afc->min_block_size || (afc->min_block_size > entry->in_block_size))
afc->min_block_size = entry->in_block_size;
out_block_size = och * bps * block_len / 8;
if (afc->max_block_size < out_block_size) afc->max_block_size = out_block_size;
entry->enable = GF_TRUE;
chan = och;
ch_cfg = ocfg;
if (!entry->in_place) not_in_place = GF_TRUE;
afc->delay_ms += entry->delay_ms;
} else {
entry->enable = GF_FALSE;
}
entry = entry->next;
}
if (!afc->max_block_size) afc->max_block_size = 1000;
if (!afc->min_block_size) afc->min_block_size = afc->max_block_size * in_ch / chan;
afc->tmp_block1 = (char*)gf_malloc(sizeof(char) * afc->max_block_size * 2);
if (!afc->tmp_block1) return GF_OUT_OF_MEM;
if (not_in_place) {
afc->tmp_block2 = (char*)gf_malloc(sizeof(char) * afc->max_block_size * 2);
if (!afc->tmp_block2) return GF_OUT_OF_MEM;
}
/*alloc buffers*/
entry = afc->filters;
while (entry) {
if (entry->enable && entry->in_block_size) {
entry->in_block = (char*)gf_malloc(sizeof(char) * (entry->in_block_size + afc->max_block_size) );
if (!entry->in_block) return GF_OUT_OF_MEM;
}
entry = entry->next;
}
*ch_out = chan;
*ch_cfg_out = ch_cfg;
afc->enable_filters = GF_TRUE;
return GF_OK;
}
u32 gf_afc_process(GF_AudioFilterChain *afc, u32 nb_bytes)
{
struct _audiofilterentry *entry = afc->filters;
while (entry) {
char *inptr, *outptr;
if (!nb_bytes || !entry->enable) {
entry = entry->next;
continue;
}
inptr = afc->tmp_block1;
outptr = entry->in_place ? afc->tmp_block1 : afc->tmp_block2;
/*sample-based input, process directly the data*/
if (!entry->in_block) {
entry->filter->Process(entry->filter, inptr, nb_bytes, outptr, &nb_bytes);
} else {
u32 processed = 0;
u32 nb_bytes_out = 0;
assert(nb_bytes + entry->nb_bytes <= entry->in_block_size + afc->max_block_size);
/*copy bytes in input*/
memcpy(entry->in_block + entry->nb_bytes, inptr, nb_bytes);
entry->nb_bytes += nb_bytes;
/*and process*/
while (entry->nb_bytes >= entry->in_block_size) {
u32 done;
entry->filter->Process(entry->filter, entry->in_block + processed, entry->in_block_size, outptr + nb_bytes_out, &done);
done = entry->in_block_size;
nb_bytes_out += done;
entry->nb_bytes -= entry->in_block_size;
processed += entry->in_block_size;
}
/*move remaining data at the beginning of the buffer*/
if (processed && entry->nb_bytes)
memmove(entry->in_block, entry->in_block+processed, entry->nb_bytes);
nb_bytes = nb_bytes_out;
}
/*swap ptr so that input data of next step (filter, output write) is always in tmp_block1*/
if (inptr != outptr) {
afc->tmp_block1 = outptr;
afc->tmp_block2 = inptr;
}
entry = entry->next;
}
return nb_bytes;
}
void gf_afc_unload(GF_AudioFilterChain *afc)
{
while (afc->filters) {
struct _audiofilterentry *tmp = afc->filters;
afc->filters = tmp->next;
gf_modules_close_interface((GF_BaseInterface *)tmp->filter);
if (tmp->in_block) gf_free(tmp->in_block);
gf_free(tmp);
}
if (afc->tmp_block1) gf_free(afc->tmp_block1);
if (afc->tmp_block2) gf_free(afc->tmp_block2);
memset(afc, 0, sizeof(GF_AudioFilterChain));
}
void gf_afc_reset(GF_AudioFilterChain *afc)
{
struct _audiofilterentry *filter = afc->filters;
while (filter) {
filter->filter->Reset(filter->filter);
filter->nb_bytes = 0;
filter = filter->next;
}
}
static GF_Err gf_ar_setup_output_format(GF_AudioRenderer *ar)
{
GF_Err e;
const char *opt;
Bool skip_hw_config = GF_FALSE;
u32 freq, nb_bits, nb_chan, ch_cfg;
u32 in_ch, in_cfg, in_bps, in_freq;
freq = nb_bits = nb_chan = ch_cfg = 0;
opt = gf_cfg_get_key(ar->user->config, "Audio", "ForceFrequency");
if (!opt) gf_cfg_set_key(ar->user->config, "Audio", "ForceFrequency", "0");
else freq = atoi(opt);
opt = gf_cfg_get_key(ar->user->config, "Audio", "ForceChannels");
if (!opt) gf_cfg_set_key(ar->user->config, "Audio", "ForceChannels", "0");
else nb_chan = atoi(opt);
opt = gf_cfg_get_key(ar->user->config, "Audio", "ForceLayout");
if (!opt) gf_cfg_set_key(ar->user->config, "Audio", "ForceLayout", "0");
else {
if (!strnicmp(opt, "0x", 2)) sscanf(opt+2, "%x", &ch_cfg);
else sscanf(opt, "%x", &ch_cfg);
}
opt = gf_cfg_get_key(ar->user->config, "Audio", "ForceBPS");
if (!opt) gf_cfg_set_key(ar->user->config, "Audio", "ForceBPS", "0");
else nb_bits = atoi(opt);
if (!freq || !nb_bits || !nb_chan || !ch_cfg) {
gf_mixer_get_config(ar->mixer, &freq, &nb_chan, &nb_bits, &ch_cfg);
/*user disabled multichannel audio*/
if (ar->disable_multichannel && (nb_chan>2) ) nb_chan = 2;
} else {
if (ar->config_forced) skip_hw_config = GF_TRUE;
else ar->config_forced++;
}
in_ch = nb_chan;
in_cfg = ch_cfg;
in_bps = nb_bits;
in_freq = freq;
if (ar->filter_chain.filters) {
u32 osr, obps, och, ocfg;
e = gf_afc_setup(&ar->filter_chain, nb_bits, freq, nb_chan, ch_cfg, &och, &ocfg);
osr = freq;
obps = nb_bits;
nb_chan = och;
/*try to reconfigure audio output*/
if (!e)
e = ar->audio_out->ConfigureOutput(ar->audio_out, &osr, &och, &obps, ocfg);
/*output module cannot support filter output, disable it ...*/
if (e || (osr != freq) || (och != nb_chan) || (obps != nb_bits)) {
nb_bits = in_bps;
freq = in_freq;
nb_chan = in_ch;
ar->filter_chain.enable_filters = GF_FALSE;
e = ar->audio_out->ConfigureOutput(ar->audio_out, &freq, &nb_chan, &nb_bits, ch_cfg);
}
} else if (!skip_hw_config) {
e = ar->audio_out->ConfigureOutput(ar->audio_out, &freq, &nb_chan, &nb_bits, ch_cfg);
} else {
e = GF_OK;
}
if (e) {
GF_LOG(GF_LOG_ERROR, GF_LOG_MMIO, ("[AudioRender] reconfigure error %d\n", e));
if (nb_chan>2) {
nb_chan=2;
in_ch=2;
ch_cfg=0;
e = ar->audio_out->ConfigureOutput(ar->audio_out, &freq, &nb_chan, &nb_bits, ch_cfg);
}
if (e) return e;
}
gf_mixer_set_config(ar->mixer, freq, nb_chan, nb_bits, in_cfg);
ar->audio_delay = ar->audio_out->GetAudioDelay(ar->audio_out);
ar->audio_out->SetVolume(ar->audio_out, ar->volume);
ar->audio_out->SetPan(ar->audio_out, ar->pan);
ar->time_at_last_config = ar->current_time;
ar->bytes_requested = 0;
ar->bytes_per_second = freq * nb_chan * nb_bits / 8;
if (ar->audio_listeners) {
u32 k=0;
GF_AudioListener *l;
while ((l = (GF_AudioListener*)gf_list_enum(ar->audio_listeners, &k))) {
l->on_audio_reconfig(l->udta, in_freq, in_bps, in_ch, in_cfg);
}
}
return GF_OK;
}
static void gf_ar_pause(GF_AudioRenderer *ar, Bool DoFreeze, Bool for_reconfig, Bool reset_hw_buffer)
{
gf_mixer_lock(ar->mixer, GF_TRUE);
if (DoFreeze) {
if (!ar->Frozen) {
ar->freeze_time = gf_sys_clock_high_res();
if (!for_reconfig && ar->audio_out && ar->audio_out->Play) ar->audio_out->Play(ar->audio_out, 0);
ar->Frozen = GF_TRUE;
GF_LOG(GF_LOG_DEBUG, GF_LOG_SYNC, ("[Audio] pausing master clock - time "LLD" (sys time "LLD")\n", ar->freeze_time, gf_sys_clock_high_res()));
}
} else {
if (ar->Frozen) {
if (!for_reconfig && ar->audio_out && ar->audio_out->Play) ar->audio_out->Play(ar->audio_out, reset_hw_buffer ? 2 : 1);
ar->Frozen = GF_FALSE;
ar->start_time += gf_sys_clock_high_res() - ar->freeze_time;
GF_LOG(GF_LOG_DEBUG, GF_LOG_SYNC, ("[Audio] resuming master clock - new time "LLD" (sys time "LLD") \n", ar->start_time, gf_sys_clock_high_res()));
}
}
gf_mixer_lock(ar->mixer, GF_FALSE);
}
static u32 gf_ar_fill_output(void *ptr, char *buffer, u32 buffer_size)
{
u32 written;
GF_AudioRenderer *ar = (GF_AudioRenderer *) ptr;
if (!ar->need_reconfig) {
u32 delay_ms = ar->disable_resync ? 0 : ar->audio_delay;
if (ar->Frozen) {
memset(buffer, 0, buffer_size);
return buffer_size;
}
gf_mixer_lock(ar->mixer, GF_TRUE);
if (ar->filter_chain.enable_filters) {
char *ptr = buffer;
written = 0;
delay_ms += ar->filter_chain.delay_ms;
while (buffer_size) {
u32 to_copy;
if (!ar->nb_used) {
u32 nb_bytes;
/*fill input block*/
nb_bytes = gf_mixer_get_output(ar->mixer, ar->filter_chain.tmp_block1, ar->filter_chain.min_block_size, delay_ms);
if (!nb_bytes)
return written;
/*delay used to check for late frames - we only use it on the first call to gf_mixer_get_output()*/
delay_ms = 0;
ar->nb_filled = gf_afc_process(&ar->filter_chain, nb_bytes);
if (!ar->nb_filled) continue;
}
to_copy = ar->nb_filled - ar->nb_used;
if (to_copy>buffer_size) to_copy = buffer_size;
memcpy(ptr, ar->filter_chain.tmp_block1 + ar->nb_used, to_copy);
ptr += to_copy;
buffer_size -= to_copy;
written += to_copy;
ar->nb_used += to_copy;
if (ar->nb_used==ar->nb_filled) ar->nb_used = 0;
}
} else {
/*written = */gf_mixer_get_output(ar->mixer, buffer, buffer_size, delay_ms);
}
gf_mixer_lock(ar->mixer, GF_FALSE);
//done with one sim step, go back in pause
if (ar->step_mode) {
ar->step_mode = GF_FALSE;
gf_ar_pause(ar, GF_TRUE, GF_FALSE, GF_FALSE);
}
if (!ar->need_reconfig) {
if (ar->audio_listeners) {
u32 k=0;
GF_AudioListener *l;
while ((l = (GF_AudioListener*)gf_list_enum(ar->audio_listeners, &k))) {
l->on_audio_frame(l->udta, buffer, buffer_size, gf_sc_ar_get_clock(ar), delay_ms);
}
}
ar->bytes_requested += buffer_size;
ar->current_time = ar->time_at_last_config + (u32) (ar->bytes_requested * 1000 / ar->bytes_per_second);
}
//always return buffer size (eg requested input size to be filled), since the clock is always increased by buffer_size (cf above line)
return buffer_size;
} else {
memset(buffer, 0, buffer_size);
}
return 0;
}
void gf_sc_flush_next_audio(GF_Compositor *compositor)
{
if (!compositor->audio_renderer->audio_out)
return;
gf_mixer_lock(compositor->audio_renderer->mixer, GF_TRUE);
compositor->audio_renderer->step_mode = GF_TRUE;
//resume for one frame
if (compositor->audio_renderer->Frozen) {
gf_ar_pause(compositor->audio_renderer, GF_FALSE, GF_FALSE, GF_FALSE);
}
gf_mixer_lock(compositor->audio_renderer->mixer, GF_FALSE);
}
Bool gf_sc_check_audio_pending(GF_Compositor *compositor)
{
Bool res = GF_FALSE;
gf_mixer_lock(compositor->audio_renderer->mixer, GF_TRUE);
if (compositor->audio_renderer->step_mode)
res = GF_FALSE;
gf_mixer_lock(compositor->audio_renderer->mixer, GF_FALSE);
return res;
}
u32 gf_ar_proc(void *p)
{
GF_AudioRenderer *ar = (GF_AudioRenderer *) p;
ar->audio_th_state = 1;
GF_LOG(GF_LOG_DEBUG, GF_LOG_CORE, ("[AudioRender] Entering audio thread ID %d\n", gf_th_id() ));
gf_mixer_lock(ar->mixer, GF_TRUE);
ar->need_reconfig = GF_TRUE;
gf_sc_ar_reconfig(ar);
gf_mixer_lock(ar->mixer, GF_FALSE);
while (ar->audio_th_state == 1) {
//do mix even if mixer is empty, otherwise we will push the same buffer over and over to the sound card
/*
if (ar->Frozen ) {
gf_sleep(0);
} else
*/ {
if (ar->need_reconfig) gf_sc_ar_reconfig(ar);
ar->audio_out->WriteAudio(ar->audio_out);
}
}
GF_LOG(GF_LOG_DEBUG, GF_LOG_AUDIO, ("[AudioRender] Exiting audio thread\n"));
ar->audio_out->Shutdown(ar->audio_out);
ar->audio_th_state = 3;
return 0;
}
GF_AudioRenderer *gf_sc_ar_load(GF_User *user)
{
const char *sOpt;
u32 i, count;
u32 num_buffers, total_duration;
GF_Err e;
GF_AudioRenderer *ar;
ar = (GF_AudioRenderer *) gf_malloc(sizeof(GF_AudioRenderer));
memset(ar, 0, sizeof(GF_AudioRenderer));
num_buffers = total_duration = 0;
sOpt = gf_cfg_get_key(user->config, "Audio", "ForceConfig");
if (sOpt && !stricmp(sOpt, "yes")) {
sOpt = gf_cfg_get_key(user->config, "Audio", "NumBuffers");
num_buffers = sOpt ? atoi(sOpt) : 6;
sOpt = gf_cfg_get_key(user->config, "Audio", "TotalDuration");
total_duration = sOpt ? atoi(sOpt) : 400;
}
sOpt = gf_cfg_get_key(user->config, "Audio", "NoResync");
ar->disable_resync = (sOpt && !stricmp(sOpt, "yes")) ? GF_TRUE : GF_FALSE;
sOpt = gf_cfg_get_key(user->config, "Audio", "DisableMultiChannel");
ar->disable_multichannel = (sOpt && !stricmp(sOpt, "yes")) ? GF_TRUE : GF_FALSE;
ar->mixer = gf_mixer_new(ar);
ar->user = user;
ar->volume = 100;
sOpt = gf_cfg_get_key(user->config, "Audio", "Volume");
if (!sOpt) gf_cfg_set_key(user->config, "Audio", "Volume", "100");
else ar->volume = atoi(sOpt);
sOpt = gf_cfg_get_key(user->config, "Audio", "Pan");
ar->pan = sOpt ? atoi(sOpt) : 50;
if (! (user->init_flags & GF_TERM_NO_AUDIO) ) {
/*get a prefered compositor*/
sOpt = gf_cfg_get_key(user->config, "Audio", "DriverName");
if (sOpt) {
ar->audio_out = (GF_AudioOutput *) gf_modules_load_interface_by_name(user->modules, sOpt, GF_AUDIO_OUTPUT_INTERFACE);
if (!ar->audio_out) {
ar->audio_out = NULL;
sOpt = NULL;
}
}
if (!ar->audio_out) {
GF_AudioOutput *raw_out = NULL;
count = gf_modules_get_count(ar->user->modules);
for (i=0; i<count; i++) {
ar->audio_out = (GF_AudioOutput *) gf_modules_load_interface(ar->user->modules, i, GF_AUDIO_OUTPUT_INTERFACE);
if (!ar->audio_out) continue;
//in enum mode, only use raw out if everything else failed ...
if (!stricmp(ar->audio_out->module_name, "Raw Audio Output")) {
raw_out = ar->audio_out;
ar->audio_out = NULL;
continue;
}
GF_LOG(GF_LOG_DEBUG, GF_LOG_AUDIO, ("[AudioRender] Audio output module %s loaded\n", ar->audio_out->module_name));
/*check that's a valid audio compositor*/
if ((ar->audio_out->SelfThreaded && ar->audio_out->SetPriority) || ar->audio_out->WriteAudio) {
/*remember the module we use*/
gf_cfg_set_key(user->config, "Audio", "DriverName", ar->audio_out->module_name);
break;
}
gf_modules_close_interface((GF_BaseInterface *)ar->audio_out);
ar->audio_out = NULL;
}
if (raw_out) {
if (ar->audio_out) gf_modules_close_interface((GF_BaseInterface *)raw_out);
else ar->audio_out = raw_out;
}
}
/*if not init we run with a NULL audio compositor*/
if (ar->audio_out) {
ar->audio_out->FillBuffer = gf_ar_fill_output;
ar->audio_out->audio_renderer = ar;
GF_LOG(GF_LOG_DEBUG, GF_LOG_AUDIO, ("[AudioRender] Setting up audio module %s\n", ar->audio_out->module_name));
e = ar->audio_out->Setup(ar->audio_out, ar->user->os_window_handler, num_buffers, total_duration);
/*load main audio filter*/
gf_afc_load(&ar->filter_chain, user, (char*)gf_cfg_get_key(user->config, "Audio", "Filter"));
if (e != GF_OK) {
GF_LOG(GF_LOG_ERROR, GF_LOG_MMIO, ("Could not setup audio out %s\n", ar->audio_out->module_name));
gf_modules_close_interface((GF_BaseInterface *)ar->audio_out);
ar->audio_out = NULL;
} else {
if (!ar->audio_out->SelfThreaded) {
ar->th = gf_th_new("AudioRenderer");
gf_th_run(ar->th, gf_ar_proc, ar);
} else {
gf_ar_setup_output_format(ar);
if (ar->audio_out->SetPriority) ar->audio_out->SetPriority(ar->audio_out, GF_THREAD_PRIORITY_REALTIME);
}
}
}
if (!ar->audio_out) {
gf_cfg_set_key(user->config, "Audio", "DriverName", "No Audio Output Available");
} else {
if (user->init_flags & GF_TERM_USE_AUDIO_HW_CLOCK)
ar->clock_use_audio_out = GF_TRUE;
}
}
/*init compositor timer*/
ar->start_time = gf_sys_clock_high_res();
ar->current_time = 0;
return ar;
}
void gf_sc_ar_del(GF_AudioRenderer *ar)
{
if (!ar) return;
GF_LOG(GF_LOG_DEBUG, GF_LOG_AUDIO, ("[AudioRender] Destroying compositor\n"));
/*resume if paused (might cause deadlock otherwise)*/
if (ar->Frozen) gf_sc_ar_control(ar, GF_SC_AR_RESUME);
/*stop and shutdown*/
if (ar->audio_out) {
/*kill audio thread*/
if (!ar->audio_out->SelfThreaded) {
GF_LOG(GF_LOG_DEBUG, GF_LOG_AUDIO, ("[AudioRender] stopping audio thread\n"));
ar->audio_th_state = 2;
while (ar->audio_th_state != 3) {
gf_sleep(33);
}
GF_LOG(GF_LOG_DEBUG, GF_LOG_AUDIO, ("[AudioRender] audio thread stopped\n"));
gf_th_del(ar->th);
GF_LOG(GF_LOG_DEBUG, GF_LOG_AUDIO, ("[AudioRender] audio thread destroyed\n"));
}
/*lock access before shutdown and emulate a reconfig (avoids mixer lock from self-threaded modules)*/
ar->need_reconfig = GF_TRUE;
gf_mixer_lock(ar->mixer, GF_TRUE);
if (ar->audio_out->SelfThreaded) ar->audio_out->Shutdown(ar->audio_out);
gf_modules_close_interface((GF_BaseInterface *)ar->audio_out);
ar->audio_out = NULL;
gf_mixer_lock(ar->mixer, GF_FALSE);
}
gf_mixer_del(ar->mixer);
if (ar->audio_listeners) gf_list_del(ar->audio_listeners);
gf_afc_unload(&ar->filter_chain);
gf_free(ar);
GF_LOG(GF_LOG_DEBUG, GF_LOG_AUDIO, ("[AudioRender] Renderer destroyed\n"));
}
void gf_sc_ar_reset(GF_AudioRenderer *ar)
{
gf_mixer_remove_all(ar->mixer);
}
void gf_sc_ar_control(GF_AudioRenderer *ar, u32 PauseType)
{
gf_ar_pause(ar, (PauseType==GF_SC_AR_PAUSE) ? GF_TRUE : GF_FALSE, GF_FALSE, (PauseType==GF_SC_AR_RESET_HW_AND_PLAY) ? GF_TRUE : GF_FALSE);
}
void gf_sc_ar_set_volume(GF_AudioRenderer *ar, u32 Volume)
{
char sOpt[10];
gf_mixer_lock(ar->mixer, GF_TRUE);
ar->volume = MIN(Volume, 100);
if (ar->audio_out) ar->audio_out->SetVolume(ar->audio_out, ar->volume);
sprintf(sOpt, "%d", ar->volume);
gf_cfg_set_key(ar->user->config, "Audio", "Volume", sOpt);
gf_mixer_lock(ar->mixer, GF_FALSE);
}
void gf_sc_ar_mute(GF_AudioRenderer *ar, Bool mute)
{
gf_mixer_lock(ar->mixer, GF_TRUE);
ar->mute = mute;
if (ar->audio_out) ar->audio_out->SetVolume(ar->audio_out, mute ? 0 : ar->volume);
gf_mixer_lock(ar->mixer, GF_FALSE);
}
void gf_sc_ar_set_pan(GF_AudioRenderer *ar, u32 Balance)
{
gf_mixer_lock(ar->mixer, GF_TRUE);
ar->pan = MIN(Balance, 100);
if (ar->audio_out) ar->audio_out->SetPan(ar->audio_out, ar->pan);
gf_mixer_lock(ar->mixer, GF_FALSE);
}
void gf_sc_ar_add_src(GF_AudioRenderer *ar, GF_AudioInterface *source)
{
Bool recfg;
if (!ar) return;
/*lock mixer*/
gf_mixer_lock(ar->mixer, GF_TRUE);
gf_mixer_add_input(ar->mixer, source);
/*if changed reconfig*/
recfg = gf_mixer_reconfig(ar->mixer);
if (!ar->need_reconfig) ar->need_reconfig = recfg;
if (!gf_mixer_empty(ar->mixer) && ar->audio_out && ar->audio_out->Play)
ar->audio_out->Play(ar->audio_out, 1);
/*unlock mixer*/
gf_mixer_lock(ar->mixer, GF_FALSE);
}
void gf_sc_ar_remove_src(GF_AudioRenderer *ar, GF_AudioInterface *source)
{
if (ar) {
gf_mixer_remove_input(ar->mixer, source);
if (gf_mixer_empty(ar->mixer) && ar->audio_out && ar->audio_out->Play)
ar->audio_out->Play(ar->audio_out, 0);
}
}
void gf_sc_ar_set_priority(GF_AudioRenderer *ar, u32 priority)
{
if (ar->audio_out && ar->audio_out->SelfThreaded) {
ar->audio_out->SetPriority(ar->audio_out, priority);
} else {
gf_th_set_priority(ar->th, priority);
}
}
void gf_sc_ar_reconfig(GF_AudioRenderer *ar)
{
Bool frozen;
if (!ar->need_reconfig || !ar->audio_out) return;
/*lock mixer*/
gf_mixer_lock(ar->mixer, GF_TRUE);
frozen = ar->Frozen;
if (!frozen )
gf_ar_pause(ar, GF_TRUE, GF_TRUE, GF_FALSE);
ar->need_reconfig = GF_FALSE;
gf_ar_setup_output_format(ar);
if (!frozen)
gf_ar_pause(ar, GF_FALSE, GF_TRUE, GF_FALSE);
/*unlock mixer*/
gf_mixer_lock(ar->mixer, GF_FALSE);
}
u32 gf_sc_ar_get_delay(GF_AudioRenderer *ar)
{
return ar->audio_out->GetAudioDelay(ar->audio_out);
}
u32 gf_sc_ar_get_clock(GF_AudioRenderer *ar)
{
if (ar->clock_use_audio_out) return ar->current_time;
if (ar->Frozen) {
return (u32) ((ar->freeze_time - ar->start_time) / 1000);
}
return (u32) ((gf_sys_clock_high_res() - ar->start_time) / 1000);
}
GF_EXPORT
void gf_sc_reload_audio_filters(GF_Compositor *compositor)
{
GF_AudioRenderer *ar = compositor->audio_renderer;
if (!ar) return;
gf_mixer_lock(ar->mixer, GF_TRUE);
gf_afc_unload(&ar->filter_chain);
gf_afc_load(&ar->filter_chain, ar->user, (char*)gf_cfg_get_key(ar->user->config, "Audio", "Filter"));
gf_ar_pause(ar, GF_TRUE, GF_TRUE, GF_FALSE);
ar->need_reconfig = GF_FALSE;
gf_ar_setup_output_format(ar);
gf_ar_pause(ar, GF_FALSE, GF_TRUE, GF_FALSE);
gf_mixer_lock(ar->mixer, GF_FALSE);
}
GF_EXPORT
GF_Err gf_sc_add_audio_listener(GF_Compositor *compositor, GF_AudioListener *al)
{
GF_AudioMixer *mixer;
u32 sr, ch, bps, ch_cfg;
if (!compositor || !al || !al->on_audio_frame || !al->on_audio_reconfig) return GF_BAD_PARAM;
if (!compositor->audio_renderer) return GF_NOT_SUPPORTED;
mixer = compositor->audio_renderer->mixer;
gf_mixer_lock(mixer, GF_TRUE);
if (!compositor->audio_renderer->audio_listeners) compositor->audio_renderer->audio_listeners = gf_list_new();
gf_list_add(compositor->audio_renderer->audio_listeners, al);
gf_mixer_get_config(mixer, &sr, &ch, &bps, &ch_cfg);
al->on_audio_reconfig(al->udta, sr, bps, ch, ch_cfg);
gf_mixer_lock(mixer, GF_FALSE);
return GF_OK;
}
GF_EXPORT
GF_Err gf_sc_remove_audio_listener(GF_Compositor *compositor, GF_AudioListener *al)
{
if (!compositor || !al) return GF_BAD_PARAM;
if (!compositor->audio_renderer) return GF_NOT_SUPPORTED;
gf_mixer_lock(compositor->audio_renderer->mixer, GF_TRUE);
gf_list_del_item(compositor->audio_renderer->audio_listeners, al);
if (!gf_list_count(compositor->audio_renderer->audio_listeners)) {
gf_list_del(compositor->audio_renderer->audio_listeners);
compositor->audio_renderer->audio_listeners = NULL;
}
gf_mixer_lock(compositor->audio_renderer->mixer, GF_FALSE);
return GF_OK;
}
| lgpl-2.1 |
youfoh/webkit-efl | Source/WebCore/rendering/RenderTableCol.cpp | 1 | 5194 | /*
* Copyright (C) 1997 Martin Jones (mjones@kde.org)
* (C) 1997 Torben Weis (weis@kde.org)
* (C) 1998 Waldo Bastian (bastian@kde.org)
* (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* Copyright (C) 2003, 2004, 2005, 2006, 2009 Apple Inc. All rights reserved.
* Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "RenderTableCol.h"
#include "CachedImage.h"
#include "HTMLNames.h"
#include "HTMLTableColElement.h"
#include "RenderTable.h"
namespace WebCore {
using namespace HTMLNames;
RenderTableCol::RenderTableCol(Node* node)
: RenderBox(node)
, m_span(1)
{
// init RenderObject attributes
setInline(true); // our object is not Inline
updateFromElement();
}
void RenderTableCol::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
{
RenderBox::styleDidChange(diff, oldStyle);
// If border was changed, notify table.
if (parent()) {
RenderTable* table = this->table();
if (table && !table->selfNeedsLayout() && !table->normalChildNeedsLayout() && oldStyle && oldStyle->border() != style()->border())
table->invalidateCollapsedBorders();
}
}
void RenderTableCol::updateFromElement()
{
unsigned oldSpan = m_span;
Node* n = node();
if (n && (n->hasTagName(colTag) || n->hasTagName(colgroupTag))) {
HTMLTableColElement* tc = static_cast<HTMLTableColElement*>(n);
m_span = tc->span();
} else
m_span = !(style() && style()->display() == TABLE_COLUMN_GROUP);
if (m_span != oldSpan && style() && parent())
setNeedsLayoutAndPrefWidthsRecalc();
}
bool RenderTableCol::isChildAllowed(RenderObject* child, RenderStyle* style) const
{
// We cannot use isTableColumn here as style() may return 0.
return child->isRenderTableCol() && style->display() == TABLE_COLUMN;
}
bool RenderTableCol::canHaveChildren() const
{
// Cols cannot have children. This is actually necessary to fix a bug
// with libraries.uc.edu, which makes a <p> be a table-column.
return isTableColumnGroup();
}
LayoutRect RenderTableCol::clippedOverflowRectForRepaint(RenderBoxModelObject* repaintContainer) const
{
// For now, just repaint the whole table.
// FIXME: Find a better way to do this, e.g., need to repaint all the cells that we
// might have propagated a background color or borders into.
// FIXME: check for repaintContainer each time here?
RenderTable* parentTable = table();
if (!parentTable)
return LayoutRect();
return parentTable->clippedOverflowRectForRepaint(repaintContainer);
}
void RenderTableCol::imageChanged(WrappedImagePtr, const IntRect*)
{
// FIXME: Repaint only the rect the image paints in.
repaint();
}
void RenderTableCol::computePreferredLogicalWidths()
{
setPreferredLogicalWidthsDirty(false);
for (RenderObject* child = firstChild(); child; child = child->nextSibling())
child->setPreferredLogicalWidthsDirty(false);
}
RenderTable* RenderTableCol::table() const
{
RenderObject* table = parent();
if (table && !table->isTable())
table = table->parent();
return table && table->isTable() ? toRenderTable(table) : 0;
}
RenderTableCol* RenderTableCol::enclosingColumnGroup() const
{
if (!parent()->isRenderTableCol())
return 0;
RenderTableCol* parentColumnGroup = toRenderTableCol(parent());
ASSERT(parentColumnGroup->isTableColumnGroup());
ASSERT(isTableColumn());
return parentColumnGroup;
}
RenderTableCol* RenderTableCol::nextColumn() const
{
// If |this| is a column-group, the next column is the colgroup's first child column.
if (RenderObject* firstChild = this->firstChild())
return toRenderTableCol(firstChild);
// Otherwise it's the next column along.
RenderObject* next = nextSibling();
// Failing that, the child is the last column in a column-group, so the next column is the next column/column-group after its column-group.
if (!next && parent()->isRenderTableCol())
next = parent()->nextSibling();
for (; next && !next->isRenderTableCol(); next = next->nextSibling()) {
// We allow captions mixed with columns and column-groups.
if (next->isTableCaption())
continue;
return 0;
}
return toRenderTableCol(next);
}
}
| lgpl-2.1 |
0branch/qtide | lib/base/pnew.cpp | 1 | 4309 | #include <QBoxLayout>
#include <QCheckBox>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include "base.h"
#include "pnew.h"
#include "dialog.h"
#include "note.h"
#include "proj.h"
#include "state.h"
#include "term.h"
#include "widget.h"
using namespace std;
// ---------------------------------------------------------------------
Pnew::Pnew()
{
setAttribute(Qt::WA_DeleteOnClose);
Title="New Project";
Path=cfpath(getprojectpath());
QVBoxLayout *v=new QVBoxLayout;
v->setContentsMargins(v->contentsMargins());
v->setSpacing(0);
v->addWidget(createfolderpanel());
v->addWidget(createscriptspanel());
v->addWidget(createotherpanel());
v->addWidget(makehline());
v->addWidget(createbuttonpanel());
setLayout(v);
setWindowTitle(Title);
#ifdef SMALL_SCREEN
move(0,0);
resize(term->width(),term->height());
#else
resize(500,0);
#endif
QMetaObject::connectSlotsByName(this);
}
// ---------------------------------------------------------------------
QWidget *Pnew::createbuttonpanel()
{
QWidget *w=new QWidget();
QHBoxLayout *h=new QHBoxLayout;
QPushButton *create=makebutton("Create");
create->setAutoDefault(true);
h->addStretch(1);
h->addWidget(create,0);
w->setLayout(h);
return w;
}
// ---------------------------------------------------------------------
QWidget *Pnew::createfolderpanel()
{
QString s;
QWidget *w=new QWidget();
QHBoxLayout *h=new QHBoxLayout;
h->addWidget(new QLabel("Folder:"),0);
folder=new QLineEdit();
s=termsep(tofoldername(Path));
folder->setText(s);
h->addWidget(folder,1);
QPushButton *browse=makebutton("Browse");
browse->setAutoDefault(false);
browse->setText("");
browse->setIcon(QIcon(":/images/dir.png"));
h->addWidget(browse,0);
w->setLayout(h);
return w;
}
// ---------------------------------------------------------------------
QWidget *Pnew::createotherpanel()
{
QWidget *w=new QWidget();
QHBoxLayout *b=new QHBoxLayout;
b->addWidget(new QLabel("Other Scripts:"));
other=new QLineEdit();
b->addWidget(other,1);
w->setLayout(b);
return w;
}
// ---------------------------------------------------------------------
QWidget *Pnew::createscriptspanel()
{
QWidget *w=new QWidget();
QHBoxLayout *b=new QHBoxLayout;
b->addWidget(new QLabel("Create Scripts:"));
cbuild=makecheckbox("build");
crun=makecheckbox("run");
cinit=makecheckbox("init");
cbuild->setChecked(true);
crun->setChecked(true);
cinit->setChecked(true);
b->addWidget(cbuild);
b->addWidget(crun);
b->addWidget(cinit);
b->addStretch(1);
w->setLayout(b);
return w;
}
// ---------------------------------------------------------------------
void Pnew::on_browse_clicked()
{
QString s=dialogdirectory(this,Title,Path);
if (s.size())
folder->setText(tofoldername(s)+"/");
}
// ---------------------------------------------------------------------
void Pnew::on_create_clicked()
{
int i;
QString m,pf,s,t;
s=remsep(cpath(folder->text()));
if (s.isEmpty()) return;
Dir=new QDir();
Dir->setPath(s);
if (!Dir->exists()) {
if (!Dir->mkpath(Dir->path())) {
info(Title,"directory could not be created:\n\n"+s);
return;
}
}
t=cfsname(s) + config.ProjExt;
pf=Dir->filePath(t);
if (cfexist(pf)) {
info(Title,"Project already exists:\n\n"+ pf);
return;
}
QStringList p;
p.append(t);
if (cbuild->isChecked())
p.append("build");
if (crun->isChecked())
p.append("run");
if (cinit->isChecked())
p.append("init");
p+=other->text().split(" ",QString::SkipEmptyParts);
for(i=0; i<p.size(); i++)
p.replace(i,defext(p.at(i)));
p.removeDuplicates();
foreach(QString m,p)
cfcreate(Dir->filePath(m));
t=config.DefCCmt;
m=t+" project:\n"+t+"\n"+t+" defines list of source files.\n";
m+=t+" path defaults to project directory.\n\n";
p.removeFirst();
p.removeAll(defext("build"));
p.removeAll(defext("run"));
cfwrite(pf,m+p.join("\n"));
QString id=tofoldername(s);
if ('~'==id.at(0))
id=id.mid(1);
if (note == 0)
term->vieweditor();
else
note->projectsave();
project.open(id);
note->projectopen(true);
accept();
}
// ---------------------------------------------------------------------
bool Pnew::run()
{
return QDialog::Accepted==exec();
}
| lgpl-2.1 |
GNOME/gtksourceview | gtksourceview/gtksourcegutterrenderertext.c | 1 | 16476 | /*
* This file is part of GtkSourceView
*
* Copyright 2010 - Jesse van den Kieboom
*
* GtkSourceView is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* GtkSourceView is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, see <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include "gtksourcegutterrenderertext.h"
#include "gtksourcegutterlines.h"
#include "gtksourceview-private.h"
/**
* GtkSourceGutterRendererText:
*
* Renders text in the gutter.
*
* A `GtkSourceGutterRendererText` can be used to render text in a cell of
* [class@Gutter].
*/
typedef struct
{
int width;
int height;
} Size;
typedef struct
{
gchar *text;
PangoLayout *cached_layout;
PangoAttribute *current_line_bold;
PangoAttribute *current_line_color;
gsize text_len;
Size cached_sizes[5];
guint is_markup : 1;
guint has_selection : 1;
} GtkSourceGutterRendererTextPrivate;
G_DEFINE_TYPE_WITH_PRIVATE (GtkSourceGutterRendererText, gtk_source_gutter_renderer_text, GTK_SOURCE_TYPE_GUTTER_RENDERER)
enum
{
PROP_0,
PROP_MARKUP,
PROP_TEXT,
N_PROPS
};
static void
gtk_source_gutter_renderer_text_clear_cached_sizes (GtkSourceGutterRendererText *text)
{
GtkSourceGutterRendererTextPrivate *priv = gtk_source_gutter_renderer_text_get_instance_private (text);
for (guint i = 0; i < G_N_ELEMENTS (priv->cached_sizes); i++)
{
priv->cached_sizes[i].width = -1;
priv->cached_sizes[i].height = -1;
}
}
static inline void
gtk_source_gutter_renderer_text_get_size (GtkSourceGutterRendererTextPrivate *priv,
PangoLayout *layout,
int text_len,
int *width,
int *height)
{
g_assert (text_len > 0);
if G_UNLIKELY (text_len > G_N_ELEMENTS (priv->cached_sizes) ||
priv->cached_sizes[text_len-1].width == -1)
{
pango_layout_get_pixel_size (layout, width, height);
if (text_len <= G_N_ELEMENTS (priv->cached_sizes))
{
priv->cached_sizes[text_len-1].width = *width;
priv->cached_sizes[text_len-1].height = *height;
}
}
else
{
*width = priv->cached_sizes[text_len-1].width;
*height = priv->cached_sizes[text_len-1].height;
}
}
static void
gtk_source_gutter_renderer_text_begin (GtkSourceGutterRenderer *renderer,
GtkSourceGutterLines *lines)
{
GtkSourceGutterRendererText *text = GTK_SOURCE_GUTTER_RENDERER_TEXT (renderer);
GtkSourceGutterRendererTextPrivate *priv = gtk_source_gutter_renderer_text_get_instance_private (text);
GtkSourceView *view = gtk_source_gutter_renderer_get_view (GTK_SOURCE_GUTTER_RENDERER (renderer));
GtkTextBuffer *buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (view));
GdkRGBA current;
GTK_SOURCE_GUTTER_RENDERER_CLASS (gtk_source_gutter_renderer_text_parent_class)->begin (renderer, lines);
priv->has_selection = gtk_text_buffer_get_has_selection (buffer);
g_clear_object (&priv->cached_layout);
priv->cached_layout = gtk_widget_create_pango_layout (GTK_WIDGET (renderer), NULL);
if (_gtk_source_view_get_current_line_number_color (view, ¤t))
{
priv->current_line_color = pango_attr_foreground_new (current.red * 65535,
current.green * 65535,
current.blue * 65535);
}
if (_gtk_source_view_get_current_line_number_bold (view))
{
priv->current_line_bold = pango_attr_weight_new (PANGO_WEIGHT_BOLD);
}
gtk_source_gutter_renderer_text_clear_cached_sizes (text);
}
static void
gtk_source_gutter_renderer_text_snapshot_line (GtkSourceGutterRenderer *renderer,
GtkSnapshot *snapshot,
GtkSourceGutterLines *lines,
guint line)
{
GtkSourceGutterRendererText *text = GTK_SOURCE_GUTTER_RENDERER_TEXT (renderer);
GtkSourceGutterRendererTextPrivate *priv = gtk_source_gutter_renderer_text_get_instance_private (text);
PangoLayout *layout;
gboolean clear_attributes;
float x;
float y;
int width;
int height;
if (priv->text == NULL || priv->text_len == 0)
{
return;
}
layout = priv->cached_layout;
clear_attributes = priv->is_markup;
if (priv->is_markup)
{
pango_layout_set_markup (layout,
priv->text,
priv->text_len);
}
else
{
pango_layout_set_text (layout,
priv->text,
priv->text_len);
}
if (G_UNLIKELY (!priv->has_selection && gtk_source_gutter_lines_is_cursor (lines, line)))
{
PangoAttrList *attrs = pango_layout_get_attributes (layout);
if (attrs == NULL)
{
attrs = pango_attr_list_new ();
pango_layout_set_attributes (layout, attrs);
}
else
{
pango_attr_list_ref (attrs);
}
if (priv->current_line_color)
{
pango_attr_list_insert_before (attrs,
pango_attribute_copy (priv->current_line_color));
clear_attributes = TRUE;
}
if (priv->current_line_bold)
{
pango_attr_list_insert_before (attrs,
pango_attribute_copy (priv->current_line_bold));
clear_attributes = TRUE;
}
pango_attr_list_unref (attrs);
}
gtk_source_gutter_renderer_text_get_size (priv, layout, priv->text_len, &width, &height);
gtk_source_gutter_renderer_align_cell (renderer, line, width, height, &x, &y);
gtk_snapshot_render_layout (snapshot,
gtk_widget_get_style_context (GTK_WIDGET (text)),
ceilf (x),
ceilf (y),
layout);
if (clear_attributes)
{
pango_layout_set_attributes (layout, NULL);
}
}
static void
gtk_source_gutter_renderer_text_end (GtkSourceGutterRenderer *renderer)
{
GtkSourceGutterRendererText *text = GTK_SOURCE_GUTTER_RENDERER_TEXT (renderer);
GtkSourceGutterRendererTextPrivate *priv = gtk_source_gutter_renderer_text_get_instance_private (text);
GTK_SOURCE_GUTTER_RENDERER_CLASS (gtk_source_gutter_renderer_text_parent_class)->end (renderer);
g_clear_pointer (&priv->current_line_bold, pango_attribute_destroy);
g_clear_pointer (&priv->current_line_color, pango_attribute_destroy);
g_clear_object (&priv->cached_layout);
}
static void
measure_text (GtkSourceGutterRendererText *renderer,
const gchar *markup,
const gchar *text,
gint *width,
gint *height)
{
GtkSourceView *view;
PangoLayout *layout;
if (width != NULL)
{
*width = 0;
}
if (height != NULL)
{
*height = 0;
}
view = gtk_source_gutter_renderer_get_view (GTK_SOURCE_GUTTER_RENDERER (renderer));
if (view == NULL)
{
return;
}
layout = gtk_widget_create_pango_layout (GTK_WIDGET (view), NULL);
if (layout == NULL)
{
return;
}
if (markup != NULL)
{
pango_layout_set_markup (layout, markup, -1);
}
else
{
pango_layout_set_text (layout, text, -1);
}
pango_layout_get_pixel_size (layout, width, height);
g_object_unref (layout);
}
/**
* gtk_source_gutter_renderer_text_measure:
* @renderer: a #GtkSourceGutterRendererText.
* @text: the text to measure.
* @width: (out) (optional): location to store the width of the text in pixels,
* or %NULL.
* @height: (out) (optional): location to store the height of the text in
* pixels, or %NULL.
*
* Measures the text provided using the pango layout used by the
* #GtkSourceGutterRendererText.
*/
void
gtk_source_gutter_renderer_text_measure (GtkSourceGutterRendererText *renderer,
const gchar *text,
gint *width,
gint *height)
{
g_return_if_fail (GTK_SOURCE_IS_GUTTER_RENDERER_TEXT (renderer));
g_return_if_fail (text != NULL);
measure_text (renderer, NULL, text, width, height);
}
/**
* gtk_source_gutter_renderer_text_measure_markup:
* @renderer: a #GtkSourceGutterRendererText.
* @markup: the pango markup to measure.
* @width: (out) (optional): location to store the width of the text in pixels,
* or %NULL.
* @height: (out) (optional): location to store the height of the text in
* pixels, or %NULL.
*
* Measures the pango markup provided using the pango layout used by the
* #GtkSourceGutterRendererText.
*/
void
gtk_source_gutter_renderer_text_measure_markup (GtkSourceGutterRendererText *renderer,
const gchar *markup,
gint *width,
gint *height)
{
g_return_if_fail (GTK_SOURCE_IS_GUTTER_RENDERER_TEXT (renderer));
g_return_if_fail (markup != NULL);
measure_text (renderer, markup, NULL, width, height);
}
static void
gtk_source_gutter_renderer_text_real_measure (GtkWidget *widget,
GtkOrientation orientation,
int for_size,
int *minimum,
int *natural,
int *minimum_baseline,
int *natural_baseline)
{
GtkSourceGutterRendererText *renderer = GTK_SOURCE_GUTTER_RENDERER_TEXT (widget);
GtkSourceGutterRendererTextPrivate *priv = gtk_source_gutter_renderer_text_get_instance_private (renderer);
*minimum = 0;
*natural = 0;
*minimum_baseline = -1;
*natural_baseline = -1;
if (orientation == GTK_ORIENTATION_HORIZONTAL)
{
gint xpad = gtk_source_gutter_renderer_get_xpad (GTK_SOURCE_GUTTER_RENDERER (renderer));
gint width = 0;
gint height = 0;
if (priv->text != NULL)
{
if (priv->is_markup)
{
measure_text (renderer, priv->text, NULL, &width, &height);
}
else
{
measure_text (renderer, NULL, priv->text, &width, &height);
}
}
*natural = *minimum = width + 2 * xpad;
}
}
static void
gtk_source_gutter_renderer_text_finalize (GObject *object)
{
GtkSourceGutterRendererText *renderer = GTK_SOURCE_GUTTER_RENDERER_TEXT (object);
GtkSourceGutterRendererTextPrivate *priv = gtk_source_gutter_renderer_text_get_instance_private (renderer);
g_clear_pointer (&priv->text, g_free);
g_clear_object (&priv->cached_layout);
G_OBJECT_CLASS (gtk_source_gutter_renderer_text_parent_class)->finalize (object);
}
static void
set_text (GtkSourceGutterRendererText *renderer,
const gchar *text,
gint length,
gboolean is_markup)
{
GtkSourceGutterRendererTextPrivate *priv = gtk_source_gutter_renderer_text_get_instance_private (renderer);
g_free (priv->text);
if (text == NULL)
{
priv->text_len = 0;
priv->text = NULL;
priv->is_markup = FALSE;
}
else
{
priv->text_len = length >= 0 ? length : strlen (text);
priv->text = g_strndup (text, priv->text_len);
priv->is_markup = !!is_markup;
}
}
static void
gtk_source_gutter_renderer_text_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
GtkSourceGutterRendererText *renderer = GTK_SOURCE_GUTTER_RENDERER_TEXT (object);
switch (prop_id)
{
case PROP_MARKUP:
set_text (renderer, g_value_get_string (value), -1, TRUE);
break;
case PROP_TEXT:
set_text (renderer, g_value_get_string (value), -1, FALSE);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gtk_source_gutter_renderer_text_get_property (GObject *object,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
GtkSourceGutterRendererText *renderer = GTK_SOURCE_GUTTER_RENDERER_TEXT (object);
GtkSourceGutterRendererTextPrivate *priv = gtk_source_gutter_renderer_text_get_instance_private (renderer);
switch (prop_id)
{
case PROP_MARKUP:
g_value_set_string (value, priv->is_markup ? priv->text : NULL);
break;
case PROP_TEXT:
g_value_set_string (value, !priv->is_markup ? priv->text : NULL);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
}
static void
gtk_source_gutter_renderer_text_class_init (GtkSourceGutterRendererTextClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass);
GtkSourceGutterRendererClass *renderer_class = GTK_SOURCE_GUTTER_RENDERER_CLASS (klass);
object_class->finalize = gtk_source_gutter_renderer_text_finalize;
object_class->get_property = gtk_source_gutter_renderer_text_get_property;
object_class->set_property = gtk_source_gutter_renderer_text_set_property;
widget_class->measure = gtk_source_gutter_renderer_text_real_measure;
renderer_class->begin = gtk_source_gutter_renderer_text_begin;
renderer_class->end = gtk_source_gutter_renderer_text_end;
renderer_class->snapshot_line = gtk_source_gutter_renderer_text_snapshot_line;
g_object_class_install_property (object_class,
PROP_MARKUP,
g_param_spec_string ("markup",
"Markup",
"The markup",
NULL,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT));
g_object_class_install_property (object_class,
PROP_TEXT,
g_param_spec_string ("text",
"Text",
"The text",
NULL,
G_PARAM_READWRITE | G_PARAM_CONSTRUCT));
}
static void
gtk_source_gutter_renderer_text_init (GtkSourceGutterRendererText *self)
{
GtkSourceGutterRendererTextPrivate *priv = gtk_source_gutter_renderer_text_get_instance_private (self);
priv->is_markup = TRUE;
gtk_source_gutter_renderer_text_clear_cached_sizes (self);
}
/**
* gtk_source_gutter_renderer_text_new:
*
* Create a new #GtkSourceGutterRendererText.
*
* Returns: (transfer full): A #GtkSourceGutterRenderer
*
**/
GtkSourceGutterRenderer *
gtk_source_gutter_renderer_text_new (void)
{
return g_object_new (GTK_SOURCE_TYPE_GUTTER_RENDERER_TEXT, NULL);
}
void
gtk_source_gutter_renderer_text_set_markup (GtkSourceGutterRendererText *renderer,
const gchar *markup,
gint length)
{
g_return_if_fail (GTK_SOURCE_IS_GUTTER_RENDERER_TEXT (renderer));
set_text (renderer, markup, length, TRUE);
}
void
gtk_source_gutter_renderer_text_set_text (GtkSourceGutterRendererText *renderer,
const gchar *text,
gint length)
{
g_return_if_fail (GTK_SOURCE_IS_GUTTER_RENDERER_TEXT (renderer));
set_text (renderer, text, length, FALSE);
}
| lgpl-2.1 |
iocroblab/log4cpp | tests/testPropertyConfig.cpp | 1 | 2618 | // testConfig.cpp : Derived from testPattern.cpp.
//
#include <log4cpp/Portability.hh>
#ifdef WIN32
#include <windows.h>
#endif
#ifdef LOG4CPP_HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <cstdlib>
#include <log4cpp/Category.hh>
#include <log4cpp/Appender.hh>
#include <log4cpp/OstreamAppender.hh>
#include <log4cpp/FileAppender.hh>
#include <log4cpp/Layout.hh>
#include <log4cpp/BasicLayout.hh>
#include <log4cpp/Priority.hh>
#include <log4cpp/NDC.hh>
#include <log4cpp/PatternLayout.hh>
#include <log4cpp/PropertyConfigurator.hh>
double calcPi()
{
double denominator = 3.0;
double retVal = 4.0;
long i;
for (i = 0; i < 50000000l; i++)
{
retVal = retVal - (4.0 / denominator);
denominator += 2.0;
retVal = retVal + (4.0 /denominator);
denominator += 2.0;
}
return retVal;
}
int main(int argc, char* argv[])
{
try {
/* looking for the init file in $srcdir is a requirement of
automake's distcheck target.
*/
char* srcdir = std::getenv("srcdir");
std::string initFileName;
if (srcdir == NULL) {
initFileName = "./testConfig.log4cpp.properties";
}
else {
initFileName = std::string(srcdir) + "/testConfig.log4cpp.properties";
}
log4cpp::PropertyConfigurator::configure(initFileName);
} catch(log4cpp::ConfigureFailure& f) {
std::cout << "Configure Problem " << f.what() << std::endl;
return -1;
}
log4cpp::Category& root = log4cpp::Category::getRoot();
log4cpp::Category& sub1 =
log4cpp::Category::getInstance(std::string("sub1"));
log4cpp::Category& sub2 =
log4cpp::Category::getInstance(std::string("sub1.sub2"));
log4cpp::Category& sub3 =
log4cpp::Category::getInstance(std::string("sub1.sub2.sub3"));
root.error("root error");
root.warn("root warn");
sub1.error("sub1 error");
sub1.warn("sub1 warn");
calcPi();
sub2.error("sub2 error");
sub2.warn("sub2 warn");
root.error("root error");
root.warn("root warn");
sub1.error("sub1 error");
sub1.warn("sub1 warn");
#ifdef WIN32
Sleep(3000);
#else
sleep(3);
#endif
sub2.error("sub2 error");
sub2.warn("sub2 warn");
sub2.error("%s %s %d", "test", "vform", 123);
sub2.warnStream() << "streamed warn";
sub2 << log4cpp::Priority::WARN << "warn2.." << "..warn3..value=" << 0
<< log4cpp::eol << "..warn4";
sub3 << log4cpp::Priority::INFO << "Very long config string follows";
log4cpp::Category::shutdown();
return 0;
}
| lgpl-2.1 |
amigadave/flatpak | app/flatpak-builtins-document-list.c | 1 | 4589 | /*
* Copyright © 2016 Red Hat, Inc
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
* Authors:
* Matthias Clasen <mclasen@redhat.com>
*/
#include "config.h"
#include <locale.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <glib/gi18n.h>
#include "libgsystem.h"
#include "libglnx/libglnx.h"
#include "document-portal/xdp-dbus.h"
#include "flatpak-builtins.h"
#include "flatpak-utils.h"
#include "flatpak-run.h"
static GOptionEntry options[] = {
{ NULL }
};
gboolean
flatpak_builtin_document_list (int argc, char **argv,
GCancellable *cancellable,
GError **error)
{
g_autoptr(GOptionContext) context = NULL;
g_autoptr(GDBusConnection) session_bus = NULL;
XdpDbusDocuments *documents;
g_autoptr(GVariant) apps = NULL;
g_autoptr(GVariantIter) iter = NULL;
const char *app_id;
const char *id;
const char *path;
context = g_option_context_new (_("[APPID] - List exported files"));
g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
if (!flatpak_option_context_parse (context, options, &argc, &argv,
FLATPAK_BUILTIN_FLAG_NO_DIR,
NULL, cancellable, error))
return FALSE;
if (argc < 2)
app_id = "";
else
app_id = argv[1];
session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, error);
if (session_bus == NULL)
return FALSE;
documents = xdp_dbus_documents_proxy_new_sync (session_bus, 0,
"org.freedesktop.portal.Documents",
"/org/freedesktop/portal/documents",
NULL, error);
if (documents == NULL)
return FALSE;
if (!xdp_dbus_documents_call_list_sync (documents, app_id, &apps, NULL, error))
return FALSE;
iter = g_variant_iter_new (apps);
while (g_variant_iter_next (iter, "{&s^&ay}", &id, &path))
g_print ("%s\t%s\n", id, path);
return TRUE;
}
gboolean
flatpak_complete_document_list (FlatpakCompletion *completion)
{
g_autoptr(GOptionContext) context = NULL;
g_autoptr(FlatpakDir) user_dir = NULL;
g_autoptr(FlatpakDir) system_dir = NULL;
g_autoptr(GError) error = NULL;
int i;
context = g_option_context_new ("");
if (!flatpak_option_context_parse (context, options, &completion->argc, &completion->argv,
FLATPAK_BUILTIN_FLAG_NO_DIR, NULL, NULL, NULL))
return FALSE;
switch (completion->argc)
{
case 0:
case 1: /* APPID */
flatpak_complete_options (completion, global_entries);
flatpak_complete_options (completion, options);
user_dir = flatpak_dir_get_user ();
{
g_auto(GStrv) refs = flatpak_dir_find_installed_refs (user_dir, NULL, NULL, NULL,
TRUE, FALSE, &error);
if (refs == NULL)
flatpak_completion_debug ("find local refs error: %s", error->message);
for (i = 0; refs != NULL && refs[i] != NULL; i++)
{
g_auto(GStrv) parts = flatpak_decompose_ref (refs[i], NULL);
if (parts)
flatpak_complete_word (completion, "%s ", parts[1]);
}
}
system_dir = flatpak_dir_get_user ();
{
g_auto(GStrv) refs = flatpak_dir_find_installed_refs (system_dir, NULL, NULL, NULL,
TRUE, FALSE, &error);
if (refs == NULL)
flatpak_completion_debug ("find local refs error: %s", error->message);
for (i = 0; refs != NULL && refs[i] != NULL; i++)
{
g_auto(GStrv) parts = flatpak_decompose_ref (refs[i], NULL);
if (parts)
flatpak_complete_word (completion, "%s ", parts[1]);
}
}
break;
}
return TRUE;
}
| lgpl-2.1 |
wbhart/flint2 | nmod_poly/taylor_shift_convolution.c | 2 | 1952 | /*
Copyright (C) 2012 Fredrik Johansson
This file is part of FLINT.
FLINT is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. See <https://www.gnu.org/licenses/>.
*/
#include "flint.h"
#include "nmod_vec.h"
#include "nmod_poly.h"
#include "ulong_extras.h"
void
_nmod_poly_taylor_shift_convolution(mp_ptr p, mp_limb_t c, slong len, nmod_t mod)
{
slong i, n = len - 1;
mp_limb_t f, d;
mp_ptr t, u;
if (c == 0 || len <= 1)
return;
t = _nmod_vec_init(len);
u = _nmod_vec_init(len);
f = 1;
for (i = 2; i <= n; i++)
{
f = n_mulmod2_preinv(f, i, mod.n, mod.ninv);
p[i] = n_mulmod2_preinv(p[i], f, mod.n, mod.ninv);
}
_nmod_poly_reverse(p, p, len, len);
t[n] = 1;
for (i = n; i > 0; i--)
t[i - 1] = n_mulmod2_preinv(t[i], i, mod.n, mod.ninv);
if (c == mod.n - 1)
{
for (i = 1; i <= n; i += 2)
t[i] = nmod_neg(t[i], mod);
}
else if (c != 1)
{
d = c;
for (i = 1; i <= n; i++)
{
t[i] = n_mulmod2_preinv(t[i], d, mod.n, mod.ninv);
d = n_mulmod2_preinv(d, c, mod.n, mod.ninv);
}
}
_nmod_poly_mullow(u, p, len, t, len, len, mod);
f = n_mulmod2_preinv(f, f, mod.n, mod.ninv);
f = n_invmod(f, mod.n);
for (i = n; i >= 0; i--)
{
p[i] = n_mulmod2_preinv(u[n - i], f, mod.n, mod.ninv);
f = n_mulmod2_preinv(f, (i == 0) ? 1 : i, mod.n, mod.ninv);
}
_nmod_vec_clear(t);
_nmod_vec_clear(u);
}
void
nmod_poly_taylor_shift_convolution(nmod_poly_t g, const nmod_poly_t f,
mp_limb_t c)
{
if (f != g)
nmod_poly_set(g, f);
_nmod_poly_taylor_shift_convolution(g->coeffs, c, g->length, g->mod);
}
| lgpl-2.1 |
fredrik-johansson/flint2 | fmpz_mpoly/test/t-compose_fmpz_poly.c | 2 | 10858 | /*
Copyright (C) 2018 Daniel Schultz
This file is part of FLINT.
FLINT is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. See <https://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdlib.h>
#include "fmpz_mpoly.h"
int
main(void)
{
slong i, v;
FLINT_TEST_INIT(state);
flint_printf("compose_fmpz_poly....");
fflush(stdout);
{
fmpz_poly_t A;
fmpz_mpoly_t B;
fmpz_poly_struct * Cp[3];
fmpz_poly_struct C[3];
fmpz_mpoly_ctx_t ctxB;
fmpz_mpoly_ctx_init(ctxB, 3, ORD_LEX);
fmpz_mpoly_init(B, ctxB);
fmpz_poly_init(A);
for (i = 0; i < 3; i++)
{
Cp[i] = C + i;
fmpz_poly_init(C + i);
}
fmpz_mpoly_set_str_pretty(B,
"1 + x1*x2^2 + x2^9999999999999999999999999*x3^9", NULL, ctxB);
fmpz_poly_zero(C + 0);
fmpz_poly_zero(C + 1);
fmpz_poly_zero(C + 2);
fmpz_poly_set_coeff_si(C + 0, 1, 1);
fmpz_poly_set_coeff_si(C + 1, 2, 2);
fmpz_poly_set_coeff_si(C + 2, 3, 3);
if (fmpz_mpoly_compose_fmpz_poly(A, B, Cp, ctxB))
{
printf("FAIL\n");
flint_printf("Check non-example 1\n", i);
fflush(stdout);
flint_abort();
}
fmpz_poly_zero(C + 0);
fmpz_poly_zero(C + 1);
fmpz_poly_zero(C + 2);
fmpz_poly_set_coeff_si(C + 0, 0, 1);
fmpz_poly_set_coeff_si(C + 1, 0, 1);
fmpz_poly_set_coeff_si(C + 2, 0, 1);
if (!fmpz_mpoly_compose_fmpz_poly(A, B, Cp, ctxB))
{
printf("FAIL\n");
flint_printf("Check example 2\n", i);
fflush(stdout);
flint_abort();
}
fmpz_poly_zero(C + 0);
fmpz_poly_set_coeff_si(C + 0, 0, 3);
if (!fmpz_poly_equal(A, C + 0))
{
printf("FAIL\n");
flint_printf("Check example 2 equality\n", i);
fflush(stdout);
flint_abort();
}
fmpz_mpoly_clear(B, ctxB);
fmpz_poly_clear(A);
for (i = 0; i < 3; i++)
fmpz_poly_clear(C + i);
fmpz_mpoly_ctx_clear(ctxB);
}
/* Check composition and evalall commute */
for (i = 0; i < 50*flint_test_multiplier(); i++)
{
fmpz_mpoly_ctx_t ctx1;
fmpz_mpoly_t f;
fmpz_poly_t g;
fmpz_poly_struct ** vals1;
fmpz_t fe, ge;
fmpz_t vals2;
fmpz ** vals3;
slong nvars1;
slong len1, len2;
slong exp_bound1;
flint_bitcnt_t coeff_bits, coeff_bits2;
fmpz_mpoly_ctx_init_rand(ctx1, state, 10);
nvars1 = ctx1->minfo->nvars;
fmpz_mpoly_init(f, ctx1);
fmpz_poly_init(g);
fmpz_init(fe);
fmpz_init(ge);
len1 = n_randint(state, 50/FLINT_MAX(WORD(1), nvars1) + 1);
len2 = n_randint(state, 40);
exp_bound1 = n_randint(state, 200/FLINT_MAX(WORD(1), nvars1) + 2) + 1;
coeff_bits = n_randint(state, 100) + 1;
coeff_bits2 = n_randint(state, 10) + 1;
fmpz_mpoly_randtest_bound(f, state, len1, coeff_bits, exp_bound1, ctx1);
vals1 = (fmpz_poly_struct **) flint_malloc(nvars1
* sizeof(fmpz_poly_struct *));
for (v = 0; v < nvars1; v++)
{
vals1[v] = (fmpz_poly_struct *) flint_malloc(
sizeof(fmpz_poly_struct));
fmpz_poly_init(vals1[v]);
fmpz_poly_randtest(vals1[v], state, len2, coeff_bits2);
}
fmpz_init(vals2);
fmpz_randbits(vals2, state, 10);
vals3 = (fmpz **) flint_malloc(nvars1*sizeof(fmpz *));
for (v = 0; v < nvars1; v++)
{
vals3[v] = (fmpz *) flint_malloc(sizeof(fmpz));
fmpz_init(vals3[v]);
fmpz_poly_evaluate_fmpz(vals3[v], vals1[v], vals2);
}
if (fmpz_mpoly_total_degree_si(f, ctx1) < 50)
{
if (!fmpz_mpoly_compose_fmpz_poly(g, f, vals1, ctx1) ||
!fmpz_mpoly_evaluate_all_fmpz(fe, f, vals3, ctx1))
{
printf("FAIL\n");
flint_printf("Check evaluation success\ni: %wd\n", i);
fflush(stdout);
flint_abort();
}
fmpz_poly_evaluate_fmpz(ge, g, vals2);
if (!fmpz_equal(fe, ge))
{
printf("FAIL\n");
flint_printf("Check composition and evalall commute\ni: %wd\n", i);
fflush(stdout);
flint_abort();
}
}
for (v = 0; v < nvars1; v++)
{
fmpz_clear(vals3[v]);
flint_free(vals3[v]);
}
flint_free(vals3);
fmpz_clear(vals2);
for (v = 0; v < nvars1; v++)
{
fmpz_poly_clear(vals1[v]);
flint_free(vals1[v]);
}
flint_free(vals1);
fmpz_clear(fe);
fmpz_clear(ge);
fmpz_mpoly_clear(f, ctx1);
fmpz_poly_clear(g);
fmpz_mpoly_ctx_clear(ctx1);
}
/* Check composition with constants matches evalall */
for (i = 0; i < 50*flint_test_multiplier(); i++)
{
fmpz_mpoly_ctx_t ctx1;
fmpz_mpoly_t f;
fmpz_poly_t g;
fmpz_poly_struct ** vals1;
fmpz_t fe;
fmpz ** vals3;
slong nvars1;
slong len1;
slong exp_bound1;
flint_bitcnt_t coeff_bits;
fmpz_mpoly_ctx_init_rand(ctx1, state, 10);
nvars1 = ctx1->minfo->nvars;
fmpz_mpoly_init(f, ctx1);
fmpz_poly_init(g);
fmpz_init(fe);
len1 = n_randint(state, 50);
exp_bound1 = n_randint(state, 200/FLINT_MAX(WORD(1), nvars1) + 2) + 1;
coeff_bits = n_randint(state, 100) + 1;
fmpz_mpoly_randtest_bound(f, state, len1, coeff_bits, exp_bound1, ctx1);
vals3 = (fmpz **) flint_malloc(nvars1*sizeof(fmpz *));
for (v = 0; v < nvars1; v++)
{
vals3[v] = (fmpz *) flint_malloc(sizeof(fmpz));
fmpz_init(vals3[v]);
fmpz_randtest(vals3[v], state, 20);
}
vals1 = (fmpz_poly_struct **) flint_malloc(nvars1
* sizeof(fmpz_poly_struct *));
for (v = 0; v < nvars1; v++)
{
vals1[v] = (fmpz_poly_struct *) flint_malloc(
sizeof(fmpz_poly_struct));
fmpz_poly_init(vals1[v]);
fmpz_poly_set_fmpz(vals1[v], vals3[v]);
}
if (fmpz_mpoly_total_degree_si(f, ctx1) < 50)
{
fmpz_poly_t t;
if (!fmpz_mpoly_compose_fmpz_poly(g, f, vals1, ctx1) ||
!fmpz_mpoly_evaluate_all_fmpz(fe, f, vals3, ctx1))
{
printf("FAIL\n");
flint_printf("Check evaluation success\ni: %wd\n", i);
fflush(stdout);
flint_abort();
}
fmpz_poly_init(t);
fmpz_poly_set_fmpz(t, fe);
if (!fmpz_poly_equal(g, t))
{
printf("FAIL\n");
flint_printf("Check composition with constants matches evalall\ni: %wd\n", i);
fflush(stdout);
flint_abort();
}
fmpz_poly_clear(t);
}
for (v = 0; v < nvars1; v++)
{
fmpz_clear(vals3[v]);
flint_free(vals3[v]);
}
flint_free(vals3);
for (v = 0; v < nvars1; v++)
{
fmpz_poly_clear(vals1[v]);
flint_free(vals1[v]);
}
flint_free(vals1);
fmpz_clear(fe);
fmpz_mpoly_clear(f, ctx1);
fmpz_poly_clear(g);
fmpz_mpoly_ctx_clear(ctx1);
}
/* Check multiprecision composition with constants matches evalall */
for (i = 0; i < 50*flint_test_multiplier(); i++)
{
fmpz_mpoly_ctx_t ctx1;
fmpz_mpoly_t f;
fmpz_poly_t g;
fmpz_poly_struct ** vals1;
fmpz_t fe;
fmpz ** vals3;
slong nvars1;
slong len1;
flint_bitcnt_t exp_bits;
flint_bitcnt_t coeff_bits;
fmpz_mpoly_ctx_init_rand(ctx1, state, 10);
nvars1 = ctx1->minfo->nvars;
fmpz_mpoly_init(f, ctx1);
fmpz_poly_init(g);
fmpz_init(fe);
len1 = n_randint(state, 50);
exp_bits = n_randint(state, 200) + 1;
coeff_bits = n_randint(state, 100) + 1;
fmpz_mpoly_randtest_bits(f, state, len1, coeff_bits, exp_bits, ctx1);
vals3 = (fmpz **) flint_malloc(nvars1*sizeof(fmpz *));
for (v = 0; v < nvars1; v++)
{
vals3[v] = (fmpz *) flint_malloc(sizeof(fmpz));
fmpz_init(vals3[v]);
fmpz_set_si(vals3[v], n_randint(state, UWORD(3)) - WORD(1));
}
vals1 = (fmpz_poly_struct **) flint_malloc(nvars1
* sizeof(fmpz_poly_struct *));
for (v = 0; v < nvars1; v++)
{
vals1[v] = (fmpz_poly_struct *) flint_malloc(
sizeof(fmpz_poly_struct));
fmpz_poly_init(vals1[v]);
fmpz_poly_set_fmpz(vals1[v], vals3[v]);
}
{
fmpz_poly_t t;
if (!fmpz_mpoly_compose_fmpz_poly(g, f, vals1, ctx1) ||
!fmpz_mpoly_evaluate_all_fmpz(fe, f, vals3, ctx1))
{
printf("FAIL\n");
flint_printf("Check evaluation success\ni: %wd\n", i);
fflush(stdout);
flint_abort();
}
fmpz_poly_init(t);
fmpz_poly_set_fmpz(t, fe);
if (!fmpz_poly_equal(g, t))
{
printf("FAIL\n");
flint_printf("Check multiprecision composition with constants matches evalall\ni: %wd\n", i);
fflush(stdout);
flint_abort();
}
fmpz_poly_clear(t);
}
for (v = 0; v < nvars1; v++)
{
fmpz_clear(vals3[v]);
flint_free(vals3[v]);
}
flint_free(vals3);
for (v = 0; v < nvars1; v++)
{
fmpz_poly_clear(vals1[v]);
flint_free(vals1[v]);
}
flint_free(vals1);
fmpz_clear(fe);
fmpz_mpoly_clear(f, ctx1);
fmpz_poly_clear(g);
fmpz_mpoly_ctx_clear(ctx1);
}
printf("PASS\n");
FLINT_TEST_CLEANUP(state);
return 0;
}
| lgpl-2.1 |
steve-the-bayesian/BOOM | Models/Hierarchical/HierarchicalZeroInflatedPoissonModel.cpp | 2 | 6919 | // Copyright 2018 Google LLC. All Rights Reserved.
/*
Copyright (C) 2005-2012 Steven L. Scott
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "Models/Hierarchical/HierarchicalZeroInflatedPoissonModel.hpp"
#include "cpputil/report_error.hpp"
#include "distributions.hpp"
namespace BOOM {
ZeroInflatedPoissonData::ZeroInflatedPoissonData(
double nzero_trials, double npos_trials, double total_number_of_events)
: suf_(nzero_trials, npos_trials, total_number_of_events) {}
ZeroInflatedPoissonData::ZeroInflatedPoissonData(
const ZeroInflatedPoissonSuf &suf)
: suf_(suf) {}
ZeroInflatedPoissonData::ZeroInflatedPoissonData(
const ZeroInflatedPoissonData &rhs)
: Data(rhs), suf_(rhs.suf_) {}
ZeroInflatedPoissonData *ZeroInflatedPoissonData::clone() const {
return new ZeroInflatedPoissonData(*this);
}
std::ostream &ZeroInflatedPoissonData::display(std::ostream &out) const {
return suf_.print(out);
}
const ZeroInflatedPoissonSuf &ZeroInflatedPoissonData::suf() const {
return suf_;
}
typedef HierarchicalZeroInflatedPoissonModel HZIP;
HZIP::HierarchicalZeroInflatedPoissonModel(double lambda_prior_guess,
double lambda_prior_sample_size,
double zero_prob_prior_guess,
double zero_prob_prior_sample_size)
: prior_for_lambda_(
new GammaModel(lambda_prior_guess * lambda_prior_sample_size,
lambda_prior_sample_size)),
prior_for_zero_probability_(new BetaModel(
zero_prob_prior_guess * zero_prob_prior_sample_size,
(1 - zero_prob_prior_guess) * zero_prob_prior_sample_size)) {
initialize();
}
HZIP::HierarchicalZeroInflatedPoissonModel(
const Ptr<GammaModel> &prior_for_lambda,
const Ptr<BetaModel> &prior_for_zero_probability)
: prior_for_lambda_(prior_for_lambda),
prior_for_zero_probability_(prior_for_zero_probability) {
initialize();
}
HZIP::HierarchicalZeroInflatedPoissonModel(
const BOOM::Vector &trials, const BOOM::Vector &events,
const BOOM::Vector &number_of_zeros)
: prior_for_lambda_(new GammaModel(1.0, 1.0)),
prior_for_zero_probability_(new BetaModel(1.0, 1.0)) {
initialize();
if (trials.size() != events.size() ||
trials.size() != number_of_zeros.size()) {
report_error(
"The trials, events, and number_of_zeros arguments must all "
"have the same size in the "
"HierarchicalZeroInflatedPoissonModel constructor.");
}
int ngroups = trials.size();
for (int i = 0; i < ngroups; ++i) {
ZeroInflatedPoissonModel *model = new ZeroInflatedPoissonModel;
model->set_sufficient_statistics(ZeroInflatedPoissonSuf(
number_of_zeros[i], trials[i] - number_of_zeros[i], events[i]));
add_data_level_model(model);
}
}
HZIP::HierarchicalZeroInflatedPoissonModel(
const HierarchicalZeroInflatedPoissonModel &rhs)
: Model(rhs),
ParamPolicy(rhs),
PriorPolicy(rhs),
prior_for_lambda_(rhs.prior_for_lambda_->clone()),
prior_for_zero_probability_(rhs.prior_for_zero_probability_->clone()) {
initialize();
for (int i = 0; i < rhs.data_level_models_.size(); ++i) {
add_data_level_model(rhs.data_level_models_[i]->clone());
}
}
HierarchicalZeroInflatedPoissonModel *HZIP::clone() const {
return new HierarchicalZeroInflatedPoissonModel(*this);
}
void HZIP::add_data_level_model(const Ptr<ZeroInflatedPoissonModel> &model) {
ParamPolicy::add_model(model);
data_level_models_.push_back(model);
}
void HZIP::clear_data() {
data_level_models_.clear();
ParamPolicy::clear();
initialize();
}
void HZIP::clear_client_data() {
for (int i = 0; i < data_level_models_.size(); ++i) {
data_level_models_[i]->clear_data();
}
}
void HZIP::clear_methods() {
prior_for_lambda_->clear_methods();
prior_for_zero_probability_->clear_methods();
for (int i = 0; i < data_level_models_.size(); ++i) {
data_level_models_[i]->clear_methods();
}
PriorPolicy::clear_methods();
}
void HZIP::combine_data(const Model &rhs, bool just_suf) {
const HZIP &rhs_model(dynamic_cast<const HZIP &>(rhs));
for (int i = 0; i < rhs_model.number_of_groups(); ++i) {
add_data_level_model(rhs_model.data_level_models_[i]);
}
}
void HZIP::add_data(const Ptr<Data> &dp) {
NEW(ZeroInflatedPoissonModel, model)();
model->set_sufficient_statistics(
dp.dcast<ZeroInflatedPoissonData>()->suf());
add_data_level_model(model);
}
int HZIP::number_of_groups() const { return data_level_models_.size(); }
ZeroInflatedPoissonModel *HZIP::data_model(int which_group) {
return data_level_models_[which_group].get();
}
GammaModel *HZIP::prior_for_poisson_mean() { return prior_for_lambda_.get(); }
BetaModel *HZIP::prior_for_zero_probability() {
return prior_for_zero_probability_.get();
}
double HZIP::poisson_prior_mean() const {
return prior_for_lambda_->alpha() / prior_for_lambda_->beta();
}
double HZIP::poisson_prior_sample_size() const {
return prior_for_lambda_->beta();
}
double HZIP::zero_probability_prior_mean() const {
return prior_for_zero_probability_->mean();
}
double HZIP::zero_probability_prior_sample_size() const {
return prior_for_zero_probability_->sample_size();
}
ZeroInflatedPoissonData HZIP::sim(int64_t n) const {
const double lambda = prior_for_lambda_->sim();
const double zero_probability = prior_for_zero_probability_->sim();
double number_of_zero_trials = rbinom(n, zero_probability);
double number_of_positive_trials = n - number_of_zero_trials;
double number_of_events = rpois(number_of_positive_trials * lambda);
return ZeroInflatedPoissonData(number_of_zero_trials,
number_of_positive_trials, number_of_events);
}
void HZIP::initialize() {
ParamPolicy::add_model(prior_for_lambda_);
ParamPolicy::add_model(prior_for_zero_probability_);
}
} // namespace BOOM
| lgpl-2.1 |
philippreston/OpenMAMA | mamda/c_cpp/src/examples/mamdalisten.cpp | 2 | 6119 | /* $Id$
*
* OpenMAMA: The open middleware agnostic messaging API
* Copyright (C) 2011 NYSE Technologies, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include <mama/mamacpp.h>
#include <mamda/MamdaSubscription.h>
#include <mamda/MamdaMsgListener.h>
#include <mamda/MamdaErrorListener.h>
#include <mamda/MamdaQualityListener.h>
#include <iostream>
#include <stdexcept>
#include <vector>
#include <stdio.h>
#include "parsecmd.h"
#include "mama/MamaQueueGroup.h"
#include "dictrequester.h"
using std::exception;
using std::endl;
using std::vector;
using std::cerr;
using std::cout;
using namespace Wombat;
void usage (int exitStatus);
class ListenerCallback : public MamdaMsgListener
, public MamdaErrorListener
, public MamdaQualityListener
, public MamaMsgFieldIterator
{
public:
ListenerCallback ():
mDictionary (NULL) {}
~ListenerCallback () {}
void onMsg (
MamdaSubscription* subscription,
const MamaMsg& msg,
short msgType);
void onError (
MamdaSubscription* subscription,
MamdaErrorSeverity severity,
MamdaErrorCode errorCode,
const char* errorStr);
void onQuality (
MamdaSubscription* subscription,
mamaQuality quality);
void onField (
const MamaMsg& msg,
const MamaMsgField& field,
void* closure);
void setDictionary (
const MamaDictionary* dictionary);
private:
const MamaDictionary* mDictionary;
};
int main (int argc, const char **argv)
{
setbuf (stdout, NULL);
try
{
CommonCommandLineParser cmdLine (argc, argv);
// Initialise the MAMA API
mamaBridge bridge = cmdLine.getBridge();
Mama::open ();
const vector<const char*>& symbolList = cmdLine.getSymbolList ();
MamaSource* source = cmdLine.getSource();
MamaQueueGroup queues (cmdLine.getNumThreads(), bridge);
ListenerCallback ticker;
DictRequester dictRequester (bridge);
dictRequester.requestDictionary (cmdLine.getDictSource());
ticker.setDictionary (dictRequester.getDictionary ());
const char* symbolMapFile = cmdLine.getSymbolMapFile ();
if (symbolMapFile)
{
MamaSymbolMapFile* aMap = new MamaSymbolMapFile;
if (MAMA_STATUS_OK == aMap->load (symbolMapFile))
{
source->getTransport()->setSymbolMap (aMap);
}
}
for (vector<const char*>::const_iterator i = symbolList.begin ();
i != symbolList.end ();
++i)
{
const char* symbol = *i;
MamdaSubscription* aSubscription = new MamdaSubscription;
aSubscription->addMsgListener (&ticker);
aSubscription->addQualityListener (&ticker);
aSubscription->addErrorListener (&ticker);
if (cmdLine.getSnapshot())
aSubscription->setServiceLevel (MAMA_SERVICE_LEVEL_SNAPSHOT);
aSubscription->create (queues.getNextQueue(), source, symbol);
}
Mama::start(bridge);
}
catch (MamaStatus &e)
{
// This exception can be thrown from Mama.open (),
// Mama::createTransport (transportName) and from
// MamdaSubscription constructor when entitlements is enabled.
cerr << "Exception in main (): " << e.toString () << endl;
exit (1);
}
catch (exception &ex)
{
cerr << "Exception in main (): " << ex.what () << endl;
exit (1);
}
catch (...)
{
cerr << "Unknown Exception in main ()." << endl;
exit (1);
}
}
void usage (int exitStatus)
{
std::cerr << "Usage: mamdalisten [-tport] tport_name [-m] middleware [-S] source [-s] symbol [options] \n";
std::cerr << "Options:" << std::endl;
std::cerr << " -1 Create snapshot subscriptions" << std::endl;
exit (exitStatus);
}
void ListenerCallback::onMsg (
MamdaSubscription* subscription,
const MamaMsg& msg,
short msgType)
{
cout << "Update (" << subscription->getSymbol () << "): \n";
msg.iterateFields (*this, mDictionary, NULL);
flush (cout);
}
void ListenerCallback::onError (
MamdaSubscription* subscription,
MamdaErrorSeverity severity,
MamdaErrorCode errorCode,
const char* errorStr)
{
cout << "Error (" << subscription->getSymbol () << ")" << endl;
flush (cout);
}
void ListenerCallback::onQuality (
MamdaSubscription* subscription,
mamaQuality quality)
{
cout << "Quality (" << subscription->getSymbol () << "): " << quality << endl;
flush (cout);
}
void ListenerCallback::onField (
const MamaMsg& msg,
const MamaMsgField& field,
void* closure)
{
char fieldValueStr[256];
const MamaFieldDescriptor* desc = field.getDescriptor ();
if (!desc) return;
msg.getFieldAsString (desc, fieldValueStr,256);
printf ("%20s | %3d | ", desc->getName (), desc->getFid ());
printf ("%20s | %s\n", desc->getTypeName (), fieldValueStr);
flush (cout);
}
void ListenerCallback::setDictionary (
const MamaDictionary* dictionary)
{
mDictionary = dictionary;
}
| lgpl-2.1 |
coin-or/qpOASES | interfaces/octave/qpOASES.cpp | 3 | 15631 | /*
* This file is part of qpOASES.
*
* qpOASES -- An Implementation of the Online Active Set Strategy.
* Copyright (C) 2007-2017 by Hans Joachim Ferreau, Andreas Potschka,
* Christian Kirches et al. All rights reserved.
*
* qpOASES is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* qpOASES is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with qpOASES; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
/**
* \file interfaces/octave/qpOASES.cpp
* \author Hans Joachim Ferreau, Alexander Buchner, Andreas Potschka
* \version 3.2
* \date 2007-2017
*
* Interface for Matlab(R) that enables to call qpOASES as a MEX function.
*
*/
#include <qpOASES.hpp>
USING_NAMESPACE_QPOASES
#include "qpOASES_octave_utils.hpp"
/** initialise handle counter of QPInstance class */
int_t QPInstance::s_nexthandle = 1;
/** global pointer to QP objects */
static std::vector<QPInstance *> g_instances;
#include "qpOASES_octave_utils.cpp"
/*
* Q P r o b l e m _ q p O A S E S
*/
int_t QProblem_qpOASES( int_t nV, int_t nC, HessianType hessianType, int_t nP,
SymmetricMatrix* H, double* g, Matrix* A,
double* lb, double* ub,
double* lbA, double* ubA,
int_t nWSRin, real_t maxCpuTimeIn,
const double* const x0, Options* options,
int_t nOutputs, mxArray* plhs[],
const double* const guessedBounds, const double* const guessedConstraints,
const double* const _R
)
{
int_t nWSRout;
real_t maxCpuTimeOut;
/* 1) Setup initial QP. */
QProblem QP( nV,nC,hessianType );
QP.setOptions( *options );
/* 2) Solve initial QP. */
returnValue returnvalue;
Bounds bounds(nV);
Constraints constraints(nC);
if (guessedBounds != 0) {
for (int_t i = 0; i < nV; i++) {
if ( isEqual(guessedBounds[i],-1.0) == BT_TRUE ) {
bounds.setupBound(i, ST_LOWER);
} else if ( isEqual(guessedBounds[i],1.0) == BT_TRUE ) {
bounds.setupBound(i, ST_UPPER);
} else if ( isEqual(guessedBounds[i],0.0) == BT_TRUE ) {
bounds.setupBound(i, ST_INACTIVE);
} else {
char msg[MAX_STRING_LENGTH];
snprintf(msg, MAX_STRING_LENGTH,
"ERROR (qpOASES): Only {-1, 0, 1} allowed for status of bounds!");
myMexErrMsgTxt(msg);
return -1;
}
}
}
if (guessedConstraints != 0) {
for (int_t i = 0; i < nC; i++) {
if ( isEqual(guessedConstraints[i],-1.0) == BT_TRUE ) {
constraints.setupConstraint(i, ST_LOWER);
} else if ( isEqual(guessedConstraints[i],1.0) == BT_TRUE ) {
constraints.setupConstraint(i, ST_UPPER);
} else if ( isEqual(guessedConstraints[i],0.0) == BT_TRUE ) {
constraints.setupConstraint(i, ST_INACTIVE);
} else {
char msg[MAX_STRING_LENGTH];
snprintf(msg, MAX_STRING_LENGTH,
"ERROR (qpOASES): Only {-1, 0, 1} allowed for status of constraints!");
myMexErrMsgTxt(msg);
return -1;
}
}
}
nWSRout = nWSRin;
maxCpuTimeOut = (maxCpuTimeIn >= 0.0) ? maxCpuTimeIn : INFTY;
returnvalue = QP.init( H,g,A,lb,ub,lbA,ubA,
nWSRout,&maxCpuTimeOut,
x0,0,
(guessedBounds != 0) ? &bounds : 0, (guessedConstraints != 0) ? &constraints : 0,
_R
);
/* 3) Solve remaining QPs and assign lhs arguments. */
/* Set up pointers to the current QP vectors */
real_t* g_current = g;
real_t* lb_current = lb;
real_t* ub_current = ub;
real_t* lbA_current = lbA;
real_t* ubA_current = ubA;
/* Loop through QP sequence. */
for ( int_t k=0; k<nP; ++k )
{
if ( k > 0 )
{
/* update pointers to the current QP vectors */
g_current = &(g[k*nV]);
if ( lb != 0 )
lb_current = &(lb[k*nV]);
if ( ub != 0 )
ub_current = &(ub[k*nV]);
if ( lbA != 0 )
lbA_current = &(lbA[k*nC]);
if ( ubA != 0 )
ubA_current = &(ubA[k*nC]);
nWSRout = nWSRin;
maxCpuTimeOut = (maxCpuTimeIn >= 0.0) ? maxCpuTimeIn : INFTY;
returnvalue = QP.hotstart( g_current,lb_current,ub_current,lbA_current,ubA_current, nWSRout,&maxCpuTimeOut );
}
/* write results into output vectors */
obtainOutputs( k,&QP,returnvalue,nWSRout,maxCpuTimeOut,
nOutputs,plhs,nV,nC );
}
//QP.writeQpDataIntoMatFile( "qpDataMat0.mat" );
return 0;
}
/*
* Q P r o b l e m B _ q p O A S E S
*/
int_t QProblemB_qpOASES( int_t nV, HessianType hessianType, int_t nP,
SymmetricMatrix *H, double* g,
double* lb, double* ub,
int_t nWSRin, real_t maxCpuTimeIn,
const double* const x0, Options* options,
int_t nOutputs, mxArray* plhs[],
const double* const guessedBounds,
const double* const _R
)
{
int_t nWSRout;
real_t maxCpuTimeOut;
/* 1) Setup initial QP. */
QProblemB QP( nV,hessianType );
QP.setOptions( *options );
/* 2) Solve initial QP. */
returnValue returnvalue;
Bounds bounds(nV);
if (guessedBounds != 0) {
for (int_t i = 0; i < nV; i++) {
if ( isEqual(guessedBounds[i],-1.0) == BT_TRUE ) {
bounds.setupBound(i, ST_LOWER);
} else if ( isEqual(guessedBounds[i],1.0) == BT_TRUE ) {
bounds.setupBound(i, ST_UPPER);
} else if ( isEqual(guessedBounds[i],0.0) == BT_TRUE ) {
bounds.setupBound(i, ST_INACTIVE);
} else {
char msg[MAX_STRING_LENGTH];
snprintf(msg, MAX_STRING_LENGTH,
"ERROR (qpOASES): Only {-1, 0, 1} allowed for status of bounds!");
myMexErrMsgTxt(msg);
return -1;
}
}
}
nWSRout = nWSRin;
maxCpuTimeOut = (maxCpuTimeIn >= 0.0) ? maxCpuTimeIn : INFTY;
returnvalue = QP.init( H,g,lb,ub,
nWSRout,&maxCpuTimeOut,
x0,0,
(guessedBounds != 0) ? &bounds : 0,
_R
);
/* 3) Solve remaining QPs and assign lhs arguments. */
/* Set up pointers to the current QP vectors */
real_t* g_current = g;
real_t* lb_current = lb;
real_t* ub_current = ub;
/* Loop through QP sequence. */
for ( int_t k=0; k<nP; ++k )
{
if ( k > 0 )
{
/* update pointers to the current QP vectors */
g_current = &(g[k*nV]);
if ( lb != 0 )
lb_current = &(lb[k*nV]);
if ( ub != 0 )
ub_current = &(ub[k*nV]);
nWSRout = nWSRin;
maxCpuTimeOut = (maxCpuTimeIn >= 0.0) ? maxCpuTimeIn : INFTY;
returnvalue = QP.hotstart( g_current,lb_current,ub_current, nWSRout,&maxCpuTimeOut );
}
/* write results into output vectors */
obtainOutputs( k,&QP,returnvalue,nWSRout,maxCpuTimeOut,
nOutputs,plhs,nV );
}
return 0;
}
/*
* m e x F u n c t i o n
*/
void mexFunction( int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[] )
{
/* inputs */
SymmetricMatrix *H=0;
Matrix *A=0;
real_t *g=0, *lb=0, *ub=0, *lbA=0, *ubA=0;
HessianType hessianType = HST_UNKNOWN;
double *x0=0, *R=0, *R_for=0;
double *guessedBounds=0, *guessedConstraints=0;
int H_idx=-1, g_idx=-1, A_idx=-1, lb_idx=-1, ub_idx=-1, lbA_idx=-1, ubA_idx=-1;
int options_idx=-1, x0_idx=-1, auxInput_idx=-1;
/* Setup default options */
Options options;
options.printLevel = PL_LOW;
#ifdef __DEBUG__
options.printLevel = PL_HIGH;
#endif
#ifdef __SUPPRESSANYOUTPUT__
options.printLevel = PL_NONE;
#endif
/* dimensions */
uint_t nV=0, nC=0, nP=0;
BooleanType isSimplyBoundedQp = BT_FALSE;
/* sparse matrix indices and values */
sparse_int_t *Hir=0, *Hjc=0, *Air=0, *Ajc=0;
real_t *Hv=0, *Av=0;
/* I) CONSISTENCY CHECKS: */
/* 1a) Ensure that qpOASES is called with a feasible number of input arguments. */
if ( ( nrhs < 4 ) || ( nrhs > 9 ) )
{
myMexErrMsgTxt( "ERROR (qpOASES): Invalid number of input arguments!\nType 'help qpOASES' for further information." );
return;
}
/* 2) Check for proper number of output arguments. */
if ( nlhs > 6 )
{
myMexErrMsgTxt( "ERROR (qpOASES): At most six output arguments are allowed: \n [x,fval,exitflag,iter,lambda,auxOutput]!" );
return;
}
if ( nlhs < 1 )
{
myMexErrMsgTxt( "ERROR (qpOASES): At least one output argument is required: [x,...]!" );
return;
}
/* II) PREPARE RESPECTIVE QPOASES FUNCTION CALL: */
/* Choose between QProblem and QProblemB object and assign the corresponding
* indices of the input pointer array in to order to access QP data correctly. */
g_idx = 1;
if ( mxIsEmpty(prhs[0]) == 1 )
{
H_idx = -1;
nV = (int_t)mxGetM( prhs[ g_idx ] ); /* if Hessian is empty, row number of gradient vector */
}
else
{
H_idx = 0;
nV = (int_t)mxGetM( prhs[ H_idx ] ); /* row number of Hessian matrix */
}
nP = (int_t)mxGetN( prhs[ g_idx ] ); /* number of columns of the gradient matrix (vectors series have to be stored columnwise!) */
if ( nrhs <= 6 )
isSimplyBoundedQp = BT_TRUE;
else
isSimplyBoundedQp = BT_FALSE;
/* 0) Check whether options are specified .*/
if ( isSimplyBoundedQp == BT_TRUE )
{
if ( ( nrhs >= 5 ) && ( !mxIsEmpty(prhs[4]) ) && ( mxIsStruct(prhs[4]) ) )
options_idx = 4;
}
else
{
/* Consistency check */
if ( ( !mxIsEmpty(prhs[4]) ) && ( mxIsStruct(prhs[4]) ) )
{
myMexErrMsgTxt( "ERROR (qpOASES): Fifth input argument must not be a struct when solving QP with general constraints!\nType 'help qpOASES' for further information." );
return;
}
if ( ( nrhs >= 8 ) && ( !mxIsEmpty(prhs[7]) ) && ( mxIsStruct(prhs[7]) ) )
options_idx = 7;
}
// Is the third argument constraint Matrix A?
int_t numberOfColumns = (int_t)mxGetN(prhs[2]);
/* 1) Simply bounded QP. */
if ( ( isSimplyBoundedQp == BT_TRUE ) ||
( ( numberOfColumns == 1 ) && ( nV != 1 ) ) )
{
lb_idx = 2;
ub_idx = 3;
if ( ( nrhs >= 6 ) && ( !mxIsEmpty(prhs[5]) ) )
{
/* auxInput specified */
if ( mxIsStruct(prhs[5]) )
{
auxInput_idx = 5;
x0_idx = -1;
}
else
{
auxInput_idx = -1;
x0_idx = 5;
}
}
else
{
auxInput_idx = -1;
x0_idx = -1;
}
}
else
{
A_idx = 2;
/* If constraint matrix is empty, use a QProblemB object! */
if ( mxIsEmpty( prhs[ A_idx ] ) )
{
lb_idx = 3;
ub_idx = 4;
nC = 0;
}
else
{
lb_idx = 3;
ub_idx = 4;
lbA_idx = 5;
ubA_idx = 6;
nC = (int_t)mxGetM( prhs[ A_idx ] ); /* row number of constraint matrix */
}
if ( ( nrhs >= 9 ) && ( !mxIsEmpty(prhs[8]) ) )
{
/* auxInput specified */
if ( mxIsStruct(prhs[8]) )
{
auxInput_idx = 8;
x0_idx = -1;
}
else
{
auxInput_idx = -1;
x0_idx = 8;
}
}
else
{
auxInput_idx = -1;
x0_idx = -1;
}
}
/* ensure that data is given in real_t precision */
if ( ( ( H_idx >= 0 ) && ( mxIsDouble( prhs[ H_idx ] ) == 0 ) ) ||
( mxIsDouble( prhs[ g_idx ] ) == 0 ) )
{
myMexErrMsgTxt( "ERROR (qpOASES): All data has to be provided in double precision!" );
return;
}
/* check if supplied data contains 'NaN' or 'Inf' */
if (containsNaNorInf( prhs,H_idx, 0 ) == BT_TRUE)
return;
if (containsNaNorInf( prhs,g_idx, 0 ) == BT_TRUE)
return;
if (containsNaNorInf( prhs,lb_idx, 1 ) == BT_TRUE)
return;
if (containsNaNorInf( prhs,ub_idx, 1 ) == BT_TRUE)
return;
/* Check inputs dimensions and assign pointers to inputs. */
if ( ( H_idx >= 0 ) && ( ( mxGetN( prhs[ H_idx ] ) != nV ) || ( mxGetM( prhs[ H_idx ] ) != nV ) ) )
{
char msg[MAX_STRING_LENGTH];
snprintf(msg, MAX_STRING_LENGTH, "ERROR (qpOASES): Hessian matrix dimension mismatch (%ld != %d)!",
(long int)mxGetN(prhs[H_idx]), (int)nV);
myMexErrMsgTxt(msg);
return;
}
if ( nC > 0 )
{
/* ensure that data is given in real_t precision */
if ( mxIsDouble( prhs[ A_idx ] ) == 0 )
{
myMexErrMsgTxt( "ERROR (qpOASES): All data has to be provided in real_t precision!" );
return;
}
/* Check inputs dimensions and assign pointers to inputs. */
if ( mxGetN( prhs[ A_idx ] ) != nV )
{
char msg[MAX_STRING_LENGTH];
snprintf(msg, MAX_STRING_LENGTH, "ERROR (qpOASES): Constraint matrix input dimension mismatch (%ld != %d)!",
(long int)mxGetN(prhs[A_idx]), (int)nV);
myMexErrMsgTxt(msg);
return;
}
if (containsNaNorInf(prhs,A_idx, 0 ) == BT_TRUE)
return;
if (containsNaNorInf(prhs,lbA_idx, 1 ) == BT_TRUE)
return;
if (containsNaNorInf(prhs,ubA_idx, 1 ) == BT_TRUE)
return;
}
/* check dimensions and copy auxInputs */
if ( smartDimensionCheck( &g,nV,nP, BT_FALSE,prhs,g_idx ) != SUCCESSFUL_RETURN )
return;
if ( smartDimensionCheck( &lb,nV,nP, BT_TRUE,prhs,lb_idx ) != SUCCESSFUL_RETURN )
return;
if ( smartDimensionCheck( &ub,nV,nP, BT_TRUE,prhs,ub_idx ) != SUCCESSFUL_RETURN )
return;
if ( smartDimensionCheck( &x0,nV,1, BT_TRUE,prhs,x0_idx ) != SUCCESSFUL_RETURN )
return;
if ( nC > 0 )
{
if ( smartDimensionCheck( &lbA,nC,nP, BT_TRUE,prhs,lbA_idx ) != SUCCESSFUL_RETURN )
return;
if ( smartDimensionCheck( &ubA,nC,nP, BT_TRUE,prhs,ubA_idx ) != SUCCESSFUL_RETURN )
return;
}
if ( auxInput_idx >= 0 )
setupAuxiliaryInputs( prhs[auxInput_idx],nV,nC, &hessianType,&x0,&guessedBounds,&guessedConstraints,&R_for );
/* convert Cholesky factor to C storage format */
if ( R_for != 0 )
{
R = new real_t[nV*nV];
convertFortranToC( R_for, nV,nV, R );
}
/* III) ACTUALLY PERFORM QPOASES FUNCTION CALL: */
int_t nWSRin = 5*(nV+nC);
real_t maxCpuTimeIn = -1.0;
if ( options_idx > 0 )
setupOptions( &options,prhs[options_idx],nWSRin,maxCpuTimeIn );
/* make a deep-copy of the user-specified Hessian matrix (possibly sparse) */
if ( H_idx >= 0 )
setupHessianMatrix( prhs[H_idx],nV, &H,&Hir,&Hjc,&Hv );
/* make a deep-copy of the user-specified constraint matrix (possibly sparse) */
if ( ( nC > 0 ) && ( A_idx >= 0 ) )
setupConstraintMatrix( prhs[A_idx],nV,nC, &A,&Air,&Ajc,&Av );
allocateOutputs( nlhs,plhs,nV,nC,nP );
if ( nC == 0 )
{
/* Call qpOASES (using QProblemB class). */
QProblemB_qpOASES( nV,hessianType, nP,
H,g,
lb,ub,
nWSRin,maxCpuTimeIn,
x0,&options,
nlhs,plhs,
guessedBounds,R
);
if (R != 0) delete R;
if (H != 0) delete H;
if (Hv != 0) delete[] Hv;
if (Hjc != 0) delete[] Hjc;
if (Hir != 0) delete[] Hir;
return;
}
else
{
if ( A == 0 )
{
myMexErrMsgTxt( "ERROR (qpOASES): Internal interface error related to constraint matrix!" );
return;
}
/* Call qpOASES (using QProblem class). */
QProblem_qpOASES( nV,nC,hessianType, nP,
H,g,A,
lb,ub,lbA,ubA,
nWSRin,maxCpuTimeIn,
x0,&options,
nlhs,plhs,
guessedBounds,guessedConstraints,R
);
if (R != 0) delete R;
if (A != 0) delete A;
if (H != 0) delete H;
if (Av != 0) delete[] Av;
if (Ajc != 0) delete[] Ajc;
if (Air != 0) delete[] Air;
if (Hv != 0) delete[] Hv;
if (Hjc != 0) delete[] Hjc;
if (Hir != 0) delete[] Hir;
return;
}
}
/*
* end of file
*/
| lgpl-2.1 |
mwtoews/libgeos | tests/unit/operation/geounion/CascadedPolygonUnionTest.cpp | 3 | 4002 | //
// Test Suite for geos::operation::geounion::CascadedPolygonUnion class.
// tut
#include <tut/tut.hpp>
#include <utility.h>
// geos
#include <geos/operation/union/CascadedPolygonUnion.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/Polygon.h>
#include <geos/geom/Point.h>
#include <geos/io/WKTReader.h>
#include <geos/io/WKTWriter.h>
// std
#include <memory>
#include <string>
#include <vector>
namespace tut {
//
// Test Group
//
// Common data used by tests
struct test_cascadedpolygonuniontest_data {
const geos::geom::GeometryFactory& gf;
geos::io::WKTReader wktreader;
geos::io::WKTWriter wktwriter;
typedef geos::geom::Geometry::Ptr GeomPtr;
test_cascadedpolygonuniontest_data()
: gf(*geos::geom::GeometryFactory::getDefaultInstance())
, wktreader(&gf)
{}
};
typedef test_group<test_cascadedpolygonuniontest_data> group;
typedef group::object object;
group test_cascadedpolygonuniontest_group("geos::operation::geounion::CascadedPolygonUnion");
// test runner
geos::geom::Geometry*
unionIterated(
std::vector<geos::geom::Polygon*>* geoms)
{
std::unique_ptr<geos::geom::Geometry> unionAll;
for(const auto& p : *geoms) {
if(unionAll == nullptr) {
unionAll = p->clone();
}
else {
unionAll = unionAll->Union(p);
}
}
return unionAll.release();
}
std::unique_ptr<geos::geom::Geometry>
unionCascaded(
std::vector<geos::geom::Polygon*>* geoms)
{
using geos::operation::geounion::CascadedPolygonUnion;
return CascadedPolygonUnion::Union(geoms);
}
void
p_test_runner(
std::vector<geos::geom::Polygon*>* geoms)
{
std::unique_ptr<geos::geom::Geometry> union1(unionIterated(geoms));
std::unique_ptr<geos::geom::Geometry> union2(unionCascaded(geoms));
union1->normalize();
union2->normalize();
ensure_equals_geometry(union1.get(), union2.get(), 0.000001);
}
void
delete_geometry(geos::geom::Geometry* g)
{
delete g;
}
//
// Test Cases
//
template<>
template<>
void object::test<1>
()
{
static char const* const polygons[] = {
"POLYGON ((80 260, 200 260, 200 30, 80 30, 80 260))",
"POLYGON ((30 180, 300 180, 300 110, 30 110, 30 180))",
"POLYGON ((30 280, 30 150, 140 150, 140 280, 30 280))",
nullptr
};
std::vector<geos::geom::Polygon*> g;
for(char const * const* p = polygons; *p != nullptr; ++p) {
std::string wkt(*p);
geos::geom::Polygon* geom =
dynamic_cast<geos::geom::Polygon*>(wktreader.read(wkt).release());
g.push_back(geom);
}
p_test_runner(&g);
for_each(g.begin(), g.end(), delete_geometry);
}
void
create_discs(geos::geom::GeometryFactory& gf, int num, double radius,
std::vector<geos::geom::Polygon*>* g)
{
for(int i = 0; i < num; ++i) {
for(int j = 0; j < num; ++j) {
std::unique_ptr<geos::geom::Point> pt(
gf.createPoint(geos::geom::Coordinate(i, j)));
g->push_back(dynamic_cast<geos::geom::Polygon*>(pt->buffer(radius).release()));
}
}
}
// these tests currently fail because the geometries generated by the different
// union algorithms are slightly different. In order to make those tests pass
// we need to port the similarity measure classes from JTS, allowing to
// approximately compare the two results
// template<>
// template<>
// void object::test<2>()
// {
// std::vector<geos::geom::Polygon*> g;
// create_discs(gf, 5, 0.7, &g);
//
// test_runner(*this, &g);
//
// std::for_each(g.begin(), g.end(), delete_geometry);
// }
// template<>
// template<>
// void object::test<3>()
// {
// std::vector<geos::geom::Polygon*> g;
// create_discs(gf, 5, 0.55, &g);
//
// test_runner(*this, &g);
//
// std::for_each(g.begin(), g.end(), delete_geometry);
// }
} // namespace tut
| lgpl-2.1 |
archlinuxarm-n900/libhildon | tests/check-hildon-date-editor.c | 3 | 33132 | /*
* This file is a part of hildon tests
*
* Copyright (C) 2006, 2007 Nokia Corporation, all rights reserved.
*
* Contact: Michael Dominic Kostrzewa <michael.kostrzewa@nokia.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <stdlib.h>
#include <check.h>
#include <gtk/gtkmain.h>
#include <gtk/gtkhbox.h>
#include "test_suites.h"
#include "check_utils.h"
#include <hildon/hildon-date-editor.h>
/* Taken from the values of the properties of HildonDateEditor */
#define MAX_YEAR 2037
#define MAX_MONTH 12
#define MAX_DAY 31
#define MIN_YEAR 1970
#define MIN_MONTH 1
#define MIN_DAY 1
/* -------------------- Fixtures -------------------- */
static HildonDateEditor *date_editor = NULL;
static GtkWidget *showed_window = NULL;
static void
fx_setup_default_date_editor ()
{
int argc = 0;
gtk_init(&argc, NULL);
showed_window = create_test_window ();
date_editor = HILDON_DATE_EDITOR(hildon_date_editor_new());
/* Check that the date editor object has been created properly */
fail_if(!HILDON_IS_DATE_EDITOR(date_editor),
"hildon-date-editor: Creation failed.");
/* This packs the widget into the window (a gtk container). */
gtk_container_add (GTK_CONTAINER (showed_window), GTK_WIDGET (date_editor));
/* Displays the widget and the window */
show_all_test_window (showed_window);
}
static void
fx_teardown_default_date_editor ()
{
/* Destroy the widget and the window */
gtk_widget_destroy (GTK_WIDGET (showed_window));
}
/* -------------------- Test cases -------------------- */
/* ----- Test case for set_date -----*/
/**
* Purpose: test setting regular values for hildon_date_editor_set_date
* Cases considered:
* - Set and get the date 30/03/1981
*/
START_TEST (test_set_date_regular)
{
guint year, month, day;
guint ret_year, ret_month, ret_day;
year = 1981;
month = 3;
day = 30;
/* Test 1: Try date 30/3/1981 */
hildon_date_editor_set_date (date_editor, year, month, day);
hildon_date_editor_get_date (date_editor, &ret_year, &ret_month, &ret_day);
fail_if ((ret_year != year) || (ret_month != month) || (ret_day != day),
"hildon-date-editor: The returned date is %u/%u/%u and should be %u/%u/%u",
ret_year, ret_month, ret_day, year, month, day);
}
END_TEST
static void
test_set_date_limits_check (guint year, guint month, guint day)
{
guint ret_year, ret_month, ret_day;
hildon_date_editor_set_date (date_editor, year, month, day);
hildon_date_editor_get_date (date_editor, &ret_year, &ret_month, &ret_day);
fail_if ((ret_year != year) || (ret_month != month) || (ret_day != day),
"hildon-date-editor: The returned date is %u/%u/%u and should be %u/%u/%u",
ret_year, ret_month, ret_day, year, month, day);
}
/**
* Purpose: test limit date values for hildon_date_editor_set_date
* Cases considered:
* - test a year value equal to the year limits (1970, 2037)
* - test a month value equal to the month limits (1, 12)
* - test a day value equal to the day limits for March (1, 31)
* - test a day value equal to the day limits June (1, 30)
* - test a day value equal to the day limit for a common February (28-2-1981)
* - test a day value equal to the day limit for a February of a leap year (29-2-1980)
*/
START_TEST (test_set_date_limits)
{
guint year, month, day;
year = MIN_YEAR;
month = 3;
day = 30;
/* Test 1: Test year limits */
test_set_date_limits_check (year, month, day);
year = MAX_YEAR;
test_set_date_limits_check (year, month, day);
/* Test 2: Test month limits */
year = 1981;
month = MIN_MONTH;
day = 30;
test_set_date_limits_check (year, month, day);
month = MAX_MONTH;
test_set_date_limits_check (year, month, day);
/* Test 3: Test day limits */
year = 1981;
month = 3;
day = 31;
test_set_date_limits_check (year, month, day);
/* Test 4: Test day limits */
year = 1981;
month = 6;
day = 30;
test_set_date_limits_check (year, month, day);
/* Test 5: Test february limits */
year = 1981;
month = 2;
day = 28;
test_set_date_limits_check (year, month, day);
/* Test 6: Test february limits for a leap year */
year = 1980;
month = 2;
day = 29;
test_set_date_limits_check (year, month, day);
}
END_TEST
/**
* Purpose: test invalid parameter values for hildon_date_editor_set_date
* Cases considered:
* - test NULL widget
* - test passing GtkHBox instead a HildonDateEditor
* - test leap year
* - test negative values
* - test invalid month days
* - test a year value lower and higher than the year limits (1970, 2037)
* - test a month value lower and higher than the year limits (1, 12)
* - test a day value lower and higher than the year limits (1, 31)
*/
START_TEST (test_set_date_invalid)
{
guint year, month, day;
guint ret_year, ret_month, ret_day;
GtkWidget *aux_object = NULL;
year = 1981;
month = 3;
day = 30;
/* Set init date */
hildon_date_editor_set_date (date_editor, year, month, day);
/* Test 1: Test NULL */
hildon_date_editor_set_date (NULL, year, month, day);
hildon_date_editor_get_date (date_editor, &ret_year, &ret_month, &ret_day);
fail_if ((ret_year != year) || (ret_month != month) || (ret_day != day),
"hildon-date-editor: The returned date is %u/%u/%u and should be %u/%u/%u",
ret_year, ret_month, ret_day, year, month, day);
/* Test 2: Test another object */
aux_object = gtk_hbox_new (TRUE, 0);
hildon_date_editor_set_date ((HildonDateEditor *) (aux_object), year, month, day);
hildon_date_editor_get_date (date_editor, &ret_year, &ret_month, &ret_day);
fail_if ((ret_year != year) || (ret_month != month) || (ret_day != day),
"hildon-date-editor: The returned date is %u/%u/%u and should be %u/%u/%u",
ret_year, ret_month, ret_day, year, month, day);
gtk_widget_destroy (GTK_WIDGET(aux_object));
/* Test 3: Test leap year */
hildon_date_editor_set_date (date_editor, year, 2, 29);
hildon_date_editor_get_date (date_editor, &ret_year, &ret_month, &ret_day);
fail_if ((ret_year != year) || (ret_month != month) || (ret_day != day),
"hildon-date-editor: The returned date is %u/%u/%u and should be %u/%u/%u",
ret_year, ret_month, ret_day, year, month, day);
/* Restore the original value */
hildon_date_editor_set_date (date_editor, year, month, day);
/* Test 4: Test negative values */
hildon_date_editor_set_date (date_editor, -year, -month, -day);
hildon_date_editor_get_date (date_editor, &ret_year, &ret_month, &ret_day);
fail_if ((ret_year != year) || (ret_month != month) || (ret_day != day),
"hildon-date-editor: The returned date is %u/%u/%u and should be %u/%u/%u",
ret_year, ret_month, ret_day, year, month, day);
/* Test 5: Test invalid month days */
hildon_date_editor_set_date (date_editor, year, 11, 31);
hildon_date_editor_get_date (date_editor, &ret_year, &ret_month, &ret_day);
fail_if ((ret_year != year) || (ret_month != month) || (ret_day != day),
"hildon-date-editor: The returned date is %u/%u/%u and should be %u/%u/%u",
ret_year, ret_month, ret_day, year, month, day);
/* Test 6: Test year invalid values, the year value could be set
under/over the value of the property because the date is not
validated if the value was not set through the user interface */
hildon_date_editor_set_date (date_editor, MIN_YEAR - 1, month, day);
hildon_date_editor_get_date (date_editor, &ret_year, &ret_month, &ret_day);
fail_if (ret_year != (MIN_YEAR - 1),
"hildon-date-editor: The returned year is %u and should be %u",
ret_year, MIN_YEAR - 1);
hildon_date_editor_set_date (date_editor, MAX_YEAR + 1, month, day);
hildon_date_editor_get_date (date_editor, &ret_year, &ret_month, &ret_day);
fail_if (ret_year != MAX_YEAR + 1,
"hildon-date-editor: The returned year is %u and should be %u",
ret_year, MAX_YEAR + 1);
/* Test 7: Test month invalid values, we do not have the same
problem with the years because both month 0 and 13 are not valid
for g_date */
hildon_date_editor_set_date (date_editor, year, MIN_MONTH - 1, day);
hildon_date_editor_get_date (date_editor, &ret_year, &ret_month, &ret_day);
fail_if (ret_month != month,
"hildon-date-editor: The returned month is %u and should be %u",
ret_month, month);
hildon_date_editor_set_date (date_editor, year, MAX_MONTH + 1, day);
hildon_date_editor_get_date (date_editor, &ret_year, &ret_month, &ret_day);
fail_if (ret_month != month,
"hildon-date-editor: The returned month is %u and should be %u",
ret_month, month);
/* Test 8: Test day invalid values */
hildon_date_editor_set_date (date_editor, year, month, MIN_DAY - 1);
hildon_date_editor_get_date (date_editor, &ret_year, &ret_month, &ret_day);
fail_if (ret_day != day,
"hildon-date-editor: The returned day is %u and should be %u",
ret_day, day);
hildon_date_editor_set_date (date_editor, year, month, MAX_DAY + 1);
hildon_date_editor_get_date (date_editor, &ret_year, &ret_month, &ret_day);
fail_if (ret_day != day,
"hildon-date-editor: The returned day is %u and should be %u",
ret_day, day);
}
END_TEST
/* ----- Test case for get_date -----*/
/* We do not include tests for limit values because we think they're
tested enought with the set_data tests */
/**
* Purpose: test getting regular values for hildon_date_editor_get_date
* Cases considered:
* - Set and get date 30/03/1981
*/
START_TEST (test_get_date_regular)
{
guint year, month, day;
guint ret_year, ret_month, ret_day;
GValue value = { 0, };
year = 1981;
month = 3;
day = 30;
/* Test 1: Test regular values */
hildon_date_editor_set_date (NULL, year, month, day);
hildon_date_editor_get_date (date_editor, &ret_year, &ret_month, &ret_day);
g_value_init (&value, G_TYPE_UINT);
g_object_get_property (G_OBJECT (date_editor), "year", &value);
fail_if (g_value_get_uint (&value) != ret_year,
"hildon-date-editor: get_date failed. The returned year is %u and should be %u",
g_value_get_uint (&value),
ret_year);
g_value_unset (&value);
g_value_init (&value, G_TYPE_UINT);
g_object_get_property (G_OBJECT (date_editor), "month", &value);
fail_if (g_value_get_uint (&value) != ret_month,
"hildon-date-editor: get_date failed. The returned month is %u and should be %u",
g_value_get_uint (&value),
ret_month);
g_value_unset (&value);
g_value_init (&value, G_TYPE_UINT);
g_object_get_property (G_OBJECT (date_editor), "day", &value);
fail_if (g_value_get_uint (&value) != ret_day,
"hildon-date-editor: get_date failed. The returned day is %u and should be %u",
g_value_get_uint (&value),
ret_day);
}
END_TEST
/**
* Purpose: test getting regular values passing invalid arguments for
* hildon_date_editor_get_date
* Cases considered:
* - HildonDateEditor NULL
* - year is NULL
* - month is NULL
* - day is NULL
*/
START_TEST (test_get_date_invalid)
{
guint year, month, day;
guint ret_year, ret_month, ret_day;
year = 1981;
month = 3;
day = 30;
hildon_date_editor_set_date (date_editor, year, month, day);
/* Check that does not fail */
hildon_date_editor_get_date (NULL, &ret_year, &ret_month, &ret_day);
/* Check NULL arguments */
hildon_date_editor_get_date (date_editor, NULL, &ret_month, &ret_day);
fail_if (hildon_date_editor_get_year (date_editor) != year,
"hildon-date-editor: get_date failed. The returned year is %u and should be %u",
ret_year, year);
hildon_date_editor_get_date (date_editor, &ret_year, NULL, &ret_day);
fail_if (hildon_date_editor_get_month (date_editor) != month,
"hildon-date-editor: get_date failed. The returned month is %u and should be %u",
ret_month, month);
hildon_date_editor_get_date (date_editor, &ret_year, &ret_month, NULL);
fail_if (hildon_date_editor_get_day (date_editor) != day,
"hildon-date-editor: get_date failed. The returned day is %u and should be %u",
ret_day, day);
}
END_TEST
/* ----- Test case for get_year -----*/
/**
* Purpose: test getting regular values of the year for hildon_date_editor_get_year
* Cases considered:
* - get a year set with set_date 30/03/1981
* - get a year set with set_year 1980
* - get a year set with set_property 2004
*/
START_TEST (test_get_year_regular)
{
guint year, month, day;
GValue value = {0, };
year = 1981;
month = 3;
day = 30;
/* Test 1: Set year with set_date */
hildon_date_editor_set_date (date_editor, year, month, day);
fail_if (hildon_date_editor_get_year (date_editor) != year,
"hildon-date-editor: get_year failed. The returned year is %u and should be %u",
hildon_date_editor_get_year (date_editor), year);
/* Test 2: set year with set_year */
year = 1980;
hildon_date_editor_set_year (date_editor, year);
fail_if (hildon_date_editor_get_year (date_editor) != year,
"hildon-date-editor: get_year failed. The returned year is %u and should be %u",
hildon_date_editor_get_year (date_editor), year);
/* Test 3: set year with set_property */
year = 2004;
g_value_init (&value, G_TYPE_UINT);
g_value_set_uint (&value, year);
g_object_set_property (G_OBJECT (date_editor), "year", &value);
fail_if (hildon_date_editor_get_year (date_editor) != year,
"hildon-date-editor: get_year failed. The returned year is %u and should be %u",
hildon_date_editor_get_year (date_editor), year);
}
END_TEST
/**
* Purpose: test getting year when a value over the limits was set for
* hildon_date_editor_get_year
* Cases considered:
* - test year 2037
* - test year 1970
*/
START_TEST (test_get_year_limits)
{
guint year;
year = 1981;
/* Set init year */
hildon_date_editor_set_year (date_editor, year);
/* Test 1: upper limit */
hildon_date_editor_set_year (date_editor, MAX_YEAR);
fail_if (hildon_date_editor_get_year (date_editor) != MAX_YEAR,
"hildon-date-editor: The returned year is %u and should be %u",
hildon_date_editor_get_year (date_editor), MAX_YEAR);
/* Test 2: lower limit */
hildon_date_editor_set_year (date_editor, MIN_YEAR);
fail_if (hildon_date_editor_get_year (date_editor) != MIN_YEAR,
"hildon-date-editor: The returned year is %u and should be %u",
hildon_date_editor_get_year (date_editor), MIN_YEAR);
}
END_TEST
/**
* Purpose: test getting a year for invalid attributes for
* hildon_date_editor_get_year
* Cases considered:
* - HildonDateEditor is NULL
* - Pass a GtkHBox instead a HildonDateEditor
* - test year 2038
* - test year 1969
*/
START_TEST (test_get_year_invalid)
{
guint ret_year;
GtkWidget *aux_object = NULL;
/* Test 1: Test NULL */
ret_year = hildon_date_editor_get_year (NULL);
fail_if (ret_year != 0,
"hildon-date-editor: get_year failed. The returned year is %u and should be %u",
ret_year, 0);
/* Test 2: another object */
aux_object = gtk_hbox_new (TRUE, 0);
ret_year = hildon_date_editor_get_year ((HildonDateEditor *) (aux_object));
fail_if (ret_year != 0,
"hildon-date-editor: get_year failed. The returned year is %u and should be %u",
ret_year, 0);
gtk_widget_destroy (GTK_WIDGET(aux_object));
/* Test 3: upper limit, the test is OK but it shouldn't. The reason
is that the value of the date is not validated by Hildon since it
was not set using the UI */
hildon_date_editor_set_year (date_editor, MAX_YEAR + 1);
fail_if (hildon_date_editor_get_year (date_editor) != MAX_YEAR + 1,
"hildon-date-editor: The returned year is %u and should be %u",
hildon_date_editor_get_year (date_editor), MAX_YEAR + 1);
/* Test 4: lower limit, see the above comment */
hildon_date_editor_set_year (date_editor, MIN_YEAR - 1);
fail_if (hildon_date_editor_get_year (date_editor) != MIN_YEAR - 1,
"hildon-date-editor: The returned year is %u and should be %u",
hildon_date_editor_get_year (date_editor), MIN_YEAR - 1);
}
END_TEST
/* ----- Test case for set_year -----*/
/**
* Purpose: test setting a regular value for a year for
* hildon_date_editor_set_year
* Cases considered:
* - Set year 1981
*/
START_TEST (test_set_year_regular)
{
guint year;
guint ret_year;
year = 1981;
/* Test 1: Try year 1981 */
hildon_date_editor_set_year (date_editor, year);
ret_year = hildon_date_editor_get_year (date_editor);
fail_if (ret_year != year,
"hildon-date-editor: set_year failed. The returned year is %u and should be %u",
ret_year, year);
}
END_TEST
/**
* Purpose: test setting values of the year over the limits for
* hildon_date_editor_set_year
* Cases considered:
* - Set year 2037
* - Set year 1970
*/
START_TEST (test_set_year_limits)
{
guint year;
GValue value = { 0, };
year = 1981;
/* Set init date */
hildon_date_editor_set_year (date_editor, year);
/* Test 1: Test upper limit */
g_value_init (&value, G_TYPE_UINT);
hildon_date_editor_set_year (date_editor, MAX_YEAR);
g_object_get_property (G_OBJECT (date_editor), "year", &value);
fail_if (g_value_get_uint (&value) != MAX_YEAR,
"hildon-date-editor: The returned year is %u and should be %u",
g_value_get_uint (&value), year);
/* Test 2: Test lower limit */
g_value_unset (&value);
g_value_init (&value, G_TYPE_UINT);
hildon_date_editor_set_year (date_editor, MIN_YEAR);
g_object_get_property (G_OBJECT (date_editor), "year", &value);
fail_if (g_value_get_uint (&value) != MIN_YEAR,
"hildon-date-editor: The returned year is %u and should be %u",
g_value_get_uint (&value), MIN_YEAR);
}
END_TEST
/* ----- Test case for get_month -----*/
/**
* Purpose: test getting a year for regular values for
* hildon_date_editor_get_month
* Cases considered:
* - set month with set_date 30/03/1981
* - set month with set_month 1
* - set month with set_property 7
*/
START_TEST (test_get_month_regular)
{
guint year, month, day;
GValue value = {0, };
year = 1981;
month = 3;
day = 30;
/* Test 1: Set year with set_date */
hildon_date_editor_set_date (date_editor, year, month, day);
fail_if (hildon_date_editor_get_month (date_editor) != month,
"hildon-date-editor: The returned month is %u and should be %u",
hildon_date_editor_get_month (date_editor), month);
/* Test 2: set month with set_month */
month = 1;
hildon_date_editor_set_month (date_editor, month);
fail_if (hildon_date_editor_get_month (date_editor) != month,
"hildon-date-editor: The returned month is %u and should be %u",
hildon_date_editor_get_month (date_editor), month);
/* Test 3: set month with set_property */
month = 7;
g_value_init (&value, G_TYPE_UINT);
g_value_set_uint (&value, month);
g_object_set_property (G_OBJECT (date_editor), "month", &value);
fail_if (hildon_date_editor_get_month (date_editor) != month,
"hildon-date-editor: The returned month is %u and should be %u",
hildon_date_editor_get_month (date_editor), month);
}
END_TEST
/**
* Purpose: test getting values of the month over the limits for
* hildon_date_editor_get_month
* Cases considered:
* - Get month 12
* - Get month 1
*/
START_TEST (test_get_month_limits)
{
/* Test 1: Upper limit */
hildon_date_editor_set_month (date_editor, MAX_MONTH);
fail_if (hildon_date_editor_get_month (date_editor) != MAX_MONTH,
"hildon-date-editor: get_month failed. The returned month is %u and should be %u",
hildon_date_editor_get_month (date_editor), MAX_MONTH);
/* Test 2: Lower limit */
hildon_date_editor_set_month (date_editor, MIN_MONTH);
fail_if (hildon_date_editor_get_month (date_editor) != MIN_MONTH,
"hildon-date-editor: get_month failed. The returned month is %u and should be %u",
hildon_date_editor_get_month (date_editor), MIN_MONTH);
}
END_TEST
/**
* Purpose: test getting a month for invalid attributes for
* hildon_date_editor_get_month
* Cases considered:
* - HildonDateEditor is NULL
* - HildonDateEditor is really a GtkHBox
*/
START_TEST (test_get_month_invalid)
{
guint ret_month;
GtkWidget *aux_object = NULL;
/* Test 1: Test NULL */
ret_month = hildon_date_editor_get_month (NULL);
fail_if (ret_month != 0,
"hildon-date-editor: get_month failed. The returned month is %u and should be %u",
ret_month, 0);
/* Test 2: another object */
aux_object = gtk_hbox_new (TRUE, 0);
ret_month = hildon_date_editor_get_month ((HildonDateEditor *) (aux_object));
fail_if (ret_month != 0,
"hildon-date-editor: get_month failed. The returned month is %u and should be %u",
ret_month, 0);
gtk_widget_destroy (GTK_WIDGET(aux_object));
}
END_TEST
/* ----- Test case for set_month -----*/
/**
* Purpose: test setting regular values for month for
* hildon_date_editor_set_month
* Cases considered:
* - Set month 3
*/
START_TEST (test_set_month_regular)
{
guint month;
guint ret_month;
month = 3;
/* Test 1: Try month March (3) */
hildon_date_editor_set_month (date_editor, month);
ret_month = hildon_date_editor_get_month (date_editor);
fail_if (ret_month != month,
"hildon-date-editor: set_month failed. The returned month is %u and should be %u",
ret_month, month);
}
END_TEST
/**
* Purpose: test setting values for month over the limits for
* hildon_date_editor_get_month
* Cases considered:
* - Set month 12
* - Set month 1
*/
START_TEST (test_set_month_limits)
{
GValue value = { 0, };
/* Test 1: Test upper limit */
g_value_init (&value, G_TYPE_UINT);
hildon_date_editor_set_month (date_editor, MAX_MONTH);
g_object_get_property (G_OBJECT (date_editor), "month", &value);
fail_if (g_value_get_uint (&value) != MAX_MONTH,
"hildon-date-editor: The returned month is %u and should be %u",
g_value_get_uint (&value), MAX_MONTH);
/* Test 2: Test lower limit */
g_value_unset (&value);
g_value_init (&value, G_TYPE_UINT);
hildon_date_editor_set_month (date_editor, MIN_MONTH);
g_object_get_property (G_OBJECT (date_editor), "month", &value);
fail_if (g_value_get_uint (&value) != MIN_MONTH,
"hildon-date-editor: The returned month is %u and should be %u",
g_value_get_uint (&value), MIN_MONTH);
}
END_TEST
/* ----- Test case for get_day -----*/
/**
* Purpose: test getting regular values for day for
* hildon_date_editor_get_day
* Cases considered:
* - Get a day set with set_date 30/03/1981
* - Get a day set with set_day 6
* - Get a day set with set_property 10
*/
START_TEST (test_get_day_regular)
{
guint year, month, day;
GValue value = {0, };
year = 1981;
month = 3;
day = 30;
/* Test 1: Set day with set_date */
hildon_date_editor_set_date (date_editor, year, month, day);
fail_if (hildon_date_editor_get_day (date_editor) != day,
"hildon-date-editor: The returned day is %u and should be %u",
hildon_date_editor_get_day (date_editor), day);
/* Test 2: set day with set_day */
day = 6;
hildon_date_editor_set_day (date_editor, day);
fail_if (hildon_date_editor_get_day (date_editor) != day,
"hildon-date-editor: The returned day is %u and should be %u",
hildon_date_editor_get_day (date_editor), day);
/* Test 3: set day with set_property */
day = 10;
g_value_init (&value, G_TYPE_UINT);
g_value_set_uint (&value, day);
g_object_set_property (G_OBJECT (date_editor), "day", &value);
fail_if (hildon_date_editor_get_day (date_editor) != day,
"hildon-date-editor: The returned day is %u and should be %u",
hildon_date_editor_get_day (date_editor), day);
}
END_TEST
/**
* Purpose: test getting a day set over the limits for
* hildon_date_editor_get_day
* Cases considered:
* - Get day 31 for March
* - Get day 30 for June
* - Get day 29 for February for a leap year
* - Get day 28 for February for a common year
* - Get day 1
*/
START_TEST (test_get_day_limits)
{
guint day, month, year;
year = 1981;
month = 3;
day = 31;
/* Test 1: 31 of February */
hildon_date_editor_set_date (date_editor, year, month, day);
fail_if (hildon_date_editor_get_day (date_editor) != day,
"hildon-date-editor: get_day failed. The returned day is %u and should be %u",
hildon_date_editor_get_day (date_editor), day);
/* Test 2: 30 of February */
month = 6;
day = 30;
hildon_date_editor_set_date (date_editor, year, month, day);
fail_if (hildon_date_editor_get_day (date_editor) != day,
"hildon-date-editor: get_day failed. The returned day is %u and should be %u",
hildon_date_editor_get_day (date_editor), day);
/* Test 3: 29 of February */
year = 1980;
month = 2;
day = 29;
hildon_date_editor_set_date (date_editor, year, month, day);
fail_if (hildon_date_editor_get_day (date_editor) != day,
"hildon-date-editor: get_day failed. The returned day is %u and should be %u",
hildon_date_editor_get_day (date_editor), day);
/* Test 3: 28 of February */
year = 1981;
month = 2;
day = 28;
hildon_date_editor_set_date (date_editor, year, month, day);
fail_if (hildon_date_editor_get_day (date_editor) != day,
"hildon-date-editor: get_day failed. The returned day is %u and should be %u",
hildon_date_editor_get_day (date_editor), day);
/* Test 5: day 1 */
hildon_date_editor_set_day (date_editor, 1);
fail_if (hildon_date_editor_get_day (date_editor) != 1,
"hildon-date-editor: get_day failed. The returned day is %u and should be %u",
hildon_date_editor_get_day (date_editor), 1);
}
END_TEST
/**
* Purpose: test getting a day with invalid attributes for
* hildon_date_editor_get_day
* Cases considered:
* - HildonDateEditor is NULL
* - HildonDateEditor is really a GtkHBox
*/
START_TEST (test_get_day_invalid)
{
guint ret_year;
GtkWidget *aux_object = NULL;
/* Test 1: Test NULL */
ret_year = hildon_date_editor_get_year (NULL);
fail_if (ret_year != 0,
"hildon-date-editor: get_year failed. The returned year is %u and should be %u",
ret_year, 0);
/* Test 2: another object */
aux_object = gtk_hbox_new (TRUE, 0);
ret_year = hildon_date_editor_get_year ((HildonDateEditor *) aux_object);
fail_if (ret_year != 0,
"hildon-date-editor: get_year failed. The returned year is %u and should be %u",
ret_year, 0);
gtk_widget_destroy (GTK_WIDGET(aux_object));
}
END_TEST
/* ----- Test case for set_day -----*/
/**
* Purpose: test setting a regular value for day for
* hildon_date_editor_get_day
* Cases considered:
* - Set day 30
*/
START_TEST (test_set_day_regular)
{
guint day;
guint ret_day;
day = 25;
/* Test 1: Try day 30 */
hildon_date_editor_set_day (date_editor, day);
ret_day = hildon_date_editor_get_day (date_editor);
fail_if (ret_day != day,
"hildon-date-editor: set_day failed. The returned day is %u and should be %u",
ret_day, day);
}
END_TEST
/**
* Purpose: test seeting a day over the limits for
* hildon_date_editor_get_day
* Cases considered:
* - Set day 31
* - Set day 30
* - Set day 29
* - Set day 28
* - Set day 1
*/
START_TEST (test_set_day_limits)
{
guint day, year, month;
GValue value = { 0, };
year = 1981;
month = 3;
day = 31;
/* Set init date */
hildon_date_editor_set_date (date_editor, year, month, MIN_DAY);
/* Test 1: Test 31/03 */
g_value_init (&value, G_TYPE_UINT);
hildon_date_editor_set_day (date_editor, day);
g_object_get_property (G_OBJECT (date_editor), "day", &value);
fail_if (g_value_get_uint (&value) != day,
"hildon-date-editor: The returned day is %u and should be %u",
g_value_get_uint (&value), day);
/* Test 2: Test 30/06 */
month = 6;
day = 30;
hildon_date_editor_set_date (date_editor, year, month, 1);
g_value_unset (&value);
g_value_init (&value, G_TYPE_UINT);
hildon_date_editor_set_day (date_editor, day);
g_object_get_property (G_OBJECT (date_editor), "day", &value);
fail_if (g_value_get_uint (&value) != day,
"hildon-date-editor: The returned day is %u and should be %u",
g_value_get_uint (&value), day);
/* Test 3: Test 29/02/1980 */
year = 1980;
month = 2;
day = 29;
hildon_date_editor_set_date (date_editor, year, month, 1);
g_value_unset (&value);
g_value_init (&value, G_TYPE_UINT);
hildon_date_editor_set_day (date_editor, day);
g_object_get_property (G_OBJECT (date_editor), "day", &value);
fail_if (g_value_get_uint (&value) != day,
"hildon-date-editor: The returned day is %u and should be %u",
g_value_get_uint (&value), day);
/* Test 4: Test 28/02/1981 */
year = 1981;
month = 2;
day = 28;
hildon_date_editor_set_date (date_editor, year, month, 1);
g_value_unset (&value);
g_value_init (&value, G_TYPE_UINT);
hildon_date_editor_set_day (date_editor, day);
g_object_get_property (G_OBJECT (date_editor), "day", &value);
fail_if (g_value_get_uint (&value) != day,
"hildon-date-editor: The returned day is %u and should be %u",
g_value_get_uint (&value), day);
/* Test 5: Test 1/02/1980 */
year = 1980;
month = 2;
day = 1;
hildon_date_editor_set_date (date_editor, year, month, 10);
g_value_unset (&value);
g_value_init (&value, G_TYPE_UINT);
hildon_date_editor_set_day (date_editor, day);
g_object_get_property (G_OBJECT (date_editor), "day", &value);
fail_if (g_value_get_uint (&value) != day,
"hildon-date-editor: The returned day is %u and should be %u",
g_value_get_uint (&value), day);
}
END_TEST
/* ---------- Suite creation ---------- */
Suite *create_hildon_date_editor_suite(void)
{
/* Create the suite */
Suite *s = suite_create("HildonDateEditor");
/* Create test cases */
TCase *tc1 = tcase_create("set_date");
TCase *tc2 = tcase_create("get_date");
TCase *tc3 = tcase_create("get_year");
TCase *tc4 = tcase_create("set_year");
TCase *tc5 = tcase_create("get_month");
TCase *tc6 = tcase_create("set_month");
TCase *tc7 = tcase_create("get_day");
TCase *tc8 = tcase_create("set_day");
/* Create test case for set_date and add it to the suite */
tcase_add_checked_fixture(tc1, fx_setup_default_date_editor, fx_teardown_default_date_editor);
tcase_add_test(tc1, test_set_date_regular);
tcase_add_test(tc1, test_set_date_limits);
tcase_add_test(tc1, test_set_date_invalid);
suite_add_tcase (s, tc1);
/* Create test case for get_date and add it to the suite */
tcase_add_checked_fixture(tc2, fx_setup_default_date_editor, fx_teardown_default_date_editor);
tcase_add_test(tc2, test_get_date_regular);
tcase_add_test(tc2, test_get_date_invalid);
suite_add_tcase (s, tc2);
/* Create test case for get_year and add it to the suite */
tcase_add_checked_fixture(tc3, fx_setup_default_date_editor, fx_teardown_default_date_editor);
tcase_add_test(tc3, test_get_year_regular);
tcase_add_test(tc3, test_get_year_limits);
tcase_add_test(tc3, test_get_year_invalid);
suite_add_tcase (s, tc3);
/* Create test case for set_year and add it to the suite */
tcase_add_checked_fixture(tc4, fx_setup_default_date_editor, fx_teardown_default_date_editor);
tcase_add_test(tc4, test_set_year_regular);
tcase_add_test(tc4, test_set_year_limits);
suite_add_tcase (s, tc4);
/* Create test case for get_month and add it to the suite */
tcase_add_checked_fixture(tc5, fx_setup_default_date_editor, fx_teardown_default_date_editor);
tcase_add_test(tc5, test_get_month_regular);
tcase_add_test(tc5, test_get_month_limits);
tcase_add_test(tc5, test_get_month_invalid);
suite_add_tcase (s, tc5);
/* Create test case for set_month and add it to the suite */
tcase_add_checked_fixture(tc6, fx_setup_default_date_editor, fx_teardown_default_date_editor);
tcase_add_test(tc6, test_set_month_regular);
tcase_add_test(tc6, test_set_month_limits);
suite_add_tcase (s, tc6);
/* Create test case for get_day and add it to the suite */
tcase_add_checked_fixture(tc7, fx_setup_default_date_editor, fx_teardown_default_date_editor);
tcase_add_test(tc7, test_get_day_regular);
tcase_add_test(tc7, test_get_day_limits);
tcase_add_test(tc7, test_get_day_invalid);
suite_add_tcase (s, tc7);
/* Create test case for set_day and add it to the suite */
tcase_add_checked_fixture(tc8, fx_setup_default_date_editor, fx_teardown_default_date_editor);
tcase_add_test(tc8, test_set_day_regular);
tcase_add_test(tc8, test_set_day_limits);
suite_add_tcase (s, tc8);
/* Return created suite */
return s;
}
| lgpl-2.1 |
RLovelett/qt | src/3rdparty/webkit/WebCore/rendering/RenderSVGImage.cpp | 3 | 10860 | /*
Copyright (C) 2006 Alexander Kellett <lypanov@kde.org>
Copyright (C) 2006 Apple Computer, Inc.
Copyright (C) 2007 Nikolas Zimmermann <zimmermann@kde.org>
Copyright (C) 2007, 2008 Rob Buis <buis@kde.org>
This file is part of the WebKit project
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "config.h"
#if ENABLE(SVG)
#include "RenderSVGImage.h"
#include "Attr.h"
#include "FloatConversion.h"
#include "GraphicsContext.h"
#include "PointerEventsHitRules.h"
#include "SVGImageElement.h"
#include "SVGLength.h"
#include "SVGPreserveAspectRatio.h"
#include "SVGRenderSupport.h"
#include "SVGResourceClipper.h"
#include "SVGResourceFilter.h"
#include "SVGResourceMasker.h"
namespace WebCore {
RenderSVGImage::RenderSVGImage(SVGImageElement* impl)
: RenderImage(impl)
{
}
RenderSVGImage::~RenderSVGImage()
{
}
void RenderSVGImage::adjustRectsForAspectRatio(FloatRect& destRect, FloatRect& srcRect, SVGPreserveAspectRatio* aspectRatio)
{
float origDestWidth = destRect.width();
float origDestHeight = destRect.height();
if (aspectRatio->meetOrSlice() == SVGPreserveAspectRatio::SVG_MEETORSLICE_MEET) {
float widthToHeightMultiplier = srcRect.height() / srcRect.width();
if (origDestHeight > (origDestWidth * widthToHeightMultiplier)) {
destRect.setHeight(origDestWidth * widthToHeightMultiplier);
switch(aspectRatio->align()) {
case SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMINYMID:
case SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMIDYMID:
case SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMAXYMID:
destRect.setY(destRect.y() + origDestHeight / 2.0f - destRect.height() / 2.0f);
break;
case SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMINYMAX:
case SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMIDYMAX:
case SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMAXYMAX:
destRect.setY(destRect.y() + origDestHeight - destRect.height());
break;
}
}
if (origDestWidth > (origDestHeight / widthToHeightMultiplier)) {
destRect.setWidth(origDestHeight / widthToHeightMultiplier);
switch(aspectRatio->align()) {
case SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMIDYMIN:
case SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMIDYMID:
case SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMIDYMAX:
destRect.setX(destRect.x() + origDestWidth / 2.0f - destRect.width() / 2.0f);
break;
case SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMAXYMIN:
case SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMAXYMID:
case SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMAXYMAX:
destRect.setX(destRect.x() + origDestWidth - destRect.width());
break;
}
}
} else if (aspectRatio->meetOrSlice() == SVGPreserveAspectRatio::SVG_MEETORSLICE_SLICE) {
float widthToHeightMultiplier = srcRect.height() / srcRect.width();
// if the destination height is less than the height of the image we'll be drawing
if (origDestHeight < (origDestWidth * widthToHeightMultiplier)) {
float destToSrcMultiplier = srcRect.width() / destRect.width();
srcRect.setHeight(destRect.height() * destToSrcMultiplier);
switch(aspectRatio->align()) {
case SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMINYMID:
case SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMIDYMID:
case SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMAXYMID:
srcRect.setY(destRect.y() + image()->height() / 2.0f - srcRect.height() / 2.0f);
break;
case SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMINYMAX:
case SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMIDYMAX:
case SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMAXYMAX:
srcRect.setY(destRect.y() + image()->height() - srcRect.height());
break;
}
}
// if the destination width is less than the width of the image we'll be drawing
if (origDestWidth < (origDestHeight / widthToHeightMultiplier)) {
float destToSrcMultiplier = srcRect.height() / destRect.height();
srcRect.setWidth(destRect.width() * destToSrcMultiplier);
switch(aspectRatio->align()) {
case SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMIDYMIN:
case SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMIDYMID:
case SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMIDYMAX:
srcRect.setX(destRect.x() + image()->width() / 2.0f - srcRect.width() / 2.0f);
break;
case SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMAXYMIN:
case SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMAXYMID:
case SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_XMAXYMAX:
srcRect.setX(destRect.x() + image()->width() - srcRect.width());
break;
}
}
}
}
bool RenderSVGImage::calculateLocalTransform()
{
TransformationMatrix oldTransform = m_localTransform;
m_localTransform = static_cast<SVGStyledTransformableElement*>(element())->animatedLocalTransform();
return (m_localTransform != oldTransform);
}
void RenderSVGImage::layout()
{
ASSERT(needsLayout());
IntRect oldBounds;
IntRect oldOutlineBox;
bool checkForRepaint = checkForRepaintDuringLayout();
if (checkForRepaint) {
oldBounds = absoluteClippedOverflowRect();
oldOutlineBox = absoluteOutlineBounds();
}
calculateLocalTransform();
// minimum height
m_height = errorOccurred() ? intrinsicSize().height() : 0;
calcWidth();
calcHeight();
SVGImageElement* image = static_cast<SVGImageElement*>(node());
m_localBounds = FloatRect(image->x().value(image), image->y().value(image), image->width().value(image), image->height().value(image));
calculateAbsoluteBounds();
if (checkForRepaint)
repaintAfterLayoutIfNeeded(oldBounds, oldOutlineBox);
setNeedsLayout(false);
}
void RenderSVGImage::paint(PaintInfo& paintInfo, int, int)
{
if (paintInfo.context->paintingDisabled() || style()->visibility() == HIDDEN)
return;
paintInfo.context->save();
paintInfo.context->concatCTM(localTransform());
if (paintInfo.phase == PaintPhaseForeground) {
SVGResourceFilter* filter = 0;
PaintInfo savedInfo(paintInfo);
prepareToRenderSVGContent(this, paintInfo, m_localBounds, filter);
FloatRect destRect = m_localBounds;
FloatRect srcRect(0, 0, image()->width(), image()->height());
SVGImageElement* imageElt = static_cast<SVGImageElement*>(node());
if (imageElt->preserveAspectRatio()->align() != SVGPreserveAspectRatio::SVG_PRESERVEASPECTRATIO_NONE)
adjustRectsForAspectRatio(destRect, srcRect, imageElt->preserveAspectRatio());
paintInfo.context->drawImage(image(), destRect, srcRect);
finishRenderSVGContent(this, paintInfo, m_localBounds, filter, savedInfo.context);
}
paintInfo.context->restore();
}
bool RenderSVGImage::nodeAtPoint(const HitTestRequest&, HitTestResult& result, int _x, int _y, int, int, HitTestAction hitTestAction)
{
// We only draw in the forground phase, so we only hit-test then.
if (hitTestAction != HitTestForeground)
return false;
PointerEventsHitRules hitRules(PointerEventsHitRules::SVG_IMAGE_HITTESTING, style()->pointerEvents());
bool isVisible = (style()->visibility() == VISIBLE);
if (isVisible || !hitRules.requireVisible) {
double localX, localY;
absoluteTransform().inverse().map(_x, _y, &localX, &localY);
if (hitRules.canHitFill) {
if (m_localBounds.contains(narrowPrecisionToFloat(localX), narrowPrecisionToFloat(localY))) {
updateHitTestResult(result, IntPoint(_x, _y));
return true;
}
}
}
return false;
}
bool RenderSVGImage::requiresLayer()
{
return false;
}
FloatRect RenderSVGImage::relativeBBox(bool) const
{
return m_localBounds;
}
void RenderSVGImage::imageChanged(WrappedImagePtr image, const IntRect* rect)
{
RenderImage::imageChanged(image, rect);
// We override to invalidate a larger rect, since SVG images can draw outside their "bounds"
repaintRectangle(absoluteClippedOverflowRect());
}
void RenderSVGImage::calculateAbsoluteBounds()
{
// FIXME: broken with CSS transforms
FloatRect absoluteRect = absoluteTransform().mapRect(relativeBBox(true));
#if ENABLE(SVG_FILTERS)
// Filters can expand the bounding box
SVGResourceFilter* filter = getFilterById(document(), style()->svgStyle()->filter());
if (filter)
absoluteRect.unite(filter->filterBBoxForItemBBox(absoluteRect));
#endif
if (!absoluteRect.isEmpty())
absoluteRect.inflate(1); // inflate 1 pixel for antialiasing
m_absoluteBounds = enclosingIntRect(absoluteRect);
}
IntRect RenderSVGImage::absoluteClippedOverflowRect()
{
return m_absoluteBounds;
}
void RenderSVGImage::addFocusRingRects(GraphicsContext* graphicsContext, int, int)
{
// this is called from paint() after the localTransform has already been applied
IntRect contentRect = enclosingIntRect(relativeBBox());
graphicsContext->addFocusRingRect(contentRect);
}
void RenderSVGImage::absoluteRects(Vector<IntRect>& rects, int, int, bool)
{
rects.append(absoluteClippedOverflowRect());
}
void RenderSVGImage::absoluteQuads(Vector<FloatQuad>& quads, bool)
{
quads.append(FloatRect(absoluteClippedOverflowRect()));
}
}
#endif // ENABLE(SVG)
| lgpl-2.1 |
omniacreator/qtcreator | src/plugins/qmldesigner/designercore/model/modelnodepositionstorage.cpp | 3 | 2505 | /****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "modelnodepositionstorage.h"
using namespace QmlDesigner;
using namespace QmlDesigner::Internal;
void ModelNodePositionStorage::setNodeOffset(const ModelNode &modelNode, int fileOffset)
{
m_rewriterData[modelNode].setOffset(fileOffset);
}
void ModelNodePositionStorage::cleanupInvalidOffsets()
{
QHash<ModelNode, RewriterData> validModelNodes;
QHashIterator<ModelNode, RewriterData> iter(m_rewriterData);
while (iter.hasNext()) {
iter.next();
const ModelNode modelNode = iter.key();
if (modelNode.isValid())
validModelNodes.insert(modelNode, iter.value());
}
m_rewriterData = validModelNodes;
}
int ModelNodePositionStorage::nodeOffset(const ModelNode &modelNode)
{
QHash<ModelNode, RewriterData>::const_iterator iter = m_rewriterData.find(modelNode);
if (iter == m_rewriterData.end())
return INVALID_LOCATION;
else
return iter.value().offset();
}
QList<ModelNode> ModelNodePositionStorage::modelNodes() const
{
return m_rewriterData.keys();
}
| lgpl-2.1 |
danimo/qt-creator | src/plugins/qmldesigner/designercore/instances/nodeinstance.cpp | 4 | 16286 | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** 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 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "nodeinstance.h"
#include <QPainter>
#include <modelnode.h>
#include <QDebug>
QT_BEGIN_NAMESPACE
void qt_blurImage(QPainter *painter, QImage &blurImage, qreal radius, bool quality, bool alphaOnly, int transposed = 0);
QT_END_NAMESPACE
namespace QmlDesigner {
class ProxyNodeInstanceData
{
public:
ProxyNodeInstanceData()
: parentInstanceId(-1),
penWidth(1),
isAnchoredBySibling(false),
isAnchoredByChildren(false),
hasContent(false),
isMovable(false),
isResizable(false),
isInLayoutable(false),
directUpdates(false)
{}
qint32 parentInstanceId;
ModelNode modelNode;
QRectF boundingRect;
QRectF contentItemBoundingRect;
QPointF position;
QSizeF size;
QTransform transform;
QTransform contentTransform;
QTransform contentItemTransform;
QTransform sceneTransform;
int penWidth;
bool isAnchoredBySibling;
bool isAnchoredByChildren;
bool hasContent;
bool isMovable;
bool isResizable;
bool isInLayoutable;
bool directUpdates;
QHash<PropertyName, QVariant> propertyValues;
QHash<PropertyName, bool> hasBindingForProperty;
QHash<PropertyName, bool> hasAnchors;
QHash<PropertyName, TypeName> instanceTypes;
QPixmap renderPixmap;
QPixmap blurredRenderPixmap;
QHash<PropertyName, QPair<PropertyName, qint32> > anchors;
};
NodeInstance::NodeInstance()
{
}
NodeInstance::NodeInstance(ProxyNodeInstanceData *dPointer)
: d(dPointer)
{
}
NodeInstance NodeInstance::create(const ModelNode &node)
{
ProxyNodeInstanceData *d = new ProxyNodeInstanceData;
d->modelNode = node;
return NodeInstance(d);
}
NodeInstance::~NodeInstance()
{
}
NodeInstance::NodeInstance(const NodeInstance &other)
: d(other.d)
{
}
NodeInstance &NodeInstance::operator=(const NodeInstance &other)
{
d = other.d;
return *this;
}
ModelNode NodeInstance::modelNode() const
{
if (d)
return d->modelNode;
else
return ModelNode();
}
qint32 NodeInstance::instanceId() const
{
if (d)
return d->modelNode.internalId();
else
return -1;
}
void NodeInstance::setDirectUpdate(bool directUpdates)
{
if (d)
d->directUpdates = directUpdates;
}
bool NodeInstance::directUpdates() const
{
if (d)
return d->directUpdates && !(d->transform.isRotating() || d->transform.isScaling() || hasAnchors());
else
return true;
}
void NodeInstance::setX(double x)
{
if (d && directUpdates()) {
double dx = x - d->transform.dx();
d->transform.translate(dx, 0.0);
}
}
void NodeInstance::setY(double y)
{
if (d && directUpdates()) {
double dy = y - d->transform.dy();
d->transform.translate(0.0, dy);
}
}
bool NodeInstance::hasAnchors() const
{
return hasAnchor("anchors.fill")
|| hasAnchor("anchors.centerIn")
|| hasAnchor("anchors.top")
|| hasAnchor("anchors.left")
|| hasAnchor("anchors.right")
|| hasAnchor("anchors.bottom")
|| hasAnchor("anchors.horizontalCenter")
|| hasAnchor("anchors.verticalCenter")
|| hasAnchor("anchors.baseline");
}
bool NodeInstance::isValid() const
{
return instanceId() >= 0 && modelNode().isValid();
}
void NodeInstance::makeInvalid()
{
if (d)
d->modelNode = ModelNode();
}
QRectF NodeInstance::boundingRect() const
{
if (isValid())
return d->boundingRect;
else
return QRectF();
}
QRectF NodeInstance::contentItemBoundingRect() const
{
if (isValid())
return d->contentItemBoundingRect;
else
return QRectF();
}
bool NodeInstance::hasContent() const
{
if (isValid())
return d->hasContent;
else
return false;
}
bool NodeInstance::isAnchoredBySibling() const
{
if (isValid())
return d->isAnchoredBySibling;
else
return false;
}
bool NodeInstance::isAnchoredByChildren() const
{
if (isValid())
return d->isAnchoredByChildren;
else
return false;
}
bool NodeInstance::isMovable() const
{
if (isValid())
return d->isMovable;
else
return false;
}
bool NodeInstance::isResizable() const
{
if (isValid())
return d->isResizable;
else
return false;
}
QTransform NodeInstance::transform() const
{
if (isValid())
return d->transform;
else
return QTransform();
}
QTransform NodeInstance::contentTransform() const
{
if (isValid())
return d->contentTransform;
else
return QTransform();
}
QTransform NodeInstance::contentItemTransform() const
{
if (isValid())
return d->contentItemTransform;
else
return QTransform();
}
QTransform NodeInstance::sceneTransform() const
{
if (isValid())
return d->sceneTransform;
else
return QTransform();
}
bool NodeInstance::isInLayoutable() const
{
if (isValid())
return d->isInLayoutable;
else
return false;
}
QPointF NodeInstance::position() const
{
if (isValid())
return d->position;
else
return QPointF();
}
QSizeF NodeInstance::size() const
{
if (isValid())
return d->size;
else
return QSizeF();
}
int NodeInstance::penWidth() const
{
if (isValid())
return d->penWidth;
else
return 1;
}
QVariant NodeInstance::property(const PropertyName &name) const
{
if (isValid())
return d->propertyValues.value(name);
return QVariant();
}
bool NodeInstance::hasProperty(const PropertyName &name) const
{
if (isValid())
return d->propertyValues.contains(name);
return false;
}
bool NodeInstance::hasBindingForProperty(const PropertyName &name) const
{
if (isValid())
return d->hasBindingForProperty.value(name, false);
return false;
}
TypeName NodeInstance::instanceType(const PropertyName &name) const
{
if (isValid())
return d->instanceTypes.value(name);
return TypeName();
}
qint32 NodeInstance::parentId() const
{
if (isValid())
return d->parentInstanceId;
else
return false;
}
bool NodeInstance::hasAnchor(const PropertyName &name) const
{
if (isValid())
return d->hasAnchors.value(name, false);
return false;
}
QPair<PropertyName, qint32> NodeInstance::anchor(const PropertyName &name) const
{
if (isValid())
return d->anchors.value(name, QPair<PropertyName, qint32>(PropertyName(), qint32(-1)));
return QPair<PropertyName, qint32>(PropertyName(), -1);
}
void NodeInstance::setProperty(const PropertyName &name, const QVariant &value)
{
d->propertyValues.insert(name, value);
}
QPixmap NodeInstance::renderPixmap() const
{
return d->renderPixmap;
}
QPixmap NodeInstance::blurredRenderPixmap() const
{
if (d->blurredRenderPixmap.isNull()) {
d->blurredRenderPixmap = QPixmap(d->renderPixmap.size());
QPainter blurPainter(&d->blurredRenderPixmap);
QImage renderImage = d->renderPixmap.toImage();
qt_blurImage(&blurPainter, renderImage, 8.0, false, false);
}
return d->blurredRenderPixmap;
}
void NodeInstance::setRenderPixmap(const QImage &image)
{
d->renderPixmap = QPixmap::fromImage(image);
d->blurredRenderPixmap = QPixmap();
}
void NodeInstance::setParentId(qint32 instanceId)
{
d->parentInstanceId = instanceId;
}
InformationName NodeInstance::setInformationSize(const QSizeF &size)
{
if (d->size != size) {
d->size = size;
return Size;
}
return NoInformationChange;
}
InformationName NodeInstance::setInformationBoundingRect(const QRectF &rectangle)
{
if (d->boundingRect != rectangle) {
d->boundingRect = rectangle;
return BoundingRect;
}
return NoInformationChange;
}
InformationName NodeInstance::setInformationContentItemBoundingRect(const QRectF &rectangle)
{
if (d->contentItemBoundingRect != rectangle) {
d->contentItemBoundingRect = rectangle;
return ContentItemBoundingRect;
}
return NoInformationChange;
}
InformationName NodeInstance::setInformationTransform(const QTransform &transform)
{
if (!directUpdates() && d->transform != transform) {
d->transform = transform;
return Transform;
}
return NoInformationChange;
}
InformationName NodeInstance::setInformationContentTransform(const QTransform &contentTransform)
{
if (d->contentTransform != contentTransform) {
d->contentTransform = contentTransform;
return ContentTransform;
}
return NoInformationChange;
}
InformationName NodeInstance::setInformationContentItemTransform(const QTransform &contentItemTransform)
{
if (d->contentItemTransform != contentItemTransform) {
d->contentItemTransform = contentItemTransform;
return ContentItemTransform;
}
return NoInformationChange;
}
InformationName NodeInstance::setInformationPenWith(int penWidth)
{
if (d->penWidth != penWidth) {
d->penWidth = penWidth;
return PenWidth;
}
return NoInformationChange;
}
InformationName NodeInstance::setInformationPosition(const QPointF &position)
{
if (d->position != position) {
d->position = position;
return Position;
}
return NoInformationChange;
}
InformationName NodeInstance::setInformationIsInLayoutable(bool isInLayoutable)
{
if (d->isInLayoutable != isInLayoutable) {
d->isInLayoutable = isInLayoutable;
return IsInLayoutable;
}
return NoInformationChange;
}
InformationName NodeInstance::setInformationSceneTransform(const QTransform &sceneTransform)
{
if (d->sceneTransform != sceneTransform) {
d->sceneTransform = sceneTransform;
if (!directUpdates())
return SceneTransform;
}
return NoInformationChange;
}
InformationName NodeInstance::setInformationIsResizable(bool isResizable)
{
if (d->isResizable != isResizable) {
d->isResizable = isResizable;
return IsResizable;
}
return NoInformationChange;
}
InformationName NodeInstance::setInformationIsMovable(bool isMovable)
{
if (d->isMovable != isMovable) {
d->isMovable = isMovable;
return IsMovable;
}
return NoInformationChange;
}
InformationName NodeInstance::setInformationIsAnchoredByChildren(bool isAnchoredByChildren)
{
if (d->isAnchoredByChildren != isAnchoredByChildren) {
d->isAnchoredByChildren = isAnchoredByChildren;
return IsAnchoredByChildren;
}
return NoInformationChange;
}
InformationName NodeInstance::setInformationIsAnchoredBySibling(bool isAnchoredBySibling)
{
if (d->isAnchoredBySibling != isAnchoredBySibling) {
d->isAnchoredBySibling = isAnchoredBySibling;
return IsAnchoredBySibling;
}
return NoInformationChange;
}
InformationName NodeInstance::setInformationHasContent(bool hasContent)
{
if (d->hasContent != hasContent) {
d->hasContent = hasContent;
return HasContent;
}
return NoInformationChange;
}
InformationName NodeInstance::setInformationHasAnchor(const PropertyName &sourceAnchorLine, bool hasAnchor)
{
if (d->hasAnchors.value(sourceAnchorLine) != hasAnchor) {
d->hasAnchors.insert(sourceAnchorLine, hasAnchor);
return HasAnchor;
}
return NoInformationChange;
}
InformationName NodeInstance::setInformationAnchor(const PropertyName &sourceAnchorLine, const PropertyName &targetAnchorLine, qint32 targetInstanceId)
{
QPair<PropertyName, qint32> anchorPair = QPair<PropertyName, qint32>(targetAnchorLine, targetInstanceId);
if (d->anchors.value(sourceAnchorLine) != anchorPair) {
d->anchors.insert(sourceAnchorLine, anchorPair);
return Anchor;
}
return NoInformationChange;
}
InformationName NodeInstance::setInformationInstanceTypeForProperty(const PropertyName &property, const TypeName &type)
{
if (d->instanceTypes.value(property) != type) {
d->instanceTypes.insert(property, type);
return InstanceTypeForProperty;
}
return NoInformationChange;
}
InformationName NodeInstance::setInformationHasBindingForProperty(const PropertyName &property, bool hasProperty)
{
if (d->hasBindingForProperty.value(property) != hasProperty) {
d->hasBindingForProperty.insert(property, hasProperty);
return HasBindingForProperty;
}
return NoInformationChange;
}
InformationName NodeInstance::setInformation(InformationName name, const QVariant &information, const QVariant &secondInformation, const QVariant &thirdInformation)
{
switch (name) {
case Size: return setInformationSize(information.toSizeF());
case BoundingRect: return setInformationBoundingRect(information.toRectF());
case ContentItemBoundingRect: return setInformationContentItemBoundingRect(information.toRectF());
case Transform: return setInformationTransform(information.value<QTransform>());
case ContentTransform: return setInformationContentTransform(information.value<QTransform>());
case ContentItemTransform: return setInformationContentItemTransform(information.value<QTransform>());
case PenWidth: return setInformationPenWith(information.toInt());
case Position: return setInformationPosition(information.toPointF());
case IsInLayoutable: return setInformationIsInLayoutable(information.toBool());
case SceneTransform: return setInformationSceneTransform(information.value<QTransform>());
case IsResizable: return setInformationIsResizable(information.toBool());
case IsMovable: return setInformationIsMovable(information.toBool());
case IsAnchoredByChildren: return setInformationIsAnchoredByChildren(information.toBool());
case IsAnchoredBySibling: return setInformationIsAnchoredBySibling(information.toBool());
case HasContent: return setInformationHasContent(information.toBool());
case HasAnchor: return setInformationHasAnchor(information.toByteArray(), secondInformation.toBool());break;
case Anchor: return setInformationAnchor(information.toByteArray(), secondInformation.toByteArray(), thirdInformation.value<qint32>());
case InstanceTypeForProperty: return setInformationInstanceTypeForProperty(information.toByteArray(), secondInformation.toByteArray());
case HasBindingForProperty: return setInformationHasBindingForProperty(information.toByteArray(), secondInformation.toBool());
case NoName:
default: break;
}
return NoInformationChange;
}
bool operator ==(const NodeInstance &first, const NodeInstance &second)
{
return first.instanceId() >= 0 && first.instanceId() == second.instanceId();
}
}
| lgpl-2.1 |
unakatsuo/multipath-tools | kpartx/unixware.c | 5 | 2733 | #include "kpartx.h"
#include <stdio.h>
#define UNIXWARE_FS_UNUSED 0
#define UNIXWARE_NUMSLICE 16
#define UNIXWARE_DISKMAGIC (0xCA5E600D)
#define UNIXWARE_DISKMAGIC2 (0x600DDEEE)
struct unixware_slice {
unsigned short s_label; /* label */
unsigned short s_flags; /* permission flags */
unsigned int start_sect; /* starting sector */
unsigned int nr_sects; /* number of sectors in slice */
};
struct unixware_disklabel {
unsigned int d_type; /* drive type */
unsigned char d_magic[4]; /* the magic number */
unsigned int d_version; /* version number */
char d_serial[12]; /* serial number of the device */
unsigned int d_ncylinders; /* # of data cylinders per device */
unsigned int d_ntracks; /* # of tracks per cylinder */
unsigned int d_nsectors; /* # of data sectors per track */
unsigned int d_secsize; /* # of bytes per sector */
unsigned int d_part_start; /* # of first sector of this partition */
unsigned int d_unknown1[12]; /* ? */
unsigned int d_alt_tbl; /* byte offset of alternate table */
unsigned int d_alt_len; /* byte length of alternate table */
unsigned int d_phys_cyl; /* # of physical cylinders per device */
unsigned int d_phys_trk; /* # of physical tracks per cylinder */
unsigned int d_phys_sec; /* # of physical sectors per track */
unsigned int d_phys_bytes; /* # of physical bytes per sector */
unsigned int d_unknown2; /* ? */
unsigned int d_unknown3; /* ? */
unsigned int d_pad[8]; /* pad */
struct unixware_vtoc {
unsigned char v_magic[4]; /* the magic number */
unsigned int v_version; /* version number */
char v_name[8]; /* volume name */
unsigned short v_nslices; /* # of slices */
unsigned short v_unknown1; /* ? */
unsigned int v_reserved[10]; /* reserved */
struct unixware_slice
v_slice[UNIXWARE_NUMSLICE]; /* slice headers */
} vtoc;
}; /* 408 */
int
read_unixware_pt(int fd, struct slice all, struct slice *sp, int ns) {
struct unixware_disklabel *l;
struct unixware_slice *p;
unsigned int offset = all.start;
char *bp;
int n = 0;
bp = getblock(fd, offset+29); /* 1 sector suffices */
if (bp == NULL)
return -1;
l = (struct unixware_disklabel *) bp;
if (four2int(l->d_magic) != UNIXWARE_DISKMAGIC ||
four2int(l->vtoc.v_magic) != UNIXWARE_DISKMAGIC2)
return -1;
p = &l->vtoc.v_slice[1]; /* slice 0 is the whole disk. */
while (p - &l->vtoc.v_slice[0] < UNIXWARE_NUMSLICE) {
if (p->s_label == UNIXWARE_FS_UNUSED)
/* nothing */;
else if (n < ns) {
sp[n].start = p->start_sect;
sp[n].size = p->nr_sects;
n++;
} else {
fprintf(stderr,
"unixware_partition: too many slices\n");
break;
}
p++;
}
return n;
}
| lgpl-2.1 |
chipx86/gtk | modules/engines/pixbuf/pixbuf-draw.c | 6 | 31007 | /* GTK+ Pixbuf Engine
* Copyright (C) 1998-2000 Red Hat, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*
* Written by Owen Taylor <otaylor@redhat.com>, based on code by
* Carsten Haitzler <raster@rasterman.com>
*/
#include <math.h>
#include <string.h>
#undef GDK_DISABLE_DEPRECATED
#include "pixbuf.h"
#include "pixbuf-rc-style.h"
#include "pixbuf-style.h"
static void pixbuf_style_init (PixbufStyle *style);
static void pixbuf_style_class_init (PixbufStyleClass *klass);
static GtkStyleClass *parent_class = NULL;
static ThemeImage *
match_theme_image (GtkStyle *style,
ThemeMatchData *match_data)
{
GList *tmp_list;
tmp_list = PIXBUF_RC_STYLE (style->rc_style)->img_list;
while (tmp_list)
{
guint flags;
ThemeImage *image = tmp_list->data;
tmp_list = tmp_list->next;
if (match_data->function != image->match_data.function)
continue;
flags = match_data->flags & image->match_data.flags;
if (flags != image->match_data.flags) /* Required components not present */
continue;
if ((flags & THEME_MATCH_STATE) &&
match_data->state != image->match_data.state)
continue;
if ((flags & THEME_MATCH_SHADOW) &&
match_data->shadow != image->match_data.shadow)
continue;
if ((flags & THEME_MATCH_ARROW_DIRECTION) &&
match_data->arrow_direction != image->match_data.arrow_direction)
continue;
if ((flags & THEME_MATCH_ORIENTATION) &&
match_data->orientation != image->match_data.orientation)
continue;
if ((flags & THEME_MATCH_GAP_SIDE) &&
match_data->gap_side != image->match_data.gap_side)
continue;
if ((flags & THEME_MATCH_EXPANDER_STYLE) &&
match_data->expander_style != image->match_data.expander_style)
continue;
if ((flags & THEME_MATCH_WINDOW_EDGE) &&
match_data->window_edge != image->match_data.window_edge)
continue;
if (image->match_data.detail &&
(!match_data->detail ||
strcmp (match_data->detail, image->match_data.detail) != 0))
continue;
return image;
}
return NULL;
}
static gboolean
draw_simple_image(GtkStyle *style,
GdkWindow *window,
GdkRectangle *area,
GtkWidget *widget,
ThemeMatchData *match_data,
gboolean draw_center,
gboolean allow_setbg,
gint x,
gint y,
gint width,
gint height)
{
ThemeImage *image;
if ((width == -1) && (height == -1))
gdk_drawable_get_size(window, &width, &height);
else if (width == -1)
gdk_drawable_get_size(window, &width, NULL);
else if (height == -1)
gdk_drawable_get_size(window, NULL, &height);
if (!(match_data->flags & THEME_MATCH_ORIENTATION))
{
match_data->flags |= THEME_MATCH_ORIENTATION;
if (height > width)
match_data->orientation = GTK_ORIENTATION_VERTICAL;
else
match_data->orientation = GTK_ORIENTATION_HORIZONTAL;
}
image = match_theme_image (style, match_data);
if (image)
{
if (image->background)
{
theme_pixbuf_render (image->background,
window, NULL, area,
draw_center ? COMPONENT_ALL : COMPONENT_ALL | COMPONENT_CENTER,
FALSE,
x, y, width, height);
}
if (image->overlay && draw_center)
theme_pixbuf_render (image->overlay,
window, NULL, area, COMPONENT_ALL,
TRUE,
x, y, width, height);
return TRUE;
}
else
return FALSE;
}
static gboolean
draw_gap_image(GtkStyle *style,
GdkWindow *window,
GdkRectangle *area,
GtkWidget *widget,
ThemeMatchData *match_data,
gboolean draw_center,
gint x,
gint y,
gint width,
gint height,
GtkPositionType gap_side,
gint gap_x,
gint gap_width)
{
ThemeImage *image;
if ((width == -1) && (height == -1))
gdk_drawable_get_size(window, &width, &height);
else if (width == -1)
gdk_drawable_get_size(window, &width, NULL);
else if (height == -1)
gdk_drawable_get_size(window, NULL, &height);
if (!(match_data->flags & THEME_MATCH_ORIENTATION))
{
match_data->flags |= THEME_MATCH_ORIENTATION;
if (height > width)
match_data->orientation = GTK_ORIENTATION_VERTICAL;
else
match_data->orientation = GTK_ORIENTATION_HORIZONTAL;
}
match_data->flags |= THEME_MATCH_GAP_SIDE;
match_data->gap_side = gap_side;
image = match_theme_image (style, match_data);
if (image)
{
gint thickness;
GdkRectangle r1, r2, r3;
GdkPixbuf *pixbuf = NULL;
guint components = COMPONENT_ALL;
if (!draw_center)
components |= COMPONENT_CENTER;
if (image->gap_start)
pixbuf = theme_pixbuf_get_pixbuf (image->gap_start);
switch (gap_side)
{
case GTK_POS_TOP:
if (pixbuf)
thickness = gdk_pixbuf_get_height (pixbuf);
else
thickness = style->ythickness;
if (!draw_center)
components |= COMPONENT_NORTH_WEST | COMPONENT_NORTH | COMPONENT_NORTH_EAST;
r1.x = x;
r1.y = y;
r1.width = gap_x;
r1.height = thickness;
r2.x = x + gap_x;
r2.y = y;
r2.width = gap_width;
r2.height = thickness;
r3.x = x + gap_x + gap_width;
r3.y = y;
r3.width = width - (gap_x + gap_width);
r3.height = thickness;
break;
case GTK_POS_BOTTOM:
if (pixbuf)
thickness = gdk_pixbuf_get_height (pixbuf);
else
thickness = style->ythickness;
if (!draw_center)
components |= COMPONENT_SOUTH_WEST | COMPONENT_SOUTH | COMPONENT_SOUTH_EAST;
r1.x = x;
r1.y = y + height - thickness;
r1.width = gap_x;
r1.height = thickness;
r2.x = x + gap_x;
r2.y = y + height - thickness;
r2.width = gap_width;
r2.height = thickness;
r3.x = x + gap_x + gap_width;
r3.y = y + height - thickness;
r3.width = width - (gap_x + gap_width);
r3.height = thickness;
break;
case GTK_POS_LEFT:
if (pixbuf)
thickness = gdk_pixbuf_get_width (pixbuf);
else
thickness = style->xthickness;
if (!draw_center)
components |= COMPONENT_NORTH_WEST | COMPONENT_WEST | COMPONENT_SOUTH_WEST;
r1.x = x;
r1.y = y;
r1.width = thickness;
r1.height = gap_x;
r2.x = x;
r2.y = y + gap_x;
r2.width = thickness;
r2.height = gap_width;
r3.x = x;
r3.y = y + gap_x + gap_width;
r3.width = thickness;
r3.height = height - (gap_x + gap_width);
break;
case GTK_POS_RIGHT:
if (pixbuf)
thickness = gdk_pixbuf_get_width (pixbuf);
else
thickness = style->xthickness;
if (!draw_center)
components |= COMPONENT_NORTH_EAST | COMPONENT_EAST | COMPONENT_SOUTH_EAST;
r1.x = x + width - thickness;
r1.y = y;
r1.width = thickness;
r1.height = gap_x;
r2.x = x + width - thickness;
r2.y = y + gap_x;
r2.width = thickness;
r2.height = gap_width;
r3.x = x + width - thickness;
r3.y = y + gap_x + gap_width;
r3.width = thickness;
r3.height = height - (gap_x + gap_width);
break;
default:
g_assert_not_reached ();
}
if (image->background)
theme_pixbuf_render (image->background,
window, NULL, area, components, FALSE,
x, y, width, height);
if (image->gap_start)
theme_pixbuf_render (image->gap_start,
window, NULL, area, COMPONENT_ALL, FALSE,
r1.x, r1.y, r1.width, r1.height);
if (image->gap)
theme_pixbuf_render (image->gap,
window, NULL, area, COMPONENT_ALL, FALSE,
r2.x, r2.y, r2.width, r2.height);
if (image->gap_end)
theme_pixbuf_render (image->gap_end,
window, NULL, area, COMPONENT_ALL, FALSE,
r3.x, r3.y, r3.width, r3.height);
return TRUE;
}
else
return FALSE;
}
static void
draw_hline (GtkStyle *style,
GdkWindow *window,
GtkStateType state,
GdkRectangle *area,
GtkWidget *widget,
const gchar *detail,
gint x1,
gint x2,
gint y)
{
ThemeImage *image;
ThemeMatchData match_data;
g_return_if_fail(style != NULL);
g_return_if_fail(window != NULL);
match_data.function = TOKEN_D_HLINE;
match_data.detail = (gchar *)detail;
match_data.flags = THEME_MATCH_ORIENTATION | THEME_MATCH_STATE;
match_data.state = state;
match_data.orientation = GTK_ORIENTATION_HORIZONTAL;
image = match_theme_image (style, &match_data);
if (image)
{
if (image->background)
theme_pixbuf_render (image->background,
window, NULL, area, COMPONENT_ALL, FALSE,
x1, y, (x2 - x1) + 1, 2);
}
else
parent_class->draw_hline (style, window, state, area, widget, detail,
x1, x2, y);
}
static void
draw_vline (GtkStyle *style,
GdkWindow *window,
GtkStateType state,
GdkRectangle *area,
GtkWidget *widget,
const gchar *detail,
gint y1,
gint y2,
gint x)
{
ThemeImage *image;
ThemeMatchData match_data;
g_return_if_fail (style != NULL);
g_return_if_fail (window != NULL);
match_data.function = TOKEN_D_VLINE;
match_data.detail = (gchar *)detail;
match_data.flags = THEME_MATCH_ORIENTATION | THEME_MATCH_STATE;
match_data.state = state;
match_data.orientation = GTK_ORIENTATION_VERTICAL;
image = match_theme_image (style, &match_data);
if (image)
{
if (image->background)
theme_pixbuf_render (image->background,
window, NULL, area, COMPONENT_ALL, FALSE,
x, y1, 2, (y2 - y1) + 1);
}
else
parent_class->draw_vline (style, window, state, area, widget, detail,
y1, y2, x);
}
static void
draw_shadow(GtkStyle *style,
GdkWindow *window,
GtkStateType state,
GtkShadowType shadow,
GdkRectangle *area,
GtkWidget *widget,
const gchar *detail,
gint x,
gint y,
gint width,
gint height)
{
ThemeMatchData match_data;
g_return_if_fail(style != NULL);
g_return_if_fail(window != NULL);
match_data.function = TOKEN_D_SHADOW;
match_data.detail = (gchar *)detail;
match_data.flags = THEME_MATCH_SHADOW | THEME_MATCH_STATE;
match_data.shadow = shadow;
match_data.state = state;
if (!draw_simple_image (style, window, area, widget, &match_data, FALSE, FALSE,
x, y, width, height))
parent_class->draw_shadow (style, window, state, shadow, area, widget, detail,
x, y, width, height);
}
/* This function makes up for some brokeness in gtkrange.c
* where we never get the full arrow of the stepper button
* and the type of button in a single drawing function.
*
* It doesn't work correctly when the scrollbar is squished
* to the point we don't have room for full-sized steppers.
*/
static void
reverse_engineer_stepper_box (GtkWidget *range,
GtkArrowType arrow_type,
gint *x,
gint *y,
gint *width,
gint *height)
{
gint slider_width = 14, stepper_size = 14;
gint box_width;
gint box_height;
if (range && GTK_IS_RANGE (range))
{
gtk_widget_style_get (range,
"slider_width", &slider_width,
"stepper_size", &stepper_size,
NULL);
}
if (arrow_type == GTK_ARROW_UP || arrow_type == GTK_ARROW_DOWN)
{
box_width = slider_width;
box_height = stepper_size;
}
else
{
box_width = stepper_size;
box_height = slider_width;
}
*x = *x - (box_width - *width) / 2;
*y = *y - (box_height - *height) / 2;
*width = box_width;
*height = box_height;
}
static void
draw_arrow (GtkStyle *style,
GdkWindow *window,
GtkStateType state,
GtkShadowType shadow,
GdkRectangle *area,
GtkWidget *widget,
const gchar *detail,
GtkArrowType arrow_direction,
gint fill,
gint x,
gint y,
gint width,
gint height)
{
ThemeMatchData match_data;
g_return_if_fail(style != NULL);
g_return_if_fail(window != NULL);
if (detail &&
(strcmp (detail, "hscrollbar") == 0 || strcmp (detail, "vscrollbar") == 0))
{
/* This is a hack to work around the fact that scrollbar steppers are drawn
* as a box + arrow, so we never have
*
* The full bounding box of the scrollbar
* The arrow direction
*
* At the same time. We simulate an extra paint function, "STEPPER", by doing
* nothing for the box, and then here, reverse engineering the box that
* was passed to draw box and using that
*/
gint box_x = x;
gint box_y = y;
gint box_width = width;
gint box_height = height;
reverse_engineer_stepper_box (widget, arrow_direction,
&box_x, &box_y, &box_width, &box_height);
match_data.function = TOKEN_D_STEPPER;
match_data.detail = (gchar *)detail;
match_data.flags = (THEME_MATCH_SHADOW |
THEME_MATCH_STATE |
THEME_MATCH_ARROW_DIRECTION);
match_data.shadow = shadow;
match_data.state = state;
match_data.arrow_direction = arrow_direction;
if (draw_simple_image (style, window, area, widget, &match_data, TRUE, TRUE,
box_x, box_y, box_width, box_height))
{
/* The theme included stepper images, we're done */
return;
}
/* Otherwise, draw the full box, and fall through to draw the arrow
*/
match_data.function = TOKEN_D_BOX;
match_data.detail = (gchar *)detail;
match_data.flags = THEME_MATCH_SHADOW | THEME_MATCH_STATE;
match_data.shadow = shadow;
match_data.state = state;
if (!draw_simple_image (style, window, area, widget, &match_data, TRUE, TRUE,
box_x, box_y, box_width, box_height))
parent_class->draw_box (style, window, state, shadow, area, widget, detail,
box_x, box_y, box_width, box_height);
}
match_data.function = TOKEN_D_ARROW;
match_data.detail = (gchar *)detail;
match_data.flags = (THEME_MATCH_SHADOW |
THEME_MATCH_STATE |
THEME_MATCH_ARROW_DIRECTION);
match_data.shadow = shadow;
match_data.state = state;
match_data.arrow_direction = arrow_direction;
if (!draw_simple_image (style, window, area, widget, &match_data, TRUE, TRUE,
x, y, width, height))
parent_class->draw_arrow (style, window, state, shadow, area, widget, detail,
arrow_direction, fill, x, y, width, height);
}
static void
draw_diamond (GtkStyle *style,
GdkWindow *window,
GtkStateType state,
GtkShadowType shadow,
GdkRectangle *area,
GtkWidget *widget,
const gchar *detail,
gint x,
gint y,
gint width,
gint height)
{
ThemeMatchData match_data;
g_return_if_fail(style != NULL);
g_return_if_fail(window != NULL);
match_data.function = TOKEN_D_DIAMOND;
match_data.detail = (gchar *)detail;
match_data.flags = THEME_MATCH_SHADOW | THEME_MATCH_STATE;
match_data.shadow = shadow;
match_data.state = state;
if (!draw_simple_image (style, window, area, widget, &match_data, TRUE, TRUE,
x, y, width, height))
parent_class->draw_diamond (style, window, state, shadow, area, widget, detail,
x, y, width, height);
}
static void
draw_string (GtkStyle * style,
GdkWindow * window,
GtkStateType state,
GdkRectangle * area,
GtkWidget * widget,
const gchar *detail,
gint x,
gint y,
const gchar * string)
{
g_return_if_fail(style != NULL);
g_return_if_fail(window != NULL);
if (state == GTK_STATE_INSENSITIVE)
{
if (area)
{
gdk_gc_set_clip_rectangle(style->white_gc, area);
gdk_gc_set_clip_rectangle(style->fg_gc[state], area);
}
gdk_draw_string(window, gtk_style_get_font (style), style->fg_gc[state], x, y, string);
if (area)
{
gdk_gc_set_clip_rectangle(style->white_gc, NULL);
gdk_gc_set_clip_rectangle(style->fg_gc[state], NULL);
}
}
else
{
gdk_gc_set_clip_rectangle(style->fg_gc[state], area);
gdk_draw_string(window, gtk_style_get_font (style), style->fg_gc[state], x, y, string);
gdk_gc_set_clip_rectangle(style->fg_gc[state], NULL);
}
}
static void
draw_box (GtkStyle *style,
GdkWindow *window,
GtkStateType state,
GtkShadowType shadow,
GdkRectangle *area,
GtkWidget *widget,
const gchar *detail,
gint x,
gint y,
gint width,
gint height)
{
ThemeMatchData match_data;
g_return_if_fail(style != NULL);
g_return_if_fail(window != NULL);
if (detail &&
(strcmp (detail, "hscrollbar") == 0 || strcmp (detail, "vscrollbar") == 0))
{
/* We handle this in draw_arrow */
return;
}
match_data.function = TOKEN_D_BOX;
match_data.detail = (gchar *)detail;
match_data.flags = THEME_MATCH_SHADOW | THEME_MATCH_STATE;
match_data.shadow = shadow;
match_data.state = state;
if (!draw_simple_image (style, window, area, widget, &match_data, TRUE, TRUE,
x, y, width, height)) {
parent_class->draw_box (style, window, state, shadow, area, widget, detail,
x, y, width, height);
}
}
static void
draw_flat_box (GtkStyle *style,
GdkWindow *window,
GtkStateType state,
GtkShadowType shadow,
GdkRectangle *area,
GtkWidget *widget,
const gchar *detail,
gint x,
gint y,
gint width,
gint height)
{
ThemeMatchData match_data;
g_return_if_fail(style != NULL);
g_return_if_fail(window != NULL);
match_data.function = TOKEN_D_FLAT_BOX;
match_data.detail = (gchar *)detail;
match_data.flags = THEME_MATCH_SHADOW | THEME_MATCH_STATE;
match_data.shadow = shadow;
match_data.state = state;
if (!draw_simple_image (style, window, area, widget, &match_data, TRUE, TRUE,
x, y, width, height))
parent_class->draw_flat_box (style, window, state, shadow, area, widget, detail,
x, y, width, height);
}
static void
draw_check (GtkStyle *style,
GdkWindow *window,
GtkStateType state,
GtkShadowType shadow,
GdkRectangle *area,
GtkWidget *widget,
const gchar *detail,
gint x,
gint y,
gint width,
gint height)
{
ThemeMatchData match_data;
g_return_if_fail(style != NULL);
g_return_if_fail(window != NULL);
match_data.function = TOKEN_D_CHECK;
match_data.detail = (gchar *)detail;
match_data.flags = THEME_MATCH_SHADOW | THEME_MATCH_STATE;
match_data.shadow = shadow;
match_data.state = state;
if (!draw_simple_image (style, window, area, widget, &match_data, TRUE, TRUE,
x, y, width, height))
parent_class->draw_check (style, window, state, shadow, area, widget, detail,
x, y, width, height);
}
static void
draw_option (GtkStyle *style,
GdkWindow *window,
GtkStateType state,
GtkShadowType shadow,
GdkRectangle *area,
GtkWidget *widget,
const gchar *detail,
gint x,
gint y,
gint width,
gint height)
{
ThemeMatchData match_data;
g_return_if_fail(style != NULL);
g_return_if_fail(window != NULL);
match_data.function = TOKEN_D_OPTION;
match_data.detail = (gchar *)detail;
match_data.flags = THEME_MATCH_SHADOW | THEME_MATCH_STATE;
match_data.shadow = shadow;
match_data.state = state;
if (!draw_simple_image (style, window, area, widget, &match_data, TRUE, TRUE,
x, y, width, height))
parent_class->draw_option (style, window, state, shadow, area, widget, detail,
x, y, width, height);
}
static void
draw_tab (GtkStyle *style,
GdkWindow *window,
GtkStateType state,
GtkShadowType shadow,
GdkRectangle *area,
GtkWidget *widget,
const gchar *detail,
gint x,
gint y,
gint width,
gint height)
{
ThemeMatchData match_data;
g_return_if_fail(style != NULL);
g_return_if_fail(window != NULL);
match_data.function = TOKEN_D_TAB;
match_data.detail = (gchar *)detail;
match_data.flags = THEME_MATCH_SHADOW | THEME_MATCH_STATE;
match_data.shadow = shadow;
match_data.state = state;
if (!draw_simple_image (style, window, area, widget, &match_data, TRUE, TRUE,
x, y, width, height))
parent_class->draw_tab (style, window, state, shadow, area, widget, detail,
x, y, width, height);
}
static void
draw_shadow_gap (GtkStyle *style,
GdkWindow *window,
GtkStateType state,
GtkShadowType shadow,
GdkRectangle *area,
GtkWidget *widget,
const gchar *detail,
gint x,
gint y,
gint width,
gint height,
GtkPositionType gap_side,
gint gap_x,
gint gap_width)
{
ThemeMatchData match_data;
match_data.function = TOKEN_D_SHADOW_GAP;
match_data.detail = (gchar *)detail;
match_data.flags = THEME_MATCH_SHADOW | THEME_MATCH_STATE;
match_data.flags = (THEME_MATCH_SHADOW |
THEME_MATCH_STATE |
THEME_MATCH_ORIENTATION);
match_data.shadow = shadow;
match_data.state = state;
if (!draw_gap_image (style, window, area, widget, &match_data, FALSE,
x, y, width, height, gap_side, gap_x, gap_width))
parent_class->draw_shadow_gap (style, window, state, shadow, area, widget, detail,
x, y, width, height, gap_side, gap_x, gap_width);
}
static void
draw_box_gap (GtkStyle *style,
GdkWindow *window,
GtkStateType state,
GtkShadowType shadow,
GdkRectangle *area,
GtkWidget *widget,
const gchar *detail,
gint x,
gint y,
gint width,
gint height,
GtkPositionType gap_side,
gint gap_x,
gint gap_width)
{
ThemeMatchData match_data;
match_data.function = TOKEN_D_BOX_GAP;
match_data.detail = (gchar *)detail;
match_data.flags = THEME_MATCH_SHADOW | THEME_MATCH_STATE;
match_data.flags = (THEME_MATCH_SHADOW |
THEME_MATCH_STATE |
THEME_MATCH_ORIENTATION);
match_data.shadow = shadow;
match_data.state = state;
if (!draw_gap_image (style, window, area, widget, &match_data, TRUE,
x, y, width, height, gap_side, gap_x, gap_width))
parent_class->draw_box_gap (style, window, state, shadow, area, widget, detail,
x, y, width, height, gap_side, gap_x, gap_width);
}
static void
draw_extension (GtkStyle *style,
GdkWindow *window,
GtkStateType state,
GtkShadowType shadow,
GdkRectangle *area,
GtkWidget *widget,
const gchar *detail,
gint x,
gint y,
gint width,
gint height,
GtkPositionType gap_side)
{
ThemeMatchData match_data;
g_return_if_fail (style != NULL);
g_return_if_fail (window != NULL);
match_data.function = TOKEN_D_EXTENSION;
match_data.detail = (gchar *)detail;
match_data.flags = THEME_MATCH_SHADOW | THEME_MATCH_STATE | THEME_MATCH_GAP_SIDE;
match_data.shadow = shadow;
match_data.state = state;
match_data.gap_side = gap_side;
if (!draw_simple_image (style, window, area, widget, &match_data, TRUE, TRUE,
x, y, width, height))
parent_class->draw_extension (style, window, state, shadow, area, widget, detail,
x, y, width, height, gap_side);
}
static void
draw_focus (GtkStyle *style,
GdkWindow *window,
GtkStateType state_type,
GdkRectangle *area,
GtkWidget *widget,
const gchar *detail,
gint x,
gint y,
gint width,
gint height)
{
ThemeMatchData match_data;
g_return_if_fail (style != NULL);
g_return_if_fail (window != NULL);
match_data.function = TOKEN_D_FOCUS;
match_data.detail = (gchar *)detail;
match_data.flags = 0;
if (!draw_simple_image (style, window, area, widget, &match_data, TRUE, FALSE,
x, y, width, height))
parent_class->draw_focus (style, window, state_type, area, widget, detail,
x, y, width, height);
}
static void
draw_slider (GtkStyle *style,
GdkWindow *window,
GtkStateType state,
GtkShadowType shadow,
GdkRectangle *area,
GtkWidget *widget,
const gchar *detail,
gint x,
gint y,
gint width,
gint height,
GtkOrientation orientation)
{
ThemeMatchData match_data;
g_return_if_fail(style != NULL);
g_return_if_fail(window != NULL);
match_data.function = TOKEN_D_SLIDER;
match_data.detail = (gchar *)detail;
match_data.flags = (THEME_MATCH_SHADOW |
THEME_MATCH_STATE |
THEME_MATCH_ORIENTATION);
match_data.shadow = shadow;
match_data.state = state;
match_data.orientation = orientation;
if (!draw_simple_image (style, window, area, widget, &match_data, TRUE, TRUE,
x, y, width, height))
parent_class->draw_slider (style, window, state, shadow, area, widget, detail,
x, y, width, height, orientation);
}
static void
draw_handle (GtkStyle *style,
GdkWindow *window,
GtkStateType state,
GtkShadowType shadow,
GdkRectangle *area,
GtkWidget *widget,
const gchar *detail,
gint x,
gint y,
gint width,
gint height,
GtkOrientation orientation)
{
ThemeMatchData match_data;
g_return_if_fail (style != NULL);
g_return_if_fail (window != NULL);
match_data.function = TOKEN_D_HANDLE;
match_data.detail = (gchar *)detail;
match_data.flags = (THEME_MATCH_SHADOW |
THEME_MATCH_STATE |
THEME_MATCH_ORIENTATION);
match_data.shadow = shadow;
match_data.state = state;
match_data.orientation = orientation;
if (!draw_simple_image (style, window, area, widget, &match_data, TRUE, TRUE,
x, y, width, height))
parent_class->draw_handle (style, window, state, shadow, area, widget, detail,
x, y, width, height, orientation);
}
static void
draw_expander (GtkStyle *style,
GdkWindow *window,
GtkStateType state,
GdkRectangle *area,
GtkWidget *widget,
const gchar *detail,
gint x,
gint y,
GtkExpanderStyle expander_style)
{
#define DEFAULT_EXPANDER_SIZE 12
ThemeMatchData match_data;
gint expander_size;
gint radius;
g_return_if_fail (style != NULL);
g_return_if_fail (window != NULL);
if (widget &&
gtk_widget_class_find_style_property (GTK_WIDGET_GET_CLASS (widget),
"expander-size"))
{
gtk_widget_style_get (widget,
"expander-size", &expander_size,
NULL);
}
else
expander_size = DEFAULT_EXPANDER_SIZE;
radius = expander_size/2;
match_data.function = TOKEN_D_EXPANDER;
match_data.detail = (gchar *)detail;
match_data.flags = (THEME_MATCH_STATE |
THEME_MATCH_EXPANDER_STYLE);
match_data.state = state;
match_data.expander_style = expander_style;
if (!draw_simple_image (style, window, area, widget, &match_data, TRUE, TRUE,
x - radius, y - radius, expander_size, expander_size))
parent_class->draw_expander (style, window, state, area, widget, detail,
x, y, expander_style);
}
static void
draw_resize_grip (GtkStyle *style,
GdkWindow *window,
GtkStateType state,
GdkRectangle *area,
GtkWidget *widget,
const gchar *detail,
GdkWindowEdge edge,
gint x,
gint y,
gint width,
gint height)
{
ThemeMatchData match_data;
g_return_if_fail (style != NULL);
g_return_if_fail (window != NULL);
match_data.function = TOKEN_D_RESIZE_GRIP;
match_data.detail = (gchar *)detail;
match_data.flags = (THEME_MATCH_STATE |
THEME_MATCH_WINDOW_EDGE);
match_data.state = state;
match_data.window_edge = edge;
if (!draw_simple_image (style, window, area, widget, &match_data, TRUE, TRUE,
x, y, width, height))
parent_class->draw_resize_grip (style, window, state, area, widget, detail,
edge, x, y, width, height);
}
GType pixbuf_type_style = 0;
void
pixbuf_style_register_type (GTypeModule *module)
{
const GTypeInfo object_info =
{
sizeof (PixbufStyleClass),
(GBaseInitFunc) NULL,
(GBaseFinalizeFunc) NULL,
(GClassInitFunc) pixbuf_style_class_init,
NULL, /* class_finalize */
NULL, /* class_data */
sizeof (PixbufStyle),
0, /* n_preallocs */
(GInstanceInitFunc) pixbuf_style_init,
};
pixbuf_type_style = g_type_module_register_type (module,
GTK_TYPE_STYLE,
"PixbufStyle",
&object_info, 0);
}
static void
pixbuf_style_init (PixbufStyle *style)
{
}
static void
pixbuf_style_class_init (PixbufStyleClass *klass)
{
GtkStyleClass *style_class = GTK_STYLE_CLASS (klass);
parent_class = g_type_class_peek_parent (klass);
style_class->draw_hline = draw_hline;
style_class->draw_vline = draw_vline;
style_class->draw_shadow = draw_shadow;
style_class->draw_arrow = draw_arrow;
style_class->draw_diamond = draw_diamond;
style_class->draw_string = draw_string;
style_class->draw_box = draw_box;
style_class->draw_flat_box = draw_flat_box;
style_class->draw_check = draw_check;
style_class->draw_option = draw_option;
style_class->draw_tab = draw_tab;
style_class->draw_shadow_gap = draw_shadow_gap;
style_class->draw_box_gap = draw_box_gap;
style_class->draw_extension = draw_extension;
style_class->draw_focus = draw_focus;
style_class->draw_slider = draw_slider;
style_class->draw_handle = draw_handle;
style_class->draw_expander = draw_expander;
style_class->draw_resize_grip = draw_resize_grip;
}
| lgpl-2.1 |
coapp-packages/aspell | modules/speller/default/language.cpp | 7 | 23433 | // Copyright 2000 by Kevin Atkinson under the terms of the LGPL
#include "settings.h"
#include <vector>
#include <assert.h>
#include <iostream.hpp>
#include "asc_ctype.hpp"
#include "clone_ptr-t.hpp"
#include "config.hpp"
#include "enumeration.hpp"
#include "errors.hpp"
#include "file_data_util.hpp"
#include "fstream.hpp"
#include "language.hpp"
#include "string.hpp"
#include "cache-t.hpp"
#include "getdata.hpp"
#include "file_util.hpp"
#ifdef ENABLE_NLS
# include <langinfo.h>
#endif
#include "gettext.h"
namespace aspeller {
static const char TO_CHAR_TYPE[256] = {
// 1 2 3 4 5 6 7 8 9 A B C D E F
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 2
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 3
0, 4, 0, 0, 3, 0, 0, 0, 2, 0, 0, 0, 6, 5, 0, 0, // 4
0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, // 5
0, 4, 0, 0, 3, 0, 0, 0, 2, 0, 0, 0, 6, 5, 0, 0, // 6
0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, // 7
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // A
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // B
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // C
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // D
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // E
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // F
};
static const int FOR_CONFIG = 1;
static const KeyInfo lang_config_keys[] = {
{"charset", KeyInfoString, "iso-8859-1", ""}
, {"data-encoding", KeyInfoString, "<charset>", ""}
, {"name", KeyInfoString, "", ""}
, {"run-together", KeyInfoBool, "", "", 0, FOR_CONFIG}
, {"run-together-limit", KeyInfoInt, "", "", 0, FOR_CONFIG}
, {"run-together-min", KeyInfoInt, "", "", 0, FOR_CONFIG}
, {"soundslike", KeyInfoString, "none", ""}
, {"special", KeyInfoString, "", ""}
, {"ignore-accents" , KeyInfoBool, "", "", 0, FOR_CONFIG}
, {"invisible-soundslike",KeyInfoBool, "", "", 0, FOR_CONFIG}
, {"keyboard", KeyInfoString, "standard", "", 0, FOR_CONFIG}
, {"affix", KeyInfoString, "none", ""}
, {"affix-compress", KeyInfoBool, "false", "", 0, FOR_CONFIG}
, {"partially-expand", KeyInfoBool, "false", "", 0, FOR_CONFIG}
, {"affix-char", KeyInfoString, "/", "", 0, FOR_CONFIG}
, {"flag-char", KeyInfoString, ":", "", 0, FOR_CONFIG}
, {"repl-table", KeyInfoString, "none", ""}
, {"sug-split-char", KeyInfoList, "", "", 0, FOR_CONFIG}
, {"store-as", KeyInfoString, "", ""}
, {"try", KeyInfoString, "", ""}
, {"normalize", KeyInfoBool, "false", "", 0, FOR_CONFIG}
, {"norm-required", KeyInfoBool, "false", "", 0, FOR_CONFIG}
, {"norm-form", KeyInfoString, "nfc", "", 0, FOR_CONFIG}
};
static GlobalCache<Language> language_cache("language");
PosibErr<void> Language::setup(const String & lang, const Config * config)
{
//
// get_lang_info
//
String dir1,dir2,path;
fill_data_dir(config, dir1, dir2);
dir_ = find_file(path,dir1,dir2,lang,".dat");
lang_config_ =
new Config("speller-lang",
lang_config_keys,
lang_config_keys + sizeof(lang_config_keys)/sizeof(KeyInfo));
Config & data = *lang_config_;
{
PosibErrBase pe = data.read_in_file(path);
if (pe.has_err(cant_read_file)) {
String mesg = pe.get_err()->mesg;
mesg[0] = asc_tolower(mesg[0]);
mesg = _("This is probably because: ") + mesg;
return make_err(unknown_language, lang, mesg);
} else if (pe.has_err())
return pe;
}
if (!data.have("name"))
return make_err(bad_file_format, path, _("The required field \"name\" is missing."));
String buf;
name_ = data.retrieve("name");
charset_ = fix_encoding_str(data.retrieve("charset"), buf);
charmap_ = charset_;
data_encoding_ = fix_encoding_str(data.retrieve("data-encoding"), buf);
DataPair d;
//
// read header of cset data file
//
FStream char_data;
String char_data_name;
find_file(char_data_name,dir1,dir2,charset_,".cset");
RET_ON_ERR(char_data.open(char_data_name, "r"));
String temp;
char * p;
do {
p = get_nb_line(char_data, temp);
if (*p == '=') {
++p;
while (asc_isspace(*p)) ++p;
charmap_ = p;
}
} while (*p != '/');
//
// fill in tables
//
for (unsigned int i = 0; i != 256; ++i) {
p = get_nb_line(char_data, temp);
if (!p || strtoul(p, &p, 16) != i)
return make_err(bad_file_format, char_data_name);
to_uni_[i] = strtol(p, &p, 16);
while (asc_isspace(*p)) ++p;
char_type_[i] = static_cast<CharType>(TO_CHAR_TYPE[to_uchar(*p++)]);
while (asc_isspace(*p)) ++p;
++p; // display, ignored for now
CharInfo inf = char_type_[i] >= Letter ? LETTER : 0;
to_upper_[i] = static_cast<char>(strtol(p, &p, 16));
inf |= to_uchar(to_upper_[i]) == i ? UPPER : 0;
to_lower_[i] = static_cast<char>(strtol(p, &p, 16));
inf |= to_uchar(to_lower_[i]) == i ? LOWER : 0;
to_title_[i] = static_cast<char>(strtol(p, &p, 16));
inf |= to_uchar(to_title_[i]) == i ? TITLE : 0;
to_plain_[i] = static_cast<char>(strtol(p, &p, 16));
inf |= to_uchar(to_plain_[i]) == i ? PLAIN : 0;
inf |= to_uchar(to_plain_[i]) == 0 ? PLAIN : 0;
sl_first_[i] = static_cast<char>(strtol(p, &p, 16));
sl_rest_[i] = static_cast<char>(strtol(p, &p, 16));
char_info_[i] = inf;
}
for (unsigned int i = 0; i != 256; ++i) {
de_accent_[i] = to_plain_[i] == 0 ? to_uchar(i) : to_plain_[i];
}
to_plain_[0] = 0x10; // to make things slightly easier
to_plain_[1] = 0x10;
for (unsigned int i = 0; i != 256; ++i) {
to_stripped_[i] = to_plain_[(unsigned char)to_lower_[i]];
}
char_data.close();
if (data.have("store-as"))
buf = data.retrieve("store-as");
else if (data.retrieve_bool("affix-compress"))
buf = "lower";
else
buf = "stripped";
char * clean_is;
if (buf == "stripped") {
store_as_ = Stripped;
clean_is = to_stripped_;
} else {
store_as_ = Lower;
clean_is = to_lower_;
}
for (unsigned i = 0; i != 256; ++i) {
to_clean_[i] = char_type_[i] > NonLetter ? clean_is[i] : 0;
if ((unsigned char)to_clean_[i] == i) char_info_[i] |= CLEAN;
}
to_clean_[0x00] = 0x10; // to make things slightly easier
to_clean_[0x10] = 0x10;
clean_chars_ = get_clean_chars(*this);
//
// determine which mapping to use
//
if (charmap_ != charset_) {
if (file_exists(dir1 + charset_ + ".cmap") ||
file_exists(dir2 + charset_ + ".cmap"))
{
charmap_ = charset_;
} else if (data_encoding_ == charset_) {
data_encoding_ = charmap_;
}
}
//
// set up conversions
//
{
#ifdef ENABLE_NLS
const char * tmp = 0;
tmp = bind_textdomain_codeset("aspell", 0);
#ifdef HAVE_LANGINFO_CODESET
if (!tmp) tmp = nl_langinfo(CODESET);
#endif
if (ascii_encoding(*config, tmp)) tmp = 0;
if (tmp)
RET_ON_ERR(mesg_conv_.setup(*config, charmap_, fix_encoding_str(tmp, buf), NormTo));
else
#endif
RET_ON_ERR(mesg_conv_.setup(*config, charmap_, data_encoding_, NormTo));
// no need to check for errors here since we know charmap_ is a
// supported encoding
to_utf8_.setup(*config, charmap_, "utf-8", NormTo);
from_utf8_.setup(*config, "utf-8", charmap_, NormFrom);
}
Conv iconv;
RET_ON_ERR(iconv.setup(*config, data_encoding_, charmap_, NormFrom));
//
// set up special
//
init(data.retrieve("special"), d, buf);
while (split(d)) {
char c = iconv(d.key)[0];
split(d);
special_[to_uchar(c)] =
SpecialChar (d.key[0] == '*',d.key[1] == '*', d.key[2] == '*');
}
//
// prep phonetic code
//
{
PosibErr<Soundslike *> pe = new_soundslike(data.retrieve("soundslike"),
iconv,
this);
if (pe.has_err()) return pe;
soundslike_.reset(pe.data);
}
soundslike_chars_ = soundslike_->soundslike_chars();
have_soundslike_ = strcmp(soundslike_->name(), "none") != 0;
//
// prep affix code
//
{
PosibErr<AffixMgr *> pe = new_affix_mgr(data.retrieve("affix"), iconv, this);
if (pe.has_err()) return pe;
affix_.reset(pe.data);
}
//
// fill repl tables (if any)
//
String repl = data.retrieve("repl-table");
have_repl_ = false;
if (repl != "none") {
String repl_file;
FStream REPL;
find_file(repl_file, dir1, dir2, repl, "_repl", ".dat");
RET_ON_ERR(REPL.open(repl_file, "r"));
size_t num_repl = 0;
while (getdata_pair(REPL, d, buf)) {
::to_lower(d.key);
if (d.key == "rep") {
num_repl = atoi(d.value); // FIXME make this more robust
break;
}
}
if (num_repl > 0)
have_repl_ = true;
for (size_t i = 0; i != num_repl; ++i) {
bool res = getdata_pair(REPL, d, buf);
assert(res); // FIXME
::to_lower(d.key);
assert(d.key == "rep"); // FIXME
split(d);
SuggestRepl rep;
rep.substr = buf_.dup(iconv(d.key));
if (check_if_valid(*this, rep.substr).get_err())
continue; // FIXME: This should probably be an error, but
// this may cause problems with compatibility with
// Myspell as these entries may make sense for
// Myspell (but obviously not for Aspell)
to_clean((char *)rep.substr, rep.substr);
rep.repl = buf_.dup(iconv(d.value));
if (check_if_valid(*this, rep.repl).get_err())
continue; // FIXME: Ditto
to_clean((char *)rep.repl, rep.repl);
if (strcmp(rep.substr, rep.repl) == 0 || rep.substr[0] == '\0')
continue; // FIXME: Ditto
repls_.push_back(rep);
}
}
return no_err;
}
void Language::set_lang_defaults(Config & config) const
{
config.replace_internal("actual-lang", name());
config.lang_config_merge(*lang_config_, FOR_CONFIG, data_encoding_);
}
WordInfo Language::get_word_info(ParmStr str) const
{
CharInfo first = CHAR_INFO_ALL, all = CHAR_INFO_ALL;
const char * p = str;
while (*p && (first = char_info(*p++), all &= first, !(first & LETTER)));
while (*p) all &= char_info(*p++);
WordInfo res;
if (all & LOWER) res = AllLower;
else if (all & UPPER) res = AllUpper;
else if (first & TITLE) res = FirstUpper;
else res = Other;
if (all & PLAIN) res |= ALL_PLAIN;
if (all & CLEAN) res |= ALL_CLEAN;
return res;
}
CasePattern Language::case_pattern(ParmStr str) const
{
CharInfo first = CHAR_INFO_ALL, all = CHAR_INFO_ALL;
const char * p = str;
while (*p && (first = char_info(*p++), all &= first, !(first & LETTER)));
while (*p) all &= char_info(*p++);
if (all & LOWER) return AllLower;
else if (all & UPPER) return AllUpper;
else if (first & TITLE) return FirstUpper;
else return Other;
}
CasePattern Language::case_pattern(const char * str, unsigned size) const
{
CharInfo first = CHAR_INFO_ALL, all = CHAR_INFO_ALL;
const char * p = str;
const char * end = p + size;
while (p < end && (first = char_info(*p++), all &= first, !(first & LETTER)));
while (p < end) all &= char_info(*p++);
if (all & LOWER) return AllLower;
else if (all & UPPER) return AllUpper;
else if (first & TITLE) return FirstUpper;
else return Other;
}
void Language::fix_case(CasePattern case_pattern,
char * res, const char * str) const
{
if (!str[0]) return;
if (case_pattern == AllUpper) {
to_upper(res,str);
} if (case_pattern == FirstUpper && is_lower(str[0])) {
*res = to_title(str[0]);
if (res == str) return;
res++;
str++;
while (*str) *res++ = *str++;
*res = '\0';
} else {
if (res == str) return;
while (*str) *res++ = *str++;
*res = '\0';
}
}
const char * Language::fix_case(CasePattern case_pattern, const char * str,
String & buf) const
{
if (!str[0]) return str;
if (case_pattern == AllUpper) {
to_upper(buf,str);
return buf.str();
} if (case_pattern == FirstUpper && is_lower(str[0])) {
buf.clear();
buf += to_title(str[0]);
str++;
while (*str) buf += *str++;
return buf.str();
} else {
return str;
}
}
WordAff * Language::fake_expand(ParmStr word, ParmStr aff,
ObjStack & buf) const
{
WordAff * cur = (WordAff *)buf.alloc_bottom(sizeof(WordAff));
cur->word = buf.dup(word);
cur->aff = (unsigned char *)buf.dup("");
cur->next = 0;
return cur;
}
bool SensitiveCompare::operator() (const char * word0,
const char * inlist0) const
{
assert(*word0 && *inlist0);
try_again:
const char * word = word0;
const char * inlist = inlist0;
if (!case_insensitive) {
if (begin) {
if (*word == *inlist || *word == lang->to_title(*inlist)) ++word, ++inlist;
else goto try_upper;
}
while (*word && *inlist && *word == *inlist) ++word, ++inlist;
if (*inlist) goto try_upper;
if (end && lang->special(*word).end) ++word;
if (*word) goto try_upper;
return true;
try_upper:
word = word0;
inlist = inlist0;
while (*word && *inlist && *word == lang->to_upper(*inlist)) ++word, ++inlist;
if (*inlist) goto fail;
if (end && lang->special(*word).end) ++word;
if (*word) goto fail;
} else { // case_insensitive
while (*word && *inlist &&
lang->to_upper(*word) == lang->to_upper(*inlist)) ++word, ++inlist;
if (*inlist) goto fail;
if (end && lang->special(*word).end) ++word;
if (*word) goto fail;
}
return true;
fail:
if (begin && lang->special(*word0).begin) {++word0; goto try_again;}
return false;
}
static PosibErrBase invalid_word_e(const Language & l,
ParmStr word,
const char * msg,
char chr = 0)
{
char m[200];
if (chr) {
// the "char *" cast is needed due to an incorrect "snprintf"
// declaration on some platforms.
snprintf(m, 200, (char *)msg, MsgConv(l)(chr), l.to_uni(chr));
msg = m;
}
return make_err(invalid_word, MsgConv(l)(word), msg);
}
PosibErr<void> check_if_valid(const Language & l, ParmStr word) {
if (*word == '\0')
return invalid_word_e(l, word, _("Empty string."));
const char * i = word;
if (!l.is_alpha(*i)) {
if (!l.special(*i).begin)
return invalid_word_e(l, word, _("The character '%s' (U+%02X) may not appear at the beginning of a word."), *i);
else if (!l.is_alpha(*(i+1)))
return invalid_word_e(l, word, _("The character '%s' (U+%02X) must be followed by an alphabetic character."), *i);
else if (!*(i+1))
return invalid_word_e(l, word, _("Does not contain any alphabetic characters."));
}
for (;*(i+1) != '\0'; ++i) {
if (!l.is_alpha(*i)) {
if (!l.special(*i).middle)
return invalid_word_e(l, word, _("The character '%s' (U+%02X) may not appear in the middle of a word."), *i);
else if (!l.is_alpha(*(i+1)))
return invalid_word_e(l, word, _("The character '%s' (U+%02X) must be followed by an alphabetic character."), *i);
}
}
if (!l.is_alpha(*i)) {
if (*i == '\r')
return invalid_word_e(l, word, _("The character '\\r' (U+0D) may not appear at the end of a word. "
"This probably means means that the file is using MS-DOS EOL instead of Unix EOL."), *i);
if (!l.special(*i).end)
return invalid_word_e(l, word, _("The character '%s' (U+%02X) may not appear at the end of a word."), *i);
}
return no_err;
}
PosibErr<void> validate_affix(const Language & l, ParmStr word, ParmStr aff)
{
for (const char * a = aff; *a; ++a) {
CheckAffixRes res = l.affix()->check_affix(word, *a);
if (res == InvalidAffix)
return make_err(invalid_affix, MsgConv(l)(*a), MsgConv(l)(word));
else if (res == InapplicableAffix)
return make_err(inapplicable_affix, MsgConv(l)(*a), MsgConv(l)(word));
}
return no_err;
}
CleanAffix::CleanAffix(const Language * lang0, OStream * log0)
: lang(lang0), log(log0), msgconv1(lang0), msgconv2(lang0)
{
}
char * CleanAffix::operator()(ParmStr word, char * aff)
{
char * r = aff;
for (const char * a = aff; *a; ++a) {
CheckAffixRes res = lang->affix()->check_affix(word, *a);
if (res == ValidAffix) {
*r = *a;
++r;
} else if (log) {
const char * msg = res == InvalidAffix
? _("Warning: Removing invalid affix '%s' from word %s.\n")
: _("Warning: Removing inapplicable affix '%s' from word %s.\n");
log->printf(msg, msgconv1(*a), msgconv2(word));
}
}
*r = '\0';
return r;
}
String get_stripped_chars(const Language & lang) {
bool chars_set[256] = {0};
String chars_list;
for (int i = 0; i != 256; ++i)
{
char c = static_cast<char>(i);
if (lang.is_alpha(c) || lang.special(c).any)
chars_set[static_cast<unsigned char>(lang.to_stripped(c))] = true;
}
for (int i = 1; i != 256; ++i)
{
if (chars_set[i])
chars_list += static_cast<char>(i);
}
return chars_list;
}
String get_clean_chars(const Language & lang) {
bool chars_set[256] = {0};
String chars_list;
for (int i = 0; i != 256; ++i)
{
char c = static_cast<char>(i);
if (lang.is_alpha(c) || lang.special(c).any)
chars_set[static_cast<unsigned char>(lang.to_clean(c))] = true;
}
for (int i = 1; i != 256; ++i)
{
if (chars_set[i]) {
chars_list += static_cast<char>(i);
}
}
return chars_list;
}
PosibErr<Language *> new_language(const Config & config, ParmStr lang)
{
if (!lang)
return get_cache_data(&language_cache, &config, config.retrieve("lang"));
else
return get_cache_data(&language_cache, &config, lang);
}
PosibErr<void> open_affix_file(const Config & c, FStream & f)
{
String lang = c.retrieve("lang");
String dir1,dir2,path;
fill_data_dir(&c, dir1, dir2);
String dir = find_file(path,dir1,dir2,lang,".dat");
String file;
file += dir;
file += '/';
file += lang;
file += "_affix.dat";
RET_ON_ERR(f.open(file,"r"));
return no_err;
}
bool find_language(Config & c)
{
String l_data = c.retrieve("lang");
char * l = l_data.mstr();
String dir1,dir2,path;
fill_data_dir(&c, dir1, dir2);
char * s = l + strlen(l);
while (s > l) {
find_file(path,dir1,dir2,l,".dat");
if (file_exists(path)) {
c.replace_internal("actual-lang", l);
return true;
}
while (s > l && !(*s == '-' || *s == '_')) --s;
*s = '\0';
}
return false;
}
WordListIterator::WordListIterator(StringEnumeration * in0,
const Language * lang0,
OStream * log0)
: in(in0), lang(lang0), log(log0), val(), str(0), str_end(0), brk(),
clean_affix(lang0, log0)
{
}
PosibErr<void> WordListIterator::init(Config & config)
{
if (!config.have("norm-strict"))
config.replace("norm-strict", "true");
have_affix = lang->have_affix();
validate_words = config.retrieve_bool("validate-words");
validate_affixes = config.retrieve_bool("validate-affixes");
clean_words = config.retrieve_bool("clean-words");
skip_invalid_words = config.retrieve_bool("skip-invalid-words");
clean_affixes = config.retrieve_bool("clean-affixes");
if (config.have("encoding")) {
RET_ON_ERR(iconv.setup(config, config.retrieve("encoding"), lang->charmap(),NormFrom));
} else {
RET_ON_ERR(iconv.setup(config, lang->data_encoding(), lang->charmap(), NormFrom));
}
brk[0] = ' ';
if (!lang->special('-').any) brk[1] = '-';
return no_err;
}
PosibErr<bool> WordListIterator::adv()
{
loop:
if (!str) {
orig = in->next();
if (!orig) return false;
if (!*orig) goto loop;
PosibErr<const char *> pe = iconv(orig);
if (pe.has_err()) {
if (!skip_invalid_words) return pe;
if (log) log->printf(_("Warning: %s Skipping string.\n"), pe.get_err()->mesg);
else pe.ignore_err();
goto loop;
}
if (pe.data == orig) {
data = orig;
data.ensure_null_end();
str = data.pbegin();
str_end = data.pend();
} else {
str = iconv.buf.pbegin();
str_end = iconv.buf.pend();
}
char * aff = str_end;
char * aff_end = str_end;
if (have_affix) {
aff = strchr(str, '/');
if (aff == 0) {
aff = str_end;
} else {
*aff = '\0';
str_end = aff;
++aff;
}
if (validate_affixes) {
if (clean_affixes)
aff_end = clean_affix(str, aff);
else
RET_ON_ERR(validate_affix(*lang, str, aff));
}
}
val.aff.str = aff;
val.aff.size = aff_end - aff;
if (!*aff && validate_words && clean_words) {
char * s = str;
while (s < str_end) {
while (s < str_end && !lang->is_alpha(*s) && !lang->special(*s).begin)
*s++ = '\0';
s += strcspn(s, brk);
*s = '\0';
char * s2 = s - 1;
while (s2 >= str && *s2 && !lang->is_alpha(*s2) && !lang->special(*s2).end)
*s2-- = '\0';
}
}
}
while (str < str_end)
{
if (!*str) {++str; continue;}
PosibErrBase pe2 = validate_words ? check_if_valid(*lang, str) : no_err;
val.word.str = str;
val.word.size = strlen(str);
str += val.word.size + 1;
if (!pe2.has_err() && val.word.size + (*val.aff ? val.aff.size + 1 : 0) > 240)
pe2 = make_err(invalid_word, MsgConv(lang)(val.word),
_("The total length is larger than 240 characters."));
if (!pe2.has_err()) return true;
if (!skip_invalid_words) return pe2;
if (log) log->printf(_("Warning: %s Skipping word.\n"), pe2.get_err()->mesg);
else pe2.ignore_err();
}
str = 0;
goto loop;
}
}
| lgpl-2.1 |
rauf/gpac | modules/raw_out/raw_video.c | 8 | 8026 | /*
* GPAC - Multimedia Framework C SDK
*
* Authors: Jean Le Feuvre
* Copyright (c) Telecom ParisTech 2000-2012
* All rights reserved
*
* This file is part of GPAC / DirectX audio and video render module
*
* GPAC is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* GPAC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*/
/*driver interfaces*/
#include <gpac/modules/video_out.h>
#include <gpac/modules/audio_out.h>
#include <gpac/user.h>
#include <gpac/list.h>
#include <gpac/constants.h>
#include <gpac/setup.h>
typedef struct
{
char *pixels;
u32 width, height;
u32 pixel_format, bpp;
Bool passthrough;
u32 sample_rate, nb_channels, chan_cfg;
} RawContext;
#define RAWCTX RawContext *rc = (RawContext *)dr->opaque
static GF_Err raw_resize(GF_VideoOutput *dr, u32 w, u32 h)
{
RAWCTX;
if (rc->pixels) gf_free(rc->pixels);
rc->width = w;
rc->height = h;
rc->pixels = (char*)gf_malloc(sizeof(char) * rc->bpp * w * h);
if (!rc->pixels) return GF_OUT_OF_MEM;
return GF_OK;
}
static GF_Err RAW_BlitPassthrough(GF_VideoOutput *dr, GF_VideoSurface *video_src, GF_Window *src_wnd, GF_Window *dst_wnd, u32 overlay_type)
{
return GF_OK;
}
GF_Err RAW_Setup(GF_VideoOutput *dr, void *os_handle, void *os_display, u32 init_flags)
{
const char *opt;
RAWCTX;
opt = gf_modules_get_option((GF_BaseInterface *)dr, "RAWVideo", "RawOutput");
if (opt && !strcmp(opt, "null")) {
rc->passthrough = GF_TRUE;
dr->Blit = RAW_BlitPassthrough;
dr->hw_caps |= GF_VIDEO_HW_HAS_RGB | GF_VIDEO_HW_HAS_RGBA | GF_VIDEO_HW_HAS_STRETCH | GF_VIDEO_HW_HAS_YUV | GF_VIDEO_HW_OPENGL | GF_VIDEO_HW_HAS_YUV_OVERLAY;
}
if (init_flags & GF_TERM_WINDOW_TRANSPARENT) {
rc->bpp = 4;
rc->pixel_format = GF_PIXEL_ARGB;
} else {
rc->bpp = 3;
rc->pixel_format = GF_PIXEL_RGB_24;
opt = gf_modules_get_option((GF_BaseInterface *)dr, "RAWVideo", "PixelFormat");
if (opt) {
if (!strcmp(opt, "555")) {
rc->bpp = 2;
rc->pixel_format = GF_PIXEL_RGB_555;
} else if (!strcmp(opt, "565")) {
rc->bpp = 2;
rc->pixel_format = GF_PIXEL_RGB_565;
} else if (!strcmp(opt, "bgr")) {
rc->bpp = 3;
rc->pixel_format = GF_PIXEL_BGR_24;
} else if (!strcmp(opt, "rgb")) {
rc->bpp = 3;
rc->pixel_format = GF_PIXEL_RGB_24;
} else if (!strcmp(opt, "bgr32")) {
rc->bpp = 4;
rc->pixel_format = GF_PIXEL_BGR_32;
} else if (!strcmp(opt, "rgb32")) {
rc->bpp = 4;
rc->pixel_format = GF_PIXEL_RGB_32;
} else if (!strcmp(opt, "rgba")) {
rc->bpp = 4;
rc->pixel_format = GF_PIXEL_RGBA;
} else if (!strcmp(opt, "argb")) {
rc->bpp = 4;
rc->pixel_format = GF_PIXEL_ARGB;
}
}
}
raw_resize(dr, 100, 100);
return GF_OK;
}
static void RAW_Shutdown(GF_VideoOutput *dr)
{
RAWCTX;
if (rc->pixels) gf_free(rc->pixels);
rc->pixels = NULL;
}
static GF_Err RAW_Flush(GF_VideoOutput *dr, GF_Window *dest)
{
#if 0
RAWCTX;
char szName[1024];
sprintf(szName, "test%d.png", gf_sys_clock());
gf_img_png_enc_file(rc->pixels, rc->width, rc->height, rc->width*rc->bpp, rc->pixel_format, szName);
#endif
return GF_OK;
}
static GF_Err RAW_LockBackBuffer(GF_VideoOutput *dr, GF_VideoSurface *vi, Bool do_lock)
{
RAWCTX;
if (do_lock) {
if (!vi) return GF_BAD_PARAM;
memset(vi, 0, sizeof(GF_VideoSurface));
vi->height = rc->height;
vi->width = rc->width;
vi->video_buffer = rc->pixels;
vi->pitch_x = rc->bpp;
vi->pitch_y = rc->bpp * vi->width;
vi->pixel_format = rc->pixel_format;
}
return GF_OK;
}
static GF_Err RAW_ProcessEvent(GF_VideoOutput *dr, GF_Event *evt)
{
if (evt) {
switch (evt->type) {
case GF_EVENT_VIDEO_SETUP:
if (evt->setup.opengl_mode) return GF_NOT_SUPPORTED;
return raw_resize(dr, evt->setup.width, evt->setup.height);
}
}
return GF_OK;
}
GF_VideoOutput *NewRawVideoOutput()
{
RawContext *pCtx;
GF_VideoOutput *driv = (GF_VideoOutput *) gf_malloc(sizeof(GF_VideoOutput));
memset(driv, 0, sizeof(GF_VideoOutput));
GF_REGISTER_MODULE_INTERFACE(driv, GF_VIDEO_OUTPUT_INTERFACE, "Raw Video Output", "gpac distribution")
pCtx = (RawContext*)gf_malloc(sizeof(RawContext));
memset(pCtx, 0, sizeof(RawContext));
driv->opaque = pCtx;
driv->Flush = RAW_Flush;
driv->LockBackBuffer = RAW_LockBackBuffer;
driv->Setup = RAW_Setup;
driv->Shutdown = RAW_Shutdown;
driv->ProcessEvent = RAW_ProcessEvent;
return driv;
}
void DeleteRawVideoOutput(void *ifce)
{
RawContext *rc;
GF_VideoOutput *driv = (GF_VideoOutput *) ifce;
rc = (RawContext *)driv->opaque;
gf_free(rc);
gf_free(driv);
}
static GF_Err RAW_AudioSetup(GF_AudioOutput *dr, void *os_handle, u32 num_buffers, u32 total_duration)
{
return GF_OK;
}
static void RAW_AudioShutdown(GF_AudioOutput *dr)
{
}
/*we assume what was asked is what we got*/
static GF_Err RAW_ConfigureOutput(GF_AudioOutput *dr, u32 *SampleRate, u32 *NbChannels, u32 *nbBitsPerSample, u32 channel_cfg)
{
RAWCTX;
rc->sample_rate = *SampleRate;
rc->nb_channels = *NbChannels;
rc->chan_cfg = channel_cfg;
return GF_OK;
}
static void RAW_WriteAudio(GF_AudioOutput *dr)
{
char buf[4096];
dr->FillBuffer(dr->audio_renderer, buf, 4096);
}
static void RAW_Play(GF_AudioOutput *dr, u32 PlayType)
{
}
static void RAW_SetVolume(GF_AudioOutput *dr, u32 Volume)
{
}
static void RAW_SetPan(GF_AudioOutput *dr, u32 Pan)
{
}
static GF_Err RAW_QueryOutputSampleRate(GF_AudioOutput *dr, u32 *desired_samplerate, u32 *NbChannels, u32 *nbBitsPerSample)
{
return GF_OK;
}
static u32 RAW_GetAudioDelay(GF_AudioOutput *dr)
{
return 0;
}
static u32 RAW_GetTotalBufferTime(GF_AudioOutput *dr)
{
return 0;
}
void *NewRawAudioOutput()
{
RawContext *ctx;
GF_AudioOutput *driv;
ctx = (RawContext*)gf_malloc(sizeof(RawContext));
memset(ctx, 0, sizeof(RawContext));
driv = (GF_AudioOutput*)gf_malloc(sizeof(GF_AudioOutput));
memset(driv, 0, sizeof(GF_AudioOutput));
GF_REGISTER_MODULE_INTERFACE(driv, GF_AUDIO_OUTPUT_INTERFACE, "Raw Audio Output", "gpac distribution")
driv->opaque = ctx;
driv->SelfThreaded = GF_FALSE;
driv->Setup = RAW_AudioSetup;
driv->Shutdown = RAW_AudioShutdown;
driv->ConfigureOutput = RAW_ConfigureOutput;
driv->GetAudioDelay = RAW_GetAudioDelay;
driv->GetTotalBufferTime = RAW_GetTotalBufferTime;
driv->SetVolume = RAW_SetVolume;
driv->SetPan = RAW_SetPan;
driv->Play = RAW_Play;
driv->QueryOutputSampleRate = RAW_QueryOutputSampleRate;
driv->WriteAudio = RAW_WriteAudio;
return driv;
}
static void DeleteAudioOutput(void *ifce)
{
GF_AudioOutput *dr = (GF_AudioOutput *) ifce;
RawContext *ctx = (RawContext*)dr->opaque;
gf_free(ctx);
gf_free(dr);
}
#ifndef GPAC_STANDALONE_RENDER_2D
/*interface query*/
GPAC_MODULE_EXPORT
const u32 *QueryInterfaces()
{
static u32 si [] = {
GF_VIDEO_OUTPUT_INTERFACE,
GF_AUDIO_OUTPUT_INTERFACE,
0
};
return si;
}
/*interface create*/
GPAC_MODULE_EXPORT
GF_BaseInterface *LoadInterface(u32 InterfaceType)
{
if (InterfaceType == GF_VIDEO_OUTPUT_INTERFACE) return (GF_BaseInterface *) NewRawVideoOutput();
if (InterfaceType == GF_AUDIO_OUTPUT_INTERFACE) return (GF_BaseInterface *) NewRawAudioOutput();
return NULL;
}
/*interface destroy*/
GPAC_MODULE_EXPORT
void ShutdownInterface(GF_BaseInterface *ifce)
{
switch (ifce->InterfaceType) {
case GF_VIDEO_OUTPUT_INTERFACE:
DeleteRawVideoOutput((GF_VideoOutput *)ifce);
break;
case GF_AUDIO_OUTPUT_INTERFACE:
DeleteAudioOutput((GF_AudioOutput *)ifce);
break;
}
}
GPAC_MODULE_STATIC_DECLARATION( raw_out )
#endif
| lgpl-2.1 |
dropbox/librsync | util.c | 10 | 1711 | /*= -*- c-basic-offset: 4; indent-tabs-mode: nil; -*-
*
* librsync -- the library for network deltas
* $Id: util.c,v 1.20 2003/06/12 05:47:23 wayned Exp $
*
* Copyright (C) 2000, 2001 by Martin Pool <mbp@samba.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
| On heroin, I have all the answers.
*/
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "util.h"
#include "librsync.h"
#include "trace.h"
void
rs_bzero(void *buf, size_t size)
{
memset(buf, 0, size);
}
void *
rs_alloc_struct0(size_t size, char const *name)
{
void *p;
if (!(p = malloc(size))) {
rs_fatal("couldn't allocate instance of %s", name);
}
rs_bzero(p, size);
return p;
}
void *
rs_alloc(size_t size, char const *name)
{
void *p;
if (!(p = malloc(size))) {
rs_fatal("couldn't allocate instance of %s", name);
}
return p;
}
| lgpl-2.1 |
ieei/glib | glib/gdataset.c | 12 | 34183 | /* GLIB - Library of useful routines for C programming
* Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
*
* gdataset.c: Generic dataset mechanism, similar to GtkObject data.
* Copyright (C) 1998 Tim Janik
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see <http://www.gnu.org/licenses/>.
*/
/*
* Modified by the GLib Team and others 1997-2000. See the AUTHORS
* file for a list of people on the GLib Team. See the ChangeLog
* files for a list of changes. These files are distributed with
* GLib at ftp://ftp.gtk.org/pub/gtk/.
*/
/*
* MT safe ; except for g_data*_foreach()
*/
#include "config.h"
#include <string.h>
#include "gdataset.h"
#include "gbitlock.h"
#include "gslice.h"
#include "gdatasetprivate.h"
#include "ghash.h"
#include "gquark.h"
#include "gstrfuncs.h"
#include "gtestutils.h"
#include "gthread.h"
#include "glib_trace.h"
/**
* SECTION:datasets
* @title: Datasets
* @short_description: associate groups of data elements with
* particular memory locations
*
* Datasets associate groups of data elements with particular memory
* locations. These are useful if you need to associate data with a
* structure returned from an external library. Since you cannot modify
* the structure, you use its location in memory as the key into a
* dataset, where you can associate any number of data elements with it.
*
* There are two forms of most of the dataset functions. The first form
* uses strings to identify the data elements associated with a
* location. The second form uses #GQuark identifiers, which are
* created with a call to g_quark_from_string() or
* g_quark_from_static_string(). The second form is quicker, since it
* does not require looking up the string in the hash table of #GQuark
* identifiers.
*
* There is no function to create a dataset. It is automatically
* created as soon as you add elements to it.
*
* To add data elements to a dataset use g_dataset_id_set_data(),
* g_dataset_id_set_data_full(), g_dataset_set_data() and
* g_dataset_set_data_full().
*
* To get data elements from a dataset use g_dataset_id_get_data() and
* g_dataset_get_data().
*
* To iterate over all data elements in a dataset use
* g_dataset_foreach() (not thread-safe).
*
* To remove data elements from a dataset use
* g_dataset_id_remove_data() and g_dataset_remove_data().
*
* To destroy a dataset, use g_dataset_destroy().
**/
/**
* SECTION:datalist
* @title: Keyed Data Lists
* @short_description: lists of data elements which are accessible by a
* string or GQuark identifier
*
* Keyed data lists provide lists of arbitrary data elements which can
* be accessed either with a string or with a #GQuark corresponding to
* the string.
*
* The #GQuark methods are quicker, since the strings have to be
* converted to #GQuarks anyway.
*
* Data lists are used for associating arbitrary data with #GObjects,
* using g_object_set_data() and related functions.
*
* To create a datalist, use g_datalist_init().
*
* To add data elements to a datalist use g_datalist_id_set_data(),
* g_datalist_id_set_data_full(), g_datalist_set_data() and
* g_datalist_set_data_full().
*
* To get data elements from a datalist use g_datalist_id_get_data()
* and g_datalist_get_data().
*
* To iterate over all data elements in a datalist use
* g_datalist_foreach() (not thread-safe).
*
* To remove data elements from a datalist use
* g_datalist_id_remove_data() and g_datalist_remove_data().
*
* To remove all data elements from a datalist, use g_datalist_clear().
**/
/**
* GData:
*
* The #GData struct is an opaque data structure to represent a
* [Keyed Data List][glib-Keyed-Data-Lists]. It should only be
* accessed via the following functions.
**/
/**
* GDestroyNotify:
* @data: the data element.
*
* Specifies the type of function which is called when a data element
* is destroyed. It is passed the pointer to the data element and
* should free any memory and resources allocated for it.
**/
#define G_DATALIST_FLAGS_MASK_INTERNAL 0x7
/* datalist pointer accesses have to be carried out atomically */
#define G_DATALIST_GET_POINTER(datalist) \
((GData*) ((gsize) g_atomic_pointer_get (datalist) & ~(gsize) G_DATALIST_FLAGS_MASK_INTERNAL))
#define G_DATALIST_SET_POINTER(datalist, pointer) G_STMT_START { \
gpointer _oldv, _newv; \
do { \
_oldv = g_atomic_pointer_get (datalist); \
_newv = (gpointer) (((gsize) _oldv & G_DATALIST_FLAGS_MASK_INTERNAL) | (gsize) pointer); \
} while (!g_atomic_pointer_compare_and_exchange ((void**) datalist, _oldv, _newv)); \
} G_STMT_END
/* --- structures --- */
typedef struct {
GQuark key;
gpointer data;
GDestroyNotify destroy;
} GDataElt;
typedef struct _GDataset GDataset;
struct _GData
{
guint32 len; /* Number of elements */
guint32 alloc; /* Number of allocated elements */
GDataElt data[1]; /* Flexible array */
};
struct _GDataset
{
gconstpointer location;
GData *datalist;
};
/* --- prototypes --- */
static inline GDataset* g_dataset_lookup (gconstpointer dataset_location);
static inline void g_datalist_clear_i (GData **datalist);
static void g_dataset_destroy_internal (GDataset *dataset);
static inline gpointer g_data_set_internal (GData **datalist,
GQuark key_id,
gpointer data,
GDestroyNotify destroy_func,
GDataset *dataset);
static void g_data_initialize (void);
/* Locking model:
* Each standalone GDataList is protected by a bitlock in the datalist pointer,
* which protects that modification of the non-flags part of the datalist pointer
* and the contents of the datalist.
*
* For GDataSet we have a global lock g_dataset_global that protects
* the global dataset hash and cache, and additionally it protects the
* datalist such that we can avoid to use the bit lock in a few places
* where it is easy.
*/
/* --- variables --- */
G_LOCK_DEFINE_STATIC (g_dataset_global);
static GHashTable *g_dataset_location_ht = NULL;
static GDataset *g_dataset_cached = NULL; /* should this be
thread specific? */
/* --- functions --- */
#define DATALIST_LOCK_BIT 2
static void
g_datalist_lock (GData **datalist)
{
g_pointer_bit_lock ((void **)datalist, DATALIST_LOCK_BIT);
}
static void
g_datalist_unlock (GData **datalist)
{
g_pointer_bit_unlock ((void **)datalist, DATALIST_LOCK_BIT);
}
/* Called with the datalist lock held, or the dataset global
* lock for dataset lists
*/
static void
g_datalist_clear_i (GData **datalist)
{
GData *data;
gint i;
data = G_DATALIST_GET_POINTER (datalist);
G_DATALIST_SET_POINTER (datalist, NULL);
if (data)
{
G_UNLOCK (g_dataset_global);
for (i = 0; i < data->len; i++)
{
if (data->data[i].data && data->data[i].destroy)
data->data[i].destroy (data->data[i].data);
}
G_LOCK (g_dataset_global);
g_free (data);
}
}
/**
* g_datalist_clear:
* @datalist: a datalist.
*
* Frees all the data elements of the datalist.
* The data elements' destroy functions are called
* if they have been set.
**/
void
g_datalist_clear (GData **datalist)
{
GData *data;
gint i;
g_return_if_fail (datalist != NULL);
g_datalist_lock (datalist);
data = G_DATALIST_GET_POINTER (datalist);
G_DATALIST_SET_POINTER (datalist, NULL);
g_datalist_unlock (datalist);
if (data)
{
for (i = 0; i < data->len; i++)
{
if (data->data[i].data && data->data[i].destroy)
data->data[i].destroy (data->data[i].data);
}
g_free (data);
}
}
/* HOLDS: g_dataset_global_lock */
static inline GDataset*
g_dataset_lookup (gconstpointer dataset_location)
{
GDataset *dataset;
if (g_dataset_cached && g_dataset_cached->location == dataset_location)
return g_dataset_cached;
dataset = g_hash_table_lookup (g_dataset_location_ht, dataset_location);
if (dataset)
g_dataset_cached = dataset;
return dataset;
}
/* HOLDS: g_dataset_global_lock */
static void
g_dataset_destroy_internal (GDataset *dataset)
{
gconstpointer dataset_location;
dataset_location = dataset->location;
while (dataset)
{
if (G_DATALIST_GET_POINTER(&dataset->datalist) == NULL)
{
if (dataset == g_dataset_cached)
g_dataset_cached = NULL;
g_hash_table_remove (g_dataset_location_ht, dataset_location);
g_slice_free (GDataset, dataset);
break;
}
g_datalist_clear_i (&dataset->datalist);
dataset = g_dataset_lookup (dataset_location);
}
}
/**
* g_dataset_destroy:
* @dataset_location: (not nullable): the location identifying the dataset.
*
* Destroys the dataset, freeing all memory allocated, and calling any
* destroy functions set for data elements.
*/
void
g_dataset_destroy (gconstpointer dataset_location)
{
g_return_if_fail (dataset_location != NULL);
G_LOCK (g_dataset_global);
if (g_dataset_location_ht)
{
GDataset *dataset;
dataset = g_dataset_lookup (dataset_location);
if (dataset)
g_dataset_destroy_internal (dataset);
}
G_UNLOCK (g_dataset_global);
}
/* HOLDS: g_dataset_global_lock if dataset != null */
static inline gpointer
g_data_set_internal (GData **datalist,
GQuark key_id,
gpointer new_data,
GDestroyNotify new_destroy_func,
GDataset *dataset)
{
GData *d, *old_d;
GDataElt old, *data, *data_last, *data_end;
g_datalist_lock (datalist);
d = G_DATALIST_GET_POINTER (datalist);
if (new_data == NULL) /* remove */
{
if (d)
{
data = d->data;
data_last = data + d->len - 1;
while (data <= data_last)
{
if (data->key == key_id)
{
old = *data;
if (data != data_last)
*data = *data_last;
d->len--;
/* We don't bother to shrink, but if all data are now gone
* we at least free the memory
*/
if (d->len == 0)
{
G_DATALIST_SET_POINTER (datalist, NULL);
g_free (d);
/* datalist may be situated in dataset, so must not be
* unlocked after we free it
*/
g_datalist_unlock (datalist);
/* the dataset destruction *must* be done
* prior to invocation of the data destroy function
*/
if (dataset)
g_dataset_destroy_internal (dataset);
}
else
{
g_datalist_unlock (datalist);
}
/* We found and removed an old value
* the GData struct *must* already be unlinked
* when invoking the destroy function.
* we use (new_data==NULL && new_destroy_func!=NULL) as
* a special hint combination to "steal"
* data without destroy notification
*/
if (old.destroy && !new_destroy_func)
{
if (dataset)
G_UNLOCK (g_dataset_global);
old.destroy (old.data);
if (dataset)
G_LOCK (g_dataset_global);
old.data = NULL;
}
return old.data;
}
data++;
}
}
}
else
{
old.data = NULL;
if (d)
{
data = d->data;
data_end = data + d->len;
while (data < data_end)
{
if (data->key == key_id)
{
if (!data->destroy)
{
data->data = new_data;
data->destroy = new_destroy_func;
g_datalist_unlock (datalist);
}
else
{
old = *data;
data->data = new_data;
data->destroy = new_destroy_func;
g_datalist_unlock (datalist);
/* We found and replaced an old value
* the GData struct *must* already be unlinked
* when invoking the destroy function.
*/
if (dataset)
G_UNLOCK (g_dataset_global);
old.destroy (old.data);
if (dataset)
G_LOCK (g_dataset_global);
}
return NULL;
}
data++;
}
}
/* The key was not found, insert it */
old_d = d;
if (d == NULL)
{
d = g_malloc (sizeof (GData));
d->len = 0;
d->alloc = 1;
}
else if (d->len == d->alloc)
{
d->alloc = d->alloc * 2;
d = g_realloc (d, sizeof (GData) + (d->alloc - 1) * sizeof (GDataElt));
}
if (old_d != d)
G_DATALIST_SET_POINTER (datalist, d);
d->data[d->len].key = key_id;
d->data[d->len].data = new_data;
d->data[d->len].destroy = new_destroy_func;
d->len++;
}
g_datalist_unlock (datalist);
return NULL;
}
/**
* g_dataset_id_set_data_full:
* @dataset_location: (not nullable): the location identifying the dataset.
* @key_id: the #GQuark id to identify the data element.
* @data: the data element.
* @destroy_func: the function to call when the data element is
* removed. This function will be called with the data
* element and can be used to free any memory allocated
* for it.
*
* Sets the data element associated with the given #GQuark id, and also
* the function to call when the data element is destroyed. Any
* previous data with the same key is removed, and its destroy function
* is called.
**/
/**
* g_dataset_set_data_full:
* @l: the location identifying the dataset.
* @k: the string to identify the data element.
* @d: the data element.
* @f: the function to call when the data element is removed. This
* function will be called with the data element and can be used to
* free any memory allocated for it.
*
* Sets the data corresponding to the given string identifier, and the
* function to call when the data element is destroyed.
**/
/**
* g_dataset_id_set_data:
* @l: the location identifying the dataset.
* @k: the #GQuark id to identify the data element.
* @d: the data element.
*
* Sets the data element associated with the given #GQuark id. Any
* previous data with the same key is removed, and its destroy function
* is called.
**/
/**
* g_dataset_set_data:
* @l: the location identifying the dataset.
* @k: the string to identify the data element.
* @d: the data element.
*
* Sets the data corresponding to the given string identifier.
**/
/**
* g_dataset_id_remove_data:
* @l: the location identifying the dataset.
* @k: the #GQuark id identifying the data element.
*
* Removes a data element from a dataset. The data element's destroy
* function is called if it has been set.
**/
/**
* g_dataset_remove_data:
* @l: the location identifying the dataset.
* @k: the string identifying the data element.
*
* Removes a data element corresponding to a string. Its destroy
* function is called if it has been set.
**/
void
g_dataset_id_set_data_full (gconstpointer dataset_location,
GQuark key_id,
gpointer data,
GDestroyNotify destroy_func)
{
GDataset *dataset;
g_return_if_fail (dataset_location != NULL);
if (!data)
g_return_if_fail (destroy_func == NULL);
if (!key_id)
{
if (data)
g_return_if_fail (key_id > 0);
else
return;
}
G_LOCK (g_dataset_global);
if (!g_dataset_location_ht)
g_data_initialize ();
dataset = g_dataset_lookup (dataset_location);
if (!dataset)
{
dataset = g_slice_new (GDataset);
dataset->location = dataset_location;
g_datalist_init (&dataset->datalist);
g_hash_table_insert (g_dataset_location_ht,
(gpointer) dataset->location,
dataset);
}
g_data_set_internal (&dataset->datalist, key_id, data, destroy_func, dataset);
G_UNLOCK (g_dataset_global);
}
/**
* g_datalist_id_set_data_full:
* @datalist: a datalist.
* @key_id: the #GQuark to identify the data element.
* @data: (allow-none): the data element or %NULL to remove any previous element
* corresponding to @key_id.
* @destroy_func: the function to call when the data element is
* removed. This function will be called with the data
* element and can be used to free any memory allocated
* for it. If @data is %NULL, then @destroy_func must
* also be %NULL.
*
* Sets the data corresponding to the given #GQuark id, and the
* function to be called when the element is removed from the datalist.
* Any previous data with the same key is removed, and its destroy
* function is called.
**/
/**
* g_datalist_set_data_full:
* @dl: a datalist.
* @k: the string to identify the data element.
* @d: (allow-none): the data element, or %NULL to remove any previous element
* corresponding to @k.
* @f: the function to call when the data element is removed. This
* function will be called with the data element and can be used to
* free any memory allocated for it. If @d is %NULL, then @f must
* also be %NULL.
*
* Sets the data element corresponding to the given string identifier,
* and the function to be called when the data element is removed.
**/
/**
* g_datalist_id_set_data:
* @dl: a datalist.
* @q: the #GQuark to identify the data element.
* @d: (allow-none): the data element, or %NULL to remove any previous element
* corresponding to @q.
*
* Sets the data corresponding to the given #GQuark id. Any previous
* data with the same key is removed, and its destroy function is
* called.
**/
/**
* g_datalist_set_data:
* @dl: a datalist.
* @k: the string to identify the data element.
* @d: (allow-none): the data element, or %NULL to remove any previous element
* corresponding to @k.
*
* Sets the data element corresponding to the given string identifier.
**/
/**
* g_datalist_id_remove_data:
* @dl: a datalist.
* @q: the #GQuark identifying the data element.
*
* Removes an element, using its #GQuark identifier.
**/
/**
* g_datalist_remove_data:
* @dl: a datalist.
* @k: the string identifying the data element.
*
* Removes an element using its string identifier. The data element's
* destroy function is called if it has been set.
**/
void
g_datalist_id_set_data_full (GData **datalist,
GQuark key_id,
gpointer data,
GDestroyNotify destroy_func)
{
g_return_if_fail (datalist != NULL);
if (!data)
g_return_if_fail (destroy_func == NULL);
if (!key_id)
{
if (data)
g_return_if_fail (key_id > 0);
else
return;
}
g_data_set_internal (datalist, key_id, data, destroy_func, NULL);
}
/**
* g_dataset_id_remove_no_notify:
* @dataset_location: (not nullable): the location identifying the dataset.
* @key_id: the #GQuark ID identifying the data element.
*
* Removes an element, without calling its destroy notification
* function.
*
* Returns: the data previously stored at @key_id, or %NULL if none.
**/
/**
* g_dataset_remove_no_notify:
* @l: the location identifying the dataset.
* @k: the string identifying the data element.
*
* Removes an element, without calling its destroy notifier.
**/
gpointer
g_dataset_id_remove_no_notify (gconstpointer dataset_location,
GQuark key_id)
{
gpointer ret_data = NULL;
g_return_val_if_fail (dataset_location != NULL, NULL);
G_LOCK (g_dataset_global);
if (key_id && g_dataset_location_ht)
{
GDataset *dataset;
dataset = g_dataset_lookup (dataset_location);
if (dataset)
ret_data = g_data_set_internal (&dataset->datalist, key_id, NULL, (GDestroyNotify) 42, dataset);
}
G_UNLOCK (g_dataset_global);
return ret_data;
}
/**
* g_datalist_id_remove_no_notify:
* @datalist: a datalist.
* @key_id: the #GQuark identifying a data element.
*
* Removes an element, without calling its destroy notification
* function.
*
* Returns: the data previously stored at @key_id, or %NULL if none.
**/
/**
* g_datalist_remove_no_notify:
* @dl: a datalist.
* @k: the string identifying the data element.
*
* Removes an element, without calling its destroy notifier.
**/
gpointer
g_datalist_id_remove_no_notify (GData **datalist,
GQuark key_id)
{
gpointer ret_data = NULL;
g_return_val_if_fail (datalist != NULL, NULL);
if (key_id)
ret_data = g_data_set_internal (datalist, key_id, NULL, (GDestroyNotify) 42, NULL);
return ret_data;
}
/**
* g_dataset_id_get_data:
* @dataset_location: (not nullable): the location identifying the dataset.
* @key_id: the #GQuark id to identify the data element.
*
* Gets the data element corresponding to a #GQuark.
*
* Returns: the data element corresponding to the #GQuark, or %NULL if
* it is not found.
**/
/**
* g_dataset_get_data:
* @l: the location identifying the dataset.
* @k: the string identifying the data element.
*
* Gets the data element corresponding to a string.
*
* Returns: the data element corresponding to the string, or %NULL if
* it is not found.
**/
gpointer
g_dataset_id_get_data (gconstpointer dataset_location,
GQuark key_id)
{
gpointer retval = NULL;
g_return_val_if_fail (dataset_location != NULL, NULL);
G_LOCK (g_dataset_global);
if (key_id && g_dataset_location_ht)
{
GDataset *dataset;
dataset = g_dataset_lookup (dataset_location);
if (dataset)
retval = g_datalist_id_get_data (&dataset->datalist, key_id);
}
G_UNLOCK (g_dataset_global);
return retval;
}
/**
* g_datalist_id_get_data:
* @datalist: a datalist.
* @key_id: the #GQuark identifying a data element.
*
* Retrieves the data element corresponding to @key_id.
*
* Returns: the data element, or %NULL if it is not found.
*/
gpointer
g_datalist_id_get_data (GData **datalist,
GQuark key_id)
{
return g_datalist_id_dup_data (datalist, key_id, NULL, NULL);
}
/**
* GDuplicateFunc:
* @data: the data to duplicate
* @user_data: user data that was specified in g_datalist_id_dup_data()
*
* The type of functions that are used to 'duplicate' an object.
* What this means depends on the context, it could just be
* incrementing the reference count, if @data is a ref-counted
* object.
*
* Returns: a duplicate of data
*/
/**
* g_datalist_id_dup_data:
* @datalist: location of a datalist
* @key_id: the #GQuark identifying a data element
* @dup_func: (allow-none): function to duplicate the old value
* @user_data: (allow-none): passed as user_data to @dup_func
*
* This is a variant of g_datalist_id_get_data() which
* returns a 'duplicate' of the value. @dup_func defines the
* meaning of 'duplicate' in this context, it could e.g.
* take a reference on a ref-counted object.
*
* If the @key_id is not set in the datalist then @dup_func
* will be called with a %NULL argument.
*
* Note that @dup_func is called while the datalist is locked, so it
* is not allowed to read or modify the datalist.
*
* This function can be useful to avoid races when multiple
* threads are using the same datalist and the same key.
*
* Returns: the result of calling @dup_func on the value
* associated with @key_id in @datalist, or %NULL if not set.
* If @dup_func is %NULL, the value is returned unmodified.
*
* Since: 2.34
*/
gpointer
g_datalist_id_dup_data (GData **datalist,
GQuark key_id,
GDuplicateFunc dup_func,
gpointer user_data)
{
gpointer val = NULL;
gpointer retval = NULL;
GData *d;
GDataElt *data, *data_end;
g_datalist_lock (datalist);
d = G_DATALIST_GET_POINTER (datalist);
if (d)
{
data = d->data;
data_end = data + d->len;
do
{
if (data->key == key_id)
{
val = data->data;
break;
}
data++;
}
while (data < data_end);
}
if (dup_func)
retval = dup_func (val, user_data);
else
retval = val;
g_datalist_unlock (datalist);
return retval;
}
/**
* g_datalist_id_replace_data:
* @datalist: location of a datalist
* @key_id: the #GQuark identifying a data element
* @oldval: (allow-none): the old value to compare against
* @newval: (allow-none): the new value to replace it with
* @destroy: (allow-none): destroy notify for the new value
* @old_destroy: (allow-none): destroy notify for the existing value
*
* Compares the member that is associated with @key_id in
* @datalist to @oldval, and if they are the same, replace
* @oldval with @newval.
*
* This is like a typical atomic compare-and-exchange
* operation, for a member of @datalist.
*
* If the previous value was replaced then ownership of the
* old value (@oldval) is passed to the caller, including
* the registred destroy notify for it (passed out in @old_destroy).
* Its up to the caller to free this as he wishes, which may
* or may not include using @old_destroy as sometimes replacement
* should not destroy the object in the normal way.
*
* Returns: %TRUE if the existing value for @key_id was replaced
* by @newval, %FALSE otherwise.
*
* Since: 2.34
*/
gboolean
g_datalist_id_replace_data (GData **datalist,
GQuark key_id,
gpointer oldval,
gpointer newval,
GDestroyNotify destroy,
GDestroyNotify *old_destroy)
{
gpointer val = NULL;
GData *d;
GDataElt *data, *data_end;
g_return_val_if_fail (datalist != NULL, FALSE);
g_return_val_if_fail (key_id != 0, FALSE);
if (old_destroy)
*old_destroy = NULL;
g_datalist_lock (datalist);
d = G_DATALIST_GET_POINTER (datalist);
if (d)
{
data = d->data;
data_end = data + d->len - 1;
while (data <= data_end)
{
if (data->key == key_id)
{
val = data->data;
if (val == oldval)
{
if (old_destroy)
*old_destroy = data->destroy;
if (newval != NULL)
{
data->data = newval;
data->destroy = destroy;
}
else
{
if (data != data_end)
*data = *data_end;
d->len--;
/* We don't bother to shrink, but if all data are now gone
* we at least free the memory
*/
if (d->len == 0)
{
G_DATALIST_SET_POINTER (datalist, NULL);
g_free (d);
}
}
}
break;
}
data++;
}
}
if (val == NULL && oldval == NULL && newval != NULL)
{
GData *old_d;
/* insert newval */
old_d = d;
if (d == NULL)
{
d = g_malloc (sizeof (GData));
d->len = 0;
d->alloc = 1;
}
else if (d->len == d->alloc)
{
d->alloc = d->alloc * 2;
d = g_realloc (d, sizeof (GData) + (d->alloc - 1) * sizeof (GDataElt));
}
if (old_d != d)
G_DATALIST_SET_POINTER (datalist, d);
d->data[d->len].key = key_id;
d->data[d->len].data = newval;
d->data[d->len].destroy = destroy;
d->len++;
}
g_datalist_unlock (datalist);
return val == oldval;
}
/**
* g_datalist_get_data:
* @datalist: a datalist.
* @key: the string identifying a data element.
*
* Gets a data element, using its string identifier. This is slower than
* g_datalist_id_get_data() because it compares strings.
*
* Returns: the data element, or %NULL if it is not found.
**/
gpointer
g_datalist_get_data (GData **datalist,
const gchar *key)
{
gpointer res = NULL;
GData *d;
GDataElt *data, *data_end;
g_return_val_if_fail (datalist != NULL, NULL);
g_datalist_lock (datalist);
d = G_DATALIST_GET_POINTER (datalist);
if (d)
{
data = d->data;
data_end = data + d->len;
while (data < data_end)
{
if (g_strcmp0 (g_quark_to_string (data->key), key) == 0)
{
res = data->data;
break;
}
data++;
}
}
g_datalist_unlock (datalist);
return res;
}
/**
* GDataForeachFunc:
* @key_id: the #GQuark id to identifying the data element.
* @data: the data element.
* @user_data: user data passed to g_dataset_foreach().
*
* Specifies the type of function passed to g_dataset_foreach(). It is
* called with each #GQuark id and associated data element, together
* with the @user_data parameter supplied to g_dataset_foreach().
**/
/**
* g_dataset_foreach:
* @dataset_location: (not nullable): the location identifying the dataset.
* @func: the function to call for each data element.
* @user_data: user data to pass to the function.
*
* Calls the given function for each data element which is associated
* with the given location. Note that this function is NOT thread-safe.
* So unless @datalist can be protected from any modifications during
* invocation of this function, it should not be called.
**/
void
g_dataset_foreach (gconstpointer dataset_location,
GDataForeachFunc func,
gpointer user_data)
{
GDataset *dataset;
g_return_if_fail (dataset_location != NULL);
g_return_if_fail (func != NULL);
G_LOCK (g_dataset_global);
if (g_dataset_location_ht)
{
dataset = g_dataset_lookup (dataset_location);
G_UNLOCK (g_dataset_global);
if (dataset)
g_datalist_foreach (&dataset->datalist, func, user_data);
}
else
{
G_UNLOCK (g_dataset_global);
}
}
/**
* g_datalist_foreach:
* @datalist: a datalist.
* @func: the function to call for each data element.
* @user_data: user data to pass to the function.
*
* Calls the given function for each data element of the datalist. The
* function is called with each data element's #GQuark id and data,
* together with the given @user_data parameter. Note that this
* function is NOT thread-safe. So unless @datalist can be protected
* from any modifications during invocation of this function, it should
* not be called.
**/
void
g_datalist_foreach (GData **datalist,
GDataForeachFunc func,
gpointer user_data)
{
GData *d;
int i, j, len;
GQuark *keys;
g_return_if_fail (datalist != NULL);
g_return_if_fail (func != NULL);
d = G_DATALIST_GET_POINTER (datalist);
if (d == NULL)
return;
/* We make a copy of the keys so that we can handle it changing
in the callback */
len = d->len;
keys = g_new (GQuark, len);
for (i = 0; i < len; i++)
keys[i] = d->data[i].key;
for (i = 0; i < len; i++)
{
/* A previous callback might have removed a later item, so always check that
it still exists before calling */
d = G_DATALIST_GET_POINTER (datalist);
if (d == NULL)
break;
for (j = 0; j < d->len; j++)
{
if (d->data[j].key == keys[i]) {
func (d->data[i].key, d->data[i].data, user_data);
break;
}
}
}
g_free (keys);
}
/**
* g_datalist_init:
* @datalist: a pointer to a pointer to a datalist.
*
* Resets the datalist to %NULL. It does not free any memory or call
* any destroy functions.
**/
void
g_datalist_init (GData **datalist)
{
g_return_if_fail (datalist != NULL);
g_atomic_pointer_set (datalist, NULL);
}
/**
* g_datalist_set_flags:
* @datalist: pointer to the location that holds a list
* @flags: the flags to turn on. The values of the flags are
* restricted by %G_DATALIST_FLAGS_MASK (currently
* 3; giving two possible boolean flags).
* A value for @flags that doesn't fit within the mask is
* an error.
*
* Turns on flag values for a data list. This function is used
* to keep a small number of boolean flags in an object with
* a data list without using any additional space. It is
* not generally useful except in circumstances where space
* is very tight. (It is used in the base #GObject type, for
* example.)
*
* Since: 2.8
**/
void
g_datalist_set_flags (GData **datalist,
guint flags)
{
g_return_if_fail (datalist != NULL);
g_return_if_fail ((flags & ~G_DATALIST_FLAGS_MASK) == 0);
g_atomic_pointer_or (datalist, (gsize)flags);
}
/**
* g_datalist_unset_flags:
* @datalist: pointer to the location that holds a list
* @flags: the flags to turn off. The values of the flags are
* restricted by %G_DATALIST_FLAGS_MASK (currently
* 3: giving two possible boolean flags).
* A value for @flags that doesn't fit within the mask is
* an error.
*
* Turns off flag values for a data list. See g_datalist_unset_flags()
*
* Since: 2.8
**/
void
g_datalist_unset_flags (GData **datalist,
guint flags)
{
g_return_if_fail (datalist != NULL);
g_return_if_fail ((flags & ~G_DATALIST_FLAGS_MASK) == 0);
g_atomic_pointer_and (datalist, ~(gsize)flags);
}
/**
* g_datalist_get_flags:
* @datalist: pointer to the location that holds a list
*
* Gets flags values packed in together with the datalist.
* See g_datalist_set_flags().
*
* Returns: the flags of the datalist
*
* Since: 2.8
**/
guint
g_datalist_get_flags (GData **datalist)
{
g_return_val_if_fail (datalist != NULL, 0);
return G_DATALIST_GET_FLAGS (datalist); /* atomic macro */
}
/* HOLDS: g_dataset_global_lock */
static void
g_data_initialize (void)
{
g_return_if_fail (g_dataset_location_ht == NULL);
g_dataset_location_ht = g_hash_table_new (g_direct_hash, NULL);
g_dataset_cached = NULL;
}
| lgpl-2.1 |
cevatbostancioglu/Energia | hardware/c2000/cores/c2000/f2802x_common/source/F2802x_PieCtrl.c | 16 | 2614 | // TI File $Revision: /main/1 $
// Checkin $Date: August 14, 2008 16:58:40 $
//###########################################################################
//
// FILE: DSP2802x_PieCtrl.c
//
// TITLE: DSP2802x Device PIE Control Register Initialization Functions.
//
//###########################################################################
// $TI Release: 2802x C/C++ Header Files and Peripheral Examples V1.29 $
// $Release Date: January 11, 2011 $
//###########################################################################
#include "F2802x_Device.h" // Headerfile Include File
#include "f2802x_common/include/F2802x_Examples.h" // Examples Include File
//---------------------------------------------------------------------------
// InitPieCtrl:
//---------------------------------------------------------------------------
// This function initializes the PIE control registers to a known state.
//
void InitPieCtrl(void)
{
// Disable Interrupts at the CPU level:
DINT;
// Disable the PIE
PieCtrlRegs.PIECTRL.bit.ENPIE = 0;
// Clear all PIEIER registers:
PieCtrlRegs.PIEIER1.all = 0;
PieCtrlRegs.PIEIER2.all = 0;
PieCtrlRegs.PIEIER3.all = 0;
PieCtrlRegs.PIEIER4.all = 0;
PieCtrlRegs.PIEIER5.all = 0;
PieCtrlRegs.PIEIER6.all = 0;
PieCtrlRegs.PIEIER7.all = 0;
PieCtrlRegs.PIEIER8.all = 0;
PieCtrlRegs.PIEIER9.all = 0;
PieCtrlRegs.PIEIER10.all = 0;
PieCtrlRegs.PIEIER11.all = 0;
PieCtrlRegs.PIEIER12.all = 0;
// Clear all PIEIFR registers:
PieCtrlRegs.PIEIFR1.all = 0;
PieCtrlRegs.PIEIFR2.all = 0;
PieCtrlRegs.PIEIFR3.all = 0;
PieCtrlRegs.PIEIFR4.all = 0;
PieCtrlRegs.PIEIFR5.all = 0;
PieCtrlRegs.PIEIFR6.all = 0;
PieCtrlRegs.PIEIFR7.all = 0;
PieCtrlRegs.PIEIFR8.all = 0;
PieCtrlRegs.PIEIFR9.all = 0;
PieCtrlRegs.PIEIFR10.all = 0;
PieCtrlRegs.PIEIFR11.all = 0;
PieCtrlRegs.PIEIFR12.all = 0;
}
//---------------------------------------------------------------------------
// EnableInterrupts:
//---------------------------------------------------------------------------
// This function enables the PIE module and CPU interrupts
//
void EnableInterrupts()
{
// Enable the PIE
PieCtrlRegs.PIECTRL.bit.ENPIE = 1;
// Enables PIE to drive a pulse into the CPU
PieCtrlRegs.PIEACK.all = 0xFFFF;
// Enable Interrupts at the CPU level
EINT;
}
//===========================================================================
// End of file.
//===========================================================================
| lgpl-2.1 |
davibe/gst-plugins-good | ext/annodex/gstcmmlparser.c | 17 | 18809 | /*
* gstcmmlparser.c - GStreamer CMML document parser
* Copyright (C) 2005 Alessandro Decina
*
* Authors:
* Alessandro Decina <alessandro@nnva.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#include <string.h>
#include <stdarg.h>
#include <gst/gst.h>
#include "gstcmmlparser.h"
#include "gstannodex.h"
#include "gstcmmlutils.h"
GST_DEBUG_CATEGORY_STATIC (cmmlparser);
#define GST_CAT_DEFAULT cmmlparser
static void gst_cmml_parser_generic_error (void *ctx, const char *msg, ...);
static xmlNodePtr gst_cmml_parser_new_node (GstCmmlParser * parser,
const gchar * name, ...);
static void
gst_cmml_parser_parse_start_element_ns (xmlParserCtxt * ctxt,
const xmlChar * name, const xmlChar * prefix, const xmlChar * URI,
int nb_preferences, const xmlChar ** namespaces,
int nb_attributes, int nb_defaulted, const xmlChar ** attributes);
static void gst_cmml_parser_parse_end_element_ns (xmlParserCtxt * ctxt,
const xmlChar * name, const xmlChar * prefix, const xmlChar * URI);
static void gst_cmml_parser_parse_processing_instruction (xmlParserCtxtPtr ctxt,
const xmlChar * target, const xmlChar * data);
static void gst_cmml_parser_meta_to_string (GstCmmlParser * parser,
xmlNodePtr parent, GValueArray * meta);
/* initialize the parser */
void
gst_cmml_parser_init (void)
{
GST_DEBUG_CATEGORY_INIT (cmmlparser, "cmmlparser", 0, "annodex CMML parser");
xmlGenericError = gst_cmml_parser_generic_error;
}
/* create a new CMML parser
*/
GstCmmlParser *
gst_cmml_parser_new (GstCmmlParserMode mode)
{
GstCmmlParser *parser = g_malloc (sizeof (GstCmmlParser));
parser->mode = mode;
parser->context = xmlCreatePushParserCtxt (NULL, NULL,
NULL, 0, "cmml-bitstream");
xmlCtxtUseOptions (parser->context, XML_PARSE_NONET | XML_PARSE_NOERROR);
parser->context->_private = parser;
parser->context->sax->startElementNs =
(startElementNsSAX2Func) gst_cmml_parser_parse_start_element_ns;
parser->context->sax->endElementNs =
(endElementNsSAX2Func) gst_cmml_parser_parse_end_element_ns;
parser->context->sax->processingInstruction = (processingInstructionSAXFunc)
gst_cmml_parser_parse_processing_instruction;
parser->preamble_callback = NULL;
parser->cmml_end_callback = NULL;
parser->stream_callback = NULL;
parser->head_callback = NULL;
parser->clip_callback = NULL;
parser->user_data = NULL;
return parser;
}
/* free a CMML parser instance
*/
void
gst_cmml_parser_free (GstCmmlParser * parser)
{
if (parser) {
xmlFreeDoc (parser->context->myDoc);
xmlFreeParserCtxt (parser->context);
g_free (parser);
}
}
/* parse an xml chunk
*
* returns false if the xml is invalid
*/
gboolean
gst_cmml_parser_parse_chunk (GstCmmlParser * parser,
const gchar * data, guint size, GError ** err)
{
gint xmlres;
xmlres = xmlParseChunk (parser->context, data, size, 0);
if (xmlres != XML_ERR_OK) {
xmlErrorPtr xml_error = xmlCtxtGetLastError (parser->context);
GST_DEBUG ("Error occurred decoding chunk %s", data);
g_set_error (err,
GST_LIBRARY_ERROR, GST_LIBRARY_ERROR_FAILED, "%s", xml_error->message);
return FALSE;
}
return TRUE;
}
/* convert an xmlNodePtr to a string
*/
static guchar *
gst_cmml_parser_node_to_string (GstCmmlParser * parser, xmlNodePtr node)
{
xmlBufferPtr xml_buffer;
xmlDocPtr doc;
guchar *str;
if (parser)
doc = parser->context->myDoc;
else
doc = NULL;
xml_buffer = xmlBufferCreate ();
xmlNodeDump (xml_buffer, doc, node, 0, 0);
str = xmlStrndup (xml_buffer->content, xml_buffer->use);
xmlBufferFree (xml_buffer);
return str;
}
guchar *
gst_cmml_parser_tag_stream_to_string (GstCmmlParser * parser,
GstCmmlTagStream * stream)
{
xmlNodePtr node;
xmlNodePtr import;
guchar *ret;
node = gst_cmml_parser_new_node (parser, "stream", NULL);
if (stream->timebase)
xmlSetProp (node, (xmlChar *) "timebase", stream->timebase);
if (stream->utc)
xmlSetProp (node, (xmlChar *) "utc", stream->utc);
if (stream->imports) {
gint i;
GValue *val;
for (i = 0; i < stream->imports->n_values; ++i) {
val = g_value_array_get_nth (stream->imports, i);
import = gst_cmml_parser_new_node (parser, "import",
"src", g_value_get_string (val), NULL);
xmlAddChild (node, import);
}
}
ret = gst_cmml_parser_node_to_string (parser, node);
xmlUnlinkNode (node);
xmlFreeNode (node);
return ret;
}
/* convert a GstCmmlTagHead to its string representation
*/
guchar *
gst_cmml_parser_tag_head_to_string (GstCmmlParser * parser,
GstCmmlTagHead * head)
{
xmlNodePtr node;
xmlNodePtr tmp;
guchar *ret;
node = gst_cmml_parser_new_node (parser, "head", NULL);
if (head->title) {
tmp = gst_cmml_parser_new_node (parser, "title", NULL);
xmlNodeSetContent (tmp, head->title);
xmlAddChild (node, tmp);
}
if (head->base) {
tmp = gst_cmml_parser_new_node (parser, "base", "uri", head->base, NULL);
xmlAddChild (node, tmp);
}
if (head->meta)
gst_cmml_parser_meta_to_string (parser, node, head->meta);
ret = gst_cmml_parser_node_to_string (parser, node);
xmlUnlinkNode (node);
xmlFreeNode (node);
return ret;
}
/* convert a GstCmmlTagClip to its string representation
*/
guchar *
gst_cmml_parser_tag_clip_to_string (GstCmmlParser * parser,
GstCmmlTagClip * clip)
{
xmlNodePtr node;
xmlNodePtr tmp;
guchar *ret;
node = gst_cmml_parser_new_node (parser, "clip",
"id", clip->id, "track", clip->track, NULL);
/* add the anchor element */
if (clip->anchor_href) {
tmp = gst_cmml_parser_new_node (parser, "a",
"href", clip->anchor_href, NULL);
if (clip->anchor_text)
xmlNodeSetContent (tmp, clip->anchor_text);
xmlAddChild (node, tmp);
}
/* add the img element */
if (clip->img_src) {
tmp = gst_cmml_parser_new_node (parser, "img",
"src", clip->img_src, "alt", clip->img_alt, NULL);
xmlAddChild (node, tmp);
}
/* add the desc element */
if (clip->desc_text) {
tmp = gst_cmml_parser_new_node (parser, "desc", NULL);
xmlNodeSetContent (tmp, clip->desc_text);
xmlAddChild (node, tmp);
}
/* add the meta elements */
if (clip->meta)
gst_cmml_parser_meta_to_string (parser, node, clip->meta);
if (parser->mode == GST_CMML_PARSER_DECODE) {
gchar *time_str;
time_str = gst_cmml_clock_time_to_npt (clip->start_time);
if (time_str == NULL)
goto fail;
xmlSetProp (node, (xmlChar *) "start", (xmlChar *) time_str);
g_free (time_str);
if (clip->end_time != GST_CLOCK_TIME_NONE) {
time_str = gst_cmml_clock_time_to_npt (clip->end_time);
if (time_str == NULL)
goto fail;
xmlSetProp (node, (xmlChar *) "end", (xmlChar *) time_str);
g_free (time_str);
}
}
ret = gst_cmml_parser_node_to_string (parser, node);
xmlUnlinkNode (node);
xmlFreeNode (node);
return ret;
fail:
xmlUnlinkNode (node);
xmlFreeNode (node);
return NULL;
}
guchar *
gst_cmml_parser_tag_object_to_string (GstCmmlParser * parser, GObject * tag)
{
guchar *tag_string = NULL;
GType tag_type = G_OBJECT_TYPE (tag);
if (tag_type == GST_TYPE_CMML_TAG_STREAM)
tag_string = gst_cmml_parser_tag_stream_to_string (parser,
GST_CMML_TAG_STREAM (tag));
else if (tag_type == GST_TYPE_CMML_TAG_HEAD)
tag_string = gst_cmml_parser_tag_head_to_string (parser,
GST_CMML_TAG_HEAD (tag));
else if (tag_type == GST_TYPE_CMML_TAG_CLIP)
tag_string = gst_cmml_parser_tag_clip_to_string (parser,
GST_CMML_TAG_CLIP (tag));
else
g_warning ("could not convert object to cmml");
return tag_string;
}
/*** private section ***/
/* create a new node
*
* helper to create a node and set its attributes
*/
static xmlNodePtr
gst_cmml_parser_new_node (GstCmmlParser * parser, const gchar * name, ...)
{
va_list args;
xmlNodePtr node;
xmlChar *prop_name, *prop_value;
node = xmlNewNode (NULL, (xmlChar *) name);
va_start (args, name);
prop_name = va_arg (args, xmlChar *);
while (prop_name != NULL) {
prop_value = va_arg (args, xmlChar *);
if (prop_value != NULL)
xmlSetProp (node, prop_name, prop_value);
prop_name = va_arg (args, xmlChar *);
}
va_end (args);
return node;
}
/* get the last node of the stream
*
* returns the last node at depth 1 (if any) or the root node
*/
static xmlNodePtr
gst_cmml_parser_get_last_element (GstCmmlParser * parser)
{
xmlNodePtr node;
node = xmlDocGetRootElement (parser->context->myDoc);
if (!node) {
g_warning ("no last cmml element");
return NULL;
}
if (node->children)
node = xmlGetLastChild (node);
return node;
}
static void
gst_cmml_parser_parse_preamble (GstCmmlParser * parser,
const guchar * attributes)
{
gchar *preamble;
gchar *element;
const gchar *version;
const gchar *encoding;
const gchar *standalone;
xmlDocPtr doc;
doc = parser->context->myDoc;
version = doc->version ? (gchar *) doc->version : "1.0";
encoding = doc->encoding ? (gchar *) doc->encoding : "UTF-8";
standalone = doc->standalone ? "yes" : "no";
preamble = g_strdup_printf ("<?xml version=\"%s\""
" encoding=\"%s\" standalone=\"%s\"?>\n"
"<!DOCTYPE cmml SYSTEM \"cmml.dtd\">\n", version, encoding, standalone);
if (attributes == NULL)
attributes = (guchar *) "";
if (parser->mode == GST_CMML_PARSER_ENCODE)
element = g_strdup_printf ("<?cmml %s?>", attributes);
else
element = g_strdup_printf ("<cmml %s>", attributes);
parser->preamble_callback (parser->user_data,
(guchar *) preamble, (guchar *) element);
g_free (preamble);
g_free (element);
}
/* parse the cmml stream tag */
static void
gst_cmml_parser_parse_stream (GstCmmlParser * parser, xmlNodePtr stream)
{
GstCmmlTagStream *stream_tag;
GValue str_val = { 0 };
xmlNodePtr walk;
guchar *timebase;
g_value_init (&str_val, G_TYPE_STRING);
/* read the timebase and utc attributes */
timebase = xmlGetProp (stream, (xmlChar *) "timebase");
if (timebase == NULL)
timebase = (guchar *) g_strdup ("0");
stream_tag = g_object_new (GST_TYPE_CMML_TAG_STREAM,
"timebase", timebase, NULL);
g_free (timebase);
stream_tag->utc = xmlGetProp (stream, (xmlChar *) "utc");
/* walk the children nodes */
for (walk = stream->children; walk; walk = walk->next) {
/* for every import tag add its src attribute to stream_tag->imports */
if (!xmlStrcmp (walk->name, (xmlChar *) "import")) {
g_value_take_string (&str_val,
(gchar *) xmlGetProp (walk, (xmlChar *) "src"));
if (stream_tag->imports == NULL)
stream_tag->imports = g_value_array_new (0);
g_value_array_append (stream_tag->imports, &str_val);
}
}
g_value_unset (&str_val);
parser->stream_callback (parser->user_data, stream_tag);
g_object_unref (stream_tag);
}
/* parse the cmml head tag */
static void
gst_cmml_parser_parse_head (GstCmmlParser * parser, xmlNodePtr head)
{
GstCmmlTagHead *head_tag;
xmlNodePtr walk;
GValue str_val = { 0 };
head_tag = g_object_new (GST_TYPE_CMML_TAG_HEAD, NULL);
g_value_init (&str_val, G_TYPE_STRING);
/* Parse the content of the node and setup the GST_TAG_CMML_HEAD tag.
* Create a GST_TAG_TITLE when we find the title element.
*/
for (walk = head->children; walk; walk = walk->next) {
if (!xmlStrcmp (walk->name, (xmlChar *) "title")) {
head_tag->title = xmlNodeGetContent (walk);
} else if (!xmlStrcmp (walk->name, (xmlChar *) "base")) {
head_tag->base = xmlGetProp (walk, (xmlChar *) "uri");
} else if (!xmlStrcmp (walk->name, (xmlChar *) "meta")) {
if (head_tag->meta == NULL)
head_tag->meta = g_value_array_new (0);
/* add a pair name, content to the meta value array */
g_value_take_string (&str_val,
(gchar *) xmlGetProp (walk, (xmlChar *) "name"));
g_value_array_append (head_tag->meta, &str_val);
g_value_take_string (&str_val,
(gchar *) xmlGetProp (walk, (xmlChar *) "content"));
g_value_array_append (head_tag->meta, &str_val);
}
}
g_value_unset (&str_val);
parser->head_callback (parser->user_data, head_tag);
g_object_unref (head_tag);
}
/* parse a cmml clip tag */
static void
gst_cmml_parser_parse_clip (GstCmmlParser * parser, xmlNodePtr clip)
{
GstCmmlTagClip *clip_tag;
GValue str_val = { 0 };
guchar *id, *track, *start, *end;
xmlNodePtr walk;
GstClockTime start_time = GST_CLOCK_TIME_NONE;
GstClockTime end_time = GST_CLOCK_TIME_NONE;
start = xmlGetProp (clip, (xmlChar *) "start");
if (parser->mode == GST_CMML_PARSER_ENCODE && start == NULL)
/* XXX: validate the document */
return;
id = xmlGetProp (clip, (xmlChar *) "id");
track = xmlGetProp (clip, (xmlChar *) "track");
end = xmlGetProp (clip, (xmlChar *) "end");
if (track == NULL)
track = (guchar *) g_strdup ("default");
if (start) {
if (!strncmp ((gchar *) start, "smpte", 5))
start_time = gst_cmml_clock_time_from_smpte ((gchar *) start);
else
start_time = gst_cmml_clock_time_from_npt ((gchar *) start);
}
if (end) {
if (!strncmp ((gchar *) end, "smpte", 5))
start_time = gst_cmml_clock_time_from_smpte ((gchar *) end);
else
end_time = gst_cmml_clock_time_from_npt ((gchar *) end);
}
clip_tag = g_object_new (GST_TYPE_CMML_TAG_CLIP, "id", id,
"track", track, "start-time", start_time, "end-time", end_time, NULL);
g_free (id);
g_free (track);
g_free (start);
g_free (end);
g_value_init (&str_val, G_TYPE_STRING);
/* parse the children */
for (walk = clip->children; walk; walk = walk->next) {
/* the clip is not empty */
clip_tag->empty = FALSE;
if (!xmlStrcmp (walk->name, (xmlChar *) "a")) {
clip_tag->anchor_href = xmlGetProp (walk, (xmlChar *) "href");
clip_tag->anchor_text = xmlNodeGetContent (walk);
} else if (!xmlStrcmp (walk->name, (xmlChar *) "img")) {
clip_tag->img_src = xmlGetProp (walk, (xmlChar *) "src");
clip_tag->img_alt = xmlGetProp (walk, (xmlChar *) "alt");
} else if (!xmlStrcmp (walk->name, (xmlChar *) "desc")) {
clip_tag->desc_text = xmlNodeGetContent (walk);
} else if (!xmlStrcmp (walk->name, (xmlChar *) "meta")) {
if (clip_tag->meta == NULL)
clip_tag->meta = g_value_array_new (0);
/* add a pair name, content to the meta value array */
g_value_take_string (&str_val,
(char *) xmlGetProp (walk, (xmlChar *) "name"));
g_value_array_append (clip_tag->meta, &str_val);
g_value_take_string (&str_val,
(char *) xmlGetProp (walk, (xmlChar *) "content"));
g_value_array_append (clip_tag->meta, &str_val);
}
}
g_value_unset (&str_val);
parser->clip_callback (parser->user_data, clip_tag);
g_object_unref (clip_tag);
}
void
gst_cmml_parser_meta_to_string (GstCmmlParser * parser,
xmlNodePtr parent, GValueArray * array)
{
gint i;
xmlNodePtr node;
GValue *name, *content;
for (i = 0; i < array->n_values - 1; i += 2) {
name = g_value_array_get_nth (array, i);
content = g_value_array_get_nth (array, i + 1);
node = gst_cmml_parser_new_node (parser, "meta",
"name", g_value_get_string (name),
"content", g_value_get_string (content), NULL);
xmlAddChild (parent, node);
}
}
static void
gst_cmml_parser_generic_error (void *ctx, const char *msg, ...)
{
#ifndef GST_DISABLE_GST_DEBUG
va_list varargs;
va_start (varargs, msg);
gst_debug_log_valist (GST_CAT_DEFAULT, GST_LEVEL_WARNING,
"", "", 0, NULL, msg, varargs);
va_end (varargs);
#endif /* GST_DISABLE_GST_DEBUG */
}
/* sax handler called when an element start tag is found
* this is used to parse the cmml start tag
*/
static void
gst_cmml_parser_parse_start_element_ns (xmlParserCtxt * ctxt,
const xmlChar * name, const xmlChar * prefix, const xmlChar * URI,
int nb_preferences, const xmlChar ** namespaces,
int nb_attributes, int nb_defaulted, const xmlChar ** attributes)
{
GstCmmlParser *parser = (GstCmmlParser *) ctxt->_private;
xmlSAX2StartElementNs (ctxt, name, prefix, URI, nb_preferences, namespaces,
nb_attributes, nb_defaulted, attributes);
if (parser->mode == GST_CMML_PARSER_ENCODE)
if (!xmlStrcmp (name, (xmlChar *) "cmml"))
if (parser->preamble_callback)
/* FIXME: parse attributes */
gst_cmml_parser_parse_preamble (parser, NULL);
}
/* sax processing instruction handler
* used to parse the cmml processing instruction
*/
static void
gst_cmml_parser_parse_processing_instruction (xmlParserCtxtPtr ctxt,
const xmlChar * target, const xmlChar * data)
{
GstCmmlParser *parser = (GstCmmlParser *) ctxt->_private;
xmlSAX2ProcessingInstruction (ctxt, target, data);
if (parser->mode == GST_CMML_PARSER_DECODE)
if (!xmlStrcmp (target, (xmlChar *) "cmml"))
if (parser->preamble_callback)
gst_cmml_parser_parse_preamble (parser, data);
}
/* sax handler called when an xml end tag is found
* used to parse the stream, head and clip nodes
*/
static void
gst_cmml_parser_parse_end_element_ns (xmlParserCtxt * ctxt,
const xmlChar * name, const xmlChar * prefix, const xmlChar * URI)
{
xmlNodePtr node;
GstCmmlParser *parser = (GstCmmlParser *) ctxt->_private;
xmlSAX2EndElementNs (ctxt, name, prefix, URI);
if (!xmlStrcmp (name, (xmlChar *) "clip")) {
if (parser->clip_callback) {
node = gst_cmml_parser_get_last_element (parser);
gst_cmml_parser_parse_clip (parser, node);
}
} else if (!xmlStrcmp (name, (xmlChar *) "cmml")) {
if (parser->cmml_end_callback)
parser->cmml_end_callback (parser->user_data);
} else if (!xmlStrcmp (name, (xmlChar *) "stream")) {
if (parser->stream_callback) {
node = gst_cmml_parser_get_last_element (parser);
gst_cmml_parser_parse_stream (parser, node);
}
} else if (!xmlStrcmp (name, (xmlChar *) "head")) {
if (parser->head_callback) {
node = gst_cmml_parser_get_last_element (parser);
gst_cmml_parser_parse_head (parser, node);
}
}
}
| lgpl-2.1 |
gittup/uClibc | libc/sysdeps/linux/common/getdirname.c | 17 | 1732 | /* vi: set sw=4 ts=4: */
/* Copyright (C) 1992, 1997, 1998, 2000 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#include <features.h>
#ifdef __USE_GNU
#include <unistd.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
/* Return a malloc'd string containing the current directory name.
If the environment variable `PWD' is set, and its value is correct,
that value is used. */
char *
get_current_dir_name (void)
{
char *pwd;
#ifdef __UCLIBC_HAS_LFS__
struct stat64 dotstat, pwdstat;
#else
struct stat dotstat, pwdstat;
#endif
pwd = getenv ("PWD");
if (pwd != NULL
#ifdef __UCLIBC_HAS_LFS__
&& stat64 (".", &dotstat) == 0
&& stat64 (pwd, &pwdstat) == 0
#else
&& stat (".", &dotstat) == 0
&& stat (pwd, &pwdstat) == 0
#endif
&& pwdstat.st_dev == dotstat.st_dev
&& pwdstat.st_ino == dotstat.st_ino)
/* The PWD value is correct. Use it. */
return strdup (pwd);
return getcwd ((char *) NULL, 0);
}
#endif
| lgpl-2.1 |
davidgfnet/uClibc-Os | libm/i386/fgetexcptflg.c | 21 | 1218 | /* Store current representation for exceptions.
Copyright (C) 1997,99,2000,01 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Ulrich Drepper <drepper@cygnus.com>, 1997.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#include <fenv.h>
int
fegetexceptflag (fexcept_t *flagp, int excepts)
{
fexcept_t temp;
/* Get the current exceptions. */
__asm__ ("fnstsw %0" : "=m" (*&temp));
*flagp = temp & excepts & FE_ALL_EXCEPT;
/* Success. */
return 0;
}
| lgpl-2.1 |
kobolabs/qt-everywhere-4.8.0 | src/3rdparty/clucene/src/CLucene/document/Document.cpp | 21 | 6598 | /*------------------------------------------------------------------------------
* Copyright (C) 2003-2006 Ben van Klinken and the CLucene Team
*
* Distributable under the terms of either the Apache License (Version 2.0) or
* the GNU Lesser General Public License, as specified in the COPYING file.
------------------------------------------------------------------------------*/
#include "CLucene/StdHeader.h"
#include "Document.h"
#include "Field.h"
#include "CLucene/util/StringBuffer.h"
CL_NS_USE(util)
CL_NS_DEF(document)
DocumentFieldEnumeration::DocumentFieldList::DocumentFieldList(Field* f, DocumentFieldList* n ) {
//Func - Constructor
//Pre - f != NULL
// n may be NULL
//Post - Instance has been created
CND_PRECONDITION(f != NULL, "f is NULL");
field = f;
next = n;
}
DocumentFieldEnumeration::DocumentFieldList::~DocumentFieldList(){
//Func - Destructor
//Pre - true
//Post - Instance has been destroyed
// Instead of recursively deleting the field list we do
// it iteratively to avoid stack overflows when
// dealing with several thousands of fields.
if (!field) {
return; // nothing to do; deleted by different invocation of dtor
}
DocumentFieldList* cur = next;
while (cur != NULL)
{
DocumentFieldList* temp = cur->next;
cur->next = NULL;
_CLDELETE(cur);
cur = temp;
}
_CLDELETE(field);
}
DocumentFieldEnumeration::DocumentFieldEnumeration(const DocumentFieldList* fl){
//Func - Constructor
//Pre - fl may be NULL
//Post - Instance has been created
fields = fl;
}
DocumentFieldEnumeration::~DocumentFieldEnumeration(){
//Func - Destructor
//Pre - true
//Post - Instance has been destroyed
}
bool DocumentFieldEnumeration::hasMoreElements() const {
return fields == NULL ? false : true;
}
Field* DocumentFieldEnumeration::nextElement() {
//Func - Return the next element in the enumeration
//Pre - true
//Post - The next element is returned or NULL
Field* result = NULL;
//Check if fields is still valid
if (fields){
result = fields->field;
fields = fields->next;
}
return result;
}
/** Constructs a new document with no fields. */
Document::Document(){
//Func - Constructor
//Pre - true
//Post - Instance has been created
boost = 1.0f;
fieldList = NULL;
}
Document::~Document(){
//Func - Destructor
//Pre - true
//Post - Instance has been destroyed
boost = 1.0f;
_CLDELETE(fieldList);
}
void Document::clear(){
_CLDELETE(fieldList);
}
void Document::add(Field& field) {
fieldList = _CLNEW DocumentFieldEnumeration::DocumentFieldList(&field, fieldList);
}
void Document::setBoost(qreal boost) {
this->boost = boost;
}
qreal Document::getBoost() const {
return boost;
}
Field* Document::getField(const TCHAR* name) const{
CND_PRECONDITION(name != NULL, "name is NULL");
for (DocumentFieldEnumeration::DocumentFieldList* list = fieldList; list != NULL; list = list->next)
//cannot use interning here, because name is probably not interned
if ( _tcscmp(list->field->name(), name) == 0 ){
return list->field;
}
return NULL;
}
const TCHAR* Document::get(const TCHAR* field) const {
CND_PRECONDITION(field != NULL, "field is NULL");
Field *f = getField(field);
if (f!=NULL)
return f->stringValue(); //this returns null it is a binary(reader)
else
return NULL;
}
DocumentFieldEnumeration* Document::fields() const {
return _CLNEW DocumentFieldEnumeration(fieldList);
}
TCHAR* Document::toString() const {
StringBuffer ret(_T("Document<"));
for (DocumentFieldEnumeration::DocumentFieldList* list = fieldList; list != NULL; list = list->next) {
TCHAR* tmp = list->field->toString();
ret.append( tmp );
if (list->next != NULL)
ret.append(_T(" "));
_CLDELETE_ARRAY( tmp );
}
ret.append(_T(">"));
return ret.toString();
}
void Document::removeField(const TCHAR* name) {
CND_PRECONDITION(name != NULL, "name is NULL");
DocumentFieldEnumeration::DocumentFieldList* previous = NULL;
DocumentFieldEnumeration::DocumentFieldList* current = fieldList;
while (current != NULL) {
//cannot use interning here, because name is probably not interned
if ( _tcscmp(current->field->name(),name) == 0 ){
if (previous){
previous->next = current->next;
}else
fieldList = current->next;
current->next=NULL; //ensure fieldlist destructor doesnt delete it
_CLDELETE(current);
return;
}
previous = current;
current = current->next;
}
}
void Document::removeFields(const TCHAR* name) {
CND_PRECONDITION(name != NULL, "name is NULL");
DocumentFieldEnumeration::DocumentFieldList* previous = NULL;
DocumentFieldEnumeration::DocumentFieldList* current = fieldList;
while (current != NULL) {
//cannot use interning here, because name is probably not interned
if ( _tcscmp(current->field->name(),name) == 0 ){
if (previous){
previous->next = current->next;
}else
fieldList = current->next;
current->next=NULL; //ensure fieldlist destructor doesnt delete it
_CLDELETE(current);
if ( previous )
current = previous->next;
else
current = fieldList;
}else{
previous = current;
current = current->next;
}
}
}
TCHAR** Document::getValues(const TCHAR* name) {
DocumentFieldEnumeration* it = fields();
int32_t count = 0;
while ( it->hasMoreElements() ){
Field* f = it->nextElement();
//cannot use interning here, because name is probably not interned
if ( _tcscmp(f->name(),name) == 0 && f->stringValue() != NULL )
count++;
}
_CLDELETE(it);
it = fields();
//todo: there must be a better way of doing this, we are doing two iterations of the fields
TCHAR** ret = NULL;
if ( count > 0 ){
//start again
ret = _CL_NEWARRAY(TCHAR*,count+1);
int32_t i=0;
while ( it->hasMoreElements() ){
Field* fld=it->nextElement();
if ( _tcscmp(fld->name(),name)== 0 && fld->stringValue() != NULL ){
ret[i] = stringDuplicate(fld->stringValue());
i++;
}
}
ret[count]=NULL;
}
_CLDELETE(it);
return ret;
}
CL_NS_END
| lgpl-2.1 |
vijayyande/spserver | spserver/spsession.cpp | 27 | 5893 | /*
* Copyright 2007-2008 Stephen Liu
* For license terms, see the file COPYING along with this library.
*/
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "spporting.hpp"
#include "spsession.hpp"
#include "sphandler.hpp"
#include "spbuffer.hpp"
#include "sputils.hpp"
#include "sprequest.hpp"
#include "spiochannel.hpp"
#ifndef WIN32
#include "event.h"
#endif
//-------------------------------------------------------------------
typedef struct tagSP_SessionEntry {
uint16_t mSeq;
uint16_t mNext;
SP_Session * mSession;
} SP_SessionEntry;
SP_SessionManager :: SP_SessionManager()
{
mFreeCount = 0;
mFreeList = 0;
mCount = 0;
memset( mArray, 0, sizeof( mArray ) );
}
SP_SessionManager :: ~SP_SessionManager()
{
for( int i = 0; i < (int)( sizeof( mArray ) / sizeof( mArray[0] ) ); i++ ) {
SP_SessionEntry_t * list = mArray[ i ];
if( NULL != list ) {
SP_SessionEntry_t * iter = list;
for( int i = 0; i < eColPerRow; i++, iter++ ) {
if( NULL != iter->mSession ) {
delete iter->mSession;
iter->mSession = NULL;
}
}
free( list );
}
}
memset( mArray, 0, sizeof( mArray ) );
}
uint16_t SP_SessionManager :: allocKey( uint16_t * seq )
{
uint16_t key = 0;
if( mFreeList <= 0 ) {
int avail = -1;
for( int i = 1; i < (int)( sizeof( mArray ) / sizeof( mArray[0] ) ); i++ ) {
if( NULL == mArray[i] ) {
avail = i;
break;
}
}
if( avail > 0 ) {
mFreeCount += eColPerRow;
mArray[ avail ] = ( SP_SessionEntry_t * )calloc(
eColPerRow, sizeof( SP_SessionEntry_t ) );
for( int i = eColPerRow - 1; i >= 0; i-- ) {
mArray[ avail ] [ i ].mNext = mFreeList;
mFreeList = eColPerRow * avail + i;
}
}
}
if( mFreeList > 0 ) {
key = mFreeList;
--mFreeCount;
int row = mFreeList / eColPerRow, col = mFreeList % eColPerRow;
*seq = mArray[ row ] [ col ].mSeq;
mFreeList = mArray[ row ] [ col ].mNext;
}
return key;
}
int SP_SessionManager :: getCount()
{
return mCount;
}
int SP_SessionManager :: getFreeCount()
{
return mFreeCount;
}
void SP_SessionManager :: put( uint16_t key, uint16_t seq, SP_Session * session )
{
int row = key / eColPerRow, col = key % eColPerRow;
assert( NULL != mArray[ row ] );
SP_SessionEntry_t * list = mArray[ row ];
assert( NULL == list[ col ].mSession );
assert( seq == list[ col ].mSeq );
list[ col ].mSession = session;
mCount++;
}
SP_Session * SP_SessionManager :: get( uint16_t key, uint16_t * seq )
{
int row = key / eColPerRow, col = key % eColPerRow;
SP_Session * ret = NULL;
SP_SessionEntry_t * list = mArray[ row ];
if( NULL != list ) {
ret = list[ col ].mSession;
* seq = list[ col ].mSeq;
} else {
* seq = 0;
}
return ret;
}
SP_Session * SP_SessionManager :: remove( uint16_t key, uint16_t seq )
{
int row = key / eColPerRow, col = key % eColPerRow;
SP_Session * ret = NULL;
SP_SessionEntry_t * list = mArray[ row ];
if( NULL != list ) {
assert( seq == list[ col ].mSeq );
ret = list[ col ].mSession;
list[ col ].mSession = NULL;
list[ col ].mSeq++;
list[ col ].mNext = mFreeList;
mFreeList = key;
++mFreeCount;
mCount--;
}
return ret;
}
//-------------------------------------------------------------------
SP_Session :: SP_Session( SP_Sid_t sid )
{
mSid = sid;
mReadEvent = NULL;
mWriteEvent = NULL;
#ifndef WIN32
mReadEvent = (struct event*)malloc( sizeof( struct event ) );
mWriteEvent = (struct event*)malloc( sizeof( struct event ) );
#endif
mHandler = NULL;
mArg = NULL;
mInBuffer = new SP_Buffer();
mRequest = new SP_Request();
mOutOffset = 0;
mOutList = new SP_ArrayList();
mStatus = eNormal;
mRunning = 0;
mWriting = 0;
mReading = 0;
mTotalRead = mTotalWrite = 0;
mIOChannel = NULL;
}
SP_Session :: ~SP_Session()
{
if( NULL != mReadEvent ) free( mReadEvent );
mReadEvent = NULL;
if( NULL != mWriteEvent ) free( mWriteEvent );
mWriteEvent = NULL;
if( NULL != mHandler ) {
delete mHandler;
mHandler = NULL;
}
delete mRequest;
mRequest = NULL;
delete mInBuffer;
mInBuffer = NULL;
delete mOutList;
mOutList = NULL;
if( NULL != mIOChannel ) {
delete mIOChannel;
mIOChannel = NULL;
}
}
struct event * SP_Session :: getReadEvent()
{
return mReadEvent;
}
struct event * SP_Session :: getWriteEvent()
{
return mWriteEvent;
}
void SP_Session :: setHandler( SP_Handler * handler )
{
mHandler = handler;
}
SP_Handler * SP_Session :: getHandler()
{
return mHandler;
}
void SP_Session :: setArg( void * arg )
{
mArg = arg;
}
void * SP_Session :: getArg()
{
return mArg;
}
SP_Sid_t SP_Session :: getSid()
{
return mSid;
}
SP_Buffer * SP_Session :: getInBuffer()
{
return mInBuffer;
}
SP_Request * SP_Session :: getRequest()
{
return mRequest;
}
void SP_Session :: setOutOffset( int offset )
{
mOutOffset = offset;
}
int SP_Session :: getOutOffset()
{
return mOutOffset;
}
SP_ArrayList * SP_Session :: getOutList()
{
return mOutList;
}
void SP_Session :: setStatus( int status )
{
mStatus = status;
}
int SP_Session :: getStatus()
{
return mStatus;
}
int SP_Session :: getRunning()
{
return mRunning;
}
void SP_Session :: setRunning( int running )
{
mRunning = running;
}
int SP_Session :: getWriting()
{
return mWriting;
}
void SP_Session :: setWriting( int writing )
{
mWriting = writing;
}
int SP_Session :: getReading()
{
return mReading;
}
void SP_Session :: setReading( int reading )
{
mReading = reading;
}
SP_IOChannel * SP_Session :: getIOChannel()
{
return mIOChannel;
}
void SP_Session :: setIOChannel( SP_IOChannel * ioChannel )
{
mIOChannel = ioChannel;
}
unsigned int SP_Session :: getTotalRead()
{
return mTotalRead;
}
void SP_Session :: addRead( int len )
{
mTotalRead += len;
}
unsigned int SP_Session :: getTotalWrite()
{
return mTotalWrite;
}
void SP_Session :: addWrite( int len )
{
mTotalWrite += len;
}
| lgpl-2.1 |
dslab-epfl/cloud9-uclibc | libpthread/linuxthreads/sysdeps/sparc/sparc32/sparcv9/pspinlock.c | 27 | 2591 | /* POSIX spinlock implementation. SPARC v9 version.
Copyright (C) 2000 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation; either version 2.1 of the
License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; see the file COPYING.LIB. If not,
write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA. */
#include <errno.h>
#include <pthread.h>
#include "internals.h"
/* This implementation is similar to the one used in the Linux kernel. */
int
__pthread_spin_lock (pthread_spinlock_t *lock)
{
__asm__ __volatile__
("1: ldstub [%0], %%g2\n"
" brnz,pn %%g2, 2f\n"
" membar #StoreLoad | #StoreStore\n"
".subsection 2\n"
"2: ldub [%0], %%g2\n"
" brnz,pt %%g2, 2b\n"
" membar #LoadLoad\n"
" b,a,pt %%xcc, 1b\n"
".previous"
: /* no outputs */
: "r" (lock)
: "g2", "memory");
return 0;
}
weak_alias (__pthread_spin_lock, pthread_spin_lock)
int
__pthread_spin_trylock (pthread_spinlock_t *lock)
{
int result;
__asm__ __volatile__
("ldstub [%1], %0\n"
"membar #StoreLoad | #StoreStore"
: "=r" (result)
: "r" (lock)
: "memory");
return result == 0 ? 0 : EBUSY;
}
weak_alias (__pthread_spin_trylock, pthread_spin_trylock)
int
__pthread_spin_unlock (pthread_spinlock_t *lock)
{
__asm__ __volatile__
("membar #StoreStore | #LoadStore\n"
"stb %%g0, [%0]"
:
: "r" (lock)
: "memory");
return 0;
}
weak_alias (__pthread_spin_unlock, pthread_spin_unlock)
int
__pthread_spin_init (pthread_spinlock_t *lock, int pshared)
{
/* We can ignore the `pshared' parameter. Since we are busy-waiting
all processes which can access the memory location `lock' points
to can use the spinlock. */
*lock = 0;
return 0;
}
weak_alias (__pthread_spin_init, pthread_spin_init)
int
__pthread_spin_destroy (pthread_spinlock_t *lock)
{
/* Nothing to do. */
return 0;
}
weak_alias (__pthread_spin_destroy, pthread_spin_destroy)
| lgpl-2.1 |
qianqians/Screw | 3rdparty/ammo.js/bullet/Extras/CDTestFramework/Opcode/OPC_PlanesCollider.cpp | 32 | 26412 | /*
* OPCODE - Optimized Collision Detection
* http://www.codercorner.com/Opcode.htm
*
* Copyright (c) 2001-2008 Pierre Terdiman, pierre@codercorner.com
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Contains code for a planes collider.
* \file OPC_PlanesCollider.cpp
* \author Pierre Terdiman
* \date January, 1st, 2002
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Contains a Planes-vs-tree collider.
*
* \class PlanesCollider
* \author Pierre Terdiman
* \version 1.3
* \date January, 1st, 2002
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Precompiled Header
#include "Stdafx.h"
using namespace Opcode;
#include "OPC_PlanesAABBOverlap.h"
#include "OPC_PlanesTriOverlap.h"
#define SET_CONTACT(prim_index, flag) \
/* Set contact status */ \
mFlags |= flag; \
mTouchedPrimitives->Add(prim_index);
//! Planes-triangle test
#define PLANES_PRIM(prim_index, flag) \
/* Request vertices from the app */ \
mIMesh->GetTriangle(mVP, prim_index); \
/* Perform triangle-box overlap test */ \
if(PlanesTriOverlap(clip_mask)) \
{ \
SET_CONTACT(prim_index, flag) \
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Constructor.
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PlanesCollider::PlanesCollider() :
mPlanes (null),
mNbPlanes (0)
{
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Destructor.
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PlanesCollider::~PlanesCollider()
{
DELETEARRAY(mPlanes);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Validates current settings. You should call this method after all the settings and callbacks have been defined.
* \return null if everything is ok, else a string describing the problem
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
const char* PlanesCollider::ValidateSettings()
{
if(TemporalCoherenceEnabled() && !FirstContactEnabled()) return "Temporal coherence only works with ""First contact"" mode!";
return VolumeCollider::ValidateSettings();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Generic collision query for generic OPCODE models. After the call, access the results:
* - with GetContactStatus()
* - with GetNbTouchedPrimitives()
* - with GetTouchedPrimitives()
*
* \param cache [in/out] a planes cache
* \param planes [in] list of planes in world space
* \param nb_planes [in] number of planes
* \param model [in] Opcode model to collide with
* \param worldm [in] model's world matrix, or null
* \return true if success
* \warning SCALE NOT SUPPORTED. The matrices must contain rotation & translation parts only.
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bool PlanesCollider::Collide(PlanesCache& cache, const Plane* planes, udword nb_planes, const Model& model, const Matrix4x4* worldm)
{
// Checkings
if(!Setup(&model)) return false;
// Init collision query
if(InitQuery(cache, planes, nb_planes, worldm)) return true;
udword PlaneMask = (1<<nb_planes)-1;
if(!model.HasLeafNodes())
{
if(model.IsQuantized())
{
const AABBQuantizedNoLeafTree* Tree = (const AABBQuantizedNoLeafTree*)model.GetTree();
// Setup dequantization coeffs
mCenterCoeff = Tree->mCenterCoeff;
mExtentsCoeff = Tree->mExtentsCoeff;
// Perform collision query
if(SkipPrimitiveTests()) _CollideNoPrimitiveTest(Tree->GetNodes(), PlaneMask);
else _Collide(Tree->GetNodes(), PlaneMask);
}
else
{
const AABBNoLeafTree* Tree = (const AABBNoLeafTree*)model.GetTree();
// Perform collision query
if(SkipPrimitiveTests()) _CollideNoPrimitiveTest(Tree->GetNodes(), PlaneMask);
else _Collide(Tree->GetNodes(), PlaneMask);
}
}
else
{
if(model.IsQuantized())
{
const AABBQuantizedTree* Tree = (const AABBQuantizedTree*)model.GetTree();
// Setup dequantization coeffs
mCenterCoeff = Tree->mCenterCoeff;
mExtentsCoeff = Tree->mExtentsCoeff;
// Perform collision query
if(SkipPrimitiveTests()) _CollideNoPrimitiveTest(Tree->GetNodes(), PlaneMask);
else _Collide(Tree->GetNodes(), PlaneMask);
}
else
{
const AABBCollisionTree* Tree = (const AABBCollisionTree*)model.GetTree();
// Perform collision query
if(SkipPrimitiveTests()) _CollideNoPrimitiveTest(Tree->GetNodes(), PlaneMask);
else _Collide(Tree->GetNodes(), PlaneMask);
}
}
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Initializes a collision query :
* - reset stats & contact status
* - compute planes in model space
* - check temporal coherence
*
* \param cache [in/out] a planes cache
* \param planes [in] list of planes
* \param nb_planes [in] number of planes
* \param worldm [in] model's world matrix, or null
* \return TRUE if we can return immediately
* \warning SCALE NOT SUPPORTED. The matrix must contain rotation & translation parts only.
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
BOOL PlanesCollider::InitQuery(PlanesCache& cache, const Plane* planes, udword nb_planes, const Matrix4x4* worldm)
{
// 1) Call the base method
VolumeCollider::InitQuery();
// 2) Compute planes in model space
if(nb_planes>mNbPlanes)
{
DELETEARRAY(mPlanes);
mPlanes = new Plane[nb_planes];
}
mNbPlanes = nb_planes;
if(worldm)
{
Matrix4x4 InvWorldM;
InvertPRMatrix(InvWorldM, *worldm);
// for(udword i=0;i<nb_planes;i++) mPlanes[i] = planes[i] * InvWorldM;
for(udword i=0;i<nb_planes;i++) TransformPlane(mPlanes[i], planes[i], InvWorldM);
}
else CopyMemory(mPlanes, planes, nb_planes*sizeof(Plane));
// 3) Setup destination pointer
mTouchedPrimitives = &cache.TouchedPrimitives;
// 4) Special case: 1-triangle meshes [Opcode 1.3]
if(mCurrentModel && mCurrentModel->HasSingleNode())
{
if(!SkipPrimitiveTests())
{
// We simply perform the BV-Prim overlap test each time. We assume single triangle has index 0.
mTouchedPrimitives->Reset();
// Perform overlap test between the unique triangle and the planes (and set contact status if needed)
udword clip_mask = (1<<mNbPlanes)-1;
PLANES_PRIM(udword(0), OPC_CONTACT)
// Return immediately regardless of status
return TRUE;
}
}
// 4) Check temporal coherence:
if(TemporalCoherenceEnabled())
{
// Here we use temporal coherence
// => check results from previous frame before performing the collision query
if(FirstContactEnabled())
{
// We're only interested in the first contact found => test the unique previously touched face
if(mTouchedPrimitives->GetNbEntries())
{
// Get index of previously touched face = the first entry in the array
udword PreviouslyTouchedFace = mTouchedPrimitives->GetEntry(0);
// Then reset the array:
// - if the overlap test below is successful, the index we'll get added back anyway
// - if it isn't, then the array should be reset anyway for the normal query
mTouchedPrimitives->Reset();
// Perform overlap test between the cached triangle and the planes (and set contact status if needed)
udword clip_mask = (1<<mNbPlanes)-1;
PLANES_PRIM(PreviouslyTouchedFace, OPC_TEMPORAL_CONTACT)
// Return immediately if possible
if(GetContactStatus()) return TRUE;
}
// else no face has been touched during previous query
// => we'll have to perform a normal query
}
else mTouchedPrimitives->Reset();
}
else
{
// Here we don't use temporal coherence => do a normal query
mTouchedPrimitives->Reset();
}
return FALSE;
}
#define TEST_CLIP_MASK \
/* If the box is completely included, so are its children. We don't need to do extra tests, we */ \
/* can immediately output a list of visible children. Those ones won't need to be clipped. */ \
if(!OutClipMask) \
{ \
/* Set contact status */ \
mFlags |= OPC_CONTACT; \
_Dump(node); \
return; \
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Recursive collision query for normal AABB trees.
* \param node [in] current collision node
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void PlanesCollider::_Collide(const AABBCollisionNode* node, udword clip_mask)
{
// Test the box against the planes. If the box is completely culled, so are its children, hence we exit.
udword OutClipMask;
if(!PlanesAABBOverlap(node->mAABB.mCenter, node->mAABB.mExtents, OutClipMask, clip_mask)) return;
TEST_CLIP_MASK
// Else the box straddles one or several planes, so we need to recurse down the tree.
if(node->IsLeaf())
{
PLANES_PRIM(node->GetPrimitive(), OPC_CONTACT)
}
else
{
_Collide(node->GetPos(), OutClipMask);
if(ContactFound()) return;
_Collide(node->GetNeg(), OutClipMask);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Recursive collision query for normal AABB trees.
* \param node [in] current collision node
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void PlanesCollider::_CollideNoPrimitiveTest(const AABBCollisionNode* node, udword clip_mask)
{
// Test the box against the planes. If the box is completely culled, so are its children, hence we exit.
udword OutClipMask;
if(!PlanesAABBOverlap(node->mAABB.mCenter, node->mAABB.mExtents, OutClipMask, clip_mask)) return;
TEST_CLIP_MASK
// Else the box straddles one or several planes, so we need to recurse down the tree.
if(node->IsLeaf())
{
SET_CONTACT(node->GetPrimitive(), OPC_CONTACT)
}
else
{
_CollideNoPrimitiveTest(node->GetPos(), OutClipMask);
if(ContactFound()) return;
_CollideNoPrimitiveTest(node->GetNeg(), OutClipMask);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Recursive collision query for quantized AABB trees.
* \param node [in] current collision node
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void PlanesCollider::_Collide(const AABBQuantizedNode* node, udword clip_mask)
{
// Dequantize box
const QuantizedAABB& Box = node->mAABB;
const Point Center(float(Box.mCenter[0]) * mCenterCoeff.x, float(Box.mCenter[1]) * mCenterCoeff.y, float(Box.mCenter[2]) * mCenterCoeff.z);
const Point Extents(float(Box.mExtents[0]) * mExtentsCoeff.x, float(Box.mExtents[1]) * mExtentsCoeff.y, float(Box.mExtents[2]) * mExtentsCoeff.z);
// Test the box against the planes. If the box is completely culled, so are its children, hence we exit.
udword OutClipMask;
if(!PlanesAABBOverlap(Center, Extents, OutClipMask, clip_mask)) return;
TEST_CLIP_MASK
// Else the box straddles one or several planes, so we need to recurse down the tree.
if(node->IsLeaf())
{
PLANES_PRIM(node->GetPrimitive(), OPC_CONTACT)
}
else
{
_Collide(node->GetPos(), OutClipMask);
if(ContactFound()) return;
_Collide(node->GetNeg(), OutClipMask);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Recursive collision query for quantized AABB trees.
* \param node [in] current collision node
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void PlanesCollider::_CollideNoPrimitiveTest(const AABBQuantizedNode* node, udword clip_mask)
{
// Dequantize box
const QuantizedAABB& Box = node->mAABB;
const Point Center(float(Box.mCenter[0]) * mCenterCoeff.x, float(Box.mCenter[1]) * mCenterCoeff.y, float(Box.mCenter[2]) * mCenterCoeff.z);
const Point Extents(float(Box.mExtents[0]) * mExtentsCoeff.x, float(Box.mExtents[1]) * mExtentsCoeff.y, float(Box.mExtents[2]) * mExtentsCoeff.z);
// Test the box against the planes. If the box is completely culled, so are its children, hence we exit.
udword OutClipMask;
if(!PlanesAABBOverlap(Center, Extents, OutClipMask, clip_mask)) return;
TEST_CLIP_MASK
// Else the box straddles one or several planes, so we need to recurse down the tree.
if(node->IsLeaf())
{
SET_CONTACT(node->GetPrimitive(), OPC_CONTACT)
}
else
{
_CollideNoPrimitiveTest(node->GetPos(), OutClipMask);
if(ContactFound()) return;
_CollideNoPrimitiveTest(node->GetNeg(), OutClipMask);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Recursive collision query for no-leaf AABB trees.
* \param node [in] current collision node
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void PlanesCollider::_Collide(const AABBNoLeafNode* node, udword clip_mask)
{
// Test the box against the planes. If the box is completely culled, so are its children, hence we exit.
udword OutClipMask;
if(!PlanesAABBOverlap(node->mAABB.mCenter, node->mAABB.mExtents, OutClipMask, clip_mask)) return;
TEST_CLIP_MASK
// Else the box straddles one or several planes, so we need to recurse down the tree.
if(node->HasPosLeaf()) { PLANES_PRIM(node->GetPosPrimitive(), OPC_CONTACT) }
else _Collide(node->GetPos(), OutClipMask);
if(ContactFound()) return;
if(node->HasNegLeaf()) { PLANES_PRIM(node->GetNegPrimitive(), OPC_CONTACT) }
else _Collide(node->GetNeg(), OutClipMask);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Recursive collision query for no-leaf AABB trees.
* \param node [in] current collision node
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void PlanesCollider::_CollideNoPrimitiveTest(const AABBNoLeafNode* node, udword clip_mask)
{
// Test the box against the planes. If the box is completely culled, so are its children, hence we exit.
udword OutClipMask;
if(!PlanesAABBOverlap(node->mAABB.mCenter, node->mAABB.mExtents, OutClipMask, clip_mask)) return;
TEST_CLIP_MASK
// Else the box straddles one or several planes, so we need to recurse down the tree.
if(node->HasPosLeaf()) { SET_CONTACT(node->GetPosPrimitive(), OPC_CONTACT) }
else _CollideNoPrimitiveTest(node->GetPos(), OutClipMask);
if(ContactFound()) return;
if(node->HasNegLeaf()) { SET_CONTACT(node->GetNegPrimitive(), OPC_CONTACT) }
else _CollideNoPrimitiveTest(node->GetNeg(), OutClipMask);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Recursive collision query for quantized no-leaf AABB trees.
* \param node [in] current collision node
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void PlanesCollider::_Collide(const AABBQuantizedNoLeafNode* node, udword clip_mask)
{
// Dequantize box
const QuantizedAABB& Box = node->mAABB;
const Point Center(float(Box.mCenter[0]) * mCenterCoeff.x, float(Box.mCenter[1]) * mCenterCoeff.y, float(Box.mCenter[2]) * mCenterCoeff.z);
const Point Extents(float(Box.mExtents[0]) * mExtentsCoeff.x, float(Box.mExtents[1]) * mExtentsCoeff.y, float(Box.mExtents[2]) * mExtentsCoeff.z);
// Test the box against the planes. If the box is completely culled, so are its children, hence we exit.
udword OutClipMask;
if(!PlanesAABBOverlap(Center, Extents, OutClipMask, clip_mask)) return;
TEST_CLIP_MASK
// Else the box straddles one or several planes, so we need to recurse down the tree.
if(node->HasPosLeaf()) { PLANES_PRIM(node->GetPosPrimitive(), OPC_CONTACT) }
else _Collide(node->GetPos(), OutClipMask);
if(ContactFound()) return;
if(node->HasNegLeaf()) { PLANES_PRIM(node->GetNegPrimitive(), OPC_CONTACT) }
else _Collide(node->GetNeg(), OutClipMask);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Recursive collision query for quantized no-leaf AABB trees.
* \param node [in] current collision node
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void PlanesCollider::_CollideNoPrimitiveTest(const AABBQuantizedNoLeafNode* node, udword clip_mask)
{
// Dequantize box
const QuantizedAABB& Box = node->mAABB;
const Point Center(float(Box.mCenter[0]) * mCenterCoeff.x, float(Box.mCenter[1]) * mCenterCoeff.y, float(Box.mCenter[2]) * mCenterCoeff.z);
const Point Extents(float(Box.mExtents[0]) * mExtentsCoeff.x, float(Box.mExtents[1]) * mExtentsCoeff.y, float(Box.mExtents[2]) * mExtentsCoeff.z);
// Test the box against the planes. If the box is completely culled, so are its children, hence we exit.
udword OutClipMask;
if(!PlanesAABBOverlap(Center, Extents, OutClipMask, clip_mask)) return;
TEST_CLIP_MASK
// Else the box straddles one or several planes, so we need to recurse down the tree.
if(node->HasPosLeaf()) { SET_CONTACT(node->GetPosPrimitive(), OPC_CONTACT) }
else _CollideNoPrimitiveTest(node->GetPos(), OutClipMask);
if(ContactFound()) return;
if(node->HasNegLeaf()) { SET_CONTACT(node->GetNegPrimitive(), OPC_CONTACT) }
else _CollideNoPrimitiveTest(node->GetNeg(), OutClipMask);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Constructor.
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
HybridPlanesCollider::HybridPlanesCollider()
{
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Destructor.
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
HybridPlanesCollider::~HybridPlanesCollider()
{
}
bool HybridPlanesCollider::Collide(PlanesCache& cache, const Plane* planes, udword nb_planes, const HybridModel& model, const Matrix4x4* worldm)
{
// We don't want primitive tests here!
mFlags |= OPC_NO_PRIMITIVE_TESTS;
// Checkings
if(!Setup(&model)) return false;
// Init collision query
if(InitQuery(cache, planes, nb_planes, worldm)) return true;
// Special case for 1-leaf trees
if(mCurrentModel && mCurrentModel->HasSingleNode())
{
// Here we're supposed to perform a normal query, except our tree has a single node, i.e. just a few triangles
udword Nb = mIMesh->GetNbTriangles();
// Loop through all triangles
udword clip_mask = (1<<mNbPlanes)-1;
for(udword i=0;i<Nb;i++)
{
PLANES_PRIM(i, OPC_CONTACT)
}
return true;
}
// Override destination array since we're only going to get leaf boxes here
mTouchedBoxes.Reset();
mTouchedPrimitives = &mTouchedBoxes;
udword PlaneMask = (1<<nb_planes)-1;
// Now, do the actual query against leaf boxes
if(!model.HasLeafNodes())
{
if(model.IsQuantized())
{
const AABBQuantizedNoLeafTree* Tree = (const AABBQuantizedNoLeafTree*)model.GetTree();
// Setup dequantization coeffs
mCenterCoeff = Tree->mCenterCoeff;
mExtentsCoeff = Tree->mExtentsCoeff;
// Perform collision query - we don't want primitive tests here!
_CollideNoPrimitiveTest(Tree->GetNodes(), PlaneMask);
}
else
{
const AABBNoLeafTree* Tree = (const AABBNoLeafTree*)model.GetTree();
// Perform collision query - we don't want primitive tests here!
_CollideNoPrimitiveTest(Tree->GetNodes(), PlaneMask);
}
}
else
{
if(model.IsQuantized())
{
const AABBQuantizedTree* Tree = (const AABBQuantizedTree*)model.GetTree();
// Setup dequantization coeffs
mCenterCoeff = Tree->mCenterCoeff;
mExtentsCoeff = Tree->mExtentsCoeff;
// Perform collision query - we don't want primitive tests here!
_CollideNoPrimitiveTest(Tree->GetNodes(), PlaneMask);
}
else
{
const AABBCollisionTree* Tree = (const AABBCollisionTree*)model.GetTree();
// Perform collision query - we don't want primitive tests here!
_CollideNoPrimitiveTest(Tree->GetNodes(), PlaneMask);
}
}
// We only have a list of boxes so far
if(GetContactStatus())
{
// Reset contact status, since it currently only reflects collisions with leaf boxes
Collider::InitQuery();
// Change dest container so that we can use built-in overlap tests and get collided primitives
cache.TouchedPrimitives.Reset();
mTouchedPrimitives = &cache.TouchedPrimitives;
// Read touched leaf boxes
udword Nb = mTouchedBoxes.GetNbEntries();
const udword* Touched = mTouchedBoxes.GetEntries();
const LeafTriangles* LT = model.GetLeafTriangles();
const udword* Indices = model.GetIndices();
// Loop through touched leaves
udword clip_mask = (1<<mNbPlanes)-1;
while(Nb--)
{
const LeafTriangles& CurrentLeaf = LT[*Touched++];
// Each leaf box has a set of triangles
udword NbTris = CurrentLeaf.GetNbTriangles();
if(Indices)
{
const udword* T = &Indices[CurrentLeaf.GetTriangleIndex()];
// Loop through triangles and test each of them
while(NbTris--)
{
udword TriangleIndex = *T++;
PLANES_PRIM(TriangleIndex, OPC_CONTACT)
}
}
else
{
udword BaseIndex = CurrentLeaf.GetTriangleIndex();
// Loop through triangles and test each of them
while(NbTris--)
{
udword TriangleIndex = BaseIndex++;
PLANES_PRIM(TriangleIndex, OPC_CONTACT)
}
}
}
}
return true;
}
| lgpl-2.1 |
bbockelm/root-historical | interpreter/llvm/src/tools/clang/test/Index/complete-super.cpp | 44 | 1883 | // The run lines are below, because this test is line- and
// column-number sensitive.
struct A {
virtual void foo(int x, int y);
virtual void bar(double x);
virtual void bar(float x);
};
struct B : A {
void foo(int a, int b);
void bar(float real);
};
void B::foo(int a, int b) {
A::foo(a, b);
}
void B::bar(float real) {
A::bar(real);
}
// RUN: c-index-test -code-completion-at=%s:16:3 %s | FileCheck -check-prefix=CHECK-FOO-UNQUAL %s
// CHECK-FOO-UNQUAL: CXXMethod:{Text A::}{TypedText foo}{LeftParen (}{Placeholder a}{Comma , }{Placeholder b}{RightParen )} (20)
// RUN: c-index-test -code-completion-at=%s:20:3 %s | FileCheck -check-prefix=CHECK-BAR-UNQUAL %s
// CHECK-BAR-UNQUAL: CXXMethod:{Text A::}{TypedText bar}{LeftParen (}{Placeholder real}{RightParen )} (20)
// CHECK-BAR-UNQUAL: CXXMethod:{ResultType void}{TypedText bar}{LeftParen (}{Placeholder float real}{RightParen )} (34)
// CHECK-BAR-UNQUAL: CXXMethod:{ResultType void}{Text A::}{TypedText bar}{LeftParen (}{Placeholder double x}{RightParen )} (36)
// RUN: c-index-test -code-completion-at=%s:16:6 %s | FileCheck -check-prefix=CHECK-FOO-QUAL %s
// CHECK-FOO-QUAL: CXXMethod:{TypedText foo}{LeftParen (}{Placeholder a}{Comma , }{Placeholder b}{RightParen )} (20)
// RUN: c-index-test -code-completion-at=%s:5:1 %s | FileCheck -check-prefix=CHECK-ACCESS %s
// CHECK-ACCESS: NotImplemented:{TypedText private} (40)
// CHECK-ACCESS: NotImplemented:{TypedText protected} (40)
// CHECK-ACCESS: NotImplemented:{TypedText public} (40)
// RUN: env CINDEXTEST_CODE_COMPLETE_PATTERNS=1 c-index-test -code-completion-at=%s:5:1 %s | FileCheck -check-prefix=CHECK-ACCESS-PATTERN %s
// CHECK-ACCESS-PATTERN: NotImplemented:{TypedText private}{Colon :} (40)
// CHECK-ACCESS-PATTERN: NotImplemented:{TypedText protected}{Colon :} (40)
// CHECK-ACCESS-PATTERN: NotImplemented:{TypedText public}{Colon :} (40)
| lgpl-2.1 |
codevog/cv-qrcode | Example/Pods/ZBarSDK/zbar/img_scanner.c | 70 | 27212 | /*------------------------------------------------------------------------
* Copyright 2007-2010 (c) Jeff Brown <spadix@users.sourceforge.net>
*
* This file is part of the ZBar Bar Code Reader.
*
* The ZBar Bar Code Reader is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* The ZBar Bar Code Reader is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with the ZBar Bar Code Reader; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* http://sourceforge.net/projects/zbar
*------------------------------------------------------------------------*/
#include <config.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef HAVE_INTTYPES_H
# include <inttypes.h>
#endif
#include <stdlib.h> /* malloc, free */
#include <string.h> /* memcmp, memset, memcpy */
#include <assert.h>
#include <zbar.h>
#include "error.h"
#include "image.h"
#include "timer.h"
#ifdef ENABLE_QRCODE
# include "qrcode.h"
#endif
#include "img_scanner.h"
#include "svg.h"
#if 1
# define ASSERT_POS \
assert(p == data + x + y * (intptr_t)w)
#else
# define ASSERT_POS
#endif
/* FIXME cache setting configurability */
/* time interval for which two images are considered "nearby"
*/
#define CACHE_PROXIMITY 1000 /* ms */
/* time that a result must *not* be detected before
* it will be reported again
*/
#define CACHE_HYSTERESIS 2000 /* ms */
/* time after which cache entries are invalidated
*/
#define CACHE_TIMEOUT (CACHE_HYSTERESIS * 2) /* ms */
#define NUM_SCN_CFGS (ZBAR_CFG_Y_DENSITY - ZBAR_CFG_X_DENSITY + 1)
#define CFG(iscn, cfg) ((iscn)->configs[(cfg) - ZBAR_CFG_X_DENSITY])
#define TEST_CFG(iscn, cfg) (((iscn)->config >> ((cfg) - ZBAR_CFG_POSITION)) & 1)
#ifndef NO_STATS
# define STAT(x) iscn->stat_##x++
#else
# define STAT(...)
# define dump_stats(...)
#endif
#define RECYCLE_BUCKETS 5
typedef struct recycle_bucket_s {
int nsyms;
zbar_symbol_t *head;
} recycle_bucket_t;
/* image scanner state */
struct zbar_image_scanner_s {
zbar_scanner_t *scn; /* associated linear intensity scanner */
zbar_decoder_t *dcode; /* associated symbol decoder */
#ifdef ENABLE_QRCODE
qr_reader *qr; /* QR Code 2D reader */
#endif
const void *userdata; /* application data */
/* user result callback */
zbar_image_data_handler_t *handler;
unsigned long time; /* scan start time */
zbar_image_t *img; /* currently scanning image *root* */
int dx, dy, du, umin, v; /* current scan direction */
zbar_symbol_set_t *syms; /* previous decode results */
/* recycled symbols in 4^n size buckets */
recycle_bucket_t recycle[RECYCLE_BUCKETS];
int enable_cache; /* current result cache state */
zbar_symbol_t *cache; /* inter-image result cache entries */
/* configuration settings */
unsigned config; /* config flags */
unsigned ean_config;
int configs[NUM_SCN_CFGS]; /* int valued configurations */
int sym_configs[1][NUM_SYMS]; /* per-symbology configurations */
#ifndef NO_STATS
int stat_syms_new;
int stat_iscn_syms_inuse, stat_iscn_syms_recycle;
int stat_img_syms_inuse, stat_img_syms_recycle;
int stat_sym_new;
int stat_sym_recycle[RECYCLE_BUCKETS];
#endif
};
void _zbar_image_scanner_recycle_syms (zbar_image_scanner_t *iscn,
zbar_symbol_t *sym)
{
zbar_symbol_t *next = NULL;
for(; sym; sym = next) {
next = sym->next;
if(sym->refcnt && _zbar_refcnt(&sym->refcnt, -1)) {
/* unlink referenced symbol */
/* FIXME handle outstanding component refs (currently unsupported)
*/
assert(sym->data_alloc);
sym->next = NULL;
}
else {
int i;
recycle_bucket_t *bucket;
/* recycle unreferenced symbol */
if(!sym->data_alloc) {
sym->data = NULL;
sym->datalen = 0;
}
if(sym->syms) {
if(_zbar_refcnt(&sym->syms->refcnt, -1))
assert(0);
_zbar_image_scanner_recycle_syms(iscn, sym->syms->head);
sym->syms->head = NULL;
_zbar_symbol_set_free(sym->syms);
sym->syms = NULL;
}
for(i = 0; i < RECYCLE_BUCKETS; i++)
if(sym->data_alloc < 1 << (i * 2))
break;
if(i == RECYCLE_BUCKETS) {
assert(sym->data);
free(sym->data);
sym->data = NULL;
sym->data_alloc = 0;
i = 0;
}
bucket = &iscn->recycle[i];
/* FIXME cap bucket fill */
bucket->nsyms++;
sym->next = bucket->head;
bucket->head = sym;
}
}
}
static inline int recycle_syms (zbar_image_scanner_t *iscn,
zbar_symbol_set_t *syms)
{
if(_zbar_refcnt(&syms->refcnt, -1))
return(1);
_zbar_image_scanner_recycle_syms(iscn, syms->head);
syms->head = syms->tail = NULL;
syms->nsyms = 0;
return(0);
}
inline void zbar_image_scanner_recycle_image (zbar_image_scanner_t *iscn,
zbar_image_t *img)
{
zbar_symbol_set_t *syms = iscn->syms;
if(syms && syms->refcnt) {
if(recycle_syms(iscn, syms)) {
STAT(iscn_syms_inuse);
iscn->syms = NULL;
}
else
STAT(iscn_syms_recycle);
}
syms = img->syms;
img->syms = NULL;
if(syms && recycle_syms(iscn, syms))
STAT(img_syms_inuse);
else if(syms) {
STAT(img_syms_recycle);
/* select one set to resurrect, destroy the other */
if(iscn->syms)
_zbar_symbol_set_free(syms);
else
iscn->syms = syms;
}
}
inline zbar_symbol_t*
_zbar_image_scanner_alloc_sym (zbar_image_scanner_t *iscn,
zbar_symbol_type_t type,
int datalen)
{
/* recycle old or alloc new symbol */
zbar_symbol_t *sym = NULL;
int i;
for(i = 0; i < RECYCLE_BUCKETS - 1; i++)
if(datalen <= 1 << (i * 2))
break;
for(; i > 0; i--)
if((sym = iscn->recycle[i].head)) {
STAT(sym_recycle[i]);
break;
}
if(sym) {
iscn->recycle[i].head = sym->next;
sym->next = NULL;
assert(iscn->recycle[i].nsyms);
iscn->recycle[i].nsyms--;
}
else {
sym = calloc(1, sizeof(zbar_symbol_t));
STAT(sym_new);
}
/* init new symbol */
sym->type = type;
sym->quality = 1;
sym->npts = 0;
sym->orient = ZBAR_ORIENT_UNKNOWN;
sym->cache_count = 0;
sym->time = iscn->time;
assert(!sym->syms);
if(datalen > 0) {
sym->datalen = datalen - 1;
if(sym->data_alloc < datalen) {
if(sym->data)
free(sym->data);
sym->data_alloc = datalen;
sym->data = malloc(datalen);
}
}
else {
if(sym->data)
free(sym->data);
sym->data = NULL;
sym->datalen = sym->data_alloc = 0;
}
return(sym);
}
static inline zbar_symbol_t *cache_lookup (zbar_image_scanner_t *iscn,
zbar_symbol_t *sym)
{
/* search for matching entry in cache */
zbar_symbol_t **entry = &iscn->cache;
while(*entry) {
if((*entry)->type == sym->type &&
(*entry)->datalen == sym->datalen &&
!memcmp((*entry)->data, sym->data, sym->datalen))
break;
if((sym->time - (*entry)->time) > CACHE_TIMEOUT) {
/* recycle stale cache entry */
zbar_symbol_t *next = (*entry)->next;
(*entry)->next = NULL;
_zbar_image_scanner_recycle_syms(iscn, *entry);
*entry = next;
}
else
entry = &(*entry)->next;
}
return(*entry);
}
static inline void cache_sym (zbar_image_scanner_t *iscn,
zbar_symbol_t *sym)
{
if(iscn->enable_cache) {
uint32_t age, near_thresh, far_thresh, dup;
zbar_symbol_t *entry = cache_lookup(iscn, sym);
if(!entry) {
/* FIXME reuse sym */
entry = _zbar_image_scanner_alloc_sym(iscn, sym->type,
sym->datalen + 1);
entry->configs = sym->configs;
entry->modifiers = sym->modifiers;
memcpy(entry->data, sym->data, sym->datalen);
entry->time = sym->time - CACHE_HYSTERESIS;
entry->cache_count = 0;
/* add to cache */
entry->next = iscn->cache;
iscn->cache = entry;
}
/* consistency check and hysteresis */
age = sym->time - entry->time;
entry->time = sym->time;
near_thresh = (age < CACHE_PROXIMITY);
far_thresh = (age >= CACHE_HYSTERESIS);
dup = (entry->cache_count >= 0);
if((!dup && !near_thresh) || far_thresh) {
int type = sym->type;
int h = _zbar_get_symbol_hash(type);
entry->cache_count = -iscn->sym_configs[0][h];
}
else if(dup || near_thresh)
entry->cache_count++;
sym->cache_count = entry->cache_count;
}
else
sym->cache_count = 0;
}
void _zbar_image_scanner_add_sym(zbar_image_scanner_t *iscn,
zbar_symbol_t *sym)
{
zbar_symbol_set_t *syms;
cache_sym(iscn, sym);
syms = iscn->syms;
if(sym->cache_count || !syms->tail) {
sym->next = syms->head;
syms->head = sym;
}
else {
sym->next = syms->tail->next;
syms->tail->next = sym;
}
if(!sym->cache_count)
syms->nsyms++;
else if(!syms->tail)
syms->tail = sym;
_zbar_symbol_refcnt(sym, 1);
}
#ifdef ENABLE_QRCODE
extern qr_finder_line *_zbar_decoder_get_qr_finder_line(zbar_decoder_t*);
# define QR_FIXED(v, rnd) ((((v) << 1) + (rnd)) << (QR_FINDER_SUBPREC - 1))
# define PRINT_FIXED(val, prec) \
((val) >> (prec)), \
(1000 * ((val) & ((1 << (prec)) - 1)) / (1 << (prec)))
static inline void qr_handler (zbar_image_scanner_t *iscn)
{
unsigned u;
int vert;
qr_finder_line *line = _zbar_decoder_get_qr_finder_line(iscn->dcode);
assert(line);
u = zbar_scanner_get_edge(iscn->scn, line->pos[0],
QR_FINDER_SUBPREC);
line->boffs = u - zbar_scanner_get_edge(iscn->scn, line->boffs,
QR_FINDER_SUBPREC);
line->len = zbar_scanner_get_edge(iscn->scn, line->len,
QR_FINDER_SUBPREC);
line->eoffs = zbar_scanner_get_edge(iscn->scn, line->eoffs,
QR_FINDER_SUBPREC) - line->len;
line->len -= u;
u = QR_FIXED(iscn->umin, 0) + iscn->du * u;
if(iscn->du < 0) {
int tmp = line->boffs;
line->boffs = line->eoffs;
line->eoffs = tmp;
u -= line->len;
}
vert = !iscn->dx;
line->pos[vert] = u;
line->pos[!vert] = QR_FIXED(iscn->v, 1);
_zbar_qr_found_line(iscn->qr, vert, line);
}
#endif
static void symbol_handler (zbar_decoder_t *dcode)
{
zbar_image_scanner_t *iscn = zbar_decoder_get_userdata(dcode);
zbar_symbol_type_t type = zbar_decoder_get_type(dcode);
int x = 0, y = 0, dir;
const char *data;
unsigned datalen;
zbar_symbol_t *sym;
#ifdef ENABLE_QRCODE
if(type == ZBAR_QRCODE) {
qr_handler(iscn);
return;
}
#else
assert(type != ZBAR_QRCODE);
#endif
if(TEST_CFG(iscn, ZBAR_CFG_POSITION)) {
/* tmp position fixup */
int w = zbar_scanner_get_width(iscn->scn);
int u = iscn->umin + iscn->du * zbar_scanner_get_edge(iscn->scn, w, 0);
if(iscn->dx) {
x = u;
y = iscn->v;
}
else {
x = iscn->v;
y = u;
}
}
/* FIXME debug flag to save/display all PARTIALs */
if(type <= ZBAR_PARTIAL) {
zprintf(256, "partial symbol @(%d,%d)\n", x, y);
return;
}
data = zbar_decoder_get_data(dcode);
datalen = zbar_decoder_get_data_length(dcode);
/* FIXME need better symbol matching */
for(sym = iscn->syms->head; sym; sym = sym->next)
if(sym->type == type &&
sym->datalen == datalen &&
!memcmp(sym->data, data, datalen)) {
sym->quality++;
zprintf(224, "dup symbol @(%d,%d): dup %s: %.20s\n",
x, y, zbar_get_symbol_name(type), data);
if(TEST_CFG(iscn, ZBAR_CFG_POSITION))
/* add new point to existing set */
/* FIXME should be polygon */
sym_add_point(sym, x, y);
return;
}
sym = _zbar_image_scanner_alloc_sym(iscn, type, datalen + 1);
sym->configs = zbar_decoder_get_configs(dcode, type);
sym->modifiers = zbar_decoder_get_modifiers(dcode);
/* FIXME grab decoder buffer */
memcpy(sym->data, data, datalen + 1);
/* initialize first point */
if(TEST_CFG(iscn, ZBAR_CFG_POSITION)) {
zprintf(192, "new symbol @(%d,%d): %s: %.20s\n",
x, y, zbar_get_symbol_name(type), data);
sym_add_point(sym, x, y);
}
dir = zbar_decoder_get_direction(dcode);
if(dir)
sym->orient = (iscn->dy != 0) + ((iscn->du ^ dir) & 2);
_zbar_image_scanner_add_sym(iscn, sym);
}
zbar_image_scanner_t *zbar_image_scanner_create ()
{
zbar_image_scanner_t *iscn = calloc(1, sizeof(zbar_image_scanner_t));
if(!iscn)
return(NULL);
iscn->dcode = zbar_decoder_create();
iscn->scn = zbar_scanner_create(iscn->dcode);
if(!iscn->dcode || !iscn->scn) {
zbar_image_scanner_destroy(iscn);
return(NULL);
}
zbar_decoder_set_userdata(iscn->dcode, iscn);
zbar_decoder_set_handler(iscn->dcode, symbol_handler);
#ifdef ENABLE_QRCODE
iscn->qr = _zbar_qr_create();
#endif
/* apply default configuration */
CFG(iscn, ZBAR_CFG_X_DENSITY) = 1;
CFG(iscn, ZBAR_CFG_Y_DENSITY) = 1;
zbar_image_scanner_set_config(iscn, 0, ZBAR_CFG_POSITION, 1);
zbar_image_scanner_set_config(iscn, 0, ZBAR_CFG_UNCERTAINTY, 2);
zbar_image_scanner_set_config(iscn, ZBAR_QRCODE, ZBAR_CFG_UNCERTAINTY, 0);
zbar_image_scanner_set_config(iscn, ZBAR_CODE128, ZBAR_CFG_UNCERTAINTY, 0);
zbar_image_scanner_set_config(iscn, ZBAR_CODE93, ZBAR_CFG_UNCERTAINTY, 0);
zbar_image_scanner_set_config(iscn, ZBAR_CODE39, ZBAR_CFG_UNCERTAINTY, 0);
zbar_image_scanner_set_config(iscn, ZBAR_CODABAR, ZBAR_CFG_UNCERTAINTY, 1);
zbar_image_scanner_set_config(iscn, ZBAR_COMPOSITE, ZBAR_CFG_UNCERTAINTY, 0);
return(iscn);
}
#ifndef NO_STATS
static inline void dump_stats (const zbar_image_scanner_t *iscn)
{
int i;
zprintf(1, "symbol sets allocated = %-4d\n", iscn->stat_syms_new);
zprintf(1, " scanner syms in use = %-4d\trecycled = %-4d\n",
iscn->stat_iscn_syms_inuse, iscn->stat_iscn_syms_recycle);
zprintf(1, " image syms in use = %-4d\trecycled = %-4d\n",
iscn->stat_img_syms_inuse, iscn->stat_img_syms_recycle);
zprintf(1, "symbols allocated = %-4d\n", iscn->stat_sym_new);
for(i = 0; i < RECYCLE_BUCKETS; i++)
zprintf(1, " recycled[%d] = %-4d\n",
i, iscn->stat_sym_recycle[i]);
}
#endif
void zbar_image_scanner_destroy (zbar_image_scanner_t *iscn)
{
int i;
dump_stats(iscn);
if(iscn->syms) {
if(iscn->syms->refcnt)
zbar_symbol_set_ref(iscn->syms, -1);
else
_zbar_symbol_set_free(iscn->syms);
iscn->syms = NULL;
}
if(iscn->scn)
zbar_scanner_destroy(iscn->scn);
iscn->scn = NULL;
if(iscn->dcode)
zbar_decoder_destroy(iscn->dcode);
iscn->dcode = NULL;
for(i = 0; i < RECYCLE_BUCKETS; i++) {
zbar_symbol_t *sym, *next;
for(sym = iscn->recycle[i].head; sym; sym = next) {
next = sym->next;
_zbar_symbol_free(sym);
}
}
#ifdef ENABLE_QRCODE
if(iscn->qr) {
_zbar_qr_destroy(iscn->qr);
iscn->qr = NULL;
}
#endif
free(iscn);
}
zbar_image_data_handler_t*
zbar_image_scanner_set_data_handler (zbar_image_scanner_t *iscn,
zbar_image_data_handler_t *handler,
const void *userdata)
{
zbar_image_data_handler_t *result = iscn->handler;
iscn->handler = handler;
iscn->userdata = userdata;
return(result);
}
int zbar_image_scanner_set_config (zbar_image_scanner_t *iscn,
zbar_symbol_type_t sym,
zbar_config_t cfg,
int val)
{
if((sym == 0 || sym == ZBAR_COMPOSITE) && cfg == ZBAR_CFG_ENABLE) {
iscn->ean_config = !!val;
if(sym)
return(0);
}
if(cfg < ZBAR_CFG_UNCERTAINTY)
return(zbar_decoder_set_config(iscn->dcode, sym, cfg, val));
if(cfg < ZBAR_CFG_POSITION) {
int c, i;
if(cfg > ZBAR_CFG_UNCERTAINTY)
return(1);
c = cfg - ZBAR_CFG_UNCERTAINTY;
if(sym > ZBAR_PARTIAL) {
i = _zbar_get_symbol_hash(sym);
iscn->sym_configs[c][i] = val;
}
else
for(i = 0; i < NUM_SYMS; i++)
iscn->sym_configs[c][i] = val;
return(0);
}
if(sym > ZBAR_PARTIAL)
return(1);
if(cfg >= ZBAR_CFG_X_DENSITY && cfg <= ZBAR_CFG_Y_DENSITY) {
CFG(iscn, cfg) = val;
return(0);
}
if(cfg > ZBAR_CFG_POSITION)
return(1);
cfg -= ZBAR_CFG_POSITION;
if(!val)
iscn->config &= ~(1 << cfg);
else if(val == 1)
iscn->config |= (1 << cfg);
else
return(1);
return(0);
}
void zbar_image_scanner_enable_cache (zbar_image_scanner_t *iscn,
int enable)
{
if(iscn->cache) {
/* recycle all cached syms */
_zbar_image_scanner_recycle_syms(iscn, iscn->cache);
iscn->cache = NULL;
}
iscn->enable_cache = (enable) ? 1 : 0;
}
const zbar_symbol_set_t *
zbar_image_scanner_get_results (const zbar_image_scanner_t *iscn)
{
return(iscn->syms);
}
static inline void quiet_border (zbar_image_scanner_t *iscn)
{
/* flush scanner pipeline */
zbar_scanner_t *scn = iscn->scn;
zbar_scanner_flush(scn);
zbar_scanner_flush(scn);
zbar_scanner_new_scan(scn);
}
#define movedelta(dx, dy) do { \
x += (dx); \
y += (dy); \
p += (dx) + ((uintptr_t)(dy) * w); \
} while(0);
int zbar_scan_image (zbar_image_scanner_t *iscn,
zbar_image_t *img)
{
zbar_symbol_set_t *syms;
const uint8_t *data;
zbar_scanner_t *scn = iscn->scn;
unsigned w, h, cx1, cy1;
int density;
/* timestamp image
* FIXME prefer video timestamp
*/
iscn->time = _zbar_timer_now();
#ifdef ENABLE_QRCODE
_zbar_qr_reset(iscn->qr);
#endif
/* image must be in grayscale format */
if(img->format != fourcc('Y','8','0','0') &&
img->format != fourcc('G','R','E','Y'))
return(-1);
iscn->img = img;
/* recycle previous scanner and image results */
zbar_image_scanner_recycle_image(iscn, img);
syms = iscn->syms;
if(!syms) {
syms = iscn->syms = _zbar_symbol_set_create();
STAT(syms_new);
zbar_symbol_set_ref(syms, 1);
}
else
zbar_symbol_set_ref(syms, 2);
img->syms = syms;
w = img->width;
h = img->height;
cx1 = img->crop_x + img->crop_w;
assert(cx1 <= w);
cy1 = img->crop_y + img->crop_h;
assert(cy1 <= h);
data = img->data;
zbar_image_write_png(img, "debug.png");
svg_open("debug.svg", 0, 0, w, h);
svg_image("debug.png", w, h);
zbar_scanner_new_scan(scn);
density = CFG(iscn, ZBAR_CFG_Y_DENSITY);
if(density > 0) {
const uint8_t *p = data;
int x = 0, y = 0;
int border = (((img->crop_h - 1) % density) + 1) / 2;
if(border > img->crop_h / 2)
border = img->crop_h / 2;
border += img->crop_y;
assert(border <= h);
svg_group_start("scanner", 0, 1, 1, 0, 0);
iscn->dy = 0;
movedelta(img->crop_x, border);
iscn->v = y;
while(y < cy1) {
int cx0 = img->crop_x;;
zprintf(128, "img_x+: %04d,%04d @%p\n", x, y, p);
svg_path_start("vedge", 1. / 32, 0, y + 0.5);
iscn->dx = iscn->du = 1;
iscn->umin = cx0;
while(x < cx1) {
uint8_t d = *p;
movedelta(1, 0);
zbar_scan_y(scn, d);
}
ASSERT_POS;
quiet_border(iscn);
svg_path_end();
movedelta(-1, density);
iscn->v = y;
if(y >= cy1)
break;
zprintf(128, "img_x-: %04d,%04d @%p\n", x, y, p);
svg_path_start("vedge", -1. / 32, w, y + 0.5);
iscn->dx = iscn->du = -1;
iscn->umin = cx1;
while(x >= cx0) {
uint8_t d = *p;
movedelta(-1, 0);
zbar_scan_y(scn, d);
}
ASSERT_POS;
quiet_border(iscn);
svg_path_end();
movedelta(1, density);
iscn->v = y;
}
svg_group_end();
}
iscn->dx = 0;
density = CFG(iscn, ZBAR_CFG_X_DENSITY);
if(density > 0) {
const uint8_t *p = data;
int x = 0, y = 0;
int border = (((img->crop_w - 1) % density) + 1) / 2;
if(border > img->crop_w / 2)
border = img->crop_w / 2;
border += img->crop_x;
assert(border <= w);
svg_group_start("scanner", 90, 1, -1, 0, 0);
movedelta(border, img->crop_y);
iscn->v = x;
while(x < cx1) {
int cy0 = img->crop_y;
zprintf(128, "img_y+: %04d,%04d @%p\n", x, y, p);
svg_path_start("vedge", 1. / 32, 0, x + 0.5);
iscn->dy = iscn->du = 1;
iscn->umin = cy0;
while(y < cy1) {
uint8_t d = *p;
movedelta(0, 1);
zbar_scan_y(scn, d);
}
ASSERT_POS;
quiet_border(iscn);
svg_path_end();
movedelta(density, -1);
iscn->v = x;
if(x >= cx1)
break;
zprintf(128, "img_y-: %04d,%04d @%p\n", x, y, p);
svg_path_start("vedge", -1. / 32, h, x + 0.5);
iscn->dy = iscn->du = -1;
iscn->umin = cy1;
while(y >= cy0) {
uint8_t d = *p;
movedelta(0, -1);
zbar_scan_y(scn, d);
}
ASSERT_POS;
quiet_border(iscn);
svg_path_end();
movedelta(density, 1);
iscn->v = x;
}
svg_group_end();
}
iscn->dy = 0;
iscn->img = NULL;
#ifdef ENABLE_QRCODE
_zbar_qr_decode(iscn->qr, iscn, img);
#endif
/* FIXME tmp hack to filter bad EAN results */
/* FIXME tmp hack to merge simple case EAN add-ons */
char filter = (!iscn->enable_cache &&
(density == 1 || CFG(iscn, ZBAR_CFG_Y_DENSITY) == 1));
int nean = 0, naddon = 0;
if(syms->nsyms) {
zbar_symbol_t **symp;
for(symp = &syms->head; *symp; ) {
zbar_symbol_t *sym = *symp;
if(sym->cache_count <= 0 &&
((sym->type < ZBAR_COMPOSITE && sym->type > ZBAR_PARTIAL) ||
sym->type == ZBAR_DATABAR ||
sym->type == ZBAR_DATABAR_EXP ||
sym->type == ZBAR_CODABAR))
{
if((sym->type == ZBAR_CODABAR || filter) && sym->quality < 4) {
if(iscn->enable_cache) {
/* revert cache update */
zbar_symbol_t *entry = cache_lookup(iscn, sym);
if(entry)
entry->cache_count--;
else
assert(0);
}
/* recycle */
*symp = sym->next;
syms->nsyms--;
sym->next = NULL;
_zbar_image_scanner_recycle_syms(iscn, sym);
continue;
}
else if(sym->type < ZBAR_COMPOSITE &&
sym->type != ZBAR_ISBN10)
{
if(sym->type > ZBAR_EAN5)
nean++;
else
naddon++;
}
}
symp = &sym->next;
}
if(nean == 1 && naddon == 1 && iscn->ean_config) {
/* create container symbol for composite result */
zbar_symbol_t *ean = NULL, *addon = NULL;
for(symp = &syms->head; *symp; ) {
zbar_symbol_t *sym = *symp;
if(sym->type < ZBAR_COMPOSITE && sym->type > ZBAR_PARTIAL) {
/* move to composite */
*symp = sym->next;
syms->nsyms--;
sym->next = NULL;
if(sym->type <= ZBAR_EAN5)
addon = sym;
else
ean = sym;
}
else
symp = &sym->next;
}
assert(ean);
assert(addon);
int datalen = ean->datalen + addon->datalen + 1;
zbar_symbol_t *ean_sym =
_zbar_image_scanner_alloc_sym(iscn, ZBAR_COMPOSITE, datalen);
ean_sym->orient = ean->orient;
ean_sym->syms = _zbar_symbol_set_create();
memcpy(ean_sym->data, ean->data, ean->datalen);
memcpy(ean_sym->data + ean->datalen,
addon->data, addon->datalen + 1);
ean_sym->syms->head = ean;
ean->next = addon;
ean_sym->syms->nsyms = 2;
_zbar_image_scanner_add_sym(iscn, ean_sym);
}
}
if(syms->nsyms && iscn->handler)
iscn->handler(img, iscn->userdata);
svg_close();
return(syms->nsyms);
}
#ifdef DEBUG_SVG
/* FIXME lame...*/
# include "svg.c"
#endif
| lgpl-2.1 |
vikramvgarg/libmesh | contrib/eigen/3.2.9/bench/btl/libs/eigen3/btl_tiny_eigen3.cpp | 617 | 1664 | //=====================================================
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
#include "utilities.h"
#include "eigen3_interface.hh"
#include "static/bench_static.hh"
#include "action_matrix_vector_product.hh"
#include "action_matrix_matrix_product.hh"
#include "action_axpy.hh"
#include "action_lu_solve.hh"
#include "action_ata_product.hh"
#include "action_aat_product.hh"
#include "action_atv_product.hh"
#include "action_cholesky.hh"
#include "action_trisolve.hh"
BTL_MAIN;
int main()
{
bench_static<Action_axpy,eigen2_interface>();
bench_static<Action_matrix_matrix_product,eigen2_interface>();
bench_static<Action_matrix_vector_product,eigen2_interface>();
bench_static<Action_atv_product,eigen2_interface>();
bench_static<Action_cholesky,eigen2_interface>();
bench_static<Action_trisolve,eigen2_interface>();
return 0;
}
| lgpl-2.1 |
hakehuang/rtthread_fsl | components/net/uip/apps/dhcpc/dhcpc.c | 107 | 9960 | /*
* Copyright (c) 2005, Swedish Institute of Computer Science
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute 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 INSTITUTE 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 INSTITUTE 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.
*
* This file is part of the uIP TCP/IP stack
*
* @(#)$Id: dhcpc.c,v 1.2 2006/06/11 21:46:37 adam Exp $
*/
#include <stdio.h>
#include <string.h>
#include "uip.h"
#include "dhcpc.h"
#include "timer.h"
#include "pt.h"
#define STATE_INITIAL 0
#define STATE_SENDING 1
#define STATE_OFFER_RECEIVED 2
#define STATE_CONFIG_RECEIVED 3
static struct dhcpc_state s;
struct dhcp_msg {
u8_t op, htype, hlen, hops;
u8_t xid[4];
u16_t secs, flags;
u8_t ciaddr[4];
u8_t yiaddr[4];
u8_t siaddr[4];
u8_t giaddr[4];
u8_t chaddr[16];
#ifndef UIP_CONF_DHCP_LIGHT
u8_t sname[64];
u8_t file[128];
#endif
u8_t options[312];
};
#define BOOTP_BROADCAST 0x8000
#define DHCP_REQUEST 1
#define DHCP_REPLY 2
#define DHCP_HTYPE_ETHERNET 1
#define DHCP_HLEN_ETHERNET 6
#define DHCP_MSG_LEN 236
#define DHCPC_SERVER_PORT 67
#define DHCPC_CLIENT_PORT 68
#define DHCPDISCOVER 1
#define DHCPOFFER 2
#define DHCPREQUEST 3
#define DHCPDECLINE 4
#define DHCPACK 5
#define DHCPNAK 6
#define DHCPRELEASE 7
#define DHCP_OPTION_SUBNET_MASK 1
#define DHCP_OPTION_ROUTER 3
#define DHCP_OPTION_DNS_SERVER 6
#define DHCP_OPTION_REQ_IPADDR 50
#define DHCP_OPTION_LEASE_TIME 51
#define DHCP_OPTION_MSG_TYPE 53
#define DHCP_OPTION_SERVER_ID 54
#define DHCP_OPTION_REQ_LIST 55
#define DHCP_OPTION_END 255
static const u8_t xid[4] = {0xad, 0xde, 0x12, 0x23};
static const u8_t magic_cookie[4] = {99, 130, 83, 99};
/*---------------------------------------------------------------------------*/
static u8_t *
add_msg_type(u8_t *optptr, u8_t type)
{
*optptr++ = DHCP_OPTION_MSG_TYPE;
*optptr++ = 1;
*optptr++ = type;
return optptr;
}
/*---------------------------------------------------------------------------*/
static u8_t *
add_server_id(u8_t *optptr)
{
*optptr++ = DHCP_OPTION_SERVER_ID;
*optptr++ = 4;
memcpy(optptr, s.serverid, 4);
return optptr + 4;
}
/*---------------------------------------------------------------------------*/
static u8_t *
add_req_ipaddr(u8_t *optptr)
{
*optptr++ = DHCP_OPTION_REQ_IPADDR;
*optptr++ = 4;
memcpy(optptr, s.ipaddr, 4);
return optptr + 4;
}
/*---------------------------------------------------------------------------*/
static u8_t *
add_req_options(u8_t *optptr)
{
*optptr++ = DHCP_OPTION_REQ_LIST;
*optptr++ = 3;
*optptr++ = DHCP_OPTION_SUBNET_MASK;
*optptr++ = DHCP_OPTION_ROUTER;
*optptr++ = DHCP_OPTION_DNS_SERVER;
return optptr;
}
/*---------------------------------------------------------------------------*/
static u8_t *
add_end(u8_t *optptr)
{
*optptr++ = DHCP_OPTION_END;
return optptr;
}
/*---------------------------------------------------------------------------*/
static void
create_msg(register struct dhcp_msg *m)
{
m->op = DHCP_REQUEST;
m->htype = DHCP_HTYPE_ETHERNET;
m->hlen = s.mac_len;
m->hops = 0;
memcpy(m->xid, xid, sizeof(m->xid));
m->secs = 0;
m->flags = HTONS(BOOTP_BROADCAST); /* Broadcast bit. */
/* uip_ipaddr_copy(m->ciaddr, uip_hostaddr);*/
memcpy(m->ciaddr, uip_hostaddr, sizeof(m->ciaddr));
memset(m->yiaddr, 0, sizeof(m->yiaddr));
memset(m->siaddr, 0, sizeof(m->siaddr));
memset(m->giaddr, 0, sizeof(m->giaddr));
memcpy(m->chaddr, s.mac_addr, s.mac_len);
memset(&m->chaddr[s.mac_len], 0, sizeof(m->chaddr) - s.mac_len);
#ifndef UIP_CONF_DHCP_LIGHT
memset(m->sname, 0, sizeof(m->sname));
memset(m->file, 0, sizeof(m->file));
#endif
memcpy(m->options, magic_cookie, sizeof(magic_cookie));
}
/*---------------------------------------------------------------------------*/
static void
send_discover(void)
{
u8_t *end;
struct dhcp_msg *m = (struct dhcp_msg *)uip_appdata;
create_msg(m);
end = add_msg_type(&m->options[4], DHCPDISCOVER);
end = add_req_options(end);
end = add_end(end);
uip_send(uip_appdata, end - (u8_t *)uip_appdata);
}
/*---------------------------------------------------------------------------*/
static void
send_request(void)
{
u8_t *end;
struct dhcp_msg *m = (struct dhcp_msg *)uip_appdata;
create_msg(m);
end = add_msg_type(&m->options[4], DHCPREQUEST);
end = add_server_id(end);
end = add_req_ipaddr(end);
end = add_end(end);
uip_send(uip_appdata, end - (u8_t *)uip_appdata);
}
/*---------------------------------------------------------------------------*/
static u8_t
parse_options(u8_t *optptr, int len)
{
u8_t *end = optptr + len;
u8_t type = 0;
while(optptr < end) {
switch(*optptr) {
case DHCP_OPTION_SUBNET_MASK:
memcpy(s.netmask, optptr + 2, 4);
break;
case DHCP_OPTION_ROUTER:
memcpy(s.default_router, optptr + 2, 4);
break;
case DHCP_OPTION_DNS_SERVER:
memcpy(s.dnsaddr, optptr + 2, 4);
break;
case DHCP_OPTION_MSG_TYPE:
type = *(optptr + 2);
break;
case DHCP_OPTION_SERVER_ID:
memcpy(s.serverid, optptr + 2, 4);
break;
case DHCP_OPTION_LEASE_TIME:
memcpy(s.lease_time, optptr + 2, 4);
break;
case DHCP_OPTION_END:
return type;
}
optptr += optptr[1] + 2;
}
return type;
}
/*---------------------------------------------------------------------------*/
static u8_t
parse_msg(void)
{
struct dhcp_msg *m = (struct dhcp_msg *)uip_appdata;
if(m->op == DHCP_REPLY &&
memcmp(m->xid, xid, sizeof(xid)) == 0 &&
memcmp(m->chaddr, s.mac_addr, s.mac_len) == 0) {
memcpy(s.ipaddr, m->yiaddr, 4);
return parse_options(&m->options[4], uip_datalen());
}
return 0;
}
/*---------------------------------------------------------------------------*/
static
PT_THREAD(handle_dhcp(void))
{
PT_BEGIN(&s.pt);
/* try_again:*/
s.state = STATE_SENDING;
s.ticks = CLOCK_SECOND;
do {
send_discover();
timer_set(&s.timer, s.ticks);
PT_WAIT_UNTIL(&s.pt, uip_newdata() || timer_expired(&s.timer));
if(uip_newdata() && parse_msg() == DHCPOFFER) {
s.state = STATE_OFFER_RECEIVED;
break;
}
if(s.ticks < CLOCK_SECOND * 60) {
s.ticks *= 2;
}
} while(s.state != STATE_OFFER_RECEIVED);
s.ticks = CLOCK_SECOND;
do {
send_request();
timer_set(&s.timer, s.ticks);
PT_WAIT_UNTIL(&s.pt, uip_newdata() || timer_expired(&s.timer));
if(uip_newdata() && parse_msg() == DHCPACK) {
s.state = STATE_CONFIG_RECEIVED;
break;
}
if(s.ticks <= CLOCK_SECOND * 10) {
s.ticks += CLOCK_SECOND;
} else {
PT_RESTART(&s.pt);
}
} while(s.state != STATE_CONFIG_RECEIVED);
#if 0
printf("Got IP address %d.%d.%d.%d\n",
uip_ipaddr1(s.ipaddr), uip_ipaddr2(s.ipaddr),
uip_ipaddr3(s.ipaddr), uip_ipaddr4(s.ipaddr));
printf("Got netmask %d.%d.%d.%d\n",
uip_ipaddr1(s.netmask), uip_ipaddr2(s.netmask),
uip_ipaddr3(s.netmask), uip_ipaddr4(s.netmask));
printf("Got DNS server %d.%d.%d.%d\n",
uip_ipaddr1(s.dnsaddr), uip_ipaddr2(s.dnsaddr),
uip_ipaddr3(s.dnsaddr), uip_ipaddr4(s.dnsaddr));
printf("Got default router %d.%d.%d.%d\n",
uip_ipaddr1(s.default_router), uip_ipaddr2(s.default_router),
uip_ipaddr3(s.default_router), uip_ipaddr4(s.default_router));
printf("Lease expires in %ld seconds\n",
ntohs(s.lease_time[0])*65536ul + ntohs(s.lease_time[1]));
#endif
dhcpc_configured(&s);
/* timer_stop(&s.timer);*/
/*
* PT_END restarts the thread so we do this instead. Eventually we
* should reacquire expired leases here.
*/
while(1) {
PT_YIELD(&s.pt);
}
PT_END(&s.pt);
}
/*---------------------------------------------------------------------------*/
void
dhcpc_init(const void *mac_addr, int mac_len)
{
uip_ipaddr_t addr;
s.mac_addr = mac_addr;
s.mac_len = mac_len;
s.state = STATE_INITIAL;
uip_ipaddr(addr, 255,255,255,255);
s.conn = uip_udp_new(&addr, HTONS(DHCPC_SERVER_PORT));
if(s.conn != NULL) {
uip_udp_bind(s.conn, HTONS(DHCPC_CLIENT_PORT));
}
PT_INIT(&s.pt);
}
/*---------------------------------------------------------------------------*/
void
dhcpc_appcall(void)
{
handle_dhcp();
}
/*---------------------------------------------------------------------------*/
void
dhcpc_request(void)
{
u16_t ipaddr[2];
if(s.state == STATE_INITIAL) {
uip_ipaddr(ipaddr, 0,0,0,0);
uip_sethostaddr(ipaddr);
/* handle_dhcp(PROCESS_EVENT_NONE, NULL);*/
}
}
/*---------------------------------------------------------------------------*/
| lgpl-2.1 |
bitsauce/SuperSauce-Engine | 3rdparty/SDL_mixer/external/libmodplug-0.8.8.4/src/load_pat.cpp | 120 | 41736 | /*
MikMod Sound System
By Jake Stine of Divine Entertainment (1996-2000)
Support:
If you find problems with this code, send mail to:
air@divent.org
Distribution / Code rights:
Use this source code in any fashion you see fit. Giving me credit where
credit is due is optional, depending on your own levels of integrity and
honesty.
-----------------------------------------
Module: LOAD_PAT
PAT sample loader.
by Peter Grootswagers (2006)
<email:pgrootswagers@planet.nl>
It's primary purpose is loading samples for the .abc and .mid modules
Can also be used stand alone, in that case a tune (frere Jacques)
is generated using al samples available in the .pat file
Portability:
All systems - all compilers (hopefully)
*/
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#ifndef _WIN32
#include <limits.h> // for PATH_MAX
#include <unistd.h> // for sleep
#endif
#ifndef PATH_MAX
#define PATH_MAX 256
#endif
#ifdef NEWMIKMOD
#include "mikmod.h"
#include "uniform.h"
typedef UBYTE BYTE;
typedef UWORD WORD;
#else
#include "stdafx.h"
#include "sndfile.h"
#endif
#include "load_pat.h"
#ifdef MSC_VER
#define DIRDELIM '\\'
#define TIMIDITYCFG "C:\\TIMIDITY\\TIMIDITY.CFG"
#define PATHFORPAT "C:\\TIMIDITY\\INSTRUMENTS"
#else
#define DIRDELIM '/'
#define TIMIDITYCFG "/usr/local/share/timidity/timidity.cfg"
#define PATHFORPAT "/usr/local/share/timidity/instruments"
#endif
#define PAT_ENV_PATH2CFG "MMPAT_PATH_TO_CFG"
// 128 gm and 63 drum
#define MAXSMP 191
static char midipat[MAXSMP][128];
static char pathforpat[128];
static char timiditycfg[128];
#pragma pack(1)
typedef struct {
char header[12]; // ascizz GF1PATCH110
char gravis_id[10]; // allways ID#000002
char description[60];
BYTE instruments;
BYTE voices;
BYTE channels;
WORD waveforms;
WORD master_volume;
DWORD data_size;
char reserved[36];
} PatchHeader;
typedef struct {
WORD instrument_id;
char instrument_name[16];
DWORD instrument_size;
BYTE layers;
char reserved[40];
} InstrumentHeader;
typedef struct {
BYTE layer_dup;
BYTE layer_id;
DWORD layer_size;
BYTE samples;
char reserved[40];
} LayerHeader;
typedef struct {
char wave_name[7];
BYTE fractions;
DWORD wave_size;
DWORD start_loop;
DWORD end_loop;
WORD sample_rate;
DWORD low_frequency ;
DWORD high_frequency;
DWORD root_frequency;
short int tune;
BYTE balance;
BYTE envelope_rate[6];
BYTE envelope_offset[6];
BYTE tremolo_sweep;
BYTE tremolo_rate;
BYTE tremolo_depth;
BYTE vibrato_sweep;
BYTE vibrato_rate;
BYTE vibrato_depth;
BYTE modes;
DWORD scale_frequency;
DWORD scale_factor;
char reserved[32];
} WaveHeader;
// WaveHeader.modes bits
#define PAT_16BIT 1
#define PAT_UNSIGNED 2
#define PAT_LOOP 4
#define PAT_PINGPONG 8
#define PAT_BACKWARD 16
#define PAT_SUSTAIN 32
#define PAT_ENVELOPE 64
#define PAT_CLAMPED 128
#define C4SPD 8363
#define C4mHz 523251
#define C4 523.251f
#define PI 3.141592653589793f
#define OMEGA ((2.0f * PI * C4)/(float)C4SPD)
/**************************************************************************
**************************************************************************/
#ifdef NEWMIKMOD
static char PAT_Version[] = "Timidity GUS Patch v1.0";
#endif
static BYTE pat_gm_used[MAXSMP];
static BYTE pat_loops[MAXSMP];
/**************************************************************************
**************************************************************************/
typedef struct _PATHANDLE
{
#ifdef NEWMIKMOD
MM_ALLOC *allochandle;
#endif
char patname[16];
int samples;
} PATHANDLE;
#ifndef HAVE_SINF
static inline float sinf(float x) {
/* default to double version */
return((float)sin((double)x));
}
#endif
// local prototypes
static int pat_getopt(const char *s, const char *o, int dflt);
static void pat_message(const char *s1, const char *s2)
{
char txt[256];
if( strlen(s1) + strlen(s2) > 255 ) return;
sprintf(txt, s1, s2);
#ifdef NEWMIKMOD
_mmlog(txt);
#else
fprintf(stderr, "load_pat > %s\n", txt);
#endif
}
void pat_resetsmp(void)
{
int i;
for( i=0; i<MAXSMP; i++ ) {
pat_loops[i] = 0;
pat_gm_used[i] = 0;
}
}
int pat_numsmp()
{
return strlen((const char *)pat_gm_used);
}
int pat_numinstr(void)
{
return strlen((const char *)pat_gm_used);
}
int pat_smptogm(int smp)
{
if( smp < MAXSMP )
return pat_gm_used[smp - 1];
return 1;
}
int pat_gmtosmp(int gm)
{
int smp;
for( smp=0; pat_gm_used[smp]; smp++ )
if( pat_gm_used[smp] == gm )
return smp+1;
if( smp < MAXSMP ) {
pat_gm_used[smp] = gm;
return smp+1;
}
return 1;
}
int pat_smplooped(int smp)
{
if( smp < MAXSMP ) return pat_loops[smp - 1];
return 1;
}
const char *pat_gm_name(int gm)
{
static char buf[40];
if( gm < 1 || gm > MAXSMP ) {
sprintf(buf, "invalid gm %d", gm);
return buf;
}
return midipat[gm - 1];
}
int pat_gm_drumnr(int n)
{
if( n < 25 ) return 129;
if( n+129-25 < MAXSMP )
return 129+n-25; // timidity.cfg drum patches start at 25
return MAXSMP;
}
int pat_gm_drumnote(int n)
{
char *p;
p = strchr(midipat[pat_gm_drumnr(n)-1], ':');
if( p ) return pat_getopt(p+1, "note", n);
return n;
}
static float pat_sinus(int i)
{
float res = sinf(OMEGA * (float)i);
return res;
}
static float pat_square(int i)
{
float res = 30.0f * sinf(OMEGA * (float)i);
if( res > 0.99f ) return 0.99f;
if( res < -0.99f ) return -0.99f;
return res;
}
static float pat_sawtooth(int i)
{
float res = OMEGA * (float)i;
while( res > 2 * PI )
res -= 2 * PI;
i = 2;
if( res > PI ) {
res = PI - res;
i = -2;
}
res = (float)i * res / PI;
if( res > 0.9f ) return 1.0f - res;
if( res < -0.9f ) return 1.0f + res;
return res;
}
typedef float (*PAT_SAMPLE_FUN)(int);
static PAT_SAMPLE_FUN pat_fun[] = { pat_sinus, pat_square, pat_sawtooth };
#ifdef NEWMIKMOD
#define MMFILE MMSTREAM
#define mmftell(x) _mm_ftell(x)
#define mmfseek(f,p,w) _mm_fseek(f,p,w)
#define mmreadUBYTES(buf,sz,f) _mm_read_UBYTES(buf,sz,f)
#else
#if defined(WIN32) && defined(_mm_free)
#undef _mm_free
#endif
#define MMSTREAM FILE
#define _mm_fopen(name,mode) fopen(name,mode)
#define _mm_fgets(f,buf,sz) fgets(buf,sz,f)
#define _mm_fseek(f,pos,whence) fseek(f,pos,whence)
#define _mm_ftell(f) ftell(f)
#define _mm_read_UBYTES(buf,sz,f) fread(buf,sz,1,f)
#define _mm_read_SBYTES(buf,sz,f) fread(buf,sz,1,f)
#define _mm_feof(f) feof(f)
#define _mm_fclose(f) fclose(f)
#define DupStr(h,buf,sz) strdup(buf)
#define _mm_calloc(h,n,sz) calloc(n,sz)
#define _mm_recalloc(h,buf,sz,elsz) realloc(buf,sz)
#define _mm_free(h,p) free(p)
typedef struct {
char *mm;
int sz;
int pos;
int error;
} MMFILE;
static long mmftell(MMFILE *mmfile)
{
return mmfile->pos;
}
static void mmfseek(MMFILE *mmfile, long p, int whence)
{
int newpos = mmfile->pos;
switch(whence) {
case SEEK_SET:
newpos = p;
break;
case SEEK_CUR:
newpos += p;
break;
case SEEK_END:
newpos = mmfile->sz + p;
break;
}
if (newpos < mmfile->sz)
mmfile->pos = newpos;
else {
mmfile->error = 1;
// printf("WARNING: seeking too far\n");
}
}
static void mmreadUBYTES(BYTE *buf, long sz, MMFILE *mmfile)
{
// do not overread.
if (sz > mmfile->sz - mmfile->pos)
sz = mmfile->sz - mmfile->pos;
memcpy(buf, &mmfile->mm[mmfile->pos], sz);
mmfile->pos += sz;
}
static void mmreadSBYTES(char *buf, long sz, MMFILE *mmfile)
{
// do not overread.
if (sz > mmfile->sz - mmfile->pos)
sz = mmfile->sz - mmfile->pos;
memcpy(buf, &mmfile->mm[mmfile->pos], sz);
mmfile->pos += sz;
}
#endif
long _mm_getfsize(MMSTREAM *mmpat) {
long fsize;
_mm_fseek(mmpat, 0L, SEEK_END);
fsize = _mm_ftell(mmpat);
_mm_fseek(mmpat, 0L, SEEK_SET);
return(fsize);
}
void pat_init_patnames(void)
{
int z, i, nsources, isdrumset, nskip, pfnlen;
char *p, *q;
char line[PATH_MAX];
char cfgsources[5][PATH_MAX] = {{0}, {0}, {0}, {0}, {0}};
MMSTREAM *mmcfg;
strcpy(pathforpat, PATHFORPAT);
strcpy(timiditycfg, TIMIDITYCFG);
p = getenv(PAT_ENV_PATH2CFG);
if( p ) {
strcpy(timiditycfg,p);
strcpy(pathforpat,p);
strcat(timiditycfg,"/timidity.cfg");
strcat(pathforpat,"/instruments");
}
strncpy(cfgsources[0], timiditycfg, PATH_MAX);
nsources = 1;
for( i=0; i<MAXSMP; i++ ) midipat[i][0] = '\0';
for ( z=0; z<5; z++ ) {
if (cfgsources[z][0] == 0) continue;
mmcfg = _mm_fopen(cfgsources[z],"r");
if( !mmcfg ) {
pat_message("can not open %s, use environment variable " PAT_ENV_PATH2CFG " for the directory", cfgsources[z]);
}
else {
// read in bank 0 and drum patches
isdrumset = 0;
_mm_fgets(mmcfg, line, PATH_MAX);
while( !_mm_feof(mmcfg) ) {
if( isdigit(line[0]) || (isblank(line[0]) && isdigit(line[1])) ) {
p = line;
// get pat number
while ( isspace(*p) ) p ++;
i = atoi(p);
while ( isdigit(*p) ) p ++;
while ( isspace(*p) ) p ++;
// get pat file name
if( *p && i < MAXSMP && i >= 0 && *p != '#' ) {
q = isdrumset ? midipat[pat_gm_drumnr(i)-1] : midipat[i];
pfnlen = 0;
while( *p && !isspace(*p) && *p != '#' && pfnlen < 128 ) {
pfnlen ++;
*q++ = *p++;
}
if( isblank(*p) && *(p+1) != '#' && pfnlen < 128 ) {
*q++ = ':'; pfnlen ++;
while( isspace(*p) ) {
while( isspace(*p) ) p++;
if ( *p == '#' ) { // comment
} else while( *p && !isspace(*p) && pfnlen < 128 ) {
pfnlen ++;
*q++ = *p++;
}
if( isspace(*p) ) { *q++ = ' '; pfnlen++; }
}
}
*q++ = '\0';
}
}
if( !strncmp(line,"drumset",7) ) isdrumset = 1;
if( !strncmp(line,"source",6) && nsources < 5 ) {
q = cfgsources[nsources];
p = &line[7];
while ( isspace(*p) ) p ++;
pfnlen = 0;
while ( *p && *p != '#' && !isspace(*p) && pfnlen < 128 ) {
pfnlen ++;
*q++ = *p++;
}
*q = 0; // null termination
nsources++;
}
_mm_fgets(mmcfg, line, PATH_MAX);
} /* end file parsing */
_mm_fclose(mmcfg);
}
}
q = midipat[0];
nskip = 0;
// make all empty patches duplicates the previous valid one.
for( i=0; i<MAXSMP; i++ ) {
if( midipat[i][0] ) q = midipat[i];
else {
if( midipat[i] != q)
strcpy(midipat[i], q);
if( midipat[i][0] == '\0' ) nskip++;
}
}
if( nskip ) {
for( i=MAXSMP; i-- > 0; ) {
if( midipat[i][0] ) q = midipat[i];
else if( midipat[i] != q )
strcpy(midipat[i], q);
}
}
}
static char *pat_build_path(char *fname, int pat)
{
char *ps;
char *patfile = midipat[pat];
int isabspath = (patfile[0] == '/');
if ( isabspath ) patfile ++;
ps = strrchr(patfile, ':');
if( ps ) {
sprintf(fname, "%s%c%s", isabspath ? "" : pathforpat, DIRDELIM, patfile);
strcpy(strrchr(fname, ':'), ".pat");
return ps;
}
sprintf(fname, "%s%c%s.pat", isabspath ? "" : pathforpat, DIRDELIM, patfile);
return 0;
}
static void pat_read_patname(PATHANDLE *h, MMFILE *mmpat) {
InstrumentHeader ih;
mmfseek(mmpat,sizeof(PatchHeader), SEEK_SET);
mmreadUBYTES((BYTE *)&ih, sizeof(InstrumentHeader), mmpat);
strncpy(h->patname, ih.instrument_name, 16);
h->patname[15] = '\0';
}
static void pat_read_layerheader(MMSTREAM *mmpat, LayerHeader *hl)
{
_mm_fseek(mmpat,sizeof(PatchHeader)+sizeof(InstrumentHeader), SEEK_SET);
_mm_read_UBYTES((BYTE *)hl, sizeof(LayerHeader), mmpat);
}
static void pat_get_layerheader(MMFILE *mmpat, LayerHeader *hl)
{
InstrumentHeader ih;
mmfseek(mmpat,sizeof(PatchHeader), SEEK_SET);
mmreadUBYTES((BYTE *)&ih, sizeof(InstrumentHeader), mmpat);
mmreadUBYTES((BYTE *)hl, sizeof(LayerHeader), mmpat);
strncpy(hl->reserved, ih.instrument_name, 40);
}
static int pat_read_numsmp(MMFILE *mmpat) {
LayerHeader hl;
pat_get_layerheader(mmpat, &hl);
return hl.samples;
}
static void pat_read_waveheader(MMSTREAM *mmpat, WaveHeader *hw, int layer)
{
long int pos, bestpos=0;
LayerHeader hl;
ULONG bestfreq, freqdist;
int i;
// read the very first and maybe only sample
pat_read_layerheader(mmpat, &hl);
if( hl.samples > 1 ) {
if( layer ) {
if( layer > hl.samples ) layer = hl.samples; // you don't fool me....
for( i=1; i<layer; i++ ) {
_mm_read_UBYTES((BYTE *)hw, sizeof(WaveHeader), mmpat);
_mm_fseek(mmpat, hw->wave_size, SEEK_CUR);
}
}
else {
bestfreq = C4mHz * 1000; // big enough
for( i=0; i<hl.samples; i++ ) {
pos = _mm_ftell(mmpat);
_mm_read_UBYTES((BYTE *)hw, sizeof(WaveHeader), mmpat);
if( hw->root_frequency > C4mHz )
freqdist = hw->root_frequency - C4mHz;
else
freqdist = 2 * (C4mHz - hw->root_frequency);
if( freqdist < bestfreq ) {
bestfreq = freqdist;
bestpos = pos;
}
_mm_fseek(mmpat, hw->wave_size, SEEK_CUR);
}
_mm_fseek(mmpat, bestpos, SEEK_SET);
}
}
_mm_read_UBYTES((BYTE *)hw, sizeof(WaveHeader), mmpat);
strncpy(hw->reserved, hl.reserved, 36);
if( hw->start_loop >= hw->wave_size ) {
hw->start_loop = 0;
hw->end_loop = 0;
hw->modes &= ~PAT_LOOP; // mask off loop indicator
}
if( hw->end_loop > hw->wave_size )
hw->end_loop = hw->wave_size;
}
#ifndef NEWMIKMOD
static void pat_get_waveheader(MMFILE *mmpat, WaveHeader *hw, int layer)
{
long int pos, bestpos=0;
LayerHeader hl;
ULONG bestfreq, freqdist;
int i;
// read the very first and maybe only sample
pat_get_layerheader(mmpat, &hl);
if( hl.samples > 1 ) {
if( layer ) {
if( layer > hl.samples ) layer = hl.samples; // you don't fool me....
for( i=1; i<layer; i++ ) {
mmreadUBYTES((BYTE *)hw, sizeof(WaveHeader), mmpat);
mmfseek(mmpat, hw->wave_size, SEEK_CUR);
if ( mmpat->error ) {
hw->wave_size = 0;
return;
}
}
}
else {
bestfreq = C4mHz * 1000; // big enough
for( i=0; i<hl.samples; i++ ) {
pos = mmftell(mmpat);
mmreadUBYTES((BYTE *)hw, sizeof(WaveHeader), mmpat);
if( hw->root_frequency > C4mHz )
freqdist = hw->root_frequency - C4mHz;
else
freqdist = 2 * (C4mHz - hw->root_frequency);
if( freqdist < bestfreq ) {
bestfreq = freqdist;
bestpos = pos;
}
mmfseek(mmpat, hw->wave_size, SEEK_CUR);
}
mmfseek(mmpat, bestpos, SEEK_SET);
}
}
mmreadUBYTES((BYTE *)hw, sizeof(WaveHeader), mmpat);
if( hw->start_loop >= hw->wave_size ) {
hw->start_loop = 0;
hw->end_loop = 0;
hw->modes &= ~PAT_LOOP; // mask off loop indicator
}
if( hw->end_loop > hw->wave_size )
hw->end_loop = hw->wave_size;
}
#endif
static int pat_readpat_attr(int pat, WaveHeader *hw, int layer)
{
char fname[128];
int fsize;
MMSTREAM *mmpat;
pat_build_path(fname, pat);
mmpat = _mm_fopen(fname, "r");
if( !mmpat )
return 0;
fsize = _mm_getfsize(mmpat);
pat_read_waveheader(mmpat, hw, layer);
_mm_fclose(mmpat);
if (hw->wave_size > fsize)
return 0;
return 1;
}
static void pat_amplify(char *b, int num, int amp, int m)
{
char *pb;
BYTE *pu;
short int *pi;
WORD *pw;
int i,n,v;
n = num;
if( m & PAT_16BIT ) { // 16 bit
n >>= 1;
if( m & 2 ) { // unsigned
pw = (WORD *)b;
for( i=0; i<n; i++ ) {
v = (((int)(*pw) - 0x8000) * amp) / 100;
if( v < -0x8000 ) v = -0x8000;
if( v > 0x7fff ) v = 0x7fff;
*pw++ = v + 0x8000;
}
}
else {
pi = (short int *)b;
for( i=0; i<n; i++ ) {
v = ((*pi) * amp) / 100;
if( v < -0x8000 ) v = -0x8000;
if( v > 0x7fff ) v = 0x7fff;
*pi++ = v;
}
}
}
else {
if( m & 2 ) { // unsigned
pu = (BYTE *)b;
for( i=0; i<n; i++ ) {
v = (((int)(*pu) - 0x80) * amp) / 100;
if( v < -0x80 ) v = -0x80;
if( v > 0x7f ) v = 0x7f;
*pu++ = v + 0x80;
}
}
else {
pb = (char *)b;
for( i=0; i<n; i++ ) {
v = ((*pb) * amp) / 100;
if( v < -0x80 ) v = -0x80;
if( v > 0x7f ) v = 0x7f;
*pb++ = v;
}
}
}
}
static int pat_getopt(const char *s, const char *o, int dflt)
{
const char *p;
if( !s ) return dflt;
p = strstr(s,o);
if( !p ) return dflt;
return atoi(strchr(p,'=')+1);
}
static void pat_readpat(int pat, char *dest, int num)
{
static int readlasttime = 0, wavesize = 0;
static MMSTREAM *mmpat = 0;
static char *opt = 0;
int amp;
char fname[128];
WaveHeader hw;
#ifdef NEWMIKMOD
static int patlast = MAXSMP;
if( !dest ) { // reset
if( mmpat ) _mm_fclose(mmpat);
readlasttime = 0;
wavesize = 0;
mmpat = 0;
patlast = MAXSMP;
return;
}
if( pat != patlast ) { // reset for other instrument
if( mmpat ) _mm_fclose(mmpat);
readlasttime = 0;
patlast = pat;
}
#endif
if( !readlasttime ) {
opt=pat_build_path(fname, pat);
mmpat = _mm_fopen(fname, "r");
if( !mmpat )
return;
pat_read_waveheader(mmpat, &hw, 0);
wavesize = hw.wave_size;
}
_mm_read_SBYTES(dest, num, mmpat);
amp = pat_getopt(opt,"amp",100);
if( amp != 100 ) pat_amplify(dest, num, amp, hw.modes);
readlasttime += num;
if( readlasttime < wavesize ) return;
readlasttime = 0;
_mm_fclose(mmpat);
mmpat = 0;
}
#ifdef NEWMIKMOD
// next code pinched from dec_raw.c and rebuild to load bytes from different places
// =====================================================================================
static void *dec_pat_Init(MMSTREAM *mmfp)
{
pat_readpat(0,0,0); // initialize pat loader
return (void *)mmfp;
}
static void dec_pat_Cleanup(void *raw)
{
}
static BOOL dec_pat_Decompress16Bit(void *raw, short int *dest, int cbcount, MMSTREAM *mmfp)
{
long samplenum = _mm_ftell(mmfp) - 1;
#else
static BOOL dec_pat_Decompress16Bit(short int *dest, int cbcount, int samplenum)
{
#endif
int i;
PAT_SAMPLE_FUN f;
if( samplenum < MAXSMP ) pat_readpat(samplenum, (char *)dest, cbcount*2);
else {
f = pat_fun[(samplenum - MAXSMP) % 3];
for( i=0; i<cbcount; i++ )
dest[i] = (short int)(32000.0*f(i));
}
return cbcount;
}
// convert 8 bit data to 16 bit!
// We do the conversion in reverse so that the data we're converting isn't overwritten
// by the result.
static void pat_blowup_to16bit(short int *dest, int cbcount) {
char *s;
short int *d;
int t;
s = (char *)dest;
d = dest;
s += cbcount;
d += cbcount;
for(t=0; t<cbcount; t++)
{ s--;
d--;
*d = (*s) << 8;
}
}
#ifdef NEWMIKMOD
static BOOL dec_pat_Decompress8Bit(void *raw, short int *dest, int cbcount, MMSTREAM *mmfp)
{
long samplenum = _mm_ftell(mmfp) - 1;
#else
static BOOL dec_pat_Decompress8Bit(short int *dest, int cbcount, int samplenum)
{
#endif
int i;
PAT_SAMPLE_FUN f;
if( samplenum < MAXSMP ) pat_readpat(samplenum, (char *)dest, cbcount);
else {
f = pat_fun[(samplenum - MAXSMP) % 3];
for( i=0; i<cbcount; i++ )
dest[i] = (char)(120.0*f(i));
}
pat_blowup_to16bit(dest, cbcount);
return cbcount;
}
#ifdef NEWMIKMOD
SL_DECOMPRESS_API dec_pat =
{
NULL,
SL_COMPRESS_RAW,
dec_pat_Init,
dec_pat_Cleanup,
dec_pat_Decompress16Bit,
dec_pat_Decompress8Bit,
};
#endif
// =====================================================================================
#ifdef NEWMIKMOD
BOOL PAT_Test(MMSTREAM *mmfile)
#else
BOOL CSoundFile::TestPAT(const BYTE *lpStream, DWORD dwMemLength)
#endif
// =====================================================================================
{
PatchHeader ph;
#ifdef NEWMIKMOD
_mm_fseek(mmfile,0,SEEK_SET);
_mm_read_UBYTES((BYTE *)&ph, sizeof(PatchHeader), mmfile);
#else
if( dwMemLength < sizeof(PatchHeader) ) return 0;
memcpy((BYTE *)&ph, lpStream, sizeof(PatchHeader));
#endif
if( !strcmp(ph.header,"GF1PATCH110") && !strcmp(ph.gravis_id,"ID#000002") ) return 1;
return 0;
}
// =====================================================================================
static PATHANDLE *PAT_Init(void)
{
PATHANDLE *retval;
#ifdef NEWMIKMOD
MM_ALLOC *allochandle;
allochandle = _mmalloc_create("Load_PAT", NULL);
retval = (PATHANDLE *)_mm_calloc(allochandle, 1,sizeof(PATHANDLE));
if( !retval ) return NULL;
SL_RegisterDecompressor(&dec_raw); // we can not get the samples out of our own routines...!
#else
retval = (PATHANDLE *)calloc(1,sizeof(PATHANDLE));
if( !retval ) return NULL;
#endif
return retval;
}
// =====================================================================================
static void PAT_Cleanup(PATHANDLE *handle)
// =====================================================================================
{
#ifdef NEWMIKMOD
if(handle && handle->allochandle) {
_mmalloc_close(handle->allochandle);
handle->allochandle = 0;
}
#else
if(handle) {
free(handle);
}
#endif
}
static char tune[] = "c d e c|c d e c|e f g..|e f g..|gagfe c|gagfe c|c G c..|c G c..|";
static int pat_note(int abc)
{
switch( abc ) {
case 'C': return 48;
case 'D': return 50;
case 'E': return 52;
case 'F': return 53;
case 'G': return 55;
case 'A': return 57;
case 'B': return 59;
case 'c': return 60;
case 'd': return 62;
case 'e': return 64;
case 'f': return 65;
case 'g': return 67;
case 'a': return 69;
case 'b': return 71;
default:
break;
}
return 0;
}
int pat_modnote(int midinote)
{
int n;
n = midinote;
#ifdef NEWMIKMOD
if( n < 12 ) n++;
else n-=11;
#else
n += 13;
#endif
return n;
}
// =====================================================================================
#ifdef NEWMIKMOD
static void PAT_ReadPatterns(UNIMOD *of, PATHANDLE *h, int numpat)
// =====================================================================================
{
int pat,row,i,ch;
BYTE n,ins,vol;
int t;
int tt1, tt2;
UNITRK_EFFECT eff;
tt2 = (h->samples - 1) * 16 + 128;
for( pat = 0; pat < numpat; pat++ ) {
utrk_reset(of->ut);
for( row = 0; row < 64; row++ ) {
tt1 = (pat * 64 + row);
for( ch = 0; ch < h->samples; ch++ ) {
t = tt1 - ch * 16;
if( t >= 0 ) {
i = tt2 - 16 * ((h->samples - 1 - ch) & 3);
if( tt1 < i ) {
t = t % 64;
if( isalpha(tune[t]) ) {
utrk_settrack(of->ut, ch);
n = pat_modnote(pat_note(tune[t]));
ins = ch;
vol = 100;
if( (t % 16) == 0 ) {
vol += vol / 10;
if( vol > 127 ) vol = 127;
}
utrk_write_inst(of->ut, ins);
utrk_write_note(of->ut, n); // <- normal note
pt_write_effect(of->ut, 0xc, vol);
}
if( tt1 == i - 1 && ch == 0 && row < 63 ) {
eff.effect = UNI_GLOB_PATBREAK;
eff.param.u = 0;
eff.framedly = UFD_RUNONCE;
utrk_write_global(of->ut, &eff, UNIMEM_NONE);
}
}
else {
if( tt1 == i ) {
eff.param.u = 0;
eff.effect = UNI_NOTEKILL;
utrk_write_local(of->ut, &eff, UNIMEM_NONE);
}
}
}
}
utrk_newline(of->ut);
}
if(!utrk_dup_pattern(of->ut,of)) return;
}
}
#else
static void PAT_ReadPatterns(MODCOMMAND *pattern[], WORD psize[], PATHANDLE *h, int numpat)
// =====================================================================================
{
int pat,row,i,ch;
BYTE n,ins,vol;
int t;
int tt1, tt2;
MODCOMMAND *m;
if( numpat > MAX_PATTERNS ) numpat = MAX_PATTERNS;
tt2 = (h->samples - 1) * 16 + 128;
for( pat = 0; pat < numpat; pat++ ) {
pattern[pat] = CSoundFile::AllocatePattern(64, h->samples);
if( !pattern[pat] ) return;
psize[pat] = 64;
for( row = 0; row < 64; row++ ) {
tt1 = (pat * 64 + row);
for( ch = 0; ch < h->samples; ch++ ) {
t = tt1 - ch * 16;
m = &pattern[pat][row * h->samples + ch];
m->param = 0;
m->command = CMD_NONE;
if( t >= 0 ) {
i = tt2 - 16 * ((h->samples - 1 - ch) & 3);
if( tt1 < i ) {
t = t % 64;
if( isalpha(tune[t]) ) {
n = pat_modnote(pat_note(tune[t]));
ins = ch + 1;
vol = 40;
if( (t % 16) == 0 ) {
vol += vol / 10;
if( vol > 64 ) vol = 64;
}
m->instr = ins;
m->note = n; // <- normal note
m->volcmd = VOLCMD_VOLUME;
m->vol = vol;
}
if( tt1 == i - 1 && ch == 0 && row < 63 ) {
m->command = CMD_PATTERNBREAK;
}
}
else {
if( tt1 == i ) {
m->param = 0;
m->command = CMD_KEYOFF;
m->volcmd = VOLCMD_VOLUME;
m->vol = 0;
}
}
}
}
}
}
}
#endif
// calculate the best speed that approximates the pat root frequency as a C note
static ULONG pat_patrate_to_C4SPD(ULONG patRate , ULONG patMilliHz)
{
ULONG u;
double x, y;
u = patMilliHz;
x = 0.1 * patRate;
x = x * C4mHz;
y = u * 0.4;
x = x / y;
u = (ULONG)(x+0.5);
return u;
}
// return relative position in samples for the rate starting with offset start ending with offset end
static int pat_envelope_rpos(int rate, int start, int end)
{
int r, p, t, s;
// rate byte is 3 bits exponent and 6 bits increment size
// eeiiiiii
// every 8 to the power ee the volume is incremented/decremented by iiiiii
// Thank you Gravis for this weirdness...
r = 3 - ((rate >> 6) & 3) * 3;
p = rate & 0x3f;
if( !p ) return 0;
t = end - start;
if( !t ) return 0;
if (t < 0) t = -t;
s = (t << r)/ p;
return s;
}
static void pat_modenv(WaveHeader *hw, int mpos[6], int mvol[6])
{
int i, sum, s;
BYTE *prate = hw->envelope_rate, *poffset = hw->envelope_offset;
for( i=0; i<6; i++ ) {
mpos[i] = 0;
mvol[i] = 64;
}
if( !memcmp(prate, "??????", 6) || poffset[5] >= 100 ) return; // weird rates or high env end volume
if( !(hw->modes & PAT_SUSTAIN) ) return; // no sustain thus no need for envelope
s = hw->wave_size;
if (s == 0) return;
if( hw->modes & PAT_16BIT )
s >>= 1;
// offsets 0 1 2 3 4 5 are distributed over 0 2 4 6 8 10, the odd numbers are set in between
sum = 0;
for( i=0; i<6; i++ ) {
mvol[i] = poffset[i];
mpos[i] = pat_envelope_rpos(prate[i], i? poffset[i-1]: 0, poffset[i]);
sum += mpos[i];
}
if( sum == 0 ) return;
if( sum > s ) {
for( i=0; i<6; i++ )
mpos[i] = (s * mpos[i]) / sum;
}
for( i=1; i<6; i++ )
mpos[i] += mpos[i-1];
for( i=0; i<6 ; i++ ) {
mpos[i] = (256 * mpos[i]) / s;
mpos[i]++;
if( i > 0 && mpos[i] <= mpos[i-1] ) {
if( mvol[i] == mvol[i-1] ) mpos[i] = mpos[i-1];
else mpos[i] = mpos[i-1] + 1;
}
if( mpos[i] > 256 ) mpos[i] = 256;
}
mvol[5] = 0; // kill Bill....
}
#ifdef NEWMIKMOD
static void pat_setpat_inst(WaveHeader *hw, INSTRUMENT *d, int smp)
{
int u, inuse;
int envpoint[6], envvolume[6];
for(u=0; u<120; u++) {
d->samplenumber[u] = smp;
d->samplenote[u] = smp;
}
d->globvol = 64;
d->volfade = 0;
d->volflg = EF_CARRY;
d->panflg = EF_CARRY;
if( hw->modes & PAT_ENVELOPE ) d->volflg |= EF_ON;
if( hw->modes & PAT_SUSTAIN ) d->volflg |= EF_SUSTAIN;
if( (hw->modes & PAT_LOOP) && (hw->start_loop != hw->end_loop) ) d->volflg |= EF_LOOP;
d->volsusbeg = 1;
d->volsusend = 1;
d->volbeg = 1;
d->volend = 2;
d->volpts = 6;
// scale volume envelope:
inuse = 0;
pat_modenv(hw, envpoint, envvolume);
for(u=0; u<6; u++)
{
if( envvolume[u] != 64 ) inuse = 1;
d->volenv[u].val = envvolume[u]<<2;
d->volenv[u].pos = envpoint[u];
}
if(!inuse) d->volpts = 0;
d->pansusbeg = 0;
d->pansusend = 0;
d->panbeg = 0;
d->panend = 0;
d->panpts = 0;
// scale panning envelope:
for(u=0; u<12; u++)
{
d->panenv[u].val = 0;
d->panenv[u].pos = 0;
}
d->panpts = 0;
}
#else
static void pat_setpat_inst(WaveHeader *hw, INSTRUMENTHEADER *d, int smp)
{
int u, inuse;
int envpoint[6], envvolume[6];
d->nMidiProgram = 0;
d->nFadeOut = 0;
d->nPan = 128;
d->nPPC = 5*12;
d->dwFlags = 0;
if( hw->modes & PAT_ENVELOPE ) d->dwFlags |= ENV_VOLUME;
if( hw->modes & PAT_SUSTAIN ) d->dwFlags |= ENV_VOLSUSTAIN;
if( (hw->modes & PAT_LOOP) && (hw->start_loop != hw->end_loop) ) d->dwFlags |= ENV_VOLLOOP;
d->nVolEnv = 6;
//if (!d->nVolEnv) d->dwFlags &= ~ENV_VOLUME;
d->nPanEnv = 0;
d->nVolSustainBegin = 1;
d->nVolSustainEnd = 1;
d->nVolLoopStart = 1;
d->nVolLoopEnd = 2;
d->nPanSustainBegin = 0;
d->nPanSustainEnd = 0;
d->nPanLoopStart = 0;
d->nPanLoopEnd = 0;
d->nGlobalVol = 64;
pat_modenv(hw, envpoint, envvolume);
inuse = 0;
for( u=0; u<6; u++)
{
if( envvolume[u] != 64 ) inuse = 1;
d->VolPoints[u] = envpoint[u];
d->VolEnv[u] = envvolume[u];
d->PanPoints[u] = 0;
d->PanEnv[u] = 0;
if (u)
{
if (d->VolPoints[u] < d->VolPoints[u-1])
{
d->VolPoints[u] &= 0xFF;
d->VolPoints[u] += d->VolPoints[u-1] & 0xFF00;
if (d->VolPoints[u] < d->VolPoints[u-1]) d->VolPoints[u] += 0x100;
}
}
}
if( !inuse ) d->nVolEnv = 0;
for( u=0; u<128; u++)
{
d->NoteMap[u] = u+1;
d->Keyboard[u] = smp;
}
}
#endif
#ifdef NEWMIKMOD
static void PATinst(UNIMOD *of, INSTRUMENT *d, int smp, int gm)
#else
static void PATinst(INSTRUMENTHEADER *d, int smp, int gm)
#endif
{
WaveHeader hw;
char s[32];
memset(s,0,32);
if( pat_readpat_attr(gm-1, &hw, 0) ) {
pat_setpat_inst(&hw, d, smp);
}
else {
hw.modes = PAT_16BIT|PAT_ENVELOPE|PAT_SUSTAIN|PAT_LOOP;
hw.start_loop = 0;
hw.end_loop = 30000;
hw.wave_size = 30000;
// envelope rates and offsets pinched from timidity's acpiano.pat sample no 1
hw.envelope_rate[0] = 0x3f;
hw.envelope_rate[1] = 0x3f;
hw.envelope_rate[2] = 0x3f;
hw.envelope_rate[3] = 0x08|(3<<6);
hw.envelope_rate[4] = 0x3f;
hw.envelope_rate[5] = 0x3f;
hw.envelope_offset[0] = 246;
hw.envelope_offset[1] = 246;
hw.envelope_offset[2] = 246;
hw.envelope_offset[3] = 0;
hw.envelope_offset[4] = 0;
hw.envelope_offset[5] = 0;
strncpy(hw.reserved, midipat[gm-1], sizeof(hw.reserved));
pat_setpat_inst(&hw, d, smp);
}
if( hw.reserved[0] )
strncpy(s, hw.reserved, 32);
else
strncpy(s, midipat[gm-1], 32);
#ifdef NEWMIKMOD
d->insname = DupStr(of->allochandle, s,28);
#else
s[31] = '\0';
memset(d->name, 0, 32);
strcpy((char *)d->name, s);
strncpy(s, midipat[gm-1], 12);
s[11] = '\0';
memset(d->filename, 0, 12);
strcpy((char *)d->filename, s);
#endif
}
#ifdef NEWMIKMOD
static void pat_setpat_attr(WaveHeader *hw, UNISAMPLE *q, int gm)
{
q->seekpos = gm; // dec_pat expects the midi samplenumber in this
q->speed = pat_patrate_to_C4SPD(hw->sample_rate , hw->root_frequency);
q->length = hw->wave_size;
q->loopstart = hw->start_loop;
q->loopend = hw->end_loop;
q->volume = 0x40;
if( hw->modes & PAT_16BIT ) {
q->format |= SF_16BITS;
q->length >>= 1;
q->loopstart >>= 1;
q->loopend >>= 1;
q->speed <<= 1;
}
if( (hw->modes & PAT_UNSIGNED)==0 ) q->format |= SF_SIGNED;
if( hw->modes & PAT_LOOP ) {
q->flags |= SL_LOOP;
if( hw->modes & PAT_PINGPONG ) q->flags |= SL_SUSTAIN_BIDI;
if( hw->modes & PAT_SUSTAIN ) q->flags |= SL_SUSTAIN_LOOP;
}
}
#else
static void pat_setpat_attr(WaveHeader *hw, MODINSTRUMENT *q)
{
q->nC4Speed = pat_patrate_to_C4SPD(hw->sample_rate , hw->root_frequency);
q->nLength = hw->wave_size;
q->nLoopStart = hw->start_loop;
q->nLoopEnd = hw->end_loop;
q->nVolume = 256;
if( hw->modes & PAT_16BIT ) {
q->nLength >>= 1;
q->nLoopStart >>= 1;
q->nLoopEnd >>= 1;
}
if( hw->modes & PAT_LOOP ) {
q->uFlags |= CHN_LOOP;
if( hw->modes & PAT_PINGPONG ) q->uFlags |= CHN_PINGPONGSUSTAIN;
if( hw->modes & PAT_SUSTAIN ) q->uFlags |= CHN_SUSTAINLOOP;
}
}
#endif
// ==========================
// Load those darned Samples!
#ifdef NEWMIKMOD
static void PATsample(UNIMOD *of, UNISAMPLE *q, int smp, int gm)
#else
static void PATsample(CSoundFile *cs, MODINSTRUMENT *q, int smp, int gm)
#endif
{
WaveHeader hw;
char s[256];
sprintf(s, "%d:%s", smp-1, midipat[gm-1]);
#ifdef NEWMIKMOD
q->samplename = DupStr(of->allochandle, s,28);
if( pat_readpat_attr(gm-1, &hw, 0) ) {
pat_setpat_attr(&hw, q, gm);
pat_loops[smp-1] = (q->flags & (SL_LOOP | SL_SUSTAIN_LOOP))? 1: 0;
}
else {
q->seekpos = smp + MAXSMP + 1; // dec_pat expects the samplenumber in this
q->speed = C4SPD;
q->length = 30000;
q->loopstart = 0;
q->loopend = 30000;
q->volume = 0x40;
// Enable aggressive declicking for songs that do not loop and that
// are long enough that they won't be adversely affected.
q->flags |= SL_LOOP;
q->format |= SF_16BITS;
q->format |= SF_SIGNED;
}
if(!(q->flags & (SL_LOOP | SL_SUSTAIN_LOOP)) && (q->length > 5000))
q->flags |= SL_DECLICK;
#else
s[31] = '\0';
memset(cs->m_szNames[smp], 0, 32);
strcpy(cs->m_szNames[smp], s);
q->nGlobalVol = 64;
q->nPan = 128;
q->uFlags = CHN_16BIT;
if( pat_readpat_attr(gm-1, &hw, 0) ) {
char *p;
pat_setpat_attr(&hw, q);
pat_loops[smp-1] = (q->uFlags & CHN_LOOP)? 1: 0;
if( hw.modes & PAT_16BIT ) p = (char *)malloc(hw.wave_size);
else p = (char *)malloc(hw.wave_size * sizeof(short int));
if( p ) {
if( hw.modes & PAT_16BIT ) {
dec_pat_Decompress16Bit((short int *)p, hw.wave_size>>1, gm - 1);
cs->ReadSample(q, (hw.modes&PAT_UNSIGNED)?RS_PCM16U:RS_PCM16S, (LPSTR)p, hw.wave_size);
}
else {
dec_pat_Decompress8Bit((short int *)p, hw.wave_size, gm - 1);
cs->ReadSample(q, (hw.modes&PAT_UNSIGNED)?RS_PCM16U:RS_PCM16S, (LPSTR)p, hw.wave_size * sizeof(short int));
}
free(p);
}
}
else {
char *p;
q->nC4Speed = C4SPD;
q->nLength = 30000;
q->nLoopStart = 0;
q->nLoopEnd = 30000;
q->nVolume = 256;
q->uFlags |= CHN_LOOP;
q->uFlags |= CHN_16BIT;
p = (char *)malloc(q->nLength*sizeof(short int));
if( p ) {
dec_pat_Decompress8Bit((short int *)p, q->nLength, smp + MAXSMP - 1);
cs->ReadSample(q, RS_PCM16S, (LPSTR)p, q->nLength*2);
free(p);
}
}
#endif
}
// =====================================================================================
BOOL PAT_Load_Instruments(void *c)
{
uint32_t t;
#ifdef NEWMIKMOD
UNIMOD *of = (UNIMOD *)c;
INSTRUMENT *d;
UNISAMPLE *q;
if( !pat_numsmp() ) pat_gmtosmp(1); // make sure there is a sample
of->numsmp = pat_numsmp();
of->numins = pat_numinstr();
if(!AllocInstruments(of)) return FALSE;
if(!AllocSamples(of, 0)) return FALSE;
d = of->instruments;
for(t=1; t<=of->numins; t++) {
PATinst(of, d, t, pat_smptogm(t));
d++;
}
q = of->samples;
for(t=1; t<=of->numsmp; t++) {
PATsample(of, q, t, pat_smptogm(t));
q++;
}
SL_RegisterDecompressor(&dec_pat); // fool him to generate samples
#else
CSoundFile *of=(CSoundFile *)c;
if( !pat_numsmp() ) pat_gmtosmp(1); // make sure there is a sample
of->m_nSamples = pat_numsmp() + 1; // xmms modplug does not use slot zero
of->m_nInstruments = pat_numinstr() + 1;
for(t=1; t<of->m_nInstruments; t++) { // xmms modplug doesn't use slot zero
if( (of->Headers[t] = new INSTRUMENTHEADER) == NULL ) return FALSE;
memset(of->Headers[t], 0, sizeof(INSTRUMENTHEADER));
PATinst(of->Headers[t], t, pat_smptogm(t));
}
for(t=1; t<of->m_nSamples; t++) { // xmms modplug doesn't use slot zero
PATsample(of, &of->Ins[t], t, pat_smptogm(t));
}
// copy last of the mohicans to entry 0 for XMMS modinfo to work....
t = of->m_nInstruments - 1;
if( (of->Headers[0] = new INSTRUMENTHEADER) == NULL ) return FALSE;
memcpy(of->Headers[0], of->Headers[t], sizeof(INSTRUMENTHEADER));
memset(of->Headers[0]->name, 0, 32);
strncpy((char *)of->Headers[0]->name, "Timidity GM patches", 32);
t = of->m_nSamples - 1;
memcpy(&of->Ins[0], &of->Ins[t], sizeof(MODINSTRUMENT));
#endif
return TRUE;
}
// =====================================================================================
#ifdef NEWMIKMOD
BOOL PAT_Load(PATHANDLE *h, UNIMOD *of, MMSTREAM *mmfile)
#else
BOOL CSoundFile::ReadPAT(const BYTE *lpStream, DWORD dwMemLength)
#endif
{
static int avoid_reentry = 0;
char buf[60];
int t;
#ifdef NEWMIKMOD
UNISAMPLE *q;
INSTRUMENT *d;
#define m_nDefaultTempo of->inittempo
#else
PATHANDLE *h;
int numpat;
MMFILE mm, *mmfile;
MODINSTRUMENT *q;
INSTRUMENTHEADER *d;
if( !TestPAT(lpStream, dwMemLength) ) return FALSE;
h = PAT_Init();
if( !h ) return FALSE;
mmfile = &mm;
mm.mm = (char *)lpStream;
mm.sz = dwMemLength;
mm.pos = 0;
mm.error = 0;
#endif
while( avoid_reentry ) sleep(1);
avoid_reentry = 1;
pat_read_patname(h, mmfile);
h->samples = pat_read_numsmp(mmfile);
if( strlen(h->patname) )
sprintf(buf,"%s canon %d-v (Fr. Jacques)", h->patname, h->samples);
else
sprintf(buf,"%d-voice canon (Fr. Jacques)", h->samples);
#ifdef NEWMIKMOD
of->songname = DupStr(of->allochandle, buf, strlen(buf));
#else
if( strlen(buf) > 31 ) buf[31] = '\0'; // chop it of
strcpy(m_szNames[0], buf);
#endif
m_nDefaultTempo = 60; // 120 / 2
t = (h->samples - 1) * 16 + 128;
if( t % 64 ) t += 64;
t = t / 64;
#ifdef NEWMIKMOD
of->memsize = PTMEM_LAST; // Number of memory slots to reserve!
of->modtype = _mm_strdup(of->allochandle, PAT_Version);
of->reppos = 0;
of->numins = h->samples;
of->numsmp = h->samples;
of->initspeed = 6;
of->numchn = h->samples;
of->numpat = t;
of->numpos = of->numpat; // one repeating pattern
of->numtrk = of->numpat * of->numchn;
of->initvolume = 64;
of->pansep=128;
// allocate resources
if(!AllocPositions(of, of->numpos)) {
avoid_reentry = 0;
return FALSE;
}
if(!AllocInstruments(of)) {
avoid_reentry = 0;
return FALSE;
}
if(!AllocSamples(of, 0)) {
avoid_reentry = 0;
return FALSE;
}
// orderlist
for(t=0; t<of->numpos; t++)
of->positions[t] = t;
d = of->instruments;
for(t=1; t<=of->numins; t++) {
WaveHeader hw;
char s[32];
sprintf(s, "%s", h->patname);
d->insname = DupStr(of->allochandle, s,28);
pat_read_waveheader(mmfile, &hw, t);
pat_setpat_inst(&hw, d, t);
}
q = of->samples;
for(t=1; t<=of->numsmp; t++) {
WaveHeader hw;
char s[28];
pat_read_waveheader(mmfile, &hw, t);
pat_setpat_attr(&hw, q, _mm_ftell(mmfile));
memset(s,0,28);
if( hw.wave_name[0] )
sprintf(s, "%d:%s", t, hw.wave_name);
else
sprintf(s, "%d:%s", t, h->patname);
q->samplename = DupStr(of->allochandle, s,28);
if(!(q->flags & (SL_LOOP | SL_SUSTAIN_LOOP)) && (q->length > 5000))
q->flags |= SL_DECLICK;
q++;
}
#else
m_nType = MOD_TYPE_PAT;
m_nInstruments = h->samples + 1; // we know better but use each sample in the pat...
m_nSamples = h->samples + 1; // xmms modplug does not use slot zero
m_nDefaultSpeed = 6;
m_nChannels = h->samples;
numpat = t;
m_dwSongFlags = SONG_LINEARSLIDES;
m_nMinPeriod = 28 << 2;
m_nMaxPeriod = 1712 << 3;
// orderlist
for(t=0; t < numpat; t++)
Order[t] = t;
for(t=1; t<(int)m_nInstruments; t++) { // xmms modplug doesn't use slot zero
WaveHeader hw;
char s[32];
if( (d = new INSTRUMENTHEADER) == NULL ) {
avoid_reentry = 0;
return FALSE;
}
memset(d, 0, sizeof(INSTRUMENTHEADER));
Headers[t] = d;
sprintf(s, "%s", h->patname);
s[31] = '\0';
memset(d->name, 0, 32);
strcpy((char *)d->name, s);
s[11] = '\0';
memset(d->filename, 0, 12);
strcpy((char *)d->filename, s);
pat_get_waveheader(mmfile, &hw, t);
pat_setpat_inst(&hw, d, t);
}
for(t=1; t<(int)m_nSamples; t++) { // xmms modplug doesn't use slot zero
WaveHeader hw;
char s[32];
char *p;
q = &Ins[t]; // we do not use slot zero
q->nGlobalVol = 64;
q->nPan = 128;
q->uFlags = CHN_16BIT;
pat_get_waveheader(mmfile, &hw, t);
pat_setpat_attr(&hw, q);
memset(s,0,32);
if( hw.wave_name[0] )
sprintf(s, "%d:%s", t, hw.wave_name);
else {
if( h->patname[0] )
sprintf(s, "%d:%s", t, h->patname);
else
sprintf(s, "%d:Untitled GM patch", t);
}
s[31] = '\0';
memset(m_szNames[t], 0, 32);
strcpy(m_szNames[t], s);
if( hw.modes & PAT_16BIT ) p = (char *)malloc(hw.wave_size);
else p = (char *)malloc(hw.wave_size * sizeof(short int));
if( p ) {
mmreadSBYTES(p, hw.wave_size, mmfile);
if( hw.modes & PAT_16BIT ) {
ReadSample(q, (hw.modes&PAT_UNSIGNED)?RS_PCM16U:RS_PCM16S, (LPSTR)p, hw.wave_size);
}
else {
pat_blowup_to16bit((short int *)p, hw.wave_size);
ReadSample(q, (hw.modes&PAT_UNSIGNED)?RS_PCM16U:RS_PCM16S, (LPSTR)p, hw.wave_size * sizeof(short int));
}
free(p);
}
}
// copy last of the mohicans to entry 0 for XMMS modinfo to work....
t = m_nInstruments - 1;
if( (Headers[0] = new INSTRUMENTHEADER) == NULL ) {
avoid_reentry = 0;
return FALSE;
}
memcpy(Headers[0], Headers[t], sizeof(INSTRUMENTHEADER));
memset(Headers[0]->name, 0, 32);
if( h->patname[0] )
strncpy((char *)Headers[0]->name, h->patname, 32);
else
strncpy((char *)Headers[0]->name, "Timidity GM patch", 32);
t = m_nSamples - 1;
memcpy(&Ins[0], &Ins[t], sizeof(MODINSTRUMENT));
#endif
#ifdef NEWMIKMOD
// ==============================
// Load the pattern info now!
if(!AllocTracks(of)) return 0;
if(!AllocPatterns(of)) return 0;
of->ut = utrk_init(of->numchn, h->allochandle);
utrk_memory_reset(of->ut);
utrk_local_memflag(of->ut, PTMEM_PORTAMENTO, TRUE, FALSE);
PAT_ReadPatterns(of, h, of->numpat);
// ============================================================
// set panning positions
for(t=0; t<of->numchn; t++) {
of->panning[t] = PAN_LEFT+((t+2)%5)*((PAN_RIGHT - PAN_LEFT)/5); // 0x30 = std s3m val
}
#else
// ==============================
// Load the pattern info now!
PAT_ReadPatterns(Patterns, PatternSize, h, numpat);
// ============================================================
// set panning positions
for(t=0; t<(int)m_nChannels; t++) {
ChnSettings[t].nPan = 0x30+((t+2)%5)*((0xD0 - 0x30)/5); // 0x30 = std s3m val
ChnSettings[t].nVolume = 64;
}
#endif
avoid_reentry = 0; // it is safe now, I'm finished
#ifndef NEWMIKMOD
PAT_Cleanup(h); // we dont need it anymore
#endif
return 1;
}
#ifdef NEWMIKMOD
// =====================================================================================
CHAR *PAT_LoadTitle(MMSTREAM *mmfile)
// =====================================================================================
{
PATHANDLE dummy;
pat_read_patname(&dummy, mmfile);
return(DupStr(NULL, dummy.patname,strlen(dummy.patname)));
}
MLOADER load_pat =
{
"PAT",
"PAT loader 1.0",
0x30,
NULL,
PAT_Test,
(void *(*)(void))PAT_Init,
(void (*)(ML_HANDLE *))PAT_Cleanup,
/* Every single loader seems to need one of these! */
(BOOL (*)(ML_HANDLE *, UNIMOD *, MMSTREAM *))PAT_Load,
PAT_LoadTitle
};
#endif
| lgpl-2.1 |
CodeDJ/qt5-hidpi | qt/qtwebkit/Source/WebCore/rendering/svg/SVGTextLayoutAttributes.cpp | 124 | 2484 | /*
* Copyright (C) Research In Motion Limited 2010-11. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#if ENABLE(SVG)
#include "SVGTextLayoutAttributes.h"
#include <stdio.h>
#include <wtf/text/CString.h>
namespace WebCore {
SVGTextLayoutAttributes::SVGTextLayoutAttributes(RenderSVGInlineText* context)
: m_context(context)
{
}
void SVGTextLayoutAttributes::clear()
{
m_characterDataMap.clear();
m_textMetricsValues.clear();
}
float SVGTextLayoutAttributes::emptyValue()
{
static float s_emptyValue = std::numeric_limits<float>::max() - 1;
return s_emptyValue;
}
static inline void dumpSVGCharacterDataMapValue(const char* identifier, float value, bool appendSpace = true)
{
if (value == SVGTextLayoutAttributes::emptyValue()) {
fprintf(stderr, "%s=x", identifier);
if (appendSpace)
fprintf(stderr, " ");
return;
}
fprintf(stderr, "%s=%lf", identifier, value);
if (appendSpace)
fprintf(stderr, " ");
}
void SVGTextLayoutAttributes::dump() const
{
fprintf(stderr, "context: %p\n", m_context);
const SVGCharacterDataMap::const_iterator end = m_characterDataMap.end();
for (SVGCharacterDataMap::const_iterator it = m_characterDataMap.begin(); it != end; ++it) {
const SVGCharacterData& data = it->value;
fprintf(stderr, " ---> pos=%i, data={", it->key);
dumpSVGCharacterDataMapValue("x", data.x);
dumpSVGCharacterDataMapValue("y", data.y);
dumpSVGCharacterDataMapValue("dx", data.dx);
dumpSVGCharacterDataMapValue("dy", data.dy);
dumpSVGCharacterDataMapValue("rotate", data.rotate, false);
fprintf(stderr, "}\n");
}
}
}
#endif // ENABLE(SVG)
| lgpl-2.1 |
brammittendorff/PF_RING | linux-3.16.7-ckt9/arch/m32r/kernel/process.c | 3967 | 4030 | /*
* linux/arch/m32r/kernel/process.c
*
* Copyright (c) 2001, 2002 Hiroyuki Kondo, Hirokazu Takata,
* Hitoshi Yamamoto
* Taken from sh version.
* Copyright (C) 1995 Linus Torvalds
* SuperH version: Copyright (C) 1999, 2000 Niibe Yutaka & Kaz Kojima
*/
#undef DEBUG_PROCESS
#ifdef DEBUG_PROCESS
#define DPRINTK(fmt, args...) printk("%s:%d:%s: " fmt, __FILE__, __LINE__, \
__func__, ##args)
#else
#define DPRINTK(fmt, args...)
#endif
/*
* This file handles the architecture-dependent parts of process handling..
*/
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/ptrace.h>
#include <linux/unistd.h>
#include <linux/hardirq.h>
#include <linux/rcupdate.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <asm/mmu_context.h>
#include <asm/elf.h>
#include <asm/m32r.h>
#include <linux/err.h>
/*
* Return saved PC of a blocked thread.
*/
unsigned long thread_saved_pc(struct task_struct *tsk)
{
return tsk->thread.lr;
}
void (*pm_power_off)(void) = NULL;
EXPORT_SYMBOL(pm_power_off);
void machine_restart(char *__unused)
{
#if defined(CONFIG_PLAT_MAPPI3)
outw(1, (unsigned long)PLD_REBOOT);
#endif
printk("Please push reset button!\n");
while (1)
cpu_relax();
}
void machine_halt(void)
{
printk("Please push reset button!\n");
while (1)
cpu_relax();
}
void machine_power_off(void)
{
/* M32R_FIXME */
}
void show_regs(struct pt_regs * regs)
{
printk("\n");
show_regs_print_info(KERN_DEFAULT);
printk("BPC[%08lx]:PSW[%08lx]:LR [%08lx]:FP [%08lx]\n", \
regs->bpc, regs->psw, regs->lr, regs->fp);
printk("BBPC[%08lx]:BBPSW[%08lx]:SPU[%08lx]:SPI[%08lx]\n", \
regs->bbpc, regs->bbpsw, regs->spu, regs->spi);
printk("R0 [%08lx]:R1 [%08lx]:R2 [%08lx]:R3 [%08lx]\n", \
regs->r0, regs->r1, regs->r2, regs->r3);
printk("R4 [%08lx]:R5 [%08lx]:R6 [%08lx]:R7 [%08lx]\n", \
regs->r4, regs->r5, regs->r6, regs->r7);
printk("R8 [%08lx]:R9 [%08lx]:R10[%08lx]:R11[%08lx]\n", \
regs->r8, regs->r9, regs->r10, regs->r11);
printk("R12[%08lx]\n", \
regs->r12);
#if defined(CONFIG_ISA_M32R2) && defined(CONFIG_ISA_DSP_LEVEL2)
printk("ACC0H[%08lx]:ACC0L[%08lx]\n", \
regs->acc0h, regs->acc0l);
printk("ACC1H[%08lx]:ACC1L[%08lx]\n", \
regs->acc1h, regs->acc1l);
#elif defined(CONFIG_ISA_M32R2) || defined(CONFIG_ISA_M32R)
printk("ACCH[%08lx]:ACCL[%08lx]\n", \
regs->acc0h, regs->acc0l);
#else
#error unknown isa configuration
#endif
}
/*
* Free current thread data structures etc..
*/
void exit_thread(void)
{
/* Nothing to do. */
DPRINTK("pid = %d\n", current->pid);
}
void flush_thread(void)
{
DPRINTK("pid = %d\n", current->pid);
memset(¤t->thread.debug_trap, 0, sizeof(struct debug_trap));
}
void release_thread(struct task_struct *dead_task)
{
/* do nothing */
DPRINTK("pid = %d\n", dead_task->pid);
}
/* Fill in the fpu structure for a core dump.. */
int dump_fpu(struct pt_regs *regs, elf_fpregset_t *fpu)
{
return 0; /* Task didn't use the fpu at all. */
}
int copy_thread(unsigned long clone_flags, unsigned long spu,
unsigned long arg, struct task_struct *tsk)
{
struct pt_regs *childregs = task_pt_regs(tsk);
extern void ret_from_fork(void);
extern void ret_from_kernel_thread(void);
if (unlikely(tsk->flags & PF_KTHREAD)) {
memset(childregs, 0, sizeof(struct pt_regs));
childregs->psw = M32R_PSW_BIE;
childregs->r1 = spu; /* fn */
childregs->r0 = arg;
tsk->thread.lr = (unsigned long)ret_from_kernel_thread;
} else {
/* Copy registers */
*childregs = *current_pt_regs();
if (spu)
childregs->spu = spu;
childregs->r0 = 0; /* Child gets zero as return value */
tsk->thread.lr = (unsigned long)ret_from_fork;
}
tsk->thread.sp = (unsigned long)childregs;
return 0;
}
/*
* These bracket the sleeping functions..
*/
#define first_sched ((unsigned long) scheduling_functions_start_here)
#define last_sched ((unsigned long) scheduling_functions_end_here)
unsigned long get_wchan(struct task_struct *p)
{
/* M32R_FIXME */
return (0);
}
| lgpl-2.1 |
cscenter/Arduino | libraries/GSM/src/GSM3ShieldV1BandManagement.cpp | 145 | 2838 | /*
This file is part of the GSM3 communications library for Arduino
-- Multi-transport communications platform
-- Fully asynchronous
-- Includes code for the Arduino-Telefonica GSM/GPRS Shield V1
-- Voice calls
-- SMS
-- TCP/IP connections
-- HTTP basic clients
This library has been developed by Telefónica Digital - PDI -
- Physical Internet Lab, as part as its collaboration with
Arduino and the Open Hardware Community.
September-December 2012
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
The latest version of this library can always be found at
https://github.com/BlueVia/Official-Arduino
*/
#include <GSM3ShieldV1BandManagement.h>
GSM3ShieldV1BandManagement::GSM3ShieldV1BandManagement(bool trace): modem(trace)
{
quectelStrings[UNDEFINED]="";
quectelStrings[EGSM_MODE]="\"EGSM_MODE\"";
quectelStrings[DCS_MODE]="\"DCS_MODE\"";
quectelStrings[PCS_MODE]="\"PCS_MODE\"";
quectelStrings[EGSM_DCS_MODE]="\"EGSM_DCS_MODE\"";
quectelStrings[GSM850_PCS_MODE]="\"GSM850_PCS_MODE\"";
quectelStrings[GSM850_EGSM_DCS_PCS_MODE]="\"GSM850_EGSM_DCS_PCS_MODE\"";
}
GSM3_NetworkStatus_t GSM3ShieldV1BandManagement::begin()
{
// check modem response
modem.begin();
// reset hardware
modem.restartModem();
return IDLE;
}
String GSM3ShieldV1BandManagement::getBand()
{
String modemResponse=modem.writeModemCommand("AT+QBAND?", 2000);
for(GSM3GSMBand i=GSM850_EGSM_DCS_PCS_MODE;i>UNDEFINED;i=(GSM3GSMBand)((int)i-1))
{
if(modemResponse.indexOf(quectelStrings[i])>=0)
return quectelStrings[i];
}
Serial.print("Unrecognized modem answer:");
Serial.println(modemResponse);
return "";
}
bool GSM3ShieldV1BandManagement::setBand(String band)
{
String command;
String modemResponse;
bool found=false;
command="AT+QBAND=";
for(GSM3GSMBand i=EGSM_MODE;((i<=GSM850_EGSM_DCS_PCS_MODE)&&(!found));i=(GSM3GSMBand)((int)i+1))
{
String aux=quectelStrings[i];
if(aux.indexOf(band)>=0)
{
command+=aux;
found=true;
}
}
if(!found)
return false;
// Quad-band takes an awful lot of time
modemResponse=modem.writeModemCommand(command, 15000);
if(modemResponse.indexOf("QBAND")>=0)
return true;
else
return false;
}
| lgpl-2.1 |
cloudlinux/MariaDB-10.0-governor | pcre/pcre16_printint.c | 188 | 2179 | /*************************************************
* Perl-Compatible Regular Expressions *
*************************************************/
/* PCRE is a library of functions to support regular expressions whose syntax
and semantics are as close as possible to those of the Perl 5 language.
Written by Philip Hazel
Copyright (c) 1997-2012 University of Cambridge
-----------------------------------------------------------------------------
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the University of Cambridge nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------
*/
/* Generate code with 16 bit character support. */
#define COMPILE_PCRE16
#include "pcre_printint.c"
/* End of pcre16_printint.c */
| lgpl-2.1 |
deovrat/jna | native/libffi/testsuite/libffi.call/nested_struct.c | 469 | 4695 | /* Area: ffi_call, closure_call
Purpose: Check structure passing with different structure size.
Contains structs as parameter of the struct itself.
Limitations: none.
PR: none.
Originator: <andreast@gcc.gnu.org> 20030828 */
/* { dg-do run } */
#include "ffitest.h"
typedef struct cls_struct_16byte1 {
double a;
float b;
int c;
} cls_struct_16byte1;
typedef struct cls_struct_16byte2 {
int ii;
double dd;
float ff;
} cls_struct_16byte2;
typedef struct cls_struct_combined {
cls_struct_16byte1 d;
cls_struct_16byte2 e;
} cls_struct_combined;
cls_struct_combined cls_struct_combined_fn(struct cls_struct_16byte1 b0,
struct cls_struct_16byte2 b1,
struct cls_struct_combined b2)
{
struct cls_struct_combined result;
result.d.a = b0.a + b1.dd + b2.d.a;
result.d.b = b0.b + b1.ff + b2.d.b;
result.d.c = b0.c + b1.ii + b2.d.c;
result.e.ii = b0.c + b1.ii + b2.e.ii;
result.e.dd = b0.a + b1.dd + b2.e.dd;
result.e.ff = b0.b + b1.ff + b2.e.ff;
printf("%g %g %d %d %g %g %g %g %d %d %g %g: %g %g %d %d %g %g\n",
b0.a, b0.b, b0.c,
b1.ii, b1.dd, b1.ff,
b2.d.a, b2.d.b, b2.d.c,
b2.e.ii, b2.e.dd, b2.e.ff,
result.d.a, result.d.b, result.d.c,
result.e.ii, result.e.dd, result.e.ff);
return result;
}
static void
cls_struct_combined_gn(ffi_cif* cif __UNUSED__, void* resp, void** args,
void* userdata __UNUSED__)
{
struct cls_struct_16byte1 b0;
struct cls_struct_16byte2 b1;
struct cls_struct_combined b2;
b0 = *(struct cls_struct_16byte1*)(args[0]);
b1 = *(struct cls_struct_16byte2*)(args[1]);
b2 = *(struct cls_struct_combined*)(args[2]);
*(cls_struct_combined*)resp = cls_struct_combined_fn(b0, b1, b2);
}
int main (void)
{
ffi_cif cif;
void *code;
ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
void* args_dbl[5];
ffi_type* cls_struct_fields[5];
ffi_type* cls_struct_fields1[5];
ffi_type* cls_struct_fields2[5];
ffi_type cls_struct_type, cls_struct_type1, cls_struct_type2;
ffi_type* dbl_arg_types[5];
struct cls_struct_16byte1 e_dbl = { 9.0, 2.0, 6};
struct cls_struct_16byte2 f_dbl = { 1, 2.0, 3.0};
struct cls_struct_combined g_dbl = {{4.0, 5.0, 6},
{3, 1.0, 8.0}};
struct cls_struct_combined res_dbl;
cls_struct_type.size = 0;
cls_struct_type.alignment = 0;
cls_struct_type.type = FFI_TYPE_STRUCT;
cls_struct_type.elements = cls_struct_fields;
cls_struct_type1.size = 0;
cls_struct_type1.alignment = 0;
cls_struct_type1.type = FFI_TYPE_STRUCT;
cls_struct_type1.elements = cls_struct_fields1;
cls_struct_type2.size = 0;
cls_struct_type2.alignment = 0;
cls_struct_type2.type = FFI_TYPE_STRUCT;
cls_struct_type2.elements = cls_struct_fields2;
cls_struct_fields[0] = &ffi_type_double;
cls_struct_fields[1] = &ffi_type_float;
cls_struct_fields[2] = &ffi_type_sint;
cls_struct_fields[3] = NULL;
cls_struct_fields1[0] = &ffi_type_sint;
cls_struct_fields1[1] = &ffi_type_double;
cls_struct_fields1[2] = &ffi_type_float;
cls_struct_fields1[3] = NULL;
cls_struct_fields2[0] = &cls_struct_type;
cls_struct_fields2[1] = &cls_struct_type1;
cls_struct_fields2[2] = NULL;
dbl_arg_types[0] = &cls_struct_type;
dbl_arg_types[1] = &cls_struct_type1;
dbl_arg_types[2] = &cls_struct_type2;
dbl_arg_types[3] = NULL;
CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 3, &cls_struct_type2,
dbl_arg_types) == FFI_OK);
args_dbl[0] = &e_dbl;
args_dbl[1] = &f_dbl;
args_dbl[2] = &g_dbl;
args_dbl[3] = NULL;
ffi_call(&cif, FFI_FN(cls_struct_combined_fn), &res_dbl, args_dbl);
/* { dg-output "9 2 6 1 2 3 4 5 6 3 1 8: 15 10 13 10 12 13" } */
CHECK( res_dbl.d.a == (e_dbl.a + f_dbl.dd + g_dbl.d.a));
CHECK( res_dbl.d.b == (e_dbl.b + f_dbl.ff + g_dbl.d.b));
CHECK( res_dbl.d.c == (e_dbl.c + f_dbl.ii + g_dbl.d.c));
CHECK( res_dbl.e.ii == (e_dbl.c + f_dbl.ii + g_dbl.e.ii));
CHECK( res_dbl.e.dd == (e_dbl.a + f_dbl.dd + g_dbl.e.dd));
CHECK( res_dbl.e.ff == (e_dbl.b + f_dbl.ff + g_dbl.e.ff));
CHECK(ffi_prep_closure_loc(pcl, &cif, cls_struct_combined_gn, NULL, code) == FFI_OK);
res_dbl = ((cls_struct_combined(*)(cls_struct_16byte1,
cls_struct_16byte2,
cls_struct_combined))
(code))(e_dbl, f_dbl, g_dbl);
/* { dg-output "\n9 2 6 1 2 3 4 5 6 3 1 8: 15 10 13 10 12 13" } */
CHECK( res_dbl.d.a == (e_dbl.a + f_dbl.dd + g_dbl.d.a));
CHECK( res_dbl.d.b == (e_dbl.b + f_dbl.ff + g_dbl.d.b));
CHECK( res_dbl.d.c == (e_dbl.c + f_dbl.ii + g_dbl.d.c));
CHECK( res_dbl.e.ii == (e_dbl.c + f_dbl.ii + g_dbl.e.ii));
CHECK( res_dbl.e.dd == (e_dbl.a + f_dbl.dd + g_dbl.e.dd));
CHECK( res_dbl.e.ff == (e_dbl.b + f_dbl.ff + g_dbl.e.ff));
exit(0);
}
| lgpl-2.1 |
WalleTrader/cmw-cmx | demo/demo-class1.cpp | 1 | 1100 | /*
* CMX (c) Copyright 2013 CERN
* This software is distributed under the terms of the GNU Lesser General Public Licence version 3
* (LGPL Version 3), copied verbatim in the file “COPYING”.
* In applying this licence, CERN does not waive the privileges and immunities granted to it by virtue of its
* status as an Intergovernmental Organization or submit itself to any jurisdiction. */
#include <cstdlib>
#include "demo-class1.h"
#include <cmw-cmx-cpp/CmxSupport.h>
#include <cmw-cmx-cpp/ProcessComponent.h>
namespace cmw {
namespace cmx {
namespace demo {
using namespace cmw::cmx;
class Demo2Metrics : CmxSupport
{
public:
Demo2Metrics(const std::string & name) :
random(newInt64("Demo2Metrics." + name, "random"))
{
}
CmxInt64 random;
};
Demo2::Demo2(const std::string & name)
{
metrics = new Demo2Metrics(name);
}
Demo2::~Demo2()
{
delete metrics;
}
void Demo2::execute()
{
metrics->random = std::rand();
}
void Demo2::updateProcess() {
ProcessComponent::update();
}
} // namespace demo
} // namespace cmx
} // namespace cmw
| lgpl-3.0 |
LodePublishing/GUI | ClawGUI/ef2/fixture/guicorefixture/bitmap_fixture.cpp | 1 | 1583 | #include <misc/randomgenerator.hpp>
#include "bitmap_fixture.hpp"
#include <misc/miscellaneous.hpp>
#include <misc/io.hpp>
#include <guicore/bitmap_storage.hpp>
#include <guicore/guicore_directories.hpp>
#pragma warning(push, 0)
#include <boost/assign/list_of.hpp>
#pragma warning(pop)
Bitmap_Fixture::Bitmap_Fixture() :
test_fileName1("clawsoftware.jpg"),
test_fileName2("clawsoftware.png"),
test_objectSizeFixture1(),
test_objectSizeFixture2(),
test_transparent1(RandomGenerator::instance().rndBool()),
test_transparent2(RandomGenerator::instance().rndBool()),
test_bitmap1(new Bitmap(test_fileName1, test_objectSizeFixture1.test_objectsize, test_transparent1)),
test_bitmap2(new Bitmap(test_fileName2, test_objectSizeFixture2.test_objectsize, test_transparent2)),
test_bitmapMap(init_bitmapmap_helper())
{
GuiCoreDirectories::initTemp("temp");
BitmapStorage::instance(test_bitmapMap);
}
Bitmap_Fixture::~Bitmap_Fixture()
{
GuiCoreDirectories::initTemp("temp");
BitmapStorage::clear();
GuiCoreDirectories::init();
}
const std::map<const boost::uuids::uuid, const boost::shared_ptr<const Bitmap> > Bitmap_Fixture::init_bitmapmap_helper() {
std::map<const boost::uuids::uuid, const boost::shared_ptr<const Bitmap> > bitmapMap;
bitmapMap.insert(std::pair<const boost::uuids::uuid, const boost::shared_ptr<const Bitmap> >(test_bitmap1->getId(), test_bitmap1));
bitmapMap.insert(std::pair<const boost::uuids::uuid, const boost::shared_ptr<const Bitmap> >(test_bitmap2->getId(), test_bitmap2));
return bitmapMap;
} | lgpl-3.0 |
pcolby/libqtaws | src/devicefarm/getjobrequest.cpp | 1 | 3447 | /*
Copyright 2013-2021 Paul Colby
This file is part of QtAws.
QtAws is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QtAws is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with the QtAws. If not, see <http://www.gnu.org/licenses/>.
*/
#include "getjobrequest.h"
#include "getjobrequest_p.h"
#include "getjobresponse.h"
#include "devicefarmrequest_p.h"
namespace QtAws {
namespace DeviceFarm {
/*!
* \class QtAws::DeviceFarm::GetJobRequest
* \brief The GetJobRequest class provides an interface for DeviceFarm GetJob requests.
*
* \inmodule QtAwsDeviceFarm
*
* Welcome to the AWS Device Farm API documentation, which contains APIs
*
* for> <ul> <li>
*
* Testing on desktop
*
* browser>
*
* Device Farm makes it possible for you to test your web applications on desktop browsers using Selenium. The APIs for
* desktop browser testing contain <code>TestGrid</code> in their names. For more information, see <a
* href="https://docs.aws.amazon.com/devicefarm/latest/testgrid/">Testing Web Applications on Selenium with Device
*
* Farm</a>> </li> <li>
*
* Testing on real mobile
*
* device>
*
* Device Farm makes it possible for you to test apps on physical phones, tablets, and other devices in the cloud. For more
* information, see the <a href="https://docs.aws.amazon.com/devicefarm/latest/developerguide/">Device Farm Developer
*
* \sa DeviceFarmClient::getJob
*/
/*!
* Constructs a copy of \a other.
*/
GetJobRequest::GetJobRequest(const GetJobRequest &other)
: DeviceFarmRequest(new GetJobRequestPrivate(*other.d_func(), this))
{
}
/*!
* Constructs a GetJobRequest object.
*/
GetJobRequest::GetJobRequest()
: DeviceFarmRequest(new GetJobRequestPrivate(DeviceFarmRequest::GetJobAction, this))
{
}
/*!
* \reimp
*/
bool GetJobRequest::isValid() const
{
return false;
}
/*!
* Returns a GetJobResponse object to process \a reply.
*
* \sa QtAws::Core::AwsAbstractClient::send
*/
QtAws::Core::AwsAbstractResponse * GetJobRequest::response(QNetworkReply * const reply) const
{
return new GetJobResponse(*this, reply);
}
/*!
* \class QtAws::DeviceFarm::GetJobRequestPrivate
* \brief The GetJobRequestPrivate class provides private implementation for GetJobRequest.
* \internal
*
* \inmodule QtAwsDeviceFarm
*/
/*!
* Constructs a GetJobRequestPrivate object for DeviceFarm \a action,
* with public implementation \a q.
*/
GetJobRequestPrivate::GetJobRequestPrivate(
const DeviceFarmRequest::Action action, GetJobRequest * const q)
: DeviceFarmRequestPrivate(action, q)
{
}
/*!
* Constructs a copy of \a other, with public implementation \a q.
*
* This copy-like constructor exists for the benefit of the GetJobRequest
* class' copy constructor.
*/
GetJobRequestPrivate::GetJobRequestPrivate(
const GetJobRequestPrivate &other, GetJobRequest * const q)
: DeviceFarmRequestPrivate(other, q)
{
}
} // namespace DeviceFarm
} // namespace QtAws
| lgpl-3.0 |
GiovanniBussi/test-travis-ci | src/multicolvar/VolumeTetrapore.cpp | 2 | 22890 | /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Copyright (c) 2015-2020 The plumed team
(see the PEOPLE file at the root of the distribution for a list of names)
See http://www.plumed.org for more information.
This file is part of plumed, version 2.
plumed is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
plumed is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with plumed. If not, see <http://www.gnu.org/licenses/>.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
#include "core/ActionRegister.h"
#include "core/PlumedMain.h"
#include "core/Atoms.h"
#include "tools/Units.h"
#include "tools/Pbc.h"
#include "ActionVolume.h"
//+PLUMEDOC VOLUMES TETRAHEDRALPORE
/*
This quantity can be used to calculate functions of the distribution of collective variables for the atoms lie that lie in a box defined by the positions of four atoms at the corners of a tetrahedron.
Each of the base quantities calculated by a multicolvar can can be assigned to a particular point in three
dimensional space. For example, if we have the coordination numbers for all the atoms in the
system each coordination number can be assumed to lie on the position of the central atom.
Because each base quantity can be assigned to a particular point in space we can calculate functions of the
distribution of base quantities in a particular part of the box by using:
\f[
\overline{s}_{\tau} = \frac{ \sum_i f(s_i) w(u_i,v_i,w_i) }{ \sum_i w(u_i,v_i,w_i) }
\f]
where the sum is over the collective variables, \f$s_i\f$, each of which can be thought to be at \f$ (u_i,v_i,z_i)\f$.
The function \f$(s_i)\f$ can be any of the usual LESS_THAN, MORE_THAN, WITHIN etc that are used in all other multicolvars.
Notice that here (at variance with what is done in \ref AROUND) we have transformed from the usual \f$(x_i,y_i,z_i)\f$
position to a position in \f$ (u_i,v_i,z_i)\f$. This is done using a rotation matrix as follows:
\f[
\left(
\begin{matrix}
u_i \\
v_i \\
w_i
\end{matrix}
\right) = \mathbf{R}
\left(
\begin{matrix}
x_i - x_o \\
y_i - y_o \\
z_i - z_o
\end{matrix}
\right)
\f]
where \f$\mathbf{R}\f$ is a rotation matrix that is calculated by constructing a set of three orthonormal vectors from the
reference positions specified by the user. Initially unit vectors are found by calculating the bisector, \f$\mathbf{b}\f$, and
cross product, \f$\mathbf{c}\f$, of the vectors connecting atoms 1 and 2. A third unit vector, \f$\mathbf{p}\f$ is then found by taking the cross
product between the cross product calculated during the first step, \f$\mathbf{c}\f$ and the bisector, \f$\mathbf{b}\f$. From this
second cross product \f$\mathbf{p}\f$ and the bisector \f$\mathbf{b}\f$ two new vectors are calculated using:
\f[
v_1 = \cos\left(\frac{\pi}{4}\right)\mathbf{b} + \sin\left(\frac{\pi}{4}\right)\mathbf{p} \qquad \textrm{and} \qquad
v_2 = \cos\left(\frac{\pi}{4}\right)\mathbf{b} - \sin\left(\frac{\pi}{4}\right)\mathbf{p}
\f]
In the previous function \f$ w(u_i,v_i,w_i) \f$ measures whether or not the system is in the subregion of interest. It
is equal to:
\f[
w(u_i,v_i,w_i) = \int_{0}^{u'} \int_{0}^{v'} \int_{0}^{w'} \textrm{d}u\textrm{d}v\textrm{d}w
K\left( \frac{u - u_i}{\sigma} \right)K\left( \frac{v - v_i}{\sigma} \right)K\left( \frac{w - w_i}{\sigma} \right)
\f]
where \f$K\f$ is one of the kernel functions described on \ref histogrambead and \f$\sigma\f$ is a bandwidth parameter.
The values of \f$u'\f$ and \f$v'\f$ are found by finding the projections of the vectors connecting atoms 1 and 2 and 1
and 3 \f$v_1\f$ and \f$v_2\f$. This gives four projections: the largest two projections are used in the remainder of
the calculations. \f$w'\f$ is calculated by taking the projection of the vector connecting atoms 1 and 4 on the vector
\f$\mathbf{c}\f$. Notice that the manner by which this box is constructed differs from the way this is done in \ref CAVITY.
This is in fact the only point of difference between these two actions.
\par Examples
The following commands tell plumed to calculate the number of atom inside a tetrahedral cavity. The extent of the tetrahedral
cavity is calculated from the positions of atoms 1, 4, 5, and 11, The final value will be labeled cav.
\plumedfile
d1: DENSITY SPECIES=20-500
TETRAHEDRALPORE DATA=d1 ATOMS=1,4,5,11 SIGMA=0.1 LABEL=cav
\endplumedfile
The following command tells plumed to calculate the coordination numbers (with other water molecules) for the water
molecules in the tetrahedral cavity described above. The average coordination number and the number of coordination
numbers more than 4 is then calculated. The values of these two quantities are given the labels cav.mean and cav.morethan
\plumedfile
d1: COORDINATIONNUMBER SPECIES=20-500 R_0=0.1
CAVITY DATA=d1 ATOMS=1,4,5,11 SIGMA=0.1 MEAN MORE_THAN={RATIONAL R_0=4} LABEL=cav
\endplumedfile
*/
//+ENDPLUMEDOC
namespace PLMD {
namespace multicolvar {
class VolumeTetrapore : public ActionVolume {
private:
bool boxout;
OFile boxfile;
double lenunit;
double jacob_det;
double len_bi, len_cross, len_perp, sigma;
Vector origin, bi, cross, perp;
std::vector<Vector> dlbi, dlcross, dlperp;
std::vector<Tensor> dbi, dcross, dperp;
public:
static void registerKeywords( Keywords& keys );
explicit VolumeTetrapore(const ActionOptions& ao);
~VolumeTetrapore();
void setupRegions() override;
void update() override;
double calculateNumberInside( const Vector& cpos, Vector& derivatives, Tensor& vir, std::vector<Vector>& refders ) const override;
};
PLUMED_REGISTER_ACTION(VolumeTetrapore,"TETRAHEDRALPORE")
void VolumeTetrapore::registerKeywords( Keywords& keys ) {
ActionVolume::registerKeywords( keys );
keys.add("atoms","ATOMS","the positions of four atoms that define spatial extent of the cavity");
keys.addFlag("PRINT_BOX",false,"write out the positions of the corners of the box to an xyz file");
keys.add("optional","FILE","the file on which to write out the box coordinates");
keys.add("optional","UNITS","( default=nm ) the units in which to write out the corners of the box");
}
VolumeTetrapore::VolumeTetrapore(const ActionOptions& ao):
Action(ao),
ActionVolume(ao),
boxout(false),
lenunit(1.0),
dlbi(4),
dlcross(4),
dlperp(4),
dbi(3),
dcross(3),
dperp(3)
{
std::vector<AtomNumber> atoms;
parseAtomList("ATOMS",atoms);
if( atoms.size()!=4 ) error("number of atoms should be equal to four");
log.printf(" boundaries for region are calculated based on positions of atoms : ");
for(unsigned i=0; i<atoms.size(); ++i) log.printf("%d ",atoms[i].serial() );
log.printf("\n");
boxout=false; parseFlag("PRINT_BOX",boxout);
if(boxout) {
std::string boxfname; parse("FILE",boxfname);
if(boxfname.length()==0) error("no name for box file specified");
std::string unitname; parse("UNITS",unitname);
if ( unitname.length()>0 ) {
Units u; u.setLength(unitname);
lenunit=plumed.getAtoms().getUnits().getLength()/u.getLength();
} else {
unitname="nm";
}
boxfile.link(*this);
boxfile.open( boxfname.c_str() );
log.printf(" printing box coordinates on file named %s in %s \n",boxfname.c_str(), unitname.c_str() );
}
checkRead();
requestAtoms(atoms);
// We have to readd the dependency because requestAtoms removes it
addDependency( getPntrToMultiColvar() );
}
VolumeTetrapore::~VolumeTetrapore() {
}
void VolumeTetrapore::setupRegions() {
// Make some space for things
Vector d1, d2, d3;
// Retrieve the sigma value
sigma=getSigma();
// Set the position of the origin
origin=getPosition(0);
// Get two vectors
d1 = pbcDistance(origin,getPosition(1));
d2 = pbcDistance(origin,getPosition(2));
// Find the vector connecting the origin to the top corner of
// the subregion
d3 = pbcDistance(origin,getPosition(3));
// Create a set of unit vectors
Vector bisector = d1 + d2; double bmod=bisector.modulo(); bisector=bisector/bmod;
// bi = d1 / d1l; len_bi=dotProduct( d3, bi );
cross = crossProduct( d1, d2 ); double crossmod=cross.modulo();
cross = cross / crossmod; len_cross=dotProduct( d3, cross );
Vector truep = crossProduct( cross, bisector );
// These are our true vectors 45 degrees from bisector
bi = cos(pi/4.0)*bisector + sin(pi/4.0)*truep;
perp = cos(pi/4.0)*bisector - sin(pi/4.0)*truep;
// And the lengths of the various parts average distance to opposite corners of tetetrahedron
len_bi = dotProduct( d1, bi ); double len_bi2 = dotProduct( d2, bi ); unsigned lbi=1;
if( len_bi2>len_bi ) { len_bi=len_bi2; lbi=2; }
len_perp = dotProduct( d1, perp ); double len_perp2 = dotProduct( d2, perp ); unsigned lpi=1;
if( len_perp2>len_perp ) { len_perp=len_perp2; lpi=2; }
plumed_assert( lbi!=lpi );
Tensor tcderiv; double cmod3=crossmod*crossmod*crossmod; Vector ucross=crossmod*cross;
tcderiv.setCol( 0, crossProduct( d1, Vector(-1.0,0.0,0.0) ) + crossProduct( Vector(-1.0,0.0,0.0), d2 ) );
tcderiv.setCol( 1, crossProduct( d1, Vector(0.0,-1.0,0.0) ) + crossProduct( Vector(0.0,-1.0,0.0), d2 ) );
tcderiv.setCol( 2, crossProduct( d1, Vector(0.0,0.0,-1.0) ) + crossProduct( Vector(0.0,0.0,-1.0), d2 ) );
dcross[0](0,0)=( tcderiv(0,0)/crossmod - ucross[0]*(ucross[0]*tcderiv(0,0) + ucross[1]*tcderiv(1,0) + ucross[2]*tcderiv(2,0))/cmod3 ); // dx/dx
dcross[0](0,1)=( tcderiv(0,1)/crossmod - ucross[0]*(ucross[0]*tcderiv(0,1) + ucross[1]*tcderiv(1,1) + ucross[2]*tcderiv(2,1))/cmod3 ); // dx/dy
dcross[0](0,2)=( tcderiv(0,2)/crossmod - ucross[0]*(ucross[0]*tcderiv(0,2) + ucross[1]*tcderiv(1,2) + ucross[2]*tcderiv(2,2))/cmod3 ); // dx/dz
dcross[0](1,0)=( tcderiv(1,0)/crossmod - ucross[1]*(ucross[0]*tcderiv(0,0) + ucross[1]*tcderiv(1,0) + ucross[2]*tcderiv(2,0))/cmod3 ); // dy/dx
dcross[0](1,1)=( tcderiv(1,1)/crossmod - ucross[1]*(ucross[0]*tcderiv(0,1) + ucross[1]*tcderiv(1,1) + ucross[2]*tcderiv(2,1))/cmod3 ); // dy/dy
dcross[0](1,2)=( tcderiv(1,2)/crossmod - ucross[1]*(ucross[0]*tcderiv(0,2) + ucross[1]*tcderiv(1,2) + ucross[2]*tcderiv(2,2))/cmod3 ); // dy/dz
dcross[0](2,0)=( tcderiv(2,0)/crossmod - ucross[2]*(ucross[0]*tcderiv(0,0) + ucross[1]*tcderiv(1,0) + ucross[2]*tcderiv(2,0))/cmod3 ); // dz/dx
dcross[0](2,1)=( tcderiv(2,1)/crossmod - ucross[2]*(ucross[0]*tcderiv(0,1) + ucross[1]*tcderiv(1,1) + ucross[2]*tcderiv(2,1))/cmod3 ); // dz/dy
dcross[0](2,2)=( tcderiv(2,2)/crossmod - ucross[2]*(ucross[0]*tcderiv(0,2) + ucross[1]*tcderiv(1,2) + ucross[2]*tcderiv(2,2))/cmod3 ); // dz/dz
tcderiv.setCol( 0, crossProduct( Vector(1.0,0.0,0.0), d2 ) );
tcderiv.setCol( 1, crossProduct( Vector(0.0,1.0,0.0), d2 ) );
tcderiv.setCol( 2, crossProduct( Vector(0.0,0.0,1.0), d2 ) );
dcross[1](0,0)=( tcderiv(0,0)/crossmod - ucross[0]*(ucross[0]*tcderiv(0,0) + ucross[1]*tcderiv(1,0) + ucross[2]*tcderiv(2,0))/cmod3 ); // dx/dx
dcross[1](0,1)=( tcderiv(0,1)/crossmod - ucross[0]*(ucross[0]*tcderiv(0,1) + ucross[1]*tcderiv(1,1) + ucross[2]*tcderiv(2,1))/cmod3 ); // dx/dy
dcross[1](0,2)=( tcderiv(0,2)/crossmod - ucross[0]*(ucross[0]*tcderiv(0,2) + ucross[1]*tcderiv(1,2) + ucross[2]*tcderiv(2,2))/cmod3 ); // dx/dz
dcross[1](1,0)=( tcderiv(1,0)/crossmod - ucross[1]*(ucross[0]*tcderiv(0,0) + ucross[1]*tcderiv(1,0) + ucross[2]*tcderiv(2,0))/cmod3 ); // dy/dx
dcross[1](1,1)=( tcderiv(1,1)/crossmod - ucross[1]*(ucross[0]*tcderiv(0,1) + ucross[1]*tcderiv(1,1) + ucross[2]*tcderiv(2,1))/cmod3 ); // dy/dy
dcross[1](1,2)=( tcderiv(1,2)/crossmod - ucross[1]*(ucross[0]*tcderiv(0,2) + ucross[1]*tcderiv(1,2) + ucross[2]*tcderiv(2,2))/cmod3 ); // dy/dz
dcross[1](2,0)=( tcderiv(2,0)/crossmod - ucross[2]*(ucross[0]*tcderiv(0,0) + ucross[1]*tcderiv(1,0) + ucross[2]*tcderiv(2,0))/cmod3 ); // dz/dx
dcross[1](2,1)=( tcderiv(2,1)/crossmod - ucross[2]*(ucross[0]*tcderiv(0,1) + ucross[1]*tcderiv(1,1) + ucross[2]*tcderiv(2,1))/cmod3 ); // dz/dy
dcross[1](2,2)=( tcderiv(2,2)/crossmod - ucross[2]*(ucross[0]*tcderiv(0,2) + ucross[1]*tcderiv(1,2) + ucross[2]*tcderiv(2,2))/cmod3 ); // dz/dz
tcderiv.setCol( 0, crossProduct( d1, Vector(1.0,0.0,0.0) ) );
tcderiv.setCol( 1, crossProduct( d1, Vector(0.0,1.0,0.0) ) );
tcderiv.setCol( 2, crossProduct( d1, Vector(0.0,0.0,1.0) ) );
dcross[2](0,0)=( tcderiv(0,0)/crossmod - ucross[0]*(ucross[0]*tcderiv(0,0) + ucross[1]*tcderiv(1,0) + ucross[2]*tcderiv(2,0))/cmod3 ); // dx/dx
dcross[2](0,1)=( tcderiv(0,1)/crossmod - ucross[0]*(ucross[0]*tcderiv(0,1) + ucross[1]*tcderiv(1,1) + ucross[2]*tcderiv(2,1))/cmod3 ); // dx/dy
dcross[2](0,2)=( tcderiv(0,2)/crossmod - ucross[0]*(ucross[0]*tcderiv(0,2) + ucross[1]*tcderiv(1,2) + ucross[2]*tcderiv(2,2))/cmod3 ); // dx/dz
dcross[2](1,0)=( tcderiv(1,0)/crossmod - ucross[1]*(ucross[0]*tcderiv(0,0) + ucross[1]*tcderiv(1,0) + ucross[2]*tcderiv(2,0))/cmod3 ); // dy/dx
dcross[2](1,1)=( tcderiv(1,1)/crossmod - ucross[1]*(ucross[0]*tcderiv(0,1) + ucross[1]*tcderiv(1,1) + ucross[2]*tcderiv(2,1))/cmod3 ); // dy/dy
dcross[2](1,2)=( tcderiv(1,2)/crossmod - ucross[1]*(ucross[0]*tcderiv(0,2) + ucross[1]*tcderiv(1,2) + ucross[2]*tcderiv(2,2))/cmod3 ); // dy/dz
dcross[2](2,0)=( tcderiv(2,0)/crossmod - ucross[2]*(ucross[0]*tcderiv(0,0) + ucross[1]*tcderiv(1,0) + ucross[2]*tcderiv(2,0))/cmod3 ); // dz/dx
dcross[2](2,1)=( tcderiv(2,1)/crossmod - ucross[2]*(ucross[0]*tcderiv(0,1) + ucross[1]*tcderiv(1,1) + ucross[2]*tcderiv(2,1))/cmod3 ); // dz/dy
dcross[2](2,2)=( tcderiv(2,2)/crossmod - ucross[2]*(ucross[0]*tcderiv(0,2) + ucross[1]*tcderiv(1,2) + ucross[2]*tcderiv(2,2))/cmod3 ); // dz/dz
std::vector<Tensor> dbisector(3);
double bmod3=bmod*bmod*bmod; Vector ubisector=bmod*bisector;
dbisector[0](0,0)= -2.0/bmod + 2*ubisector[0]*ubisector[0]/bmod3;
dbisector[0](0,1)= 2*ubisector[0]*ubisector[1]/bmod3;
dbisector[0](0,2)= 2*ubisector[0]*ubisector[2]/bmod3;
dbisector[0](1,0)= 2*ubisector[1]*ubisector[0]/bmod3;
dbisector[0](1,1)= -2.0/bmod + 2*ubisector[1]*ubisector[1]/bmod3;
dbisector[0](1,2)= 2*ubisector[1]*ubisector[2]/bmod3;
dbisector[0](2,0)= 2*ubisector[2]*ubisector[0]/bmod3;
dbisector[0](2,1)= 2*ubisector[2]*ubisector[1]/bmod3;
dbisector[0](2,2)= -2.0/bmod + 2*ubisector[2]*ubisector[2]/bmod3;
dbisector[1](0,0)= 1.0/bmod - ubisector[0]*ubisector[0]/bmod3;
dbisector[1](0,1)= -ubisector[0]*ubisector[1]/bmod3;
dbisector[1](0,2)= -ubisector[0]*ubisector[2]/bmod3;
dbisector[1](1,0)= -ubisector[1]*ubisector[0]/bmod3;
dbisector[1](1,1)= 1.0/bmod - ubisector[1]*ubisector[1]/bmod3;
dbisector[1](1,2)= -ubisector[1]*ubisector[2]/bmod3;
dbisector[1](2,0)= -ubisector[2]*ubisector[0]/bmod3;
dbisector[1](2,1)= -ubisector[2]*ubisector[1]/bmod3;
dbisector[1](2,2)=1.0/bmod - ubisector[2]*ubisector[2]/bmod3;
dbisector[2](0,0)=1.0/bmod - ubisector[0]*ubisector[0]/bmod3;
dbisector[2](0,1)= -ubisector[0]*ubisector[1]/bmod3;
dbisector[2](0,2)= -ubisector[0]*ubisector[2]/bmod3;
dbisector[2](1,0)= -ubisector[1]*ubisector[0]/bmod3;
dbisector[2](1,1)=1.0/bmod - ubisector[1]*ubisector[1]/bmod3;
dbisector[2](1,2)= -ubisector[1]*ubisector[2]/bmod3;
dbisector[2](2,0)= -ubisector[2]*ubisector[0]/bmod3;
dbisector[2](2,1)= -ubisector[2]*ubisector[1]/bmod3;
dbisector[2](2,2)=1.0/bmod - ubisector[2]*ubisector[2]/bmod3;
std::vector<Tensor> dtruep(3);
dtruep[0].setCol( 0, ( crossProduct( dcross[0].getCol(0), bisector ) + crossProduct( cross, dbisector[0].getCol(0) ) ) );
dtruep[0].setCol( 1, ( crossProduct( dcross[0].getCol(1), bisector ) + crossProduct( cross, dbisector[0].getCol(1) ) ) );
dtruep[0].setCol( 2, ( crossProduct( dcross[0].getCol(2), bisector ) + crossProduct( cross, dbisector[0].getCol(2) ) ) );
dtruep[1].setCol( 0, ( crossProduct( dcross[1].getCol(0), bisector ) + crossProduct( cross, dbisector[1].getCol(0) ) ) );
dtruep[1].setCol( 1, ( crossProduct( dcross[1].getCol(1), bisector ) + crossProduct( cross, dbisector[1].getCol(1) ) ) );
dtruep[1].setCol( 2, ( crossProduct( dcross[1].getCol(2), bisector ) + crossProduct( cross, dbisector[1].getCol(2) ) ) );
dtruep[2].setCol( 0, ( crossProduct( dcross[2].getCol(0), bisector ) + crossProduct( cross, dbisector[2].getCol(0) ) ) );
dtruep[2].setCol( 1, ( crossProduct( dcross[2].getCol(1), bisector ) + crossProduct( cross, dbisector[2].getCol(1) ) ) );
dtruep[2].setCol( 2, ( crossProduct( dcross[2].getCol(2), bisector ) + crossProduct( cross, dbisector[2].getCol(2) ) ) );
// Now convert these to the derivatives of the true axis
for(unsigned i=0; i<3; ++i) {
dbi[i] = cos(pi/4.0)*dbisector[i] + sin(pi/4.0)*dtruep[i];
dperp[i] = cos(pi/4.0)*dbisector[i] - sin(pi/4.0)*dtruep[i];
}
// Ensure that all lengths are positive
if( len_bi<0 ) {
bi=-bi; len_bi=-len_bi;
for(unsigned i=0; i<3; ++i) dbi[i]*=-1.0;
}
if( len_cross<0 ) {
cross=-cross; len_cross=-len_cross;
for(unsigned i=0; i<3; ++i) dcross[i]*=-1.0;
}
if( len_perp<0 ) {
perp=-perp; len_perp=-len_perp;
for(unsigned i=0; i<3; ++i) dperp[i]*=-1.0;
}
if( len_bi<=0 || len_cross<=0 || len_bi<=0 ) plumed_merror("Invalid box coordinates");
// Now derivatives of lengths
Tensor dd3( Tensor::identity() ); Vector ddb2=d1; if( lbi==2 ) ddb2=d2;
dlbi[1].zero(); dlbi[2].zero(); dlbi[3].zero();
dlbi[0] = matmul(ddb2,dbi[0]) - matmul(bi,dd3);
dlbi[lbi] = matmul(ddb2,dbi[lbi]) + matmul(bi,dd3); // Derivative wrt d1
dlcross[0] = matmul(d3,dcross[0]) - matmul(cross,dd3);
dlcross[1] = matmul(d3,dcross[1]);
dlcross[2] = matmul(d3,dcross[2]);
dlcross[3] = matmul(cross,dd3);
ddb2=d1; if( lpi==2 ) ddb2=d2;
dlperp[1].zero(); dlperp[2].zero(); dlperp[3].zero();
dlperp[0] = matmul(ddb2,dperp[0]) - matmul( perp, dd3 );
dlperp[lpi] = matmul(ddb2,dperp[lpi]) + matmul(perp, dd3);
// Need to calculate the jacobian
Tensor jacob;
jacob(0,0)=bi[0]; jacob(1,0)=bi[1]; jacob(2,0)=bi[2];
jacob(0,1)=cross[0]; jacob(1,1)=cross[1]; jacob(2,1)=cross[2];
jacob(0,2)=perp[0]; jacob(1,2)=perp[1]; jacob(2,2)=perp[2];
jacob_det = fabs( jacob.determinant() );
}
void VolumeTetrapore::update() {
if(boxout) {
boxfile.printf("%d\n",8);
const Tensor & t(getPbc().getBox());
if(getPbc().isOrthorombic()) {
boxfile.printf(" %f %f %f\n",lenunit*t(0,0),lenunit*t(1,1),lenunit*t(2,2));
} else {
boxfile.printf(" %f %f %f %f %f %f %f %f %f\n",
lenunit*t(0,0),lenunit*t(0,1),lenunit*t(0,2),
lenunit*t(1,0),lenunit*t(1,1),lenunit*t(1,2),
lenunit*t(2,0),lenunit*t(2,1),lenunit*t(2,2)
);
}
boxfile.printf("AR %f %f %f \n",lenunit*origin[0],lenunit*origin[1],lenunit*origin[2]);
Vector ut, vt, wt;
ut = origin + len_bi*bi;
vt = origin + len_cross*cross;
wt = origin + len_perp*perp;
boxfile.printf("AR %f %f %f \n",lenunit*(ut[0]), lenunit*(ut[1]), lenunit*(ut[2]) );
boxfile.printf("AR %f %f %f \n",lenunit*(vt[0]), lenunit*(vt[1]), lenunit*(vt[2]) );
boxfile.printf("AR %f %f %f \n",lenunit*(wt[0]), lenunit*(wt[1]), lenunit*(wt[2]) );
boxfile.printf("AR %f %f %f \n",lenunit*(vt[0]+len_bi*bi[0]),
lenunit*(vt[1]+len_bi*bi[1]),
lenunit*(vt[2]+len_bi*bi[2]) );
boxfile.printf("AR %f %f %f \n",lenunit*(ut[0]+len_perp*perp[0]),
lenunit*(ut[1]+len_perp*perp[1]),
lenunit*(ut[2]+len_perp*perp[2]) );
boxfile.printf("AR %f %f %f \n",lenunit*(vt[0]+len_perp*perp[0]),
lenunit*(vt[1]+len_perp*perp[1]),
lenunit*(vt[2]+len_perp*perp[2]) );
boxfile.printf("AR %f %f %f \n",lenunit*(vt[0]+len_perp*perp[0]+len_bi*bi[0]),
lenunit*(vt[1]+len_perp*perp[1]+len_bi*bi[1]),
lenunit*(vt[2]+len_perp*perp[2]+len_bi*bi[2]) );
}
}
double VolumeTetrapore::calculateNumberInside( const Vector& cpos, Vector& derivatives, Tensor& vir, std::vector<Vector>& rderiv ) const {
// Setup the histogram bead
HistogramBead bead; bead.isNotPeriodic(); bead.setKernelType( getKernelType() );
// Calculate distance of atom from origin of new coordinate frame
Vector datom=pbcDistance( origin, cpos );
double ucontr, uder, vcontr, vder, wcontr, wder;
// Calculate contribution from integral along bi
bead.set( 0, len_bi, sigma );
double upos=dotProduct( datom, bi );
ucontr=bead.calculate( upos, uder );
double udlen=bead.uboundDerivative( upos );
double uder2 = bead.lboundDerivative( upos ) - udlen;
// Calculate contribution from integral along cross
bead.set( 0, len_cross, sigma );
double vpos=dotProduct( datom, cross );
vcontr=bead.calculate( vpos, vder );
double vdlen=bead.uboundDerivative( vpos );
double vder2 = bead.lboundDerivative( vpos ) - vdlen;
// Calculate contribution from integral along perp
bead.set( 0, len_perp, sigma );
double wpos=dotProduct( datom, perp );
wcontr=bead.calculate( wpos, wder );
double wdlen=bead.uboundDerivative( wpos );
double wder2 = bead.lboundDerivative( wpos ) - wdlen;
Vector dfd; dfd[0]=uder*vcontr*wcontr; dfd[1]=ucontr*vder*wcontr; dfd[2]=ucontr*vcontr*wder;
derivatives[0] = (dfd[0]*bi[0]+dfd[1]*cross[0]+dfd[2]*perp[0]);
derivatives[1] = (dfd[0]*bi[1]+dfd[1]*cross[1]+dfd[2]*perp[1]);
derivatives[2] = (dfd[0]*bi[2]+dfd[1]*cross[2]+dfd[2]*perp[2]);
double tot = ucontr*vcontr*wcontr*jacob_det;
// Add reference atom derivatives
dfd[0]=uder2*vcontr*wcontr; dfd[1]=ucontr*vder2*wcontr; dfd[2]=ucontr*vcontr*wder2;
Vector dfld; dfld[0]=udlen*vcontr*wcontr; dfld[1]=ucontr*vdlen*wcontr; dfld[2]=ucontr*vcontr*wdlen;
rderiv[0] = dfd[0]*matmul(datom,dbi[0]) + dfd[1]*matmul(datom,dcross[0]) + dfd[2]*matmul(datom,dperp[0]) +
dfld[0]*dlbi[0] + dfld[1]*dlcross[0] + dfld[2]*dlperp[0] - derivatives;
rderiv[1] = dfd[0]*matmul(datom,dbi[1]) + dfd[1]*matmul(datom,dcross[1]) + dfd[2]*matmul(datom,dperp[1]) +
dfld[0]*dlbi[1] + dfld[1]*dlcross[1] + dfld[2]*dlperp[1];
rderiv[2] = dfd[0]*matmul(datom,dbi[2]) + dfd[1]*matmul(datom,dcross[2]) + dfd[2]*matmul(datom,dperp[2]) +
dfld[0]*dlbi[2] + dfld[1]*dlcross[2] + dfld[2]*dlperp[2];
rderiv[3] = dfld[0]*dlbi[3] + dfld[1]*dlcross[3] + dfld[2]*dlperp[3];
vir.zero(); vir-=Tensor( cpos,derivatives );
for(unsigned i=0; i<4; ++i) {
vir -= Tensor( getPosition(i), rderiv[i] );
}
return tot;
}
}
}
| lgpl-3.0 |
ntop/nDPI | src/lib/third_party/src/ndpi_patricia.c | 2 | 27785 | /*
* $Id: patricia.c,v 1.7 2005/12/07 20:46:41 dplonka Exp $
* Dave Plonka <plonka@doit.wisc.edu>
*
* This product includes software developed by the University of Michigan,
* Merit Network, Inc., and their contributors.
*
* This file had been called "radix.c" in the MRT sources.
*
* I renamed it to "patricia.c" since it's not an implementation of a general
* radix trie. Also I pulled in various requirements from "prefix.c" and
* "demo.c" so that it could be used as a standalone API.
https://github.com/deepfield/MRT/blob/master/COPYRIGHT
Copyright (c) 1999-2013
The Regents of the University of Michigan ("The Regents") and Merit
Network, Inc.
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.
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 <assert.h> /* assert */
#include <ctype.h> /* isdigit */
#include <errno.h> /* errno */
#include <math.h> /* sin */
#include <stddef.h> /* NULL */
#include <stdio.h> /* sprintf, fprintf, stderr */
#include <stdlib.h> /* free, atol, calloc */
#include <string.h> /* memcpy, strchr, strlen */
#include <sys/types.h> /* BSD: for inet_addr */
#if !defined(WIN32) && !defined(_MSC_VER)
#include <sys/socket.h> /* BSD, Linux: for inet_addr */
#include <netinet/in.h> /* BSD, Linux: for inet_addr */
#include <arpa/inet.h> /* BSD, Linux, Solaris: for inet_addr */
#endif
#include "ndpi_patricia.h"
static void ndpi_DeleteEntry(void *a) {
ndpi_free(a);
}
/* { from prefix.c */
/* ndpi_prefix_tochar
* convert prefix information to bytes
*/
static u_char* ndpi_prefix_tochar (ndpi_prefix_t * prefix)
{
unsigned short family;
if(prefix == NULL)
return (NULL);
family = prefix->family;
if(family == AF_INET) return ((u_char *) & prefix->add.sin);
else if(family == AF_INET6) return ((u_char *) & prefix->add.sin6);
else /* if(family == AF_MAC) */ return ((u_char *) & prefix->add.mac);
return ((u_char *) & prefix->add.sin);
}
static int ndpi_comp_with_mask (void *addr, void *dest, u_int mask) {
uint32_t *pa = addr;
uint32_t *pd = dest;
uint32_t m;
for(;mask >= 32; mask -= 32, pa++,pd++)
if(*pa != *pd) return 0;
if(!mask) return 1;
m = htonl((~0u) << (32-mask));
return (*pa & m) == (*pd &m);
}
#if 0
/* this allows incomplete prefix */
static int ndpi_my_inet_pton (int af, const char *src, void *dst)
{
if(af == AF_INET) {
int i;
u_char xp[sizeof(struct in_addr)] = {0, 0, 0, 0};
for (i = 0; ; i++) {
int c, val;
c = *src++;
if(!isdigit (c))
return (-1);
val = 0;
do {
val = val * 10 + c - '0';
if(val > 255)
return (0);
c = *src++;
} while (c && isdigit (c));
xp[i] = (u_char)val;
if(c == '\0')
break;
if(c != '.')
return (0);
if(i >= 3)
return (0);
}
memcpy (dst, xp, sizeof(struct in_addr));
return (1);
} else if(af == AF_INET6) {
return (inet_pton (af, src, dst));
} else {
#ifndef NT
errno = EAFNOSUPPORT;
#endif /* NT */
return -1;
}
}
#endif
#define PATRICIA_MAX_THREADS 16
#if 0
/*
* convert prefix information to ascii string with length
* thread safe and (almost) re-entrant implementation
*/
static char * ndpi_prefix_toa2x (ndpi_prefix_t *prefix, char *buff, int with_len)
{
if(prefix == NULL)
return ((char*)"(Null)");
assert (prefix->ref_count >= 0);
if(buff == NULL) {
struct buffer {
char buffs[PATRICIA_MAX_THREADS][48+5];
u_int i;
} *buffp;
# if 0
THREAD_SPECIFIC_DATA (struct buffer, buffp, 1);
# else
{ /* for scope only */
static struct buffer local_buff;
buffp = &local_buff;
}
# endif
if(buffp == NULL) {
/* XXX should we report an error? */
return (NULL);
}
buff = buffp->buffs[buffp->i++%PATRICIA_MAX_THREADS];
}
if(prefix->family == AF_INET) {
u_char *a;
assert (prefix->bitlen <= sizeof(struct in_addr) * 8);
a = ndpi_prefix_touchar (prefix);
if(with_len) {
sprintf (buff, "%d.%d.%d.%d/%d", a[0], a[1], a[2], a[3],
prefix->bitlen);
}
else {
sprintf (buff, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]);
}
return (buff);
}
else if(prefix->family == AF_INET6) {
char *r;
r = (char *) inet_ntop (AF_INET6, &prefix->add.sin6, buff, 48 /* a guess value */ );
if(r && with_len) {
assert (prefix->bitlen <= sizeof(struct in6_addr) * 8);
sprintf (buff + strlen (buff), "/%d", prefix->bitlen);
}
return (buff);
}
else
return (NULL);
}
/* ndpi_prefix_toa2
* convert prefix information to ascii string
*/
static char * ndpi_prefix_toa2 (ndpi_prefix_t *prefix, char *buff)
{
return (ndpi_prefix_toa2x (prefix, buff, 0));
}
/* ndpi_prefix_toa
*/
static char * ndpi_prefix_toa (ndpi_prefix_t * prefix)
{
return (ndpi_prefix_toa2 (prefix, (char *) NULL));
}
#endif
static ndpi_prefix_t * ndpi_New_Prefix2 (int family, void *dest, int bitlen, ndpi_prefix_t *prefix)
{
int dynamic_allocated = 0;
int default_bitlen = sizeof(struct in_addr) * 8;
if(family == AF_INET6) {
default_bitlen = sizeof(struct in6_addr) * 8;
if(prefix == NULL) {
prefix = (ndpi_prefix_t*)ndpi_calloc(1, sizeof (ndpi_prefix_t));
dynamic_allocated++;
}
memcpy (&prefix->add.sin6, dest, sizeof(struct in6_addr));
}
else
if(family == AF_INET) {
if(prefix == NULL) {
#ifndef NT
prefix = (ndpi_prefix_t*)ndpi_calloc(1, sizeof (prefix4_t));
#else
//for some reason, compiler is getting
//prefix4_t size incorrect on NT
prefix = ndpi_calloc(1, sizeof (ndpi_prefix_t));
#endif /* NT */
dynamic_allocated++;
}
memcpy (&prefix->add.sin, dest, sizeof(struct in_addr));
}
else {
return (NULL);
}
prefix->bitlen = (u_int16_t)((bitlen >= 0) ? bitlen : default_bitlen);
prefix->family = (u_int16_t)family;
prefix->ref_count = 0;
if(dynamic_allocated) {
prefix->ref_count++;
}
/* fprintf(stderr, "[C %s, %d]\n", ndpi_prefix_toa (prefix), prefix->ref_count); */
return (prefix);
}
#if 0
static ndpi_prefix_t * ndpi_New_Prefix (int family, void *dest, int bitlen)
{
return (ndpi_New_Prefix2 (family, dest, bitlen, NULL));
}
#endif
static ndpi_prefix_t *
ndpi_Ref_Prefix (ndpi_prefix_t * prefix)
{
if(prefix == NULL)
return (NULL);
if(prefix->ref_count == 0) {
/* make a copy in case of a static prefix */
return (ndpi_New_Prefix2 (prefix->family, &prefix->add, prefix->bitlen, NULL));
}
prefix->ref_count++;
/* fprintf(stderr, "[A %s, %d]\n", ndpi_prefix_toa (prefix), prefix->ref_count); */
return (prefix);
}
static void
ndpi_Deref_Prefix (ndpi_prefix_t * prefix)
{
if(prefix == NULL)
return;
/* for secure programming, raise an assert. no static prefix can call this */
assert (prefix->ref_count > 0);
prefix->ref_count--;
assert (prefix->ref_count >= 0);
if(prefix->ref_count <= 0) {
ndpi_DeleteEntry (prefix);
return;
}
}
// #define PATRICIA_DEBUG 1
static int num_active_patricia = 0;
/* these routines support continuous mask only */
ndpi_patricia_tree_t *
ndpi_patricia_new (u_int16_t maxbits)
{
ndpi_patricia_tree_t *patricia = (ndpi_patricia_tree_t*)ndpi_calloc(1, sizeof *patricia);
patricia->maxbits = maxbits;
patricia->head = NULL;
patricia->num_active_node = 0;
assert((u_int16_t)maxbits <= PATRICIA_MAXBITS); /* XXX */
num_active_patricia++;
return (patricia);
}
/*
* if func is supplied, it will be called as func(node->data)
* before deleting the node
*/
void
ndpi_Clear_Patricia (ndpi_patricia_tree_t *patricia, ndpi_void_fn_t func)
{
assert (patricia);
if(patricia->head) {
ndpi_patricia_node_t *Xstack[PATRICIA_MAXBITS+1];
ndpi_patricia_node_t **Xsp = Xstack;
ndpi_patricia_node_t *Xrn = patricia->head;
while (Xrn) {
ndpi_patricia_node_t *l = Xrn->l;
ndpi_patricia_node_t *r = Xrn->r;
if(Xrn->prefix) {
ndpi_Deref_Prefix (Xrn->prefix);
if(Xrn->data && func)
func (Xrn->data);
}
else {
assert (Xrn->data == NULL);
}
ndpi_DeleteEntry (Xrn);
patricia->num_active_node--;
if(l) {
if(r) {
*Xsp++ = r;
}
Xrn = l;
} else if(r) {
Xrn = r;
} else if(Xsp != Xstack) {
Xrn = *(--Xsp);
} else {
Xrn = NULL;
}
}
}
assert (patricia->num_active_node == 0);
/* ndpi_DeleteEntry (patricia); */
}
void
ndpi_patricia_destroy (ndpi_patricia_tree_t *patricia, ndpi_void_fn_t func)
{
ndpi_Clear_Patricia (patricia, func);
ndpi_DeleteEntry (patricia);
num_active_patricia--;
}
/*
* if func is supplied, it will be called as func(node->prefix, node->data)
*/
void
ndpi_patricia_process (ndpi_patricia_tree_t *patricia, ndpi_void_fn2_t func)
{
ndpi_patricia_node_t *node;
assert (func);
PATRICIA_WALK (patricia->head, node) {
func (node->prefix, node->data);
} PATRICIA_WALK_END;
}
static size_t
ndpi_patricia_clone_walk(ndpi_patricia_node_t *node, ndpi_patricia_tree_t *dst)
{
ndpi_patricia_node_t *cloned_node;
size_t n = 0;
if(node->l) {
n += ndpi_patricia_clone_walk(node->l, dst);
}
if(node->prefix) {
cloned_node = ndpi_patricia_lookup(dst, node->prefix);
if(cloned_node) {
/* Note: this is not cloning clone referenced void * data / user_data */
memcpy(&cloned_node->value, &node->value, sizeof(cloned_node->value));
}
n++;
}
if(node->r) {
n += ndpi_patricia_clone_walk(node->r, dst);
}
return n;
}
ndpi_patricia_tree_t *
ndpi_patricia_clone (const ndpi_patricia_tree_t * const from)
{
if(!from) return (NULL);
ndpi_patricia_tree_t *patricia = ndpi_patricia_new(from->maxbits);
if(!patricia) return (NULL);
if(from->head)
ndpi_patricia_clone_walk(from->head, patricia);
return (patricia);
}
size_t
ndpi_patricia_walk_inorder(ndpi_patricia_node_t *node, ndpi_void_fn3_t func, void *data)
{
size_t n = 0;
assert(func);
if(node->l) {
n += ndpi_patricia_walk_inorder(node->l, func, data);
}
if(node->prefix) {
func(node, node->data, data);
n++;
}
if(node->r) {
n += ndpi_patricia_walk_inorder(node->r, func, data);
}
return n;
}
size_t
ndpi_patricia_walk_tree_inorder(ndpi_patricia_tree_t *patricia, ndpi_void_fn3_t func, void *data) {
if (patricia->head == NULL)
return 0;
return ndpi_patricia_walk_inorder(patricia->head, func, data);
}
ndpi_patricia_node_t *
ndpi_patricia_search_exact (ndpi_patricia_tree_t *patricia, ndpi_prefix_t *prefix)
{
ndpi_patricia_node_t *node;
u_char *addr;
u_int16_t bitlen;
assert (patricia);
assert (prefix);
assert (prefix->bitlen <= patricia->maxbits);
patricia->stats.n_search++;
if(patricia->head == NULL)
return (NULL);
node = patricia->head;
addr = ndpi_prefix_touchar (prefix);
bitlen = prefix->bitlen;
while (node->bit < bitlen) {
if(BIT_TEST (addr[node->bit >> 3], 0x80 >> (node->bit & 0x07))) {
#ifdef PATRICIA_DEBUG
if(node->prefix)
fprintf (stderr, "patricia_search_exact: take right %s/%d\n",
ndpi_prefix_toa (node->prefix), node->prefix->bitlen);
else
fprintf (stderr, "patricia_search_exact: take right at %u\n",
node->bit);
#endif /* PATRICIA_DEBUG */
node = node->r;
}
else {
#ifdef PATRICIA_DEBUG
if(node->prefix)
fprintf (stderr, "patricia_search_exact: take left %s/%d\n",
ndpi_prefix_toa (node->prefix), node->prefix->bitlen);
else
fprintf (stderr, "patricia_search_exact: take left at %u\n",
node->bit);
#endif /* PATRICIA_DEBUG */
node = node->l;
}
if(node == NULL)
return (NULL);
}
#ifdef PATRICIA_DEBUG
if(node->prefix)
fprintf (stderr, "patricia_search_exact: stop at %s/%d [node->bit: %u][bitlen: %u]\n",
ndpi_prefix_toa (node->prefix), node->prefix->bitlen, node->bit, bitlen);
else
fprintf (stderr, "patricia_search_exact: stop at %u\n", node->bit);
#endif /* PATRICIA_DEBUG */
if(node->bit > bitlen || node->prefix == NULL)
return (NULL);
assert (node->bit == bitlen);
assert (node->bit == node->prefix->bitlen);
if(ndpi_comp_with_mask (ndpi_prefix_tochar (node->prefix), ndpi_prefix_tochar (prefix),
bitlen)) {
#ifdef PATRICIA_DEBUG
fprintf (stderr, "patricia_search_exact: found %s/%d\n",
ndpi_prefix_toa (node->prefix), node->prefix->bitlen);
#endif /* PATRICIA_DEBUG */
patricia->stats.n_found++;
return (node);
}
return (NULL);
}
/* if inclusive != 0, "best" may be the given prefix itself */
ndpi_patricia_node_t *
ndpi_patricia_search_best2 (ndpi_patricia_tree_t *patricia, ndpi_prefix_t *prefix, int inclusive)
{
ndpi_patricia_node_t *node;
ndpi_patricia_node_t *stack[PATRICIA_MAXBITS + 1];
u_char *addr;
u_int16_t bitlen;
int cnt = 0;
assert (patricia);
assert (prefix);
assert (prefix->bitlen <= patricia->maxbits);
patricia->stats.n_search++;
if(patricia->head == NULL)
return (NULL);
node = patricia->head;
addr = ndpi_prefix_touchar (prefix);
bitlen = prefix->bitlen;
while (node->bit < bitlen) {
if(node->prefix) {
#ifdef PATRICIA_DEBUG
fprintf (stderr, "patricia_search_best: push %s/%d\n",
ndpi_prefix_toa (node->prefix), node->prefix->bitlen);
#endif /* PATRICIA_DEBUG */
stack[cnt++] = node;
}
if(BIT_TEST (addr[node->bit >> 3], 0x80 >> (node->bit & 0x07))) {
#ifdef PATRICIA_DEBUG
if(node->prefix)
fprintf (stderr, "patricia_search_best: take right %s/%d\n",
ndpi_prefix_toa (node->prefix), node->prefix->bitlen);
else
fprintf (stderr, "patricia_search_best: take right at %u\n",
node->bit);
#endif /* PATRICIA_DEBUG */
node = node->r;
} else {
#ifdef PATRICIA_DEBUG
if(node->prefix)
fprintf (stderr, "patricia_search_best: take left %s/%d\n",
ndpi_prefix_toa (node->prefix), node->prefix->bitlen);
else
fprintf (stderr, "patricia_search_best: take left at %u\n",
node->bit);
#endif /* PATRICIA_DEBUG */
node = node->l;
}
if(node == NULL)
break;
}
if(inclusive && node && node->prefix) {
#ifdef PATRICIA_DEBUG
fprintf (stderr, "patricia_search_best: found node %s/%d [searching %s/%d]\n",
ndpi_prefix_toa (node->prefix), node->prefix->bitlen,
ndpi_prefix_toa (prefix), prefix->bitlen);
#endif
stack[cnt++] = node;
}
#ifdef PATRICIA_DEBUG
if(node == NULL)
fprintf (stderr, "patricia_search_best: stop at null\n");
else if(node->prefix)
fprintf (stderr, "patricia_search_best: stop at %s/%d\n",
ndpi_prefix_toa (node->prefix), node->prefix->bitlen);
else
fprintf (stderr, "patricia_search_best: stop at %u\n", node->bit);
#endif /* PATRICIA_DEBUG */
if(cnt <= 0)
return (NULL);
while (--cnt >= 0) {
node = stack[cnt];
#ifdef PATRICIA_DEBUG
fprintf (stderr, "patricia_search_best: pop %s/%d\n",
ndpi_prefix_toa (node->prefix), node->prefix->bitlen);
#endif /* PATRICIA_DEBUG */
if(ndpi_comp_with_mask (ndpi_prefix_tochar (node->prefix),
ndpi_prefix_tochar (prefix),
node->prefix->bitlen) && node->prefix->bitlen <= bitlen) {
#ifdef PATRICIA_DEBUG
fprintf (stderr, "patricia_search_best: found %s/%d\n",
ndpi_prefix_toa (node->prefix), node->prefix->bitlen);
#endif /* PATRICIA_DEBUG */
patricia->stats.n_found++;
return (node);
}
}
return (NULL);
}
ndpi_patricia_node_t *
ndpi_patricia_search_best (ndpi_patricia_tree_t *patricia, ndpi_prefix_t *prefix)
{
return (ndpi_patricia_search_best2 (patricia, prefix, 1));
}
ndpi_patricia_node_t *
ndpi_patricia_lookup (ndpi_patricia_tree_t *patricia, ndpi_prefix_t *prefix)
{
ndpi_patricia_node_t *node, *new_node, *parent, *glue;
u_char *addr, *test_addr;
u_int16_t bitlen, check_bit, differ_bit;
int i, j;
#ifdef PATRICIA_DEBUG
fprintf (stderr, "patricia_lookup() %s/%d (head)\n",
ndpi_prefix_toa (prefix), prefix->bitlen);
#endif /* PATRICIA_DEBUG */
assert (patricia);
assert (prefix);
assert (prefix->bitlen <= patricia->maxbits);
if(patricia->head == NULL) {
node = (ndpi_patricia_node_t*)ndpi_calloc(1, sizeof *node);
node->bit = prefix->bitlen;
node->prefix = ndpi_Ref_Prefix (prefix);
node->parent = NULL;
node->l = node->r = NULL;
node->data = NULL;
patricia->head = node;
#ifdef PATRICIA_DEBUG
fprintf (stderr, "patricia_lookup: new_node #0 %s/%d (head)\n",
ndpi_prefix_toa (prefix), prefix->bitlen);
#endif /* PATRICIA_DEBUG */
patricia->num_active_node++;
return (node);
}
addr = ndpi_prefix_touchar (prefix);
bitlen = prefix->bitlen;
node = patricia->head;
while (node->bit < bitlen || node->prefix == NULL) {
if(node->bit < patricia->maxbits &&
BIT_TEST (addr[node->bit >> 3], 0x80 >> (node->bit & 0x07))) {
if(node->r == NULL)
break;
#ifdef PATRICIA_DEBUG
if(node->prefix)
fprintf (stderr, "patricia_lookup: take right %s/%d\n",
ndpi_prefix_toa (node->prefix), node->prefix->bitlen);
else
fprintf (stderr, "patricia_lookup: take right at %u\n", node->bit);
#endif /* PATRICIA_DEBUG */
node = node->r;
}
else {
if(node->l == NULL)
break;
#ifdef PATRICIA_DEBUG
if(node->prefix)
fprintf (stderr, "patricia_lookup: take left %s/%d\n",
ndpi_prefix_toa (node->prefix), node->prefix->bitlen);
else
fprintf (stderr, "patricia_lookup: take left at %u\n", node->bit);
#endif /* PATRICIA_DEBUG */
node = node->l;
}
assert (node);
}
assert (node->prefix);
#ifdef PATRICIA_DEBUG
fprintf (stderr, "patricia_lookup: stop at %s/%d\n",
ndpi_prefix_toa (node->prefix), node->prefix->bitlen);
#endif /* PATRICIA_DEBUG */
test_addr = ndpi_prefix_touchar (node->prefix);
/* find the first bit different */
check_bit = (node->bit < bitlen)? node->bit: bitlen;
differ_bit = 0;
for (i = 0; (u_int)i*8 < check_bit; i++) {
int r;
if((r = (addr[i] ^ test_addr[i])) == 0) {
differ_bit = (i + 1) * 8;
continue;
}
/* I know the better way, but for now */
for (j = 0; j < 8; j++) {
if(BIT_TEST (r, (0x80 >> j)))
break;
}
/* must be found */
assert (j < 8);
differ_bit = i * 8 + j;
break;
}
if(differ_bit > check_bit)
differ_bit = check_bit;
#ifdef PATRICIA_DEBUG
fprintf (stderr, "patricia_lookup: differ_bit %d\n", differ_bit);
#endif /* PATRICIA_DEBUG */
parent = node->parent;
while (parent && parent->bit >= differ_bit) {
node = parent;
parent = node->parent;
#ifdef PATRICIA_DEBUG
if(node->prefix)
fprintf (stderr, "patricia_lookup: up to %s/%d\n",
ndpi_prefix_toa (node->prefix), node->prefix->bitlen);
else
fprintf (stderr, "patricia_lookup: up to %u\n", node->bit);
#endif /* PATRICIA_DEBUG */
}
if(differ_bit == bitlen && node->bit == bitlen) {
if(node->prefix) {
#ifdef PATRICIA_DEBUG
fprintf (stderr, "patricia_lookup: found %s/%d\n",
ndpi_prefix_toa (node->prefix), node->prefix->bitlen);
#endif /* PATRICIA_DEBUG */
return (node);
}
node->prefix = ndpi_Ref_Prefix (prefix);
#ifdef PATRICIA_DEBUG
fprintf (stderr, "patricia_lookup: new node #1 %s/%d (glue mod)\n",
ndpi_prefix_toa (prefix), prefix->bitlen);
#endif /* PATRICIA_DEBUG */
assert (node->data == NULL);
return (node);
}
new_node = (ndpi_patricia_node_t*)ndpi_calloc(1, sizeof *new_node);
if(!new_node) return NULL;
new_node->bit = prefix->bitlen;
new_node->prefix = ndpi_Ref_Prefix (prefix);
new_node->parent = NULL;
new_node->l = new_node->r = NULL;
new_node->data = NULL;
patricia->num_active_node++;
if(node->bit == differ_bit) {
new_node->parent = node;
if(node->bit < patricia->maxbits &&
BIT_TEST (addr[node->bit >> 3], 0x80 >> (node->bit & 0x07))) {
assert (node->r == NULL);
node->r = new_node;
}
else {
assert (node->l == NULL);
node->l = new_node;
}
#ifdef PATRICIA_DEBUG
fprintf (stderr, "patricia_lookup: new_node #2 %s/%d (child)\n",
ndpi_prefix_toa (prefix), prefix->bitlen);
#endif /* PATRICIA_DEBUG */
return (new_node);
}
if(bitlen == differ_bit) {
if(bitlen < patricia->maxbits &&
BIT_TEST (test_addr[bitlen >> 3], 0x80 >> (bitlen & 0x07))) {
new_node->r = node;
}
else {
new_node->l = node;
}
new_node->parent = node->parent;
if(node->parent == NULL) {
assert (patricia->head == node);
patricia->head = new_node;
}
else if(node->parent->r == node) {
node->parent->r = new_node;
}
else {
node->parent->l = new_node;
}
node->parent = new_node;
#ifdef PATRICIA_DEBUG
fprintf (stderr, "patricia_lookup: new_node #3 %s/%d (parent)\n",
ndpi_prefix_toa (prefix), prefix->bitlen);
#endif /* PATRICIA_DEBUG */
}
else {
glue = (ndpi_patricia_node_t*)ndpi_calloc(1, sizeof *glue);
if(!glue) return(NULL);
glue->bit = differ_bit;
glue->prefix = NULL;
glue->parent = node->parent;
glue->data = NULL;
patricia->num_active_node++;
if(differ_bit < patricia->maxbits &&
BIT_TEST (addr[differ_bit >> 3], 0x80 >> (differ_bit & 0x07))) {
glue->r = new_node;
glue->l = node;
}
else {
glue->r = node;
glue->l = new_node;
}
new_node->parent = glue;
if(node->parent == NULL) {
assert (patricia->head == node);
patricia->head = glue;
}
else if(node->parent->r == node) {
node->parent->r = glue;
}
else {
node->parent->l = glue;
}
node->parent = glue;
#ifdef PATRICIA_DEBUG
fprintf (stderr, "patricia_lookup: new_node #4 %s/%d (glue+node)\n",
ndpi_prefix_toa (prefix), prefix->bitlen);
#endif /* PATRICIA_DEBUG */
}
return (new_node);
}
void
ndpi_patricia_remove (ndpi_patricia_tree_t *patricia, ndpi_patricia_node_t *node)
{
ndpi_patricia_node_t *parent, *child;
assert (patricia);
assert (node);
if(node->r && node->l) {
#ifdef PATRICIA_DEBUG
fprintf (stderr, "patricia_remove: #0 %s/%d (r & l)\n",
ndpi_prefix_toa (node->prefix), node->prefix->bitlen);
#endif /* PATRICIA_DEBUG */
/* this might be a placeholder node -- have to check and make sure
* there is a prefix associated with it ! */
if(node->prefix != NULL)
ndpi_Deref_Prefix (node->prefix);
node->prefix = NULL;
/* Also I needed to clear data pointer -- masaki */
node->data = NULL;
return;
}
if(node->r == NULL && node->l == NULL) {
#ifdef PATRICIA_DEBUG
fprintf (stderr, "patricia_remove: #1 %s/%d (!r & !l)\n",
ndpi_prefix_toa (node->prefix), node->prefix->bitlen);
#endif /* PATRICIA_DEBUG */
parent = node->parent;
ndpi_Deref_Prefix (node->prefix);
ndpi_DeleteEntry (node);
patricia->num_active_node--;
if(parent == NULL) {
assert (patricia->head == node);
patricia->head = NULL;
return;
}
if(parent->r == node) {
parent->r = NULL;
child = parent->l;
}
else {
assert (parent->l == node);
parent->l = NULL;
child = parent->r;
}
if(parent->prefix)
return;
/* we need to remove parent too */
if(parent->parent == NULL) {
assert (patricia->head == parent);
patricia->head = child;
}
else if(parent->parent->r == parent) {
parent->parent->r = child;
}
else {
assert (parent->parent->l == parent);
parent->parent->l = child;
}
child->parent = parent->parent;
ndpi_DeleteEntry (parent);
patricia->num_active_node--;
return;
}
#ifdef PATRICIA_DEBUG
fprintf (stderr, "patricia_remove: #2 %s/%d (r ^ l)\n",
ndpi_prefix_toa (node->prefix), node->prefix->bitlen);
#endif /* PATRICIA_DEBUG */
if(node->r) {
child = node->r;
}
else {
assert (node->l);
child = node->l;
}
parent = node->parent;
child->parent = parent;
ndpi_Deref_Prefix (node->prefix);
ndpi_DeleteEntry (node);
patricia->num_active_node--;
if(parent == NULL) {
assert (patricia->head == node);
patricia->head = child;
return;
}
if(parent->r == node) {
parent->r = child;
}
else {
assert (parent->l == node);
parent->l = child;
}
}
/* { from demo.c */
#if 0
/* ndpi_ascii2prefix */
static ndpi_prefix_t * ndpi_ascii2prefix (int family, char *string)
{
long bitlen;
long maxbitlen = 0;
char *cp;
struct in_addr sin;
struct in6_addr sin6;
char save[MAXLINE];
if(string == NULL)
return (NULL);
/* easy way to handle both families */
if(family == 0) {
family = AF_INET;
if(strchr (string, ':')) family = AF_INET6;
}
if(family == AF_INET) {
maxbitlen = sizeof(struct in_addr) * 8;
}
else if(family == AF_INET6) {
maxbitlen = sizeof(struct in6_addr) * 8;
}
if((cp = strchr (string, '/')) != NULL) {
bitlen = atol (cp + 1);
/* *cp = '\0'; */
/* copy the string to save. Avoid destroying the string */
assert (cp - string < MAXLINE);
memcpy (save, string, cp - string);
save[cp - string] = '\0';
string = save;
if((bitlen < 0) || (bitlen > maxbitlen))
bitlen = maxbitlen;
} else {
bitlen = maxbitlen;
}
if(family == AF_INET) {
if(ndpi_my_inet_pton (AF_INET, string, &sin) <= 0)
return (NULL);
return (ndpi_New_Prefix (AF_INET, &sin, bitlen));
}
else if(family == AF_INET6) {
// Get rid of this with next IPv6 upgrade
#if defined(NT) && !defined(HAVE_INET_NTOP)
inet6_addr(string, &sin6);
return (ndpi_New_Prefix (AF_INET6, &sin6, bitlen));
#else
if(inet_pton (AF_INET6, string, &sin6) <= 0)
return (NULL);
#endif /* NT */
return (ndpi_New_Prefix (AF_INET6, &sin6, bitlen));
}
else
return (NULL);
}
ndpi_patricia_node_t *
ndpi_make_and_lookup (ndpi_patricia_tree_t *tree, char *string)
{
ndpi_prefix_t *prefix;
ndpi_patricia_node_t *node;
prefix = ndpi_ascii2prefix (AF_INET, string);
printf ("make_and_lookup: %s/%d\n", ndpi_prefix_toa (prefix), prefix->bitlen);
node = ndpi_patricia_lookup (tree, prefix);
ndpi_Deref_Prefix (prefix);
return (node);
}
ndpi_patricia_node_t *
ndpi_try_search_exact (ndpi_patricia_tree_t *tree, char *string)
{
ndpi_prefix_t *prefix;
ndpi_patricia_node_t *node;
prefix = ndpi_ascii2prefix (AF_INET, string);
printf ("try_search_exact: %s/%d\n", ndpi_prefix_toa (prefix), prefix->bitlen);
if((node = patricia_search_exact (tree, prefix)) == NULL) {
printf ("try_search_exact: not found\n");
}
else {
printf ("try_search_exact: %s/%d found\n",
ndpi_prefix_toa (node->prefix), node->prefix->bitlen);
}
ndpi_Deref_Prefix (prefix);
return (node);
}
void
ndpi_lookup_then_remove (ndpi_patricia_tree_t *tree, char *string)
{
ndpi_patricia_node_t *node;
if((node = try_search_exact (tree, string)))
patricia_remove (tree, node);
}
#endif
| lgpl-3.0 |
mohseniaref/six-library | externals/nitro/modules/java/nitf/src/jni/source/nitf_FileSecurity.c | 3 | 6483 | /* =========================================================================
* This file is part of NITRO
* =========================================================================
*
* (C) Copyright 2004 - 2014, MDA Information Systems LLC
*
* NITRO is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, If not,
* see <http://www.gnu.org/licenses/>.
*
*/
#include <import/nitf.h>
#include "nitf_FileSecurity.h"
#include "nitf_JNI.h"
NITF_JNI_DECLARE_OBJ(nitf_FileSecurity)
/*
* Class: nitf_FileSecurity
* Method: getClassificationAuthority
* Signature: ()Lnitf/Field;
*/
JNIEXPORT jobject JNICALL Java_nitf_FileSecurity_getClassificationAuthority
(JNIEnv * env, jobject self)
{
nitf_FileSecurity *info = _GetObj(env, self);
return _GetFieldObj(env, info->classificationAuthority);
}
/*
* Class: nitf_FileSecurity
* Method: getClassificationAuthorityType
* Signature: ()Lnitf/Field;
*/
JNIEXPORT jobject JNICALL
Java_nitf_FileSecurity_getClassificationAuthorityType(JNIEnv * env,
jobject self)
{
nitf_FileSecurity *info = _GetObj(env, self);
return _GetFieldObj(env, info->classificationAuthorityType);
}
/*
* Class: nitf_FileSecurity
* Method: getClassificationReason
* Signature: ()Lnitf/Field;
*/
JNIEXPORT jobject JNICALL Java_nitf_FileSecurity_getClassificationReason
(JNIEnv * env, jobject self)
{
nitf_FileSecurity *info = _GetObj(env, self);
return _GetFieldObj(env, info->classificationReason);
}
/*
* Class: nitf_FileSecurity
* Method: getClassificationSystem
* Signature: ()Lnitf/Field;
*/
JNIEXPORT jobject JNICALL Java_nitf_FileSecurity_getClassificationSystem
(JNIEnv * env, jobject self)
{
nitf_FileSecurity *info = _GetObj(env, self);
return _GetFieldObj(env, info->classificationSystem);
}
/*
* Class: nitf_FileSecurity
* Method: getClassificationText
* Signature: ()Lnitf/Field;
*/
JNIEXPORT jobject JNICALL Java_nitf_FileSecurity_getClassificationText
(JNIEnv * env, jobject self)
{
nitf_FileSecurity *info = _GetObj(env, self);
return _GetFieldObj(env, info->classificationText);
}
/*
* Class: nitf_FileSecurity
* Method: getCodewords
* Signature: ()Lnitf/Field;
*/
JNIEXPORT jobject JNICALL Java_nitf_FileSecurity_getCodewords
(JNIEnv * env, jobject self)
{
nitf_FileSecurity *info = _GetObj(env, self);
return _GetFieldObj(env, info->codewords);
}
/*
* Class: nitf_FileSecurity
* Method: getControlAndHandling
* Signature: ()Lnitf/Field;
*/
JNIEXPORT jobject JNICALL Java_nitf_FileSecurity_getControlAndHandling
(JNIEnv * env, jobject self)
{
nitf_FileSecurity *info = _GetObj(env, self);
return _GetFieldObj(env, info->controlAndHandling);
}
/*
* Class: nitf_FileSecurity
* Method: getDeclassificationDate
* Signature: ()Lnitf/Field;
*/
JNIEXPORT jobject JNICALL Java_nitf_FileSecurity_getDeclassificationDate
(JNIEnv * env, jobject self)
{
nitf_FileSecurity *info = _GetObj(env, self);
return _GetFieldObj(env, info->declassificationDate);
}
/*
* Class: nitf_FileSecurity
* Method: getDeclassificationExemption
* Signature: ()Lnitf/Field;
*/
JNIEXPORT jobject JNICALL
Java_nitf_FileSecurity_getDeclassificationExemption(JNIEnv * env,
jobject self)
{
nitf_FileSecurity *info = _GetObj(env, self);
return _GetFieldObj(env, info->declassificationExemption);
}
/*
* Class: nitf_FileSecurity
* Method: getDeclassificationType
* Signature: ()Lnitf/Field;
*/
JNIEXPORT jobject JNICALL Java_nitf_FileSecurity_getDeclassificationType
(JNIEnv * env, jobject self)
{
nitf_FileSecurity *info = _GetObj(env, self);
return _GetFieldObj(env, info->declassificationType);
}
/*
* Class: nitf_FileSecurity
* Method: getDowngrade
* Signature: ()Lnitf/Field;
*/
JNIEXPORT jobject JNICALL Java_nitf_FileSecurity_getDowngrade
(JNIEnv * env, jobject self)
{
nitf_FileSecurity *info = _GetObj(env, self);
return _GetFieldObj(env, info->downgrade);
}
/*
* Class: nitf_FileSecurity
* Method: getDowngradeDateTime
* Signature: ()Lnitf/Field;
*/
JNIEXPORT jobject JNICALL Java_nitf_FileSecurity_getDowngradeDateTime
(JNIEnv * env, jobject self)
{
nitf_FileSecurity *info = _GetObj(env, self);
return _GetFieldObj(env, info->downgradeDateTime);
}
/*
* Class: nitf_FileSecurity
* Method: getReleasingInstructions
* Signature: ()Lnitf/Field;
*/
JNIEXPORT jobject JNICALL Java_nitf_FileSecurity_getReleasingInstructions
(JNIEnv * env, jobject self)
{
nitf_FileSecurity *info = _GetObj(env, self);
return _GetFieldObj(env, info->releasingInstructions);
}
/*
* Class: nitf_FileSecurity
* Method: getSecurityControlNumber
* Signature: ()Lnitf/Field;
*/
JNIEXPORT jobject JNICALL Java_nitf_FileSecurity_getSecurityControlNumber
(JNIEnv * env, jobject self)
{
nitf_FileSecurity *info = _GetObj(env, self);
return _GetFieldObj(env, info->securityControlNumber);
}
/*
* Class: nitf_FileSecurity
* Method: getSecuritySourceDate
* Signature: ()Lnitf/Field;
*/
JNIEXPORT jobject JNICALL Java_nitf_FileSecurity_getSecuritySourceDate
(JNIEnv * env, jobject self)
{
nitf_FileSecurity *info = _GetObj(env, self);
return _GetFieldObj(env, info->securitySourceDate);
}
/*
* Class: nitf_FileSecurity
* Method: resizeForVersion
* Signature: (Lnitf/Version;)V
*/
JNIEXPORT void JNICALL Java_nitf_FileSecurity_resizeForVersion
(JNIEnv *env, jobject self, jobject versionObject)
{
nitf_FileSecurity *info = _GetObj(env, self);
nitf_Version version = _GetNITFVersion(env, versionObject);
nitf_Error error;
if (!nitf_FileSecurity_resizeForVersion(info, version, &error))
_ThrowNITFException(env, error.message);
}
| lgpl-3.0 |
mgigante/nDPI | src/lib/protocols/drda.c | 4 | 2869 | /*
* drda.c
*
* Copyright (C) 2012-16 - ntop.org
*
* This module is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This module is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License.
* If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "ndpi_api.h"
#ifdef NDPI_PROTOCOL_DRDA
struct ndpi_drda_hdr {
u_int16_t length;
u_int8_t magic;
u_int8_t format;
u_int16_t correlID;
u_int16_t length2;
u_int16_t code_pnt;
};
void ndpi_search_drda(struct ndpi_detection_module_struct *ndpi_struct,
struct ndpi_flow_struct *flow)
{
struct ndpi_packet_struct * packet = &flow->packet;
u_int16_t payload_len = packet->payload_packet_len;
u_int count = 0; // prevent integer overflow
if(packet->tcp != NULL) {
/* check port */
if(payload_len >= sizeof(struct ndpi_drda_hdr)) {
struct ndpi_drda_hdr * drda = (struct ndpi_drda_hdr *) packet->payload;
u_int16_t len = ntohs(drda->length);
/* check first header */
if(len != ntohs(drda->length2) + 6 ||
drda->magic != 0xd0)
goto no_drda;
/* check if there are more drda headers */
if(payload_len > len) {
count = len;
while(count + sizeof(struct ndpi_drda_hdr) < payload_len)
{
/* update info */
drda = (struct ndpi_drda_hdr *)(packet->payload + count);
len = ntohs(drda->length);
if(len != ntohs(drda->length2) + 6 ||
drda->magic != 0xd0)
goto no_drda;
count += len;
}
if(count != payload_len) goto no_drda;
}
NDPI_LOG(NDPI_PROTOCOL_DRDA, ndpi_struct, NDPI_LOG_DEBUG, "found DRDA.\n");
ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_DRDA, NDPI_PROTOCOL_UNKNOWN);
return;
}
}
no_drda:
NDPI_LOG(NDPI_PROTOCOL_DRDA, ndpi_struct, NDPI_LOG_DEBUG, "exclude DRDA.\n");
NDPI_ADD_PROTOCOL_TO_BITMASK(flow->excluded_protocol_bitmask, NDPI_PROTOCOL_DRDA);
}
/* ***************************************************************** */
void init_drda_dissector(struct ndpi_detection_module_struct *ndpi_struct, u_int32_t *id,
NDPI_PROTOCOL_BITMASK *detection_bitmask)
{
ndpi_set_bitmask_protocol_detection("DRDA", ndpi_struct, detection_bitmask, *id,
NDPI_PROTOCOL_DRDA,
ndpi_search_drda,
NDPI_SELECTION_BITMASK_PROTOCOL_TCP_WITH_PAYLOAD,
SAVE_DETECTION_BITMASK_AS_UNKNOWN,
ADD_TO_DETECTION_BITMASK);
*id += 1;
}
#endif /* NDPI_PROTOCOL_DRDA */
| lgpl-3.0 |
SilviaAmAm/plumed2 | src/adjmat/ContactAlignedMatrix.cpp | 4 | 3617 | /* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Copyright (c) 2015,2016 The plumed team
(see the PEOPLE file at the root of the distribution for a list of names)
See http://www.plumed.org for more information.
This file is part of plumed, version 2.
plumed is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
plumed is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with plumed. If not, see <http://www.gnu.org/licenses/>.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
#include "AlignedMatrixBase.h"
#include "core/ActionRegister.h"
#include "tools/Matrix.h"
//+PLUMEDOC MATRIX ALIGNED_MATRIX
/*
Adjacency matrix in which two molecule are adjacent if they are within a certain cutoff and if they have the same orientation.
\par Examples
*/
//+ENDPLUMEDOC
namespace PLMD {
namespace adjmat {
class ContactAlignedMatrix : public AlignedMatrixBase {
private:
Matrix<SwitchingFunction> sf;
public:
///
static void registerKeywords( Keywords& keys );
///
explicit ContactAlignedMatrix(const ActionOptions&);
void readOrientationConnector( const unsigned& i, const unsigned& j, const std::vector<std::string>& desc );
double computeVectorFunction( const unsigned& iv, const unsigned& jv,
const Vector& conn, const std::vector<double>& vec1, const std::vector<double>& vec2,
Vector& dconn, std::vector<double>& dvec1, std::vector<double>& dvec2 ) const ;
};
PLUMED_REGISTER_ACTION(ContactAlignedMatrix,"ALIGNED_MATRIX")
void ContactAlignedMatrix::registerKeywords( Keywords& keys ){
AlignedMatrixBase::registerKeywords( keys );
keys.add("numbered","ORIENTATION_SWITCH","A switching function that transforms the dot product of the input vectors.");
}
ContactAlignedMatrix::ContactAlignedMatrix( const ActionOptions& ao ):
Action(ao),
AlignedMatrixBase(ao)
{
unsigned nrows, ncols, ig; retrieveTypeDimensions( nrows, ncols, ig );
sf.resize( nrows, ncols );
parseConnectionDescriptions("ORIENTATION_SWITCH",false,0);
}
void ContactAlignedMatrix::readOrientationConnector( const unsigned& i, const unsigned& j, const std::vector<std::string>& desc ){
plumed_assert( desc.size()==1 ); std::string errors; sf(j,i).set(desc[0],errors);
if( j!=i ) sf(i,j).set(desc[0],errors);
log.printf(" vectors in %u th and %u th groups must have a dot product that is greater than %s \n",i+1,j+1,(sf(i,j).description()).c_str() );
}
double ContactAlignedMatrix::computeVectorFunction( const unsigned& iv, const unsigned& jv,
const Vector& conn, const std::vector<double>& vec1, const std::vector<double>& vec2,
Vector& dconn, std::vector<double>& dvec1, std::vector<double>& dvec2 ) const {
double dot_df, dot=0; dconn.zero();
for(unsigned k=2;k<vec1.size();++k) dot+=vec1[k]*vec2[k];
double f_dot = sf(iv,jv).calculate( dot, dot_df );
for(unsigned k=2;k<vec1.size();++k){ dvec1[k]=dot_df*vec2[k]; dvec2[k]=dot_df*vec1[k]; }
return f_dot;
}
}
}
| lgpl-3.0 |
universsky/diddler-master | jni/winpcap_send_queue.cpp | 4 | 5516 | /***************************************************************************
* Copyright (C) 2007, Sly Technologies, Inc *
* Distributed under the Lesser GNU Public License (LGPL) *
***************************************************************************/
/*
* Utility file that provides various conversion methods for chaging objects
* back and forth between C and Java JNI.
*/
#include <stdio.h>
#include <stdlib.h>
#include <pcap.h>
#include <jni.h>
#ifndef WIN32
#include <errno.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <unistd.h>
#else
#include <Win32-Extensions.h>
#endif /*WIN32*/
#include "nio_jmemory.h"
#include "packet_jscanner.h"
#include "jnetpcap_utils.h"
#include "org_jnetpcap_winpcap_WinPcapSendQueue.h"
#include "export.h"
/****************************************************************
* **************************************************************
*
* Java declared native functions
*
* **************************************************************
****************************************************************/
/*
* Class: org_jnetpcap_winpcap_WinPcapSendQueue
* Method: sizeof
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_org_jnetpcap_winpcap_WinPcapSendQueue_sizeof(
JNIEnv *env, jclass clazz) {
#ifdef WIN32
return (jint) sizeof(pcap_send_queue);
#else
throwException(env, PCAP_EXTENSION_NOT_AVAILABLE_EXCEPTION, NULL);
return -1;
#endif
}
/*
* Class: org_jnetpcap_winpcap_WinPcapSendQueue
* Method: getLen
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_org_jnetpcap_winpcap_WinPcapSendQueue_getLen(
JNIEnv *env, jobject obj) {
#ifdef WIN32
pcap_send_queue *q = (pcap_send_queue *)getJMemoryPhysical(env, obj);
if (q == NULL) {
throwException(env, NULL_PTR_EXCEPTION, "pcap_send_queue NULL");
return -1;
}
return (jint) q->len;
#else
throwException(env, PCAP_EXTENSION_NOT_AVAILABLE_EXCEPTION, NULL);
return -1;
#endif
}
/*
* Class: org_jnetpcap_winpcap_WinPcapSendQueue
* Method: getMaxLen
* Signature: ()I
*/
JNIEXPORT jint JNICALL Java_org_jnetpcap_winpcap_WinPcapSendQueue_getMaxLen(
JNIEnv *env, jobject obj) {
#ifdef WIN32
pcap_send_queue *q = (pcap_send_queue *)getJMemoryPhysical(env, obj);
if (q == NULL) {
throwException(env, NULL_PTR_EXCEPTION, "pcap_send_queue NULL");
return -1;
}
return (jint) q->maxlen;
#else
throwException(env, PCAP_EXTENSION_NOT_AVAILABLE_EXCEPTION, NULL);
return -1;
#endif
}
/*
* Class: org_jnetpcap_winpcap_WinPcapSendQueue
* Method: incLen
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_org_jnetpcap_winpcap_WinPcapSendQueue_incLen(
JNIEnv *env, jobject obj, jint jdelta) {
#ifdef WIN32
pcap_send_queue *q = (pcap_send_queue *)getJMemoryPhysical(env, obj);
if (q == NULL) {
throwException(env, NULL_PTR_EXCEPTION, "pcap_send_queue NULL");
return -1;
}
q->len += (int) jdelta;
return (jint) q->len;
#else
throwException(env, PCAP_EXTENSION_NOT_AVAILABLE_EXCEPTION, NULL);
return -1;
#endif
}
/*
* Class: org_jnetpcap_winpcap_WinPcapSendQueue
* Method: setBuffer
* Signature: (Lorg/jnetpcap/nio/JBuffer;)V
*/
JNIEXPORT void JNICALL Java_org_jnetpcap_winpcap_WinPcapSendQueue_setBuffer
(JNIEnv *env, jobject obj, jobject jbuf) {
#ifdef WIN32
pcap_send_queue *q = (pcap_send_queue *)getJMemoryPhysical(env, obj);
if (q == NULL) {
throwException(env, NULL_PTR_EXCEPTION, "pcap_send_queue NULL");
return;
}
q->buffer = (char *)getJMemoryPhysical(env, jbuf);
#else
throwException(env, PCAP_EXTENSION_NOT_AVAILABLE_EXCEPTION, NULL);
return;
#endif
}
/*
* Class: org_jnetpcap_winpcap_WinPcapSendQueue
* Method: setLen
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_org_jnetpcap_winpcap_WinPcapSendQueue_setLen
(JNIEnv *env, jobject obj, jint jlen) {
#ifdef WIN32
pcap_send_queue *q = (pcap_send_queue *)getJMemoryPhysical(env, obj);
if (q == NULL) {
throwException(env, NULL_PTR_EXCEPTION, "pcap_send_queue NULL");
return;
}
q->len = (int) jlen;
#else
throwException(env, PCAP_EXTENSION_NOT_AVAILABLE_EXCEPTION, NULL);
return;
#endif
}
/*
* Class: org_jnetpcap_winpcap_WinPcapSendQueue
* Method: setMaxLen
* Signature: (I)V
*/
JNIEXPORT void JNICALL Java_org_jnetpcap_winpcap_WinPcapSendQueue_setMaxLen
(JNIEnv *env, jobject obj, jint jmaxlen) {
#ifdef WIN32
pcap_send_queue *q = (pcap_send_queue *)getJMemoryPhysical(env, obj);
if (q == NULL) {
throwException(env, NULL_PTR_EXCEPTION, "pcap_send_queue NULL");
return;
}
q->maxlen = (int) jmaxlen;
#else
throwException(env, PCAP_EXTENSION_NOT_AVAILABLE_EXCEPTION, NULL);
return;
#endif
}
/*
* Class: org_jnetpcap_winpcap_WinPcapSendQueue
* Method: toDebugString
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_org_jnetpcap_winpcap_WinPcapSendQueue_toDebugString(
JNIEnv *env, jobject obj) {
#ifdef WIN32
pcap_send_queue *q = (pcap_send_queue *)getJMemoryPhysical(env, obj);
if (q == NULL) {
throwException(env, NULL_PTR_EXCEPTION, "pcap_send_queue NULL");
return NULL;
}
char buf[8 * 1024];
buf[0] = '\0';
sprintf(buf,
"WinPcapSendQueue: maxlen=%d\n"
"WinPcapSendQueue: len=%d\n"
"WinPcapSendQueue: buffer=@%p\n",
q->maxlen,
q->len,
q->buffer);
return env->NewStringUTF(buf);
#else
throwException(env, PCAP_EXTENSION_NOT_AVAILABLE_EXCEPTION, NULL);
return NULL;
#endif
}
| lgpl-3.0 |
ssangkong/NVRAM_KWU | qt-everywhere-opensource-src-4.7.4/doc/src/snippets/qmake/paintwidget_win.cpp | 14 | 2047 | /****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
** the names of its contributors may be used to endorse or promote
** products derived from this software without specific prior written
** permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
** $QT_END_LICENSE$
**
****************************************************************************/
| lgpl-3.0 |
DocCreator/DocCreator | software/DocCreator/src/Degradations/Distortion3DModel/thirdparty/eigen-3.3.7/bench/spmv.cpp | 283 | 6096 |
//g++-4.4 -DNOMTL -Wl,-rpath /usr/local/lib/oski -L /usr/local/lib/oski/ -l oski -l oski_util -l oski_util_Tid -DOSKI -I ~/Coding/LinearAlgebra/mtl4/ spmv.cpp -I .. -O2 -DNDEBUG -lrt -lm -l oski_mat_CSC_Tid -loskilt && ./a.out r200000 c200000 n100 t1 p1
#define SCALAR double
#include <iostream>
#include <algorithm>
#include "BenchTimer.h"
#include "BenchSparseUtil.h"
#define SPMV_BENCH(CODE) BENCH(t,tries,repeats,CODE);
// #ifdef MKL
//
// #include "mkl_types.h"
// #include "mkl_spblas.h"
//
// template<typename Lhs,typename Rhs,typename Res>
// void mkl_multiply(const Lhs& lhs, const Rhs& rhs, Res& res)
// {
// char n = 'N';
// float alpha = 1;
// char matdescra[6];
// matdescra[0] = 'G';
// matdescra[1] = 0;
// matdescra[2] = 0;
// matdescra[3] = 'C';
// mkl_scscmm(&n, lhs.rows(), rhs.cols(), lhs.cols(), &alpha, matdescra,
// lhs._valuePtr(), lhs._innerIndexPtr(), lhs.outerIndexPtr(),
// pntre, b, &ldb, &beta, c, &ldc);
// // mkl_somatcopy('C', 'T', lhs.rows(), lhs.cols(), 1,
// // lhs._valuePtr(), lhs.rows(), DST, dst_stride);
// }
//
// #endif
int main(int argc, char *argv[])
{
int size = 10000;
int rows = size;
int cols = size;
int nnzPerCol = 40;
int tries = 2;
int repeats = 2;
bool need_help = false;
for(int i = 1; i < argc; i++)
{
if(argv[i][0] == 'r')
{
rows = atoi(argv[i]+1);
}
else if(argv[i][0] == 'c')
{
cols = atoi(argv[i]+1);
}
else if(argv[i][0] == 'n')
{
nnzPerCol = atoi(argv[i]+1);
}
else if(argv[i][0] == 't')
{
tries = atoi(argv[i]+1);
}
else if(argv[i][0] == 'p')
{
repeats = atoi(argv[i]+1);
}
else
{
need_help = true;
}
}
if(need_help)
{
std::cout << argv[0] << " r<nb rows> c<nb columns> n<non zeros per column> t<nb tries> p<nb repeats>\n";
return 1;
}
std::cout << "SpMV " << rows << " x " << cols << " with " << nnzPerCol << " non zeros per column. (" << repeats << " repeats, and " << tries << " tries)\n\n";
EigenSparseMatrix sm(rows,cols);
DenseVector dv(cols), res(rows);
dv.setRandom();
BenchTimer t;
while (nnzPerCol>=4)
{
std::cout << "nnz: " << nnzPerCol << "\n";
sm.setZero();
fillMatrix2(nnzPerCol, rows, cols, sm);
// dense matrices
#ifdef DENSEMATRIX
{
DenseMatrix dm(rows,cols), (rows,cols);
eiToDense(sm, dm);
SPMV_BENCH(res = dm * sm);
std::cout << "Dense " << t.value()/repeats << "\t";
SPMV_BENCH(res = dm.transpose() * sm);
std::cout << t.value()/repeats << endl;
}
#endif
// eigen sparse matrices
{
SPMV_BENCH(res.noalias() += sm * dv; )
std::cout << "Eigen " << t.value()/repeats << "\t";
SPMV_BENCH(res.noalias() += sm.transpose() * dv; )
std::cout << t.value()/repeats << endl;
}
// CSparse
#ifdef CSPARSE
{
std::cout << "CSparse \n";
cs *csm;
eiToCSparse(sm, csm);
// BENCH();
// timer.stop();
// std::cout << " a * b:\t" << timer.value() << endl;
// BENCH( { m3 = cs_sorted_multiply2(m1, m2); cs_spfree(m3); } );
// std::cout << " a * b:\t" << timer.value() << endl;
}
#endif
#ifdef OSKI
{
oski_matrix_t om;
oski_vecview_t ov, ores;
oski_Init();
om = oski_CreateMatCSC(sm._outerIndexPtr(), sm._innerIndexPtr(), sm._valuePtr(), rows, cols,
SHARE_INPUTMAT, 1, INDEX_ZERO_BASED);
ov = oski_CreateVecView(dv.data(), cols, STRIDE_UNIT);
ores = oski_CreateVecView(res.data(), rows, STRIDE_UNIT);
SPMV_BENCH( oski_MatMult(om, OP_NORMAL, 1, ov, 0, ores) );
std::cout << "OSKI " << t.value()/repeats << "\t";
SPMV_BENCH( oski_MatMult(om, OP_TRANS, 1, ov, 0, ores) );
std::cout << t.value()/repeats << "\n";
// tune
t.reset();
t.start();
oski_SetHintMatMult(om, OP_NORMAL, 1.0, SYMBOLIC_VEC, 0.0, SYMBOLIC_VEC, ALWAYS_TUNE_AGGRESSIVELY);
oski_TuneMat(om);
t.stop();
double tuning = t.value();
SPMV_BENCH( oski_MatMult(om, OP_NORMAL, 1, ov, 0, ores) );
std::cout << "OSKI tuned " << t.value()/repeats << "\t";
SPMV_BENCH( oski_MatMult(om, OP_TRANS, 1, ov, 0, ores) );
std::cout << t.value()/repeats << "\t(" << tuning << ")\n";
oski_DestroyMat(om);
oski_DestroyVecView(ov);
oski_DestroyVecView(ores);
oski_Close();
}
#endif
#ifndef NOUBLAS
{
using namespace boost::numeric;
UblasMatrix um(rows,cols);
eiToUblas(sm, um);
boost::numeric::ublas::vector<Scalar> uv(cols), ures(rows);
Map<Matrix<Scalar,Dynamic,1> >(&uv[0], cols) = dv;
Map<Matrix<Scalar,Dynamic,1> >(&ures[0], rows) = res;
SPMV_BENCH(ublas::axpy_prod(um, uv, ures, true));
std::cout << "ublas " << t.value()/repeats << "\t";
SPMV_BENCH(ublas::axpy_prod(boost::numeric::ublas::trans(um), uv, ures, true));
std::cout << t.value()/repeats << endl;
}
#endif
// GMM++
#ifndef NOGMM
{
GmmSparse gm(rows,cols);
eiToGmm(sm, gm);
std::vector<Scalar> gv(cols), gres(rows);
Map<Matrix<Scalar,Dynamic,1> >(&gv[0], cols) = dv;
Map<Matrix<Scalar,Dynamic,1> >(&gres[0], rows) = res;
SPMV_BENCH(gmm::mult(gm, gv, gres));
std::cout << "GMM++ " << t.value()/repeats << "\t";
SPMV_BENCH(gmm::mult(gmm::transposed(gm), gv, gres));
std::cout << t.value()/repeats << endl;
}
#endif
// MTL4
#ifndef NOMTL
{
MtlSparse mm(rows,cols);
eiToMtl(sm, mm);
mtl::dense_vector<Scalar> mv(cols, 1.0);
mtl::dense_vector<Scalar> mres(rows, 1.0);
SPMV_BENCH(mres = mm * mv);
std::cout << "MTL4 " << t.value()/repeats << "\t";
SPMV_BENCH(mres = trans(mm) * mv);
std::cout << t.value()/repeats << endl;
}
#endif
std::cout << "\n";
if(nnzPerCol==1)
break;
nnzPerCol -= nnzPerCol/2;
}
return 0;
}
| lgpl-3.0 |
m-a-hicks/Simulacrum | External/liblua/loadlib.c | 314 | 21488 | /*
** $Id: loadlib.c,v 1.111 2012/05/30 12:33:44 roberto Exp $
** Dynamic library loader for Lua
** See Copyright Notice in lua.h
**
** This module contains an implementation of loadlib for Unix systems
** that have dlfcn, an implementation for Windows, and a stub for other
** systems.
*/
/*
** if needed, includes windows header before everything else
*/
#if defined(_WIN32)
#include <windows.h>
#endif
#include <stdlib.h>
#include <string.h>
#define loadlib_c
#define LUA_LIB
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
/*
** LUA_PATH and LUA_CPATH are the names of the environment
** variables that Lua check to set its paths.
*/
#if !defined(LUA_PATH)
#define LUA_PATH "LUA_PATH"
#endif
#if !defined(LUA_CPATH)
#define LUA_CPATH "LUA_CPATH"
#endif
#define LUA_PATHSUFFIX "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR
#define LUA_PATHVERSION LUA_PATH LUA_PATHSUFFIX
#define LUA_CPATHVERSION LUA_CPATH LUA_PATHSUFFIX
/*
** LUA_PATH_SEP is the character that separates templates in a path.
** LUA_PATH_MARK is the string that marks the substitution points in a
** template.
** LUA_EXEC_DIR in a Windows path is replaced by the executable's
** directory.
** LUA_IGMARK is a mark to ignore all before it when building the
** luaopen_ function name.
*/
#if !defined (LUA_PATH_SEP)
#define LUA_PATH_SEP ";"
#endif
#if !defined (LUA_PATH_MARK)
#define LUA_PATH_MARK "?"
#endif
#if !defined (LUA_EXEC_DIR)
#define LUA_EXEC_DIR "!"
#endif
#if !defined (LUA_IGMARK)
#define LUA_IGMARK "-"
#endif
/*
** LUA_CSUBSEP is the character that replaces dots in submodule names
** when searching for a C loader.
** LUA_LSUBSEP is the character that replaces dots in submodule names
** when searching for a Lua loader.
*/
#if !defined(LUA_CSUBSEP)
#define LUA_CSUBSEP LUA_DIRSEP
#endif
#if !defined(LUA_LSUBSEP)
#define LUA_LSUBSEP LUA_DIRSEP
#endif
/* prefix for open functions in C libraries */
#define LUA_POF "luaopen_"
/* separator for open functions in C libraries */
#define LUA_OFSEP "_"
/* table (in the registry) that keeps handles for all loaded C libraries */
#define CLIBS "_CLIBS"
#define LIB_FAIL "open"
/* error codes for ll_loadfunc */
#define ERRLIB 1
#define ERRFUNC 2
#define setprogdir(L) ((void)0)
/*
** system-dependent functions
*/
static void ll_unloadlib (void *lib);
static void *ll_load (lua_State *L, const char *path, int seeglb);
static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym);
#if defined(LUA_USE_DLOPEN)
/*
** {========================================================================
** This is an implementation of loadlib based on the dlfcn interface.
** The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD,
** NetBSD, AIX 4.2, HPUX 11, and probably most other Unix flavors, at least
** as an emulation layer on top of native functions.
** =========================================================================
*/
#include <dlfcn.h>
static void ll_unloadlib (void *lib) {
dlclose(lib);
}
static void *ll_load (lua_State *L, const char *path, int seeglb) {
void *lib = dlopen(path, RTLD_NOW | (seeglb ? RTLD_GLOBAL : RTLD_LOCAL));
if (lib == NULL) lua_pushstring(L, dlerror());
return lib;
}
static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
lua_CFunction f = (lua_CFunction)dlsym(lib, sym);
if (f == NULL) lua_pushstring(L, dlerror());
return f;
}
/* }====================================================== */
#elif defined(LUA_DL_DLL)
/*
** {======================================================================
** This is an implementation of loadlib for Windows using native functions.
** =======================================================================
*/
#undef setprogdir
/*
** optional flags for LoadLibraryEx
*/
#if !defined(LUA_LLE_FLAGS)
#define LUA_LLE_FLAGS 0
#endif
static void setprogdir (lua_State *L) {
char buff[MAX_PATH + 1];
char *lb;
DWORD nsize = sizeof(buff)/sizeof(char);
DWORD n = GetModuleFileNameA(NULL, buff, nsize);
if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == NULL)
luaL_error(L, "unable to get ModuleFileName");
else {
*lb = '\0';
luaL_gsub(L, lua_tostring(L, -1), LUA_EXEC_DIR, buff);
lua_remove(L, -2); /* remove original string */
}
}
static void pusherror (lua_State *L) {
int error = GetLastError();
char buffer[128];
if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
NULL, error, 0, buffer, sizeof(buffer)/sizeof(char), NULL))
lua_pushstring(L, buffer);
else
lua_pushfstring(L, "system error %d\n", error);
}
static void ll_unloadlib (void *lib) {
FreeLibrary((HMODULE)lib);
}
static void *ll_load (lua_State *L, const char *path, int seeglb) {
HMODULE lib = LoadLibraryExA(path, NULL, LUA_LLE_FLAGS);
(void)(seeglb); /* not used: symbols are 'global' by default */
if (lib == NULL) pusherror(L);
return lib;
}
static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
lua_CFunction f = (lua_CFunction)GetProcAddress((HMODULE)lib, sym);
if (f == NULL) pusherror(L);
return f;
}
/* }====================================================== */
#else
/*
** {======================================================
** Fallback for other systems
** =======================================================
*/
#undef LIB_FAIL
#define LIB_FAIL "absent"
#define DLMSG "dynamic libraries not enabled; check your Lua installation"
static void ll_unloadlib (void *lib) {
(void)(lib); /* not used */
}
static void *ll_load (lua_State *L, const char *path, int seeglb) {
(void)(path); (void)(seeglb); /* not used */
lua_pushliteral(L, DLMSG);
return NULL;
}
static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
(void)(lib); (void)(sym); /* not used */
lua_pushliteral(L, DLMSG);
return NULL;
}
/* }====================================================== */
#endif
static void *ll_checkclib (lua_State *L, const char *path) {
void *plib;
lua_getfield(L, LUA_REGISTRYINDEX, CLIBS);
lua_getfield(L, -1, path);
plib = lua_touserdata(L, -1); /* plib = CLIBS[path] */
lua_pop(L, 2); /* pop CLIBS table and 'plib' */
return plib;
}
static void ll_addtoclib (lua_State *L, const char *path, void *plib) {
lua_getfield(L, LUA_REGISTRYINDEX, CLIBS);
lua_pushlightuserdata(L, plib);
lua_pushvalue(L, -1);
lua_setfield(L, -3, path); /* CLIBS[path] = plib */
lua_rawseti(L, -2, luaL_len(L, -2) + 1); /* CLIBS[#CLIBS + 1] = plib */
lua_pop(L, 1); /* pop CLIBS table */
}
/*
** __gc tag method for CLIBS table: calls 'll_unloadlib' for all lib
** handles in list CLIBS
*/
static int gctm (lua_State *L) {
int n = luaL_len(L, 1);
for (; n >= 1; n--) { /* for each handle, in reverse order */
lua_rawgeti(L, 1, n); /* get handle CLIBS[n] */
ll_unloadlib(lua_touserdata(L, -1));
lua_pop(L, 1); /* pop handle */
}
return 0;
}
static int ll_loadfunc (lua_State *L, const char *path, const char *sym) {
void *reg = ll_checkclib(L, path); /* check loaded C libraries */
if (reg == NULL) { /* must load library? */
reg = ll_load(L, path, *sym == '*');
if (reg == NULL) return ERRLIB; /* unable to load library */
ll_addtoclib(L, path, reg);
}
if (*sym == '*') { /* loading only library (no function)? */
lua_pushboolean(L, 1); /* return 'true' */
return 0; /* no errors */
}
else {
lua_CFunction f = ll_sym(L, reg, sym);
if (f == NULL)
return ERRFUNC; /* unable to find function */
lua_pushcfunction(L, f); /* else create new function */
return 0; /* no errors */
}
}
static int ll_loadlib (lua_State *L) {
const char *path = luaL_checkstring(L, 1);
const char *init = luaL_checkstring(L, 2);
int stat = ll_loadfunc(L, path, init);
if (stat == 0) /* no errors? */
return 1; /* return the loaded function */
else { /* error; error message is on stack top */
lua_pushnil(L);
lua_insert(L, -2);
lua_pushstring(L, (stat == ERRLIB) ? LIB_FAIL : "init");
return 3; /* return nil, error message, and where */
}
}
/*
** {======================================================
** 'require' function
** =======================================================
*/
static int readable (const char *filename) {
FILE *f = fopen(filename, "r"); /* try to open file */
if (f == NULL) return 0; /* open failed */
fclose(f);
return 1;
}
static const char *pushnexttemplate (lua_State *L, const char *path) {
const char *l;
while (*path == *LUA_PATH_SEP) path++; /* skip separators */
if (*path == '\0') return NULL; /* no more templates */
l = strchr(path, *LUA_PATH_SEP); /* find next separator */
if (l == NULL) l = path + strlen(path);
lua_pushlstring(L, path, l - path); /* template */
return l;
}
static const char *searchpath (lua_State *L, const char *name,
const char *path,
const char *sep,
const char *dirsep) {
luaL_Buffer msg; /* to build error message */
luaL_buffinit(L, &msg);
if (*sep != '\0') /* non-empty separator? */
name = luaL_gsub(L, name, sep, dirsep); /* replace it by 'dirsep' */
while ((path = pushnexttemplate(L, path)) != NULL) {
const char *filename = luaL_gsub(L, lua_tostring(L, -1),
LUA_PATH_MARK, name);
lua_remove(L, -2); /* remove path template */
if (readable(filename)) /* does file exist and is readable? */
return filename; /* return that file name */
lua_pushfstring(L, "\n\tno file " LUA_QS, filename);
lua_remove(L, -2); /* remove file name */
luaL_addvalue(&msg); /* concatenate error msg. entry */
}
luaL_pushresult(&msg); /* create error message */
return NULL; /* not found */
}
static int ll_searchpath (lua_State *L) {
const char *f = searchpath(L, luaL_checkstring(L, 1),
luaL_checkstring(L, 2),
luaL_optstring(L, 3, "."),
luaL_optstring(L, 4, LUA_DIRSEP));
if (f != NULL) return 1;
else { /* error message is on top of the stack */
lua_pushnil(L);
lua_insert(L, -2);
return 2; /* return nil + error message */
}
}
static const char *findfile (lua_State *L, const char *name,
const char *pname,
const char *dirsep) {
const char *path;
lua_getfield(L, lua_upvalueindex(1), pname);
path = lua_tostring(L, -1);
if (path == NULL)
luaL_error(L, LUA_QL("package.%s") " must be a string", pname);
return searchpath(L, name, path, ".", dirsep);
}
static int checkload (lua_State *L, int stat, const char *filename) {
if (stat) { /* module loaded successfully? */
lua_pushstring(L, filename); /* will be 2nd argument to module */
return 2; /* return open function and file name */
}
else
return luaL_error(L, "error loading module " LUA_QS
" from file " LUA_QS ":\n\t%s",
lua_tostring(L, 1), filename, lua_tostring(L, -1));
}
static int searcher_Lua (lua_State *L) {
const char *filename;
const char *name = luaL_checkstring(L, 1);
filename = findfile(L, name, "path", LUA_LSUBSEP);
if (filename == NULL) return 1; /* module not found in this path */
return checkload(L, (luaL_loadfile(L, filename) == LUA_OK), filename);
}
static int loadfunc (lua_State *L, const char *filename, const char *modname) {
const char *funcname;
const char *mark;
modname = luaL_gsub(L, modname, ".", LUA_OFSEP);
mark = strchr(modname, *LUA_IGMARK);
if (mark) {
int stat;
funcname = lua_pushlstring(L, modname, mark - modname);
funcname = lua_pushfstring(L, LUA_POF"%s", funcname);
stat = ll_loadfunc(L, filename, funcname);
if (stat != ERRFUNC) return stat;
modname = mark + 1; /* else go ahead and try old-style name */
}
funcname = lua_pushfstring(L, LUA_POF"%s", modname);
return ll_loadfunc(L, filename, funcname);
}
static int searcher_C (lua_State *L) {
const char *name = luaL_checkstring(L, 1);
const char *filename = findfile(L, name, "cpath", LUA_CSUBSEP);
if (filename == NULL) return 1; /* module not found in this path */
return checkload(L, (loadfunc(L, filename, name) == 0), filename);
}
static int searcher_Croot (lua_State *L) {
const char *filename;
const char *name = luaL_checkstring(L, 1);
const char *p = strchr(name, '.');
int stat;
if (p == NULL) return 0; /* is root */
lua_pushlstring(L, name, p - name);
filename = findfile(L, lua_tostring(L, -1), "cpath", LUA_CSUBSEP);
if (filename == NULL) return 1; /* root not found */
if ((stat = loadfunc(L, filename, name)) != 0) {
if (stat != ERRFUNC)
return checkload(L, 0, filename); /* real error */
else { /* open function not found */
lua_pushfstring(L, "\n\tno module " LUA_QS " in file " LUA_QS,
name, filename);
return 1;
}
}
lua_pushstring(L, filename); /* will be 2nd argument to module */
return 2;
}
static int searcher_preload (lua_State *L) {
const char *name = luaL_checkstring(L, 1);
lua_getfield(L, LUA_REGISTRYINDEX, "_PRELOAD");
lua_getfield(L, -1, name);
if (lua_isnil(L, -1)) /* not found? */
lua_pushfstring(L, "\n\tno field package.preload['%s']", name);
return 1;
}
static void findloader (lua_State *L, const char *name) {
int i;
luaL_Buffer msg; /* to build error message */
luaL_buffinit(L, &msg);
lua_getfield(L, lua_upvalueindex(1), "searchers"); /* will be at index 3 */
if (!lua_istable(L, 3))
luaL_error(L, LUA_QL("package.searchers") " must be a table");
/* iterate over available searchers to find a loader */
for (i = 1; ; i++) {
lua_rawgeti(L, 3, i); /* get a searcher */
if (lua_isnil(L, -1)) { /* no more searchers? */
lua_pop(L, 1); /* remove nil */
luaL_pushresult(&msg); /* create error message */
luaL_error(L, "module " LUA_QS " not found:%s",
name, lua_tostring(L, -1));
}
lua_pushstring(L, name);
lua_call(L, 1, 2); /* call it */
if (lua_isfunction(L, -2)) /* did it find a loader? */
return; /* module loader found */
else if (lua_isstring(L, -2)) { /* searcher returned error message? */
lua_pop(L, 1); /* remove extra return */
luaL_addvalue(&msg); /* concatenate error message */
}
else
lua_pop(L, 2); /* remove both returns */
}
}
static int ll_require (lua_State *L) {
const char *name = luaL_checkstring(L, 1);
lua_settop(L, 1); /* _LOADED table will be at index 2 */
lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
lua_getfield(L, 2, name); /* _LOADED[name] */
if (lua_toboolean(L, -1)) /* is it there? */
return 1; /* package is already loaded */
/* else must load package */
lua_pop(L, 1); /* remove 'getfield' result */
findloader(L, name);
lua_pushstring(L, name); /* pass name as argument to module loader */
lua_insert(L, -2); /* name is 1st argument (before search data) */
lua_call(L, 2, 1); /* run loader to load module */
if (!lua_isnil(L, -1)) /* non-nil return? */
lua_setfield(L, 2, name); /* _LOADED[name] = returned value */
lua_getfield(L, 2, name);
if (lua_isnil(L, -1)) { /* module did not set a value? */
lua_pushboolean(L, 1); /* use true as result */
lua_pushvalue(L, -1); /* extra copy to be returned */
lua_setfield(L, 2, name); /* _LOADED[name] = true */
}
return 1;
}
/* }====================================================== */
/*
** {======================================================
** 'module' function
** =======================================================
*/
#if defined(LUA_COMPAT_MODULE)
/*
** changes the environment variable of calling function
*/
static void set_env (lua_State *L) {
lua_Debug ar;
if (lua_getstack(L, 1, &ar) == 0 ||
lua_getinfo(L, "f", &ar) == 0 || /* get calling function */
lua_iscfunction(L, -1))
luaL_error(L, LUA_QL("module") " not called from a Lua function");
lua_pushvalue(L, -2); /* copy new environment table to top */
lua_setupvalue(L, -2, 1);
lua_pop(L, 1); /* remove function */
}
static void dooptions (lua_State *L, int n) {
int i;
for (i = 2; i <= n; i++) {
if (lua_isfunction(L, i)) { /* avoid 'calling' extra info. */
lua_pushvalue(L, i); /* get option (a function) */
lua_pushvalue(L, -2); /* module */
lua_call(L, 1, 0);
}
}
}
static void modinit (lua_State *L, const char *modname) {
const char *dot;
lua_pushvalue(L, -1);
lua_setfield(L, -2, "_M"); /* module._M = module */
lua_pushstring(L, modname);
lua_setfield(L, -2, "_NAME");
dot = strrchr(modname, '.'); /* look for last dot in module name */
if (dot == NULL) dot = modname;
else dot++;
/* set _PACKAGE as package name (full module name minus last part) */
lua_pushlstring(L, modname, dot - modname);
lua_setfield(L, -2, "_PACKAGE");
}
static int ll_module (lua_State *L) {
const char *modname = luaL_checkstring(L, 1);
int lastarg = lua_gettop(L); /* last parameter */
luaL_pushmodule(L, modname, 1); /* get/create module table */
/* check whether table already has a _NAME field */
lua_getfield(L, -1, "_NAME");
if (!lua_isnil(L, -1)) /* is table an initialized module? */
lua_pop(L, 1);
else { /* no; initialize it */
lua_pop(L, 1);
modinit(L, modname);
}
lua_pushvalue(L, -1);
set_env(L);
dooptions(L, lastarg);
return 1;
}
static int ll_seeall (lua_State *L) {
luaL_checktype(L, 1, LUA_TTABLE);
if (!lua_getmetatable(L, 1)) {
lua_createtable(L, 0, 1); /* create new metatable */
lua_pushvalue(L, -1);
lua_setmetatable(L, 1);
}
lua_pushglobaltable(L);
lua_setfield(L, -2, "__index"); /* mt.__index = _G */
return 0;
}
#endif
/* }====================================================== */
/* auxiliary mark (for internal use) */
#define AUXMARK "\1"
/*
** return registry.LUA_NOENV as a boolean
*/
static int noenv (lua_State *L) {
int b;
lua_getfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
b = lua_toboolean(L, -1);
lua_pop(L, 1); /* remove value */
return b;
}
static void setpath (lua_State *L, const char *fieldname, const char *envname1,
const char *envname2, const char *def) {
const char *path = getenv(envname1);
if (path == NULL) /* no environment variable? */
path = getenv(envname2); /* try alternative name */
if (path == NULL || noenv(L)) /* no environment variable? */
lua_pushstring(L, def); /* use default */
else {
/* replace ";;" by ";AUXMARK;" and then AUXMARK by default path */
path = luaL_gsub(L, path, LUA_PATH_SEP LUA_PATH_SEP,
LUA_PATH_SEP AUXMARK LUA_PATH_SEP);
luaL_gsub(L, path, AUXMARK, def);
lua_remove(L, -2);
}
setprogdir(L);
lua_setfield(L, -2, fieldname);
}
static const luaL_Reg pk_funcs[] = {
{"loadlib", ll_loadlib},
{"searchpath", ll_searchpath},
#if defined(LUA_COMPAT_MODULE)
{"seeall", ll_seeall},
#endif
{NULL, NULL}
};
static const luaL_Reg ll_funcs[] = {
#if defined(LUA_COMPAT_MODULE)
{"module", ll_module},
#endif
{"require", ll_require},
{NULL, NULL}
};
static void createsearcherstable (lua_State *L) {
static const lua_CFunction searchers[] =
{searcher_preload, searcher_Lua, searcher_C, searcher_Croot, NULL};
int i;
/* create 'searchers' table */
lua_createtable(L, sizeof(searchers)/sizeof(searchers[0]) - 1, 0);
/* fill it with pre-defined searchers */
for (i=0; searchers[i] != NULL; i++) {
lua_pushvalue(L, -2); /* set 'package' as upvalue for all searchers */
lua_pushcclosure(L, searchers[i], 1);
lua_rawseti(L, -2, i+1);
}
}
LUAMOD_API int luaopen_package (lua_State *L) {
/* create table CLIBS to keep track of loaded C libraries */
luaL_getsubtable(L, LUA_REGISTRYINDEX, CLIBS);
lua_createtable(L, 0, 1); /* metatable for CLIBS */
lua_pushcfunction(L, gctm);
lua_setfield(L, -2, "__gc"); /* set finalizer for CLIBS table */
lua_setmetatable(L, -2);
/* create `package' table */
luaL_newlib(L, pk_funcs);
createsearcherstable(L);
#if defined(LUA_COMPAT_LOADERS)
lua_pushvalue(L, -1); /* make a copy of 'searchers' table */
lua_setfield(L, -3, "loaders"); /* put it in field `loaders' */
#endif
lua_setfield(L, -2, "searchers"); /* put it in field 'searchers' */
/* set field 'path' */
setpath(L, "path", LUA_PATHVERSION, LUA_PATH, LUA_PATH_DEFAULT);
/* set field 'cpath' */
setpath(L, "cpath", LUA_CPATHVERSION, LUA_CPATH, LUA_CPATH_DEFAULT);
/* store config information */
lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATH_SEP "\n" LUA_PATH_MARK "\n"
LUA_EXEC_DIR "\n" LUA_IGMARK "\n");
lua_setfield(L, -2, "config");
/* set field `loaded' */
luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED");
lua_setfield(L, -2, "loaded");
/* set field `preload' */
luaL_getsubtable(L, LUA_REGISTRYINDEX, "_PRELOAD");
lua_setfield(L, -2, "preload");
lua_pushglobaltable(L);
lua_pushvalue(L, -2); /* set 'package' as upvalue for next lib */
luaL_setfuncs(L, ll_funcs, 1); /* open lib into global table */
lua_pop(L, 1); /* pop global table */
return 1; /* return 'package' table */
}
| lgpl-3.0 |
tunneff/tef | deps/boost_1_63_0/libs/numeric/interval/test/det.cpp | 62 | 2636 | /* Boost test/det.cpp
* test protected and unprotected rounding on an unstable determinant
*
* Copyright 2002-2003 Guillaume Melquiond
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or
* copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#include <boost/numeric/interval.hpp>
#include <boost/test/minimal.hpp>
#include "bugs.hpp"
#define size 8
template<class I>
void det(I (&mat)[size][size]) {
for(int i = 0; i < size; i++)
for(int j = 0; j < size; j++)
mat[i][j] = I(1) / I(i + j + 1);
for(int i = 0; i < size - 1; i++) {
int m = i, n = i;
typename I::base_type v = 0;
for(int a = i; a < size; a++)
for(int b = i; b < size; b++) {
typename I::base_type w = abs(mat[a][b]).lower();
if (w > v) { m = a; n = b; v = w; }
}
if (n != i)
for(int a = 0; a < size; a++) {
I t = mat[a][n];
mat[a][n] = mat[a][i];
mat[a][i] = t;
}
if (m != i)
for(int b = i; b < size; b++) {
I t = mat[m][b];
mat[m][b] = mat[m][i];
mat[m][i] = t;
}
if (((m + n) & 1) == 1) { };
I c = mat[i][i];
for(int j = i + 1; j < size; j++) {
I f = mat[j][i] / c;
for(int k = i; k < size; k++)
mat[j][k] -= f * mat[i][k];
}
if (zero_in(c)) return;
}
}
namespace my_namespace {
using namespace boost;
using namespace numeric;
using namespace interval_lib;
template<class T>
struct variants {
typedef interval<T> I_op;
typedef typename change_rounding<I_op, save_state<rounded_arith_std<T> > >::type I_sp;
typedef typename unprotect<I_op>::type I_ou;
typedef typename unprotect<I_sp>::type I_su;
typedef T type;
};
}
template<class T>
bool test() {
typedef my_namespace::variants<double> types;
types::I_op mat_op[size][size];
types::I_sp mat_sp[size][size];
types::I_ou mat_ou[size][size];
types::I_su mat_su[size][size];
det(mat_op);
det(mat_sp);
{ types::I_op::traits_type::rounding rnd; det(mat_ou); }
{ types::I_sp::traits_type::rounding rnd; det(mat_su); }
for(int i = 0; i < size; i++)
for(int j = 0; j < size; j++) {
typedef types::I_op I;
I d_op = mat_op[i][j];
I d_sp = mat_sp[i][j];
I d_ou = mat_ou[i][j];
I d_su = mat_su[i][j];
if (!(equal(d_op, d_sp) && equal(d_sp, d_ou) && equal(d_ou, d_su)))
return false;
}
return true;
}
int test_main(int, char *[]) {
BOOST_CHECK(test<float>());
BOOST_CHECK(test<double>());
BOOST_CHECK(test<long double>());
# ifdef __BORLANDC__
::detail::ignore_warnings();
# endif
return 0;
}
| lgpl-3.0 |
tolgayilmaz86/WiringPi | examples/blink.c | 97 | 1459 | /*
* blink.c:
* Standard "blink" program in wiringPi. Blinks an LED connected
* to the first GPIO pin.
*
* Copyright (c) 2012-2013 Gordon Henderson. <projects@drogon.net>
***********************************************************************
* This file is part of wiringPi:
* https://projects.drogon.net/raspberry-pi/wiringpi/
*
* wiringPi is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* wiringPi is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with wiringPi. If not, see <http://www.gnu.org/licenses/>.
***********************************************************************
*/
#include <stdio.h>
#include <wiringPi.h>
// LED Pin - wiringPi pin 0 is BCM_GPIO 17.
#define LED 0
int main (void)
{
printf ("Raspberry Pi blink\n") ;
wiringPiSetup () ;
pinMode (LED, OUTPUT) ;
for (;;)
{
digitalWrite (LED, HIGH) ; // On
delay (500) ; // mS
digitalWrite (LED, LOW) ; // Off
delay (500) ;
}
return 0 ;
}
| lgpl-3.0 |
mellowcandle/epOS | 3rd_party/newlib-2.5.0.20170818/newlib/libc/sys/linux/net/ifname.c | 31 | 5692 | /* $KAME: ifname.c,v 1.4 2001/08/20 02:32:40 itojun Exp $ */
/*
* Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project 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 PROJECT 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 PROJECT 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 <sys/cdefs.h>
#include <sys/types.h>
#include <sys/types.h>
/*
* TODO:
* - prototype defs into arpa/inet.h, not net/if.h (bsd-api-new-02)
*/
#include <sys/param.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/route.h>
#include <net/if_dl.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#define ROUNDUP(a) \
((a) > 0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
#define ADVANCE(x, n)
static unsigned int
if_onametoindex(ifname)
const char *ifname;
{
struct if_nameindex *iff = if_nameindex(), *ifx;
int ret;
if (iff == NULL) return 0;
ifx = iff;
while (ifx->if_name != NULL) {
if (strcmp(ifx->if_name, ifname) == 0) {
ret = ifx->if_index;
if_freenameindex(iff);
return ret;
}
ifx++;
}
if_freenameindex(iff);
errno = ENXIO;
return 0;
}
unsigned int
if_nametoindex(ifname)
const char *ifname;
{
int s;
struct ifreq ifr;
s = socket(AF_INET, SOCK_DGRAM, 0);
if (s == -1)
return (0);
strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
if (ioctl(s, SIOCGIFINDEX, &ifr) == -1) {
close (s);
return (if_onametoindex(ifname));
}
close(s);
return (ifr.ifr_index);
}
char *
if_indextoname(ifindex, ifname)
unsigned int ifindex;
char *ifname; /* at least IF_NAMESIZE */
{
struct if_nameindex *iff = if_nameindex(), *ifx;
char *cp, *dp;
if (iff == NULL) return NULL;
ifx = iff;
while (ifx->if_index != 0) {
if (ifx->if_index == ifindex) {
cp = ifname;
dp = ifx->if_name;
while ((*cp++ = *dp++)) ;
if_freenameindex(iff);
return (ifname);
}
ifx++;
}
if_freenameindex(iff);
errno = ENXIO;
return NULL;
}
struct if_nameindex *
if_nameindex()
{
size_t needed;
int mib[6], ifn = 0, off = 0, hlen;
unsigned int i;
char *buf = NULL, *lim, *next, *cp, *ifbuf = NULL;
struct rt_msghdr *rtm;
struct if_msghdr *ifm;
struct sockaddr *sa;
struct if_nameindex *ret = NULL;
static int ifxs = 64; /* initial upper limit */
struct _ifx {
int if_index;
int if_off;
} *ifx = NULL;
mib[0] = CTL_NET;
mib[1] = PF_ROUTE;
mib[2] = 0; /* protocol */
mib[3] = 0; /* wildcard address family */
mib[4] = 0;
mib[5] = 0; /* no flags */
if (__sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
return NULL;
if ((buf = malloc(needed)) == NULL) {
errno = ENOMEM;
goto end;
}
/* XXX: we may have allocated too much than necessary */
if ((ifbuf = malloc(needed)) == NULL) {
errno = ENOMEM;
goto end;
}
if ((ifx = (struct _ifx *)malloc(sizeof(*ifx) * ifxs)) == NULL) {
errno = ENOMEM;
goto end;
}
if (__sysctl(mib, 6, buf, &needed, NULL, 0) < 0) {
/* sysctl has set errno */
goto end;
}
lim = buf + needed;
for (next = buf; next < lim; next += rtm->rtm_msglen) {
rtm = (struct rt_msghdr *)next;
if (rtm->rtm_version != RTM_VERSION) {
errno = EPROTONOSUPPORT;
goto end;
}
switch (rtm->rtm_type) {
case RTM_IFINFO:
ifm = (struct if_msghdr *)rtm;
ifx[ifn].if_index = ifm->ifm_index;
ifx[ifn].if_off = off;
cp = (char *)(ifm + 1);
for (i = 1; i; i <<= 1) {
if (i & ifm->ifm_addrs) {
sa = (struct sockaddr *)cp;
ADVANCE(cp, sa);
}
}
if (++ifn == ifxs) {
/* we need more memory */
struct _ifx *newifx;
ifxs *= 2;
if ((newifx = (struct _ifx *)malloc(sizeof(*newifx) * ifxs)) == NULL) {
errno = ENOMEM;
goto end;
}
/* copy and free old data */
memcpy(newifx, ifx, (sizeof(*ifx) * ifxs) / 2);
free(ifx);
ifx = newifx;
}
}
}
hlen = sizeof(struct if_nameindex) * (ifn + 1);
if ((cp = (char *)malloc(hlen + off)) == NULL) {
errno = ENOMEM;
goto end;
}
bcopy(ifbuf, cp + hlen, off);
ret = (struct if_nameindex *)cp;
for (i = 0; i < ifn; i++) {
ret[i].if_index = ifx[i].if_index;
ret[i].if_name = cp + hlen + ifx[i].if_off;
}
ret[ifn].if_index = 0;
ret[ifn].if_name = NULL;
end:
if (buf) free(buf);
if (ifbuf) free(ifbuf);
if (ifx) free(ifx);
return ret;
}
void if_freenameindex(ptr)
struct if_nameindex *ptr;
{
free(ptr);
}
| unlicense |
execunix/vinos | external/bsd/ntp/dist/sntp/libevent/test/tinytest.c | 1 | 12608 | /* $NetBSD: tinytest.c,v 1.1.1.1.6.2 2015/04/23 18:53:06 snj Exp $ */
/* tinytest.c -- Copyright 2009-2012 Nick Mathewson
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef TINYTEST_LOCAL
#include "tinytest_local.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#ifndef NO_FORKING
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#endif
#if defined(__APPLE__) && defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__)
#if (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1060 && \
__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 1070)
/* Workaround for a stupid bug in OSX 10.6 */
#define FORK_BREAKS_GCOV
#include <vproc.h>
#endif
#endif
#endif /* !NO_FORKING */
#ifndef __GNUC__
#define __attribute__(x)
#endif
#include "tinytest.h"
#include "tinytest_macros.h"
#define LONGEST_TEST_NAME 16384
static int in_tinytest_main = 0; /**< true if we're in tinytest_main().*/
static int n_ok = 0; /**< Number of tests that have passed */
static int n_bad = 0; /**< Number of tests that have failed. */
static int n_skipped = 0; /**< Number of tests that have been skipped. */
static int opt_forked = 0; /**< True iff we're called from inside a win32 fork*/
static int opt_nofork = 0; /**< Suppress calls to fork() for debugging. */
static int opt_verbosity = 1; /**< -==quiet,0==terse,1==normal,2==verbose */
const char *verbosity_flag = "";
const struct testlist_alias_t *cfg_aliases=NULL;
enum outcome { SKIP=2, OK=1, FAIL=0 };
static enum outcome cur_test_outcome = 0;
const char *cur_test_prefix = NULL; /**< prefix of the current test group */
/** Name of the current test, if we haven't logged is yet. Used for --quiet */
const char *cur_test_name = NULL;
#ifdef _WIN32
/* Copy of argv[0] for win32. */
static char commandname[MAX_PATH+1];
#endif
static void usage(struct testgroup_t *groups, int list_groups)
__attribute__((noreturn));
static int process_test_option(struct testgroup_t *groups, const char *test);
static enum outcome
testcase_run_bare_(const struct testcase_t *testcase)
{
void *env = NULL;
int outcome;
if (testcase->setup) {
env = testcase->setup->setup_fn(testcase);
if (!env)
return FAIL;
else if (env == (void*)TT_SKIP)
return SKIP;
}
cur_test_outcome = OK;
testcase->fn(env);
outcome = cur_test_outcome;
if (testcase->setup) {
if (testcase->setup->cleanup_fn(testcase, env) == 0)
outcome = FAIL;
}
return outcome;
}
#define MAGIC_EXITCODE 42
#ifndef NO_FORKING
static enum outcome
testcase_run_forked_(const struct testgroup_t *group,
const struct testcase_t *testcase)
{
#ifdef _WIN32
/* Fork? On Win32? How primitive! We'll do what the smart kids do:
we'll invoke our own exe (whose name we recall from the command
line) with a command line that tells it to run just the test we
want, and this time without forking.
(No, threads aren't an option. The whole point of forking is to
share no state between tests.)
*/
int ok;
char buffer[LONGEST_TEST_NAME+256];
STARTUPINFOA si;
PROCESS_INFORMATION info;
DWORD exitcode;
if (!in_tinytest_main) {
printf("\nERROR. On Windows, testcase_run_forked_ must be"
" called from within tinytest_main.\n");
abort();
}
if (opt_verbosity>0)
printf("[forking] ");
snprintf(buffer, sizeof(buffer), "%s --RUNNING-FORKED %s %s%s",
commandname, verbosity_flag, group->prefix, testcase->name);
memset(&si, 0, sizeof(si));
memset(&info, 0, sizeof(info));
si.cb = sizeof(si);
ok = CreateProcessA(commandname, buffer, NULL, NULL, 0,
0, NULL, NULL, &si, &info);
if (!ok) {
printf("CreateProcess failed!\n");
return 0;
}
WaitForSingleObject(info.hProcess, INFINITE);
GetExitCodeProcess(info.hProcess, &exitcode);
CloseHandle(info.hProcess);
CloseHandle(info.hThread);
if (exitcode == 0)
return OK;
else if (exitcode == MAGIC_EXITCODE)
return SKIP;
else
return FAIL;
#else
int outcome_pipe[2];
pid_t pid;
(void)group;
if (pipe(outcome_pipe))
perror("opening pipe");
if (opt_verbosity>0)
printf("[forking] ");
pid = fork();
#ifdef FORK_BREAKS_GCOV
vproc_transaction_begin(0);
#endif
if (!pid) {
/* child. */
int test_r, write_r;
char b[1];
close(outcome_pipe[0]);
test_r = testcase_run_bare_(testcase);
assert(0<=(int)test_r && (int)test_r<=2);
b[0] = "NYS"[test_r];
write_r = (int)write(outcome_pipe[1], b, 1);
if (write_r != 1) {
perror("write outcome to pipe");
exit(1);
}
exit(0);
return FAIL; /* unreachable */
} else {
/* parent */
int status, r;
char b[1];
/* Close this now, so that if the other side closes it,
* our read fails. */
close(outcome_pipe[1]);
r = (int)read(outcome_pipe[0], b, 1);
if (r == 0) {
printf("[Lost connection!] ");
return 0;
} else if (r != 1) {
perror("read outcome from pipe");
}
waitpid(pid, &status, 0);
close(outcome_pipe[0]);
return b[0]=='Y' ? OK : (b[0]=='S' ? SKIP : FAIL);
}
#endif
}
#endif /* !NO_FORKING */
int
testcase_run_one(const struct testgroup_t *group,
const struct testcase_t *testcase)
{
enum outcome outcome;
if (testcase->flags & (TT_SKIP|TT_OFF_BY_DEFAULT)) {
if (opt_verbosity>0)
printf("%s%s: %s\n",
group->prefix, testcase->name,
(testcase->flags & TT_SKIP) ? "SKIPPED" : "DISABLED");
++n_skipped;
return SKIP;
}
if (opt_verbosity>0 && !opt_forked) {
printf("%s%s: ", group->prefix, testcase->name);
} else {
if (opt_verbosity==0) printf(".");
cur_test_prefix = group->prefix;
cur_test_name = testcase->name;
}
#ifndef NO_FORKING
if ((testcase->flags & TT_FORK) && !(opt_forked||opt_nofork)) {
outcome = testcase_run_forked_(group, testcase);
} else {
#else
{
#endif
outcome = testcase_run_bare_(testcase);
}
if (outcome == OK) {
++n_ok;
if (opt_verbosity>0 && !opt_forked)
puts(opt_verbosity==1?"OK":"");
} else if (outcome == SKIP) {
++n_skipped;
if (opt_verbosity>0 && !opt_forked)
puts("SKIPPED");
} else {
++n_bad;
if (!opt_forked)
printf("\n [%s FAILED]\n", testcase->name);
}
if (opt_forked) {
exit(outcome==OK ? 0 : (outcome==SKIP?MAGIC_EXITCODE : 1));
return 1; /* unreachable */
} else {
return (int)outcome;
}
}
int
tinytest_set_flag_(struct testgroup_t *groups, const char *arg, int set, unsigned long flag)
{
int i, j;
size_t length = LONGEST_TEST_NAME;
char fullname[LONGEST_TEST_NAME];
int found=0;
if (strstr(arg, ".."))
length = strstr(arg,"..")-arg;
for (i=0; groups[i].prefix; ++i) {
for (j=0; groups[i].cases[j].name; ++j) {
struct testcase_t *testcase = &groups[i].cases[j];
snprintf(fullname, sizeof(fullname), "%s%s",
groups[i].prefix, testcase->name);
if (!flag) { /* Hack! */
printf(" %s", fullname);
if (testcase->flags & TT_OFF_BY_DEFAULT)
puts(" (Off by default)");
else if (testcase->flags & TT_SKIP)
puts(" (DISABLED)");
else
puts("");
}
if (!strncmp(fullname, arg, length)) {
if (set)
testcase->flags |= flag;
else
testcase->flags &= ~flag;
++found;
}
}
}
return found;
}
static void
usage(struct testgroup_t *groups, int list_groups)
{
puts("Options are: [--verbose|--quiet|--terse] [--no-fork]");
puts(" Specify tests by name, or using a prefix ending with '..'");
puts(" To skip a test, prefix its name with a colon.");
puts(" To enable a disabled test, prefix its name with a plus.");
puts(" Use --list-tests for a list of tests.");
if (list_groups) {
puts("Known tests are:");
tinytest_set_flag_(groups, "..", 1, 0);
}
exit(0);
}
static int
process_test_alias(struct testgroup_t *groups, const char *test)
{
int i, j, n, r;
for (i=0; cfg_aliases && cfg_aliases[i].name; ++i) {
if (!strcmp(cfg_aliases[i].name, test)) {
n = 0;
for (j = 0; cfg_aliases[i].tests[j]; ++j) {
r = process_test_option(groups, cfg_aliases[i].tests[j]);
if (r<0)
return -1;
n += r;
}
return n;
}
}
printf("No such test alias as @%s!",test);
return -1;
}
static int
process_test_option(struct testgroup_t *groups, const char *test)
{
int flag = TT_ENABLED_;
int n = 0;
if (test[0] == '@') {
return process_test_alias(groups, test + 1);
} else if (test[0] == ':') {
++test;
flag = TT_SKIP;
} else if (test[0] == '+') {
++test;
++n;
if (!tinytest_set_flag_(groups, test, 0, TT_OFF_BY_DEFAULT)) {
printf("No such test as %s!\n", test);
return -1;
}
} else {
++n;
}
if (!tinytest_set_flag_(groups, test, 1, flag)) {
printf("No such test as %s!\n", test);
return -1;
}
return n;
}
void
tinytest_set_aliases(const struct testlist_alias_t *aliases)
{
cfg_aliases = aliases;
}
int
tinytest_main(int c, const char **v, struct testgroup_t *groups)
{
int i, j, n=0;
#ifdef _WIN32
const char *sp = strrchr(v[0], '.');
const char *extension = "";
if (!sp || stricmp(sp, ".exe"))
extension = ".exe"; /* Add an exe so CreateProcess will work */
snprintf(commandname, sizeof(commandname), "%s%s", v[0], extension);
commandname[MAX_PATH]='\0';
#endif
for (i=1; i<c; ++i) {
if (v[i][0] == '-') {
if (!strcmp(v[i], "--RUNNING-FORKED")) {
opt_forked = 1;
} else if (!strcmp(v[i], "--no-fork")) {
opt_nofork = 1;
} else if (!strcmp(v[i], "--quiet")) {
opt_verbosity = -1;
verbosity_flag = "--quiet";
} else if (!strcmp(v[i], "--verbose")) {
opt_verbosity = 2;
verbosity_flag = "--verbose";
} else if (!strcmp(v[i], "--terse")) {
opt_verbosity = 0;
verbosity_flag = "--terse";
} else if (!strcmp(v[i], "--help")) {
usage(groups, 0);
} else if (!strcmp(v[i], "--list-tests")) {
usage(groups, 1);
} else {
printf("Unknown option %s. Try --help\n",v[i]);
return -1;
}
} else {
int r = process_test_option(groups, v[i]);
if (r<0)
return -1;
n += r;
}
}
if (!n)
tinytest_set_flag_(groups, "..", 1, TT_ENABLED_);
#ifdef _IONBF
setvbuf(stdout, NULL, _IONBF, 0);
#endif
++in_tinytest_main;
for (i=0; groups[i].prefix; ++i)
for (j=0; groups[i].cases[j].name; ++j)
if (groups[i].cases[j].flags & TT_ENABLED_)
testcase_run_one(&groups[i],
&groups[i].cases[j]);
--in_tinytest_main;
if (opt_verbosity==0)
puts("");
if (n_bad)
printf("%d/%d TESTS FAILED. (%d skipped)\n", n_bad,
n_bad+n_ok,n_skipped);
else if (opt_verbosity >= 1)
printf("%d tests ok. (%d skipped)\n", n_ok, n_skipped);
return (n_bad == 0) ? 0 : 1;
}
int
tinytest_get_verbosity_(void)
{
return opt_verbosity;
}
void
tinytest_set_test_failed_(void)
{
if (opt_verbosity <= 0 && cur_test_name) {
if (opt_verbosity==0) puts("");
printf("%s%s: ", cur_test_prefix, cur_test_name);
cur_test_name = NULL;
}
cur_test_outcome = 0;
}
void
tinytest_set_test_skipped_(void)
{
if (cur_test_outcome==OK)
cur_test_outcome = SKIP;
}
char *
tinytest_format_hex_(const void *val_, unsigned long len)
{
const unsigned char *val = val_;
char *result, *cp;
size_t i;
if (!val)
return strdup("null");
if (!(result = malloc(len*2+1)))
return strdup("<allocation failure>");
cp = result;
for (i=0;i<len;++i) {
*cp++ = "0123456789ABCDEF"[val[i] >> 4];
*cp++ = "0123456789ABCDEF"[val[i] & 0x0f];
}
*cp = 0;
return result;
}
| apache-2.0 |
JasonRuonanWang/ADIOS2 | testing/adios2/engine/bp/operations/TestBPWriteReadZfpComplex.cpp | 1 | 14447 | /*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* TestBPWriteReadZfpComplex.cpp
*
* Created on: Jun 18, 2021
* Author: Jason Wang
*/
#include <adios2.h>
#include <cmath>
#include <gtest/gtest.h>
#include <numeric>
#include <thread>
using namespace adios2;
std::string ioName = "TestIO";
std::string fileName = "TestBPWriteReadZfpComplex";
std::string accuracy = "0.01";
class BPEngineTest : public ::testing::Test
{
public:
BPEngineTest() = default;
};
template <class T>
void PrintData(const T *data, const size_t step, const Dims &start,
const Dims &count)
{
size_t size = std::accumulate(count.begin(), count.end(), 1,
std::multiplies<size_t>());
std::cout << "Step: " << step << " Size:" << size << "\n";
size_t printsize = 128;
if (size < printsize)
{
printsize = size;
}
int s = 0;
for (size_t i = 0; i < printsize; ++i)
{
++s;
std::cout << data[i] << " ";
if (s == count[1])
{
std::cout << std::endl;
s = 0;
}
}
std::cout << "]" << std::endl;
}
template <class T>
void GenData(std::vector<std::complex<T>> &data, const size_t step,
const Dims &start, const Dims &count, const Dims &shape)
{
if (start.size() == 2)
{
for (size_t i = 0; i < count[0]; ++i)
{
for (size_t j = 0; j < count[1]; ++j)
{
data[i * count[1] + j] =
(i + start[1]) * shape[1] + j + start[0] +
std::stof(accuracy) * 0.00001 * (T)step;
}
}
}
}
template <class T>
void GenData(std::vector<T> &data, const size_t step, const Dims &start,
const Dims &count, const Dims &shape)
{
if (start.size() == 2)
{
for (size_t i = 0; i < count[0]; ++i)
{
for (size_t j = 0; j < count[1]; ++j)
{
data[i * count[1] + j] =
(i + start[1]) * shape[1] + j + start[0] +
std::stof(accuracy) * 0.00001 * (T)step;
}
}
}
}
template <class T>
void VerifyData(const std::complex<T> *data, size_t step, const Dims &start,
const Dims &count, const Dims &shape, bool &compressed)
{
size_t size = std::accumulate(count.begin(), count.end(), 1,
std::multiplies<size_t>());
std::vector<std::complex<T>> tmpdata(size);
GenData(tmpdata, step, start, count, shape);
for (size_t i = 0; i < size; ++i)
{
ASSERT_EQ(std::abs(data[i].real() - tmpdata[i].real()) <
std::stof(accuracy),
true);
ASSERT_EQ(std::abs(data[i].imag() - tmpdata[i].imag()) <
std::stof(accuracy),
true);
if (data[i].real() != tmpdata[i].real() ||
data[i].imag() != tmpdata[i].imag())
{
compressed = true;
}
}
}
template <class T>
void VerifyData(const T *data, size_t step, const Dims &start,
const Dims &count, const Dims &shape, bool &compressed)
{
size_t size = std::accumulate(count.begin(), count.end(), 1,
std::multiplies<size_t>());
std::vector<T> tmpdata(size);
GenData(tmpdata, step, start, count, shape);
for (size_t i = 0; i < size; ++i)
{
ASSERT_EQ(std::abs((double)(data[i] - tmpdata[i])) <
std::stof(accuracy),
true);
if (data[i] != tmpdata[i])
{
compressed = true;
}
}
}
void Writer(const Dims &shape, const Dims &start, const Dims &count,
const size_t steps)
{
size_t datasize = std::accumulate(count.begin(), count.end(), 1,
std::multiplies<size_t>());
#if ADIOS2_USE_MPI
adios2::ADIOS adios(MPI_COMM_WORLD);
#else
adios2::ADIOS adios;
#endif
adios2::IO io = adios.DeclareIO(ioName);
std::vector<char> myChars(datasize);
std::vector<unsigned char> myUChars(datasize);
std::vector<short> myShorts(datasize);
std::vector<unsigned short> myUShorts(datasize);
std::vector<int> myInts(datasize);
std::vector<unsigned int> myUInts(datasize);
std::vector<float> myFloats(datasize);
std::vector<double> myDoubles(datasize);
std::vector<std::complex<float>> myComplexes(datasize);
std::vector<std::complex<double>> myDComplexes(datasize);
auto bpChars = io.DefineVariable<char>("bpChars", shape, start, count);
auto bpUChars =
io.DefineVariable<unsigned char>("bpUChars", shape, start, count);
auto bpShorts = io.DefineVariable<short>("bpShorts", shape, start, count);
auto bpUShorts =
io.DefineVariable<unsigned short>("bpUShorts", shape, start, count);
auto bpInts = io.DefineVariable<int>("bpInts", shape, start, count);
auto bpUInts =
io.DefineVariable<unsigned int>("bpUInts", shape, start, count);
auto bpFloats = io.DefineVariable<float>("bpFloats", shape, start, count);
adios2::Operator zfpOp =
adios.DefineOperator("zfpCompressor", adios2::ops::LossyZFP);
bpFloats.AddOperation(zfpOp, {{"accuracy", accuracy}});
auto bpDoubles =
io.DefineVariable<double>("bpDoubles", shape, start, count);
bpDoubles.AddOperation(zfpOp, {{"accuracy", accuracy}});
auto bpComplexes = io.DefineVariable<std::complex<float>>(
"bpComplexes", shape, start, count);
bpComplexes.AddOperation(zfpOp, {{"accuracy", accuracy}});
auto bpDComplexes = io.DefineVariable<std::complex<double>>(
"bpDComplexes", shape, start, count);
bpDComplexes.AddOperation(zfpOp, {{"accuracy", accuracy}});
io.DefineAttribute<int>("AttInt", 110);
adios2::Engine writerEngine = io.Open(fileName, adios2::Mode::Write);
for (int i = 0; i < static_cast<int>(steps); ++i)
{
writerEngine.BeginStep();
GenData(myChars, i, start, count, shape);
GenData(myUChars, i, start, count, shape);
GenData(myShorts, i, start, count, shape);
GenData(myUShorts, i, start, count, shape);
GenData(myInts, i, start, count, shape);
GenData(myUInts, i, start, count, shape);
GenData(myFloats, i, start, count, shape);
GenData(myDoubles, i, start, count, shape);
GenData(myComplexes, i, start, count, shape);
GenData(myDComplexes, i, start, count, shape);
writerEngine.Put(bpChars, myChars.data(), adios2::Mode::Sync);
writerEngine.Put(bpUChars, myUChars.data(), adios2::Mode::Sync);
writerEngine.Put(bpShorts, myShorts.data(), adios2::Mode::Sync);
writerEngine.Put(bpUShorts, myUShorts.data(), adios2::Mode::Sync);
writerEngine.Put(bpInts, myInts.data(), adios2::Mode::Sync);
writerEngine.Put(bpUInts, myUInts.data(), adios2::Mode::Sync);
writerEngine.Put(bpFloats, myFloats.data(), adios2::Mode::Sync);
writerEngine.Put(bpDoubles, myDoubles.data(), adios2::Mode::Sync);
writerEngine.Put(bpComplexes, myComplexes.data(), adios2::Mode::Sync);
writerEngine.Put(bpDComplexes, myDComplexes.data(), adios2::Mode::Sync);
writerEngine.EndStep();
}
writerEngine.Close();
}
void Reader(const Dims &shape, const Dims &start, const Dims &count,
const size_t steps)
{
#if ADIOS2_USE_MPI
adios2::ADIOS adios(MPI_COMM_WORLD);
#else
adios2::ADIOS adios;
#endif
adios2::IO io = adios.DeclareIO(ioName);
adios2::Engine readerEngine = io.Open(fileName, adios2::Mode::Read);
size_t datasize = std::accumulate(count.begin(), count.end(), 1,
std::multiplies<size_t>());
std::vector<char> myChars(datasize);
std::vector<unsigned char> myUChars(datasize);
std::vector<short> myShorts(datasize);
std::vector<unsigned short> myUShorts(datasize);
std::vector<int> myInts(datasize);
std::vector<unsigned int> myUInts(datasize);
std::vector<float> myFloats(datasize);
std::vector<double> myDoubles(datasize);
std::vector<std::complex<float>> myComplexes(datasize);
std::vector<std::complex<double>> myDComplexes(datasize);
size_t currentStep;
bool floatCompressed = false;
bool doubleCompressed = false;
bool complexCompressed = false;
bool dcomplexCompressed = false;
bool otherCompressed = false;
while (true)
{
adios2::StepStatus status = readerEngine.BeginStep();
if (status == adios2::StepStatus::OK)
{
const auto &vars = io.AvailableVariables();
ASSERT_EQ(vars.size(), 10);
currentStep = readerEngine.CurrentStep();
GenData(myChars, currentStep, start, count, shape);
GenData(myUChars, currentStep, start, count, shape);
GenData(myShorts, currentStep, start, count, shape);
GenData(myUShorts, currentStep, start, count, shape);
GenData(myInts, currentStep, start, count, shape);
GenData(myUInts, currentStep, start, count, shape);
GenData(myFloats, currentStep, start, count, shape);
GenData(myDoubles, currentStep, start, count, shape);
GenData(myComplexes, currentStep, start, count, shape);
GenData(myDComplexes, currentStep, start, count, shape);
adios2::Variable<char> bpChars =
io.InquireVariable<char>("bpChars");
adios2::Variable<unsigned char> bpUChars =
io.InquireVariable<unsigned char>("bpUChars");
adios2::Variable<short> bpShorts =
io.InquireVariable<short>("bpShorts");
adios2::Variable<unsigned short> bpUShorts =
io.InquireVariable<unsigned short>("bpUShorts");
adios2::Variable<int> bpInts = io.InquireVariable<int>("bpInts");
adios2::Variable<unsigned int> bpUInts =
io.InquireVariable<unsigned int>("bpUInts");
adios2::Variable<float> bpFloats =
io.InquireVariable<float>("bpFloats");
adios2::Variable<double> bpDoubles =
io.InquireVariable<double>("bpDoubles");
adios2::Variable<std::complex<float>> bpComplexes =
io.InquireVariable<std::complex<float>>("bpComplexes");
adios2::Variable<std::complex<double>> bpDComplexes =
io.InquireVariable<std::complex<double>>("bpDComplexes");
auto charsBlocksInfo = readerEngine.AllStepsBlocksInfo(bpChars);
bpChars.SetSelection({start, count});
bpUChars.SetSelection({start, count});
bpShorts.SetSelection({start, count});
bpUShorts.SetSelection({start, count});
bpInts.SetSelection({start, count});
bpUInts.SetSelection({start, count});
bpFloats.SetSelection({start, count});
bpDoubles.SetSelection({start, count});
bpComplexes.SetSelection({start, count});
bpDComplexes.SetSelection({start, count});
readerEngine.Get(bpChars, myChars.data(), adios2::Mode::Sync);
readerEngine.Get(bpUChars, myUChars.data(), adios2::Mode::Sync);
readerEngine.Get(bpShorts, myShorts.data(), adios2::Mode::Sync);
readerEngine.Get(bpUShorts, myUShorts.data(), adios2::Mode::Sync);
readerEngine.Get(bpInts, myInts.data(), adios2::Mode::Sync);
readerEngine.Get(bpUInts, myUInts.data(), adios2::Mode::Sync);
readerEngine.Get(bpFloats, myFloats.data(), adios2::Mode::Sync);
readerEngine.Get(bpDoubles, myDoubles.data(), adios2::Mode::Sync);
readerEngine.Get(bpComplexes, myComplexes.data(),
adios2::Mode::Sync);
readerEngine.Get(bpDComplexes, myDComplexes.data(),
adios2::Mode::Sync);
VerifyData(myChars.data(), currentStep, start, count, shape,
otherCompressed);
VerifyData(myUChars.data(), currentStep, start, count, shape,
otherCompressed);
VerifyData(myShorts.data(), currentStep, start, count, shape,
otherCompressed);
VerifyData(myUShorts.data(), currentStep, start, count, shape,
otherCompressed);
VerifyData(myInts.data(), currentStep, start, count, shape,
otherCompressed);
VerifyData(myUInts.data(), currentStep, start, count, shape,
otherCompressed);
VerifyData(myFloats.data(), currentStep, start, count, shape,
floatCompressed);
VerifyData(myDoubles.data(), currentStep, start, count, shape,
doubleCompressed);
VerifyData(myComplexes.data(), currentStep, start, count, shape,
complexCompressed);
VerifyData(myDComplexes.data(), currentStep, start, count, shape,
dcomplexCompressed);
readerEngine.EndStep();
}
else if (status == adios2::StepStatus::EndOfStream)
{
break;
}
else if (status == adios2::StepStatus::NotReady)
{
continue;
}
}
auto attInt = io.InquireAttribute<int>("AttInt");
ASSERT_EQ(110, attInt.Data()[0]);
ASSERT_EQ(otherCompressed, false);
ASSERT_EQ(floatCompressed, true);
ASSERT_EQ(doubleCompressed, true);
ASSERT_EQ(complexCompressed, true);
ASSERT_EQ(dcomplexCompressed, true);
readerEngine.Close();
}
TEST_F(BPEngineTest, ZfpComplex)
{
int mpiRank = 0, mpiSize = 1;
#if ADIOS2_USE_MPI
MPI_Comm_rank(MPI_COMM_WORLD, &mpiRank);
MPI_Comm_size(MPI_COMM_WORLD, &mpiSize);
#endif
Dims shape = {(size_t)mpiSize, 100};
Dims start = {(size_t)mpiRank, 0};
Dims count = {1, 80};
size_t steps = 500;
Writer(shape, start, count, steps);
#if ADIOS2_USE_MPI
MPI_Barrier(MPI_COMM_WORLD);
#endif
Reader(shape, start, count, steps);
}
int main(int argc, char **argv)
{
#if ADIOS2_USE_MPI
MPI_Init(nullptr, nullptr);
#endif
int result;
::testing::InitGoogleTest(&argc, argv);
result = RUN_ALL_TESTS();
#if ADIOS2_USE_MPI
MPI_Finalize();
#endif
return result;
}
| apache-2.0 |
HotwireDotCom/dns-active-cache | src/dns_utils.c | 1 | 7046 | /**********************************************************************
// Copyright (c) 2015 Henry Seurer
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
**********************************************************************/
#define _GNU_SOURCE
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <stdio.h>
#include <stdarg.h>
#include <uuid/uuid.h>
#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
#endif
#include "dns_utils.h"
#include "dns_settings.h"
#include "dns_string.h"
char *malloc_string(size_t size) {
char *string = malloc(size + 1);
if (string) {
memset(string, 0, size + 1);
}
return string;
}
void free_string(char *string) {
if (string != NULL) {
free(string);
}
}
char **malloc_string_array(size_t count) {
size_t size = count * sizeof(char *);
void *buffer = malloc(size);
if (buffer) {
memset(buffer, 0, size);
}
return buffer;
}
void free_string_array(char **resolvers, size_t count) {
for (size_t i = 0; i < count; i++) {
free_string(resolvers[i]);
}
}
void *memory_clear(void *p, size_t n) {
if (NULL != p) {
memset(p, 0, n);
}
return p;
}
void current_utc_time(struct timespec *ts) {
memory_clear(ts, sizeof(struct timespec));
#ifdef __MACH__
// OS X does not have clock_gettime, use clock_get_time
//
clock_serv_t c_clock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &c_clock);
clock_get_time(c_clock, &mts);
mach_port_deallocate(mach_task_self(), c_clock);
ts->tv_sec = mts.tv_sec;
ts->tv_nsec = mts.tv_nsec;
#else
// How everyone else does it.
//
clock_gettime(CLOCK_REALTIME, ts);
#endif
}
// call this function to start a nanosecond-resolution timer
//
struct timespec timer_start() {
struct timespec start_time;
current_utc_time(&start_time);
return start_time;
}
static const long long kNsPerSec = 1000000000;
// Convert timespec to nanoseconds
//
long long timespec_to_ns(const struct timespec *ts) {
long long base_ns = (long long) (ts->tv_sec) * kNsPerSec;
return base_ns + (long long) (ts->tv_nsec);
}
// call this function to end a timer, returning nanoseconds elapsed as a long
//
long long timer_end(struct timespec start_time) {
struct timespec end_time;
current_utc_time(&end_time);
return timespec_to_ns(&end_time) - timespec_to_ns(&start_time);
}
context_t create_context() {
context_t context;
memory_clear(&context, sizeof context);
uuid_generate(context.origination_uuid);
struct timespec now = timer_start();
context.start_time = timespec_to_ns(&now);
return context;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wuninitialized"
void create_output_header(dns_string_t *output, const char *status, const char *function, const char *file,
int line, context_t *context) {
// Build Context ID
//
uuid_string_t context_uuid_string;
memory_clear(context_uuid_string, sizeof(context_uuid_string));
long long time_diff = 0;
if (context) {
uuid_unparse(context->origination_uuid, context_uuid_string);
struct timespec now = timer_start();
time_diff = timespec_to_ns(&now) - context->start_time;
}
// Output the common header
//
dns_string_sprintf(output,
"service=dns_active_cache;context=%s;timediff=%lld;status=%s;location=%s:%d;function=%s;message=",
context_uuid_string,
time_diff,
status,
file,
line,
function);
}
#pragma clang diagnostic pop
void log_message(int log_level,
const char *function,
const char *file,
int line,
context_t *context,
const char *template, ...) {
char *message_type = NULL;
bool log_message;
switch (log_level) {
case LOG_EMERG:
case LOG_ALERT:
case LOG_CRIT:
case LOG_ERR:
case LOG_WARNING:
message_type = "ERROR";
log_message = true;
break;
case LOG_NOTICE:
case LOG_INFO:
message_type = "INFO";
log_message = dns_get_log_mode();
break;
case LOG_DEBUG:
default:
message_type = "DEBUG";
log_message = dns_get_log_mode();
break;
}
if (log_message) {
dns_string_ptr output = dns_string_new(1024);
create_output_header(output, message_type, function, file, line, context);
char *str;
va_list arg_list;
va_start(arg_list, template);
vasprintf(&str, template, arg_list);
va_end(arg_list);
if (str) {
dns_string_append_str(output, str);
free(str);
}
if (output && dns_get_daemon_process_id() == 0) {
switch (log_level) {
case LOG_EMERG:
case LOG_ALERT:
case LOG_CRIT:
case LOG_ERR:
case LOG_WARNING:
fprintf(stderr, "%s\n", dns_string_c_string(output));
fflush(stderr);
break;
case LOG_NOTICE:
case LOG_INFO:
case LOG_DEBUG:
default:
fprintf(stdout, "%s\n", dns_string_c_string(output));
fflush(stdout);
break;
}
}
syslog(log_level, "%s", dns_string_c_string(output));
dns_string_delete(output, true);
}
}
void create_logs() {
setlogmask(LOG_UPTO (LOG_DEBUG));
openlog("dns_active_cache", LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL0);
}
void close_logs() {
closelog();
}
| apache-2.0 |
mbedmicro/FlashAlgo | source/ti/CC3220SF/FlashPrg.c | 1 | 13432 | /* Flash OS Routines
* Copyright (c) 2009-2018 ARM Limited
*
* 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.
*/
/** @file FlashPrg.c */
#include "FlashOS.h"
#include "FlashPrg.h"
#include "inc/hw_types.h"
#include "inc/hw_flash_ctrl.h"
#include "inc/hw_memmap.h"
#include "inc/hw_gprcm.h"
#include "inc/hw_hib3p3.h"
#include "inc/prcm.h"
#include "inc/hw_apps_rcm.h"
#define HAVE_WRITE_BUFFER 1
//*****************************************************************************
// Global Peripheral clock and rest Registers
//*****************************************************************************
static const PRCM_PeriphRegs_t PRCM_PeriphRegsList[] =
{
{APPS_RCM_O_CAMERA_CLK_GATING, APPS_RCM_O_CAMERA_SOFT_RESET },
{APPS_RCM_O_MCASP_CLK_GATING, APPS_RCM_O_MCASP_SOFT_RESET },
{APPS_RCM_O_MMCHS_CLK_GATING, APPS_RCM_O_MMCHS_SOFT_RESET },
{APPS_RCM_O_MCSPI_A1_CLK_GATING, APPS_RCM_O_MCSPI_A1_SOFT_RESET },
{APPS_RCM_O_MCSPI_A2_CLK_GATING, APPS_RCM_O_MCSPI_A2_SOFT_RESET },
{APPS_RCM_O_UDMA_A_CLK_GATING, APPS_RCM_O_UDMA_A_SOFT_RESET },
{APPS_RCM_O_GPIO_A_CLK_GATING, APPS_RCM_O_GPIO_A_SOFT_RESET },
{APPS_RCM_O_GPIO_B_CLK_GATING, APPS_RCM_O_GPIO_B_SOFT_RESET },
{APPS_RCM_O_GPIO_C_CLK_GATING, APPS_RCM_O_GPIO_C_SOFT_RESET },
{APPS_RCM_O_GPIO_D_CLK_GATING, APPS_RCM_O_GPIO_D_SOFT_RESET },
{APPS_RCM_O_GPIO_E_CLK_GATING, APPS_RCM_O_GPIO_E_SOFT_RESET },
{APPS_RCM_O_WDOG_A_CLK_GATING, APPS_RCM_O_WDOG_A_SOFT_RESET },
{APPS_RCM_O_UART_A0_CLK_GATING, APPS_RCM_O_UART_A0_SOFT_RESET },
{APPS_RCM_O_UART_A1_CLK_GATING, APPS_RCM_O_UART_A1_SOFT_RESET },
{APPS_RCM_O_GPT_A0_CLK_GATING , APPS_RCM_O_GPT_A0_SOFT_RESET },
{APPS_RCM_O_GPT_A1_CLK_GATING, APPS_RCM_O_GPT_A1_SOFT_RESET },
{APPS_RCM_O_GPT_A2_CLK_GATING, APPS_RCM_O_GPT_A2_SOFT_RESET },
{APPS_RCM_O_GPT_A3_CLK_GATING, APPS_RCM_O_GPT_A3_SOFT_RESET },
{APPS_RCM_O_CRYPTO_CLK_GATING, APPS_RCM_O_CRYPTO_SOFT_RESET },
{APPS_RCM_O_MCSPI_S0_CLK_GATING, APPS_RCM_O_MCSPI_S0_SOFT_RESET },
{APPS_RCM_O_I2C_CLK_GATING, APPS_RCM_O_I2C_SOFT_RESET }
};
void UtilsDelay(unsigned long ulCount)
{
__asm("Count: SUBS ulCount, #1\n"
" BNE Count");
}
uint32_t Init(uint32_t adr, uint32_t clk, uint32_t fnc)
{
// Called to configure the SoC. Should enable clocks
// watchdogs, peripherals and anything else needed to
// access or program memory. Fnc parameter has meaning
// but currently isnt used in MSC programming routines
unsigned long ulRegValue;
//
// DIG DCDC LPDS ECO Enable
//
HWREG(0x4402F064) |= 0x800000;
//
// Enable hibernate ECO for PG 1.32 devices only. With this ECO enabled,
// any hibernate wakeup source will be kept maked until the device enters
// hibernate completely (analog + digital)
//
ulRegValue = HWREG(HIB3P3_BASE + HIB3P3_O_MEM_HIB_REG0);
UtilsDelay((80*200)/3);
//PRCMHIBRegWrite(HIB3P3_BASE + HIB3P3_O_MEM_HIB_REG0, ulRegValue | (1<<4));
HWREG(HIB3P3_BASE + HIB3P3_O_MEM_HIB_REG0) = ulRegValue | (1<<4);
UtilsDelay((80*200)/3);
//
// Handling the clock switching (for 1.32 only)
//
HWREG(0x4402E16C) |= 0x3C;
//
//Enable uDMA
//
//
// Enable the specified peripheral clocks, Nothing to be done for PRCM_ADC
// as it is a dummy define for pinmux utility code generation
//
if(PRCM_UDMA != PRCM_ADC)
{
HWREG(ARCM_BASE + PRCM_PeriphRegsList[PRCM_UDMA].ulClkReg) |= PRCM_RUN_MODE_CLK;
}
//
// Checking ROM Version less than 2.x.x.
// Only for driverlib backward compatibility
//
if( (HWREG(0x00000400) & 0xFFFF) < 2 )
{
//
// Set the default clock for camera
//
if(PRCM_UDMA == PRCM_CAMERA)
{
HWREG(ARCM_BASE + APPS_RCM_O_CAMERA_CLK_GEN) = 0x0404;
}
}
//
// Reset uDMA
volatile unsigned long ulDelay;
if( PRCM_UDMA != PRCM_DTHE)
{
//
// Assert the reset
//
HWREG(ARCM_BASE + PRCM_PeriphRegsList[PRCM_UDMA].ulRstReg)
|= 0x00000001;
//
// Delay a little bit.
//
for(ulDelay = 0; ulDelay < 16; ulDelay++)
{
}
//
// Deassert the reset
//
HWREG(ARCM_BASE+PRCM_PeriphRegsList[PRCM_UDMA].ulRstReg)
&= ~0x00000001;
}
//
//
// Disable uDMA
HWREG(ARCM_BASE + PRCM_PeriphRegsList[PRCM_UDMA].ulClkReg) &= ~PRCM_RUN_MODE_CLK;
//
// Enable RTC
//
unsigned long lWakeupStatus = (HWREG(GPRCM_BASE+ GPRCM_O_APPS_RESET_CAUSE) & 0xFF);
if(lWakeupStatus == PRCM_POWER_ON)
{
HWREG(0x4402F804) = PRCM_POWER_ON;
UtilsDelay((80*200)/3);
}
//
// SWD mode
//
if(((HWREG(0x4402F0C8) & 0xFF) == 0x2))
{
HWREG(0x4402E110) = ((HWREG(0x4402E110) & ~0xC0F) | 0x2);
HWREG(0x4402E114) = ((HWREG(0x4402E114) & ~0xC0F) | 0x2);
}
//
// Override JTAG mux
//
HWREG(0x4402E184) |= 0x2;
//
// DIG DCDC VOUT trim settings based on PROCESS INDICATOR
//
if(((HWREG(0x4402DC78) >> 22) & 0xF) == 0xE)
{
HWREG(0x4402F0B0) = ((HWREG(0x4402F0B0) & ~(0x00FC0000))|(0x32 << 18));
}
else
{
HWREG(0x4402F0B0) = ((HWREG(0x4402F0B0) & ~(0x00FC0000))|(0x29 << 18));
}
//
// Enable SOFT RESTART in case of DIG DCDC collapse
//
HWREG(0x4402FC74) &= ~(0x10000000);
//
// Required only if ROM version is lower than 2.x.x
//
if( (HWREG(0x00000400) & 0xFFFF) < 2 )
{
//
// Disable the sleep for ANA DCDC
//
HWREG(0x4402F0A8) |= 0x00000004 ;
}
else if( (HWREG(0x00000400) >> 16) >= 1 )
{
//
// Enable NWP force reset and HIB on WDT reset
// Enable direct boot path for flash
//
HWREG(OCP_SHARED_BASE + 0x00000188) |= ((7<<5) | 0x1);
if((HWREG(HIB3P3_BASE + HIB3P3_O_MEM_HIB_REG2) & 0x1) )
{
HWREG(HIB3P3_BASE + HIB3P3_O_MEM_HIB_REG2) &= ~0x1;
HWREG(OCP_SHARED_BASE + 0x00000188) |= (1<<9);
//
// Clear the RTC hib wake up source
//
HWREG(HIB3P3_BASE+HIB3P3_O_MEM_HIB_RTC_WAKE_EN) &= ~0x1;
//
// Reset RTC match value
//
HWREG(HIB3P3_BASE + HIB3P3_O_MEM_HIB_RTC_WAKE_LSW_CONF) = 0;
HWREG(HIB3P3_BASE + HIB3P3_O_MEM_HIB_RTC_WAKE_MSW_CONF) = 0;
}
}
unsigned long efuse_reg2;
unsigned long ulDevMajorVer, ulDevMinorVer;
//
// Read the device identification register
//
efuse_reg2= HWREG(GPRCM_BASE + GPRCM_O_GPRCM_EFUSE_READ_REG2);
//
// Read the ROM mojor and minor version
//
ulDevMajorVer = ((efuse_reg2 >> 28) & 0xF);
ulDevMinorVer = ((efuse_reg2 >> 24) & 0xF);
if(((ulDevMajorVer == 0x3) && (ulDevMinorVer == 0)) || (ulDevMajorVer < 0x3))
{
unsigned int Scratch, PreRegulatedMode;
// 0x4402F840 => 6th bit “1” indicates device is in pre-regulated mode.
PreRegulatedMode = (HWREG(0x4402F840) >> 6) & 1;
if( PreRegulatedMode)
{
Scratch = HWREG(0x4402F028);
Scratch &= 0xFFFFFF7F; // <7:7> = 0
HWREG(0x4402F028) = Scratch;
Scratch = HWREG(0x4402F010);
Scratch &= 0x0FFFFFFF; // <31:28> = 0
Scratch |= 0x10000000; // <31:28> = 1
HWREG(0x4402F010) = Scratch;
}
else
{
Scratch = HWREG(0x4402F024);
Scratch &= 0xFFFFFFF0; // <3:0> = 0
Scratch |= 0x00000001; // <3:0> = 1
Scratch &= 0xFFFFF0FF; // <11:8> = 0000
Scratch |= 0x00000500; // <11:8> = 0101
Scratch &= 0xFFFE7FFF; // <16:15> = 0000
Scratch |= 0x00010000; // <16:15> = 10
HWREG(0x4402F024) = Scratch;
Scratch = HWREG(0x4402F028);
Scratch &= 0xFFFFFF7F; // <7:7> = 0
Scratch &= 0x0FFFFFFF; // <31:28> = 0
Scratch &= 0xFF0FFFFF; // <23:20> = 0
Scratch |= 0x00300000; // <23:20> = 0011
Scratch &= 0xFFF0FFFF; // <19:16> = 0
Scratch |= 0x00030000; // <19:16> = 0011
HWREG(0x4402F028) = Scratch;
HWREG(0x4402F010) &= 0x0FFFFFFF; // <31:28> = 0
}
}
//
// Success.
//
return 0;
}
uint32_t UnInit(uint32_t fnc)
{
// When a session is complete this is called to powerdown
// communication channels and clocks that were enabled
// Fnc parameter has meaning but isnt used in MSC program
// routines
return 0;
}
uint32_t EraseChip(void)
{
// Execute a sequence that erases the entire of flash memory region
//
// Clear the flash access and error interrupts.
//
HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FCMISC) =
(FLASH_CTRL_FCMISC_AMISC | FLASH_CTRL_FCMISC_VOLTMISC |
FLASH_CTRL_FCMISC_ERMISC);
//
// Command the flash controller for mass erase.
//
HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMC) =
FLASH_CTRL_FMC_WRKEY | FLASH_CTRL_FMC_MERASE1;
//
// Wait until mass erase completes.
//
while(HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMC) & FLASH_CTRL_FMC_MERASE1)
{
}
//
// Return an error if an access violation or erase error occurred.
//
if(HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FCRIS)
& (FLASH_CTRL_FCRIS_ARIS | FLASH_CTRL_FCRIS_VOLTRIS |
FLASH_CTRL_FCRIS_ERRIS))
{
return 1;
}
//
// Success.
//
return 0;
}
uint32_t EraseSector(uint32_t adr)
{
// Execute a sequence that erases the sector that adr resides in
//
// Check the arguments.
//
//ASSERT(!(adr & (FLASH_CTRL_ERASE_SIZE - 1)));
//
// Clear the flash access and error interrupts.
//
HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FCMISC)
= (FLASH_CTRL_FCMISC_AMISC | FLASH_CTRL_FCMISC_VOLTMISC |
FLASH_CTRL_FCMISC_ERMISC);
// Erase the block.
//
HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMA) = adr;
HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMC)
= FLASH_CTRL_FMC_WRKEY | FLASH_CTRL_FMC_ERASE;
//
// Wait until the block has been erased.
//
while(HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMC) & FLASH_CTRL_FMC_ERASE)
{
}
//
// Return an error if an access violation or erase error occurred.
//
if(HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FCRIS)
& (FLASH_CTRL_FCRIS_ARIS | FLASH_CTRL_FCRIS_VOLTRIS |
FLASH_CTRL_FCRIS_ERRIS))
{
return(1);
}
//
// Success.
//
return(0);
}
uint32_t ProgramPage(uint32_t adr, uint32_t sz, uint32_t *buf)
{
// Program the contents of buf starting at adr for length of sz
//
// Check the arguments.
//
//ASSERT(!(adr & 3));
//ASSERT(!(sz & 3));
//
// Clear the flash access and error interrupts.
//
HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FCMISC)
= (FLASH_CTRL_FCMISC_AMISC | FLASH_CTRL_FCMISC_VOLTMISC |
FLASH_CTRL_FCMISC_INVDMISC | FLASH_CTRL_FCMISC_PROGMISC);
//
// See if this device has a write buffer.
//
while(sz)
{
//
// Set the address of this block of words. for 1 MB
//
HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMA) = adr & ~(0x7F);
//
// Loop over the words in this 32-word block.
//
while(((adr & 0x7C) ||
(HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FWBVAL) == 0)) &&
(sz != 0))
{
//
// Write this word into the write buffer.
//
HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FWBN
+ (adr & 0x7C)) = *buf++;
adr += 4;
sz -= 4;
}
//
// Program the contents of the write buffer into flash.
//
HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMC2)
= FLASH_CTRL_FMC2_WRKEY | FLASH_CTRL_FMC2_WRBUF;
//
// Wait until the write buffer has been programmed.
//
while(HWREG(FLASH_CONTROL_BASE + FLASH_CTRL_O_FMC2) & FLASH_CTRL_FMC2_WRBUF)
{
}
}
//
// Success.
//
return(0);
}
/*uint32_t BlankCheck(uint32_t adr, uint32_t sz, uint8_t pat)
{
// Check that the memory at address adr for length sz is
// empty or the same as pat
return 1;
}*/
/*
uint32_t Verify(uint32_t adr, uint32_t sz, uint32_t *buf)
{
// Given an adr and sz compare this against the content of buf
return 1;
}*/
| apache-2.0 |
openssl/openssl | crypto/x509/v3_ncons.c | 1 | 25776 | /*
* Copyright 2003-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/cryptlib.h"
#include "internal/numbers.h"
#include "internal/safe_math.h"
#include <stdio.h>
#include "crypto/asn1.h"
#include <openssl/asn1t.h>
#include <openssl/conf.h>
#include <openssl/x509v3.h>
#include <openssl/bn.h>
#include "crypto/x509.h"
#include "crypto/punycode.h"
#include "ext_dat.h"
OSSL_SAFE_MATH_SIGNED(int, int)
static void *v2i_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method,
X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *nval);
static int i2r_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method, void *a,
BIO *bp, int ind);
static int do_i2r_name_constraints(const X509V3_EXT_METHOD *method,
STACK_OF(GENERAL_SUBTREE) *trees, BIO *bp,
int ind, const char *name);
static int print_nc_ipadd(BIO *bp, ASN1_OCTET_STRING *ip);
static int nc_match(GENERAL_NAME *gen, NAME_CONSTRAINTS *nc);
static int nc_match_single(GENERAL_NAME *sub, GENERAL_NAME *gen);
static int nc_dn(const X509_NAME *sub, const X509_NAME *nm);
static int nc_dns(ASN1_IA5STRING *sub, ASN1_IA5STRING *dns);
static int nc_email(ASN1_IA5STRING *sub, ASN1_IA5STRING *eml);
static int nc_email_eai(ASN1_TYPE *emltype, ASN1_IA5STRING *base);
static int nc_uri(ASN1_IA5STRING *uri, ASN1_IA5STRING *base);
static int nc_ip(ASN1_OCTET_STRING *ip, ASN1_OCTET_STRING *base);
const X509V3_EXT_METHOD ossl_v3_name_constraints = {
NID_name_constraints, 0,
ASN1_ITEM_ref(NAME_CONSTRAINTS),
0, 0, 0, 0,
0, 0,
0, v2i_NAME_CONSTRAINTS,
i2r_NAME_CONSTRAINTS, 0,
NULL
};
ASN1_SEQUENCE(GENERAL_SUBTREE) = {
ASN1_SIMPLE(GENERAL_SUBTREE, base, GENERAL_NAME),
ASN1_IMP_OPT(GENERAL_SUBTREE, minimum, ASN1_INTEGER, 0),
ASN1_IMP_OPT(GENERAL_SUBTREE, maximum, ASN1_INTEGER, 1)
} ASN1_SEQUENCE_END(GENERAL_SUBTREE)
ASN1_SEQUENCE(NAME_CONSTRAINTS) = {
ASN1_IMP_SEQUENCE_OF_OPT(NAME_CONSTRAINTS, permittedSubtrees,
GENERAL_SUBTREE, 0),
ASN1_IMP_SEQUENCE_OF_OPT(NAME_CONSTRAINTS, excludedSubtrees,
GENERAL_SUBTREE, 1),
} ASN1_SEQUENCE_END(NAME_CONSTRAINTS)
IMPLEMENT_ASN1_ALLOC_FUNCTIONS(GENERAL_SUBTREE)
IMPLEMENT_ASN1_ALLOC_FUNCTIONS(NAME_CONSTRAINTS)
#define IA5_OFFSET_LEN(ia5base, offset) \
((ia5base)->length - ((unsigned char *)(offset) - (ia5base)->data))
/* Like memchr but for ASN1_IA5STRING. Additionally you can specify the
* starting point to search from
*/
# define ia5memchr(str, start, c) memchr(start, c, IA5_OFFSET_LEN(str, start))
/* Like memrrchr but for ASN1_IA5STRING */
static char *ia5memrchr(ASN1_IA5STRING *str, int c)
{
int i;
for (i = str->length; i > 0 && str->data[i - 1] != c; i--);
if (i == 0)
return NULL;
return (char *)&str->data[i - 1];
}
/*
* We cannot use strncasecmp here because that applies locale specific rules. It
* also doesn't work with ASN1_STRINGs that may have embedded NUL characters.
* For example in Turkish 'I' is not the uppercase character for 'i'. We need to
* do a simple ASCII case comparison ignoring the locale (that is why we use
* numeric constants below).
*/
static int ia5ncasecmp(const char *s1, const char *s2, size_t n)
{
for (; n > 0; n--, s1++, s2++) {
if (*s1 != *s2) {
unsigned char c1 = (unsigned char)*s1, c2 = (unsigned char)*s2;
/* Convert to lower case */
if (c1 >= 0x41 /* A */ && c1 <= 0x5A /* Z */)
c1 += 0x20;
if (c2 >= 0x41 /* A */ && c2 <= 0x5A /* Z */)
c2 += 0x20;
if (c1 == c2)
continue;
if (c1 < c2)
return -1;
/* c1 > c2 */
return 1;
}
}
return 0;
}
static void *v2i_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval)
{
int i;
CONF_VALUE tval, *val;
STACK_OF(GENERAL_SUBTREE) **ptree = NULL;
NAME_CONSTRAINTS *ncons = NULL;
GENERAL_SUBTREE *sub = NULL;
ncons = NAME_CONSTRAINTS_new();
if (ncons == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
for (i = 0; i < sk_CONF_VALUE_num(nval); i++) {
val = sk_CONF_VALUE_value(nval, i);
if (HAS_PREFIX(val->name, "permitted") && val->name[9]) {
ptree = &ncons->permittedSubtrees;
tval.name = val->name + 10;
} else if (HAS_PREFIX(val->name, "excluded") && val->name[8]) {
ptree = &ncons->excludedSubtrees;
tval.name = val->name + 9;
} else {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_SYNTAX);
goto err;
}
tval.value = val->value;
sub = GENERAL_SUBTREE_new();
if (sub == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
if (!v2i_GENERAL_NAME_ex(sub->base, method, ctx, &tval, 1)) {
ERR_raise(ERR_LIB_X509V3, ERR_R_X509V3_LIB);
goto err;
}
if (*ptree == NULL)
*ptree = sk_GENERAL_SUBTREE_new_null();
if (*ptree == NULL || !sk_GENERAL_SUBTREE_push(*ptree, sub)) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
goto err;
}
sub = NULL;
}
return ncons;
err:
NAME_CONSTRAINTS_free(ncons);
GENERAL_SUBTREE_free(sub);
return NULL;
}
static int i2r_NAME_CONSTRAINTS(const X509V3_EXT_METHOD *method, void *a,
BIO *bp, int ind)
{
NAME_CONSTRAINTS *ncons = a;
do_i2r_name_constraints(method, ncons->permittedSubtrees,
bp, ind, "Permitted");
if (ncons->permittedSubtrees && ncons->excludedSubtrees)
BIO_puts(bp, "\n");
do_i2r_name_constraints(method, ncons->excludedSubtrees,
bp, ind, "Excluded");
return 1;
}
static int do_i2r_name_constraints(const X509V3_EXT_METHOD *method,
STACK_OF(GENERAL_SUBTREE) *trees,
BIO *bp, int ind, const char *name)
{
GENERAL_SUBTREE *tree;
int i;
if (sk_GENERAL_SUBTREE_num(trees) > 0)
BIO_printf(bp, "%*s%s:\n", ind, "", name);
for (i = 0; i < sk_GENERAL_SUBTREE_num(trees); i++) {
if (i > 0)
BIO_puts(bp, "\n");
tree = sk_GENERAL_SUBTREE_value(trees, i);
BIO_printf(bp, "%*s", ind + 2, "");
if (tree->base->type == GEN_IPADD)
print_nc_ipadd(bp, tree->base->d.ip);
else
GENERAL_NAME_print(bp, tree->base);
}
return 1;
}
static int print_nc_ipadd(BIO *bp, ASN1_OCTET_STRING *ip)
{
/* ip->length should be 8 or 32 and len1 == len2 == 4 or len1 == len2 == 16 */
int len1 = ip->length >= 16 ? 16 : ip->length >= 4 ? 4 : ip->length;
int len2 = ip->length - len1;
char *ip1 = ossl_ipaddr_to_asc(ip->data, len1);
char *ip2 = ossl_ipaddr_to_asc(ip->data + len1, len2);
int ret = ip1 != NULL && ip2 != NULL
&& BIO_printf(bp, "IP:%s/%s", ip1, ip2) > 0;
OPENSSL_free(ip1);
OPENSSL_free(ip2);
return ret;
}
#define NAME_CHECK_MAX (1 << 20)
static int add_lengths(int *out, int a, int b)
{
int err = 0;
/* sk_FOO_num(NULL) returns -1 but is effectively 0 when iterating. */
if (a < 0)
a = 0;
if (b < 0)
b = 0;
*out = safe_add_int(a, b, &err);
return !err;
}
/*-
* Check a certificate conforms to a specified set of constraints.
* Return values:
* X509_V_OK: All constraints obeyed.
* X509_V_ERR_PERMITTED_VIOLATION: Permitted subtree violation.
* X509_V_ERR_EXCLUDED_VIOLATION: Excluded subtree violation.
* X509_V_ERR_SUBTREE_MINMAX: Min or max values present and matching type.
* X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE: Unsupported constraint type.
* X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX: bad unsupported constraint syntax.
* X509_V_ERR_UNSUPPORTED_NAME_SYNTAX: bad or unsupported syntax of name
*/
int NAME_CONSTRAINTS_check(X509 *x, NAME_CONSTRAINTS *nc)
{
int r, i, name_count, constraint_count;
X509_NAME *nm;
nm = X509_get_subject_name(x);
/*
* Guard against certificates with an excessive number of names or
* constraints causing a computationally expensive name constraints check.
*/
if (!add_lengths(&name_count, X509_NAME_entry_count(nm),
sk_GENERAL_NAME_num(x->altname))
|| !add_lengths(&constraint_count,
sk_GENERAL_SUBTREE_num(nc->permittedSubtrees),
sk_GENERAL_SUBTREE_num(nc->excludedSubtrees))
|| (name_count > 0 && constraint_count > NAME_CHECK_MAX / name_count))
return X509_V_ERR_UNSPECIFIED;
if (X509_NAME_entry_count(nm) > 0) {
GENERAL_NAME gntmp;
gntmp.type = GEN_DIRNAME;
gntmp.d.directoryName = nm;
r = nc_match(&gntmp, nc);
if (r != X509_V_OK)
return r;
gntmp.type = GEN_EMAIL;
/* Process any email address attributes in subject name */
for (i = -1;;) {
const X509_NAME_ENTRY *ne;
i = X509_NAME_get_index_by_NID(nm, NID_pkcs9_emailAddress, i);
if (i == -1)
break;
ne = X509_NAME_get_entry(nm, i);
gntmp.d.rfc822Name = X509_NAME_ENTRY_get_data(ne);
if (gntmp.d.rfc822Name->type != V_ASN1_IA5STRING)
return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
r = nc_match(&gntmp, nc);
if (r != X509_V_OK)
return r;
}
}
for (i = 0; i < sk_GENERAL_NAME_num(x->altname); i++) {
GENERAL_NAME *gen = sk_GENERAL_NAME_value(x->altname, i);
r = nc_match(gen, nc);
if (r != X509_V_OK)
return r;
}
return X509_V_OK;
}
static int cn2dnsid(ASN1_STRING *cn, unsigned char **dnsid, size_t *idlen)
{
int utf8_length;
unsigned char *utf8_value;
int i;
int isdnsname = 0;
/* Don't leave outputs uninitialized */
*dnsid = NULL;
*idlen = 0;
/*-
* Per RFC 6125, DNS-IDs representing internationalized domain names appear
* in certificates in A-label encoded form:
*
* https://tools.ietf.org/html/rfc6125#section-6.4.2
*
* The same applies to CNs which are intended to represent DNS names.
* However, while in the SAN DNS-IDs are IA5Strings, as CNs they may be
* needlessly encoded in 16-bit Unicode. We perform a conversion to UTF-8
* to ensure that we get an ASCII representation of any CNs that are
* representable as ASCII, but just not encoded as ASCII. The UTF-8 form
* may contain some non-ASCII octets, and that's fine, such CNs are not
* valid legacy DNS names.
*
* Note, 'int' is the return type of ASN1_STRING_to_UTF8() so that's what
* we must use for 'utf8_length'.
*/
if ((utf8_length = ASN1_STRING_to_UTF8(&utf8_value, cn)) < 0)
return X509_V_ERR_OUT_OF_MEM;
/*
* Some certificates have had names that include a *trailing* NUL byte.
* Remove these harmless NUL characters. They would otherwise yield false
* alarms with the following embedded NUL check.
*/
while (utf8_length > 0 && utf8_value[utf8_length - 1] == '\0')
--utf8_length;
/* Reject *embedded* NULs */
if (memchr(utf8_value, 0, utf8_length) != NULL) {
OPENSSL_free(utf8_value);
return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
}
/*
* XXX: Deviation from strict DNS name syntax, also check names with '_'
* Check DNS name syntax, any '-' or '.' must be internal,
* and on either side of each '.' we can't have a '-' or '.'.
*
* If the name has just one label, we don't consider it a DNS name. This
* means that "CN=sometld" cannot be precluded by DNS name constraints, but
* that is not a problem.
*/
for (i = 0; i < utf8_length; ++i) {
unsigned char c = utf8_value[i];
if ((c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z')
|| (c >= '0' && c <= '9')
|| c == '_')
continue;
/* Dot and hyphen cannot be first or last. */
if (i > 0 && i < utf8_length - 1) {
if (c == '-')
continue;
/*
* Next to a dot the preceding and following characters must not be
* another dot or a hyphen. Otherwise, record that the name is
* plausible, since it has two or more labels.
*/
if (c == '.'
&& utf8_value[i + 1] != '.'
&& utf8_value[i - 1] != '-'
&& utf8_value[i + 1] != '-') {
isdnsname = 1;
continue;
}
}
isdnsname = 0;
break;
}
if (isdnsname) {
*dnsid = utf8_value;
*idlen = (size_t)utf8_length;
return X509_V_OK;
}
OPENSSL_free(utf8_value);
return X509_V_OK;
}
/*
* Check CN against DNS-ID name constraints.
*/
int NAME_CONSTRAINTS_check_CN(X509 *x, NAME_CONSTRAINTS *nc)
{
int r, i;
const X509_NAME *nm = X509_get_subject_name(x);
ASN1_STRING stmp;
GENERAL_NAME gntmp;
stmp.flags = 0;
stmp.type = V_ASN1_IA5STRING;
gntmp.type = GEN_DNS;
gntmp.d.dNSName = &stmp;
/* Process any commonName attributes in subject name */
for (i = -1;;) {
X509_NAME_ENTRY *ne;
ASN1_STRING *cn;
unsigned char *idval;
size_t idlen;
i = X509_NAME_get_index_by_NID(nm, NID_commonName, i);
if (i == -1)
break;
ne = X509_NAME_get_entry(nm, i);
cn = X509_NAME_ENTRY_get_data(ne);
/* Only process attributes that look like hostnames */
if ((r = cn2dnsid(cn, &idval, &idlen)) != X509_V_OK)
return r;
if (idlen == 0)
continue;
stmp.length = idlen;
stmp.data = idval;
r = nc_match(&gntmp, nc);
OPENSSL_free(idval);
if (r != X509_V_OK)
return r;
}
return X509_V_OK;
}
/*
* Return nonzero if the GeneralSubtree has valid 'minimum' field
* (must be absent or 0) and valid 'maximum' field (must be absent).
*/
static int nc_minmax_valid(GENERAL_SUBTREE *sub) {
BIGNUM *bn = NULL;
int ok = 1;
if (sub->maximum)
ok = 0;
if (sub->minimum) {
bn = ASN1_INTEGER_to_BN(sub->minimum, NULL);
if (bn == NULL || !BN_is_zero(bn))
ok = 0;
BN_free(bn);
}
return ok;
}
static int nc_match(GENERAL_NAME *gen, NAME_CONSTRAINTS *nc)
{
GENERAL_SUBTREE *sub;
int i, r, match = 0;
/*
* We need to compare not gen->type field but an "effective" type because
* the otherName field may contain EAI email address treated specially
* according to RFC 8398, section 6
*/
int effective_type = ((gen->type == GEN_OTHERNAME) &&
(OBJ_obj2nid(gen->d.otherName->type_id) ==
NID_id_on_SmtpUTF8Mailbox)) ? GEN_EMAIL : gen->type;
/*
* Permitted subtrees: if any subtrees exist of matching the type at
* least one subtree must match.
*/
for (i = 0; i < sk_GENERAL_SUBTREE_num(nc->permittedSubtrees); i++) {
sub = sk_GENERAL_SUBTREE_value(nc->permittedSubtrees, i);
if (effective_type != sub->base->type)
continue;
if (!nc_minmax_valid(sub))
return X509_V_ERR_SUBTREE_MINMAX;
/* If we already have a match don't bother trying any more */
if (match == 2)
continue;
if (match == 0)
match = 1;
r = nc_match_single(gen, sub->base);
if (r == X509_V_OK)
match = 2;
else if (r != X509_V_ERR_PERMITTED_VIOLATION)
return r;
}
if (match == 1)
return X509_V_ERR_PERMITTED_VIOLATION;
/* Excluded subtrees: must not match any of these */
for (i = 0; i < sk_GENERAL_SUBTREE_num(nc->excludedSubtrees); i++) {
sub = sk_GENERAL_SUBTREE_value(nc->excludedSubtrees, i);
if (effective_type != sub->base->type)
continue;
if (!nc_minmax_valid(sub))
return X509_V_ERR_SUBTREE_MINMAX;
r = nc_match_single(gen, sub->base);
if (r == X509_V_OK)
return X509_V_ERR_EXCLUDED_VIOLATION;
else if (r != X509_V_ERR_PERMITTED_VIOLATION)
return r;
}
return X509_V_OK;
}
static int nc_match_single(GENERAL_NAME *gen, GENERAL_NAME *base)
{
switch (gen->type) {
case GEN_OTHERNAME:
/*
* We are here only when we have SmtpUTF8 name,
* so we match the value of othername with base->d.rfc822Name
*/
return nc_email_eai(gen->d.otherName->value, base->d.rfc822Name);
case GEN_DIRNAME:
return nc_dn(gen->d.directoryName, base->d.directoryName);
case GEN_DNS:
return nc_dns(gen->d.dNSName, base->d.dNSName);
case GEN_EMAIL:
return nc_email(gen->d.rfc822Name, base->d.rfc822Name);
case GEN_URI:
return nc_uri(gen->d.uniformResourceIdentifier,
base->d.uniformResourceIdentifier);
case GEN_IPADD:
return nc_ip(gen->d.iPAddress, base->d.iPAddress);
default:
return X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE;
}
}
/*
* directoryName name constraint matching. The canonical encoding of
* X509_NAME makes this comparison easy. It is matched if the subtree is a
* subset of the name.
*/
static int nc_dn(const X509_NAME *nm, const X509_NAME *base)
{
/* Ensure canonical encodings are up to date. */
if (nm->modified && i2d_X509_NAME(nm, NULL) < 0)
return X509_V_ERR_OUT_OF_MEM;
if (base->modified && i2d_X509_NAME(base, NULL) < 0)
return X509_V_ERR_OUT_OF_MEM;
if (base->canon_enclen > nm->canon_enclen)
return X509_V_ERR_PERMITTED_VIOLATION;
if (memcmp(base->canon_enc, nm->canon_enc, base->canon_enclen))
return X509_V_ERR_PERMITTED_VIOLATION;
return X509_V_OK;
}
static int nc_dns(ASN1_IA5STRING *dns, ASN1_IA5STRING *base)
{
char *baseptr = (char *)base->data;
char *dnsptr = (char *)dns->data;
/* Empty matches everything */
if (base->length == 0)
return X509_V_OK;
if (dns->length < base->length)
return X509_V_ERR_PERMITTED_VIOLATION;
/*
* Otherwise can add zero or more components on the left so compare RHS
* and if dns is longer and expect '.' as preceding character.
*/
if (dns->length > base->length) {
dnsptr += dns->length - base->length;
if (*baseptr != '.' && dnsptr[-1] != '.')
return X509_V_ERR_PERMITTED_VIOLATION;
}
if (ia5ncasecmp(baseptr, dnsptr, base->length))
return X509_V_ERR_PERMITTED_VIOLATION;
return X509_V_OK;
}
/*
* This function implements comparison between ASCII/U-label in emltype
* and A-label in base according to RFC 8398, section 6.
* Convert base to U-label and ASCII-parts of domain names, for base
* Octet-to-octet comparison of `emltype` and `base` hostname parts
* (ASCII-parts should be compared in case-insensitive manner)
*/
static int nc_email_eai(ASN1_TYPE *emltype, ASN1_IA5STRING *base)
{
ASN1_UTF8STRING *eml;
char *baseptr = NULL;
const char *emlptr;
const char *emlat;
char ulabel[256];
size_t size = sizeof(ulabel);
int ret = X509_V_OK;
size_t emlhostlen;
/* We do not accept embedded NUL characters */
if (base->length > 0 && memchr(base->data, 0, base->length) != NULL)
return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
/* 'base' may not be NUL terminated. Create a copy that is */
baseptr = OPENSSL_strndup((char *)base->data, base->length);
if (baseptr == NULL)
return X509_V_ERR_OUT_OF_MEM;
if (emltype->type != V_ASN1_UTF8STRING) {
ret = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
goto end;
}
eml = emltype->value.utf8string;
emlptr = (char *)eml->data;
emlat = ia5memrchr(eml, '@');
if (emlat == NULL) {
ret = X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
goto end;
}
/* Special case: initial '.' is RHS match */
if (*baseptr == '.') {
ulabel[0] = '.';
if (ossl_a2ulabel(baseptr, ulabel + 1, size - 1) <= 0) {
ret = X509_V_ERR_UNSPECIFIED;
goto end;
}
if ((size_t)eml->length > strlen(ulabel)) {
emlptr += eml->length - strlen(ulabel);
/* X509_V_OK */
if (ia5ncasecmp(ulabel, emlptr, strlen(ulabel)) == 0)
goto end;
}
ret = X509_V_ERR_PERMITTED_VIOLATION;
goto end;
}
if (ossl_a2ulabel(baseptr, ulabel, size) <= 0) {
ret = X509_V_ERR_UNSPECIFIED;
goto end;
}
/* Just have hostname left to match: case insensitive */
emlptr = emlat + 1;
emlhostlen = IA5_OFFSET_LEN(eml, emlptr);
if (emlhostlen != strlen(ulabel)
|| ia5ncasecmp(ulabel, emlptr, emlhostlen) != 0) {
ret = X509_V_ERR_PERMITTED_VIOLATION;
goto end;
}
end:
OPENSSL_free(baseptr);
return ret;
}
static int nc_email(ASN1_IA5STRING *eml, ASN1_IA5STRING *base)
{
const char *baseptr = (char *)base->data;
const char *emlptr = (char *)eml->data;
const char *baseat = ia5memrchr(base, '@');
const char *emlat = ia5memrchr(eml, '@');
size_t basehostlen, emlhostlen;
if (!emlat)
return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
/* Special case: initial '.' is RHS match */
if (!baseat && base->length > 0 && (*baseptr == '.')) {
if (eml->length > base->length) {
emlptr += eml->length - base->length;
if (ia5ncasecmp(baseptr, emlptr, base->length) == 0)
return X509_V_OK;
}
return X509_V_ERR_PERMITTED_VIOLATION;
}
/* If we have anything before '@' match local part */
if (baseat) {
if (baseat != baseptr) {
if ((baseat - baseptr) != (emlat - emlptr))
return X509_V_ERR_PERMITTED_VIOLATION;
if (memchr(baseptr, 0, baseat - baseptr) ||
memchr(emlptr, 0, emlat - emlptr))
return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
/* Case sensitive match of local part */
if (strncmp(baseptr, emlptr, emlat - emlptr))
return X509_V_ERR_PERMITTED_VIOLATION;
}
/* Position base after '@' */
baseptr = baseat + 1;
}
emlptr = emlat + 1;
basehostlen = IA5_OFFSET_LEN(base, baseptr);
emlhostlen = IA5_OFFSET_LEN(eml, emlptr);
/* Just have hostname left to match: case insensitive */
if (basehostlen != emlhostlen || ia5ncasecmp(baseptr, emlptr, emlhostlen))
return X509_V_ERR_PERMITTED_VIOLATION;
return X509_V_OK;
}
static int nc_uri(ASN1_IA5STRING *uri, ASN1_IA5STRING *base)
{
const char *baseptr = (char *)base->data;
const char *hostptr = (char *)uri->data;
const char *p = ia5memchr(uri, (char *)uri->data, ':');
int hostlen;
/* Check for foo:// and skip past it */
if (p == NULL
|| IA5_OFFSET_LEN(uri, p) < 3
|| p[1] != '/'
|| p[2] != '/')
return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
hostptr = p + 3;
/* Determine length of hostname part of URI */
/* Look for a port indicator as end of hostname first */
p = ia5memchr(uri, hostptr, ':');
/* Otherwise look for trailing slash */
if (p == NULL)
p = ia5memchr(uri, hostptr, '/');
if (p == NULL)
hostlen = IA5_OFFSET_LEN(uri, hostptr);
else
hostlen = p - hostptr;
if (hostlen == 0)
return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
/* Special case: initial '.' is RHS match */
if (base->length > 0 && *baseptr == '.') {
if (hostlen > base->length) {
p = hostptr + hostlen - base->length;
if (ia5ncasecmp(p, baseptr, base->length) == 0)
return X509_V_OK;
}
return X509_V_ERR_PERMITTED_VIOLATION;
}
if ((base->length != (int)hostlen)
|| ia5ncasecmp(hostptr, baseptr, hostlen))
return X509_V_ERR_PERMITTED_VIOLATION;
return X509_V_OK;
}
static int nc_ip(ASN1_OCTET_STRING *ip, ASN1_OCTET_STRING *base)
{
int hostlen, baselen, i;
unsigned char *hostptr, *baseptr, *maskptr;
hostptr = ip->data;
hostlen = ip->length;
baseptr = base->data;
baselen = base->length;
/* Invalid if not IPv4 or IPv6 */
if (!((hostlen == 4) || (hostlen == 16)))
return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
if (!((baselen == 8) || (baselen == 32)))
return X509_V_ERR_UNSUPPORTED_NAME_SYNTAX;
/* Do not match IPv4 with IPv6 */
if (hostlen * 2 != baselen)
return X509_V_ERR_PERMITTED_VIOLATION;
maskptr = base->data + hostlen;
/* Considering possible not aligned base ipAddress */
/* Not checking for wrong mask definition: i.e.: 255.0.255.0 */
for (i = 0; i < hostlen; i++)
if ((hostptr[i] & maskptr[i]) != (baseptr[i] & maskptr[i]))
return X509_V_ERR_PERMITTED_VIOLATION;
return X509_V_OK;
}
| apache-2.0 |
JoyIfBam5/aws-sdk-cpp | aws-cpp-sdk-rekognition/source/model/CompareFacesMatch.cpp | 1 | 1802 | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
#include <aws/rekognition/model/CompareFacesMatch.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Rekognition
{
namespace Model
{
CompareFacesMatch::CompareFacesMatch() :
m_similarity(0.0),
m_similarityHasBeenSet(false),
m_faceHasBeenSet(false)
{
}
CompareFacesMatch::CompareFacesMatch(JsonView jsonValue) :
m_similarity(0.0),
m_similarityHasBeenSet(false),
m_faceHasBeenSet(false)
{
*this = jsonValue;
}
CompareFacesMatch& CompareFacesMatch::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("Similarity"))
{
m_similarity = jsonValue.GetDouble("Similarity");
m_similarityHasBeenSet = true;
}
if(jsonValue.ValueExists("Face"))
{
m_face = jsonValue.GetObject("Face");
m_faceHasBeenSet = true;
}
return *this;
}
JsonValue CompareFacesMatch::Jsonize() const
{
JsonValue payload;
if(m_similarityHasBeenSet)
{
payload.WithDouble("Similarity", m_similarity);
}
if(m_faceHasBeenSet)
{
payload.WithObject("Face", m_face.Jsonize());
}
return payload;
}
} // namespace Model
} // namespace Rekognition
} // namespace Aws
| apache-2.0 |
nosredna/mbed-tpl | DISCO_F051R8/mbed/targets/hal/TARGET_STM/TARGET_DISCO_F051R8/analogin_api.c | 1 | 5262 | /* mbed Microcontroller Library
* Copyright (c) 2014, STMicroelectronics
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics 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 "analogin_api.h"
#include "wait_api.h"
#if DEVICE_ANALOGIN
#include "cmsis.h"
#include "pinmap.h"
#include "error.h"
static const PinMap PinMap_ADC[] = {
{PA_0, ADC_1, STM_PIN_DATA(GPIO_Mode_AN, GPIO_OType_PP, GPIO_PuPd_NOPULL, 0xFF)}, // ADC_IN0
{PA_1, ADC_1, STM_PIN_DATA(GPIO_Mode_AN, GPIO_OType_PP, GPIO_PuPd_NOPULL, 0xFF)}, // ADC_IN1
{PA_4, ADC_1, STM_PIN_DATA(GPIO_Mode_AN, GPIO_OType_PP, GPIO_PuPd_NOPULL, 0xFF)}, // ADC_IN4
{PB_0, ADC_1, STM_PIN_DATA(GPIO_Mode_AN, GPIO_OType_PP, GPIO_PuPd_NOPULL, 0xFF)}, // ADC_IN8
{PC_1, ADC_1, STM_PIN_DATA(GPIO_Mode_AN, GPIO_OType_PP, GPIO_PuPd_NOPULL, 0xFF)}, // ADC_IN11
{PC_0, ADC_1, STM_PIN_DATA(GPIO_Mode_AN, GPIO_OType_PP, GPIO_PuPd_NOPULL, 0xFF)}, // ADC_IN10
{NC, NC, 0}
};
int adc_inited = 0;
void analogin_init(analogin_t *obj, PinName pin) {
ADC_TypeDef *adc;
ADC_InitTypeDef ADC_InitStructure;
// Get the peripheral name (ADC_1, ADC_2...) from the pin and assign it to the object
obj->adc = (ADCName)pinmap_peripheral(pin, PinMap_ADC);
if (obj->adc == (ADCName)NC) {
error("ADC pin mapping failed");
}
// Configure GPIO
pinmap_pinout(pin, PinMap_ADC);
// Save pin number for the read function
obj->pin = pin;
// The ADC initialization is done once
if (adc_inited == 0) {
adc_inited = 1;
// Get ADC registers structure address
adc = (ADC_TypeDef *)(obj->adc);
// Enable ADC clock
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);
// Configure ADC
ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b;
ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;
ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;
ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_T1_TRGO;
ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
ADC_InitStructure.ADC_ScanDirection = ADC_ScanDirection_Upward;
ADC_Init(adc, &ADC_InitStructure);
// Calibrate ADC
ADC_GetCalibrationFactor(adc);
// Enable ADC
ADC_Cmd(adc, ENABLE);
}
}
static inline uint16_t adc_read(analogin_t *obj) {
// Get ADC registers structure address
ADC_TypeDef *adc = (ADC_TypeDef *)(obj->adc);
adc->CHSELR = 0; // Clear all channels first
// Configure ADC channel
switch (obj->pin) {
case PA_0:
ADC_ChannelConfig(adc, ADC_Channel_0, ADC_SampleTime_7_5Cycles);
break;
case PA_1:
ADC_ChannelConfig(adc, ADC_Channel_1, ADC_SampleTime_7_5Cycles);
break;
case PA_4:
ADC_ChannelConfig(adc, ADC_Channel_4, ADC_SampleTime_7_5Cycles);
break;
case PB_0:
ADC_ChannelConfig(adc, ADC_Channel_8, ADC_SampleTime_7_5Cycles);
break;
case PC_1:
ADC_ChannelConfig(adc, ADC_Channel_11, ADC_SampleTime_7_5Cycles);
break;
case PC_0:
ADC_ChannelConfig(adc, ADC_Channel_10, ADC_SampleTime_7_5Cycles);
break;
default:
return 0;
}
while(!ADC_GetFlagStatus(adc, ADC_FLAG_ADRDY)); // Wait ADC ready
ADC_StartOfConversion(adc); // Start conversion
while(ADC_GetFlagStatus(adc, ADC_FLAG_EOC) == RESET); // Wait end of conversion
return(ADC_GetConversionValue(adc)); // Get conversion value
}
uint16_t analogin_read_u16(analogin_t *obj) {
return(adc_read(obj));
}
float analogin_read(analogin_t *obj) {
uint16_t value = adc_read(obj);
return (float)value * (1.0f / (float)0xFFF); // 12 bits range
}
#endif
| apache-2.0 |
jim-b/ECCSI-SAKKE | es-demo-2.c | 1 | 31913 | /******************************************************************************/
/* Main/ test program 2. */
/* */
/* Copyright 2015 Jim Buller */
/* */
/* 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. */
/******************************************************************************/
/******************************************************************************/
/**
* @brief
* Main program 2 - Non RFC values, alice and bob different and different
* community. More of a real world example; Charlie creates a SSV (Shared
* Secret Value) and then produces an encrypted (for Dylan) version of this,
* the encapsulated data. Charlie then Signs the encapsulated data. Dylan can
* now check (verify) that Charlie really send it the message, then decrypt
* the encapsulated data to retrieve the SSV. Now, Charlie and Dylan both know
* the SSV and can set about encrypting their communications.
*
* @file
* Main program 2.
*/
/******************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <eccsi.h>
#include <sakke.h>
#include <mikeySakkeParameters.h>
#include <communityParameters.h>
#include <esprng.h>
#include <global.h>
#define ES_MAIN_SECTION_NAME "(ES-MAIN) " /*!< Section name output */
#define ES_USE_RFC_VALUES /*!< Comment this out to NOT use RFC values. */
#define SSV_LEN 16 /*!< The length of an SSV in bytes. */
#define RND_J_LEN 32 /*!< The length of random 'j' in bytes. */
/***************************************************************************//**
* Example of how to add a community (community.mikey-sakke.org).
*
* Data created with sister project (also on GitHub) KMS.
*
* @return ES_SUCCESS or ES_FAILURE
*****************************************************************************/
short main_addExampleCommunity() {
short ret_val = ES_FAILURE;
char *pub_enc_key = NULL; /* Z_T */
char *pub_auth_key = NULL; /* KPAK */
uint8_t *KPAK = NULL;
size_t KPAK_len = 0;
uint8_t *Z = NULL;
size_t Z_len = 0;
/**************************************************************************/
/* Init. */
/**************************************************************************/
pub_auth_key =
strdup("04253587" "2D7931C6" "891210FF" "2CDFFD06"
"FD464107" "AC5F819E" "5EACC8AC" "D4BBA806"
"72C813BA" "18955F4E" "A37D9BE3" "DD9FAFED"
"38BD1BF9" "A9DF42B8" "FD3D52E1" "C64FB62B"
"E8");
pub_enc_key =
strdup("0478475A" "19DB9038" "50E4402D" "01629185"
"B58971DB" "CCB08CA2" "7AECEE50" "DFA2C981"
"DFEF96CA" "AB8F449C" "CADC0966" "7FC5AC0C"
"28B335CC" "7D18A013" "5482E97C" "8E38FA40"
"0C517734" "7CC4E7B1" "128A7015" "EFF23788"
"77CF4BD2" "BBAF911A" "DD63D9FC" "56018134"
"B3D83330" "D12C981A" "A1955951" "CCF4F55A"
"231D69C8" "3EE82D92" "8EC0DFE7" "80237C90"
"D93414D5" "0EEC3F11" "99CD9B06" "1C477CDA"
"717AD07F" "152EF956" "ADD52C2F" "2FE3B66D"
"862040D6" "9D10E6E6" "4F095A57" "E5AB1261"
"541DF307" "B965243C" "0F053420" "A92007D5"
"21B83F3C" "91F290E8" "BDB0BE03" "BF6B404A"
"3539D030" "A4438B82" "244099DF" "90F74332"
"B8058462" "A37FF4DD" "5FC73253" "A2892FC6"
"7B08205B" "D87EE768" "6ED7C67F" "B801F3A8"
"C0");
utils_convertHexStringToOctetString((char *)pub_auth_key,
strlen((char *)pub_auth_key)/2, &KPAK, &KPAK_len);
utils_convertHexStringToOctetString((char *)pub_enc_key,
strlen((char *)pub_enc_key)/2, &Z, &Z_len);
if (!community_store(
NULL, /* Optional version */
(uint8_t *)"community.mikey-sakke.org",
/* Mandatory cert_uri - community */
(uint8_t *)"kms.mikey-sakke.org",
/* Mandatory kms_uri - kms. */
NULL, /* Optional issuer */
NULL, /* Optional valid_from */
NULL, /* Optional valid_to */
0, /* Optional revoked */
NULL, /* Optional user_id_format */
Z, /* Mandatory pub_enc_key - AKA 'Z'. */
Z_len, /* Mandatory pub_enc_key len. */
KPAK, /* Mandatory pub_auth_key - 'KPAK'. */
KPAK_len, /* Mandatory pub_auth_key len. */
NULL /* Optional kms_domain_list */
)) {
ret_val = ES_SUCCESS;
}
else {
ES_ERROR("%s:%s:%d - Failed to store community (KMS Certificate) data!",
__FILE__, __FUNCTION__, __LINE__);
}
/**************************************************************************/
/* Clear down */
/**************************************************************************/
if (NULL != pub_auth_key) {
memset(pub_auth_key, 0, strlen(pub_auth_key));
free(pub_auth_key);
}
if (NULL != pub_enc_key) {
memset(pub_enc_key, 0, strlen(pub_enc_key));
free(pub_enc_key);
}
if (NULL != KPAK) {
memset(KPAK, 0, KPAK_len);
free(KPAK);
}
if (NULL != Z) {
memset(Z, 0, Z_len);
free(Z);
}
return ret_val;
} /* main_addExampleCommunity */
/***************************************************************************//**
* Add User Charlie
*
* Data created with sister project (also on GitHub) KMS.
*
* @return ES_SUCCESS or ES_FAILURE
******************************************************************************/
short main_addExampleUserCharlie() {
uint8_t ret_val = ES_FAILURE;
uint8_t *community = NULL;
uint8_t *date = NULL;
uint8_t *uri = NULL;
uint8_t *id = NULL;
size_t id_len = 0;
char *ssk = NULL;
char *rsk = NULL;
char *pvt = NULL;
uint8_t *SSK = NULL;
size_t SSK_len = 0;
uint8_t *RSK = NULL;
size_t RSK_len = 0;
uint8_t *PVT = NULL;
size_t PVT_len = 0;
/**************************************************************************/
/* Init. */
/**************************************************************************/
community = (uint8_t *)strdup("community.mikey-sakke.org");
date = (uint8_t *)strdup("2015-04");
uri = (uint8_t *)strdup("tel:+441111111111");
id_len = strlen((char *)date) + strlen((char *)uri) + 2;
/* 2 is for NULL separator plus NULL termninal as
* per RFC 6507 Appendix A, Page 13, 'ID'.
*/
id = (uint8_t *)calloc(1, id_len);
strcpy((char *)id, (char *)date);
strcat((char *)id+strlen((char *)id)+1, (char *)uri);
/**************************************************************************/
/* Values from KMS for SSK(private), RSK(private) and PVT (public). */
/**************************************************************************/
ssk = strdup("EF78C601" "CE73934C" "BFA1D578" "E34E4E3E"
"3FCBAA8F" "DC8EE0B4" "36DD34E9" "71DD72D7");
rsk = strdup("041BB681" "A2008151" "EE7A788A" "ADBFA170"
"8745FE05" "94987AA2" "D4111410" "A98DDA8A"
"78DA6767" "4AD22533" "ADC20490" "1D72DBF2"
"0A01384F" "FB7799A3" "18E4160A" "34352A1B"
"66575EB7" "53F14C2D" "2292608A" "38344650"
"AA252745" "2CC29A1A" "C66027D7" "19714C38"
"AE5601E3" "035B4B93" "7C3B8B8E" "1C1FDEAB"
"6D466FE1" "5E3A65E0" "572F0912" "D0E9CD44"
"B60D812D" "1EAA9B30" "370394ED" "0791EDEE"
"34B151C8" "92802B6E" "65750F28" "DEFE0028"
"46B2DA19" "D052B6CC" "F4F3C6ED" "C24722A4"
"FF4F1F36" "59ECED52" "BE3592E8" "18A04A99"
"598CCE1A" "EA56694B" "75B4665D" "58D3F91E"
"3A2F613A" "B6D3D80E" "5FB5D090" "0988E072"
"04CA5D33" "CE29829D" "7F1A72A8" "BD0D8F2F"
"DF2C26BB" "34DD25E3" "B3015490" "34A23F4F"
"5B");
pvt = strdup("041D2EFB" "DDBB4E00" "C31F7CD8" "6FFA6CA3"
"BDD1F0C9" "93C113FB" "2A10622C" "FA8328BB"
"DAF14480" "2672D0CC" "EF9747E6" "0EEAE222"
"F68A92ED" "815E523C" "5CC045B8" "06C1883E"
"D0");
utils_convertHexStringToOctetString((char *)ssk, strlen((char *)ssk)/2,
&SSK, &SSK_len);
utils_convertHexStringToOctetString((char *)rsk, strlen((char *)rsk)/2,
&RSK, &RSK_len);
utils_convertHexStringToOctetString((char *)pvt, strlen((char *)pvt)/2,
&PVT, &PVT_len);
/***************************************************************************
*! Store User Details.
*
* RSK will be validated during save.
* SSK will be validated during save (and Hash created).
* Hash created during validate-SSK will also be saved to storage.
**************************************************************************/
if (user_store((uint8_t *)date, (uint8_t *)uri, (uint8_t *)community,
SSK, SSK_len, RSK, RSK_len, PVT, PVT_len)) {
/* This call can return ES_SAKKE_ERROR_RSK_VALIDATION_FAILED or
* ES_ECCSI_ERROR_SSK_VALIDATION_FAILED as well as ES_SUCCESS, or,
* ES_FAILURE.
*/
ES_ERROR("%s:%s:%d - New user Key Mat was NOT stored!",
__FILE__, __FUNCTION__, __LINE__);
}
else {
ret_val = ES_SUCCESS;
}
/* community_outputKMSCertificate(community); */
/* user_outputParameterSets(id, id_len, community); */
/**************************************************************************/
/* Clear down */
/**************************************************************************/
if (NULL != community) {
memset(community, 0, strlen((char *)community));
free(community);
}
if (NULL != date) {
memset(date, 0, strlen((char *)date));
free(date);
}
if (NULL != uri) {
memset(uri, 0, strlen((char *)uri));
free(uri);
}
if (NULL != id) {
memset(id, 0, strlen((char *)id));
free(id);
}
if (NULL != ssk) {
memset(ssk, 0, strlen((char *)ssk));
free(ssk);
}
if (NULL != rsk) {
memset(rsk, 0, strlen((char *)rsk));
free(rsk);
}
if (NULL != pvt) {
memset(pvt, 0, strlen((char *)pvt));
free(pvt);
}
if (NULL != SSK) {
memset(SSK, 0, SSK_len);
free(SSK);
}
if (NULL != RSK) {
memset(RSK, 0, RSK_len);
free(RSK);
}
if (NULL != PVT) {
memset(PVT, 0, PVT_len);
free(PVT);
}
return ret_val;
} /* main_addExampleUserCharlie */
/***************************************************************************//**
* Add User Dylan
*
* Data created with sister project (also on GitHub) KMS.
*
* @return ES_SUCCESS or ES_FAILURE
******************************************************************************/
short main_addExampleUserDylan() {
uint8_t ret_val = ES_FAILURE;
uint8_t *community = NULL;
uint8_t *date = NULL;
uint8_t *uri = NULL;
uint8_t *id = NULL;
size_t id_len = 0;
char *ssk = NULL;
char *rsk = NULL;
char *pvt = NULL;
uint8_t *SSK = NULL;
size_t SSK_len = 0;
uint8_t *RSK = NULL;
size_t RSK_len = 0;
uint8_t *PVT = NULL;
size_t PVT_len = 0;
/**************************************************************************/
/* Init. */
/**************************************************************************/
community = (uint8_t *)strdup("community.mikey-sakke.org");
date = (uint8_t *)strdup("2015-04");
uri = (uint8_t *)strdup("tel:+442222222222");
id_len = strlen((char *)date) + strlen((char *)uri) + 2;
/* 2 is for NULL separator plus NULL termninal as
* per RFC 6507 Appendix A, Page 13, 'ID'.
*/
id = (uint8_t *)calloc(1, id_len);
strcpy((char *)id, (char *)date);
strcat((char *)id+strlen((char *)id)+1, (char *)uri);
/**************************************************************************/
/* Values from KMS for SSK(private), RSK(private) and PVT (public). */
/**************************************************************************/
ssk = strdup("133AB0D7" "920D0D16" "FF11870E" "9B8ED29C"
"D759C547" "FEA1BAA3" "189AABFD" "91D1EFE8");
rsk = strdup("045096DC" "BDB29B2D" "A3580EC9" "6CF1F50E"
"0D348EA5" "F69F6B53" "7626B469" "79662B0E"
"D645CD9B" "AD35D547" "8574D882" "D55B604B"
"1B0CFE60" "28C8C618" "6EDD9079" "8A77F3C7"
"A9FD09F8" "37211069" "C01A640A" "20B81F31"
"BDAF641C" "B2C9EAFB" "9838FB38" "5C78463E"
"4780BD4D" "135CED1F" "FB6D8D7F" "088015A1"
"57576550" "7669A6DC" "A9585D63" "00709F75"
"75149282" "CBD698BC" "44B8FC19" "D057ADFE"
"B5E7A379" "5013598D" "C5EDEF55" "39F2C98A"
"C2E2027B" "D6C564B3" "92A728FB" "EE59359A"
"2E1B5AD0" "4AA80936" "13A307D6" "E3D75CC2"
"599C0D02" "FD2C737D" "ED82946D" "7CFB9791"
"452C90B6" "62DA5007" "25FB433B" "6F54D16C"
"6AAD3D29" "ABABB689" "675FE898" "00A0FF33"
"B8F58633" "7A931A9F" "3BA5E91A" "A55E183C"
"AE");
pvt = strdup("04FD3CDA" "286E41DF" "C2AACFE7" "9911727E"
"2314FA7A" "66FDA655" "BBA5C5FE" "9AFF4777"
"20479E8D" "999CFBED" "32028AFE" "B6C19DF0"
"BCBA44AD" "F2FE95D4" "985749F9" "54CB4634"
"27");
utils_convertHexStringToOctetString((char *)ssk, strlen((char *)ssk)/2,
&SSK, &SSK_len);
utils_convertHexStringToOctetString((char *)rsk, strlen((char *)rsk)/2,
&RSK, &RSK_len);
utils_convertHexStringToOctetString((char *)pvt, strlen((char *)pvt)/2,
&PVT, &PVT_len);
/***************************************************************************
* Store User Details.
*
* RSK will be validated during save.
* SSK will be validated during save (and Hash created).
* Hash created during validate-SSK will also be saved to storage.
**************************************************************************/
if (user_store((uint8_t *)date, (uint8_t *)uri, (uint8_t *)community,
SSK, SSK_len, RSK, RSK_len, PVT, PVT_len)) {
/* This call can return ES_SAKKE_ERROR_RSK_VALIDATION_FAILED or
* ES_ECCSI_ERROR_SSK_VALIDATION_FAILED as well as ES_SUCCESS, or,
* ES_FAILURE.
*/
ES_ERROR("%s:%s:%d - New user Key Mat was NOT stored!",
__FILE__, __FUNCTION__, __LINE__);
}
else {
ret_val = ES_SUCCESS;
}
/* community_outputKMSCertificate(community); */
/* user_outputParameterSets(id, id_len, community); */
/**************************************************************************/
/* Clear down */
/**************************************************************************/
if (NULL != community) {
memset(community, 0, strlen((char *)community));
free(community);
}
if (NULL != date) {
memset(date, 0, strlen((char *)date));
free(date);
}
if (NULL != uri) {
memset(uri, 0, strlen((char *)uri));
free(uri);
}
if (NULL != id) {
memset(id, 0, strlen((char *)id));
free(id);
}
if (NULL != ssk) {
memset(ssk, 0, strlen((char *)ssk));
free(ssk);
}
if (NULL != rsk) {
memset(rsk, 0, strlen((char *)rsk));
free(rsk);
}
if (NULL != pvt) {
memset(pvt, 0, strlen((char *)pvt));
free(pvt);
}
if (NULL != SSK) {
memset(SSK, 0, SSK_len);
free(SSK);
}
if (NULL != RSK) {
memset(RSK, 0, RSK_len);
free(RSK);
}
if (NULL != PVT) {
memset(PVT, 0, PVT_len);
free(PVT);
}
return ret_val;
} /* main_addExampleUserDylan */
/***************************************************************************//**
* Initialise all the Mikey-Sakke data structures in the correct order.
*
* MUST be called before ANY Mikey-Sakke processing.
*
* @return ES_SUCCESS or ES_FAILURE
*****************************************************************************/
static short main_initialiseMSInCorrectOrder() {
short ret_val = ES_FAILURE;
/*************************************************************************/
/* Mikey-Sakke Parameters */
/*************************************************************************/
ES_DEBUG("%s ****************************************", ES_MAIN_SECTION_NAME);
ES_DEBUG("%s * Create Mikey-Sakke Parameter List(s) *", ES_MAIN_SECTION_NAME);
ES_DEBUG("%s * Obtained and stored by Alice and Bob *", ES_MAIN_SECTION_NAME);
ES_DEBUG("%s ****************************************", ES_MAIN_SECTION_NAME);
if (ms_initParameterSets()) {
ES_ERROR("%s:%s:%d - Mikey Sakke Parameter Set initialisation failed. Check logs for errors!",
__FILE__, __FUNCTION__, __LINE__);
}
else {
/* If you want to see the parameter sets - ms_outputParameterSets(); */
/*********************************************************************/
/* Community Parameters */
/*********************************************************************/
ES_DEBUG("%s ****************************************", ES_MAIN_SECTION_NAME);
ES_DEBUG("%s * Create Community Parameter List *", ES_MAIN_SECTION_NAME);
ES_DEBUG("%s * Obtained and stored by Alice and Bob *", ES_MAIN_SECTION_NAME);
ES_DEBUG("%s ****************************************", ES_MAIN_SECTION_NAME);
if (community_initStorage()) {
ES_ERROR("%s:%s:%d - Community initialisation failed. Check logs for errors!",
__FILE__, __FUNCTION__, __LINE__);
}
else {
/* If you want to see the community data
* community_outputParameterSets. Note however, all we have done
* is initialise. If there are no communities stored you will have
* to add one to see it, see main_addCommunity() (above).
*/
/******************************************************************/
/* User Accounts - no init required. */
/******************************************************************/
ret_val = ES_SUCCESS;
}
}
return ret_val;
} /* main_initialiseMSInCorrectOrder */
/***************************************************************************//**
* Main example code - Charlie establishes a SSV for dialogs with Dylan.
*
* @param[in] argc Number of arguments.
* @param[in] argv[] Array of arguments.
*
* @return Status code.
*****************************************************************************/
int main(int argc, char *argv[]) {
/* User Id's have a NULL between date and ID so we need len indication. */
uint8_t *charlie_id = NULL;
size_t charlie_id_len = 0;
uint8_t *dylan_id = NULL;
size_t dylan_id_len = 0;
uint8_t *community = NULL;
uint8_t *ssv_for_dylan = NULL;
size_t ssv_for_dylan_length = 0;
uint8_t *encapsulated_data = NULL;
size_t encapsulated_data_length = 0;
uint8_t *charlie_ssv = NULL;
uint8_t *signature = NULL;
size_t signature_len = 0;
unsigned int loop = 0;
uint8_t *j_rnd = NULL;
BIGNUM *j_rnd_bn = NULL;
ES_INFO("The ECCSI/ SAKKE Software Version is <%s>", softwareVersion());
/**************************************************************************/
/* Set up user id's - Note the RFC use the same ID for Alice and Bob.. */
/**************************************************************************/
charlie_id = (uint8_t *)calloc(1, 255); /* Some space */
strcpy((char *)charlie_id, "2015-04");
strcat((char *)charlie_id+strlen((char *)charlie_id)+1, "tel:+441111111111");
charlie_id_len = strlen((char *)charlie_id) +
strlen((char *)charlie_id+(strlen((char *)charlie_id)+1))
+2; /* Null separator for date+id and NULL terminator. */
dylan_id = (uint8_t *)calloc(1, 255); /* Some space */
strcpy((char *)dylan_id, "2015-04");
strcat((char *)dylan_id+strlen((char*)dylan_id)+1, "tel:+442222222222");
dylan_id_len = strlen((char *)dylan_id) +
strlen((char *)dylan_id+(strlen((char *)dylan_id)+1))
+2; /* Null separator for date+id and NULL terminator. */
/**************************************************************************/
/* Community name */
/**************************************************************************/
community = (uint8_t *)strdup("community.mikey-sakke.org");
/**************************************************************************/
/* Initialise internal storage structures !MUST! be called before any */
/* ECCSI/ SAKKE code is performed. */
/**************************************************************************/
main_initialiseMSInCorrectOrder();
/* If the community exists, it is overwritten/ updated. */
if (ES_SUCCESS != main_addExampleCommunity()) {
exit(1);
}
/* If the user exists, it is overwritten/ updated. For specific user
* deletion use user_remove.
*/
if (ES_SUCCESS != main_addExampleUserCharlie()) {
exit(1);
}
if (ES_SUCCESS != main_addExampleUserDylan()) {
exit(1);
}
/* If you want to repeat/ test this code, for instance with non RFC values
* you can modify the characteristics of this loop and comment out
* ES_USE_RFC_VALUES at the start of this file.
*/
for (loop=0; loop < 1; loop++) {
ES_INFO("%s Counter <%d>", ES_MAIN_SECTION_NAME, loop);
/**********************************************************************/
/* ACTING AS CHARLIE */
/**********************************************************************/
ES_INFO("%s *****************************************", ES_MAIN_SECTION_NAME);
ES_INFO("%s * CHARLIE *", ES_MAIN_SECTION_NAME);
ES_INFO("%s *****************************************", ES_MAIN_SECTION_NAME);
/* Charlie creates an SSV (Shared Secret Value) and constructs
* the Encapsulated Data (message).
*/
ES_PRNG(&charlie_ssv, SSV_LEN);
ES_INFO_PRINT_FORMATTED_OCTET_STRING(ES_MAIN_SECTION_NAME,
" Charlie creates a random SSV :", 8,
charlie_ssv, SSV_LEN);
ES_INFO("%s Charlie makes encapsulated data message", ES_MAIN_SECTION_NAME);
if (sakke_generateSakkeEncapsulatedData(
&encapsulated_data, &encapsulated_data_length,
dylan_id, dylan_id_len, /* Use the receiver's ID */
community,
charlie_ssv, SSV_LEN)) {
ES_ERROR("%s:%s:%d - SAKKE Encapsulated Data creation failed. Exiting!",
__FILE__, __FUNCTION__, __LINE__);
exit(1);
}
else {
/* Now we have the message (encapsulated data) let's sign it. */
/* First we need a random 'j' 1..q-1. As we do the checks here,
* we don't need to check the response from the sign request
*/
do {
ES_PRNG(&j_rnd, RND_J_LEN);
j_rnd_bn = BN_bin2bn((unsigned char *)j_rnd, RND_J_LEN, NULL);
if ((BN_cmp(j_rnd_bn, BN_value_one()) >= 0) &&
(BN_cmp(j_rnd_bn, community_getq_bn()) == -1)) {
BN_clear_free(j_rnd_bn);
j_rnd_bn = NULL;
break;
}
BN_clear_free(j_rnd_bn);
j_rnd_bn = NULL;
} while(1);
/* If you want to see that 'j' is definately random, uncomment
* the following line and recompile.
*/
/*ES_INFO_PRINT_FORMATTED_OCTET_STRING(ES_MAIN_SECTION_NAME,
* " Create a (random) 'j' value:", 8, j_rnd, j_rnd_len);
*/
/* Now we sign the (encapsulated data) message. */
if (NULL != signature) {
free(signature);
signature = NULL;
signature_len = 0;
}
ES_INFO("%s Charlie signs the message", ES_MAIN_SECTION_NAME);
if (eccsi_sign(
encapsulated_data, encapsulated_data_length,
charlie_id, charlie_id_len, /* Use the signer's ID */
community, j_rnd, RND_J_LEN, &signature, &signature_len)) {
ES_ERROR("%s:%s:%d - Sign failed. Exiting!",
__FILE__, __FUNCTION__, __LINE__);
exit(1);
}
ES_INFO("%s *****************************************", ES_MAIN_SECTION_NAME);
ES_INFO("%s * What CHARLIE sends to DYLAN >>>>>>>>> *", ES_MAIN_SECTION_NAME);
ES_INFO("%s *****************************************", ES_MAIN_SECTION_NAME);
ES_INFO_PRINT_FORMATTED_OCTET_STRING(ES_MAIN_SECTION_NAME,
" ECCSI Signature :", 8,
signature, signature_len);
ES_INFO_PRINT_FORMATTED_OCTET_STRING(ES_MAIN_SECTION_NAME,
" Encapsulated Data :", 8,
encapsulated_data, encapsulated_data_length);
}
/**********************************************************************/
/* ACTING AS DYLAN */
/**********************************************************************/
ES_INFO("%s *****************************************", ES_MAIN_SECTION_NAME);
ES_INFO("%s * DYLAN *", ES_MAIN_SECTION_NAME);
ES_INFO("%s *****************************************", ES_MAIN_SECTION_NAME);
ES_INFO("%s DYLAN verifies message from CHARLIE", ES_MAIN_SECTION_NAME);
if (eccsi_verify(encapsulated_data, encapsulated_data_length,
signature, signature_len,
charlie_id, charlie_id_len, /* Use the sender's ID */
community)) {
ES_ERROR("%s:%s:%d - Verification of received signed message failed. Exiting!",
__FILE__, __FUNCTION__, __LINE__);
ES_DEBUG("%s Signature NOT VERIFIED!", ES_MAIN_SECTION_NAME);
exit(1);
}
ES_INFO("%s Signature VERIFIED", ES_MAIN_SECTION_NAME);
ES_INFO("%s - the message is from Charlie!", ES_MAIN_SECTION_NAME);
ES_INFO("%s DYLAN parses the Encapsulated Data", ES_MAIN_SECTION_NAME);
ES_INFO("%s to get the SSV (Shared Secret Value).", ES_MAIN_SECTION_NAME);
ssv_for_dylan = NULL;
if (sakke_extractSharedSecret(
encapsulated_data, encapsulated_data_length,
/* Use the receiver's ID */
dylan_id, dylan_id_len,
community,
&ssv_for_dylan, &ssv_for_dylan_length) == ES_SUCCESS) {
ES_INFO_PRINT_FORMATTED_OCTET_STRING(ES_MAIN_SECTION_NAME,
" SSV obtained/ used by Dylan:",
8, ssv_for_dylan, ssv_for_dylan_length);
}
else {
ES_DEBUG("%s Failed to parse encapsulated data", ES_MAIN_SECTION_NAME);
exit(1);
}
if (NULL != j_rnd) {
free(j_rnd);
j_rnd = NULL;
}
if (NULL != charlie_ssv) {
free(charlie_ssv);
charlie_ssv = NULL;
/* Do not reset length, used if regenerating ssv in loop. */
}
if (NULL != ssv_for_dylan) {
free(ssv_for_dylan);
ssv_for_dylan = NULL;
ssv_for_dylan_length = 0;
}
if (NULL != encapsulated_data) {
free(encapsulated_data);
encapsulated_data = NULL;
encapsulated_data_length = 0;
}
}
/* Cleanup */
community_deleteStorage();
ms_deleteParameterSets();
free(charlie_id);
free(dylan_id);
free(ssv_for_dylan);
free(encapsulated_data);
free(signature);
free(community);
free(charlie_ssv);
return 0;
} /* main */
/******************************************************************************/
/* End of file */
/******************************************************************************/
| apache-2.0 |
espressif/esp-idf | components/efuse/esp32/esp_efuse_utility.c | 1 | 11120 | /*
* SPDX-FileCopyrightText: 2017-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "esp_efuse_utility.h"
#include "soc/efuse_periph.h"
#include "hal/efuse_hal.h"
#include "esp_private/esp_clk.h"
#include "esp_log.h"
#include "assert.h"
#include "sdkconfig.h"
#include <sys/param.h>
static const char *TAG = "efuse";
#ifdef CONFIG_EFUSE_VIRTUAL
extern uint32_t virt_blocks[EFUSE_BLK_MAX][COUNT_EFUSE_REG_PER_BLOCK];
#endif // CONFIG_EFUSE_VIRTUAL
/*Range addresses to read blocks*/
const esp_efuse_range_addr_t range_read_addr_blocks[] = {
{EFUSE_BLK0_RDATA0_REG, EFUSE_BLK0_RDATA6_REG}, // range address of EFUSE_BLK0
{EFUSE_BLK1_RDATA0_REG, EFUSE_BLK1_RDATA7_REG}, // range address of EFUSE_BLK1
{EFUSE_BLK2_RDATA0_REG, EFUSE_BLK2_RDATA7_REG}, // range address of EFUSE_BLK2
{EFUSE_BLK3_RDATA0_REG, EFUSE_BLK3_RDATA7_REG} // range address of EFUSE_BLK3
};
static uint32_t write_mass_blocks[EFUSE_BLK_MAX][COUNT_EFUSE_REG_PER_BLOCK] = { 0 };
/*Range addresses to write blocks (it is not real regs, it is a buffer) */
const esp_efuse_range_addr_t range_write_addr_blocks[] = {
{(uint32_t) &write_mass_blocks[EFUSE_BLK0][0], (uint32_t) &write_mass_blocks[EFUSE_BLK0][6]},
{(uint32_t) &write_mass_blocks[EFUSE_BLK1][0], (uint32_t) &write_mass_blocks[EFUSE_BLK1][7]},
{(uint32_t) &write_mass_blocks[EFUSE_BLK2][0], (uint32_t) &write_mass_blocks[EFUSE_BLK2][7]},
{(uint32_t) &write_mass_blocks[EFUSE_BLK3][0], (uint32_t) &write_mass_blocks[EFUSE_BLK3][7]},
};
#ifndef CONFIG_EFUSE_VIRTUAL
/* Addresses to write blocks*/
const uint32_t start_write_addr[] = {
EFUSE_BLK0_WDATA0_REG,
EFUSE_BLK1_WDATA0_REG,
EFUSE_BLK2_WDATA0_REG,
EFUSE_BLK3_WDATA0_REG,
};
static void apply_repeat_encoding(const uint8_t *in_bytes, uint32_t *out_words, size_t in_bytes_len);
// Update Efuse timing configuration
static esp_err_t esp_efuse_set_timing(void)
{
uint32_t apb_freq_mhz = esp_clk_apb_freq() / 1000000;
efuse_hal_set_timing(apb_freq_mhz);
return ESP_OK;
}
#endif // ifndef CONFIG_EFUSE_VIRTUAL
// Efuse read operation: copies data from physical efuses to efuse read registers.
void esp_efuse_utility_clear_program_registers(void)
{
efuse_hal_clear_program_registers();
}
esp_err_t esp_efuse_utility_check_errors(void)
{
return ESP_OK;
}
// Burn values written to the efuse write registers
esp_err_t esp_efuse_utility_burn_chip(void)
{
esp_err_t error = ESP_OK;
#ifdef CONFIG_EFUSE_VIRTUAL
ESP_LOGW(TAG, "Virtual efuses enabled: Not really burning eFuses");
for (int num_block = EFUSE_BLK_MAX - 1; num_block >= EFUSE_BLK0; num_block--) {
int subblock = 0;
for (uint32_t addr_wr_block = range_write_addr_blocks[num_block].start; addr_wr_block <= range_write_addr_blocks[num_block].end; addr_wr_block += 4) {
virt_blocks[num_block][subblock++] |= REG_READ(addr_wr_block);
}
}
#ifdef CONFIG_EFUSE_VIRTUAL_KEEP_IN_FLASH
esp_efuse_utility_write_efuses_to_flash();
#endif
#else // CONFIG_EFUSE_VIRTUAL
if (esp_efuse_set_timing() != ESP_OK) {
ESP_LOGE(TAG, "Efuse fields are not burnt");
} else {
// Permanently update values written to the efuse write registers
// It is necessary to process blocks in the order from MAX-> EFUSE_BLK0, because EFUSE_BLK0 has protection bits for other blocks.
for (int num_block = EFUSE_BLK_MAX - 1; num_block >= EFUSE_BLK0; num_block--) {
esp_efuse_coding_scheme_t scheme = esp_efuse_get_coding_scheme(num_block);
bool need_burn_block = false;
for (uint32_t addr_wr_block = range_write_addr_blocks[num_block].start; addr_wr_block <= range_write_addr_blocks[num_block].end; addr_wr_block += 4) {
if (REG_READ(addr_wr_block) != 0) {
need_burn_block = true;
break;
}
}
if (!need_burn_block) {
continue;
}
if (error) {
// It is done for a use case: BLOCK2 (Flash encryption key) could have an error (incorrect written data)
// in this case we can not burn any data into BLOCK0 because it might set read/write protections of BLOCK2.
ESP_LOGE(TAG, "BLOCK%d can not be burned because a previous block got an error, skipped.", num_block);
continue;
}
efuse_hal_clear_program_registers();
unsigned w_data_len;
unsigned r_data_len;
if (scheme == EFUSE_CODING_SCHEME_3_4) {
esp_efuse_utility_apply_34_encoding((void *)range_write_addr_blocks[num_block].start, (uint32_t *)start_write_addr[num_block], ESP_EFUSE_LEN_OF_3_4_SCHEME_BLOCK_IN_BYTES);
r_data_len = ESP_EFUSE_LEN_OF_3_4_SCHEME_BLOCK_IN_BYTES;
w_data_len = 32;
} else if (scheme == EFUSE_CODING_SCHEME_REPEAT) {
apply_repeat_encoding((void *)range_write_addr_blocks[num_block].start, (uint32_t *)start_write_addr[num_block], 16);
r_data_len = ESP_EFUSE_LEN_OF_REPEAT_BLOCK_IN_BYTES;
w_data_len = 32;
} else {
r_data_len = (range_read_addr_blocks[num_block].end - range_read_addr_blocks[num_block].start) + sizeof(uint32_t);
w_data_len = (range_write_addr_blocks[num_block].end - range_write_addr_blocks[num_block].start) + sizeof(uint32_t);
memcpy((void *)start_write_addr[num_block], (void *)range_write_addr_blocks[num_block].start, w_data_len);
}
uint32_t backup_write_data[8];
memcpy(backup_write_data, (void *)start_write_addr[num_block], w_data_len);
int repeat_burn_op = 1;
bool correct_written_data;
bool coding_error_before = efuse_hal_is_coding_error_in_block(num_block);
if (coding_error_before) {
ESP_LOGW(TAG, "BLOCK%d already has a coding error", num_block);
}
bool coding_error_occurred;
do {
ESP_LOGI(TAG, "BURN BLOCK%d", num_block);
efuse_hal_program(0); // BURN a block
bool coding_error_after = efuse_hal_is_coding_error_in_block(num_block);
coding_error_occurred = (coding_error_before != coding_error_after) && coding_error_before == false;
if (coding_error_occurred) {
ESP_LOGW(TAG, "BLOCK%d got a coding error", num_block);
}
correct_written_data = esp_efuse_utility_is_correct_written_data(num_block, r_data_len);
if (!correct_written_data || coding_error_occurred) {
ESP_LOGW(TAG, "BLOCK%d: next retry to fix an error [%d/3]...", num_block, repeat_burn_op);
memcpy((void *)start_write_addr[num_block], (void *)backup_write_data, w_data_len);
}
} while ((!correct_written_data || coding_error_occurred) && repeat_burn_op++ < 3);
if (coding_error_occurred) {
ESP_LOGW(TAG, "Coding error was not fixed");
}
if (!correct_written_data) {
ESP_LOGE(TAG, "Written data are incorrect");
error = ESP_FAIL;
}
}
}
#endif // CONFIG_EFUSE_VIRTUAL
esp_efuse_utility_reset();
return error;
}
esp_err_t esp_efuse_utility_apply_34_encoding(const uint8_t *in_bytes, uint32_t *out_words, size_t in_bytes_len)
{
if (in_bytes == NULL || out_words == NULL || in_bytes_len % 6 != 0) {
return ESP_ERR_INVALID_ARG;
}
while (in_bytes_len > 0) {
uint8_t out[8];
uint8_t xor = 0;
uint8_t mul = 0;
for (int i = 0; i < 6; i++) {
xor ^= in_bytes[i];
mul += (i + 1) * __builtin_popcount(in_bytes[i]);
}
memcpy(out, in_bytes, 6); // Data bytes
out[6] = xor;
out[7] = mul;
memcpy(out_words, out, 8);
in_bytes_len -= 6;
in_bytes += 6;
out_words += 2;
}
return ESP_OK;
}
#ifndef CONFIG_EFUSE_VIRTUAL
static void apply_repeat_encoding(const uint8_t *in_bytes, uint32_t *out_words, size_t in_bytes_len)
{
for (unsigned i = 0; i < 2; i++) {
memcpy(&out_words[i * 4], (uint32_t *)in_bytes, in_bytes_len);
}
}
#endif // CONFIG_EFUSE_VIRTUAL
static void read_r_data(esp_efuse_block_t num_block, uint32_t* buf_r_data)
{
int i = 0;
for (uint32_t addr_rd_block = range_read_addr_blocks[num_block].start; addr_rd_block <= range_read_addr_blocks[num_block].end; addr_rd_block += 4, ++i) {
buf_r_data[i] = esp_efuse_utility_read_reg(num_block, i);
}
}
// This function just checkes that given data for blocks will not rise a coding issue during the burn operation.
// Encoded data will be set during the burn operation.
esp_err_t esp_efuse_utility_apply_new_coding_scheme()
{
uint8_t buf_r_data[COUNT_EFUSE_REG_PER_BLOCK * 4];
// start with EFUSE_BLK1. EFUSE_BLK0 - always uses EFUSE_CODING_SCHEME_NONE.
for (int num_block = EFUSE_BLK1; num_block < EFUSE_BLK_MAX; num_block++) {
esp_efuse_coding_scheme_t scheme = esp_efuse_get_coding_scheme(num_block);
if (scheme != EFUSE_CODING_SCHEME_NONE) {
bool is_write_data = false;
for (uint32_t addr_wr_block = range_write_addr_blocks[num_block].start; addr_wr_block <= range_write_addr_blocks[num_block].end; addr_wr_block += 4) {
if (REG_READ(addr_wr_block)) {
is_write_data = true;
break;
}
}
if (is_write_data) {
read_r_data(num_block, (uint32_t*)buf_r_data);
uint8_t* buf_w_data = (uint8_t*)range_write_addr_blocks[num_block].start;
if (scheme == EFUSE_CODING_SCHEME_3_4) {
if (*((uint32_t*)buf_w_data + 6) != 0 || *((uint32_t*)buf_w_data + 7) != 0) {
return ESP_ERR_CODING;
}
for (int i = 0; i < ESP_EFUSE_LEN_OF_3_4_SCHEME_BLOCK_IN_BYTES; ++i) {
if (buf_w_data[i] != 0) {
int st_offset_buf = (i / 6) * 6;
// check that place is free.
for (int n = st_offset_buf; n < st_offset_buf + 6; ++n) {
if (buf_r_data[n] != 0) {
ESP_LOGE(TAG, "Bits are not empty. Write operation is forbidden.");
return ESP_ERR_CODING;
}
}
}
}
} else if (scheme == EFUSE_CODING_SCHEME_REPEAT) {
for (int i = 4; i < 8; ++i) {
if (*((uint32_t*)buf_w_data + i) != 0) {
return ESP_ERR_CODING;
}
}
}
}
}
}
return ESP_OK;
}
| apache-2.0 |
datastax/cpp-driver | src/result_metadata.cpp | 1 | 1231 | /*
Copyright (c) DataStax, Inc.
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.
*/
// The FNV1a hash code is based on work found here:
// http://www.isthe.com/chongo/tech/comp/fnv/index.html
// and is therefore public domain.
#include "result_metadata.hpp"
#include "utils.hpp"
#include <iterator>
using namespace datastax;
using namespace datastax::internal;
using namespace datastax::internal::core;
ResultMetadata::ResultMetadata(size_t column_count, const RefBuffer::Ptr& buffer)
: defs_(column_count)
, buffer_(buffer) {}
size_t ResultMetadata::get_indices(StringRef name, IndexVec* result) const {
return defs_.get_indices(name, result);
}
void ResultMetadata::add(const ColumnDefinition& def) { defs_.add(def); }
| apache-2.0 |
cxxjava/cxxMina | http/src/EHttpClientEncoder.cpp | 1 | 1827 | /*
* EHttpClientEncoder.cpp
*
* Created on: 2017-1-4
* Author: cxxjava@163.com
*/
#include "../inc/EHttpClientEncoder.hh"
#include "../inc/EHttpRequest.hh"
#include "../inc/EHttpEndOfContent.hh"
#include "../../inc/EIoBuffer.hh"
namespace efc {
namespace eio {
sp<ELogger> EHttpClientEncoder::LOG = ELoggerManager::getLogger("EHttpClientEncoder");
void EHttpClientEncoder::encode(sp<EIoSession>& session, sp<EObject>& message, sp<EProtocolEncoderOutput>& out) {
LOG->debug_("encode %s", typeid(message.get()).name());
EHttpRequest* msg = dynamic_cast<EHttpRequest*>(message.get());
if (msg) {
LOG->debug("HttpRequest");
EString sb(msg->getMethod());
sb.append(" ");
sb.append(msg->getRequestPath().get());
sp<EString> qs = msg->getQueryString();
if (qs != null && !qs->isEmpty()) {
sb.append("?");
sb.append(qs.get());
}
sb.append(" ");
sb.append(msg->getProtocolVersion());
sb.append("\r\n");
sp<EIterator<EMapEntry<EString*,EString*>*> > iter = msg->getHeaders()->entrySet()->iterator();
while (iter->hasNext()) {
EMapEntry<EString*,EString*>* header = iter->next();
sb.append(header->getKey());
sb.append(": ");
sb.append(header->getValue());
sb.append("\r\n");
}
sb.append("\r\n");
sp<EIoBuffer> buf = EIoBuffer::allocate(sb.length())->setAutoExpand(true);
buf->putString(sb.toString().c_str()/*, ENCODER*/);
buf->flip();
out->write(buf);
} else if (instanceof<EIoBuffer>(message.get())) {
LOG->debug_("Body %s", message->toString().c_str());
out->write(message.get());
} else if (instanceof<EHttpEndOfContent>(message.get())) {
LOG->debug("End of Content");
// end of HTTP content
// keep alive ?
}
}
void EHttpClientEncoder::dispose(sp<EIoSession>& session) THROWS(EException) {
//
}
} /* namespace eio */
} /* namespace efc */
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.